Docs: add durable code comments for OSCAR/TOC architecture and gotchas

This commit is contained in:
Clay 2026-12-03 15:31:33 -05:00
parent 6aa8c9e633
commit 2ba9870f32
16 changed files with 133 additions and 29 deletions

View file

@ -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);

View file

@ -4,7 +4,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Web OSCAR Chat</title>
<link rel="stylesheet" href="/style.css?v=34">
<link rel="stylesheet" href="/style.css?v=35">
</head>
<body>
<div id="app">
@ -98,6 +98,6 @@
</main>
</div>
<script type="module" src="/app.js?v=34"></script>
<script type="module" src="/app.js?v=35"></script>
</body>
</html>

View file

@ -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);

View file

@ -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}`);

View file

@ -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';

View file

@ -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.

View file

@ -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));

View file

@ -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';

View file

@ -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);

View file

@ -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';

View file

@ -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

View file

@ -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';

View file

@ -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<ServerResponse>,
// polling: boolean,
// sessionId, screenName, token, aimsid, webapiBase,
// seqNum, sseClients: Set<ServerResponse>, polling,
// eventBuffer: [], toc: TOCClient|null, tocConnected: boolean,
// fetchBaseURL?: string,
// }

View file

@ -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';

View file

@ -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';

View file

@ -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:<Source User>:<Auto Response T/F?>:<Unknown>:<Message>
const parts = rest.split(':');