oscar-web/HANDOFF.md

126 lines
11 KiB
Markdown

# Web OSCAR Chat - Handoff
## Status
**Phase:** M1/M2 in progress - TOC transport added for IM/chat/invites; Web API kept for buddy/presence where available. Public-hardening pass applied (SQLite sessions, corrupt DB recovery, SSE per-IP limit, input validation, session cleanup).
**Date:** 2026-12-03 (updated)
## What was done
- Created initial project scaffold in `git/oscar-web/` based on `planning.md`.
- Added project config/docs: `.gitignore`, `.env.example`, `package.json` (ESM, Node >=20.19, Express + express-session + express-rate-limit), `HANDOFF.md`.
- Added backend skeleton: `src/config.js`, `src/oscar.js`, `src/sessions.js`, `src/bus.js`, `src/poller.js`, `src/server.js`, routes (`auth`, `stream`, `messages`, `buddies`, `users`), `src/features/broadcasts.js`.
- Added minimal frontend (plain HTML/CSS/JS, no bundler): `public/index.html`, `style.css`, `app.js`, `js/api.js`, `js/stream.js`, `js/ui.js`. Uses `textContent` for message bodies (XSS-safe).
- Installed dependencies (`npm install`, 0 vulnerabilities).
- Performed partial M0 against `http://oscar.claytonia.net:8081` using temporary test account `8520258` (see Test environment section; do not bother real users).
- Fixed login bug: clientLogin returns `token` as object `{a, expiresIn}`; auth now extracts `token.a` before startSession.
- Fixed SSE race: poller buffers recent events and replays them on SSE connect; `/api/buddies` prefers latest buffered `buddylist` event. Frontend search falls back to direct IM when management API unavailable; buddy add is optimistic. Added poller event-type logging.
- Fixed `convKey` typo (`toLower` -> `toLowerCase`) that broke conversation selection and IM rendering.
- Added cache-busting/no-store for JS/CSS/HTML to avoid stale frontend.
- Fixed duplicate sent messages by returning `msgId` from send routes and deduping optimistic/sentIM.
- Stripped incoming AIM HTML to plain text safely (DOMParser) before rendering.
- Added graceful shutdown (SIGINT/SIGTERM ends OSCAR sessions).
- Installed Playwright + Chromium for headless UI testing.
- **TOC pivot (2026-12-02):**
- Confirmed Web API chat is unavailable on deployed 0.25.0 server: `/chat/createAndJoinChat`, `/chat/joinChat`, `/chat/sendMessage`, `/chat/setTyping` all return 404. Local oscar-server binary is `0.25.0` and has no Web API chat routes.
- Confirmed TOC is reachable on `oscar.claytonia.net:9898`. Probe sending `FLAPON\r\n\r\n` received FLAP signon frame `2a010000000400000001` (channel 1, len 4). Earlier HTTP 400 probe was misleading because it didn't send `FLAPON` first; TOC port serves HTTP to non-TOC clients.
- Prod env shows `TOC_LISTENERS=0.0.0.0:9898`, `WEBAPI_LISTENERS=0.0.0.0:8081` (from user-shared env). `ss` confirms open_oscar_server owns 9898/8081.
- Added `src/toc.js`: minimal TOC/TOC2 FLAP client (FLAPON announce, FLAP signon, `toc2_signon`, roasted password, NUL-less command send for login compat, IM/chat/invite/accept/leave/send helpers, parsed events).
- Added `src/toc-session.js`: bridges TOC events to existing SSE/bus event shape (`im`, `chat_invite`, `chat_join`, `chat_in`, `chat_update`, `chat_left`, `presence`, `toc_error`).
- Updated `src/routes/auth.js`: login tries Web API and/or TOC (if `TOC_HOST` set); TOC-only session supported; logout stops TOC.
- Updated `src/routes/messages.js`: IM/chat send/join/accept/leave prefer TOC when connected; added `/api/chat/accept`.
- Updated frontend (`public/app.js`, `js/api.js`, `js/ui.js`, `index.html`, `style.css`): chat invite panel with Join/Ignore, TOC chat event handlers, chat send uses roomId, cache-bust v4.
- Updated `.env.example` and `.env` with `TOC_HOST`/`TOC_PORT`.
## Local smoke test (passed)
Against local open-oscar-server 0.25.0 with `DISABLE_AUTH=true`, TOC listener 9898:
- `toc2_signon` -> `SIGN_ON:TOC2.0`, `NICK`, `CONFIG2` OK.
- IM: alice `toc2_send_im` bob -> bob received `IM_IN2:alice:F:F:hello from alice`.
- Chat: alice `toc_chat_join 4 "testroom"` -> `CHAT_JOIN:0:testroom`, `CHAT_UPDATE_BUDDY`.
- Chat send: alice `toc_chat_send 0 "hello room"` -> `CHAT_IN:0:alice:F:hello room`.
- Invite: alice `toc_chat_invite 0 "join me" bob` -> bob received `CHAT_INVITE:testroom:0:alice:join me`.
- Accept: bob `toc_chat_accept 0` -> `CHAT_JOIN`, `CHAT_UPDATE_BUDDY` for both.
- Chat message after join: bob `toc_chat_send 0 "bob here"` -> both received `CHAT_IN`.
## Current blockers / environment notes
- **TOC 980 root cause (fixed 2026-12-02):** `src/toc.js` `roastPassword` incorrectly prepended `00 02` before XORing. open-oscar-server `wire.RoastTOCPassword` XORs the full payload with `Tic/Toc` and does not strip a prefix, so the extra bytes corrupted the cleartext and caused 980 on real-auth servers. Fixed by removing the prefix. Verified: local auth-enabled oscar-server and remote `oscar.claytonia.net:9898` both sign on with `steve/please` (`SIGN_ON:TOC2.0`).
- **UI overhaul (initial, 2026-12-02):** dark theme, sidebar sections as cards, conversations moved to tabs above chat window, message style toggle (Bubbles/Classic AIM-IRC) persisted in localStorage. Local static assets only, no build step.
- **Recent UI/fix pass (2026-12-03):** CSP `upgrade-insecure-requests` disabled for HTTP deployments; TOC status label shows Connected/Disconnected; TOC-sent IMs broadcast into SSE buffer for replay on refresh; frontend `addMessage()` dedupes by msgId/recent same-sender text to prevent duplicate display; message input is textarea with Enter-to-send/Shift+Enter newline; buddy list shows per-person outlined rows with green/red/yellow status dots and handles `presence` updates.
- **Login hardening/UX (2026-12-03):** login page includes a simple server-side math bot check (`GET /api/auth/challenge`, validated on login) and configurable server host + Web API/TOC ports (defaults prefilled from env, Claytonia-friendly). Backend auth supports per-login Web API base/TOC host+port.
- **ICQ presence shim (2026-12-03, best-effort):** `src/icq-presence.js` applies conservative TOC hints for all-digit/ICQ UINs on signon (`toc_set_idle 0`) without changing AIM flow. ICQ online/offline visibility to others may still depend on open-oscar-server behavior.
- **Web API chat unavailable on 0.25.0:** do not rely on `/chat/*` Web API endpoints on this server. TOC is the working transport for chat/invites.
- **TOC is HTTP-mixed on 9898:** normal HTTP clients get 404; TOC clients must send `FLAPON\r\n\r\n` first. Any proxy in front of 9898 must pass raw TCP.
- **No reliable all-users list:** Management API not exposed; `memberDir/search` returned empty. UI has direct "Start IM by screen name" flow.
- **npm missing earlier** - resolved (`npm 9.2.0`, deps installed).
- **Nginx config exists:** `/etc/nginx/sites-available/oscar-web` proxies `192.168.122.64` -> `127.0.0.1:3000`, SSE buffering off for `/api/events`. If not already active, run `sudo nginx -t && sudo systemctl reload nginx`.
- **App durability:** not systemd; process won't survive reboot. M5.
## Local deployment (current machine)
- **App process:** run `npm start` in `git/oscar-web` (`node --env-file=.env src/server.js`) on `127.0.0.1:3000`. If restarting, kill old process and start fresh so new TOC code loads.
- **Nginx:** `/etc/nginx/sites-available/oscar-web` -> `192.168.122.64:80` proxy to `127.0.0.1:3000`.
- **Local test server:** oscar-server 0.25.0 can run from `/home/clay/Projects/git/oscar-server/server` with `DISABLE_AUTH=true` for local smoke tests.
## Test environment (temporary)
- **Web API base:** `http://oscar.claytonia.net:8081` (HTTP). Web API auth/chat-login currently failing for temp account.
- **TOC:** `oscar.claytonia.net:9898` (TCP, FLAPON+FLAP). Reachable; auth for temp account currently `ERROR:980`.
- **Temporary test accounts:** `8520258` / `please` (ICQ-style, Web API works; TOC now also works after roast fix) and `steve` / `please` (AIM-style, confirmed Web API + TOC signon). **Do not bother real users.** Only send test IMs to `clarth` if explicitly allowed.
- **DevId/k:** Not required on tested server; `src/oscar.js` sends `k` only when `DEV_ID` is real.
## M0 findings (2026-12-02, partial)
| Probe | Result | Notes |
|---|---|---|
| `GET /?f=json` | 200 `Ok` | Envelope confirmed |
| `POST /auth/clientLogin` form `username`,`password` | 200 (earlier) / 3011 now | Temp account currently rejected |
| `GET /aim/startSession?f=json&a=<token>` | 200 | Returns aimsid, fetchTimeout, timeToNextFetch, fetchBaseURL, events |
| `GET /aim/fetchEvents?f=json&aimsid=<id>&seqNum=0` | 200 | Event shape: `{type, seqNum, timestamp, eventData}` |
| `GET /im/sendIM?f=json&aimsid=<id>&t=<target>&message=<text>` | 200 | Confirmed earlier |
| `GET /buddylist/addBuddy?f=json&aimsid=<id>&buddy=<name>&group=Buddies` | 200 | Confirmed earlier |
| Web API chat endpoints | 404 | `createAndJoinChat`, `joinChat`, `sendMessage`, `setTyping` not present on 0.25.0 |
| TOC 9898 FLAPON probe | 2a01... | FLAP signon frame received; TOC reachable |
| TOC signon 8520258/please | ERROR:980 | Same auth failure as Web API |
## Public-hardening pass (done, 2026-12-03)
- **SQLite sessions:** `better-sqlite3`-backed session store in `src/db.js` + `src/sqlite-session-store.js`; DB path configurable via `DB_PATH`.
- **Malformed DB recovery:** corrupt/unopenable DB rotated aside (`.corrupt-*`) and recreated at startup/runtime recovery paths.
- **Connection limits:** max 3 concurrent SSE connections per IP in `src/routes/stream.js`.
- **CSRF:** removed CSRF middleware per request.
- **Input validation:** added `src/validate.js`; normalized/length-limited screen names/messages; reduced RAM-abuse risk.
- **Session cleanup:** SSE disconnect schedules per-session cleanup (30s grace); periodic sweep removes expired/orphaned OSCAR sessions (no global logout).
- **Rate limiting:** removed app send limiter; kept login + general API limiter. Message rate limiting handled by OSCAR server.
- **Scale:** intentionally small/single-process deployment.
## Needs to be done next
1. **Deploy publicly behind HTTPS nginx:** `LISTEN_HOST=127.0.0.1`, `TRUST_PROXY=1`, `COOKIE_SECURE=true`, strong `SESSION_SECRET`, `.env` chmod `0600`, non-root systemd service, firewall block app port, nginx SSE buffering off for `/api/events`.
2. **UI polish follow-up:** tab close buttons, unread indicators, chat room membership/leave/invite-send UI, better mobile layout.
3. **Harden TOC client:** handle reconnect/backoff, keepalive timeout, parse CONFIG2 buddy list properly, handle TOC1/TOC2 variants, handle chat errors/room not found.
4. **Chat UX:** show chat room membership, leave button, invite-send UI, better system messages, error states.
5. **Security follow-up:** configurable login host/ports enable arbitrary server targets; consider SSRF/egress restrictions or allowlist if exposed publicly.
## Files of interest
- Plan: `planning.md`
- Handoff: `HANDOFF.md`
- TOC client: `src/toc.js`
- TOC bridge: `src/toc-session.js`
- Web API choke point: `src/oscar.js`
- Event normalization: `src/poller.js`
- Auth/session wiring: `src/routes/auth.js`, `src/sessions.js`
- Message/chat routes: `src/routes/messages.js`
- Frontend: `public/app.js`, `public/js/ui.js`, `public/js/api.js`
- Nginx: `/etc/nginx/sites-available/oscar-web`
## Quick verification performed
- `node --check` should pass for touched JS modules (syntax).
- Local TOC smoke test passed against oscar-server 0.25.0 (`DISABLE_AUTH=true`): signon, IM, chat join, chat send, invite, accept.
- Remote TOC probe: `FLAPON\r\n\r\n` -> FLAP signon frame from `oscar.claytonia.net:9898`.
- Remote temp account login still fails (Web API 3011 / TOC 980) - environment/account blocker, not code path.