SQLite sessions, DB recovery, connection limits, input validation
This commit is contained in:
parent
5c8737ba29
commit
661adcf387
15 changed files with 706 additions and 57 deletions
|
|
@ -21,6 +21,8 @@ TRUST_PROXY=1
|
|||
COOKIE_SECURE=auto
|
||||
# Session lifetime in hours.
|
||||
SESSION_MAX_AGE_HOURS=24
|
||||
# SQLite DB path (sessions). Corrupt DB is rotated aside automatically.
|
||||
DB_PATH=./data/oscar-web.sqlite
|
||||
# Web API devId/key - see planning.md open question 2 / M0.
|
||||
DEV_ID=your-web-api-key
|
||||
# Long random string for cookie signing.
|
||||
|
|
|
|||
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -4,3 +4,5 @@ npm-debug.log*
|
|||
.DS_Store
|
||||
*.sqlite
|
||||
*.db
|
||||
data/
|
||||
|
||||
|
|
|
|||
22
HANDOFF.md
22
HANDOFF.md
|
|
@ -83,14 +83,24 @@ Against local open-oscar-server 0.25.0 with `DISABLE_AUTH=true`, TOC listener 98
|
|||
| TOC 9898 FLAPON probe | 2a01... | FLAP signon frame received; TOC reachable |
|
||||
| TOC signon 8520258/please | ERROR:980 | Same auth failure as Web API |
|
||||
|
||||
## Public-hardening pass (done, 2026-12-03)
|
||||
|
||||
- **SQLite sessions:** `better-sqlite3`-backed session store in `src/db.js` + `src/sqlite-session-store.js`; DB path configurable via `DB_PATH`.
|
||||
- **Malformed DB recovery:** corrupt/unopenable DB rotated aside (`.corrupt-*`) and recreated at startup/runtime recovery paths.
|
||||
- **Connection limits:** max 3 concurrent SSE connections per IP in `src/routes/stream.js`.
|
||||
- **CSRF:** removed CSRF middleware per request.
|
||||
- **Input validation:** added `src/validate.js`; normalized/length-limited screen names/messages; reduced RAM-abuse risk.
|
||||
- **Session cleanup:** SSE disconnect schedules per-session cleanup (30s grace); periodic sweep removes expired/orphaned OSCAR sessions (no global logout).
|
||||
- **Rate limiting:** removed app send limiter; kept login + general API limiter. Message rate limiting handled by OSCAR server.
|
||||
- **Scale:** intentionally small/single-process deployment.
|
||||
|
||||
## Needs to be done next
|
||||
|
||||
1. **UI polish follow-up:** refine dark theme/tabs/cards as needed, add tab close buttons, unread indicators, chat room membership/leave/invite-send UI, better mobile layout.
|
||||
2. **Harden TOC client:** handle reconnect/backoff, keepalive timeout, parse CONFIG2 buddy list properly, handle TOC1/TOC2 variants, handle chat errors/room not found.
|
||||
3. **Chat UX:** show chat room membership, leave button, invite-send UI, better system messages, error states.
|
||||
4. **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. **M5:** systemd service, env file permissions, nginx/certbot review, CSP/rate-limit review.
|
||||
1. **Complete public-hardening pass** and verify login/IM/chat/SSE still work.
|
||||
2. **UI polish follow-up:** tab close buttons, unread indicators, chat room membership/leave/invite-send UI, better mobile layout.
|
||||
3. **Harden TOC client:** handle reconnect/backoff, keepalive timeout, parse CONFIG2 buddy list properly, handle TOC1/TOC2 variants, handle chat errors/room not found.
|
||||
4. **Chat UX:** show chat room membership, leave button, invite-send UI, better system messages, error states.
|
||||
5. **M5:** systemd service, env file permissions, nginx/certbot review.
|
||||
|
||||
## Files of interest
|
||||
|
||||
|
|
|
|||
13
README.md
13
README.md
|
|
@ -62,6 +62,7 @@ Copy `.env.example` to `.env` and set values for your environment.
|
|||
| `TRUST_PROXY` | Number of proxy hops in front of app | `1` |
|
||||
| `COOKIE_SECURE` | Session cookie secure mode: `auto`, `true`, `false` | `auto` |
|
||||
| `SESSION_MAX_AGE_HOURS` | Session lifetime in hours | `24` |
|
||||
| `DB_PATH` | SQLite DB path for sessions | `./data/oscar-web.sqlite` |
|
||||
| `DEV_ID` | Optional Web API devId/key if your server requires it | unset |
|
||||
| `SESSION_SECRET` | Long random secret for cookie signing | required |
|
||||
|
||||
|
|
@ -119,16 +120,14 @@ For all other routes, proxy normally to `http://127.0.0.1:3000`.
|
|||
|
||||
- Do **not** expose port `3000` publicly; bind to `127.0.0.1`.
|
||||
- Run with a process manager (e.g. systemd) and restart on failure.
|
||||
- Sessions are stored in memory: restart logs users out and the app should run as a single process.
|
||||
- Sessions are stored in SQLite; corrupted DB files are rotated aside and recreated automatically. Run as a single process.
|
||||
|
||||
## Security notes
|
||||
|
||||
The app includes basic hardening (Helmet/CSP, rate limits, JSON-only mutating API checks, Origin checks, input limits, fetch timeouts), but you should still:
|
||||
|
||||
- Use HTTPS only
|
||||
- Keep Node/npm dependencies updated (`npm audit`)
|
||||
- Monitor logs and auth failures
|
||||
- Review before exposing to untrusted users
|
||||
- Sessions are stored in SQLite (`DB_PATH`). If the DB is malformed/corrupt, the app rotates it aside and starts fresh so it can continue running.
|
||||
- SSE connections are limited to 3 per IP.
|
||||
- The app includes Helmet/CSP, basic rate limits, input normalization/length limits, and fetch timeouts.
|
||||
- Use HTTPS only, keep dependencies updated (`npm audit`), and monitor logs/auth failures.
|
||||
|
||||
## Development
|
||||
|
||||
|
|
|
|||
388
package-lock.json
generated
388
package-lock.json
generated
|
|
@ -8,6 +8,7 @@
|
|||
"name": "web-oscar-chat",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^11.10.0",
|
||||
"express": "^4.21.2",
|
||||
"express-rate-limit": "^7.5.0",
|
||||
"express-session": "^1.18.1",
|
||||
|
|
@ -37,6 +38,53 @@
|
|||
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
|
||||
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="
|
||||
},
|
||||
"node_modules/base64-js": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
||||
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
|
||||
"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/better-sqlite3": {
|
||||
"version": "11.10.0",
|
||||
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz",
|
||||
"integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"bindings": "^1.5.0",
|
||||
"prebuild-install": "^7.1.1"
|
||||
}
|
||||
},
|
||||
"node_modules/bindings": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
|
||||
"integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
|
||||
"dependencies": {
|
||||
"file-uri-to-path": "1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/bl": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
|
||||
"integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
|
||||
"dependencies": {
|
||||
"buffer": "^5.5.0",
|
||||
"inherits": "^2.0.4",
|
||||
"readable-stream": "^3.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser": {
|
||||
"version": "1.20.9",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.9.tgz",
|
||||
|
|
@ -60,6 +108,29 @@
|
|||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer": {
|
||||
"version": "5.7.1",
|
||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
|
||||
"integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.1",
|
||||
"ieee754": "^1.1.13"
|
||||
}
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
|
|
@ -95,6 +166,11 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/chownr": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
|
||||
"integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="
|
||||
},
|
||||
"node_modules/content-disposition": {
|
||||
"version": "0.5.4",
|
||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
||||
|
|
@ -135,6 +211,28 @@
|
|||
"ms": "2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/decompress-response": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
|
||||
"integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
|
||||
"dependencies": {
|
||||
"mimic-response": "^3.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/deep-extend": {
|
||||
"version": "0.6.0",
|
||||
"resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
|
||||
"integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
|
||||
"engines": {
|
||||
"node": ">=4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/depd": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
||||
|
|
@ -152,6 +250,14 @@
|
|||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/detect-libc": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
|
||||
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/dunder-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
|
|
@ -182,6 +288,14 @@
|
|||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/end-of-stream": {
|
||||
"version": "1.4.5",
|
||||
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
|
||||
"integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
|
||||
"dependencies": {
|
||||
"once": "^1.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/es-define-property": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||
|
|
@ -222,6 +336,14 @@
|
|||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/expand-template": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
|
||||
"integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/express": {
|
||||
"version": "4.22.3",
|
||||
"resolved": "https://registry.npmjs.org/express/-/express-4.22.3.tgz",
|
||||
|
|
@ -303,6 +425,11 @@
|
|||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/file-uri-to-path": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
|
||||
"integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="
|
||||
},
|
||||
"node_modules/finalhandler": {
|
||||
"version": "1.3.2",
|
||||
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",
|
||||
|
|
@ -336,6 +463,11 @@
|
|||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/fs-constants": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
|
||||
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="
|
||||
},
|
||||
"node_modules/function-bind": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
||||
|
|
@ -379,6 +511,11 @@
|
|||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/github-from-package": {
|
||||
"version": "0.0.0",
|
||||
"resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
|
||||
"integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="
|
||||
},
|
||||
"node_modules/gopd": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
||||
|
|
@ -453,11 +590,35 @@
|
|||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ieee754": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
|
||||
"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/inherits": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
|
||||
},
|
||||
"node_modules/ini": {
|
||||
"version": "1.3.8",
|
||||
"resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
|
||||
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="
|
||||
},
|
||||
"node_modules/ipaddr.js": {
|
||||
"version": "1.9.1",
|
||||
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
|
||||
|
|
@ -528,11 +689,40 @@
|
|||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mimic-response": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
|
||||
"integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/minimist": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
|
||||
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/mkdirp-classic": {
|
||||
"version": "0.5.3",
|
||||
"resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
|
||||
"integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
|
||||
},
|
||||
"node_modules/napi-build-utils": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
|
||||
"integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="
|
||||
},
|
||||
"node_modules/negotiator": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
|
||||
|
|
@ -541,6 +731,17 @@
|
|||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/node-abi": {
|
||||
"version": "3.104.0",
|
||||
"resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.104.0.tgz",
|
||||
"integrity": "sha512-J2lVAHTQ8v1J7hl2k1eX70d/Fm+HE1EyUes2dOew59JgBlAW6NB7DABI8kdrgRPehhepJd18p1ivekA8BF7AOg==",
|
||||
"dependencies": {
|
||||
"semver": "^7.3.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/object-inspect": {
|
||||
"version": "1.14.0",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.14.0.tgz",
|
||||
|
|
@ -575,6 +776,14 @@
|
|||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/once": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
|
||||
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
|
||||
"dependencies": {
|
||||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"node_modules/parseurl": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
|
||||
|
|
@ -615,6 +824,32 @@
|
|||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/prebuild-install": {
|
||||
"version": "7.1.3",
|
||||
"resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
|
||||
"integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",
|
||||
"deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",
|
||||
"dependencies": {
|
||||
"detect-libc": "^2.0.0",
|
||||
"expand-template": "^2.0.3",
|
||||
"github-from-package": "0.0.0",
|
||||
"minimist": "^1.2.3",
|
||||
"mkdirp-classic": "^0.5.3",
|
||||
"napi-build-utils": "^2.0.0",
|
||||
"node-abi": "^3.3.0",
|
||||
"pump": "^3.0.0",
|
||||
"rc": "^1.2.7",
|
||||
"simple-get": "^4.0.0",
|
||||
"tar-fs": "^2.0.0",
|
||||
"tunnel-agent": "^0.6.0"
|
||||
},
|
||||
"bin": {
|
||||
"prebuild-install": "bin.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/proxy-addr": {
|
||||
"version": "2.0.8",
|
||||
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
|
||||
|
|
@ -631,6 +866,15 @@
|
|||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/pump": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
|
||||
"integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
|
||||
"dependencies": {
|
||||
"end-of-stream": "^1.1.0",
|
||||
"once": "^1.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.16.2",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.2.tgz",
|
||||
|
|
@ -676,6 +920,33 @@
|
|||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/rc": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
|
||||
"integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
|
||||
"dependencies": {
|
||||
"deep-extend": "^0.6.0",
|
||||
"ini": "~1.3.0",
|
||||
"minimist": "^1.2.0",
|
||||
"strip-json-comments": "~2.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"rc": "cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/readable-stream": {
|
||||
"version": "3.6.2",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
|
||||
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
||||
"dependencies": {
|
||||
"inherits": "^2.0.3",
|
||||
"string_decoder": "^1.1.1",
|
||||
"util-deprecate": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/safe-buffer": {
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||
|
|
@ -700,6 +971,17 @@
|
|||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
|
||||
},
|
||||
"node_modules/semver": {
|
||||
"version": "7.8.6",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
|
||||
"integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/send": {
|
||||
"version": "0.19.2",
|
||||
"resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
|
||||
|
|
@ -815,6 +1097,49 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/simple-concat": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
|
||||
"integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
|
||||
"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/simple-get": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",
|
||||
"integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"decompress-response": "^6.0.0",
|
||||
"once": "^1.3.1",
|
||||
"simple-concat": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/statuses": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
||||
|
|
@ -823,6 +1148,48 @@
|
|||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/string_decoder": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.4.0.tgz",
|
||||
"integrity": "sha512-r8azg21Y67ckRmeG0hHol5CeDXMs4ZFkFT6eXMO39hX7khvJcopBcYTCeWZ0rQXkMoPh8lVdbjmsOMGL8krxRQ==",
|
||||
"dependencies": {
|
||||
"safe-buffer": "~5.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-json-comments": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
|
||||
"integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tar-fs": {
|
||||
"version": "2.1.6",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.6.tgz",
|
||||
"integrity": "sha512-vsdruOmnweDIXJXWpfc5aszWMVOj6qFI+dXxNuprh6Kt+WrGJh1MQL/2xYUEzI3EX86o9b2Rop8ziIF5Ol/UoQ==",
|
||||
"dependencies": {
|
||||
"chownr": "^1.1.1",
|
||||
"mkdirp-classic": "^0.5.2",
|
||||
"pump": "^3.0.0",
|
||||
"tar-stream": "^2.1.4"
|
||||
}
|
||||
},
|
||||
"node_modules/tar-stream": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
|
||||
"integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
|
||||
"dependencies": {
|
||||
"bl": "^4.0.3",
|
||||
"end-of-stream": "^1.4.1",
|
||||
"fs-constants": "^1.0.0",
|
||||
"inherits": "^2.0.3",
|
||||
"readable-stream": "^3.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/toidentifier": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
|
||||
|
|
@ -831,6 +1198,17 @@
|
|||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/tunnel-agent": {
|
||||
"version": "0.6.0",
|
||||
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
|
||||
"integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
|
||||
"dependencies": {
|
||||
"safe-buffer": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/type-is": {
|
||||
"version": "1.6.18",
|
||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
|
||||
|
|
@ -862,6 +1240,11 @@
|
|||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/util-deprecate": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
||||
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="
|
||||
},
|
||||
"node_modules/utils-merge": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
||||
|
|
@ -877,6 +1260,11 @@
|
|||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/wrappy": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
||||
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@
|
|||
"node": ">=20.19"
|
||||
},
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^11.10.0",
|
||||
"express": "^4.21.2",
|
||||
"express-rate-limit": "^7.5.0",
|
||||
"express-session": "^1.18.1",
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ export const COOKIE_SECURE = (() => {
|
|||
throw new Error(`COOKIE_SECURE must be auto|true|false, got: ${raw}`);
|
||||
})();
|
||||
export const SESSION_MAX_AGE_MS = int('SESSION_MAX_AGE_HOURS', 24, { min: 1, max: 24 * 30 }) * 60 * 60 * 1000;
|
||||
export const DB_PATH = process.env.DB_PATH || './data/oscar-web.sqlite';
|
||||
export const NODE_ENV = process.env.NODE_ENV || 'development';
|
||||
|
||||
export function logStartupConfig() {
|
||||
|
|
@ -61,4 +62,5 @@ export function logStartupConfig() {
|
|||
console.log(`[config] App listen: http://${LISTEN_HOST}:${PORT}`);
|
||||
console.log(`[config] trust proxy: ${TRUST_PROXY}`);
|
||||
console.log(`[config] cookie secure: ${COOKIE_SECURE}`);
|
||||
console.log(`[config] db path: ${DB_PATH}`);
|
||||
}
|
||||
|
|
|
|||
80
src/db.js
Normal file
80
src/db.js
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import Database from 'better-sqlite3';
|
||||
import { DB_PATH } from './config.js';
|
||||
|
||||
let db = null;
|
||||
|
||||
function rotateCorrupt(dbPath) {
|
||||
try {
|
||||
if (fs.existsSync(dbPath)) {
|
||||
const ts = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
const backup = `${dbPath}.corrupt-${ts}`;
|
||||
fs.renameSync(dbPath, backup);
|
||||
console.error(`[db] malformed DB moved to ${backup}`);
|
||||
}
|
||||
for (const suffix of ['-wal', '-shm']) {
|
||||
const p = dbPath + suffix;
|
||||
if (fs.existsSync(p)) fs.renameSync(p, `${p}.corrupt-${Date.now()}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[db] failed to rotate corrupt DB:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
function initSchema(database) {
|
||||
database.exec(`
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
sid TEXT PRIMARY KEY,
|
||||
sess TEXT NOT NULL,
|
||||
expires INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires);
|
||||
`);
|
||||
}
|
||||
|
||||
function openDb() {
|
||||
const dbPath = path.resolve(DB_PATH);
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
const database = new Database(dbPath);
|
||||
try {
|
||||
database.pragma('journal_mode = WAL');
|
||||
database.pragma('synchronous = NORMAL');
|
||||
initSchema(database);
|
||||
database.prepare('SELECT 1 FROM sessions LIMIT 1').get();
|
||||
return database;
|
||||
} catch (err) {
|
||||
try { database.close(); } catch {}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export function getDb() {
|
||||
if (db) return db;
|
||||
const dbPath = path.resolve(DB_PATH);
|
||||
try {
|
||||
db = openDb();
|
||||
return db;
|
||||
} catch (err) {
|
||||
console.error('[db] open/init failed, attempting recovery:', err.message);
|
||||
rotateCorrupt(dbPath);
|
||||
db = openDb();
|
||||
return db;
|
||||
}
|
||||
}
|
||||
|
||||
export function recoverDbIfCorrupt(err) {
|
||||
const msg = String(err?.message || err || '');
|
||||
if (!/malformed|corrupt|disk image/i.test(msg)) return false;
|
||||
console.error('[db] corruption detected, recreating DB:', msg);
|
||||
try { db?.close(); } catch {}
|
||||
db = null;
|
||||
rotateCorrupt(path.resolve(DB_PATH));
|
||||
db = openDb();
|
||||
return true;
|
||||
}
|
||||
|
||||
export function closeDb() {
|
||||
try { db?.close(); } catch {}
|
||||
db = null;
|
||||
}
|
||||
|
|
@ -3,13 +3,10 @@ import * as oscar from '../oscar.js';
|
|||
import * as sessions from '../sessions.js';
|
||||
import { runPoller } from '../poller.js';
|
||||
import { startTOCSession, stopTOCSession } from '../toc-session.js';
|
||||
import { cleanScreenName } from '../validate.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' });
|
||||
|
|
@ -40,16 +37,23 @@ export async function logoutSession(req) {
|
|||
await new Promise((resolve) => req.session.destroy(() => resolve()));
|
||||
}
|
||||
|
||||
export async function cleanupSessionById(sessionId, sessionStore) {
|
||||
const rec = sessions.getSession(sessionId);
|
||||
if (!rec) return;
|
||||
if (rec.sseClients.size > 0) return;
|
||||
await endOscarSession(rec, sessionId);
|
||||
if (sessionStore?.destroy) {
|
||||
await new Promise((resolve) => sessionStore.destroy(sessionId, () => resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
authRouter.post('/login', async (req, res) => {
|
||||
const screenName = sanitizeScreenName(req.body?.screenName).slice(0, 64);
|
||||
const password = String(req.body?.password || '');
|
||||
const screenName = cleanScreenName(req.body?.screenName);
|
||||
const password = String(req.body?.password || '').replace(/[\u0000-\u001f\u007f]/g, '').slice(0, 256);
|
||||
|
||||
if (!screenName || !password) {
|
||||
return res.status(400).json({ error: 'screenName and password are required' });
|
||||
}
|
||||
if (password.length > 256) {
|
||||
return res.status(400).json({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
// If this browser session already has an OSCAR session, clean it up first.
|
||||
const existing = sessions.getSession(req.session.id);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Router } from 'express';
|
||||
import * as oscar from '../oscar.js';
|
||||
import { requireLogin } from './auth.js';
|
||||
import { cleanScreenName } from '../validate.js';
|
||||
|
||||
export const buddiesRouter = Router();
|
||||
|
||||
|
|
@ -24,7 +25,7 @@ buddiesRouter.get('/buddies', requireLogin, async (req, res) => {
|
|||
});
|
||||
|
||||
buddiesRouter.post('/buddies', requireLogin, async (req, res) => {
|
||||
const screenName = String(req.body?.screenName || '').trim().slice(0, 64);
|
||||
const screenName = cleanScreenName(req.body?.screenName);
|
||||
if (!screenName) return res.status(400).json({ error: 'screenName is required' });
|
||||
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
import { Router } from 'express';
|
||||
import * as oscar from '../oscar.js';
|
||||
import { requireLogin } from './auth.js';
|
||||
import { cleanMessage, cleanScreenName, cleanText } from '../validate.js';
|
||||
|
||||
export const messagesRouter = Router();
|
||||
|
||||
function text(value, max = 2000) {
|
||||
const s = String(value ?? '').trim();
|
||||
if (!s) return null;
|
||||
return s.slice(0, max);
|
||||
const s = cleanMessage(value, max);
|
||||
return s || null;
|
||||
}
|
||||
|
||||
messagesRouter.post('/im', requireLogin, async (req, res) => {
|
||||
const to = text(req.body?.to, 64);
|
||||
const to = cleanScreenName(req.body?.to);
|
||||
const message = text(req.body?.text, 2000);
|
||||
if (!to || !message) return res.status(400).json({ error: 'to and text are required' });
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,30 @@
|
|||
import { Router } from 'express';
|
||||
import { requireLogin } from './auth.js';
|
||||
import { requireLogin, cleanupSessionById } from './auth.js';
|
||||
|
||||
export const streamRouter = Router();
|
||||
|
||||
const ipConnections = new Map(); // ip -> count
|
||||
const MAX_CONN_PER_IP = 3;
|
||||
const pendingCleanup = new Map(); // sessionId -> timer
|
||||
|
||||
function incIp(ip) {
|
||||
const n = (ipConnections.get(ip) || 0) + 1;
|
||||
ipConnections.set(ip, n);
|
||||
return n;
|
||||
}
|
||||
function decIp(ip) {
|
||||
const n = (ipConnections.get(ip) || 0) - 1;
|
||||
if (n <= 0) ipConnections.delete(ip);
|
||||
else ipConnections.set(ip, n);
|
||||
}
|
||||
|
||||
streamRouter.get('/events', requireLogin, (req, res) => {
|
||||
const ip = req.ip || req.socket.remoteAddress || 'unknown';
|
||||
const count = incIp(ip);
|
||||
if (count > MAX_CONN_PER_IP) {
|
||||
decIp(ip);
|
||||
return res.status(429).json({ error: 'Too many active connections from this IP' });
|
||||
}
|
||||
res.set({
|
||||
'Content-Type': 'text/event-stream', // tells the browser this is a stream
|
||||
'Cache-Control': 'no-cache',
|
||||
|
|
@ -15,6 +36,8 @@ streamRouter.get('/events', requireLogin, (req, res) => {
|
|||
|
||||
const rec = req.oscar;
|
||||
rec.sseClients.add(res); // poller writes to everything in here
|
||||
const pending = pendingCleanup.get(rec.sessionId);
|
||||
if (pending) { clearTimeout(pending); pendingCleanup.delete(rec.sessionId); }
|
||||
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.
|
||||
|
|
@ -28,8 +51,26 @@ streamRouter.get('/events', requireLogin, (req, res) => {
|
|||
try { res.write(': ping\n\n'); } catch { /* ignore */ }
|
||||
}, 30000);
|
||||
|
||||
req.on('close', () => {
|
||||
let cleaned = false;
|
||||
const cleanupConn = () => {
|
||||
if (cleaned) return;
|
||||
cleaned = true;
|
||||
clearInterval(heartbeat);
|
||||
rec.sseClients.delete(res); // tab closed, stop sending
|
||||
decIp(ip);
|
||||
if (rec.sseClients.size === 0) {
|
||||
const old = pendingCleanup.get(rec.sessionId);
|
||||
if (old) clearTimeout(old);
|
||||
const timer = setTimeout(() => {
|
||||
pendingCleanup.delete(rec.sessionId);
|
||||
cleanupSessionById(rec.sessionId, req.app.locals.sessionStore).catch((err) => {
|
||||
console.error('[sse] session cleanup failed:', err.message);
|
||||
});
|
||||
}, 30000);
|
||||
timer.unref?.();
|
||||
pendingCleanup.set(rec.sessionId, timer);
|
||||
}
|
||||
};
|
||||
req.on('close', cleanupConn);
|
||||
res.on('close', cleanupConn);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -8,10 +8,12 @@ import path from 'node:path';
|
|||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
import { PORT, LISTEN_HOST, SESSION_SECRET, TRUST_PROXY, COOKIE_SECURE, SESSION_MAX_AGE_MS, NODE_ENV, logStartupConfig } from './config.js';
|
||||
import { getDb, closeDb } from './db.js';
|
||||
import { SqliteSessionStore } from './sqlite-session-store.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 { authRouter, requireLogin, cleanupSessionById } from './routes/auth.js';
|
||||
import { streamRouter } from './routes/stream.js';
|
||||
import { messagesRouter } from './routes/messages.js';
|
||||
import { buddiesRouter } from './routes/buddies.js';
|
||||
|
|
@ -46,27 +48,15 @@ app.use(helmet({
|
|||
app.use(express.json({ limit: '16kb' }));
|
||||
app.use(express.urlencoded({ extended: false, limit: '16kb' }));
|
||||
|
||||
// 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();
|
||||
});
|
||||
// CSRF middleware intentionally omitted per project preference.
|
||||
|
||||
const cookieSecure = COOKIE_SECURE === 'true' ? true : COOKIE_SECURE === 'false' ? false : 'auto';
|
||||
const sessionStore = new SqliteSessionStore();
|
||||
app.locals.sessionStore = sessionStore;
|
||||
app.use(session({
|
||||
name: 'oscar.sid',
|
||||
secret: SESSION_SECRET(),
|
||||
store: sessionStore,
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
proxy: TRUST_PROXY > 0,
|
||||
|
|
@ -92,18 +82,8 @@ const apiLimiter = rateLimit({
|
|||
legacyHeaders: false,
|
||||
message: { error: 'Too many requests, slow down.' },
|
||||
});
|
||||
const sendLimiter = rateLimit({
|
||||
windowMs: 60 * 1000,
|
||||
limit: 30,
|
||||
standardHeaders: 'draft-7',
|
||||
legacyHeaders: false,
|
||||
message: { error: 'Too many messages, slow down.' },
|
||||
});
|
||||
|
||||
app.use('/api', apiLimiter);
|
||||
app.use('/api/login', loginLimiter);
|
||||
app.use('/api/im', sendLimiter);
|
||||
app.use('/api/chat', sendLimiter);
|
||||
|
||||
app.use('/api', (_req, res, next) => {
|
||||
res.set('Cache-Control', 'no-store');
|
||||
|
|
@ -191,10 +171,36 @@ async function shutdown(signal) {
|
|||
process.on('SIGINT', () => { void shutdown('SIGINT'); });
|
||||
process.on('SIGTERM', () => { void shutdown('SIGTERM'); });
|
||||
|
||||
function startSessionSweep() {
|
||||
const timer = setInterval(async () => {
|
||||
try {
|
||||
const now = Date.now();
|
||||
for (const rec of Array.from(sessionsStore.allSessions())) {
|
||||
if (rec.sseClients.size > 0) continue; // active browser connection
|
||||
// Check if express session still exists and not expired
|
||||
let expired = false;
|
||||
try {
|
||||
const row = getDb().prepare('SELECT expires FROM sessions WHERE sid = ?').get(rec.sessionId);
|
||||
expired = !row || Number(row.expires) <= now;
|
||||
} catch {
|
||||
continue; // don't kill sessions on DB read hiccup
|
||||
}
|
||||
if (expired) {
|
||||
await cleanupSessionById(rec.sessionId, app.locals.sessionStore);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[sweep] failed:', err.message);
|
||||
}
|
||||
}, 5 * 60 * 1000);
|
||||
timer.unref?.();
|
||||
}
|
||||
|
||||
async function main() {
|
||||
logStartupConfig();
|
||||
await oscar.healthCheck();
|
||||
await loadFeatures();
|
||||
startSessionSweep();
|
||||
|
||||
app.listen(PORT, LISTEN_HOST, () => {
|
||||
console.log(`[server] listening on http://${LISTEN_HOST}:${PORT}`);
|
||||
|
|
|
|||
97
src/sqlite-session-store.js
Normal file
97
src/sqlite-session-store.js
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import session from 'express-session';
|
||||
import { getDb, recoverDbIfCorrupt } from './db.js';
|
||||
|
||||
function withRecovery(fn) {
|
||||
try {
|
||||
return fn();
|
||||
} catch (err) {
|
||||
if (recoverDbIfCorrupt(err)) {
|
||||
return fn();
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export class SqliteSessionStore extends session.Store {
|
||||
constructor({ cleanupIntervalMs = 15 * 60 * 1000 } = {}) {
|
||||
super();
|
||||
this.cleanupIntervalMs = cleanupIntervalMs;
|
||||
// Eagerly open DB so malformed DBs are recovered at startup.
|
||||
getDb();
|
||||
this._startCleanup();
|
||||
}
|
||||
|
||||
_startCleanup() {
|
||||
this._timer = setInterval(() => {
|
||||
try { this.cleanupExpired(); } catch (err) { console.error('[session-store] cleanup failed:', err.message); }
|
||||
}, this.cleanupIntervalMs);
|
||||
this._timer.unref?.();
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (this._timer) clearInterval(this._timer);
|
||||
this._timer = null;
|
||||
}
|
||||
|
||||
cleanupExpired() {
|
||||
const now = Date.now();
|
||||
withRecovery(() => getDb().prepare('DELETE FROM sessions WHERE expires <= ?').run(now));
|
||||
}
|
||||
|
||||
get(sid, cb = () => {}) {
|
||||
try {
|
||||
const row = withRecovery(() => getDb().prepare('SELECT sess, expires FROM sessions WHERE sid = ?').get(sid));
|
||||
if (!row) return cb(null, null);
|
||||
if (row.expires <= Date.now()) {
|
||||
this.destroy(sid, () => cb(null, null));
|
||||
return;
|
||||
}
|
||||
const sess = JSON.parse(row.sess);
|
||||
cb(null, sess);
|
||||
} catch (err) {
|
||||
console.error('[session-store] get failed:', err.message);
|
||||
cb(err);
|
||||
}
|
||||
}
|
||||
|
||||
set(sid, sess, cb = () => {}) {
|
||||
try {
|
||||
const maxAge = sess?.cookie?.maxAge;
|
||||
const expires = typeof maxAge === 'number'
|
||||
? Date.now() + maxAge
|
||||
: (sess?.cookie?.expires ? new Date(sess.cookie.expires).getTime() : Date.now() + 24 * 60 * 60 * 1000);
|
||||
const data = JSON.stringify(sess);
|
||||
withRecovery(() => getDb().prepare(
|
||||
'INSERT INTO sessions(sid, sess, expires) VALUES(?, ?, ?) ON CONFLICT(sid) DO UPDATE SET sess=excluded.sess, expires=excluded.expires'
|
||||
).run(sid, data, expires));
|
||||
cb(null);
|
||||
} catch (err) {
|
||||
console.error('[session-store] set failed:', err.message);
|
||||
cb(err);
|
||||
}
|
||||
}
|
||||
|
||||
destroy(sid, cb = () => {}) {
|
||||
try {
|
||||
withRecovery(() => getDb().prepare('DELETE FROM sessions WHERE sid = ?').run(sid));
|
||||
cb(null);
|
||||
} catch (err) {
|
||||
console.error('[session-store] destroy failed:', err.message);
|
||||
cb(err);
|
||||
}
|
||||
}
|
||||
|
||||
touch(sid, sess, cb = () => {}) {
|
||||
try {
|
||||
const maxAge = sess?.cookie?.maxAge;
|
||||
const expires = typeof maxAge === 'number'
|
||||
? Date.now() + maxAge
|
||||
: (sess?.cookie?.expires ? new Date(sess.cookie.expires).getTime() : Date.now() + 24 * 60 * 60 * 1000);
|
||||
withRecovery(() => getDb().prepare('UPDATE sessions SET expires = ? WHERE sid = ?').run(expires, sid));
|
||||
cb(null);
|
||||
} catch (err) {
|
||||
console.error('[session-store] touch failed:', err.message);
|
||||
cb(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
16
src/validate.js
Normal file
16
src/validate.js
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
const CONTROL_CHARS = /[\u0000-\u001f\u007f]/g;
|
||||
|
||||
export function cleanText(value, { max = 2000, allowEmpty = false } = {}) {
|
||||
let s = String(value ?? '').normalize('NFC').replace(CONTROL_CHARS, '').trim();
|
||||
if (s.length > max) s = s.slice(0, max);
|
||||
if (!s && !allowEmpty) return '';
|
||||
return s;
|
||||
}
|
||||
|
||||
export function cleanScreenName(value) {
|
||||
return cleanText(value, { max: 64 }).replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
export function cleanMessage(value, max = 2000) {
|
||||
return cleanText(value, { max }).replace(/\r\n?/g, '\n');
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue