first commit

This commit is contained in:
Brian Fertig 2026-11-18 18:12:13 -07:00
commit 602fe38258
23 changed files with 2773 additions and 0 deletions

19
Dockerfile Normal file
View File

@ -0,0 +1,19 @@
FROM node:22-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY tsconfig.json ./
COPY src ./src
RUN npm run build && npm prune --omit=dev
FROM node:22-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY package.json ./
COPY db ./db
COPY public ./public
USER node
EXPOSE 8080
CMD ["node", "dist/server.js"]

56
README.md Normal file
View File

@ -0,0 +1,56 @@
# WarezHou$e BBS
A late-80s / early-90s style bulletin board system that runs in the browser.
Dial in, hear the modem handshake, log on, and land on the main menu.
(303) 674-5489 :: 7 Nodes - 1.5 GB Online - HQ and Distro
## Quick start
```sh
cp .env.example .env # set a real POSTGRES_PASSWORD
docker compose up -d --build
```
Open http://localhost:8080 and press any key to dial. ESC skips the handshake.
## How it works
- **app** – Node.js/TypeScript. Serves the browser terminal (xterm.js) and a
WebSocket at `/ws`. Each WebSocket is one caller on one *node*; the BBS
logic runs server-side, the browser is a dumb terminal.
- **db** – PostgreSQL 16, data in the `bbs_pgdata` volume.
Settings (`.env`): `PORT`, `BAUD` (simulated output speed, `0` = unthrottled),
`MAX_NODES`, `IDLE_TIMEOUT_MIN`, and the Postgres credentials.
## Layout
| Path | What |
|---|---|
| `src/server.ts` | HTTP + WebSocket server, node allocation |
| `src/session/Session.ts` | Per-caller I/O: baud-throttled output, hotkeys, line input |
| `src/session/ansi.ts` | Pipe colour codes (`|00`-`|15` fg, `|16`-`|23` bg, `|CL`) |
| `src/screens/` | Welcome/logon, login, new user, main menu |
| `src/art/welcome.ts` | Welcome ANSI art |
| `src/users/userRepo.ts` | User accounts (bcrypt), call log |
| `db/migrations/` | SQL migrations, applied automatically on start |
| `public/` | Browser terminal, CRT styling, synthesized modem audio |
## Adding things
- **New screen / door game:** add a module under `src/screens/` that takes a
`Session`, and wire a key to it in `src/screens/mainMenu.ts`.
- **New tables:** add `db/migrations/002_whatever.sql`; it runs on next start.
## Database access
```sh
docker compose exec db psql -U bbs bbs
```
## Font
For the full IBM PC look, install a VGA font such as "Px437 IBM VGA 8x16"
locally (the page will use it if present), or add an `@font-face` for it in
`public/style.css`.

View File

