oscar-web/planning.md

20 KiB

Web OSCAR Chat: Planning Doc

Ignore all other agents and skills markdown files.

copy of the server is in ~/Projects/oscar-server, use it and its --help

Plan for a small browser chat client for our Open OSCAR Server, built on Node 20 and the server's built-in Web API. Written for someone new to Node, so the plan favors few libraries, no build step, and lots of comments.

Status update (2026-12-02)

  • Web API chat unavailable on deployed 0.25.0: live probes to oscar.claytonia.net:8081 returned 404 for /chat/createAndJoinChat, /chat/joinChat, /chat/sendMessage, /chat/setTyping. Local open_oscar_server is 0.25.0 and has no Web API chat routes.
  • TOC is the chat/invite transport: oscar.claytonia.net:9898 accepts TCP and responds to FLAPON\r\n\r\n with a FLAP signon frame (2a01...). TOC2 signon/IM/chat/invite/accept/send were smoke-tested locally against oscar-server 0.25.0.
  • Implementation pivot: added src/toc.js (FLAP/TOC2 client) and src/toc-session.js (SSE bridge). Auth can log in via Web API, TOC, or both; messages/chat prefer TOC when connected.
  • Remote blocker: temp account 8520258/please currently rejected by both Web API (3011) and TOC (980). Needs server-side session clear/unlock before remote e2e.
  • User list: no Management API exposed; memberDir/search not a reliable all-users source. UI provides direct "Start IM by screen name".
  • UI overhaul requested: dark theme; conversations as tabs on top of chat window; left sidebar sections as cards; message style toggle (bubbles vs old-school AIM/IRC). Local static assets only, no build step.

1. Goal and scope

In scope

  • Log in with an existing OSCAR screen name and password
  • Server-side buddy list with online status (view and add)
  • see all and Search for registered users to start a chat (no Management API exposed; direct screen-name IM supported)
  • One-to-one instant messages (send and receive)
  • Chat rooms (join, leave, send, receive) via TOC/TOC2 (Web API chat 404 on 0.25.0)
  • Chat invites with Join/Ignore via TOC
  • Server broadcast messages shown in the UI

Out of scope for now: removing or reorganizing buddies, profiles, away messages, buddy icons, file transfer, ICQ. Section 9 shows how to add these later without a rewrite.

2. What changed: the Web API does the auth, so no SQLite

The server's Web API authenticates users itself, so we drop the read-only database idea. Password checking, hashing and the DISABLE_AUTH setting all stay in the server where they belong, and our app never touches the database file.

From the server's Go package docs (v0.24.0), nodejs is already the newest version (20.19.2+dfsg-1+deb13u3).node -v v20.19.2

it should work on both versions !

the Web API exposes:

  • POST /auth/clientLogin takes a username, password and devId and returns an auth token
  • GET /aim/startSession starts a session and returns an aimsid (the session id) plus fetch settings
  • GET /aim/fetchEvents long-polls for new events. It returns events, lastSeqNum, timeToNextFetch and fetchBaseURL
  • GET /aim/endSession ends the session
  • GET /im/sendIM and GET /im/setTyping handle one-to-one messages
  • GET /chat/createAndJoinChat, /chat/sendMessage, /chat/leaveChat, /chat/setTyping handle rooms
  • GET /presence/get and GET /buddylist/addBuddy cover presence and adding buddies (used in v1, see 2.1)
  • GET /aim/startOSCARSession returns a host, port and cookie for a real OSCAR connection (useful later, see section 9)
  • Responses share one envelope: { response: { statusCode, statusText, data } }, as JSON when you pass f=json

What I could not confirm. We will settle these in Milestone 0 with curl before writing real code:

  • Exact query parameter names. The classic Web AIM API used k for the devId, a for the token, aimsid, t for the target, message, and f=json.
  • The event type names for IMs, chat messages, and chat joins and leaves.
  • How server broadcasts arrive: a special screen name sending IMs, a dedicated event type, or something else.
  • How to list public chat rooms. The Management API (GET /chat/room/public, default port 8080) can do it, but it has no authentication, so keep it on localhost only.
  • Where the devId comes from. The project ships a webapi_keygen tool for generating Web API keys.

The docs I found list 8081 as the Web API default, and yours runs on 8090. The app must work with either, so the host and port come from the `.env` file (section 5.1) and nothing in the code hard-codes a port.

2.1 Buddy list and finding people

