From afe382e666e685c3e0a76d46c11e41f4ab3ee285 Mon Sep 17 00:00:00 2001 From: Clay Date: Wed, 2 Dec 2026 22:54:30 -0500 Subject: [PATCH] Initial oscar-web: Web API + TOC chat client --- .env.example | 20 + .gitignore | 6 + HANDOFF.md | 113 +++++ TOC-learning.md | 156 +++++++ package-lock.json | 870 +++++++++++++++++++++++++++++++++++++ package.json | 22 + planning.md | 349 +++++++++++++++ public/app.js | 386 ++++++++++++++++ public/index.html | 89 ++++ public/js/api.js | 50 +++ public/js/stream.js | 46 ++ public/js/ui.js | 153 +++++++ public/style.css | 82 ++++ src/bus.js | 12 + src/config.js | 37 ++ src/features/broadcasts.js | 26 ++ src/oscar.js | 181 ++++++++ src/poller.js | 82 ++++ src/routes/auth.js | 147 +++++++ src/routes/buddies.js | 37 ++ src/routes/messages.js | 97 +++++ src/routes/stream.js | 35 ++ src/routes/users.js | 44 ++ src/server.js | 161 +++++++ src/sessions.js | 36 ++ src/toc-session.js | 168 +++++++ src/toc.js | 358 +++++++++++++++ 27 files changed, 3763 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 HANDOFF.md create mode 100644 TOC-learning.md create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 planning.md create mode 100644 public/app.js create mode 100644 public/index.html create mode 100644 public/js/api.js create mode 100644 public/js/stream.js create mode 100644 public/js/ui.js create mode 100644 public/style.css create mode 100644 src/bus.js create mode 100644 src/config.js create mode 100644 src/features/broadcasts.js create mode 100644 src/oscar.js create mode 100644 src/poller.js create mode 100644 src/routes/auth.js create mode 100644 src/routes/buddies.js create mode 100644 src/routes/messages.js create mode 100644 src/routes/stream.js create mode 100644 src/routes/users.js create mode 100644 src/server.js create mode 100644 src/sessions.js create mode 100644 src/toc-session.js create mode 100644 src/toc.js diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..feaa1df --- /dev/null +++ b/.env.example @@ -0,0 +1,20 @@ +# .env - never commit this file. Copy to .env and fill in real values. +# Web API: your server's port. Delete the line to use the default (8081). +WEBAPI_HOST=127.0.0.1 +WEBAPI_PORT=8081 + +# TOC (Talk to OSCAR) - used for IM/chat/invites on servers without Web API chat. +# Leave unset to use Web API only. +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 +# Web API devId/key - see planning.md open question 2 / M0. +DEV_ID=your-web-api-key +# Long random string for cookie signing. +SESSION_SECRET=change-me-to-a-long-random-string diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a644e3b --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +.env +npm-debug.log* +.DS_Store +*.sqlite +*.db diff --git a/HANDOFF.md b/HANDOFF.md new file mode 100644 index 0000000..e5cc757 --- /dev/null +++ b/HANDOFF.md @@ -0,0 +1,113 @@ +# 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. TOC auth fixed (roast prefix bug); remote `steve:please` signs on to TOC successfully. Group chat/invite flow should now be testable on web UI. + +**Date:** 2026-12-02 (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`). +- **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=` | 200 | Returns aimsid, fetchTimeout, timeToNextFetch, fetchBaseURL, events | +| `GET /aim/fetchEvents?f=json&aimsid=&seqNum=0` | 200 | Event shape: `{type, seqNum, timestamp, eventData}` | +| `GET /im/sendIM?f=json&aimsid=&t=&message=` | 200 | Confirmed earlier | +| `GET /buddylist/addBuddy?f=json&aimsid=&buddy=&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 | + +## Needs to be done next + +1. **Unblock remote auth:** clear/unlock `8520258` sessions on OSCAR server; re-verify Web API and TOC login. +2. **Remote TOC e2e:** after auth fixed, test IM, chat join, invite, accept, chat send against `oscar.claytonia.net:9898` from web UI. +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. **Decide Web API vs TOC responsibility:** currently TOC preferred for IM/chat when connected; Web API still used for buddylist/presence/profile where it works. Make this explicit and test fallback. +5. **User list UX:** no management API. Keep direct screen-name open; consider caching known buddies/recent contacts locally in browser. +6. **UI polish:** show chat room membership, leave button, invite-send UI, better system messages, error states. +7. **M5:** systemd service, env file permissions, nginx/certbot review, CSP/rate-limit review. + +## 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. diff --git a/TOC-learning.md b/TOC-learning.md new file mode 100644 index 0000000..100aa10 --- /dev/null +++ b/TOC-learning.md @@ -0,0 +1,156 @@ + +TOC ("Talk to OSCAR") is a simplified, text-based way to talk to an AIM server. The original TOC server was just an OSCAR client that listened on a socket and translated between the two protocols. So instead of binary SNACs, you send and receive readable commands. Open OSCAR Server implements it itself, so the TOC listener on 9898 plays that role for you. +Wikipedia + +Everything below comes from the TOC2 spec as I remember it. I've noted where I'm sure and where you should check the repo's docs/TOC.md. + +1. The three layers +TCP: Node opens a plain socket to 9898. +FLAP framing: every message is wrapped in a 6-byte header. TCP is a stream with no message boundaries, so the header tells you where each message ends. +TOC commands: the text inside each frame, such as toc_chat_join 4 "lobby". + +Frame header (6 bytes): + +Byte(s) Meaning +0 Always * (0x2A) +1 Frame type: 1 = sign-on, 2 = data +2-3 Sequence number (16-bit, big-endian, you increment it) +4-5 Length of the body (big-endian) + +Data frames carry ASCII text ending in a null byte. Sign-on frames carry a small binary body. + +2. Logging in +Connect and send the plain text FLAPON\r\n\r\n. This is what separates a TOC client from a web browser on that port, and it's why your earlier probe got HTTP errors. +The server replies with a sign-on frame (type 1). +You reply with your own sign-on frame: version 00000001, then a TLV (tag 1, length, your screen name). +You send the command toc2_signon ... as a data frame. It carries a roasted password, a language, a client name, and a numeric code. I'm fairly sure the argument list is host port screenname roasted-password language "client name" 160 code, but verify it against docs/TOC.md. +The server answers SIGN_ON:TOC2.0, then your configuration (buddy list). +You send toc_init_done. Until you do, the server holds back events. + +Roasting is not security. It's XOR-ing the password with a fixed key, then hex-encoding it with 0x in front. The key is the string "Tic/Toc," and the password has to be roasted when connecting over FLAP. Use TLS or a trusted network, because the password is trivially reversible. +mit + +3. Sending commands + +Commands are one line of text. Arguments are space-separated, and any text with spaces goes in double quotes with a backslash before special characters. The server drops the connection if a command exceeds 2048 bytes, so cap message length. +mit + +You want to Command +Send an IM toc2_send_im "" +Add a buddy toc2_add_buddy (names are lowercase, no spaces) +Join a room toc_chat_join "" +Say something in a room toc_chat_send "" +Invite someone toc_chat_invite "" +Accept an invite toc_chat_accept +Leave a room toc_chat_leave + +toc_chat_invite is used once you're inside a room, toc_chat_accept answers an invite, and the server then replies with a CHAT_JOIN. The room id is a number the server gives you, not the room name. The spec says the exchange should currently always be 4. Open OSCAR Server has both private (4) and public (5) exchanges, so test both. +mit +mit + +4. Events you receive + +Server messages are colon-separated. The message text is the last field and can itself contain colons, so split only a fixed number of times. The room-related ones are: +apple + +CHAT_JOIN:: means you're in; remember the id. +CHAT_IN:::: is a room message. +CHAT_INVITE:::: is an invite. This is how invites arrive. +CHAT_LEFT: means you left. + +There are also IM_IN2 (incoming IM), UPDATE_BUDDY2 (buddy online/offline), CHAT_UPDATE_BUDDY (who is in a room), and ERROR. I'm less sure of their exact field layouts, so log them in Milestone 0 before relying on them. Your own chat messages come back to you as CHAT_IN, so don't add them to the screen yourself when you send. IMs are not echoed back. +mit + +5. A learning script + +This signs on and prints everything the server sends. It's an untested sketch, and the toc2_signon details are from memory. + +``` +js +// toc-demo.mjs +// Run: TOC_HOST=oscar.claytonia.net TOC_USER=you TOC_PASS=secret node toc-demo.mjs +import net from 'node:net'; + +const { TOC_HOST, TOC_USER, TOC_PASS } = process.env; +const TOC_PORT = Number(process.env.TOC_PORT ?? 9898); + +// Roasting: XOR each password byte with the repeating key 'Tic/Toc', as hex. +function roast(pw) { + const key = Buffer.from('Tic/Toc'); + const bytes = Array.from(Buffer.from(pw), (b, i) => b ^ key[i % key.length]); + return '0x' + Buffer.from(bytes).toString('hex'); +} + +// The numeric code toc2_signon wants (recalled from the spec; the server may ignore it). +function signonCode(user, pass) { + const sn = user.toLowerCase().charCodeAt(0) - 96; + const pw = pass.toLowerCase().charCodeAt(0) - 96; + const a = sn * 7696 + 738816; + return pw * a - a + sn * 746512 + 71665152; +} + +// Quote an argument: wrap in double quotes, backslash-escape special characters. +const q = (s) => '"' + s.replace(/([\\"$\[\]{}()])/g, '\\$1') + '"'; + +// ---- FLAP framing ---- +let seq = Math.floor(Math.random() * 0xffff); // we pick the starting sequence number + +function frame(type, body) { + const head = Buffer.alloc(6); + head.write('*', 0); // byte 0: always '*' + head.writeUInt8(type, 1); // byte 1: 1 = sign-on, 2 = data + head.writeUInt16BE(seq, 2); // bytes 2-3: sequence number + seq = (seq + 1) & 0xffff; // wraps at 16 bits + head.writeUInt16BE(body.length, 4); // bytes 4-5: body length + return Buffer.concat([head, body]); +} + +// Send one TOC command: text plus a null byte, inside a data frame. +const sendCmd = (text) => sock.write(frame(2, Buffer.from(text + '\0'))); + +function signonBody(name) { + const n = Buffer.from(name); + const b = Buffer.alloc(8 + n.length); + b.writeUInt32BE(1, 0); // FLAP version 1 + b.writeUInt16BE(1, 4); // TLV tag 1 = screen name + b.writeUInt16BE(n.length, 6); // TLV length + n.copy(b, 8); + return b; +} + +// ---- Connection ---- +const sock = net.connect(TOC_PORT, TOC_HOST, () => { + console.log('connected'); + sock.write('FLAPON\r\n\r\n'); // announce ourselves as a TOC client +}); + +let buf = Buffer.alloc(0); // TCP delivers arbitrary chunks, so we buffer +sock.on('data', (chunk) => { + buf = Buffer.concat([buf, chunk]); + while (buf.length >= 6) { // need a full header + const len = buf.readUInt16BE(4); + if (buf.length < 6 + len) break; // frame incomplete: wait for more data + const type = buf[1]; + const body = buf.subarray(6, 6 + len); + buf = buf.subarray(6 + len); // drop this frame from the buffer + onFrame(type, body); + } +}); + +function onFrame(type, body) { + if (type === 1) { // server sign-on frame: reply, then log in + sock.write(frame(1, signonBody(TOC_USER))); + sendCmd(`toc2_signon localhost 5190 ${TOC_USER} ${roast(TOC_PASS)} english ` + + `${q('web-oscar-chat')} 160 ${signonCode(TOC_USER, TOC_PASS)}`); + return; + } + const text = body.toString('latin1').replace(/\0$/, ''); + console.log('<<', text); + if (text.startsWith('SIGN_ON:')) sendCmd('toc_init_done'); // start receiving events +} + +sock.on('error', (e) => console.error('socket error:', e.message)); +sock.on('close', () => console.log('closed')); + +``` +To try it, run it, then message the account from Pidgin and watch IM_IN2 appear. Once that works, add sendCmd('toc_chat_join 4 "testroom"') after toc_init_done, and log what comes back. Then invite the account from Pidgin and look for CHAT_INVITE. diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..b24a7dd --- /dev/null +++ b/package-lock.json @@ -0,0 +1,870 @@ +{ + "name": "web-oscar-chat", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "web-oscar-chat", + "version": "0.1.0", + "dependencies": { + "express": "^4.21.2", + "express-rate-limit": "^7.5.0", + "express-session": "^1.18.1" + }, + "devDependencies": { + "playwright": "^1.65.2" + }, + "engines": { + "node": ">=20.19" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "node_modules/body-parser": { + "version": "1.20.9", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.9.tgz", + "integrity": "sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw==", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.16.0", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "node_modules/encodeurl": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.3.tgz", + "integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.22.3", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.3.tgz", + "integrity": "sha512-Bdcs4+3qlpVlx2NRn6fgX2Ue2/gGRaPeawebgclM0ERSCqDpA+owF1fdPwjJUTAJWMTuAaxjDf+hzb0/4eKvvw==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.5", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.13", + "proxy-addr": "~2.0.7", + "qs": "~6.16.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "7.5.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.1.tgz", + "integrity": "sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/express-session": { + "version": "1.19.0", + "resolved": "https://registry.npmjs.org/express-session/-/express-session-1.19.0.tgz", + "integrity": "sha512-0csaMkGq+vaiZTmSMMGkfdCOabYv192VbytFypcvI0MANrp+4i/7yEkJ0sbAEhycQjntaKGzYfjfXQyVb7BHMA==", + "dependencies": { + "cookie": "~0.7.2", + "cookie-signature": "~1.0.7", + "debug": "~2.6.9", + "depd": "~2.0.0", + "on-headers": "~1.1.0", + "parseurl": "~1.3.3", + "safe-buffer": "~5.2.1", + "uid-safe": "~2.1.5" + }, + "engines": { + "node": ">= 0.8.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-inspect": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.14.0.tgz", + "integrity": "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", + "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/on-headers": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz", + "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==" + }, + "node_modules/playwright": { + "version": "1.65.2", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.2.tgz", + "integrity": "sha512-Bfg9lfUnqknFzjWrvz2GMckl656TWYwDHiR+T8MQK1V+Sp1D+ODuxpcsnMQ31BYH+LBiKs6kXRMInesqO8F41w==", + "dev": true, + "dependencies": { + "playwright-core": "1.65.2" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.65.2", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.2.tgz", + "integrity": "sha512-aHu9F46Mx5ha9iiB+VLZMUUtex3PBw4am9MHptc0IXaJhz++6YXsH96eEyThwCwMkIUiB8TdZcwXqnb3xKDzmA==", + "dev": true, + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/qs": { + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.2.tgz", + "integrity": "sha512-VYdnB5S7/0IeXzBacUtwNAaM6d7Y/PgYnNC7bJCI6meqA/OgnsQbZMtVW8Dt2D1PHgbHGtYmhSoEIgvt7xZ2ZA==", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/random-bytes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz", + "integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/uid-safe": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz", + "integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==", + "dependencies": { + "random-bytes": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..e3ec8ce --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "web-oscar-chat", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Small browser chat client for Open OSCAR Server, built on the server Web API.", + "scripts": { + "start": "node --env-file=.env src/server.js", + "dev": "node --watch --env-file=.env src/server.js" + }, + "engines": { + "node": ">=20.19" + }, + "dependencies": { + "express": "^4.21.2", + "express-rate-limit": "^7.5.0", + "express-session": "^1.18.1" + }, + "devDependencies": { + "playwright": "^1.65.2" + } +} diff --git a/planning.md b/planning.md new file mode 100644 index 0000000..128cfd3 --- /dev/null +++ b/planning.md @@ -0,0 +1,349 @@ +# 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". + +## 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 +``` + +```js +// 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** + +```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** + +```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) + +```js +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`. diff --git a/public/app.js b/public/app.js new file mode 100644 index 0000000..327a95d --- /dev/null +++ b/public/app.js @@ -0,0 +1,386 @@ +// public/app.js - front-end entry point. Wires state, UI, API, and event stream. +import { api } from './js/api.js'; +import { createStream } from './js/stream.js'; +import * as ui from './js/ui.js'; + +window.addEventListener('error', (e) => { + console.error('[ui] error', e.error || e.message); + try { ui.setChatError(`UI error: ${e.message}`); } catch {} +}); +window.addEventListener('unhandledrejection', (e) => { + console.error('[ui] unhandled rejection', e.reason); + try { ui.setChatError(`UI error: ${e.reason?.message || e.reason}`); } catch {} +}); + +const state = { + screenName: null, + active: null, + conversations: {}, // key -> { key, type: 'im'|'chat', name, messages: [], roomId?, roomName? } + buddies: [], + invites: [], // { roomId, roomName, from, message, time } + selectConversation(key) { + state.active = key; + ui.renderConversations(state); + ui.renderMessages(state); + }, +}; + +const stream = createStream(); + +function convKey(type, name) { + return `${type}:${String(name).toLowerCase()}`; +} + +function ensureConversation(type, name) { + const key = convKey(type, name); + if (!state.conversations[key]) { + state.conversations[key] = { key, type, name, messages: [] }; + } + return state.conversations[key]; +} + +function addMessage(type, name, msg) { + const conv = ensureConversation(type, name); + conv.messages.push(msg); + if (!state.active) state.active = conv.key; + ui.renderConversations(state); + ui.renderMessages(state); +} + +function openIM(name) { + const conv = ensureConversation('im', name); + state.selectConversation(conv.key); +} + +function openChat(name) { + const existing = Object.values(state.conversations).find((c) => c.type === 'chat' && normalizeName(c.roomName || c.name) === normalizeName(name)); + if (existing) { state.selectConversation(existing.key); return; } + const conv = ensureConversation('chat', name); + state.selectConversation(conv.key); +} + +function plainText(s) { + if (typeof s !== 'string') return ''; + // AIM messages often arrive as HTML; render as plain text safely. + if (s.includes('<') && s.includes('>')) { + try { + const doc = new DOMParser().parseFromString(s, 'text/html'); + return (doc.body.textContent || '').trim(); + } catch { /* fall through */ } + } + return s; +} + +function normalizeName(s) { + return String(s || '').toLowerCase().replace(/\s+/g, ''); +} + +// --- Event handlers (M0 partially confirmed) --- + +function aimId(obj) { + return obj?.aimId || obj?.displayId || obj?.screenName || obj?.sender || 'unknown'; +} + +stream.on('im', (event) => { + const d = event.data || event.raw?.eventData || {}; + const from = aimId(d.source || d.sender || d); + const to = aimId(d.dest || d.target || {}); + const text = plainText(d.message || d.text || d.msg || ''); + const mine = normalizeName(from) === normalizeName(state.screenName); + const peer = mine ? (to && to !== 'unknown' ? to : from) : from; + const key = convKey('im', peer); + const conv = state.conversations[key]; + if (conv && d.msgId && conv.messages.some((m) => m.msgId && m.msgId === d.msgId)) return; + if (conv) { + const recent = conv.messages.slice(-6).some((m) => m.text === text && normalizeName(m.from) === normalizeName(from)); + if (recent) return; + } + addMessage('im', peer, { from, text, time: event.time, mine, msgId: d.msgId }); +}); + +stream.on('sentIM', (event) => { + const d = event.data || event.raw?.eventData || {}; + if (!d.iSent) return; + const to = aimId(d.dest || {}); + const text = plainText(d.message || d.text || d.msg || ''); + // Optimistic UI already added local sends; avoid obvious dup by msgId. + const conv = state.conversations[convKey('im', to)]; + if (conv && d.msgId && conv.messages.some((m) => m.msgId === d.msgId)) return; + addMessage('im', to, { from: state.screenName || 'me', text, time: event.time, mine: true, msgId: d.msgId }); +}); + +stream.on('chat', (event) => { + const d = event.data || event.raw?.eventData || {}; + const room = d.room || d.chat || d.chatId || d.exchange || 'room'; + const from = aimId(d.source || d.sender || d); + const text = plainText(d.message || d.text || d.msg || ''); + const mine = normalizeName(from) === normalizeName(state.screenName); + const key = convKey('chat', room); + const conv = state.conversations[key]; + if (conv && d.msgId && conv.messages.some((m) => m.msgId && m.msgId === d.msgId)) return; + if (conv && conv.messages.slice(-6).some((m) => m.text === text && normalizeName(m.from) === normalizeName(from))) return; + addMessage('chat', room, { from, text, time: event.time, mine, msgId: d.msgId }); +}); + +function renderInvites() { + ui.renderInvites(state.invites, async (roomId) => { + try { await api.acceptChat(roomId); } catch (err) { ui.setChatError(err.message); } + }, (roomId) => { + state.invites = state.invites.filter((i) => i.roomId !== roomId); + renderInvites(); + }); +} + +stream.on('chat_invite', (event) => { + const d = event.data || {}; + const invite = { + roomId: String(d.roomId || ''), + roomName: String(d.roomName || 'Chat room'), + from: String(d.from || 'unknown'), + message: plainText(d.message || ''), + time: event.time, + }; + state.invites.unshift(invite); + renderInvites(); + // Also surface as a system message so it's visible. + const key = convKey('im', invite.from); + addMessage('im', invite.from, { from: 'system', text: `Chat invite: "${invite.roomName}" - use Invites panel to join.`, time: event.time, mine: false, system: true }); +}); + +stream.on('chat_join', (event) => { + const d = event.data || {}; + const roomId = String(d.roomId || d.roomName || 'room'); + const roomName = String(d.roomName || d.roomId || 'Chat room'); + const key = convKey('chat', roomId); + if (!state.conversations[key]) { + state.conversations[key] = { key, type: 'chat', name: roomName, roomId, roomName, messages: [] }; + } else { + state.conversations[key].name = roomName; + state.conversations[key].roomId = roomId; + state.conversations[key].roomName = roomName; + } + // Merge any duplicate conv created by name before roomId was known. + const nameKey = convKey('chat', roomName); + if (nameKey !== key && state.conversations[nameKey]) { + const old = state.conversations[nameKey]; + const target = state.conversations[key]; + for (const m of old.messages || []) { + if (m.msgId && target.messages.some((x) => x.msgId && x.msgId === m.msgId)) continue; + if (target.messages.some((x) => x.text === m.text && x.from === m.from && x.mine === m.mine)) continue; + target.messages.push(m); + } + target.messages.sort((a, b) => (a.time || 0) - (b.time || 0)); + delete state.conversations[nameKey]; + if (state.active === nameKey) state.active = key; + } + // remove matching invite + state.invites = state.invites.filter((i) => i.roomId !== roomId); + renderInvites(); + state.selectConversation(key); +}); + +stream.on('chat_in', (event) => { + const d = event.data || {}; + const roomId = String(d.roomId || 'room'); + const from = String(d.from || 'unknown'); + const text = plainText(d.message || ''); + const mine = normalizeName(from) === normalizeName(state.screenName); + const key = convKey('chat', roomId); + if (!state.conversations[key]) state.conversations[key] = { key, type: 'chat', name: roomId, roomId, messages: [] }; + const conv = state.conversations[key]; + if (d.msgId && conv.messages.some((m) => m.msgId && m.msgId === d.msgId)) return; + if (conv.messages.slice(-6).some((m) => m.text === text && normalizeName(m.from) === normalizeName(from))) return; + addMessage('chat', roomId, { from, text, time: event.time, mine, msgId: d.msgId }); +}); + +stream.on('chat_left', (event) => { + const d = event.data || {}; + const roomId = String(d.roomId || ''); + const key = convKey('chat', roomId); + if (state.conversations[key]) { + state.conversations[key].messages.push({ from: 'system', text: 'You left the chat.', time: event.time, mine: false, system: true }); + ui.renderMessages(state); + } +}); + +stream.on('toc_status', (event) => { + const d = event.data || {}; + const detail = d.error || d.code ? String(d.error || d.code) : ''; + ui.setTocStatus(!!d.connected, detail); +}); + +stream.on('toc_error', (event) => { + const code = String(event.data?.code || ''); + if (['980', '981', '982'].includes(code)) { + console.warn('[toc]', event.data?.message || event.data?.raw); + return; // expected auth/rate-limit noise when TOC unavailable + } + const msg = event.data?.message || 'TOC error'; + ui.setChatError(msg); +}); + +stream.on('buddylist', (event) => { + const d = event.data || event.raw?.eventData || {}; + const groups = Array.isArray(d.groups) ? d.groups : []; + const buddies = groups.flatMap((g) => Array.isArray(g.buddies) ? g.buddies : []); + state.buddies = buddies; + ui.renderBuddies(state.buddies, (name) => openIM(name)); +}); + +stream.on('broadcast', (event) => { + const d = event.data || event.raw?.eventData || {}; + const text = event.text || d.message || d.text || d.msg || ''; + if (text) ui.showBroadcast(text); +}); + +// Fallback: show unknown events in console to help M0 discovery. +stream.on('*', (event) => { + if (!['im', 'chat', 'broadcast'].includes(event.type)) { + console.debug('[stream] unhandled event', event); + } +}); + +// --- UI wiring --- + +document.getElementById('loginForm').addEventListener('submit', async (e) => { + e.preventDefault(); + ui.setLoginError(''); + const screenName = document.getElementById('screenName').value.trim(); + const password = document.getElementById('password').value; + try { + await api.login(screenName, password); + await afterLogin(screenName); + } catch (err) { + ui.setLoginError(err.message); + } +}); + +document.getElementById('logoutBtn').addEventListener('click', async () => { + try { await api.logout(); } catch { /* ignore */ } + stream.close(); + state.screenName = null; + state.active = null; + state.conversations = {}; + ui.showLogin(); +}); + +document.getElementById('messageForm').addEventListener('submit', async (e) => { + e.preventDefault(); + ui.setChatError(''); + const input = document.getElementById('messageInput'); + const text = input.value.trim(); + if (!text || !state.active) return; + const conv = state.conversations[state.active]; + try { + let msgId; + if (conv.type === 'im') { + const res = await api.sendIM(conv.name, text); + msgId = res?.data?.msgId; + } else { + const res = await api.sendChat(conv.roomId || conv.name, text); + msgId = res?.data?.msgId; + } + addMessage(conv.type, conv.roomId || conv.name, { + from: state.screenName, + text, + time: Date.now(), + mine: true, + msgId, + }); + input.value = ''; + } catch (err) { + ui.setChatError(err.message); + } +}); + +document.getElementById('userSearchForm').addEventListener('submit', async (e) => { + e.preventDefault(); + ui.setChatError(''); + const q = document.getElementById('userSearch').value.trim(); + if (!q) return; + try { + const data = await api.searchUsers(q); + const users = Array.isArray(data.users) ? data.users : []; + // Always offer the exact typed name so users can open IM directly even if search is unavailable. + if (!users.map((u) => u.toLowerCase()).includes(q.toLowerCase())) users.unshift(q); + ui.renderUserResults(users, (name) => openIM(name)); + } catch (err) { + // Management API may be unreachable; still allow direct IM by screen name. + ui.renderUserResults([q], (name) => openIM(name)); + ui.setChatError(`User search unavailable (${err.message}). You can still click the name to open an IM.`); + } +}); + +document.getElementById('addBuddyForm').addEventListener('submit', async (e) => { + e.preventDefault(); + ui.setChatError(''); + const name = document.getElementById('buddyName').value.trim(); + if (!name) return; + try { + await api.addBuddy(name); + document.getElementById('buddyName').value = ''; + if (!state.buddies.some((b) => (b.aimId || b.displayId || b.screenName || b.name || b).toString().toLowerCase() === name.toLowerCase())) { + state.buddies.push({ aimId: name, displayId: name, state: 'unknown' }); + } + ui.renderBuddies(state.buddies, (name) => openIM(name)); + await loadBuddies(); + } catch (err) { + ui.setChatError(err.message); + } +}); + +document.getElementById('joinRoomForm').addEventListener('submit', async (e) => { + e.preventDefault(); + ui.setChatError(''); + const room = document.getElementById('roomName').value.trim(); + if (!room) return; + try { + await api.joinRoom(room); + openChat(room); + document.getElementById('roomName').value = ''; + } catch (err) { + ui.setChatError(err.message); + } +}); + +async function loadBuddies() { + try { + const data = await api.buddies(); + // M0: buddylist event buffer preferred; presence/get is fallback. + const groups = Array.isArray(data?.data?.groups) ? data.data.groups : []; + const users = Array.isArray(data?.data?.users) ? data.data.users : []; + const buddies = [ + ...groups.flatMap((g) => Array.isArray(g.buddies) ? g.buddies : []), + ...users, + ]; + if (buddies.length) state.buddies = buddies; + ui.renderBuddies(state.buddies, (name) => openIM(name)); + } catch (err) { + console.warn('[buddies] load failed', err.message); + } +} + +async function afterLogin(screenName) { + state.screenName = screenName; + ui.showChat(screenName); + ui.setTocStatus(false); + ui.renderConversations(state); + ui.renderMessages(state); + stream.connect(); + await loadBuddies(); +} + +async function boot() { + try { + const me = await api.me(); + if (me.loggedIn) { + await afterLogin(me.screenName); + return; + } + } catch { + // fall through to login + } + ui.showLogin(); +} + +boot(); diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..99551e6 --- /dev/null +++ b/public/index.html @@ -0,0 +1,89 @@ + + + + + + Web OSCAR Chat + + + +
+
+
Web OSCAR Chat
+ +
+ +
+ + + +
+ + + +
+
+ + + + diff --git a/public/js/api.js b/public/js/api.js new file mode 100644 index 0000000..ec6c8ab --- /dev/null +++ b/public/js/api.js @@ -0,0 +1,50 @@ +// public/js/api.js - wrappers around fetch. All network calls go here. + +async function request(path, options = {}) { + const res = await fetch(path, { + headers: { 'Content-Type': 'application/json', ...(options.headers || {}) }, + credentials: 'same-origin', + ...options, + }); + const body = await res.json().catch(() => ({})); + if (!res.ok) { + const msg = body?.error || `Request failed (${res.status})`; + throw new Error(msg); + } + return body; +} + +export const api = { + me: () => request('/api/me'), + login: (screenName, password) => request('/api/login', { + method: 'POST', + body: JSON.stringify({ screenName, password }), + }), + logout: () => request('/api/logout', { method: 'POST', body: '{}' }), + sendIM: (to, text) => request('/api/im', { + method: 'POST', + body: JSON.stringify({ to, text }), + }), + joinRoom: (room, exchange = 4) => request('/api/chat/join', { + method: 'POST', + body: JSON.stringify({ room, exchange }), + }), + sendChat: (room, text) => request('/api/chat/send', { + method: 'POST', + body: JSON.stringify({ room, text }), + }), + acceptChat: (roomId) => request('/api/chat/accept', { + method: 'POST', + body: JSON.stringify({ roomId }), + }), + leaveRoom: (room) => request('/api/chat/leave', { + method: 'POST', + body: JSON.stringify({ room }), + }), + buddies: () => request('/api/buddies'), + addBuddy: (screenName) => request('/api/buddies', { + method: 'POST', + body: JSON.stringify({ screenName }), + }), + searchUsers: (q) => request(`/api/users?q=${encodeURIComponent(q)}`), +}; diff --git a/public/js/stream.js b/public/js/stream.js new file mode 100644 index 0000000..7a051f7 --- /dev/null +++ b/public/js/stream.js @@ -0,0 +1,46 @@ +// public/js/stream.js - EventSource + event dispatch. +// EventSource reconnects by itself; we just register handlers by type. + +export function createStream() { + const handlers = new Map(); + let es = null; + + function on(type, fn) { + if (!handlers.has(type)) handlers.set(type, new Set()); + handlers.get(type).add(fn); + return () => handlers.get(type)?.delete(fn); + } + + function dispatch(event) { + const type = event?.type || 'unknown'; + const report = (err) => { + console.error('[stream] handler error', err); + try { const el = document.getElementById('chatError'); if (el) el.textContent = `UI handler error: ${err?.message || err}`; } catch {} + }; + for (const fn of handlers.get(type) || []) { + try { fn(event); } catch (err) { report(err); } + } + for (const fn of handlers.get('*') || []) { + try { fn(event); } catch (err) { report(err); } + } + } + + function connect() { + close(); + es = new EventSource('/api/events'); + es.onmessage = (e) => { + try { dispatch(JSON.parse(e.data)); } + catch (err) { console.error('[stream] bad event', err); } + }; + es.onerror = () => { + // Browser will reconnect automatically; log for visibility. + console.warn('[stream] connection error, browser will retry'); + }; + } + + function close() { + if (es) { es.close(); es = null; } + } + + return { on, connect, close }; +} diff --git a/public/js/ui.js b/public/js/ui.js new file mode 100644 index 0000000..34ee517 --- /dev/null +++ b/public/js/ui.js @@ -0,0 +1,153 @@ +// public/js/ui.js - all DOM updates. Show message text with textContent, never innerHTML. + +const el = (id) => document.getElementById(id); + +function clear(node) { + while (node.firstChild) node.removeChild(node.firstChild); +} + +function button(label, onClick, { active = false } = {}) { + const b = document.createElement('button'); + b.type = 'button'; + b.textContent = label; + if (active) b.classList.add('active'); + b.addEventListener('click', onClick); + return b; +} + +export function showLogin() { + el('loginView').classList.remove('hidden'); + el('chatView').classList.add('hidden'); + el('logoutBtn').classList.add('hidden'); + el('tocStatus').classList.add('hidden'); + el('me').textContent = ''; +} + +export function showChat(screenName) { + el('loginView').classList.add('hidden'); + el('chatView').classList.remove('hidden'); + el('logoutBtn').classList.remove('hidden'); + el('tocStatus').classList.remove('hidden'); + el('me').textContent = `Signed in as ${screenName}`; +} + +export function setLoginError(msg) { + el('loginError').textContent = msg || ''; +} + +export function setChatError(msg) { + el('chatError').textContent = msg || ''; +} + +export function showBroadcast(text) { + const banner = el('broadcastBanner'); + banner.textContent = `Broadcast: ${text}`; + banner.classList.remove('hidden'); +} + +export function renderConversations(state) { + const list = el('conversations'); + clear(list); + for (const conv of Object.values(state.conversations)) { + const li = document.createElement('li'); + const label = conv.type === 'chat' ? `# ${conv.name}` : conv.name; + li.appendChild(button(label, () => state.selectConversation(conv.key), { + active: state.active === conv.key, + })); + list.appendChild(li); + } +} + +export function renderMessages(state) { + const conv = state.conversations[state.active]; + el('chatTitle').textContent = conv ? (conv.type === 'chat' ? `# ${conv.name}` : conv.name) : 'No conversation selected'; + el('chatMeta').textContent = conv ? (conv.type === 'chat' ? 'Chat room' : 'Direct message') : ''; + + const box = el('messages'); + clear(box); + if (!conv) return; + for (const msg of conv.messages) { + const item = document.createElement('div'); + item.className = 'msg' + (msg.mine ? ' me' : ''); + + const meta = document.createElement('div'); + meta.className = 'meta'; + const when = msg.time ? new Date(msg.time).toLocaleTimeString() : ''; + meta.textContent = `${msg.from || 'unknown'}${when ? ' ยท ' + when : ''}`; + + const body = document.createElement('div'); + body.className = 'body'; + body.textContent = msg.text || ''; // XSS-safe + + item.append(meta, body); + box.appendChild(item); + } + box.scrollTop = box.scrollHeight; + const input = el('messageInput'); + if (input) input.focus(); +} + +export function renderUserResults(users, onOpen) { + const list = el('userResults'); + clear(list); + for (const name of users) { + const li = document.createElement('li'); + li.appendChild(button(name, () => onOpen(name))); + list.appendChild(li); + } +} + +export function renderBuddies(buddies, onOpen) { + const list = el('buddies'); + clear(list); + for (const b of buddies) { + const li = document.createElement('li'); + const name = typeof b === 'string' + ? b + : (b.aimId || b.displayId || b.screenName || b.name || JSON.stringify(b)); + const state = b && typeof b === 'object' && b.state ? ` (${b.state})` : ''; + li.appendChild(button(`${name}${state}`, () => onOpen(name))); + list.appendChild(li); + } +} + +export function renderInvites(invites, onAccept, onIgnore) { + const list = document.getElementById('invites'); + if (!list) return; + clear(list); + for (const inv of invites || []) { + const li = document.createElement('li'); + li.className = 'invite'; + const title = document.createElement('div'); + title.textContent = `${inv.from} invited you to "${inv.roomName}"`; + const msg = document.createElement('div'); + msg.className = 'meta'; + msg.textContent = inv.message || ''; + const actions = document.createElement('div'); + actions.className = 'invite-actions'; + const join = document.createElement('button'); + join.type = 'button'; + join.textContent = 'Join'; + join.addEventListener('click', () => onAccept && onAccept(inv.roomId)); + const ignore = document.createElement('button'); + ignore.type = 'button'; + ignore.textContent = 'Ignore'; + ignore.addEventListener('click', () => onIgnore && onIgnore(inv.roomId)); + actions.append(join, ignore); + li.append(title, msg, actions); + list.appendChild(li); + } +} + +export function setTocStatus(connected, detail = '') { + const wrap = document.getElementById('tocStatus'); + if (!wrap) return; + const dot = wrap.querySelector('.dot'); + if (dot) { + dot.classList.toggle('dot-on', !!connected); + dot.classList.toggle('dot-off', !connected); + } + const label = connected ? 'TOC connected' : 'TOC disconnected'; + wrap.title = detail ? `${label}: ${detail}` : label; + wrap.classList.remove('hidden'); +} diff --git a/public/style.css b/public/style.css new file mode 100644 index 0000000..e885981 --- /dev/null +++ b/public/style.css @@ -0,0 +1,82 @@ +:root { + --bg: #f4f1ea; + --panel: #fffdf8; + --border: #d8d0c0; + --text: #1f1b16; + --muted: #6b6257; + --accent: #0a5f59; + --accent-soft: #dcefeb; + --danger: #9b2c2c; + --shadow: 0 1px 2px rgba(0,0,0,0.04); + font-family: "IBM Plex Sans", "Segoe UI", sans-serif; + color: var(--text); + background: linear-gradient(180deg, #efe8da 0%, var(--bg) 100%); +} +* { box-sizing: border-box; } +body { margin: 0; min-height: 100vh; } +button, input { font: inherit; } +button { + cursor: pointer; border: 1px solid var(--accent); background: var(--accent); + color: white; padding: 0.45rem 0.75rem; border-radius: 6px; +} +button:hover { filter: brightness(1.05); } +input { + width: 100%; padding: 0.5rem 0.6rem; border: 1px solid var(--border); + border-radius: 6px; background: white; +} +.topbar { + display: flex; gap: 1rem; align-items: center; padding: 0.75rem 1rem; + border-bottom: 1px solid var(--border); background: rgba(255,253,248,0.9); + position: sticky; top: 0; backdrop-filter: blur(4px); +} +.brand { font-weight: 700; } +.me { margin-left: auto; color: var(--muted); font-size: 0.95rem; } +main { padding: 1rem; max-width: 1400px; margin: 0 auto; } +.panel { + background: var(--panel); border: 1px solid var(--border); + border-radius: 10px; box-shadow: var(--shadow); +} +.login-panel { max-width: 420px; margin: 4rem auto; padding: 1.25rem; } +.login-panel form { display: grid; gap: 0.75rem; } +.login-panel label { display: grid; gap: 0.3rem; font-size: 0.95rem; } +.chat-layout { display: grid; grid-template-columns: 320px 1fr; gap: 1rem; min-height: calc(100vh - 8rem); } +.sidebar { padding: 0.75rem; overflow: auto; } +.sidebar-section + .sidebar-section { margin-top: 1rem; padding-top: 1rem; border-top: 1px solid var(--border); } +.sidebar h2, .chat-header h2 { margin: 0 0 0.5rem 0; font-size: 1rem; } +.list { list-style: none; padding: 0; margin: 0.5rem 0 0 0; display: grid; gap: 0.25rem; } +.list button { + width: 100%; text-align: left; background: transparent; color: var(--text); + border: 1px solid transparent; padding: 0.4rem 0.5rem; +} +.list button:hover, .list button.active { background: var(--accent-soft); border-color: #bfd9d5; } +.inline-form { display: grid; grid-template-columns: 1fr auto; gap: 0.5rem; } +.chat-panel { display: grid; grid-template-rows: auto 1fr auto auto; min-height: 60vh; } +.chat-header { padding: 0.75rem 1rem; border-bottom: 1px solid var(--border); } +.messages { padding: 1rem; overflow: auto; display: flex; flex-direction: column; gap: 0.5rem; } +.msg { max-width: 70ch; padding: 0.5rem 0.65rem; border-radius: 8px; background: #f2ede2; } +.msg.me { align-self: flex-end; background: #dcefeb; } +.msg .meta { font-size: 0.75rem; color: var(--muted); margin-bottom: 0.15rem; } +.msg .body { white-space: pre-wrap; word-break: break-word; } +.message-form { display: grid; grid-template-columns: 1fr auto; gap: 0.5rem; padding: 0.75rem 1rem 0; border-top: 1px solid var(--border); } +.muted { color: var(--muted); font-size: 0.9rem; } +.error { color: var(--danger); min-height: 1.2em; margin: 0.5rem 1rem 0.75rem; font-size: 0.9rem; } +.banner { + margin: 0.75rem 1rem 0; padding: 0.6rem 0.75rem; background: #fff4cc; + border: 1px solid #ecd88f; border-radius: 8px; color: #5f4b00; +} +.hidden { display: none !important; } +@media (max-width: 900px) { + .chat-layout { grid-template-columns: 1fr; } + .chat-panel { min-height: 50vh; } +} + +.invite { border: 1px solid var(--border); border-radius: 8px; padding: 0.5rem; background: #fff; display: grid; gap: 0.3rem; } +.invite .meta { font-size: 0.8rem; color: var(--muted); } +.invite-actions { display: flex; gap: 0.5rem; } +.invite-actions button { padding: 0.25rem 0.5rem; font-size: 0.85rem; } + +.toc-status { display: inline-flex; align-items: center; gap: 0.35rem; margin-left: 1rem; font-size: 0.85rem; color: var(--muted); } +.dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; } +.dot-on { background: #2ecc71; box-shadow: 0 0 0 2px rgba(46,204,113,0.2); } +.dot-off { background: #e74c3c; box-shadow: 0 0 0 2px rgba(231,76,60,0.2); } +.toc-label { font-size: 0.8rem; } diff --git a/src/bus.js b/src/bus.js new file mode 100644 index 0000000..fee16aa --- /dev/null +++ b/src/bus.js @@ -0,0 +1,12 @@ +// src/bus.js - tiny event bus: poller publishes, features subscribe. +// The poller does not know about features. It publishes each Web API event by +// type, and any feature subscribes with bus.on('chat.message', handler). + +import { EventEmitter } from 'node:events'; + +export const bus = new EventEmitter(); + +// Avoid crashing the process on an unhandled 'error' event. +bus.on('error', (err) => { + console.error('[bus] error:', err); +}); diff --git a/src/config.js b/src/config.js new file mode 100644 index 0000000..c2067bd --- /dev/null +++ b/src/config.js @@ -0,0 +1,37 @@ +// 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; +const required = (name) => { + const value = process.env[name]; + if (!value) throw new Error(`${name} is required (set it in .env)`); + return value; +}; + +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)}`; +export const PORT = port('PORT', 3000); +export const DEV_ID = () => required('DEV_ID'); +export const SESSION_SECRET = () => required('SESSION_SECRET'); + +// Bind address for this app. Default localhost; set 0.0.0.0 only behind nginx. +export const LISTEN_HOST = host('LISTEN_HOST', '127.0.0.1'); + +export function logStartupConfig() { + // Never log DEV_ID or SESSION_SECRET. + 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/features/broadcasts.js b/src/features/broadcasts.js new file mode 100644 index 0000000..e608b7f --- /dev/null +++ b/src/features/broadcasts.js @@ -0,0 +1,26 @@ +// src/features/broadcasts.js - turns broadcast events into a UI message. +// TODO(M0): determine how broadcasts arrive. If they are IMs from a system +// screen name, recognize that sender here. If a dedicated event type, subscribe +// to it. + +const BROADCAST_SENDERS = new Set(['system', 'admin', 'aolsystemmsg']); + +export function register(ctx) { + const { bus, broadcast } = ctx; + + // Heuristic: treat IM-like events from known system senders as broadcasts. + bus.on('*', ({ rec, event }) => { + const raw = event.raw || {}; + const from = String(raw.from || raw.sender || raw.screenName || '').toLowerCase(); + if (!from) return; + if (BROADCAST_SENDERS.has(from) || raw.broadcast === true || event.type === 'broadcast') { + broadcast(rec, { + type: 'broadcast', + time: Date.now(), + from: raw.from || raw.sender || raw.screenName || 'system', + text: raw.text || raw.message || raw.msg || '', + raw, + }); + } + }); +} diff --git a/src/oscar.js b/src/oscar.js new file mode 100644 index 0000000..5da6252 --- /dev/null +++ b/src/oscar.js @@ -0,0 +1,181 @@ +// 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. +// +// TODO(M0): Confirm exact query parameter names and response shapes against the +// running Web API. The plan guesses classic Web AIM names: k, a, aimsid, t, +// message, f=json. Verify with curl before relying on this in production. + +import { WEBAPI_BASE, MANAGEMENT_BASE, DEV_ID } from './config.js'; + +export class OscarApiError extends Error { + constructor(message, { statusCode, statusText, path, body } = {}) { + super(message); + this.name = 'OscarApiError'; + this.statusCode = statusCode; + this.statusText = statusText; + this.path = path; + this.body = body; + } +} + +function redactParams(params) { + const redacted = { ...params }; + for (const key of ['a', 'password', 'pwd', 'pass']) { + if (key in redacted) redacted[key] = '[redacted]'; + } + return redacted; +} + +// Call a Web API endpoint and unwrap the { response: { statusCode, statusText, data } } envelope. +async function call(path, params = {}, { base = WEBAPI_BASE, method = 'GET', formBody = null } = {}) { + const url = new URL(path, base); + url.search = new URLSearchParams({ f: 'json', ...params }).toString(); + + const opts = { method }; + if (formBody) { + opts.headers = { 'Content-Type': 'application/x-www-form-urlencoded' }; + opts.body = new URLSearchParams(formBody).toString(); + } + + let res; + try { + res = await fetch(url, opts); + } catch (err) { + throw new OscarApiError(`Web API request failed: ${err.message}`, { path }); + } + + let body; + try { + body = await res.json(); + } catch { + throw new OscarApiError(`Web API returned non-JSON for ${path}`, { + path, + statusCode: res.status, + }); + } + + const response = body?.response; + if (!response) { + throw new OscarApiError(`Unexpected Web API response shape for ${path}`, { path, body }); + } + if (response.statusCode !== 200) { + throw new OscarApiError(response.statusText || `Web API error ${response.statusCode}`, { + statusCode: response.statusCode, + statusText: response.statusText, + path, + body, + }); + } + return response.data; +} + +// --- Auth / session --- + +export async function clientLogin(screenName, password) { + // M0 partial: POST /auth/clientLogin accepts form-encoded username/password. + // TODO(M0): confirm whether k/devId is required and its param name. + const params = {}; + const devId = process.env.DEV_ID; + if (devId && devId !== 'your-web-api-key') params.k = devId; + return call('/auth/clientLogin', params, { + method: 'POST', + formBody: { username: screenName, password }, + }); +} + +export async function startSession(token, { events = [] } = {}) { + // TODO(M0): confirm param names and how event subscriptions are requested. + const params = { a: token }; + if (events.length) params.events = events.join(','); + return call('/aim/startSession', params); +} + +export async function fetchEvents(aimsid, seqNum, { timeout = 25000 } = {}) { + // TODO(M0): confirm timeout units/param name and seqNum semantics. + return call('/aim/fetchEvents', { + aimsid, + seqNum, + timeout, + }); +} + +export async function endSession(aimsid) { + return call('/aim/endSession', { aimsid }); +} + +// --- IM --- + +export async function sendIM(aimsid, to, message) { + // TODO(M0): confirm param names (t/target, message/msg). + return call('/im/sendIM', { aimsid, t: to, message }); +} + +export async function setTyping(aimsid, to, typingStatus = 'typing') { + // TODO(M0): confirm typingStatus values. + return call('/im/setTyping', { aimsid, t: to, typingStatus }); +} + +// --- Chat --- + +export async function createAndJoinChat(aimsid, room) { + // TODO(M0): confirm param name for room/exchange. + return call('/chat/createAndJoinChat', { aimsid, room }); +} + +export async function sendChatMessage(aimsid, chatId, message) { + // TODO(M0): confirm chat id param name. + return call('/chat/sendMessage', { aimsid, c: chatId, message }); +} + +export async function leaveChat(aimsid, chatId) { + return call('/chat/leaveChat', { aimsid, c: chatId }); +} + +export async function setChatTyping(aimsid, chatId, typingStatus = 'typing') { + return call('/chat/setTyping', { aimsid, c: chatId, typingStatus }); +} + +// --- Presence / buddy list --- + +export async function getPresence(aimsid) { + return call('/presence/get', { aimsid }); +} + +export async function addBuddy(aimsid, screenName, { group = 'Buddies' } = {}) { + // TODO(M0): confirm param names and group behavior. + return call('/buddylist/addBuddy', { aimsid, buddy: screenName, group }); +} + +// --- Management API (localhost only, unauthenticated) --- + +export async function listUsers() { + // TODO(M0): confirm Management API path/shape for user listing. + const url = new URL('/user', MANAGEMENT_BASE); + const res = await fetch(url); + if (!res.ok) { + throw new Error(`Management API /user failed: ${res.status}`); + } + return res.json(); +} + +export async function listPublicRooms() { + // TODO(M0): confirm Management API path/shape for public rooms. + const url = new URL('/chat/room/public', MANAGEMENT_BASE); + const res = await fetch(url); + if (!res.ok) { + throw new Error(`Management API /chat/room/public failed: ${res.status}`); + } + return res.json(); +} + +// Startup health check - makes a cheap request so a wrong port fails clearly. +// We intentionally do not log secrets. +export async function healthCheck() { + const url = new URL('/', WEBAPI_BASE); + try { + const res = await fetch(url); + console.log(`[startup] Web API reachable at ${WEBAPI_BASE} (HTTP ${res.status})`); + } catch (err) { + console.warn(`[startup] WARNING: Web API not reachable at ${WEBAPI_BASE}: ${err.message}`); + } +} diff --git a/src/poller.js b/src/poller.js new file mode 100644 index 0000000..2da496d --- /dev/null +++ b/src/poller.js @@ -0,0 +1,82 @@ +// src/poller.js - one long-poll loop per logged-in user. +// 'async' functions can pause with 'await' without blocking other users. + +import * as oscar from './oscar.js'; +import { bus } from './bus.js'; + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +function sseSend(client, event) { + // SSE format: one "data:" line per payload line, blank line terminates event. + client.write(`data: ${JSON.stringify(event)}\n\n`); +} + +const EVENT_BUFFER_MAX = 200; + +export function broadcast(rec, event) { + if (!Array.isArray(rec.eventBuffer)) rec.eventBuffer = []; + rec.eventBuffer.push(event); + if (rec.eventBuffer.length > EVENT_BUFFER_MAX) { + rec.eventBuffer.splice(0, rec.eventBuffer.length - EVENT_BUFFER_MAX); + } + for (const client of rec.sseClients) { + try { + sseSend(client, event); + } catch (err) { + console.error('[sse] write failed:', err.message); + rec.sseClients.delete(client); + } + } +} + +// M0 confirmed fetchEvents event shape: { type, seqNum, timestamp, eventData }. +// Normalize to a stable internal shape while keeping raw/eventData for debugging. +function normalizeEvent(raw) { + const type = String(raw?.type || raw?.eventType || raw?.event || 'unknown'); + const data = raw?.eventData && typeof raw.eventData === 'object' ? raw.eventData : raw?.data || {}; + return { + type, + time: typeof raw?.timestamp === 'number' ? raw.timestamp * 1000 : Date.now(), + seqNum: raw?.seqNum, + data, + raw, + }; +} + +export async function runPoller(rec) { + rec.polling = true; + console.log(`[poller] started for ${rec.screenName}`); + + while (rec.polling) { + try { + const data = await oscar.fetchEvents(rec.aimsid, rec.seqNum); + + // TODO(M0): confirm field names: lastSeqNum, events, fetchBaseURL. + if (typeof data?.lastSeqNum === 'number') { + rec.seqNum = data.lastSeqNum; + } + if (data?.fetchBaseURL) { + rec.fetchBaseURL = data.fetchBaseURL; + // Intentionally ignored for actual requests; see planning.md 5.1. + } + + const events = Array.isArray(data?.events) ? data.events : []; + for (const raw of events) { + const event = normalizeEvent(raw); + console.log(`[poller] ${rec.screenName} event type=${event.type} seq=${event.seqNum} sseClients=${rec.sseClients.size}`); + if (!['myInfo', 'presence', 'buddylist'].includes(event.type)) { + console.log(`[poller] event detail: ${JSON.stringify(event).slice(0, 2000)}`); + } + bus.emit(event.type, { rec, event }); + bus.emit('*', { rec, event }); + broadcast(rec, event); + } + } catch (err) { + if (!rec.polling) break; // logout/endSession can cause expected errors + console.error(`[poller] ${rec.screenName} poll failed:`, err.message); + await sleep(2000); // back off, then try again + } + } + + console.log(`[poller] stopped for ${rec.screenName}`); +} diff --git a/src/routes/auth.js b/src/routes/auth.js new file mode 100644 index 0000000..a81bbbe --- /dev/null +++ b/src/routes/auth.js @@ -0,0 +1,147 @@ +import { Router } from 'express'; +import * as oscar from '../oscar.js'; +import * as sessions from '../sessions.js'; +import { runPoller } from '../poller.js'; +import { startTOCSession, stopTOCSession } from '../toc-session.js'; + +export const authRouter = Router(); + +function sanitizeScreenName(value) { + return String(value || '').trim(); +} + +export function requireLogin(req, res, next) { + const rec = sessions.getSession(req.session?.id); + if (!rec) return res.status(401).json({ error: 'Not logged in' }); + req.oscar = rec; + next(); +} + +async function endOscarSession(rec, sessionId) { + rec.polling = false; + stopTOCSession(rec); + for (const client of rec.sseClients) { + try { client.end(); } catch { /* ignore */ } + } + rec.sseClients.clear(); + sessions.deleteSession(sessionId); + if (rec.aimsid) { + try { + await oscar.endSession(rec.aimsid); + } catch (err) { + console.warn(`[logout] endSession failed for ${rec.screenName}:`, err.message); + } + } +} + +export async function logoutSession(req) { + const rec = sessions.getSession(req.session?.id); + if (rec) await endOscarSession(rec, req.session.id); + await new Promise((resolve) => req.session.destroy(() => resolve())); +} + +authRouter.post('/login', async (req, res) => { + const screenName = sanitizeScreenName(req.body?.screenName); + const password = String(req.body?.password || ''); + + if (!screenName || !password) { + return res.status(400).json({ error: 'screenName and password are required' }); + } + + // If this browser session already has an OSCAR session, clean it up first. + const existing = sessions.getSession(req.session.id); + if (existing) await endOscarSession(existing, req.session.id); + // Avoid duplicate OSCAR sessions for the same screen name. + const byName = sessions.getSessionByScreenName(screenName); + if (byName) await endOscarSession(byName, byName.sessionId); + + // Regenerate session on login to avoid session fixation. + await new Promise((resolve, reject) => { + req.session.regenerate((err) => (err ? reject(err) : resolve())); + }); + + const tocHost = process.env.TOC_HOST; + const tocPort = Number(process.env.TOC_PORT || 9898); + let webErr = null; + let tocErr = null; + let rec = null; + + // Try Web API login (buddy list/presence/profile) when configured. + if (process.env.WEBAPI_HOST) { + try { + const loginData = await oscar.clientLogin(screenName, password); + let token = loginData?.token || loginData?.a || loginData?.loginCookie; + if (token && typeof token === 'object') token = token.a || token.token || token.loginCookie; + if (typeof token !== 'string' || !token) throw new Error('no token in login response'); + const startData = await oscar.startSession(token); + const aimsid = startData?.aimsid; + if (!aimsid) throw new Error('startSession returned no aimsid'); + rec = { + sessionId: req.session.id, + screenName, + token, + aimsid, + seqNum: typeof startData?.lastSeqNum === 'number' ? startData.lastSeqNum : -1, + sseClients: new Set(), + polling: false, + fetchBaseURL: startData?.fetchBaseURL, + eventBuffer: [], + }; + } catch (err) { + webErr = err; + console.warn('[login] webapi failed:', err.message); + } + } + + // Try TOC login for IM/chat/invites (works where Web API chat is unavailable). + if (tocHost) { + try { + if (!rec) { + rec = { + sessionId: req.session.id, + screenName, + token: null, + aimsid: null, + seqNum: -1, + sseClients: new Set(), + polling: false, + eventBuffer: [], + }; + } + await startTOCSession(rec, { host: tocHost, port: tocPort, password }); + } catch (err) { + tocErr = err; + console.warn('[login] toc failed:', err.message); + if (!rec?.aimsid) rec = null; // no usable session + } + } + + if (!rec) { + console.error('[login] failed:', webErr?.message || tocErr?.message); + const status = (webErr?.statusCode === 401 || webErr?.statusCode === 403) ? 401 : 502; + return res.status(status).json({ error: 'Login failed. Check screen name/password and server status.' }); + } + + sessions.setSession(req.session.id, rec); + req.session.screenName = screenName; + + if (rec.aimsid) { + runPoller(rec).catch((err) => { + console.error(`[poller] crashed for ${screenName}:`, err); + rec.polling = false; + }); + } + + return res.json({ ok: true, screenName, transport: { webapi: !!rec.aimsid, toc: !!rec.tocConnected } }); +}); + +authRouter.post('/logout', requireLogin, async (req, res) => { + await logoutSession(req); + res.json({ ok: true }); +}); + +authRouter.get('/me', (req, res) => { + const rec = sessions.getSession(req.session?.id); + if (!rec) return res.status(401).json({ loggedIn: false }); + res.json({ loggedIn: true, screenName: rec.screenName }); +}); diff --git a/src/routes/buddies.js b/src/routes/buddies.js new file mode 100644 index 0000000..2a3d8a9 --- /dev/null +++ b/src/routes/buddies.js @@ -0,0 +1,37 @@ +import { Router } from 'express'; +import * as oscar from '../oscar.js'; +import { requireLogin } from './auth.js'; + +export const buddiesRouter = Router(); + +buddiesRouter.get('/buddies', requireLogin, async (req, res) => { + try { + // M0: presence/get returns {groups:[],users:[]} but buddylist comes via + // fetchEvents/startSession. Prefer latest buddylist event from buffer. + const rec = req.oscar; + const buf = Array.isArray(rec.eventBuffer) ? rec.eventBuffer : []; + for (let i = buf.length - 1; i >= 0; i--) { + if (buf[i].type === 'buddylist') { + return res.json({ ok: true, data: buf[i].data || {}, source: 'buddylist-event' }); + } + } + const data = await oscar.getPresence(req.oscar.aimsid); + res.json({ ok: true, data, source: 'presence' }); + } catch (err) { + console.error('[buddies] list failed:', err.message); + res.status(502).json({ error: 'Failed to get buddies/presence' }); + } +}); + +buddiesRouter.post('/buddies', requireLogin, async (req, res) => { + const screenName = String(req.body?.screenName || '').trim().slice(0, 64); + if (!screenName) return res.status(400).json({ error: 'screenName is required' }); + + try { + const data = await oscar.addBuddy(req.oscar.aimsid, screenName); + res.json({ ok: true, data }); + } catch (err) { + console.error('[buddies] add failed:', err.message); + res.status(502).json({ error: 'Failed to add buddy' }); + } +}); diff --git a/src/routes/messages.js b/src/routes/messages.js new file mode 100644 index 0000000..954ced0 --- /dev/null +++ b/src/routes/messages.js @@ -0,0 +1,97 @@ +import { Router } from 'express'; +import * as oscar from '../oscar.js'; +import { requireLogin } from './auth.js'; + +export const messagesRouter = Router(); + +function text(value, max = 2000) { + const s = String(value ?? '').trim(); + if (!s) return null; + return s.slice(0, max); +} + +messagesRouter.post('/im', requireLogin, async (req, res) => { + const to = text(req.body?.to, 64); + const message = text(req.body?.text, 2000); + if (!to || !message) return res.status(400).json({ error: 'to and text are required' }); + + try { + if (req.oscar.tocConnected && req.oscar.toc) { + req.oscar.toc.sendIM(to, message); + return res.json({ ok: true, transport: 'toc' }); + } + const data = await oscar.sendIM(req.oscar.aimsid, to, message); + res.json({ ok: true, data, transport: 'webapi' }); + } catch (err) { + console.error('[im] send failed:', err.message); + res.status(502).json({ error: 'Failed to send IM' }); + } +}); + +messagesRouter.post('/chat/join', requireLogin, async (req, res) => { + const room = text(req.body?.room, 128); + const exchange = Number(req.body?.exchange ?? 4); + if (!room) return res.status(400).json({ error: 'room is required' }); + + try { + if (req.oscar.tocConnected && req.oscar.toc) { + req.oscar.toc.chatJoin(exchange, room); + return res.json({ ok: true, transport: 'toc', note: 'CHAT_JOIN event will arrive via SSE' }); + } + const data = await oscar.createAndJoinChat(req.oscar.aimsid, room); + res.json({ ok: true, data, transport: 'webapi' }); + } catch (err) { + console.error('[chat] join failed:', err.message); + res.status(502).json({ error: 'Failed to join chat' }); + } +}); + +messagesRouter.post('/chat/accept', requireLogin, async (req, res) => { + const roomId = text(req.body?.roomId, 128); + if (!roomId) return res.status(400).json({ error: 'roomId is required' }); + try { + if (req.oscar.tocConnected && req.oscar.toc) { + req.oscar.toc.chatAccept(roomId); + return res.json({ ok: true, transport: 'toc' }); + } + return res.status(501).json({ error: 'Chat accept not available on Web API transport' }); + } catch (err) { + console.error('[chat] accept failed:', err.message); + res.status(502).json({ error: 'Failed to accept chat invite' }); + } +}); + +messagesRouter.post('/chat/send', requireLogin, async (req, res) => { + const room = text(req.body?.room, 128); // TOC: roomId; Web API: room name + const message = text(req.body?.text, 2000); + if (!room || !message) return res.status(400).json({ error: 'room and text are required' }); + + try { + if (req.oscar.tocConnected && req.oscar.toc) { + req.oscar.toc.chatSend(room, message); + return res.json({ ok: true, transport: 'toc' }); + } + const data = await oscar.sendChatMessage(req.oscar.aimsid, room, message); + res.json({ ok: true, data, transport: 'webapi' }); + } catch (err) { + console.error('[chat] send failed:', err.message); + res.status(502).json({ error: 'Failed to send chat message' }); + } +}); + +messagesRouter.post('/chat/leave', requireLogin, async (req, res) => { + const room = text(req.body?.room, 128); // TOC: roomId + if (!room) return res.status(400).json({ error: 'room is required' }); + + try { + if (req.oscar.tocConnected && req.oscar.toc) { + req.oscar.toc.chatLeave(room); + return res.json({ ok: true, transport: 'toc' }); + } + await oscar.leaveChat(req.oscar.aimsid, room); + res.json({ ok: true, transport: 'webapi' }); + } catch (err) { + console.error('[chat] leave failed:', err.message); + res.status(502).json({ error: 'Failed to leave chat' }); + } +}); diff --git a/src/routes/stream.js b/src/routes/stream.js new file mode 100644 index 0000000..c72c0af --- /dev/null +++ b/src/routes/stream.js @@ -0,0 +1,35 @@ +import { Router } from 'express'; +import { requireLogin } from './auth.js'; + +export const streamRouter = Router(); + +streamRouter.get('/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', + 'X-Accel-Buffering': 'no', // nginx: do not buffer SSE + }); + res.flushHeaders(); + res.write(': connected\n\n'); // SSE comment to establish stream + + const rec = req.oscar; + rec.sseClients.add(res); // poller writes to everything in here + console.log(`[sse] client connected for ${rec.screenName}, total=${rec.sseClients.size}, replay=${rec.eventBuffer?.length || 0}`); + + // Replay recent events so clients that connect after poller startup don't miss them. + if (Array.isArray(rec.eventBuffer)) { + for (const event of rec.eventBuffer) { + try { res.write(`data: ${JSON.stringify(event)}\n\n`); } catch { break; } + } + } + + const heartbeat = setInterval(() => { + try { res.write(': ping\n\n'); } catch { /* ignore */ } + }, 30000); + + req.on('close', () => { + clearInterval(heartbeat); + rec.sseClients.delete(res); // tab closed, stop sending + }); +}); diff --git a/src/routes/users.js b/src/routes/users.js new file mode 100644 index 0000000..a906d93 --- /dev/null +++ b/src/routes/users.js @@ -0,0 +1,44 @@ +import { Router } from 'express'; +import * as oscar from '../oscar.js'; +import { requireLogin } from './auth.js'; + +export const usersRouter = Router(); + +let cache = { at: 0, names: [] }; +const CACHE_MS = 60_000; + +function extractScreenNames(data) { + // TODO(M0): confirm Management API /user response shape. + // Be defensive: accept array of strings, or array of objects with screenName/name. + const list = Array.isArray(data) ? data : Array.isArray(data?.users) ? data.users : []; + const names = []; + for (const item of list) { + if (typeof item === 'string') names.push(item); + else if (item && typeof item === 'object') { + const name = item.screenName || item.screenname || item.name || item.username; + if (typeof name === 'string' && name.trim()) names.push(name.trim()); + } + } + return [...new Set(names)]; +} + +async function getUserNames() { + if (Date.now() - cache.at < CACHE_MS) return cache.names; + const data = await oscar.listUsers(); + cache = { at: Date.now(), names: extractScreenNames(data) }; + return cache.names; +} + +usersRouter.get('/users', requireLogin, async (req, res) => { + const q = String(req.query?.q || '').trim().toLowerCase(); + try { + const names = await getUserNames(); + const filtered = (q ? names.filter((n) => n.toLowerCase().includes(q)) : names) + .slice(0, 20); + // Only screen names leave the server. + res.json({ ok: true, users: filtered }); + } catch (err) { + console.error('[users] search failed:', err.message); + res.status(502).json({ error: 'Failed to search users' }); + } +}); diff --git a/src/server.js b/src/server.js new file mode 100644 index 0000000..ccb96d7 --- /dev/null +++ b/src/server.js @@ -0,0 +1,161 @@ +// src/server.js - starts Express, wires everything together. +import express from 'express'; +import session from 'express-session'; +import rateLimit from 'express-rate-limit'; +import { readdir } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +import { PORT, LISTEN_HOST, SESSION_SECRET, logStartupConfig } from './config.js'; +import * as oscar from './oscar.js'; +import { bus } from './bus.js'; +import { broadcast } from './poller.js'; +import { authRouter, requireLogin } from './routes/auth.js'; +import { streamRouter } from './routes/stream.js'; +import { messagesRouter } from './routes/messages.js'; +import { buddiesRouter } from './routes/buddies.js'; +import { usersRouter } from './routes/users.js'; +import * as sessionsStore from './sessions.js'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const publicDir = path.resolve(__dirname, '../public'); + +const app = express(); +app.set('trust proxy', 1); // behind nginx +app.disable('x-powered-by'); + +app.use(express.json({ limit: '32kb' })); + +// CSRF-lite: for POSTs, require JSON content-type and verify Origin when present. +app.use((req, res, next) => { + if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) return next(); + const ct = String(req.headers['content-type'] || ''); + if (!ct.includes('application/json')) { + return res.status(415).json({ error: 'Content-Type must be application/json' }); + } + const origin = req.headers.origin; + if (origin) { + const host = req.headers.host; + let ok = false; + try { ok = new URL(origin).host === host; } catch { ok = false; } + if (!ok) return res.status(403).json({ error: 'Invalid Origin' }); + } + next(); +}); + +app.use(session({ + name: 'oscar.sid', + secret: SESSION_SECRET(), + resave: false, + saveUninitialized: false, + cookie: { + httpOnly: true, + sameSite: 'lax', + secure: 'auto', // set true behind HTTPS proxy via trust proxy + }, +})); + +const loginLimiter = rateLimit({ + windowMs: 15 * 60 * 1000, + limit: 30, + standardHeaders: 'draft-7', + legacyHeaders: false, + message: { error: 'Too many login attempts, try again later.' }, +}); +app.use('/api/login', loginLimiter); + +app.get('/api/health', (_req, res) => res.json({ ok: true })); + +app.use('/api', authRouter); +app.use('/api', streamRouter); +app.use('/api', messagesRouter); +app.use('/api', buddiesRouter); +app.use('/api', usersRouter); + +app.use(express.static(publicDir, { + setHeaders(res, filePath) { + if (filePath.endsWith('.js') || filePath.endsWith('.css') || filePath.endsWith('.html')) { + res.setHeader('Cache-Control', 'no-store'); + } + }, +})); + +// SPA-ish fallback: serve index.html for unknown non-API paths. +app.get('*', (req, res, next) => { + if (req.path.startsWith('/api/')) return next(); + res.sendFile(path.join(publicDir, 'index.html')); +}); + +app.use((err, _req, res, _next) => { + console.error('[express] unhandled error:', err); + res.status(500).json({ error: 'Internal server error' }); +}); + +async function loadFeatures() { + const featuresDir = path.resolve(__dirname, 'features'); + let entries = []; + try { + entries = await readdir(featuresDir); + } catch { + return; + } + + const ctx = { + app, + bus, + oscar, + sessions: sessionsStore, + broadcast, + requireLogin, + }; + + for (const file of entries.filter((f) => f.endsWith('.js')).sort()) { + const full = path.join(featuresDir, file); + const mod = await import(pathToFileURL(full).href); + if (typeof mod.register === 'function') { + mod.register(ctx); + console.log(`[features] loaded ${file}`); + } + } +} + +let shuttingDown = false; + +async function shutdown(signal) { + if (shuttingDown) return; + shuttingDown = true; + console.log(`[shutdown] received ${signal}, ending OSCAR sessions...`); + const tasks = []; + for (const rec of sessionsStore.allSessions()) { + rec.polling = false; + for (const client of rec.sseClients) { + try { client.end(); } catch { /* ignore */ } + } + rec.sseClients.clear(); + tasks.push( + oscar.endSession(rec.aimsid) + .catch((err) => console.warn(`[shutdown] endSession failed for ${rec.screenName}:`, err.message)) + ); + } + await Promise.allSettled(tasks); + console.log('[shutdown] done'); + process.exit(0); +} + +process.on('SIGINT', () => { void shutdown('SIGINT'); }); +process.on('SIGTERM', () => { void shutdown('SIGTERM'); }); + +async function main() { + logStartupConfig(); + await oscar.healthCheck(); + await loadFeatures(); + + app.listen(PORT, LISTEN_HOST, () => { + console.log(`[server] listening on http://${LISTEN_HOST}:${PORT}`); + }); +} + +main().catch((err) => { + console.error('[startup] fatal:', err); + process.exit(1); +}); diff --git a/src/sessions.js b/src/sessions.js new file mode 100644 index 0000000..3516ebb --- /dev/null +++ b/src/sessions.js @@ -0,0 +1,36 @@ +// 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: +// { +// sessionId, screenName, token, aimsid, seqNum, +// sseClients: Set, +// polling: boolean, +// fetchBaseURL?: string, +// } + +const sessions = new Map(); + +export function getSession(sessionId) { + return sessions.get(sessionId); +} + +export function setSession(sessionId, record) { + sessions.set(sessionId, record); +} + +export function deleteSession(sessionId) { + sessions.delete(sessionId); +} + +export function allSessions() { + return sessions.values(); +} + +export function getSessionByScreenName(screenName) { + const target = screenName.toLowerCase(); + for (const rec of sessions.values()) { + if (rec.screenName.toLowerCase() === target) return rec; + } + return null; +} diff --git a/src/toc-session.js b/src/toc-session.js new file mode 100644 index 0000000..24b1bd2 --- /dev/null +++ b/src/toc-session.js @@ -0,0 +1,168 @@ +// 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. + +import { TOCClient } from './toc.js'; +import { bus } from './bus.js'; +import { broadcast } from './poller.js'; + +function normalize(sn) { + return String(sn || '').toLowerCase().replace(/\s+/g, ''); +} + +function makeEvent(type, data) { + return { type, time: Date.now(), data, raw: { type, eventData: data } }; +} + +export async function startTOCSession(rec, { host, port, password }) { + const toc = new TOCClient({ + host, + port, + screenName: rec.screenName, + password, + logger: console, + }); + rec.toc = toc; + rec.tocConnected = false; + + let lastError = ''; + toc.on('signon', () => { + rec.tocConnected = true; + lastError = ''; + console.log(`[toc] signed on ${rec.screenName}`); + broadcast(rec, makeEvent('toc_status', { connected: true })); + }); + + toc.on('close', () => { + const was = rec.tocConnected; + rec.tocConnected = false; + console.log(`[toc] closed ${rec.screenName}`); + broadcast(rec, makeEvent('toc_status', { connected: false, error: lastError || undefined })); + }); + + toc.on('error', (err) => { + console.error(`[toc] ${rec.screenName} error:`, err.message); + }); + + toc.on('toc-error', ({ raw }) => { + console.warn(`[toc] ${rec.screenName} toc-error: ${raw}`); + const code = String(raw || '').match(/ERROR:(\d+)/)?.[1]; + const friendly = { + '980': 'TOC login failed: incorrect screen name or password. All-digit ICQ/UIN names may not work over TOC; try an AIM-style name for group chat.', + '981': 'TOC login failed: auth error.', + '982': 'TOC login failed: too many login attempts / rate limited.', + '983': 'TOC signon temporarily unavailable.', + }[code] || `TOC error: ${raw}`; + lastError = code ? `ERROR ${code}` : raw; + broadcast(rec, makeEvent('toc_error', { message: friendly, raw, code })); + broadcast(rec, makeEvent('toc_status', { connected: false, error: lastError, code })); + }); + + toc.on('im', ({ from, auto, message }) => { + const event = makeEvent('im', { + from, + to: rec.screenName, + message, + auto, + msgId: `toc-${Date.now()}-${Math.random().toString(36).slice(2)}`, + }); + console.log(`[toc] im from=${from} to=${rec.screenName}`); + bus.emit(event.type, { rec, event }); + bus.emit('*', { rec, event }); + broadcast(rec, event); + }); + + toc.on('chat-invite', ({ roomName, roomId, from, message }) => { + const event = makeEvent('chat_invite', { roomName, roomId, from, message }); + console.log(`[toc] chat-invite room=${roomId} from=${from}`); + bus.emit(event.type, { rec, event }); + bus.emit('*', { rec, event }); + broadcast(rec, event); + }); + + toc.on('chat-join', ({ roomId, roomName }) => { + const event = makeEvent('chat_join', { roomId, roomName }); + console.log(`[toc] chat-join room=${roomId} name=${roomName}`); + bus.emit(event.type, { rec, event }); + bus.emit('*', { rec, event }); + broadcast(rec, event); + }); + + toc.on('chat-in', ({ roomId, from, whisper, message }) => { + const event = makeEvent('chat_in', { roomId, from, whisper, message }); + console.log(`[toc] chat-in room=${roomId} from=${from}`); + bus.emit(event.type, { rec, event }); + bus.emit('*', { rec, event }); + broadcast(rec, event); + }); + + toc.on('chat-update-buddy', ({ roomId, inside, users }) => { + const event = makeEvent('chat_update', { roomId, inside, users }); + bus.emit(event.type, { rec, event }); + bus.emit('*', { rec, event }); + broadcast(rec, event); + }); + + toc.on('chat-left', ({ roomId }) => { + const event = makeEvent('chat_left', { roomId }); + bus.emit(event.type, { rec, event }); + bus.emit('*', { rec, event }); + broadcast(rec, event); + }); + + toc.on('buddy-update', ({ screenName, online, evil, idle }) => { + const event = makeEvent('presence', { + screenName, + online, + idleMins: Number(idle) || 0, + evil: Number(evil) || 0, + source: 'toc', + }); + bus.emit(event.type, { rec, event }); + bus.emit('*', { rec, event }); + broadcast(rec, event); + }); + + // Parse CONFIG2 buddy list (TOC2). Format is colon-delimited groups/buddies; + // we do a best-effort extraction of screen names. + toc.on('message', ({ cmd, rest }) => { + if (cmd !== 'CONFIG2' && cmd !== 'CONFIG') return; + const buddies = extractBuddiesFromConfig(rest); + if (buddies.length) { + const event = makeEvent('buddylist', { + groups: [{ name: 'Buddies', buddies: buddies.map((sn) => ({ screenName: sn })) }], + source: 'toc', + }); + bus.emit(event.type, { rec, event }); + bus.emit('*', { rec, event }); + broadcast(rec, event); + } + }); + + await toc.connect(); + return toc; +} + +function extractBuddiesFromConfig(rest) { + // CONFIG2: . Best-effort: pull tokens that look like screen names + // from buddy group sections. This is intentionally lenient. + // A proper parser should follow TOC2 config format; this covers common cases. + const out = []; + const parts = String(rest || '').split(':'); + for (const part of parts) { + // buddy entries often appear as "b:screenname" or inside group lists + if (part.startsWith('b:')) out.push(part.slice(2)); + else if (/^[a-zA-Z0-9][a-zA-Z0-9 _.-]{0,15}$/.test(part) && !['g', 'p', 'd', 'm', 'done', ''].includes(part)) { + // heuristic; avoid obvious config markers + } + } + return [...new Set(out.map(normalize).filter(Boolean))]; +} + +export function stopTOCSession(rec) { + if (rec?.toc) { + try { rec.toc.close(); } catch {} + rec.toc = null; + rec.tocConnected = false; + } +} diff --git a/src/toc.js b/src/toc.js new file mode 100644 index 0000000..46965d7 --- /dev/null +++ b/src/toc.js @@ -0,0 +1,358 @@ +// 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). + +import net from 'node:net'; +import { EventEmitter } from 'node:events'; + +const FLAP_HEADER = 6; +const FLAP_AST = 0x2a; +const FLAP_CHAN_SIGNON = 1; +const FLAP_CHAN_DATA = 2; +const FLAP_CHAN_ERROR = 3; // not used by TOC +const FLAP_CHAN_SIGNOFF = 4; +const FLAP_CHAN_KEEPALIVE = 5; +const ROAST = 'Tic/Toc'; + +function roastPassword(password) { + const pass = Buffer.from(password, 'latin1'); + const roast = Buffer.from(ROAST, 'latin1'); + const out = Buffer.alloc(pass.length); + for (let i = 0; i < pass.length; i++) out[i] = pass[i] ^ roast[i % roast.length]; + return '0x' + out.toString('hex'); +} + +function escapeTOCArg(s) { + return String(s) + .replace(/\\/g, '\\\\') + .replace(/\$/g, '\\$') + .replace(/"/g, '\\"') + .replace(/\(/g, '\\(') + .replace(/\)/g, '\\)') + .replace(/\[/g, '\\[') + .replace(/\]/g, '\\]') + .replace(/\{/g, '\\{') + .replace(/\}/g, '\\}'); +} + +function unescapeTOCArg(s) { + return String(s).replace(/\\(.)/g, '$1'); +} + +function parseTOCArgs(line) { + // Simple TOC arg parser: splits by whitespace, respects quoted strings. + const args = []; + let i = 0; + while (i < line.length) { + while (i < line.length && line[i] === ' ') i++; + if (i >= line.length) break; + if (line[i] === '"') { + i++; + let arg = ''; + while (i < line.length) { + if (line[i] === '\\' && i + 1 < line.length) { arg += line[i + 1]; i += 2; continue; } + if (line[i] === '"') { i++; break; } + arg += line[i++]; + } + args.push(arg); + } else { + let j = i; + while (j < line.length && line[j] !== ' ') j++; + args.push(unescapeTOCArg(line.slice(i, j))); + i = j; + } + } + return args; +} + +export class TOCClient extends EventEmitter { + constructor({ host, port = 9898, screenName, password, logger = console }) { + super(); + this.host = host; + this.port = port; + this.screenName = screenName; + this.password = password; + this.logger = logger; + this.socket = null; + this.buf = Buffer.alloc(0); + this.seq = 0; + this.connected = false; + this.signedOn = false; + this.closed = false; + } + + nextSeq() { + this.seq = (this.seq + 1) & 0xffff; + return this.seq; + } + + connect() { + return new Promise((resolve, reject) => { + let settled = false; + const fail = (err) => { if (!settled) { settled = true; reject(err); } }; + const ok = () => { if (!settled) { settled = true; resolve(); } }; + + const socket = net.createConnection({ host: this.host, port: this.port }); + this.socket = socket; + socket.setNoDelay(true); + + socket.on('connect', () => { + this.connected = true; + // TOC announces itself with plain text before FLAP frames. + socket.write('FLAPON\r\n\r\n'); + }); + + socket.on('data', (chunk) => { + this.buf = Buffer.concat([this.buf, chunk]); + this._drain(ok, fail); + }); + + socket.on('error', (err) => { + this.logger.error?.('[toc] socket error', err.message); + if (!this.signedOn) fail(err); + this.emit('error', err); + }); + + socket.on('close', () => { + this.connected = false; + this.signedOn = false; + if (!settled) fail(new Error('TOC connection closed before signon')); + this.emit('close'); + }); + + // Safety timeout for signon + setTimeout(() => fail(new Error('TOC signon timeout')), 15000).unref?.(); + }); + } + + _sendFLAP(channel, payload) { + const data = Buffer.isBuffer(payload) ? payload : Buffer.from(payload, 'utf8'); + const frame = Buffer.alloc(FLAP_HEADER + data.length); + frame[0] = FLAP_AST; + frame[1] = channel; + frame.writeUInt16BE(this.nextSeq(), 2); + frame.writeUInt16BE(data.length, 4); + data.copy(frame, 6); + this.logger.info?.('[toc] send flap', channel, data.length, frame.slice(0, Math.min(frame.length, 32)).toString('hex')); + this.socket.write(frame); + } + + sendCommand(cmd) { + // TOC commands are sent in FLAP channel 2. NUL terminator is tolerated by + // server but breaks open-oscar-server login() which doesn't trim it. + const payload = Buffer.from(cmd, 'utf8'); + this._sendFLAP(FLAP_CHAN_DATA, payload); + } + + _drain(onSignon, onSignonFail) { + while (this.buf.length >= FLAP_HEADER) { + if (this.buf[0] !== FLAP_AST) { + // Try to recover by finding next asterisk + const idx = this.buf.indexOf(FLAP_AST, 1); + this.logger.warn?.('[toc] bad FLAP header, resyncing'); + this.buf = idx === -1 ? Buffer.alloc(0) : this.buf.slice(idx); + continue; + } + const channel = this.buf[1]; + const len = this.buf.readUInt16BE(4); + if (this.buf.length < FLAP_HEADER + len) return; + const payload = this.buf.slice(FLAP_HEADER, FLAP_HEADER + len); + this.buf = this.buf.slice(FLAP_HEADER + len); + this._handleFrame(channel, payload, onSignon, onSignonFail); + } + } + + _handleFrame(channel, payload, onSignon, onSignonFail) { + this.logger.info?.('[toc] flap', channel, payload.length, payload.slice(0, 80).toString('utf8').replace(/[^\x20-\x7e]/g, '.')); + if (channel === FLAP_CHAN_SIGNON) { + // Server sent FLAP signon. Client must reply with FLAP signon containing + // screen name TLV (0x0001), then send toc_signon command as data frame. + if (!this.signedOn) { + const sn = Buffer.from(this.screenName, 'ascii'); + // FLAP signon body: 4-byte version + TLV 0x0001 (screen name) + const body = Buffer.alloc(4 + 4 + sn.length); + body.writeUInt32BE(1, 0); // FLAP version 1 + body.writeUInt16BE(0x0001, 4); + body.writeUInt16BE(sn.length, 6); + sn.copy(body, 8); + this._sendFLAP(FLAP_CHAN_SIGNON, body); + + const roasted = roastPassword(this.password); + const cmd = `toc2_signon login oscar-web ${this.screenName} ${roasted}`; + this.logger.info?.('[toc] sending signon'); + this.sendCommand(cmd); + } + return; + } + if (channel === FLAP_CHAN_KEEPALIVE) { + this._sendFLAP(FLAP_CHAN_KEEPALIVE, Buffer.alloc(0)); + return; + } + if (channel === FLAP_CHAN_SIGNOFF) { + this.close(); + return; + } + if (channel !== FLAP_CHAN_DATA) return; + + // Data frames: NUL-terminated TOC strings + const text = payload.toString('utf8').replace(/\0+$/, ''); + if (!text) return; + this._handleMessage(text, onSignon, onSignonFail); + } + + _handleMessage(text, onSignon, onSignonFail) { + const colonIdx = text.indexOf(':'); + const cmd = colonIdx === -1 ? text : text.slice(0, colonIdx); + const rest = colonIdx === -1 ? '' : text.slice(colonIdx + 1); + this.logger.info?.('[toc] recv', cmd, rest.slice(0, 80)); + + if (cmd === 'SIGN_ON') { + this.signedOn = true; + this.sendCommand('toc_init_done'); + this.sendCommand('toc_set_caps 09461341-4C7F-11D1-8222-444553540000 0946134a-4c7f-11d1-8222-444553540000'); + this.emit('signon', { version: rest }); + onSignon?.(); + return; + } + if (cmd === 'ERROR') { + // ERROR:: + this.emit('toc-error', { raw: text, rest }); + if (!this.signedOn) onSignonFail?.(new Error(`TOC signon error: ${text}`)); + return; + } + + this.emit('message', { cmd, rest, raw: text }); + this._emitParsed(cmd, rest, text); + } + + _emitParsed(cmd, rest, raw) { + // Parse common server messages into structured events. + if (cmd === 'IM_IN2') { + // IM_IN2:::: + const parts = rest.split(':'); + const from = parts[0] || ''; + const auto = parts[1] === 'T'; + // parts[2] unknown/whisper flag in some impls; message is rest after 3rd colon + const message = parts.slice(3).join(':'); + this.emit('im', { from, auto, message, raw }); + return; + } + if (cmd === 'IM_IN_ENC2' || cmd === 'IM_IN_ENC') { + // IM_IN_ENC2::::::::: + const parts = rest.split(':'); + const from = parts[0] || ''; + const auto = parts[1] === 'T'; + const message = parts.slice(8).join(':'); + this.emit('im', { from, auto, message, raw }); + return; + } + if (cmd === 'IM_IN') { + // IM_IN::: + const parts = rest.split(':'); + const from = parts[0] || ''; + const auto = parts[1] === 'T'; + const message = parts.slice(2).join(':'); + this.emit('im', { from, auto, message, raw }); + return; + } + if (cmd === 'CHAT_INVITE') { + // CHAT_INVITE:::: + const parts = rest.split(':'); + const roomName = parts[0] || ''; + const roomId = parts[1] || ''; + const from = parts[2] || ''; + const message = parts.slice(3).join(':'); + this.emit('chat-invite', { roomName, roomId, from, message, raw }); + return; + } + if (cmd === 'CHAT_JOIN') { + // CHAT_JOIN:: + const parts = rest.split(':'); + const roomId = parts[0] || ''; + const roomName = parts.slice(1).join(':'); + this.emit('chat-join', { roomId, roomName, raw }); + return; + } + if (cmd === 'CHAT_IN' || cmd === 'CHAT_IN_ENC') { + // CHAT_IN:::: + // CHAT_IN_ENC:::::en: + const parts = rest.split(':'); + if (cmd === 'CHAT_IN_ENC') { + const roomId = parts[0] || ''; + const from = parts[1] || ''; + const whisper = parts[2] === 'T'; + const message = parts.slice(5).join(':'); + this.emit('chat-in', { roomId, from, whisper, message, raw }); + } else { + const roomId = parts[0] || ''; + const from = parts[1] || ''; + const whisper = parts[2] === 'T'; + const message = parts.slice(3).join(':'); + this.emit('chat-in', { roomId, from, whisper, message, raw }); + } + return; + } + if (cmd === 'CHAT_UPDATE_BUDDY') { + // CHAT_UPDATE_BUDDY::: + const parts = rest.split(':'); + const roomId = parts[0] || ''; + const inside = parts[1] === 'T'; + const users = parts.slice(2).filter(Boolean); + this.emit('chat-update-buddy', { roomId, inside, users, raw }); + return; + } + if (cmd === 'CHAT_LEFT') { + const roomId = rest.trim(); + this.emit('chat-left', { roomId, raw }); + return; + } + if (cmd === 'UPDATE_BUDDY2' || cmd === 'UPDATE_BUDDY') { + // UPDATE_BUDDY2::::::: + const parts = rest.split(':'); + this.emit('buddy-update', { + screenName: parts[0] || '', + online: parts[1] === 'T', + evil: parts[2] || '0', + signonTime: parts[3] || '0', + idle: parts[4] || '0', + uc: parts[5] || '', + raw, + }); + return; + } + } + + // --- high-level commands --- + + sendIM(to, text) { + this.sendCommand(`toc2_send_im ${escapeTOCArg(to)} "${escapeTOCArg(text)}"`); + } + + chatJoin(exchange, roomName) { + this.sendCommand(`toc_chat_join ${exchange} "${escapeTOCArg(roomName)}"`); + } + + chatAccept(roomId) { + this.sendCommand(`toc_chat_accept ${roomId}`); + } + + chatSend(roomId, text) { + this.sendCommand(`toc_chat_send ${roomId} "${escapeTOCArg(text)}"`); + } + + chatLeave(roomId) { + this.sendCommand(`toc_chat_leave ${roomId}`); + } + + chatInvite(roomId, msg, ...buddies) { + const buddyArgs = buddies.map((b) => escapeTOCArg(b)).join(' '); + this.sendCommand(`toc_chat_invite ${roomId} "${escapeTOCArg(msg)}" ${buddyArgs}`); + } + + close() { + if (this.closed) return; + this.closed = true; + try { this.socket?.end(); } catch {} + try { this.socket?.destroy(); } catch {} + } +}