@ -0,0 +1,29 @@
-- Core user accounts
CREATE TABLE users (
id SERIAL PRIMARY KEY,
handle VARCHAR(20) NOT NULL,
password_hash TEXT NOT NULL,
real_name VARCHAR(40) NOT NULL,
location VARCHAR(40) NOT NULL,
email VARCHAR(80),
security_level INTEGER NOT NULL DEFAULT 10,
times_called INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_login_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX users_handle_lower_idx ON users (lower(handle));
-- Every successful logon; id doubles as the system-wide caller number
CREATE TABLE calls (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
node INTEGER NOT NULL,
connected_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX calls_user_idx ON calls (user_id);
-- Misc key/value system data
CREATE TABLE system_stats (
key VARCHAR(64) PRIMARY KEY,
value TEXT NOT NULL
);

38
docker-compose.yml Normal file
View File

@ -0,0 +1,38 @@
services:
db:
image: postgres:16-alpine
restart: unless-stopped
environment:
POSTGRES_USER: ${POSTGRES_USER:-bbs}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-change-me}
POSTGRES_DB: ${POSTGRES_DB:-bbs}
volumes:
- bbs_pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 10
app:
build: .
restart: unless-stopped
depends_on:
db:
condition: service_healthy
environment:
PORT: 8080
TZ: ${TZ:-America/Denver}
PGHOST: db
PGPORT: 5432
PGUSER: ${POSTGRES_USER:-bbs}
PGPASSWORD: ${POSTGRES_PASSWORD:-change-me}
PGDATABASE: ${POSTGRES_DB:-bbs}
BAUD: ${BAUD:-14400}
MAX_NODES: ${MAX_NODES:-7}
IDLE_TIMEOUT_MIN: ${IDLE_TIMEOUT_MIN:-10}
ports:
- "${PORT:-8080}:8080"
volumes:
bbs_pgdata:

1149
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

30
package.json Normal file
View File

@ -0,0 +1,30 @@
{
"name": "warezhouse-bbs",
"version": "0.1.0",
"private": true,
"description": "WarezHou$e - a late 80s / early 90s style BBS for the browser",
"main": "dist/server.js",
"scripts": {
"build": "tsc -p tsconfig.json",
"start": "node dist/server.js",
"dev": "tsc -p tsconfig.json && node dist/server.js"
},
"engines": {
"node": ">=20"
},
"dependencies": {
"@xterm/xterm": "5.5.0",
"bcryptjs": "2.4.3",
"express": "4.21.2",
"pg": "8.13.1",
"ws": "8.18.0"
},
"devDependencies": {
"@types/bcryptjs": "2.4.6",
"@types/express": "4.17.21",
"@types/node": "22.10.2",
"@types/pg": "8.11.10",
"@types/ws": "8.5.13",
"typescript": "5.7.2"
}
}

29
public/index.html Normal file
View File

@ -0,0 +1,29 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>WarezHou$e BBS</title>
<link rel="stylesheet" href="/vendor/xterm/css/xterm.css" />
<link rel="stylesheet" href="/style.css" />
</head>
<body>
<main id="crt">
<div id="screen">
<div id="terminal"></div>
<div id="scanlines" aria-hidden="true"></div>
</div>
</main>
<footer id="status">
<span id="st-state">OFFLINE</span>
<span id="st-timer">00:00:00</span>
<span id="st-line">ANSI-BBS</span>
<span id="st-speed">8N1</span>
<span id="st-node">--</span>
<button id="st-sound" type="button" title="Toggle modem sounds">SOUND: ON</button>
</footer>
<script src="/vendor/xterm/lib/xterm.js"></script>
<script src="/modem-audio.js"></script>
<script src="/terminal.js"></script>
</body>
</html>

172
public/modem-audio.js Normal file
View File

@ -0,0 +1,172 @@
/*
* Synthesised phone-line + modem sounds (Web Audio, no sample files).
* Not a faithful V.32bis handshake - just close enough to bring back memories.
*/
(function () {
let ctx = null;
let master = null;
let noiseBuf = null;
let skipping = false;
let pending = [];
const live = new Set();
const MA = { enabled: true };
function init() {
if (!MA.enabled) return;
if (!ctx) {
const AC = window.AudioContext || window.webkitAudioContext;
if (!AC) { MA.enabled = false; return; }
ctx = new AC();
master = ctx.createGain();
master.gain.value = 0.22;
master.connect(ctx.destination);
noiseBuf = ctx.createBuffer(1, ctx.sampleRate * 2, ctx.sampleRate);
const d = noiseBuf.getChannelData(0);
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
}
if (ctx.state === 'suspended') ctx.resume();
}
function on() { return MA.enabled && ctx && !skipping; }
function wait(ms) {
if (skipping) return Promise.resolve();
return new Promise((resolve) => {
const done = () => { clearTimeout(t); pending = pending.filter((p) => p !== done); resolve(); };
const t = setTimeout(done, ms);
pending.push(done);
});
}
function track(node, stopAt) {
live.add(node);
node.onended = () => live.delete(node);
node.start(ctx.currentTime);
node.stop(stopAt);
return node;
}
function envGain(start, dur, level) {
const g = ctx.createGain();
g.gain.setValueAtTime(0, start);
g.gain.linearRampToValueAtTime(level, start + 0.006);
g.gain.setValueAtTime(level, Math.max(start + 0.006, start + dur - 0.006));
g.gain.linearRampToValueAtTime(0, start + dur);
g.connect(master);
return g;
}
/** Sum of steady sine tones. */
function tones(freqs, ms, level = 0.5) {
if (!on()) return;
const t = ctx.currentTime;
const g = envGain(t, ms / 1000, level / freqs.length);
for (const f of freqs) {
const o = ctx.createOscillator();
o.frequency.value = f;
o.connect(g);
track(o, t + ms / 1000 + 0.02);
}
}
/** Frequency-shift keying: random hops between the given frequencies. */
function fsk(freqSets, ms, baud, level = 0.4) {
if (!on()) return;
const t = ctx.currentTime;
const dur = ms / 1000;
const g = envGain(t, dur, level / freqSets.length);
for (const [f0, f1] of freqSets) {
const o = ctx.createOscillator();
for (let x = 0; x < dur; x += 1 / baud) {
o.frequency.setValueAtTime(Math.random() < 0.5 ? f0 : f1, t + x);
}
o.connect(g);
track(o, t + dur + 0.02);
}
}
/** Band-passed white noise - the "screech" of a fast carrier. */
function noise(ms, centre, q, level = 0.6) {
if (!on()) return;
const t = ctx.currentTime;
const src = ctx.createBufferSource();
src.buffer = noiseBuf;
src.loop = true;
const bp = ctx.createBiquadFilter();
bp.type = 'bandpass';
bp.frequency.value = centre;
bp.Q.value = q;
src.connect(bp).connect(envGain(t, ms / 1000, level));
track(src, t + ms / 1000 + 0.02);
}
const DTMF = {
1: [697, 1209], 2: [697, 1336], 3: [697, 1477],
4: [770, 1209], 5: [770, 1336], 6: [770, 1477],
7: [852, 1209], 8: [852, 1336], 9: [852, 1477],
0: [941, 1336], '*': [941, 1209], '#': [941, 1477],
};
const pace = (withSound, silent) => (MA.enabled ? withSound : silent);
MA.init = init;
MA.wait = wait;
MA.dialTone = async () => {
const ms = pace(900, 200);
tones([350, 440], ms, 0.5);
await wait(ms);
};
MA.dial = async (digits) => {
for (const d of digits) {
if (skipping) return;
if (DTMF[d]) tones(DTMF[d], 85, 0.55);
await wait(pace(150, 40));
}
};
MA.ringback = async () => {
tones([440, 480], 1600, 0.4);
await wait(pace(2300, 400));
};
MA.busy = async () => {
for (let i = 0; i < 3; i++) {
tones([480, 620], 480, 0.5);
await wait(pace(950, 200));
}
};
MA.handshake = async () => {
if (!MA.enabled) return wait(700);
tones([2100], 1100, 0.35); // answer tone
await wait(1180);
fsk([[980, 1180], [1650, 1850]], 520, 300, 0.4); // V.21 negotiation
await wait(620);
tones([150, 300, 450, 600, 900, 1200, 1800, 2400, 3000, 3600], 320, 0.6); // line probe "bong"
await wait(360);
fsk([[1800, 2400]], 380, 600, 0.3);
await wait(420);
noise(520, 1800, 0.9, 0.7); // training
tones([1800], 520, 0.12);
await wait(640);
noise(1500, 1900, 0.6, 0.55); // data carrier
tones([1800], 1500, 0.08);
await wait(1550);
};
/** Cut all sound and fast-forward any pending waits. */
MA.skip = () => {
skipping = true;
for (const n of live) { try { n.stop(); } catch (e) { /* already stopped */ } }
live.clear();
pending.slice().forEach((done) => done());
};
MA.reset = () => { skipping = false; };
MA.isSkipping = () => skipping;
window.ModemAudio = MA;
})();

82
public/style.css Normal file
View File

@ -0,0 +1,82 @@
html, body {
margin: 0;
height: 100%;
background: #050505;
color: #aaa;
overflow: hidden;
}
body {
display: flex;
flex-direction: column;
}
#crt {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
min-height: 0;
background: radial-gradient(ellipse at center, #111 0%, #000 75%);
}
#screen {
position: relative;
padding: 18px 22px;
background: #000;
border-radius: 18px;
box-shadow:
0 0 0 3px #1a1a1a,
0 0 0 14px #2b2924,
0 0 0 16px #111,
0 0 60px rgba(80, 180, 255, 0.12),
inset 0 0 80px rgba(0, 0, 0, 0.9);
}
#terminal {
filter: drop-shadow(0 0 2px rgba(170, 220, 255, 0.35));
}
#terminal .xterm-viewport {
overflow-y: hidden !important;
background: #000 !important;
}
#scanlines {
pointer-events: none;
position: absolute;
inset: 0;
border-radius: 18px;
background: repeating-linear-gradient(
to bottom,
rgba(0, 0, 0, 0) 0px,
rgba(0, 0, 0, 0) 2px,
rgba(0, 0, 0, 0.22) 3px
);
box-shadow: inset 0 0 120px rgba(0, 0, 0, 0.75);
animation: flicker 0.15s infinite alternate;
}
@keyframes flicker {
from { opacity: 0.92; }
to { opacity: 1; }
}
@media (prefers-reduced-motion: reduce) {
#scanlines { animation: none; }
}
#status {
display: flex;
flex-wrap: wrap;
gap: 0;
background: #0000aa;
color: #fff;
font: 14px/1.6 "Perfect DOS VGA 437", "Px437 IBM VGA 8x16", Consolas, "DejaVu Sans Mono", "Courier New", monospace;
padding: 0 8px;
}
#status > * {
padding: 0 12px;
border-right: 1px solid #5555ff;
}
#status button {
margin-left: auto;
background: none;
color: #ffff55;
border: 0;
font: inherit;
cursor: pointer;
}
#st-state.online { color: #55ff55; }
#st-state.dialing { color: #ffff55; }

217
public/terminal.js Normal file
View File

@ -0,0 +1,217 @@
(function () {
const PHONE = '1-303-674-5489';
const DIGITS = PHONE.replace(/\D/g, '');
const FONT = '"Perfect DOS VGA 437", "Px437 IBM VGA 8x16", Consolas, "DejaVu Sans Mono", "Courier New", monospace';
const audio = window.ModemAudio;
// Classic CGA/VGA 16-colour palette
const theme = {
background: '#000000', foreground: '#aaaaaa', cursor: '#aaaaaa', cursorAccent: '#000000',
black: '#000000', red: '#aa0000', green: '#00aa00', yellow: '#aa5500',
blue: '#0000aa', magenta: '#aa00aa', cyan: '#00aaaa', white: '#aaaaaa',
brightBlack: '#555555', brightRed: '#ff5555', brightGreen: '#55ff55', brightYellow: '#ffff55',
brightBlue: '#5555ff', brightMagenta: '#ff55ff', brightCyan: '#55ffff', brightWhite: '#ffffff',
};
const term = new Terminal({
cols: 80, rows: 25, scrollback: 0, cursorBlink: true, cursorStyle: 'underline',
fontFamily: FONT, fontSize: 16, lineHeight: 1, theme, allowTransparency: false,
customGlyphs: true, drawBoldTextInBrightColors: true,
});
term.open(document.getElementById('terminal'));
// ---- layout: scale the font so a full 80x25 screen fits the window ----
const screenEl = document.getElementById('terminal');
const statusEl = document.getElementById('status');
function fit() {
const availW = window.innerWidth - 90;
const availH = window.innerHeight - statusEl.offsetHeight - 90;
for (let i = 0; i < 4; i++) {
const r = screenEl.querySelector('.xterm-screen').getBoundingClientRect();
if (!r.width || !r.height) return;
const size = term.options.fontSize;
const next = Math.max(8, Math.floor(size * Math.min(availW / r.width, availH / r.height)));
if (next === size) break;
term.options.fontSize = next;
}
}
window.addEventListener('resize', fit);
(document.fonts ? document.fonts.ready : Promise.resolve()).then(fit);
fit();
// ---- status bar --------------------------------------------------------
const st = {
state: document.getElementById('st-state'),
timer: document.getElementById('st-timer'),
speed: document.getElementById('st-speed'),
node: document.getElementById('st-node'),
sound: document.getElementById('st-sound'),
};
let onlineSince = 0;
let timerId = null;
function setState(label, cls) {
st.state.textContent = label;
st.state.className = cls || '';
}
function startTimer() {
onlineSince = Date.now();
clearInterval(timerId);
timerId = setInterval(() => {
const s = Math.floor((Date.now() - onlineSince) / 1000);
const p = (n) => String(n).padStart(2, '0');
st.timer.textContent = `${p(Math.floor(s / 3600))}:${p(Math.floor(s / 60) % 60)}:${p(s % 60)}`;
}, 1000);
}
function stopTimer() { clearInterval(timerId); }
function loadSoundPref() {
try { return localStorage.getItem('bbs-sound') !== 'off'; } catch (e) { return true; }
}
function renderSound() { st.sound.textContent = audio.enabled ? 'SOUND: ON' : 'SOUND: OFF'; }
audio.enabled = loadSoundPref();
renderSound();
st.sound.addEventListener('click', () => {
audio.enabled = !audio.enabled;
try { localStorage.setItem('bbs-sound', audio.enabled ? 'on' : 'off'); } catch (e) { /* ignore */ }
if (!audio.enabled) audio.skip();
renderSound();
term.focus();
});
// ---- connection state machine -----------------------------------------
let state = 'idle'; // idle | dialing | online | offline
let ws = null;
let lineBaud = 14400;
function intro() {
term.reset();
term.write('\x1b[0;37;44m\x1b[2K ModemTerm v1.4 (c) 1991 Basement Softworks \x1b[0m\r\n\r\n');
term.write('\x1b[96m Dialing Directory\x1b[0m\r\n');
term.write('\x1b[90m ' + '─'.repeat(74) + '\x1b[0m\r\n');
term.write('\x1b[97m 1. \x1b[95mWarezHou$e BBS \x1b[90m.................... \x1b[97m' + PHONE + ' \x1b[37m14400 N81 ANSI\x1b[0m\r\n');
term.write('\x1b[90m ' + '─'.repeat(74) + '\x1b[0m\r\n\r\n');
term.write('\x1b[37m COM2: 14400 baud, 8 data bits, no parity, 1 stop bit\x1b[0m\r\n\r\n');
term.write('\x1b[93m Press any key to dial...\x1b[0m\x1b[90m (ESC skips the handshake)\x1b[0m');
setState('OFFLINE');
}
function wait(ms) { return audio.wait(ms); }
async function type(text, cps = 28) {
for (const ch of text) {
term.write(ch);
await wait(1000 / cps);
}
term.write('\r\n');
}
function openLine() {
return new Promise((resolve) => {
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
const sock = new WebSocket(`${proto}://${location.host}/ws`);
ws = sock;
let answered = false;
sock.onmessage = (ev) => {
let msg;
try { msg = JSON.parse(ev.data); } catch (e) { return; }
if (msg.t === 'ring' && !answered) {
answered = true;
lineBaud = msg.baud || 115200;
st.node.textContent = `NODE ${msg.node}`;
resolve('ring');
} else if (msg.t === 'busy' && !answered) {
answered = true;
resolve('busy');
} else if (msg.t === 'd' && state === 'online') {
term.write(msg.d);
} else if (msg.t === 'hangup') {
noCarrier();
}
};
sock.onerror = () => { if (!answered) { answered = true; resolve('error'); } };
sock.onclose = () => {
if (ws === sock) ws = null;
if (!answered) { answered = true; resolve('error'); }
if (state === 'online') noCarrier();
};
});
}
async function dial() {
state = 'dialing';
setState('DIALING', 'dialing');
st.timer.textContent = '00:00:00';
audio.reset();
audio.init();
term.reset();
term.write('\x1b[37m');
await type('ATZ');
await wait(250);
term.write('OK\r\n');
await wait(300);
await type('ATDT ' + PHONE);
const answer = openLine();
await audio.dialTone();
await audio.dial(DIGITS);
const result = await answer;
if (result === 'busy') {
await audio.busy();
term.write('BUSY\r\n');
return offline('All nodes are busy. Try again in a few minutes.');
}
if (result !== 'ring') {
await wait(1500);
term.write('NO ANSWER\r\n');
return offline('The BBS did not answer.');
}
term.write('RINGING\r\n');
await audio.ringback();
await audio.handshake();
if (!ws || ws.readyState !== WebSocket.OPEN) {
term.write('NO CARRIER\r\n');
return offline();
}
term.write(`CONNECT ${lineBaud}/ARQ/V32BIS/LAPM/V42BIS\r\n\x1b[0m`);
st.speed.textContent = `${lineBaud} 8N1`;
setState('ONLINE', 'online');
startTimer();
state = 'online';
ws.send(JSON.stringify({ t: 'start' }));
}
function offline(note) {
state = 'offline';
setState('OFFLINE');
stopTimer();
if (ws) { try { ws.close(); } catch (e) { /* ignore */ } ws = null; }
if (note) term.write(`\r\n\x1b[90m${note}\x1b[0m\r\n`);
term.write('\r\n\x1b[93mPress any key to redial...\x1b[0m');
}
function noCarrier() {
if (state !== 'online') return;
term.write('\x1b[0m\r\n\r\nNO CARRIER\r\n');
offline();
}
term.onData((data) => {
if (state === 'online') {
if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ t: 'd', d: data }));
} else if (state === 'dialing') {
if (data === '\x1b') audio.skip();
} else {
dial().catch((err) => {
console.error(err);
offline('Modem error.');
});
}
});
document.addEventListener('click', () => term.focus());
intro();
term.focus();
})();