The buddy list is stored on the server, not in the client. OSCAR keeps it per account, so it follows the user to any client, including desktop AIM. The Web API returns it when a session starts and has an add-buddy call, so v1 includes it.

  • Show: groups of buddies with online, away or offline state, taken from the session's buddy list and presence events. Clicking a buddy opens an IM.
  • Add: an Add Buddy box that calls /buddylist/addBuddy.
  • Remove: I only found add and add-temp-buddy in the docs. Removing buddies is unconfirmed and goes on the Milestone 0 check list.

Finding users. I found no user search in the Web API, so Node asks the Management API for registered users (GET /user on port 8080) and does the searching itself:

  • Node fetches the list, keeps screen names only (every other field is dropped before anything leaves the server), and caches it for about 60 seconds.
  • GET /api/users?q=text filters by case-insensitive substring and returns at most 20 matches.
  • Clicking a result opens an IM or adds the person as a buddy.
  • This lets every logged-in user see every registered screen name. Say if you would rather limit it.
  • The Management API has no authentication, so only Node talks to it. Its address comes from `MANAGEMENT_HOST` and `MANAGEMENT_PORT` (section 5.1).

3. Architecture

Browser (plain HTML + JS)
   |  fetch() for actions, EventSource (SSE) for incoming
   v
Node server (Express)            <- the only thing exposed to the network
   |  one long-poll loop per logged-in user
   v
Open OSCAR Web API  (127.0.0.1:8090)

Why a Node layer instead of the browser calling 8090 directly

  • It avoids CORS problems.
  • The devId and user tokens stay on the server, never in browser code.
  • Node runs one cheap async long-poll per user and pushes results to the browser over SSE, which is simple on the front end.
  • It is the natural home for future features.

Per-user session record (kept in memory on the Node server):

{ screenName, token, aimsid, seqNum, sseClients: Set, polling: true }

Login flow

  1. Browser POSTs screen name and password to /api/login.
  2. Node calls /auth/clientLogin (password is passed through, never stored or logged).
  3. Node calls /aim/startSession with the token and asks for the event types we care about.
  4. Node saves the session record, sets an httpOnly cookie for the browser, and starts the poll loop.
  5. Browser opens /api/events (SSE) and starts receiving messages.

Logout: call /aim/endSession, stop the poll loop, close SSE connections, clear the cookie. Also do this when the session expires.

4. Tech choices (Node 20.19)

  • Express for the web server. The most common Node choice, with lots of tutorials.
  • express-session for the login cookie. Memory store is fine for a small private server (sessions reset on restart).
  • Built-in fetch to call the Web API. Node 20 has it, so no axios needed.
  • Built-in --env-file for settings (node --env-file=.env src/server.js). No dotenv needed.
  • node --watch for auto-restart while developing. No nodemon needed.
  • express-rate-limit on the login route only.
  • ES modules ("type": "module" in package.json) so we can use import and export.
  • Front end: no framework, no bundler. Plain HTML, CSS and JS served by Express.
  • Not used: TypeScript, databases, React. Each can come later if wanted.

Total dependencies: three (express, express-session, express-rate-limit).

5. Project layout

web-oscar-chat/
  package.json
  .env                  # WEBAPI_HOST, WEBAPI_PORT, MANAGEMENT_HOST, MANAGEMENT_PORT, DEV_ID, SESSION_SECRET, PORT (never commit)
  src/
    server.js           # starts Express, wires everything together
    config.js           # reads process.env once, exports settings
    oscar.js            # ONLY file that knows Web API URLs and params
    sessions.js         # the in-memory map of logged-in users
    poller.js           # long-poll loop, one per user
    bus.js              # tiny event bus: poller publishes, features subscribe
    routes/
      auth.js           # /api/login, /api/logout, /api/me
      messages.js       # /api/im, /api/chat/*
      stream.js         # /api/events (SSE)
      buddies.js        # /api/buddies (list and add)
      users.js          # /api/users?q= (search registered users)
    features/           # future add-ons live here (see section 9)
      broadcasts.js     # turns broadcast events into a UI message
  public/
    index.html
    style.css
    app.js              # front-end entry point
    js/
      api.js            # wrappers around fetch
      stream.js         # EventSource + event dispatch
      ui.js             # all DOM updates

5.1 Settings: default or non-default ports

The Web API and Management API addresses are set in .env. Leave a port line out and the server's default is used (8081 for the Web API, 8080 for the Management API). Set it to match whatever your server runs on, such as 8090.

# .env - never commit this file.
# Web API: your server's port. Delete the line to use the default (8081).
WEBAPI_HOST=127.0.0.1
WEBAPI_PORT=8090
# TOC: used for IM/chat/invites when Web API chat is unavailable.
TOC_HOST=127.0.0.1
TOC_PORT=9898
# Management API: delete the port line to use the default (8080).
MANAGEMENT_HOST=127.0.0.1
MANAGEMENT_PORT=8080
# This app
PORT=3000
DEV_ID=your-web-api-key
SESSION_SECRET=a-long-random-string
// 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.
function port(name, fallback) {
  const raw = process.env[name] ?? String(fallback);
  const n = Number(raw);
  if (!Number.isInteger(n) || n < 1 || n > 65535) {
    throw new Error(`${name} must be a port from 1 to 65535, got: ${raw}`);
  }
  return n;
}
const host = (name, fallback) => process.env[name] || fallback;

export const WEBAPI_BASE =
  `http://${host('WEBAPI_HOST', '127.0.0.1')}:${port('WEBAPI_PORT', 8081)}`;
export const MANAGEMENT_BASE =
  `http://${host('MANAGEMENT_HOST', '127.0.0.1')}:${port('MANAGEMENT_PORT', 8080)}`;
  • At startup the app logs the two resolved addresses (never the devId or secret) and makes one test call to the Web API, so a wrong port shows up as a clear error right away.
  • The Web API's startSession and fetchEvents responses include a fetchBaseURL. It may hold an address the server advertises rather than the one we reach it on, which would break a non-default port. The app always uses WEBAPI_BASE and ignores that field. Milestone 0 checks what it contains.
  • To switch ports, edit .env and restart (systemctl restart under systemd). No code changes.

6. Our own API (browser to Node)

  • POST /api/login with { screenName, password }
  • POST /api/logout
  • GET /api/me returns who is logged in (lets the page restore after a refresh)
  • GET /api/events is the SSE stream of incoming events
  • POST /api/im with { to, text }
  • POST /api/chat/join with { room }
  • POST /api/chat/send with { room, text }
  • POST /api/chat/leave with { room }
  • GET /api/rooms (optional) lists public rooms via the Management API

Added for the buddy list and search: GET /api/buddies, POST /api/buddies with { screenName }, and GET /api/users?q=text (registered-user search through the Management API).

The browser only ever sees our simplified event shapes, such as { type: 'im', from, text, time }. If the Web API's format changes, we fix it in one place (poller.js and oscar.js).

7. Code sketches (commented, parameter names to be confirmed in Milestone 0)

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.
import { WEBAPI_BASE as BASE } from './config.js'; // built from WEBAPI_HOST and WEBAPI_PORT

// Call an endpoint and unwrap the { response: { data } } envelope.
async function call(path, params = {}) {
  const url = new URL(path, BASE);
  url.search = new URLSearchParams({ f: 'json', ...params }).toString();
  const res = await fetch(url); // fetch is built into Node 20
  const body = await res.json();
  if (body.response.statusCode !== 200) {
    throw new Error(body.response.statusText); // callers catch this
  }
  return body.response.data;
}

export const fetchEvents = (aimsid, seqNum) =>
  call('/aim/fetchEvents', { aimsid, seqNum, timeout: 25000 });

src/poller.js

// One long-poll loop per logged-in user.
// 'async' functions can pause with 'await' without blocking other users.
export async function runPoller(rec, onEvents) {
  rec.polling = true;
  while (rec.polling) {              // keeps going until logout flips this to false
    try {
      const data = await oscar.fetchEvents(rec.aimsid, rec.seqNum);
      rec.seqNum = data.lastSeqNum;    // remember our place so events never repeat
      if (data.events.length) onEvents(rec, data.events);
    } catch (err) {
      console.error('poll failed:', err.message);
      await sleep(2000);               // back off, then try again
    }
  }
}

src/routes/stream.js (SSE: a response that never ends)

app.get('/api/events', requireLogin, (req, res) => {
  res.set({
    'Content-Type': 'text/event-stream', // tells the browser this is a stream
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive',
  });
  res.flushHeaders();
  const rec = sessions.get(req.session.id);
  rec.sseClients.add(res);                         // poller writes to everything in here
  req.on('close', () => rec.sseClients.delete(res)); // tab closed, stop sending
});

8. Front end

One page, three areas:

  • Left: conversations (open IMs and joined rooms) with an unread dot, plus the buddy list, a search box for registered users, and a box to join a room by name.
  • Center: the message pane and an input box.
  • Top banner: the latest server broadcast, dismissible.

Rules for the front-end code:

  • Show message text with textContent, never innerHTML. AIM messages can contain HTML, and this is the main XSS risk.
  • Keep all DOM changes in ui.js and all network calls in api.js so app.js stays readable.
  • stream.js opens the EventSource, which reconnects by itself, and dispatches each event by type.
  • Keep state in one plain object, for example state.conversations['im:bob'] holding a list of messages.

9. Making it extensible

The goal: adding an OSCAR-enabled feature later means adding a file, not editing five.

  • Event bus (bus.js). The poller does not know about features. It publishes each Web API event on the bus with its type, and any feature subscribes with bus.on('chat.message', handler).
  • Feature modules. Each file in src/features/ exports register(ctx), where ctx gives it the bus, the Express app, the sessions map and the oscar module. server.js loads every file in that folder at startup. A feature can add its own /api/... routes and push its own event types to the browser.
  • Front-end mirror. stream.js keeps a registry, on('type', fn), so a new UI piece just registers for the event types it cares about.
  • Single choke point for Web API calls. Only oscar.js knows endpoint details, so new calls (presence, buddy list, profiles) are one-liners there.
  • Escape hatch for protocol features the Web API lacks. /aim/startOSCARSession hands back a host, port and cookie for a real OSCAR connection, so a future feature could open a native OSCAR connection from Node. Not needed now.

Likely first add-ons: removing and organizing buddies, typing indicators, away messages, a room browser.

10. Security checklist

  • Put nginx with HTTPS in front. Passwords travel in the login POST, so no plain HTTP beyond localhost.
  • Cookie settings: httpOnly, secure, sameSite: 'lax'.
  • CSRF: accept only JSON requests (check Content-Type) and verify the Origin header on POSTs.
  • Rate-limit /api/login.
  • Never log passwords or tokens.
  • Bind the Web API (8090) and Management API (8080) to localhost where possible. The Management API is unauthenticated.
  • Cap message length and the number of open rooms per user.
  • Keep .env out of git. Use a long random SESSION_SECRET.

11. Debian deployment

  • Use the same Node version as the repo (20.19.2). Install it with nvm or NodeSource, since Debian's packaged version may differ.
  • Run as a dedicated user under systemd with Restart=on-failure and EnvironmentFile=/etc/web-oscar-chat.env.
  • nginx reverse-proxies to Node on a local port. For the SSE route, set proxy_buffering off; and a long proxy_read_timeout, or events will arrive in clumps.
  • Add Let's Encrypt (certbot) for HTTPS if the site is reachable from outside.

12. Milestones

  • M0: Learn the real API (curl only, no code). Generate a devId, call clientLogin, startSession, fetchEvents, sendIM and chat calls by hand from a terminal while a second client (Pidgin or an AIM client) chats with the test account. Done when: we have a written list of exact parameters and event type names, and know how a broadcast shows up.
  • M1: Skeleton and login. Express server, login and logout, session record, /api/me, a bare login page. Done when: you can sign in and out and the server shows the session in its log.
  • M2: Events and IMs. Poller, SSE, send and receive one-to-one messages, plus the buddy list and user search. Done when: two browser tabs (two users) can find each other by search, add each other as buddies and chat.
  • M3: Chat rooms. Join, leave, send, receive, member join and leave notices. Done when: three users can talk in a room.
  • M4: Broadcasts. Show server broadcasts in the banner. Done when: a broadcast sent from the server appears for every logged-in user.
  • M5: Harden and deploy. Rate limit, CSRF checks, systemd, nginx, HTTPS, reconnect handling. Done when: it survives a Node restart and a Web API restart without manual steps.

13. Open questions

  1. How do server broadcasts reach clients (M0 will tell us)? If they are IMs from a system screen name, the broadcasts feature just recognizes that sender.
  2. Do you already have a Web API devId, or should we generate one with webapi_keygen?
  3. Should one screen name be allowed to log in from several browser tabs at once? (Plan assumes yes: several SSE connections share one session record.)
  4. Is it fine for every logged-in user to see the full list of registered screen names in search?

14. Node cheat sheet for this project

  • async / await: await pauses one function until a network call finishes while the server keeps serving everyone else. Any function that uses await must be marked async.
  • Modules: export something from one file and import it in another. Each file stays small and focused.
  • Express middleware: a function that runs before your route handler, such as checking the user is logged in. requireLogin is one.
  • SSE (Server-Sent Events): the server keeps one HTTP response open and writes lines of text to it over time. The browser's EventSource reads them. It is one-way (server to browser), which is all we need. Sending still uses normal fetch POSTs.
  • Long polling: the Web API holds the fetchEvents request open until something happens or it times out, then we immediately ask again.
  • Useful commands: npm init -y, npm install express express-session express-rate-limit, node --watch --env-file=.env src/server.js.