feat(auth): implement session-based authentication and API token management
Server CI / Lint (push) Successful in 19s
Server CI / Build & Push Docker Image (push) Failing after 44s

- Introduced a new authentication system using session cookies for the web dashboard and API tokens for sync clients.
- Replaced the old SERVER_PASSWORD scheme with a more secure API token mechanism.
- Added routes for user setup, login, logout, and credential updates.
- Implemented middleware to require session and API token for protected routes.
- Updated web UI to handle authentication states and provide user feedback.
- Enhanced error handling in API requests and responses.
- Updated README to reflect new authentication flow and database requirements.
This commit is contained in:
Gabriel20xx committed 2026-08-01 12:51:02 +02:00
1 parent 240e1fda4a
commit b150d835a1
18 files changed
+1022 -982

No files matched your search

+5 -21
View File
@@ -3,25 +3,12 @@
#################################################################
PORT=3000
NODE_ENV=production
SERVER_PASSWORD=your_secure_password_here
# Set to "true" once served over HTTPS - marks the admin session cookie Secure.
COOKIE_SECURE=false
#################################################################
# Database backend selection
# - sqlite (default if not set)
# - postgres
#################################################################
# Choose the DB client; if omitted or not set to "postgres", SQLite is used
DB_CLIENT=sqlite
#################################################################
# SQLite configuration (used when DB_CLIENT=sqlite)
#################################################################
# Path to the SQLite database file. Default in code: ./data/collabtable.db
# For Docker, you may prefer a volume path like /data/collabtable.db
DB_PATH=/data/collabtable.db
#################################################################
# PostgreSQL configuration (used when DB_CLIENT=postgres)
# PostgreSQL configuration
# You can either provide a single DATABASE_URL or the PG* variables below
#################################################################
# Example URL: postgres://user:password@localhost:5432/collabtable
@@ -35,7 +22,7 @@ PGPASSWORD=
PGDATABASE=collabtable
#################################################################
# Startup resilience and sync/auth tuning
# Startup resilience and sync tuning
#################################################################
# DB init retry interval in milliseconds (default: 5000)
DB_INIT_RETRY_INTERVAL_MS=5000
@@ -43,9 +30,6 @@ DB_INIT_RETRY_INTERVAL_MS=5000
# Max DB init retry attempts. 0 means retry forever (default: 0)
DB_INIT_RETRY_MAX_ATTEMPTS=0
# Suppress repetitive auth warning logs for the same path/method (default: 30000)
AUTH_LOG_THROTTLE_MS=30000
# Allow at most this much client clock skew into sync timestamps (default: 0)
# Keep this at 0 to prevent future-dated rows from being re-sent in hot loops.
SYNC_MAX_FUTURE_SKEW_MS=0
-3
View File
@@ -24,9 +24,6 @@ RUN npm run build
# Built webui, served by webRoutes.ts from ./web (sibling of dist/)
COPY --from=webui-builder /webui/build ./web
# Create data directory for SQLite
RUN mkdir -p /data
# Expose port
EXPOSE 3000
+32 -37
View File
@@ -1,19 +1,21 @@
# CollabTable Server
A collaborative table management server built with Node.js, Express, TypeScript, and a pluggable database (SQLite or PostgreSQL).
A collaborative table management server built with Node.js, Express, TypeScript, and PostgreSQL.
## Features
- RESTful API for managing lists, fields, items, and values
- Real-time synchronization via WebSocket (primary) with HTTP fallback
- SQLite (better-sqlite3) or PostgreSQL (pg) database backends
- PostgreSQL (pg) database backend
- Single-admin-account web dashboard login (session cookie, bcrypt-hashed password) plus a
long-lived API token for sync clients/devices, generated from the dashboard
- Dockerized deployment with persistent storage
- TypeScript for type safety
## Prerequisites
- Docker and Docker Compose
- Or Node.js 20+ (for local development)
- Or Node.js 20+ and a PostgreSQL instance (for local development)
## Quick Start with Docker
@@ -28,14 +30,13 @@ A collaborative table management server built with Node.js, Express, TypeScript,
cp .env.example .env
```
4. Start the services:
4. Start the services (this also starts a bundled PostgreSQL container):
```bash
docker-compose up -d
```
The server will be available at `http://localhost:3000`
**Important:** The default backend is SQLite with a Docker volume `sqlite_data` for persistence. You can also switch to PostgreSQL by setting environment variables.
The server will be available at `http://localhost:3000`. Open it in a browser to create the
admin account, then generate an API token from the dashboard for your sync clients/devices.
## Local Development
@@ -49,21 +50,18 @@ The server will be available at `http://localhost:3000`
cp .env.example .env
```
3. Choose your database in `.env` (SQLite by default):
3. Point it at a PostgreSQL instance in `.env`:
```
# Backend: sqlite | postgres (default sqlite)
DB_CLIENT=sqlite
# SQLite
DB_PATH=./data/collabtable.db
# OR PostgreSQL
# DATABASE_URL=postgres://user:password@localhost:5432/collabtable
DATABASE_URL=postgres://user:password@localhost:5432/collabtable
# OR, as discrete variables:
# PGHOST=localhost
# PGPORT=5432
# PGUSER=postgres
# PGPASSWORD=yourpassword
# PGDATABASE=collabtable
# Set to "true" once served over HTTPS
COOKIE_SECURE=false
```
4. Start the development server:
@@ -102,7 +100,7 @@ The server will be available at `http://localhost:3000`
- `{"type":"ping"}` → `{"type":"pong"}`
- `{"type":"sync", "id":"<uuid>", "payload": { ...SyncRequest }}` → `{"type":"syncResponse", "id":"<uuid>", "payload": { ...SyncResponse }}`
Authentication: If `SERVER_PASSWORD` is set, include header `Authorization: Bearer <password>` on HTTP and WebSocket requests.
Authentication: include header `Authorization: Bearer <api-token>` on sync/collaboration API requests, using the API token generated from the web dashboard's Settings page (see "Authentication" below).
### Health Check
- `GET /health` - Check server health
@@ -225,34 +223,31 @@ docker-compose up -d --build
- `PORT` - Server port (default: 3000)
- `NODE_ENV` - Environment (development/production)
- `SERVER_PASSWORD` - Optional shared password for API and WebSocket (recommended)
- `DB_CLIENT` - `sqlite` (default) or `postgres`
- `DB_PATH` - Path to SQLite database file (default: ./data/collabtable.db for local, /data/collabtable.db in Docker)
- `COOKIE_SECURE` - Set to `true` to mark the admin session cookie `Secure` (requires HTTPS); default `false`
- `DATABASE_URL` - PostgreSQL connection URL (optional alternative to PG* variables)
- `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE` - PostgreSQL connection parameters
- `DB_INIT_RETRY_INTERVAL_MS` - Delay between DB init retries in ms (default: `5000`)
- `DB_INIT_RETRY_MAX_ATTEMPTS` - Max DB init retries; `0` retries forever (default: `0`)
- `AUTH_LOG_THROTTLE_MS` - Minimum interval before repeating the same auth warning log (default: `30000`)
- `SYNC_MAX_FUTURE_SKEW_MS` - Allowed future timestamp skew from clients during sync (default: `0`)
## Authentication
There is a single admin account for the web dashboard (username + password, bcrypt-hashed,
session cookie - no accounts beyond the one admin). The first time you open the dashboard
you're walked through creating it; there is no default/seeded account.
Sync clients and devices (the mobile app, or anything hitting the `/api/lists` /
`/api/fields` / `/api/items` / `/api/sync` / `/api/notifications` endpoints) authenticate
with a separate long-lived API token instead - generate or regenerate it from the
dashboard's Settings page, then set `Authorization: Bearer <token>` on those requests. This
replaces the old optional `SERVER_PASSWORD` scheme, which silently disabled auth entirely
when left unset.
## Data Persistence
### SQLite
The SQLite database file is stored in a Docker volume, ensuring data persists across container lifecycle events.
Backup:
```bash
docker cp collabtable-server:/data/collabtable.db ./backup.db
```
Restore:
```bash
docker cp ./backup.db collabtable-server:/data/collabtable.db
docker-compose restart
```
### PostgreSQL
Use your normal PostgreSQL backup/restore procedures (e.g., `pg_dump`, `pg_restore`). If using the optional Dockerized Postgres service, the data is stored in a named volume (see `docker-compose.yml`).
Use your normal PostgreSQL backup/restore procedures (e.g., `pg_dump`, `pg_restore`). If
using the bundled Dockerized Postgres service, the data is stored in a named volume (see
`docker-compose.yml`).
## License
+50 -58
View File
@@ -1,58 +1,50 @@
version: '3.8'
services:
server:
build: .
container_name: collabtable-server
restart: unless-stopped
environment:
- PORT=3000
- NODE_ENV=production
# Authentication (optional but recommended)
- SERVER_PASSWORD=change_me
# Database selection: sqlite | postgres (default sqlite)
- DB_CLIENT=sqlite
# SQLite path (used when DB_CLIENT=sqlite)
- DB_PATH=/data/collabtable.db
# Retry DB initialization instead of crashing immediately on startup races
- DB_INIT_RETRY_INTERVAL_MS=5000
- DB_INIT_RETRY_MAX_ATTEMPTS=0
# Clamp future client timestamps during sync to avoid resend loops
- SYNC_MAX_FUTURE_SKEW_MS=0
# PostgreSQL (used when DB_CLIENT=postgres) - choose either DATABASE_URL or the PG* vars
# - DATABASE_URL=postgres://user:password@postgres:5432/collabtable
# - PGHOST=postgres
# - PGPORT=5432
# - PGUSER=postgres
# - PGPASSWORD=yourpassword
# - PGDATABASE=collabtable
ports:
- "3000:3000"
volumes:
- sqlite_data:/data
networks:
- collabtable-network
# Optional PostgreSQL database
# postgres:
# image: postgres:16-alpine
# container_name: collabtable-postgres
# restart: unless-stopped
# environment:
# - POSTGRES_DB=collabtable
# - POSTGRES_USER=postgres
# - POSTGRES_PASSWORD=yourpassword
# ports:
# - "5432:5432"
# volumes:
# - pg_data:/var/lib/postgresql/data
# networks:
# - collabtable-network
volumes:
sqlite_data:
# pg_data:
networks:
collabtable-network:
driver: bridge
version: '3.8'
services:
postgres:
image: postgres:17-alpine
container_name: collabtable-postgres
restart: unless-stopped
environment:
- POSTGRES_DB=collabtable
- POSTGRES_USER=collabtable
- POSTGRES_PASSWORD=collabtable
volumes:
- pg_data:/var/lib/postgresql/data
networks:
- collabtable-network
healthcheck:
test: ["CMD-SHELL", "pg_isready -U collabtable"]
interval: 10s
timeout: 5s
retries: 5
server:
build: .
container_name: collabtable-server
restart: unless-stopped
environment:
- PORT=3000
- NODE_ENV=production
# Session cookie for the admin web dashboard (see src/routes/authRoutes.ts)
- COOKIE_SECURE=false
# Retry DB initialization instead of crashing immediately on startup races
- DB_INIT_RETRY_INTERVAL_MS=5000
- DB_INIT_RETRY_MAX_ATTEMPTS=0
# Clamp future client timestamps during sync to avoid resend loops
- SYNC_MAX_FUTURE_SKEW_MS=0
- DATABASE_URL=postgres://collabtable:collabtable@postgres:5432/collabtable
ports:
- "3000:3000"
depends_on:
postgres:
condition: service_healthy
networks:
- collabtable-network
volumes:
pg_data:
networks:
collabtable-network:
driver: bridge
+47 -385
View File
@@ -11,7 +11,8 @@
"dependencies": {
"@typescript-eslint/eslint-plugin": "^7.0.2",
"@typescript-eslint/parser": "^7.0.2",
"better-sqlite3": "^11.0.0",
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"eslint": "^8.57.0",
@@ -21,7 +22,8 @@
"prettier": "^3.3.3"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.11",
"@types/bcryptjs": "^2.4.6",
"@types/cookie-parser": "^1.4.7",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/node": "^20.10.6",
@@ -286,15 +288,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/better-sqlite3": {
"version": "7.6.13",
"resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz",
"integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==",
"node_modules/@types/bcryptjs": {
"version": "2.4.6",
"resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz",
"integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
"license": "MIT"
},
"node_modules/@types/body-parser": {
"version": "1.19.6",
@@ -317,6 +316,16 @@
"@types/node": "*"
}
},
"node_modules/@types/cookie-parser": {
"version": "1.4.10",
"resolved": "https://registry.npmjs.org/@types/cookie-parser/-/cookie-parser-1.4.10.tgz",
"integrity": "sha512-B4xqkqfZ8Wek+rCOeRxsjMS9OgvzebEzzLYw7NHYuvzb7IdxOkI0ZHGgeEBX4PUM7QGVvNSK60T3OvWj3YfBRg==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/express": "*"
}
},
"node_modules/@types/cors": {
"version": "2.8.19",
"resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz",
@@ -869,37 +878,12 @@
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"license": "MIT"
},
"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/bcryptjs": {
"version": "2.4.3",
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz",
"integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==",
"license": "MIT"
},
"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,
"license": "MIT",
"dependencies": {
"bindings": "^1.5.0",
"prebuild-install": "^7.1.1"
}
},
"node_modules/binary-extensions": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
@@ -913,26 +897,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"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==",
"license": "MIT",
"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==",
"license": "MIT",
"dependencies": {
"buffer": "^5.5.0",
"inherits": "^2.0.4",
"readable-stream": "^3.4.0"
}
},
"node_modules/body-parser": {
"version": "1.20.3",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz",
@@ -979,30 +943,6 @@
"node": ">=8"
}
},
"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"
}
],
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.1.13"
}
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
@@ -1098,12 +1038,6 @@
"fsevents": "~2.3.2"
}
},
"node_modules/chownr": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
"integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
"license": "ISC"
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -1158,6 +1092,28 @@
"node": ">= 0.6"
}
},
"node_modules/cookie-parser": {
"version": "1.4.7",
"resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.7.tgz",
"integrity": "sha512-nGUvgXnotP3BsjiLX2ypbQnWoGUPIIfHQNZkkC668ntrzGWEZVW70HDEB1qnNGMicPje6EttlIgzo51YSwNQGw==",
"license": "MIT",
"dependencies": {
"cookie": "0.7.2",
"cookie-signature": "1.0.6"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/cookie-parser/node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie-signature": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
@@ -1207,30 +1163,6 @@
"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==",
"license": "MIT",
"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==",
"license": "MIT",
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/deep-is": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
@@ -1256,15 +1188,6 @@
"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==",
"license": "Apache-2.0",
"engines": {
"node": ">=8"
}
},
"node_modules/diff": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz",
@@ -1350,15 +1273,6 @@
"node": ">= 0.8"
}
},
"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==",
"license": "MIT",
"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",
@@ -1606,15 +1520,6 @@
"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==",
"license": "(MIT OR WTFPL)",
"engines": {
"node": ">=6"
}
},
"node_modules/express": {
"version": "4.21.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz",
@@ -1716,12 +1621,6 @@
"node": "^10.12.0 || >=12.0.0"
}
},
"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==",
"license": "MIT"
},
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@@ -1822,12 +1721,6 @@
"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==",
"license": "MIT"
},
"node_modules/fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
@@ -1895,12 +1788,6 @@
"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==",
"license": "MIT"
},
"node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
@@ -2048,26 +1935,6 @@
"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"
}
],
"license": "BSD-3-Clause"
},
"node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
@@ -2119,12 +1986,6 @@
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/ini": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
"license": "ISC"
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
@@ -2379,18 +2240,6 @@
"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==",
"license": "MIT",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
@@ -2407,6 +2256,7 @@
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
@@ -2425,24 +2275,12 @@
"node": ">=10"
}
},
"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==",
"license": "MIT"
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT"
},
"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==",
"license": "MIT"
},
"node_modules/natural-compare": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
@@ -2458,18 +2296,6 @@
"node": ">= 0.6"
}
},
"node_modules/node-abi": {
"version": "3.78.0",
"resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.78.0.tgz",
"integrity": "sha512-E2wEyrgX/CqvicaQYU3Ze1PFGjc4QYPGsjUrlYkqAE0WjHEZwgOsGMPMzkMse4LjJbDmaEuDX3CM036j5K2DSQ==",
"license": "MIT",
"dependencies": {
"semver": "^7.3.5"
},
"engines": {
"node": ">=10"
}
},
"node_modules/normalize-path": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
@@ -2779,32 +2605,6 @@
"node": ">=0.10.0"
}
},
"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==",
"license": "MIT",
"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/prelude-ls": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
@@ -2842,16 +2642,6 @@
"node": ">= 0.10"
}
},
"node_modules/pump": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz",
"integrity": "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==",
"license": "MIT",
"dependencies": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
}
},
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@@ -2920,35 +2710,6 @@
"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==",
"license": "(BSD-2-Clause OR MIT OR Apache-2.0)",
"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==",
"license": "MIT",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
@@ -3230,51 +2991,6 @@
"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"
}
],
"license": "MIT"
},
"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"
}
],
"license": "MIT",
"dependencies": {
"decompress-response": "^6.0.0",
"once": "^1.3.1",
"simple-concat": "^1.0.0"
}
},
"node_modules/slash": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz",
@@ -3323,15 +3039,6 @@
"node": ">= 0.8"
}
},
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.2.0"
}
},
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
@@ -3358,6 +3065,7 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
"integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -3388,34 +3096,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/tar-fs": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",
"integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==",
"license": "MIT",
"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==",
"license": "MIT",
"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/text-table": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz",
@@ -3557,18 +3237,6 @@
"strip-json-comments": "^2.0.0"
}
},
"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==",
"license": "Apache-2.0",
"dependencies": {
"safe-buffer": "^5.0.1"
},
"engines": {
"node": "*"
}
},
"node_modules/type-check": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
@@ -3644,12 +3312,6 @@
"punycode": "^2.1.0"
}
},
"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==",
"license": "MIT"
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
+4 -2
View File
@@ -17,7 +17,8 @@
"dependencies": {
"express": "^4.18.2",
"cors": "^2.8.5",
"better-sqlite3": "^11.0.0",
"cookie-parser": "^1.4.6",
"bcryptjs": "^2.4.3",
"dotenv": "^16.3.1",
"@typescript-eslint/eslint-plugin": "^7.0.2",
"@typescript-eslint/parser": "^7.0.2",
@@ -29,8 +30,9 @@
"devDependencies": {
"@types/express": "^4.17.21",
"@types/cors": "^2.8.17",
"@types/cookie-parser": "^1.4.7",
"@types/bcryptjs": "^2.4.6",
"@types/node": "^20.10.6",
"@types/better-sqlite3": "^7.6.11",
"@types/pg": "^8.10.2",
"typescript": "5.5.4",
"ts-node-dev": "^2.0.0"
+227 -304
View File
@@ -1,304 +1,227 @@
import dotenv from 'dotenv';
import BetterSqlite3, { Database as SqliteDB } from 'better-sqlite3';
import { Pool, PoolClient, QueryResult, types as pgTypes } from 'pg';
import path from 'path';
import fs from 'fs';
dotenv.config();
type Param = any;
type ExecResult = { changes: number };
interface DBAdapter {
queryAll(sql: string, params?: Param[]): Promise<any[]>;
queryOne(sql: string, params?: Param[]): Promise<any | undefined>;
execute(sql: string, params?: Param[]): Promise<ExecResult>;
transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T>;
initialize(): Promise<void>;
}
function ensureDataDir(dbPath: string) {
const dir = path.dirname(dbPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}
function replaceQuotedIdentifiers(sql: string) {
// Convert backticks to double quotes for portability
return sql.replace(/`([^`]+)`/g, '"$1"');
}
function convertQMarksToPg(sql: string) {
// Replace each ? with $1, $2, ...
let idx = 0;
return sql.replace(/\?/g, () => `$${++idx}`);
}
// ---------- SQLite Adapter (wrapped async) ----------
class SqliteAdapter implements DBAdapter {
private db: SqliteDB;
constructor() {
const DB_PATH = process.env.DB_PATH || './data/collabtable.db';
ensureDataDir(DB_PATH);
this.db = new BetterSqlite3(DB_PATH);
this.db.pragma('foreign_keys = ON');
}
async initialize(): Promise<void> {
// Create tables and indexes
this.db.exec(`
CREATE TABLE IF NOT EXISTS lists (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
isDeleted INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS fields (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
fieldType TEXT NOT NULL,
fieldOptions TEXT,
alignment TEXT NOT NULL DEFAULT 'start',
listId TEXT NOT NULL,
"order" INTEGER NOT NULL,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
isDeleted INTEGER DEFAULT 0,
FOREIGN KEY (listId) REFERENCES lists(id)
);
CREATE TABLE IF NOT EXISTS items (
id TEXT PRIMARY KEY,
listId TEXT NOT NULL,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
isDeleted INTEGER DEFAULT 0,
FOREIGN KEY (listId) REFERENCES lists(id)
);
CREATE TABLE IF NOT EXISTS item_values (
id TEXT PRIMARY KEY,
itemId TEXT NOT NULL,
fieldId TEXT NOT NULL,
value TEXT,
updatedAt INTEGER NOT NULL,
FOREIGN KEY (itemId) REFERENCES items(id),
FOREIGN KEY (fieldId) REFERENCES fields(id)
);
CREATE INDEX IF NOT EXISTS idx_fields_listId ON fields(listId);
CREATE INDEX IF NOT EXISTS idx_items_listId ON items(listId);
CREATE INDEX IF NOT EXISTS idx_item_values_itemId ON item_values(itemId);
CREATE INDEX IF NOT EXISTS idx_item_values_fieldId ON item_values(fieldId);
-- Notification events table (for remote-change notifications)
CREATE TABLE IF NOT EXISTS notifications (
id TEXT PRIMARY KEY,
deviceIdOrigin TEXT,
eventType TEXT NOT NULL,
entityType TEXT NOT NULL,
entityId TEXT,
listId TEXT,
createdAt INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_notifications_createdAt ON notifications(createdAt);
CREATE INDEX IF NOT EXISTS idx_notifications_listId ON notifications(listId);
`);
// Attempt to add alignment column if upgrading an existing DB (ignore error if exists)
try {
this.db.exec(`ALTER TABLE fields ADD COLUMN alignment TEXT NOT NULL DEFAULT 'start'`);
} catch (e) {
// Column may already exist; ignore
}
}
async queryAll(sql: string, params: Param[] = []): Promise<any[]> {
const stmt = this.db.prepare(replaceQuotedIdentifiers(sql));
return stmt.all(...params);
}
async queryOne(sql: string, params: Param[] = []): Promise<any | undefined> {
const stmt = this.db.prepare(replaceQuotedIdentifiers(sql));
return stmt.get(...params);
}
async execute(sql: string, params: Param[] = []): Promise<ExecResult> {
const stmt = this.db.prepare(replaceQuotedIdentifiers(sql));
const res = stmt.run(...params);
return { changes: res.changes || 0 };
}
async transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T> {
const tx = this.db.transaction((innerFn: (tx: DBAdapter) => Promise<T>) => {
// We can reuse the same adapter since better-sqlite3 is transactional per connection
return innerFn(this);
});
return tx(fn);
}
}
// ---------- Postgres Adapter ----------
class PostgresAdapter implements DBAdapter {
private pool: Pool;
constructor() {
// Ensure BIGINT (int8) is parsed as number to avoid string timestamps
// OID 20 = INT8, OID 1700 = NUMERIC (keep default for now)
pgTypes.setTypeParser(20, (val: string) => parseInt(val, 10));
const connectionString = process.env.DATABASE_URL;
if (connectionString) {
this.pool = new Pool({ connectionString });
} else {
this.pool = new Pool({
host: process.env.PGHOST || 'localhost',
port: parseInt(process.env.PGPORT || '5432', 10),
user: process.env.PGUSER || 'postgres',
password: process.env.PGPASSWORD || '',
database: process.env.PGDATABASE || 'collabtable'
});
}
}
async initialize(): Promise<void> {
// Create tables if not exist, keeping schema aligned with sqlite (isDeleted INTEGER 0/1)
const client = await this.pool.connect();
try {
await client.query('BEGIN');
await client.query(`
CREATE TABLE IF NOT EXISTS lists (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
createdAt BIGINT NOT NULL,
updatedAt BIGINT NOT NULL,
isDeleted INTEGER DEFAULT 0
);
`);
await client.query(`
CREATE TABLE IF NOT EXISTS fields (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
fieldType TEXT NOT NULL,
fieldOptions TEXT,
alignment TEXT NOT NULL DEFAULT 'start',
listId TEXT NOT NULL,
"order" INTEGER NOT NULL,
createdAt BIGINT NOT NULL,
updatedAt BIGINT NOT NULL,
isDeleted INTEGER DEFAULT 0,
FOREIGN KEY (listId) REFERENCES lists(id)
);
`);
await client.query(`
CREATE TABLE IF NOT EXISTS items (
id TEXT PRIMARY KEY,
listId TEXT NOT NULL,
createdAt BIGINT NOT NULL,
updatedAt BIGINT NOT NULL,
isDeleted INTEGER DEFAULT 0,
FOREIGN KEY (listId) REFERENCES lists(id)
);
`);
await client.query(`
CREATE TABLE IF NOT EXISTS item_values (
id TEXT PRIMARY KEY,
itemId TEXT NOT NULL,
fieldId TEXT NOT NULL,
value TEXT,
updatedAt BIGINT NOT NULL,
FOREIGN KEY (itemId) REFERENCES items(id),
FOREIGN KEY (fieldId) REFERENCES fields(id)
);
`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_fields_listId ON fields(listId);`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_items_listId ON items(listId);`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_item_values_itemId ON item_values(itemId);`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_item_values_fieldId ON item_values(fieldId);`);
// Notifications table
await client.query(`
CREATE TABLE IF NOT EXISTS notifications (
id TEXT PRIMARY KEY,
deviceIdOrigin TEXT,
eventType TEXT NOT NULL,
entityType TEXT NOT NULL,
entityId TEXT,
listId TEXT,
createdAt BIGINT NOT NULL
);
`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_notifications_createdAt ON notifications(createdAt);`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_notifications_listId ON notifications(listId);`);
// Migrate existing DBs: ensure alignment column exists
await client.query(`ALTER TABLE fields ADD COLUMN IF NOT EXISTS alignment TEXT NOT NULL DEFAULT 'start';`);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
}
private async runQuery(sql: string, params: Param[] = [], client?: PoolClient): Promise<QueryResult<any>> {
// Replace backticks and convert ? to $1..$n
const text = convertQMarksToPg(replaceQuotedIdentifiers(sql));
const runner: Pool | PoolClient = client || this.pool;
return runner.query(text, params);
}
async queryAll(sql: string, params: Param[] = []): Promise<any[]> {
const res = await this.runQuery(sql, params);
return res.rows;
}
async queryOne(sql: string, params: Param[] = []): Promise<any | undefined> {
const res = await this.runQuery(sql, params);
return res.rows[0];
}
async execute(sql: string, params: Param[] = []): Promise<ExecResult> {
const res = await this.runQuery(sql, params);
return { changes: res.rowCount || 0 };
}
async transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T> {
const client = await this.pool.connect();
try {
await client.query('BEGIN');
const txAdapter: DBAdapter = {
initialize: async () => {},
queryAll: (sql, params) => this.runQuery(sql, params, client).then(r => r.rows),
queryOne: (sql, params) => this.runQuery(sql, params, client).then(r => r.rows[0]),
execute: (sql, params) => this.runQuery(sql, params, client).then(r => ({ changes: r.rowCount || 0 })),
transaction: async (inner) => {
// Nested transactions are treated as flat for simplicity
return inner(txAdapter);
}
} as DBAdapter;
const result = await fn(txAdapter);
await client.query('COMMIT');
return result;
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
}
}
const clientType = (process.env.DB_CLIENT || process.env.DB_TYPE || 'sqlite').toLowerCase();
const isPostgres = clientType === 'postgres' || clientType === 'postgresql';
export const dbEngine = isPostgres ? 'PostgreSQL' : 'SQLite';
export const dbAdapter: DBAdapter = isPostgres
? new PostgresAdapter()
: new SqliteAdapter();
export async function initializeDatabase() {
await dbAdapter.initialize();
}
export type { DBAdapter };
import dotenv from 'dotenv';
import { Pool, PoolClient, QueryResult, types as pgTypes } from 'pg';
dotenv.config();
type Param = any;
type ExecResult = { changes: number };
interface DBAdapter {
queryAll(sql: string, params?: Param[]): Promise<any[]>;
queryOne(sql: string, params?: Param[]): Promise<any | undefined>;
execute(sql: string, params?: Param[]): Promise<ExecResult>;
transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T>;
initialize(): Promise<void>;
}
function replaceQuotedIdentifiers(sql: string) {
// Convert backticks to double quotes for portability
return sql.replace(/`([^`]+)`/g, '"$1"');
}
function convertQMarksToPg(sql: string) {
// Replace each ? with $1, $2, ...
let idx = 0;
return sql.replace(/\?/g, () => `$${++idx}`);
}
// ---------- Postgres Adapter ----------
class PostgresAdapter implements DBAdapter {
private pool: Pool;
constructor() {
// Ensure BIGINT (int8) is parsed as number to avoid string timestamps
// OID 20 = INT8, OID 1700 = NUMERIC (keep default for now)
pgTypes.setTypeParser(20, (val: string) => parseInt(val, 10));
const connectionString = process.env.DATABASE_URL;
if (connectionString) {
this.pool = new Pool({ connectionString });
} else {
this.pool = new Pool({
host: process.env.PGHOST || 'localhost',
port: parseInt(process.env.PGPORT || '5432', 10),
user: process.env.PGUSER || 'postgres',
password: process.env.PGPASSWORD || '',
database: process.env.PGDATABASE || 'collabtable'
});
}
}
async initialize(): Promise<void> {
// Create tables if not exist
const client = await this.pool.connect();
try {
await client.query('BEGIN');
await client.query(`
CREATE TABLE IF NOT EXISTS lists (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
createdAt BIGINT NOT NULL,
updatedAt BIGINT NOT NULL,
isDeleted INTEGER DEFAULT 0
);
`);
await client.query(`
CREATE TABLE IF NOT EXISTS fields (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
fieldType TEXT NOT NULL,
fieldOptions TEXT,
alignment TEXT NOT NULL DEFAULT 'start',
listId TEXT NOT NULL,
"order" INTEGER NOT NULL,
createdAt BIGINT NOT NULL,
updatedAt BIGINT NOT NULL,
isDeleted INTEGER DEFAULT 0,
FOREIGN KEY (listId) REFERENCES lists(id)
);
`);
await client.query(`
CREATE TABLE IF NOT EXISTS items (
id TEXT PRIMARY KEY,
listId TEXT NOT NULL,
createdAt BIGINT NOT NULL,
updatedAt BIGINT NOT NULL,
isDeleted INTEGER DEFAULT 0,
FOREIGN KEY (listId) REFERENCES lists(id)
);
`);
await client.query(`
CREATE TABLE IF NOT EXISTS item_values (
id TEXT PRIMARY KEY,
itemId TEXT NOT NULL,
fieldId TEXT NOT NULL,
value TEXT,
updatedAt BIGINT NOT NULL,
FOREIGN KEY (itemId) REFERENCES items(id),
FOREIGN KEY (fieldId) REFERENCES fields(id)
);
`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_fields_listId ON fields(listId);`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_items_listId ON items(listId);`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_item_values_itemId ON item_values(itemId);`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_item_values_fieldId ON item_values(fieldId);`);
// Notifications table
await client.query(`
CREATE TABLE IF NOT EXISTS notifications (
id TEXT PRIMARY KEY,
deviceIdOrigin TEXT,
eventType TEXT NOT NULL,
entityType TEXT NOT NULL,
entityId TEXT,
listId TEXT,
createdAt BIGINT NOT NULL
);
`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_notifications_createdAt ON notifications(createdAt);`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_notifications_listId ON notifications(listId);`);
// Migrate existing DBs: ensure alignment column exists
await client.query(`ALTER TABLE fields ADD COLUMN IF NOT EXISTS alignment TEXT NOT NULL DEFAULT 'start';`);
// ---- Auth (single admin account for the web dashboard) ----
// Matches the Bitmagnet/UnraidMonitor pattern: opaque session-cookie tokens (no JWT),
// bcrypt-hashed passwords, schema created idempotently on every startup.
await client.query(`
CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
`);
// Enforces a single admin account, matching a single-tenant dashboard.
await client.query(`
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
`);
await client.query(`
CREATE TABLE IF NOT EXISTS auth_sessions (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
`);
await client.query(`CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);`);
await client.query(`CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);`);
// Long-lived credential for sync clients/devices (replaces the old optional
// SERVER_PASSWORD scheme, which silently disabled auth entirely when unset). Only
// the SHA-256 hash is stored; the raw token is shown once, at creation/regeneration.
await client.query(`
CREATE TABLE IF NOT EXISTS api_tokens (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
`);
await client.query(`CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens (user_id);`);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
}
private async runQuery(sql: string, params: Param[] = [], client?: PoolClient): Promise<QueryResult<any>> {
// Replace backticks and convert ? to $1..$n
const text = convertQMarksToPg(replaceQuotedIdentifiers(sql));
const runner: Pool | PoolClient = client || this.pool;
return runner.query(text, params);
}
async queryAll(sql: string, params: Param[] = []): Promise<any[]> {
const res = await this.runQuery(sql, params);
return res.rows;
}
async queryOne(sql: string, params: Param[] = []): Promise<any | undefined> {
const res = await this.runQuery(sql, params);
return res.rows[0];
}
async execute(sql: string, params: Param[] = []): Promise<ExecResult> {
const res = await this.runQuery(sql, params);
return { changes: res.rowCount || 0 };
}
async transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T> {
const client = await this.pool.connect();
try {
await client.query('BEGIN');
const txAdapter: DBAdapter = {
initialize: async () => {},
queryAll: (sql, params) => this.runQuery(sql, params, client).then(r => r.rows),
queryOne: (sql, params) => this.runQuery(sql, params, client).then(r => r.rows[0]),
execute: (sql, params) => this.runQuery(sql, params, client).then(r => ({ changes: r.rowCount || 0 })),
transaction: async (inner) => {
// Nested transactions are treated as flat for simplicity
return inner(txAdapter);
}
} as DBAdapter;
const result = await fn(txAdapter);
await client.query('COMMIT');
return result;
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
}
}
export const dbEngine = 'PostgreSQL';
export const dbAdapter: DBAdapter = new PostgresAdapter();
export async function initializeDatabase() {
await dbAdapter.initialize();
}
export type { DBAdapter };
+18 -13
View File
@@ -1,9 +1,11 @@
import express from 'express';
import cors from 'cors';
import cookieParser from 'cookie-parser';
import dotenv from 'dotenv';
import { initializeDatabase } from './db';
import { authenticatePassword } from './middleware/auth';
import { requireApiToken } from './middleware/auth';
import { deviceIdMiddleware } from './middleware/device';
import authRoutes from './routes/authRoutes';
import listRoutes from './routes/listRoutes';
import fieldRoutes from './routes/fieldRoutes';
import itemRoutes from './routes/itemRoutes';
@@ -51,27 +53,35 @@ async function initializeDatabaseWithRetry() {
}
// Middleware
app.use(cors());
app.use(cors({ credentials: true, origin: true }));
app.use(express.json());
app.use(cookieParser());
// Health check (no auth required)
app.get('/health', (req, res) => {
res.json({ status: 'ok', timestamp: Date.now() });
});
// Apply authentication middleware to all API routes
app.use('/api', authenticatePassword);
// Auth bootstrap routes (status/setup/login/logout/credentials/token) - must stay
// reachable without a token or session, mounted before the API-token gate below.
app.use('/api', authRoutes);
// Sync/collaboration API: gated by a long-lived API token shared by every collaborating
// device (see middleware/auth.ts) - this replaces the old optional SERVER_PASSWORD scheme,
// which silently disabled auth entirely when unset.
app.use('/api', requireApiToken);
// Attach device id for downstream routes
app.use('/api', deviceIdMiddleware);
// Routes (protected by auth)
// Routes (protected by the API token above)
app.use('/api/lists', listRoutes);
app.use('/api/fields', fieldRoutes);
app.use('/api/items', itemRoutes);
app.use('/api', syncRoutes);
app.use('/api', notificationRoutes);
// Web UI (no auth required, must be last to not interfere with API routes)
// Web UI (static SPA shell is public; its /web/info and /web/data JSON endpoints require
// the admin session - see webRoutes.ts. Mounted last to not interfere with API routes.)
app.use('/', webRoutes);
// Initialize database and start server
@@ -92,13 +102,8 @@ app.use('/', webRoutes);
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
const dbClient = (process.env.DB_CLIENT || process.env.DB_TYPE || 'sqlite').toLowerCase();
if (dbClient === 'postgres' || dbClient === 'postgresql') {
const source = process.env.DATABASE_URL ? 'DATABASE_URL' : 'PGHOST/PGDATABASE';
console.log(`Database: PostgreSQL (${source})`);
} else {
console.log(`Database: ${process.env.DB_PATH || './data/collabtable.db'}`);
}
const source = process.env.DATABASE_URL ? 'DATABASE_URL' : 'PGHOST/PGDATABASE';
console.log(`Database: PostgreSQL (${source})`);
});
} catch (error) {
console.error('Database initialization error:', error);
+54 -101
View File
@@ -1,101 +1,54 @@
import { Request, Response, NextFunction } from 'express';
let warningLogged = false;
const AUTH_LOG_THROTTLE_MS = Math.max(1000, Number(process.env.AUTH_LOG_THROTTLE_MS || 30000));
const lastAuthLogAt = new Map<string, number>();
const commonProbePathPatterns = [
/^\/\./,
/client_secret\.json$/i,
/phpinfo/i,
/\.git/i,
/wp-admin/i,
/wp-login/i,
/id_rsa/i,
/config(\.|$)/i
];
function isCommonProbePath(pathname: string) {
return commonProbePathPatterns.some(pattern => pattern.test(pathname));
}
function shouldLogAuthWarning(kind: string, req: Request) {
const key = `${kind}:${req.method}:${req.path}`;
const now = Date.now();
const lastSeen = lastAuthLogAt.get(key) || 0;
if (now - lastSeen < AUTH_LOG_THROTTLE_MS) {
return false;
}
lastAuthLogAt.set(key, now);
return true;
}
export const authenticatePassword = (req: Request, res: Response, next: NextFunction) => {
const serverPassword = process.env.SERVER_PASSWORD;
// If no password is set in environment, skip authentication
if (!serverPassword) {
if (!warningLogged) {
console.warn('Warning: SERVER_PASSWORD not set in environment variables. Authentication is disabled.');
warningLogged = true;
}
return next();
}
// Get password from Authorization header (format: "Bearer <password>")
const authHeader = req.headers.authorization;
if (!authHeader) {
if (!isCommonProbePath(req.path) && shouldLogAuthWarning('missingHeader', req)) {
console.warn('[AUTH] Missing Authorization header', {
path: req.path,
method: req.method,
ip: req.ip,
});
}
return res.status(401).json({
error: 'Unauthorized',
message: 'No authorization header provided'
});
}
// Parse the authorization header
const parts = authHeader.split(' ');
if (parts.length !== 2 || parts[0] !== 'Bearer') {
if (shouldLogAuthWarning('invalidHeaderFormat', req)) {
console.warn('[AUTH] Invalid authorization header format', {
path: req.path,
method: req.method,
ip: req.ip,
// Do not log full header to avoid leaking secrets; include prefix only
headerPreview: authHeader.substring(0, Math.min(authHeader.length, 20)) + '...'
});
}
return res.status(401).json({
error: 'Unauthorized',
message: 'Invalid authorization header format. Expected: Bearer <password>'
});
}
const providedPassword = parts[1];
// Validate password
if (providedPassword !== serverPassword) {
// Avoid logging the full password; log only length and a small preview
if (shouldLogAuthWarning('invalidPassword', req)) {
const safePreview = providedPassword ? `${providedPassword.substring(0, 2)}..(${providedPassword.length})` : 'null';
console.warn('[AUTH] Invalid password', {
path: req.path,
method: req.method,
ip: req.ip,
providedPreview: safePreview,
});
}
return res.status(401).json({
error: 'Unauthorized',
message: 'Invalid password'
});
}
// Password is valid, continue
next();
};
import { Request, Response, NextFunction } from 'express';
import crypto from 'crypto';
import { dbAdapter } from '../db';
export const SESSION_COOKIE_NAME = 'collabtable_session';
export function hashToken(token: string): string {
return crypto.createHash('sha256').update(token).digest('hex');
}
export function randomToken(): string {
return crypto.randomBytes(32).toString('base64url');
}
/**
* Gates the web dashboard (webRoutes' JSON endpoints) behind the single admin account's
* session cookie. Matches the Bitmagnet/UnraidMonitor pattern - opaque cookie tokens, not JWT.
*/
export async function requireSession(req: Request, res: Response, next: NextFunction) {
const token = req.cookies?.[SESSION_COOKIE_NAME];
if (!token) {
return res.status(401).json({ error: 'Unauthorized', message: 'Authentication required' });
}
const user = await dbAdapter.queryOne(
`SELECT u.id, u.username FROM auth_sessions s
JOIN auth_users u ON u.id = s.user_id
WHERE s.token_hash = ? AND s.expires_at > now()`,
[hashToken(token)]
);
if (!user) {
return res.status(401).json({ error: 'Unauthorized', message: 'Session expired or invalid' });
}
(req as any).user = user;
next();
}
/**
* Gates the sync/collaboration API (lists/fields/items/sync/notifications) behind a
* long-lived API token tied to the admin account - this is machine/multi-device traffic
* shared by every collaborating client, not an interactive browser login. Replaces the old
* optional SERVER_PASSWORD scheme, which silently disabled auth entirely when unset.
*/
export async function requireApiToken(req: Request, res: Response, next: NextFunction) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized', message: 'No bearer token provided' });
}
const token = authHeader.slice('Bearer '.length);
const row = await dbAdapter.queryOne('SELECT user_id FROM api_tokens WHERE token_hash = ?', [hashToken(token)]);
if (!row) {
return res.status(401).json({ error: 'Unauthorized', message: 'Invalid API token' });
}
next();
}
+185
View File
@@ -0,0 +1,185 @@
import { Router, Request, Response } from 'express';
import bcrypt from 'bcryptjs';
import { dbAdapter } from '../db';
import { SESSION_COOKIE_NAME, hashToken, randomToken, requireSession } from '../middleware/auth';
const router = Router();
const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
const MIN_PASSWORD_LEN = 8;
const MAX_USERNAME_LEN = 64;
const SECURE_COOKIE = process.env.COOKIE_SECURE === 'true';
function normalizeUsername(username: unknown): string | null {
if (typeof username !== 'string') return null;
const trimmed = username.trim();
if (!trimmed || trimmed.length > MAX_USERNAME_LEN) return null;
return trimmed;
}
function isValidPassword(password: unknown): password is string {
return typeof password === 'string' && password.length >= MIN_PASSWORD_LEN;
}
function setSessionCookie(res: Response, token: string, expiresAt: Date) {
res.cookie(SESSION_COOKIE_NAME, token, {
httpOnly: true,
secure: SECURE_COOKIE,
sameSite: 'lax',
path: '/',
expires: expiresAt,
});
}
function clearSessionCookie(res: Response) {
res.clearCookie(SESSION_COOKIE_NAME, { path: '/' });
}
async function startSession(userId: number, res: Response) {
const token = randomToken();
const expiresAt = new Date(Date.now() + SESSION_TTL_MS);
await dbAdapter.execute('INSERT INTO auth_sessions (user_id, token_hash, expires_at) VALUES (?, ?, ?)', [
userId,
hashToken(token),
expiresAt,
]);
setSessionCookie(res, token, expiresAt);
}
router.get('/auth/status', async (req: Request, res: Response) => {
const countRow = await dbAdapter.queryOne('SELECT count(*) as count FROM auth_users');
const count = Number(countRow?.count ?? 0);
if (count === 0) {
return res.json({ setupRequired: true, authenticated: false });
}
const token = req.cookies?.[SESSION_COOKIE_NAME];
if (!token) {
return res.json({ setupRequired: false, authenticated: false });
}
const user = await dbAdapter.queryOne(
`SELECT u.username FROM auth_sessions s JOIN auth_users u ON u.id = s.user_id
WHERE s.token_hash = ? AND s.expires_at > now()`,
[hashToken(token)]
);
if (!user) {
return res.json({ setupRequired: false, authenticated: false });
}
res.json({ setupRequired: false, authenticated: true, username: user.username });
});
router.post('/auth/setup', async (req: Request, res: Response) => {
const countRow = await dbAdapter.queryOne('SELECT count(*) as count FROM auth_users');
if (Number(countRow?.count ?? 0) > 0) {
return res.status(409).json({ error: 'Conflict', message: 'Setup has already been completed.' });
}
const username = normalizeUsername(req.body?.username);
if (!username) {
return res.status(400).json({ error: 'Bad Request', message: 'Username is required.' });
}
if (!isValidPassword(req.body?.password)) {
return res.status(400).json({ error: 'Bad Request', message: 'Password must be at least 8 characters.' });
}
const passwordHash = await bcrypt.hash(req.body.password, 12);
let created;
try {
created = await dbAdapter.queryOne(
'INSERT INTO auth_users (username, password_hash, updated_at) VALUES (?, ?, now()) RETURNING id, username',
[username, passwordHash]
);
} catch (e: any) {
if (e?.code === '23505') {
return res.status(409).json({ error: 'Conflict', message: 'Setup has already been completed.' });
}
throw e;
}
await startSession(created.id, res);
res.json({ setupRequired: false, authenticated: true, username: created.username });
});
router.post('/auth/login', async (req: Request, res: Response) => {
const username = normalizeUsername(req.body?.username);
const password = req.body?.password;
const invalid = () => res.status(401).json({ error: 'Unauthorized', message: 'Invalid username or password.' });
if (!username || typeof password !== 'string') return invalid();
const user = await dbAdapter.queryOne('SELECT id, username, password_hash FROM auth_users WHERE username = ?', [
username,
]);
if (!user || !(await bcrypt.compare(password, user.password_hash))) {
return invalid();
}
await startSession(user.id, res);
res.json({ setupRequired: false, authenticated: true, username: user.username });
});
router.post('/auth/logout', requireSession, async (req: Request, res: Response) => {
const token = req.cookies?.[SESSION_COOKIE_NAME];
if (token) {
await dbAdapter.execute('DELETE FROM auth_sessions WHERE token_hash = ?', [hashToken(token)]);
}
clearSessionCookie(res);
res.json({ ok: true });
});
router.post('/auth/credentials', requireSession, async (req: Request, res: Response) => {
const user = (req as any).user as { id: number; username: string };
const currentUser = await dbAdapter.queryOne('SELECT id, username, password_hash FROM auth_users WHERE id = ?', [
user.id,
]);
if (!currentUser || !(await bcrypt.compare(req.body?.currentPassword ?? '', currentUser.password_hash))) {
return res.status(400).json({ error: 'Bad Request', message: 'Current password is incorrect.' });
}
let username = currentUser.username;
if (req.body?.newUsername !== undefined) {
const normalized = normalizeUsername(req.body.newUsername);
if (!normalized) {
return res.status(400).json({ error: 'Bad Request', message: 'Username is required.' });
}
username = normalized;
}
let passwordHash = currentUser.password_hash;
if (req.body?.newPassword) {
if (!isValidPassword(req.body.newPassword)) {
return res.status(400).json({ error: 'Bad Request', message: 'Password must be at least 8 characters.' });
}
passwordHash = await bcrypt.hash(req.body.newPassword, 12);
}
await dbAdapter.execute('UPDATE auth_users SET username = ?, password_hash = ?, updated_at = now() WHERE id = ?', [
username,
passwordHash,
currentUser.id,
]);
// Force re-login everywhere (including this browser) after a credential change,
// matching the Bitmagnet/UnraidMonitor reference behavior.
await dbAdapter.execute('DELETE FROM auth_sessions WHERE user_id = ?', [currentUser.id]);
clearSessionCookie(res);
res.json({ ok: true });
});
router.get('/auth/token/status', requireSession, async (req: Request, res: Response) => {
const user = (req as any).user as { id: number };
const row = await dbAdapter.queryOne('SELECT 1 FROM api_tokens WHERE user_id = ?', [user.id]);
res.json({ hasToken: !!row });
});
// Issues a brand new API token for sync clients/devices, invalidating any previous one.
// The raw token is returned exactly once and is never retrievable again.
router.post('/auth/token/regenerate', requireSession, async (req: Request, res: Response) => {
const user = (req as any).user as { id: number };
const token = randomToken();
await dbAdapter.transaction(async (tx) => {
await tx.execute('DELETE FROM api_tokens WHERE user_id = ?', [user.id]);
await tx.execute('INSERT INTO api_tokens (user_id, token_hash) VALUES (?, ?)', [user.id, hashToken(token)]);
});
res.json({ token });
});
export default router;
+6 -5
View File
@@ -2,6 +2,7 @@ import express, { Router, Request, Response } from 'express';
import fs from 'fs';
import path from 'path';
import { dbAdapter, dbEngine } from '../db';
import { requireSession } from '../middleware/auth';
const router = Router();
@@ -28,22 +29,22 @@ function depVersion(name: string): string {
return deps[name] ? deps[name].replace(/^[^\d]*/, '') : 'unknown';
}
// API endpoint to get server tech stack info (no auth required for web UI)
router.get('/web/info', (req: Request, res: Response) => {
// API endpoint to get server tech stack info (requires the admin session)
router.get('/web/info', requireSession, (req: Request, res: Response) => {
res.json({
appVersion: packageJson.version ?? 'unknown',
stack: [
{ label: 'Runtime', value: `Node.js ${process.version}` },
{ label: 'Language', value: `TypeScript ${depVersion('typescript')}` },
{ label: 'Web Framework', value: `Express ${depVersion('express')}` },
{ label: 'Database', value: `${dbEngine} (${dbEngine === 'PostgreSQL' ? 'pg ' + depVersion('pg') : 'better-sqlite3 ' + depVersion('better-sqlite3')})` },
{ label: 'Database', value: `${dbEngine} (pg ${depVersion('pg')})` },
{ label: 'CORS', value: `cors ${depVersion('cors')}` },
],
});
});
// API endpoint to get all data (no auth required for web UI)
router.get('/web/data', async (req: Request, res: Response) => {
// API endpoint to get all data (requires the admin session)
router.get('/web/data', requireSession, async (req: Request, res: Response) => {
try {
// Add cache control headers to prevent stale data
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
+46 -3
View File
@@ -1,9 +1,29 @@
async function getJson(url) {
const res = await fetch(url, { cache: 'no-store' });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
async function request(url, options) {
const res = await fetch(url, {
...options,
headers: options?.body ? { 'Content-Type': 'application/json', ...options?.headers } : options?.headers,
});
if (!res.ok) {
let message = `HTTP ${res.status}`;
try {
const body = await res.json();
// This backend's error responses are { error: "<category>", message: "<human text>" } -
// message is the human-readable text; error is just a category label (e.g. "Unauthorized").
if (body?.message) message = body.message;
else if (body?.error) message = body.error;
} catch {
// Response body wasn't JSON (or was empty) - keep the generic status message.
}
throw new Error(message);
}
if (res.status === 204) return undefined;
return res.json();
}
async function getJson(url) {
return request(url);
}
export async function fetchOverview() {
return getJson('/web/data');
}
@@ -16,3 +36,26 @@ export async function fetchHealth() {
const res = await fetch('/health');
return { up: res.ok };
}
export async function fetchAuthStatus() {
return getJson('/api/auth/status');
}
export async function setupAccount(username, password) {
return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, password }) });
}
export async function login(username, password) {
return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) });
}
export async function logout() {
return request('/api/auth/logout', { method: 'POST' });
}
export async function updateCredentials({ currentPassword, newUsername, newPassword }) {
return request('/api/auth/credentials', {
method: 'POST',
body: JSON.stringify({ currentPassword, newUsername, newPassword }),
});
}
@@ -0,0 +1,97 @@
<script>
import { Table2 } from '@lucide/svelte';
import Button from '$lib/components/ui/button.svelte';
import { useAuth } from '$lib/features/auth/auth.svelte.js';
let { setupRequired } = $props();
const auth = useAuth();
let username = $state('');
let password = $state('');
let confirmPassword = $state('');
let submitting = $state(false);
let error = $state('');
async function submit(event) {
event.preventDefault();
error = '';
if (setupRequired && password !== confirmPassword) {
error = 'Passwords do not match.';
return;
}
submitting = true;
try {
if (setupRequired) {
await auth.setup(username, password);
} else {
await auth.login(username, password);
}
} catch (submitError) {
error = submitError instanceof Error ? submitError.message : 'Request failed.';
} finally {
submitting = false;
}
}
</script>
<main class="flex min-h-screen items-center justify-center bg-bg px-4 py-8">
<section class="w-full max-w-sm rounded-lg border border-border bg-surface p-6 shadow-sm">
<div class="mb-6 flex flex-col items-center gap-2 text-center">
<Table2 class="size-8 text-primary" />
<h1 class="text-xl font-semibold">CollabTable</h1>
<p class="text-sm text-muted-fg">
{setupRequired ? 'Create the admin account for this dashboard.' : 'Sign in to view this dashboard.'}
</p>
</div>
<form class="space-y-4" onsubmit={submit}>
<div>
<label for="auth-username" class="mb-1 block text-sm font-medium">Username</label>
<!-- svelte-ignore a11y_autofocus -->
<input
id="auth-username"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={username}
autocomplete="username"
required
autofocus
/>
</div>
<div>
<label for="auth-password" class="mb-1 block text-sm font-medium">Password</label>
<input
id="auth-password"
type="password"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={password}
autocomplete={setupRequired ? 'new-password' : 'current-password'}
minlength={8}
required
/>
</div>
{#if setupRequired}
<div>
<label for="auth-confirm-password" class="mb-1 block text-sm font-medium">Confirm password</label>
<input
id="auth-confirm-password"
type="password"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={confirmPassword}
autocomplete="new-password"
minlength={8}
required
/>
</div>
{/if}
{#if error}
<p class="text-sm text-danger">{error}</p>
{/if}
<Button type="submit" class="w-full" disabled={submitting}>
{submitting ? 'Working…' : setupRequired ? 'Create account' : 'Sign in'}
</Button>
</form>
</section>
</main>
@@ -0,0 +1,109 @@
<script>
import Button from '$lib/components/ui/button.svelte';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '$lib/components/ui/dialog';
import { useAuth } from '$lib/features/auth/auth.svelte.js';
let { open = $bindable(false), currentUsername } = $props();
const auth = useAuth();
let username = $state('');
let currentPassword = $state('');
let newPassword = $state('');
let confirmPassword = $state('');
let error = $state('');
let saving = $state(false);
$effect(() => {
if (open) username = currentUsername;
});
async function submit(event) {
event.preventDefault();
error = '';
if (newPassword !== confirmPassword) {
error = 'Passwords do not match.';
return;
}
saving = true;
try {
await auth.updateCredentials({
currentPassword,
newUsername: username.trim() || undefined,
newPassword: newPassword || undefined,
});
currentPassword = '';
newPassword = '';
confirmPassword = '';
open = false;
} catch (saveError) {
error = saveError instanceof Error ? saveError.message : 'Request failed.';
} finally {
saving = false;
}
}
</script>
<Dialog bind:open>
<DialogContent>
<DialogHeader>
<DialogTitle>Account</DialogTitle>
</DialogHeader>
<form class="space-y-4" onsubmit={submit}>
<p class="text-sm text-muted-fg">Changing your credentials will sign you out everywhere.</p>
<div>
<label for="credentials-username" class="mb-1 block text-sm font-medium">Username</label>
<input
id="credentials-username"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={username}
autocomplete="username"
/>
</div>
<div>
<label for="credentials-current-password" class="mb-1 block text-sm font-medium">Current password</label>
<input
id="credentials-current-password"
type="password"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={currentPassword}
autocomplete="current-password"
required
/>
</div>
<div>
<label for="credentials-new-password" class="mb-1 block text-sm font-medium">New password</label>
<input
id="credentials-new-password"
type="password"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={newPassword}
autocomplete="new-password"
minlength={8}
placeholder="Leave blank to keep current password"
/>
</div>
<div>
<label for="credentials-confirm-password" class="mb-1 block text-sm font-medium">Confirm new password</label>
<input
id="credentials-confirm-password"
type="password"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={confirmPassword}
autocomplete="new-password"
minlength={8}
/>
</div>
{#if error}
<p class="text-sm text-danger">{error}</p>
{/if}
<DialogFooter>
<Button type="submit" disabled={saving}>
{saving ? 'Saving…' : 'Save'}
</Button>
<Button type="button" variant="secondary" onclick={() => (open = false)}>Dismiss</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
@@ -0,0 +1,68 @@
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import { getContext, setContext } from 'svelte';
import { fetchAuthStatus, login, logout, setupAccount, updateCredentials } from '$lib/api.js';
const AUTH_STATUS_KEY = ['AuthStatus'];
const AUTH_CONTEXT_KEY = Symbol('auth');
export function createAuthStore() {
const queryClient = useQueryClient();
const statusQuery = createQuery(() => ({
queryKey: AUTH_STATUS_KEY,
queryFn: fetchAuthStatus,
}));
const setupMutation = createMutation(() => ({
mutationFn: ({ username, password }) => setupAccount(username, password),
}));
const loginMutation = createMutation(() => ({
mutationFn: ({ username, password }) => login(username, password),
}));
const logoutMutation = createMutation(() => ({
mutationFn: () => logout(),
}));
const updateCredentialsMutation = createMutation(() => ({
mutationFn: (input) => updateCredentials(input),
}));
const refresh = () => queryClient.invalidateQueries({ queryKey: AUTH_STATUS_KEY });
const store = {
get status() {
return statusQuery.data;
},
get loading() {
return statusQuery.isLoading;
},
get error() {
return statusQuery.error;
},
async setup(username, password) {
await setupMutation.mutateAsync({ username, password });
await refresh();
},
async login(username, password) {
await loginMutation.mutateAsync({ username, password });
await refresh();
},
async logout() {
await logoutMutation.mutateAsync();
await refresh();
},
async updateCredentials(input) {
await updateCredentialsMutation.mutateAsync(input);
await refresh();
},
};
setContext(AUTH_CONTEXT_KEY, store);
return store;
}
export function useAuth() {
const ctx = getContext(AUTH_CONTEXT_KEY);
if (!ctx) {
throw new Error('useAuth() must be called within the root layout that calls createAuthStore()');
}
return ctx;
}
@@ -1,15 +1,29 @@
<script>
import { Tooltip } from 'bits-ui';
import Header from '$lib/components/Header.svelte';
import AuthPage from '$lib/features/auth/AuthPage.svelte';
import { createAuthStore } from '$lib/features/auth/auth.svelte.js';
let { children } = $props();
const auth = createAuthStore();
</script>
<Tooltip.Provider delayDuration={300}>
<div class="flex min-h-screen flex-col">
<Header />
<main class="flex min-w-0 flex-1 flex-col">
{@render children?.()}
</main>
</div>
{#if auth.loading}
<div class="flex min-h-screen items-center justify-center text-sm text-muted-fg">Loading…</div>
{:else if auth.error}
<div class="flex min-h-screen items-center justify-center px-4 text-sm text-danger">
{auth.error instanceof Error ? auth.error.message : 'Request failed.'}
</div>
{:else if !auth.status || auth.status.setupRequired || !auth.status.authenticated}
<AuthPage setupRequired={auth.status?.setupRequired ?? true} />
{:else}
<div class="flex min-h-screen flex-col">
<Header />
<main class="flex min-w-0 flex-1 flex-col">
{@render children?.()}
</main>
</div>
{/if}
</Tooltip.Provider>
@@ -1,10 +1,28 @@
<script>
import { Moon, Sun, SunMoon } from '@lucide/svelte';
import { LogOut, Moon, Sun, SunMoon, UserCog } from '@lucide/svelte';
import Button from '$lib/components/ui/button.svelte';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '$lib/components/ui/dialog';
import { themeState } from '$lib/theme.svelte.js';
import { useAuth } from '$lib/features/auth/auth.svelte.js';
import CredentialsDialog from '$lib/features/auth/CredentialsDialog.svelte';
let { open = $bindable(false) } = $props();
const auth = useAuth();
let credentialsOpen = $state(false);
// bits-ui dialogs don't nest cleanly (focus-trap/z-index conflicts), so close this one
// before opening the next, matching the pattern used elsewhere in this project series.
function openCredentials() {
open = false;
credentialsOpen = true;
}
async function handleLogout() {
open = false;
await auth.logout();
}
</script>
<Dialog bind:open>
@@ -47,8 +65,23 @@
</Button>
</div>
</div>
<div>
<span class="mb-2 block text-sm font-medium">Account</span>
<div class="flex flex-col gap-2">
<Button type="button" variant="secondary" class="justify-start gap-2" onclick={openCredentials}>
<UserCog class="size-4" />
Change username / password
</Button>
<Button type="button" variant="secondary" class="justify-start gap-2" onclick={handleLogout}>
<LogOut class="size-4" />
Log out
</Button>
</div>
</div>
<DialogFooter>
<Button type="button" variant="secondary" onclick={() => (open = false)}>Dismiss</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<CredentialsDialog bind:open={credentialsOpen} currentUsername={auth.status?.username ?? ''} />