56
src/art/welcome.ts Normal file
View File

@ -0,0 +1,56 @@
import { center } from '../session/ansi';
import { config } from '../config';
// "ANSI Shadow" figlet lettering, split over two lines to fit 80 columns.
const WAREZ = [
'██╗ ██╗ █████╗ ██████╗ ███████╗███████╗',
'██║ ██║██╔══██╗██╔══██╗██╔════╝╚══███╔╝',
'██║ █╗ ██║███████║██████╔╝█████╗ ███╔╝ ',
'██║███╗██║██╔══██║██╔══██╗██╔══╝ ███╔╝ ',
'╚███╔███╔╝██║ ██║██║ ██║███████╗███████╗',
' ╚══╝╚══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚══════╝',
];
const HOUSE = [
'██╗ ██╗ ██████╗ ██╗ ██╗▄▄███▄▄ ███████╗',
'██║ ██║██╔═══██╗██║ ██║██╔════╝██╔════╝',
'███████║██║ ██║██║ ██║███████╗█████╗ ',
'██╔══██║██║ ██║██║ ██║╚════██║██╔══╝ ',
'██║ ██║╚██████╔╝╚██████╔╝███████║███████╗',
'╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═▀▀▀══╝╚══════╝',
];
const DOLLAR_COLS: [number, number] = [26, 34]; // the "$" glyph in HOUSE
/** Colours solid blocks with `face` and the box-drawing shadow with `shadow`. */
function shade(line: string, face: string, shadow: string, alt?: { cols: [number, number]; face: string; shadow: string }): string {
let out = '';
let cur = '';
[...line].forEach((ch, i) => {
const inAlt = alt && i >= alt.cols[0] && i < alt.cols[1];
const solid = '█▄▀'.includes(ch);
const color = ch === ' ' ? cur : solid ? (inAlt ? alt!.face : face) : inAlt ? alt!.shadow : shadow;
if (color !== cur) {
out += color;
cur = color;
}
out += ch;
});
return out;
}
const RULE = '|08░|07▒|15▓' + '|07' + '─'.repeat(70) + '|15▓|07▒|08░';
export function welcomeScreen(node: number, baud: number): string {
const lines: string[] = ['|CL ' + RULE];
for (const l of WAREZ) lines.push(' ' + shade(l, '|11', '|03'));
for (const l of HOUSE) lines.push(' '.repeat(35) + shade(l, '|13', '|05', { cols: DOLLAR_COLS, face: '|14', shadow: '|06' }));
lines.push(' ' + RULE);
lines.push('');
lines.push(center(`|08-=[ |15${config.phone} |08]=-`));
lines.push(center('|107 Nodes |08- |141.5 GB Online |08- |12HQ and Distro'));
lines.push('');
lines.push(center(`|07Connected on |15Node ${node} |07at |15${baud || 'Hi-Speed'} bps|07 :: |03${new Date().toLocaleString('en-US', { dateStyle: 'medium', timeStyle: 'short' })}`));
lines.push(center('|08Running WHBBS v0.1 - Sysop: The Architect'));
lines.push('');
return lines.join('\r\n') + '|07';
}

13
src/config.ts Normal file
View File

@ -0,0 +1,13 @@
const num = (v: string | undefined, d: number) => {
const n = Number(v);
return v !== undefined && v !== '' && Number.isFinite(n) ? n : d;
};
export const config = {
port: num(process.env.PORT, 8080),
baud: num(process.env.BAUD, 14400),
maxNodes: Math.max(1, num(process.env.MAX_NODES, 7)),
idleMs: num(process.env.IDLE_TIMEOUT_MIN, 10) * 60_000,
bbsName: 'WarezHou$e',
phone: '(303) 674-5489',
};

54
src/db.ts Normal file
View File

@ -0,0 +1,54 @@
import fs from 'fs';
import path from 'path';
import { Pool } from 'pg';
// Connection settings come from the standard PG* environment variables.
export const pool = new Pool({ max: 10 });
const MIGRATIONS_DIR = path.resolve(__dirname, '..', 'db', 'migrations');
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
async function waitForDb(retries = 30): Promise<void> {
for (let i = 1; ; i++) {
try {
await pool.query('SELECT 1');
return;
} catch (err) {
if (i >= retries) throw err;
console.log(`[db] waiting for database (${i}/${retries})...`);
await sleep(2000);
}
}
}
/** Applies any db/migrations/*.sql files not yet recorded, in filename order. */
export async function migrate(): Promise<void> {
await waitForDb();
const client = await pool.connect();
try {
await client.query('SELECT pg_advisory_lock(727274)');
await client.query(`CREATE TABLE IF NOT EXISTS schema_migrations (
name TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())`);
const { rows } = await client.query<{ name: string }>('SELECT name FROM schema_migrations');
const applied = new Set(rows.map((r) => r.name));
const files = fs.readdirSync(MIGRATIONS_DIR).filter((f) => f.endsWith('.sql')).sort();
for (const file of files) {
if (applied.has(file)) continue;
const sql = fs.readFileSync(path.join(MIGRATIONS_DIR, file), 'utf8');
await client.query('BEGIN');
try {
await client.query(sql);
await client.query('INSERT INTO schema_migrations (name) VALUES ($1)', [file]);
await client.query('COMMIT');
console.log(`[db] applied migration ${file}`);
} catch (err) {
await client.query('ROLLBACK');
throw err;
}
}
console.log('[db] migrations applied');
} finally {
await client.query('SELECT pg_advisory_unlock(727274)').catch(() => {});
client.release();
}
}

