From 2ba9870f32a0d9b8f2d3b085e79bf740a726f781 Mon Sep 17 00:00:00 2001 From: Clay Date: Thu, 3 Dec 2026 15:31:33 -0500 Subject: [PATCH] Docs: add durable code comments for OSCAR/TOC architecture and gotchas --- public/app.js | 15 +++++++++++---- public/index.html | 4 ++-- public/js/ui.js | 4 +++- src/config.js | 12 ++++++++---- src/db.js | 5 +++++ src/icq-presence.js | 4 ++++ src/oscar.js | 19 ++++++++++++++++--- src/poller.js | 10 ++++++++-- src/routes/auth.js | 9 +++++++++ src/routes/messages.js | 9 +++++++++ src/routes/stream.js | 6 ++++++ src/server.js | 10 +++++++++- src/sessions.js | 17 ++++++++++------- src/sqlite-session-store.js | 2 ++ src/toc-session.js | 13 +++++++++++-- src/toc.js | 23 ++++++++++++++++++++--- 16 files changed, 133 insertions(+), 29 deletions(-) diff --git a/public/app.js b/public/app.js index 8876792..c3c2763 100644 --- a/public/app.js +++ b/public/app.js @@ -1,7 +1,14 @@ -// public/app.js - front-end entry point. Wires state, UI, API, and event stream. -import { api } from './js/api.js?v=34'; -import { createStream } from './js/stream.js?v=34'; -import * as ui from './js/ui.js?v=34'; +// public/app.js - front-end entry point. Wires state, UI, API, and SSE event stream. +// +// Architecture: +// - State is a small in-memory object (conversations, buddies, invites, active tab). +// - SSE events arrive from /api/events; handlers normalize/dedupe and update state + UI. +// - Dedupe matters because TOC/Web API paths and SSE replay can surface the same message; +// we use msgId when present, otherwise a short recent text/from/mine heuristic. +// - UI rendering is delegated to js/ui.js; API calls to js/api.js; SSE to js/stream.js. +import { api } from './js/api.js?v=35'; +import { createStream } from './js/stream.js?v=35'; +import * as ui from './js/ui.js?v=35'; window.addEventListener('error', (e) => { console.error('[ui] error', e.error || e.message); diff --git a/public/index.html b/public/index.html index 57b570f..8818a10 100644 --- a/public/index.html +++ b/public/index.html @@ -4,7 +4,7 @@ Web OSCAR Chat - +
@@ -98,6 +98,6 @@
- + diff --git a/public/js/ui.js b/public/js/ui.js index 41aa940..778dd7b 100644 --- a/public/js/ui.js +++ b/public/js/ui.js @@ -1,4 +1,6 @@ -// public/js/ui.js - all DOM updates. Show message text with textContent, never innerHTML. +// public/js/ui.js - DOM rendering/helpers for the frontend. +// Security: render user/message text with textContent (never innerHTML). +// UX: buddy presence is intentionally simplified to online/offline only. const el = (id) => document.getElementById(id); diff --git a/src/config.js b/src/config.js index f94c745..4dafc2c 100644 --- a/src/config.js +++ b/src/config.js @@ -1,6 +1,10 @@ -// src/config.js - reads the settings once; every other file imports from here. -// A missing variable falls back to the server's default. A bad value stops the -// app at startup with a clear message instead of failing in a confusing way later. +// src/config.js - central runtime config (env vars, defaults, startup validation). +// +// Notes: +// - WEBAPI_BASE/MANAGEMENT_BASE are default OSCAR endpoints; login can also accept +// user-supplied host/ports (validated/SSRF-checked in auth) for per-session targets. +// - Bad config should fail fast at startup with a clear error. +// - Never log secrets (SESSION_SECRET, passwords, tokens). function port(name, fallback) { const raw = process.env[name] ?? String(fallback); @@ -47,7 +51,7 @@ export const DB_PATH = process.env.DB_PATH || './data/oscar-web.sqlite'; export const NODE_ENV = process.env.NODE_ENV || 'development'; export function logStartupConfig() { - // Never log DEV_ID or SESSION_SECRET. + // Never log secrets. console.log(`[config] Web API: ${WEBAPI_BASE}`); console.log(`[config] Management API: ${MANAGEMENT_BASE}`); console.log(`[config] App listen: http://${LISTEN_HOST}:${PORT}`); diff --git a/src/db.js b/src/db.js index 03382be..13122e0 100644 --- a/src/db.js +++ b/src/db.js @@ -1,3 +1,8 @@ +// src/db.js - SQLite bootstrap for persistent express-session storage. +// +// Why SQLite: small single-process deployment, no external DB dependency, survives restarts. +// If the DB is malformed/corrupt, we rotate it aside (*.corrupt-*) and recreate schema so the +// app can come back up cleanly (users will need to log in again, but service recovers). import fs from 'node:fs'; import path from 'node:path'; import Database from 'better-sqlite3'; diff --git a/src/icq-presence.js b/src/icq-presence.js index 728470a..c61a2cf 100644 --- a/src/icq-presence.js +++ b/src/icq-presence.js @@ -5,6 +5,10 @@ export { isIcqScreenName } from './screenname.js'; // users may not. OSCAR/TOC presence semantics can differ for ICQ; this module keeps // any ICQ-specific nudges separate from the working AIM/TOC flow. // +// Limitation: this does not guarantee native AIM/ICQ clients see ICQ webui users online. +// That requires server-side BuddyArrived/presence behavior. See web-presence.js for the +// webui-only SSE overlay workaround. +// // Do not add guessing here. Only safe, documented TOC commands with clear intent. // Wrapped in try/catch by caller so failures never break normal login. diff --git a/src/oscar.js b/src/oscar.js index afd9364..7f0e5aa 100644 --- a/src/oscar.js +++ b/src/oscar.js @@ -1,5 +1,16 @@ -// src/oscar.js - the ONLY file that knows how to talk to the Web API. -// Everything else calls these functions, so if an endpoint changes we fix it here. +// src/oscar.js - the ONLY file that knows how to talk to the Open OSCAR Web API. +// +// Everything else calls these functions; if an endpoint/param/shape changes, fix it here. +// +// Architecture notes: +// - Open OSCAR Server 0.25.0 exposes Web API (HTTP) and TOC (FLAP/TCP). This app uses +// Web API for login/startSession/fetchEvents/presence/buddies and TOC for IM/chat/invites +// because Web API chat endpoints (/chat/*) returned 404 on 0.25.0 in testing. +// - All Web API calls use the envelope: { response: { statusCode, statusText, data } }. +// We always request f=json and throw OscarApiError on non-200 statusCode. +// - `base` is per-login (user can point at a configured host/port). Never assume the +// default WEBAPI_BASE for logged-in session operations; pass rec.webapiBase. +// - fetchBaseURL from startSession/fetchEvents is intentionally ignored; see poller.js. import { WEBAPI_BASE, MANAGEMENT_BASE } from './config.js'; @@ -93,7 +104,9 @@ export async function sendIM(aimsid, to, message, { base } = {}) { return call('/im/sendIM', { aimsid, t: to, message }, baseOpt(base)); } -// --- Chat --- +// --- Chat (Web API) --- +// Note: Open OSCAR Server 0.25.0 did not expose these Web API chat endpoints in testing. +// TOC is the primary chat transport; these remain for compatibility/future servers. export async function createAndJoinChat(aimsid, room, { base } = {}) { return call('/chat/createAndJoinChat', { aimsid, room }, baseOpt(base)); diff --git a/src/poller.js b/src/poller.js index 6ff7a32..25c71e7 100644 --- a/src/poller.js +++ b/src/poller.js @@ -1,5 +1,11 @@ -// src/poller.js - one long-poll loop per logged-in user. -// 'async' functions can pause with 'await' without blocking other users. +// src/poller.js - Web API long-poll loop (one per logged-in session with aimsid). +// +// Open OSCAR Web API delivers events via /aim/fetchEvents. We keep a simple loop: +// fetch -> normalize -> emit on bus -> broadcast to SSE clients -> repeat. +// `seqNum` is advanced from lastSeqNum so we don't reprocess events. +// fetchBaseURL is intentionally ignored (see planning.md); using configured base is simpler. +// We keep a small per-session event buffer so new SSE connections can replay recent events +// (helps when frontend connects after initial buddylist/presence/myInfo). import * as oscar from './oscar.js'; import { bus } from './bus.js'; diff --git a/src/routes/auth.js b/src/routes/auth.js index 82e812e..ded7a26 100644 --- a/src/routes/auth.js +++ b/src/routes/auth.js @@ -123,6 +123,15 @@ async function tryTocLogin(rec, { screenName, host, tocPort, password, webapiBas return next; } +// Login flow: +// 1) Validate captcha + required credentials. +// 2) Validate target host/ports and block private/local targets (SSRF guard). +// 3) Tear down any existing session for this browser/screen name, then regenerate +// the express-session id (session fixation protection). +// 4) Try Web API login/startSession for buddy/presence/poller. +// 5) Try TOC login for IM/chat/invites (works even when Web API chat is unavailable). +// 6) If either transport succeeds, store session record, start poller (if Web API), +// mark ICQ webui presence overlay, and return transport status. authRouter.post('/login', async (req, res) => { const screenName = cleanScreenName(req.body?.screenName); const password = readPassword(req); diff --git a/src/routes/messages.js b/src/routes/messages.js index b0b9e3f..90e0e9c 100644 --- a/src/routes/messages.js +++ b/src/routes/messages.js @@ -1,3 +1,12 @@ +// src/routes/messages.js - IM/chat send/join/leave/accept endpoints. +// +// Transport selection: prefer TOC when connected (required for chat on OSCAR 0.25.0, +// also used for IM). Fall back to Web API where possible. The frontend gets the same +// SSE event shapes regardless of transport; TOC sends may synthesize "sentIM" echoes. +// +// Subtlety: for chat send/leave, `room` is the TOC roomId when on TOC transport, but +// Web API chat endpoints historically used room name/id differently - keep payloads aligned +// with frontend behavior (frontend stores chat roomId/name from events). import { Router } from 'express'; import * as oscar from '../oscar.js'; import { broadcast } from '../poller.js'; diff --git a/src/routes/stream.js b/src/routes/stream.js index 2d53ba1..8859aff 100644 --- a/src/routes/stream.js +++ b/src/routes/stream.js @@ -2,6 +2,12 @@ import { Router } from 'express'; import { requireLogin, cleanupSessionById } from './auth.js'; import { replayWebuiPresence } from '../web-presence.js'; +// SSE endpoint for real-time events. +// +// Notes: +// - One browser may hold an SSE connection; we cap per-IP connections to limit abuse. +// - We replay rec.eventBuffer so a freshly connected client sees recent buddylist/presence/myInfo. +// - On disconnect, we wait briefly before tearing down OSCAR/TOC session to tolerate page reloads. export const streamRouter = Router(); const ipConnections = new Map(); // ip -> count diff --git a/src/server.js b/src/server.js index 1027b1b..fe40df3 100644 --- a/src/server.js +++ b/src/server.js @@ -1,4 +1,12 @@ -// src/server.js - starts Express, wires everything together. +// src/server.js - Express app composition / process entrypoint. +// +// Wiring overview: +// - HTTP API + static frontend served by Express. +// - express-session is backed by SQLite (db.js + sqlite-session-store.js) for persistence. +// - OSCAR/TOC live session state is in-memory (sessions.js); on restart users re-login. +// - Web API events come from poller.js long-poll; TOC events come from toc-session.js. +// Both broadcast normalized events over SSE (/api/events) via poller.broadcast/bus. +// - Session sweep cleans up expired/orphaned OSCAR sessions when SSE disconnects/timeouts. import express from 'express'; import session from 'express-session'; import rateLimit from 'express-rate-limit'; diff --git a/src/sessions.js b/src/sessions.js index 3516ebb..f20ef6b 100644 --- a/src/sessions.js +++ b/src/sessions.js @@ -1,11 +1,14 @@ -// src/sessions.js - in-memory map of logged-in users. -// Keyed by express-session id. Sessions reset on restart (acceptable for v1). - -// Session record shape: +// src/sessions.js - in-memory OSCAR/TOC session state keyed by express-session id. +// +// Important distinction: +// - Express-session cookie/session data is persisted in SQLite (see db.js/sqlite-session-store.js). +// - OSCAR/TOC live connections are in-memory only. After process restart, users must log in again. +// +// Session record shape (typical): // { -// sessionId, screenName, token, aimsid, seqNum, -// sseClients: Set, -// polling: boolean, +// sessionId, screenName, token, aimsid, webapiBase, +// seqNum, sseClients: Set, polling, +// eventBuffer: [], toc: TOCClient|null, tocConnected: boolean, // fetchBaseURL?: string, // } diff --git a/src/sqlite-session-store.js b/src/sqlite-session-store.js index ebee3ff..e3cdb7f 100644 --- a/src/sqlite-session-store.js +++ b/src/sqlite-session-store.js @@ -1,3 +1,5 @@ +// src/sqlite-session-store.js - minimal express-session store backed by SQLite. +// Sessions persist across process restarts; corrupt DB errors trigger recovery via db.js. import session from 'express-session'; import { getDb, recoverDbIfCorrupt } from './db.js'; diff --git a/src/toc-session.js b/src/toc-session.js index 17d27d1..d594ee4 100644 --- a/src/toc-session.js +++ b/src/toc-session.js @@ -1,6 +1,15 @@ // src/toc-session.js - TOC/TOC2 transport bridge. -// Connects a TOCClient for a logged-in web session and emits normalized events -// on the same bus/SSE shape as the Web API poller. +// +// Why this exists: +// - Web API is good for login/presence/buddylist on 0.25.0, but chat endpoints were 404. +// - TOC provides IM + chat + chat invites. We run TOC alongside Web API for the same user. +// +// Design: +// - TOCClient emits parsed TOC events; this file normalizes them into the same internal +// event shape used by poller.js ({ type, time, data, raw }) so the frontend/SSE path can +// handle both transports uniformly. +// - Some TOC events are synthesized (e.g. toc_status, sentIM echo) because Web API/poller +// has different semantics. Keep this layer small and defensive. import { TOCClient } from './toc.js'; import { bus } from './bus.js'; diff --git a/src/toc.js b/src/toc.js index 46965d7..94b20a4 100644 --- a/src/toc.js +++ b/src/toc.js @@ -1,6 +1,21 @@ // src/toc.js - minimal TOC/TOC2 client for Open OSCAR Server. -// Implements FLAP framing and TOC commands needed for IM and chat. -// Reference: open-oscar-server server/toc/* (mk6i/open-oscar-server). +// +// Implements the small subset of TOC/TOC2 we need: signon, IM, chat join/send/invite, +// and buddy/presence events. Reference: mk6i/open-oscar-server server/toc/*. +// +// Protocol tips (worth knowing before debugging): +// - TOC runs over TCP, usually port 9898. Client starts by sending "FLAPON\r\n\r\n" +// (plain text), then speaks FLAP frames. +// - FLAP frame: [0x2A, channel, seq(2), len(2), payload...]. Channels: 1=signon, +// 2=data (TOC commands), 4=signoff, 5=keepalive. +// - TOC signon flow: server sends FLAP SIGNON -> client replies with FLAP SIGNON body +// (version 1 + TLV 0x0001 screen name) -> client sends `toc2_signon ...` on data +// channel -> server replies SIGN_ON -> client sends toc_init_done / toc_set_caps. +// - TOC data payloads are UTF-8 text commands; args are whitespace-separated and may be +// quoted/escaped. Do NOT add a NUL terminator for open-oscar-server compatibility. +// - Password "roasting" is XOR with "Tic/Toc" and sent as `0x...` hex. Do NOT prepend +// the old OSCAR 0x0002 prefix here; that breaks TOC signon. +// - TOC is picky/old: log raw FLAP/data during debugging, but redact secrets. import net from 'node:net'; import { EventEmitter } from 'node:events'; @@ -226,7 +241,9 @@ export class TOCClient extends EventEmitter { } _emitParsed(cmd, rest, raw) { - // Parse common server messages into structured events. + // Parse common TOC server messages into structured events. + // TOC formats vary slightly across servers/clients (TOC1 vs TOC2, ENC variants). + // We parse defensively by splitting on ':' and joining trailing message fields. if (cmd === 'IM_IN2') { // IM_IN2:::: const parts = rest.split(':');