9
src/nodes.ts Normal file
View File

@ -0,0 +1,9 @@
import type { Session } from './session/Session';
/** Node slots: index 0 is Node 1. null = line free. */
export const nodes: (Session | null)[] = [];
export function initNodes(count: number): void {
nodes.length = 0;
for (let i = 0; i < count; i++) nodes.push(null);
}

50
src/screens/connect.ts Normal file
View File

@ -0,0 +1,50 @@
import type { Session } from '../session/Session';
import { welcomeScreen } from '../art/welcome';
import { login } from './login';
import { newUser } from './newUser';
import { mainMenu, goodbye } from './mainMenu';
import { recordCall, type User } from '../users/userRepo';
import { esc } from '../session/ansi';
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
/** Entire life of a call, from carrier detect to logoff. */
export async function runCall(s: Session): Promise<void> {
await sleep(500);
await s.print(welcomeScreen(s.node, s.baud));
for (;;) {
s.activity = 'Logging on';
await s.print('\r\n |08[|15L|08]|07ogin |08[|15N|08]|07ew User |08[|15G|08]|07oodbye |08:: |07');
const choice = await s.readChoice('LNG');
await s.println('\r\n');
if (choice === 'G') return goodbye(s);
const user = choice === 'L' ? await login(s) : await newUser(s);
if (user) {
await logon(s, user, choice === 'N');
return mainMenu(s);
}
}
}
async function logon(s: Session, user: User, isNew: boolean): Promise<void> {
const previousLogin = user.last_login_at;
const { callerNo, user: fresh } = await recordCall(user.id, s.node);
s.user = fresh;
s.loginAt = new Date();
await s.println();
if (isNew) {
await s.println(` |10Welcome aboard, |15${esc(fresh.handle)}|10!`);
} else {
await s.println(` |10Welcome back, |15${esc(fresh.handle)}|10!`);
if (previousLogin) {
await s.println(` |07Last on: |15${previousLogin.toLocaleString('en-US', { dateStyle: 'medium', timeStyle: 'short' })}`);
}
}
await s.println(` |07You are caller |15#${callerNo}|07. Total calls by you: |15${fresh.times_called}`);
await s.println();
await s.pause();
}

30
src/screens/login.ts Normal file
View File

@ -0,0 +1,30 @@
import type { Session } from '../session/Session';
import { verifyLogin, type User } from '../users/userRepo';
const MAX_ATTEMPTS = 3;
/** Returns the user on success, null if the caller backs out. Hangs up after too many failures. */
export async function login(s: Session): Promise<User | null> {
s.activity = 'Logging in';
let failures = 0;
for (;;) {
await s.print(' |03Handle |08(|07Enter to cancel|08)|03: ');
const handle = (await s.readLine({ maxLen: 20 })).trim();
if (!handle) return null;
await s.print(' |03Password: ');
const password = await s.readLine({ maxLen: 32, mask: true });
const user = await verifyLogin(handle, password);
if (user) return user;
failures++;
if (failures >= MAX_ATTEMPTS) {
await s.println('\r\n |12Too many failed logon attempts. |07Goodbye.');
s.hangup();
return null;
}
await s.println(`\r\n |12Invalid handle or password. |08(${MAX_ATTEMPTS - failures} attempt${MAX_ATTEMPTS - failures === 1 ? '' : 's'} left)\r\n`);
}
}

153
src/screens/mainMenu.ts Normal file
View File

@ -0,0 +1,153 @@
import type { Session } from '../session/Session';
import { esc, padRight, center } from '../session/ansi';
import { nodes } from '../nodes';
import { lastCallers } from '../users/userRepo';
import { config } from '../config';
const W = 78; // inner box width
const box = {
top: `|09╔${'═'.repeat(W)}╗`,
mid: `|09╟${'─'.repeat(W)}╢`,
bot: `|09╚${'═'.repeat(W)}╝`,
row: (content: string) => `|09║|07${padRight(content, W)}|09║`,
};
const item = (key: string, label: string) => padRight(` |08[|15${key}|08] |11${label}`, 39);
function minutesOn(s: Session): number {
return Math.floor((Date.now() - (s.loginAt ?? s.connectedAt).getTime()) / 60000);
}
function securityLabel(level: number): string {
if (level >= 255) return 'Sysop';
if (level >= 100) return 'Co-Sysop';
if (level >= 50) return 'Elite';
if (level >= 20) return 'Validated';
return 'New User';
}
async function drawMenu(s: Session): Promise<void> {
const u = s.user!;
const time = new Date().toLocaleTimeString('en-US', { hour12: false });
const header = padRight(` |15${config.bbsName}`, 26) + padRight('|14M A I N M E N U', 34) + padRight(`|08Node |15${s.node} |08· |07${time}`, 18);
s.clear();
await s.println(box.top);
await s.println(box.row(header));
await s.println(box.mid);
await s.println(box.row(''));
await s.println(box.row(item('M', 'Message Bases') + item('L', 'Last Callers')));
await s.println(box.row(item('F', 'File Areas') + item('W', "Who's Online")));
await s.println(box.row(item('D', 'Door Games') + item('U', 'User Settings')));
await s.println(box.row(item('B', 'Bulletins') + item('G', 'Goodbye |08(|07Logoff|08)')));
await s.println(box.row(''));
await s.println(box.bot);
await s.println(
` |08Handle: |15${esc(u.handle)} |08Access: |15${securityLabel(u.security_level)} ` +
`|08Calls: |15${u.times_called} |08Time on: |15${minutesOn(s)} min`,
);
await s.println();
}
export async function mainMenu(s: Session): Promise<void> {
let redraw = true;
for (;;) {
s.activity = 'Main Menu';
if (redraw) await drawMenu(s);
redraw = true;
await s.print(`|08[|13${config.bbsName}|08] |07Main Menu |08(|15?|08=|07Redraw|08)|07: `);
const k = await s.readChoice('MFDBLWUG?');
await s.println();
switch (k) {
case 'G':
return goodbye(s);
case 'W':
await whosOnline(s);
break;
case 'L':
await showLastCallers(s);
break;
case 'M':
await underConstruction(s, 'Message Bases');
break;
case 'F':
await underConstruction(s, 'File Areas');
break;
case 'D':
await underConstruction(s, 'Door Games');
break;
case 'B':
await underConstruction(s, 'Bulletins');
break;
case 'U':
await underConstruction(s, 'User Settings');
break;
case '?':
break;
}
}
}
async function underConstruction(s: Session, area: string): Promise<void> {
s.activity = area;
await s.println();
await s.println(center('|14▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄'));
await s.println(center(`|15${area}`));
await s.println(center('|07This area is under construction.'));
await s.println(center('|08Check back soon - the Sysop is hard at work!'));
await s.println(center('|14▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀'));
await s.println();
await s.pause();
}
async function whosOnline(s: Session): Promise<void> {
s.activity = "Who's Online";
s.clear();
await s.println(`|15 Who's Online |08- |07${config.bbsName}`);
await s.println('|08' + '─'.repeat(79));
await s.println(`|03 ${padRight('Node', 6)}${padRight('Handle', 22)}${padRight('Activity', 30)}On`);
await s.println('|08' + '─'.repeat(79));
for (let i = 0; i < nodes.length; i++) {
const n = nodes[i];
const num = padRight(`|15${i + 1}`, 6);
if (!n) {
await s.println(` ${num}|08Waiting for caller...`);
} else {
const who = n.user ? `|11${esc(n.user.handle)}` : '|08<logging on>';
await s.println(` ${num}${padRight(who, 22)}${padRight(`|07${n.activity}`, 30)}|07${minutesOn(n)}m`);
}
}
await s.println();
await s.pause();
}
async function showLastCallers(s: Session): Promise<void> {
s.activity = 'Last Callers';
const rows = await lastCallers(15);
s.clear();
await s.println(`|15 Last Callers |08- |07${config.bbsName}`);
await s.println('|08' + '─'.repeat(79));
await s.println(`|03 ${padRight('Caller', 9)}${padRight('Handle', 22)}${padRight('Location', 26)}${padRight('Node', 6)}When`);
await s.println('|08' + '─'.repeat(79));
if (!rows.length) await s.println(' |08No callers yet.');
for (const r of rows) {
const when = r.connected_at.toLocaleString('en-US', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false });
await s.println(
` |07${padRight(`#${r.id}`, 9)}|11${padRight(esc(r.handle), 22)}|07${padRight(esc(r.location).slice(0, 25), 26)}|15${padRight(String(r.node), 6)}|08${when}`,
);
}
await s.println();
await s.pause();
}
export async function goodbye(s: Session): Promise<void> {
s.activity = 'Logging off';
const name = s.user ? esc(s.user.handle) : 'caller';
await s.println();
await s.println(`|08░▒▓█ |15Thanks for calling |13${config.bbsName}|15, |11${name}|15! |08█▓▒░`);
if (s.user) await s.println(`|07 You were online for |15${minutesOn(s)}|07 minute${minutesOn(s) === 1 ? '' : 's'}.`);
await s.println(`|07 Call back soon: |15${config.phone}`);
await s.println();
await new Promise((r) => setTimeout(r, 800));
s.hangup();
}

103
src/screens/newUser.ts Normal file
View File

@ -0,0 +1,103 @@
import type { Session } from '../session/Session';
import { createUser, handleExists, HandleTakenError, type User } from '../users/userRepo';
import { esc } from '../session/ansi';
const HANDLE_RE = /^[A-Za-z0-9][A-Za-z0-9 _.\-]{1,18}[A-Za-z0-9_.\-]$/;
const RESERVED = new Set(['sysop', 'new', 'all', 'guest', 'admin', 'root', 'everyone']);
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
async function ask(s: Session, label: string, maxLen: number, mask = false): Promise<string> {
await s.print(` |03${label}|08: `);
return (await s.readLine({ maxLen, mask })).trim();
}
async function error(s: Session, msg: string): Promise<void> {
await s.println(` |12${msg}`);
}
/** New user application. Returns the created user, or null if the caller backs out. */
export async function newUser(s: Session): Promise<User | null> {
s.activity = 'New user application';
for (;;) {
s.clear();
await s.println('|08' + '─'.repeat(79));
await s.println('|15 New User Application |08- |07WarezHou$e');
await s.println('|08' + '─'.repeat(79));
await s.println(' |07Handles are 3-20 characters: letters, numbers, spaces, |15_ . -');
await s.println(' |08Leave the handle blank to cancel.\r\n');
// Handle
let handle = '';
for (;;) {
handle = (await ask(s, 'Desired handle', 20)).replace(/\s+/g, ' ');
if (!handle) return null;
if (!HANDLE_RE.test(handle)) await error(s, 'Invalid handle. Try again.');
else if (RESERVED.has(handle.toLowerCase())) await error(s, 'That handle is reserved.');
else if (await handleExists(handle)) await error(s, 'That handle is already in use.');
else break;
}
// Password
let password = '';
for (;;) {
password = await ask(s, 'Password (6+ chars)', 32, true);
if (password.length < 6) {
await error(s, 'Password must be at least 6 characters.');
continue;
}
const confirm = await ask(s, 'Confirm password', 32, true);
if (confirm !== password) {
await error(s, 'Passwords do not match.');
continue;
}
break;
}
let realName = '';
while (!realName) {
realName = await ask(s, 'Real name', 30);
if (!realName) await error(s, 'Real name is required (only the Sysop sees it).');
}
let location = '';
while (!location) {
location = await ask(s, 'City, State', 30);
if (!location) await error(s, 'Location is required.');
}
let email: string | null = null;
for (;;) {
const e = await ask(s, 'Email (optional)', 50);
if (!e) break;
if (EMAIL_RE.test(e)) {
email = e;
break;
}
await error(s, 'That does not look like an email address.');
}
await s.println('\r\n|08 ' + '─'.repeat(40));
await s.println(` |07Handle |08: |15${esc(handle)}`);
await s.println(` |07Password |08: |15${'*'.repeat(password.length)}`);
await s.println(` |07Real name|08: |15${esc(realName)}`);
await s.println(` |07Location |08: |15${esc(location)}`);
await s.println(` |07Email |08: |15${email ? esc(email) : '|08(none)'}`);
await s.println('|08 ' + '─'.repeat(40));
await s.print(' |14Is this correct? |08(|15Y|08/|07n|08) |07');
if (!(await s.yesNo(true))) continue;
try {
const user = await createUser({ handle, password, realName, location, email });
await s.println('\r\n |10Account created! |07Your access level is |15New User|07.');
return user;
} catch (err) {
if (err instanceof HandleTakenError) {
await s.println('\r\n |12Someone grabbed that handle while you were typing. Please start over.');
await s.pause();
continue;
}
throw err;
}
}
}

88
src/server.ts Normal file
View File

@ -0,0 +1,88 @@
import http from 'http';
import path from 'path';
import express from 'express';
import { WebSocketServer } from 'ws';
import { config } from './config';
import { migrate } from './db';
import { nodes, initNodes } from './nodes';
import { Session, Disconnected } from './session/Session';
import { runCall } from './screens/connect';
const ROOT = path.resolve(__dirname, '..');
const send = (ws: import('ws').WebSocket, msg: object) => ws.send(JSON.stringify(msg));
async function main(): Promise<void> {
await migrate();
initNodes(config.maxNodes);
const app = express();
app.disable('x-powered-by');
app.use('/vendor/xterm', express.static(path.join(ROOT, 'node_modules', '@xterm', 'xterm')));
app.use(express.static(path.join(ROOT, 'public')));
app.get('/healthz', (_req, res) => res.json({ ok: true }));
const server = http.createServer(app);
const wss = new WebSocketServer({ server, path: '/ws', maxPayload: 4096 });
wss.on('connection', (ws) => {
const slot = nodes.indexOf(null);
if (slot < 0) {
send(ws, { t: 'busy' });
ws.close(1000, 'BUSY');
return;
}
const session = new Session(ws, slot + 1, config.baud, config.idleMs);
nodes[slot] = session;
console.log(`[node ${session.node}] ring`);
send(ws, { t: 'ring', node: session.node, baud: config.baud });
// A caller who dials but never completes the handshake frees the line.
const answerTimeout = setTimeout(() => session.hangup(), 60_000);
let started = false;
ws.on('message', (raw) => {
let msg: { t?: string; d?: unknown };
try {
msg = JSON.parse(String(raw));
} catch {
return;
}
if (msg.t === 'start' && !started) {
started = true;
clearTimeout(answerTimeout);
console.log(`[node ${session.node}] connect`);
runCall(session)
.catch((err) => {
if (err instanceof Disconnected) return;
console.error(`[node ${session.node}] error`, err);
try {
session.write('\r\n\x1b[91mSystem error. Please call back later.\x1b[0m\r\n');
} catch {
/* gone */
}
})
.finally(() => session.hangup());
} else if (msg.t === 'd' && typeof msg.d === 'string') {
session.onInput(msg.d.slice(0, 512));
}
});
ws.on('close', () => {
clearTimeout(answerTimeout);
session.markClosed();
if (nodes[slot] === session) nodes[slot] = null;
console.log(`[node ${session.node}] no carrier${session.user ? ` (${session.user.handle})` : ''}`);
});
ws.on('error', () => session.markClosed());
});
server.listen(config.port, () => {
console.log(`[bbs] ${config.bbsName} online: http://localhost:${config.port} (${config.maxNodes} nodes @ ${config.baud} bps)`);
});
}
main().catch((err) => {
console.error('[bbs] fatal', err);
process.exit(1);
});

241
src/session/Session.ts Normal file
View File

@ -0,0 +1,241 @@
import type { WebSocket } from 'ws';
import { pipe, CLS } from './ansi';
import type { User } from '../users/userRepo';
export class Disconnected extends Error {
constructor() {
super('Caller disconnected');
}
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export interface ReadLineOptions {
maxLen?: number;
mask?: boolean;
/** Draw a highlighted input field (classic BBS style). */
field?: boolean;
}
/** One caller on one node. All BBS screens talk to the terminal through this. */
export class Session {
user: User | null = null;
activity = 'Logging on';
readonly connectedAt = new Date();
loginAt: Date | null = null;
private keys: string[] = [];
private waiter: ((key: string) => void) | null = null;
private failer: ((err: Error) => void) | null = null;
private closed = false;
private printing = false;
private skipThrottle = false;
private idleTimer: NodeJS.Timeout | null = null;
constructor(
private readonly ws: WebSocket,
readonly node: number,
readonly baud: number,
private readonly idleMs: number,
) {}
get isOpen(): boolean {
return !this.closed;
}
// ---- input ----------------------------------------------------------
/** Raw keystrokes from the browser terminal. */
onInput(data: string): void {
if (this.closed) return;
// Drop cursor/function-key escape sequences and bare LFs (Enter arrives as CR).
const clean = data.replace(/\x1b(\[[0-9;?]*[ -/]*[@-~]|O.|.)?/g, '').replace(/\n/g, '');
if (!clean) return;
if (this.printing) {
// Any key while a screen is "transmitting" fast-forwards it.
this.skipThrottle = true;
return;
}
for (const ch of clean) this.keys.push(ch);
if (this.keys.length > 256) this.keys.splice(0, this.keys.length - 256);
this.deliver();
}
private deliver(): void {
if (this.waiter && this.keys.length) {
const w = this.waiter;
this.waiter = null;
this.failer = null;
this.clearIdle();
w(this.keys.shift()!);
}
}
readKey(): Promise<string> {
this.ensureOpen();
this.skipThrottle = false;
if (this.keys.length) return Promise.resolve(this.keys.shift()!);
return new Promise((resolve, reject) => {
this.waiter = resolve;
this.failer = reject;
this.armIdle();
});
}
/** Waits for one of the given hotkeys (case-insensitive) and echoes it. */
async readChoice(valid: string, echo = true): Promise<string> {
const set = valid.toUpperCase();
for (;;) {
const k = (await this.readKey()).toUpperCase();
if (set.includes(k)) {
if (echo) this.write(k === '\r' ? '' : k);
return k;
}
}
}
async yesNo(defaultYes = true): Promise<boolean> {
const k = await this.readChoice('YN\r', false);
const yes = k === '\r' ? defaultYes : k === 'Y';
this.write(yes ? 'Yes' : 'No');
this.write('\r\n');
return yes;
}
async readLine(opts: ReadLineOptions = {}): Promise<string> {
const max = opts.maxLen ?? 60;
const field = opts.field ?? true;
if (field) this.write(`\x1b[97;44m${' '.repeat(max)}\x1b[${max}D`);
let buf = '';
try {
for (;;) {
const k = await this.readKey();
if (k === '\r') break;
if (k === '\x7f' || k === '\b') {
if (buf.length) {
buf = buf.slice(0, -1);
this.write('\b \b');
}
continue;
}
if (k === '\x15' || k === '\x18') {
// Ctrl-U / Ctrl-X: erase line
this.write('\b \b'.repeat(buf.length));
buf = '';
continue;
}
if (k < ' ' || k > '~' || k === '|') continue;
if (buf.length >= max) {
this.write('\x07');
continue;
}
buf += k;
this.write(opts.mask ? '*' : k);
}
} finally {
if (this.isOpen) this.write('\x1b[0m');
}
this.write('\r\n');
return buf;
}
async pause(): Promise<void> {
this.write(pipe('|08[|07Press any key to continue|08]|07'));
await this.readKey();
this.write('\r\x1b[2K');
}
// ---- output ---------------------------------------------------------
/** Immediate, unthrottled output (echo, cursor control). */
write(data: string): void {
this.ensureOpen();
this.ws.send(JSON.stringify({ t: 'd', d: data }));
}
/** Output with pipe codes, throttled to the simulated baud rate. */
async print(text: string): Promise<void> {
await this.transmit(pipe(text));
}
async println(text = ''): Promise<void> {
await this.transmit(pipe(text) + '\r\n');
}
clear(): void {
this.write(CLS);
}
private async transmit(data: string): Promise<void> {
this.ensureOpen();
const cps = this.baud / 10; // 8N1 = 10 bits per character
if (cps <= 0 || this.skipThrottle) {
this.write(data);
return;
}
const tick = 20;
const chunk = Math.max(1, Math.round((cps * tick) / 1000));
this.printing = true;
try {
for (let i = 0; i < data.length; i += chunk) {
if (this.skipThrottle) {
this.write(data.slice(i));
break;
}
this.write(data.slice(i, i + chunk));
if (i + chunk >= data.length) break; // no trailing delay: keys typed now are real input
await sleep(tick);
this.ensureOpen();
}
} finally {
this.printing = false;
}
}
// ---- connection -----------------------------------------------------
/** Drop carrier from the BBS side. */
hangup(): void {
if (this.closed) return;
try {
this.ws.send(JSON.stringify({ t: 'hangup' }));
this.ws.close(1000, 'NO CARRIER');
} catch {
/* socket already gone */
}
this.markClosed();
}
/** Called when the socket closes from either side. */
markClosed(): void {
if (this.closed) return;
this.closed = true;
this.clearIdle();
const fail = this.failer;
this.waiter = null;
this.failer = null;
fail?.(new Disconnected());
}
private ensureOpen(): void {
if (this.closed) throw new Disconnected();
}
private armIdle(): void {
this.clearIdle();
if (this.idleMs <= 0) return;
this.idleTimer = setTimeout(() => {
try {
this.write(pipe('\r\n\r\n|12Idle time limit exceeded. |07Disconnecting...\r\n'));
} catch {
/* ignore */
}
this.hangup();
}, this.idleMs);
}
private clearIdle(): void {
if (this.idleTimer) clearTimeout(this.idleTimer);
this.idleTimer = null;
}
}

42
src/session/ansi.ts Normal file
View File

@ -0,0 +1,42 @@
/**
* Pipe color codes, in the style of classic BBS software:
* |00-|15 foreground (CGA palette order)
* |16-|23 background
* |CL clear screen + home
* |RS reset attributes
*/
const CGA_TO_ANSI = [0, 4, 2, 6, 1, 5, 3, 7]; // black blue green cyan red magenta brown grey
export const ESC = '\x1b[';
export const RESET = `${ESC}0m`;
export const CLS = `${ESC}0m${ESC}2J${ESC}H`;
export function pipe(text: string): string {
return text.replace(/\|(\d\d|CL|RS)/g, (_m, code: string) => {
if (code === 'CL') return CLS;
if (code === 'RS') return RESET;
const n = Number(code);
if (n < 8) return `${ESC}${30 + CGA_TO_ANSI[n]}m`;
if (n < 16) return `${ESC}${90 + CGA_TO_ANSI[n - 8]}m`;
if (n < 24) return `${ESC}${40 + CGA_TO_ANSI[n - 16]}m`;
return '';
});
}
/** Visible length of a string containing pipe codes. */
export function vlen(text: string): number {
return [...text.replace(/\|(\d\d|CL|RS)/g, '')].length;
}
export function padRight(text: string, width: number): string {
return text + ' '.repeat(Math.max(0, width - vlen(text)));
}
export function center(text: string, width = 80): string {
return ' '.repeat(Math.max(0, Math.floor((width - vlen(text)) / 2))) + text;
}
/** Neutralise pipe codes in user-supplied text before embedding it in a template. */
export function esc(text: string): string {
return text.replace(/\|/g, '!');
}

100
src/users/userRepo.ts Normal file
View File

@ -0,0 +1,100 @@
import bcrypt from 'bcryptjs';
import { pool } from '../db';
export interface User {
id: number;
handle: string;
password_hash: string;
real_name: string;
location: string;
email: string | null;
security_level: number;
times_called: number;
created_at: Date;
last_login_at: Date | null;
}
export interface NewUser {
handle: string;
password: string;
realName: string;
location: string;
email: string | null;
}
export class HandleTakenError extends Error {}
// Used so a login attempt for an unknown handle costs the same as a real one.
const DUMMY_HASH = bcrypt.hashSync('not-a-real-password', 10);
export async function findByHandle(handle: string): Promise<User | null> {
const { rows } = await pool.query<User>('SELECT * FROM users WHERE lower(handle) = lower($1)', [handle]);
return rows[0] ?? null;
}
export async function handleExists(handle: string): Promise<boolean> {
return (await findByHandle(handle)) !== null;
}
export async function verifyLogin(handle: string, password: string): Promise<User | null> {
const user = await findByHandle(handle);
const ok = await bcrypt.compare(password, user?.password_hash ?? DUMMY_HASH);
return user && ok ? user : null;
}
export async function createUser(u: NewUser): Promise<User> {
const hash = await bcrypt.hash(u.password, 10);
try {
const { rows } = await pool.query<User>(
`INSERT INTO users (handle, password_hash, real_name, location, email)
VALUES ($1, $2, $3, $4, $5) RETURNING *`,
[u.handle, hash, u.realName, u.location, u.email],
);
return rows[0];
} catch (err: unknown) {
if ((err as { code?: string }).code === '23505') throw new HandleTakenError();
throw err;
}
}
/** Records a successful logon. Returns the system caller number and the refreshed user row. */
export async function recordCall(userId: number, node: number): Promise<{ callerNo: number; user: User }> {
const client = await pool.connect();
try {
await client.query('BEGIN');
const call = await client.query<{ id: number }>(
'INSERT INTO calls (user_id, node) VALUES ($1, $2) RETURNING id',
[userId, node],
);
const upd = await client.query<User>(
`UPDATE users SET times_called = times_called + 1, last_login_at = now()
WHERE id = $1 RETURNING *`,
[userId],
);
await client.query('COMMIT');
return { callerNo: call.rows[0].id, user: upd.rows[0] };
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
export interface LastCaller {
id: number;
handle: string;
location: string;
node: number;
connected_at: Date;
}
export async function lastCallers(limit = 10): Promise<LastCaller[]> {
const { rows } = await pool.query<LastCaller>(
`SELECT c.id, u.handle, u.location, c.node, c.connected_at
FROM calls c JOIN users u ON u.id = c.user_id
ORDER BY c.id DESC LIMIT $1`,
[limit],
);
return rows;
}

13
tsconfig.json Normal file
View File

@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"sourceMap": true
},
"include": ["src"]
}