From b150d835a1390335479bb8f64c0f73225cdcd06c Mon Sep 17 00:00:00 2001 From: Gabriel Date: Sat, 1 Aug 2026 12:51:02 +0200 Subject: [PATCH] feat(auth): implement session-based authentication and API token management - 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. --- CollabTableServer/.env.example | 26 +- CollabTableServer/Dockerfile | 3 - CollabTableServer/README.md | 69 ++- CollabTableServer/docker-compose.yml | 108 ++-- CollabTableServer/package-lock.json | 432 ++------------ CollabTableServer/package.json | 6 +- CollabTableServer/src/db.ts | 531 ++++++++---------- CollabTableServer/src/index.ts | 31 +- CollabTableServer/src/middleware/auth.ts | 155 ++--- CollabTableServer/src/routes/authRoutes.ts | 185 ++++++ CollabTableServer/src/routes/webRoutes.ts | 11 +- CollabTableServer/webui/src/lib/api.js | 49 +- .../src/lib/features/auth/AuthPage.svelte | 97 ++++ .../features/auth/CredentialsDialog.svelte | 109 ++++ .../src/lib/features/auth/auth.svelte.js | 68 +++ .../src/lib/features/layout/AppShell.svelte | 26 +- .../lib/features/layout/SettingsDialog.svelte | 35 +- README.md | 63 +-- 18 files changed, 1022 insertions(+), 982 deletions(-) create mode 100644 CollabTableServer/src/routes/authRoutes.ts create mode 100644 CollabTableServer/webui/src/lib/features/auth/AuthPage.svelte create mode 100644 CollabTableServer/webui/src/lib/features/auth/CredentialsDialog.svelte create mode 100644 CollabTableServer/webui/src/lib/features/auth/auth.svelte.js diff --git a/CollabTableServer/.env.example b/CollabTableServer/.env.example index e90ae72..48930a2 100644 --- a/CollabTableServer/.env.example +++ b/CollabTableServer/.env.example @@ -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 diff --git a/CollabTableServer/Dockerfile b/CollabTableServer/Dockerfile index 2f762ba..7795529 100644 --- a/CollabTableServer/Dockerfile +++ b/CollabTableServer/Dockerfile @@ -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 diff --git a/CollabTableServer/README.md b/CollabTableServer/README.md index 7e52c67..28b9011 100644 --- a/CollabTableServer/README.md +++ b/CollabTableServer/README.md @@ -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":"", "payload": { ...SyncRequest }}` → `{"type":"syncResponse", "id":"", "payload": { ...SyncResponse }}` -Authentication: If `SERVER_PASSWORD` is set, include header `Authorization: Bearer ` on HTTP and WebSocket requests. +Authentication: include header `Authorization: Bearer ` 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 ` 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 diff --git a/CollabTableServer/docker-compose.yml b/CollabTableServer/docker-compose.yml index ac6b221..ce81917 100644 --- a/CollabTableServer/docker-compose.yml +++ b/CollabTableServer/docker-compose.yml @@ -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 diff --git a/CollabTableServer/package-lock.json b/CollabTableServer/package-lock.json index ef86bfe..5fba58d 100644 --- a/CollabTableServer/package-lock.json +++ b/CollabTableServer/package-lock.json @@ -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", diff --git a/CollabTableServer/package.json b/CollabTableServer/package.json index e831527..e11a825 100644 --- a/CollabTableServer/package.json +++ b/CollabTableServer/package.json @@ -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" diff --git a/CollabTableServer/src/db.ts b/CollabTableServer/src/db.ts index 77a4b1c..c4c180c 100644 --- a/CollabTableServer/src/db.ts +++ b/CollabTableServer/src/db.ts @@ -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; - queryOne(sql: string, params?: Param[]): Promise; - execute(sql: string, params?: Param[]): Promise; - transaction(fn: (tx: DBAdapter) => Promise): Promise; - initialize(): Promise; -} - -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 { - // 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 { - const stmt = this.db.prepare(replaceQuotedIdentifiers(sql)); - return stmt.all(...params); - } - - async queryOne(sql: string, params: Param[] = []): Promise { - const stmt = this.db.prepare(replaceQuotedIdentifiers(sql)); - return stmt.get(...params); - } - - async execute(sql: string, params: Param[] = []): Promise { - const stmt = this.db.prepare(replaceQuotedIdentifiers(sql)); - const res = stmt.run(...params); - return { changes: res.changes || 0 }; - } - - async transaction(fn: (tx: DBAdapter) => Promise): Promise { - const tx = this.db.transaction((innerFn: (tx: DBAdapter) => Promise) => { - // 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 { - // 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> { - // 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 { - const res = await this.runQuery(sql, params); - return res.rows; - } - - async queryOne(sql: string, params: Param[] = []): Promise { - const res = await this.runQuery(sql, params); - return res.rows[0]; - } - - async execute(sql: string, params: Param[] = []): Promise { - const res = await this.runQuery(sql, params); - return { changes: res.rowCount || 0 }; - } - - async transaction(fn: (tx: DBAdapter) => Promise): Promise { - 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; + queryOne(sql: string, params?: Param[]): Promise; + execute(sql: string, params?: Param[]): Promise; + transaction(fn: (tx: DBAdapter) => Promise): Promise; + initialize(): Promise; +} + +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 { + // 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> { + // 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 { + const res = await this.runQuery(sql, params); + return res.rows; + } + + async queryOne(sql: string, params: Param[] = []): Promise { + const res = await this.runQuery(sql, params); + return res.rows[0]; + } + + async execute(sql: string, params: Param[] = []): Promise { + const res = await this.runQuery(sql, params); + return { changes: res.rowCount || 0 }; + } + + async transaction(fn: (tx: DBAdapter) => Promise): Promise { + 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 }; diff --git a/CollabTableServer/src/index.ts b/CollabTableServer/src/index.ts index e4989a0..8b89cdc 100644 --- a/CollabTableServer/src/index.ts +++ b/CollabTableServer/src/index.ts @@ -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); diff --git a/CollabTableServer/src/middleware/auth.ts b/CollabTableServer/src/middleware/auth.ts index cc5c154..d480970 100644 --- a/CollabTableServer/src/middleware/auth.ts +++ b/CollabTableServer/src/middleware/auth.ts @@ -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(); -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 ") - 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 ' - }); - } - - 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(); +} diff --git a/CollabTableServer/src/routes/authRoutes.ts b/CollabTableServer/src/routes/authRoutes.ts new file mode 100644 index 0000000..b26ee23 --- /dev/null +++ b/CollabTableServer/src/routes/authRoutes.ts @@ -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; diff --git a/CollabTableServer/src/routes/webRoutes.ts b/CollabTableServer/src/routes/webRoutes.ts index 0a0a1ba..827e291 100644 --- a/CollabTableServer/src/routes/webRoutes.ts +++ b/CollabTableServer/src/routes/webRoutes.ts @@ -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'); diff --git a/CollabTableServer/webui/src/lib/api.js b/CollabTableServer/webui/src/lib/api.js index 4967fcb..93209bc 100644 --- a/CollabTableServer/webui/src/lib/api.js +++ b/CollabTableServer/webui/src/lib/api.js @@ -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: "", message: "" } - + // 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 }), + }); +} diff --git a/CollabTableServer/webui/src/lib/features/auth/AuthPage.svelte b/CollabTableServer/webui/src/lib/features/auth/AuthPage.svelte new file mode 100644 index 0000000..273f49e --- /dev/null +++ b/CollabTableServer/webui/src/lib/features/auth/AuthPage.svelte @@ -0,0 +1,97 @@ + + +
+
+
+ +

CollabTable

+

+ {setupRequired ? 'Create the admin account for this dashboard.' : 'Sign in to view this dashboard.'} +

+
+ +
+
+ + + +
+
+ + +
+ {#if setupRequired} +
+ + +
+ {/if} + {#if error} +

{error}

+ {/if} + +
+
+
diff --git a/CollabTableServer/webui/src/lib/features/auth/CredentialsDialog.svelte b/CollabTableServer/webui/src/lib/features/auth/CredentialsDialog.svelte new file mode 100644 index 0000000..1cd6cd5 --- /dev/null +++ b/CollabTableServer/webui/src/lib/features/auth/CredentialsDialog.svelte @@ -0,0 +1,109 @@ + + + + + + Account + +
+

Changing your credentials will sign you out everywhere.

+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ {#if error} +

{error}

+ {/if} + + + + +
+
+
diff --git a/CollabTableServer/webui/src/lib/features/auth/auth.svelte.js b/CollabTableServer/webui/src/lib/features/auth/auth.svelte.js new file mode 100644 index 0000000..d6a4f0f --- /dev/null +++ b/CollabTableServer/webui/src/lib/features/auth/auth.svelte.js @@ -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; +} diff --git a/CollabTableServer/webui/src/lib/features/layout/AppShell.svelte b/CollabTableServer/webui/src/lib/features/layout/AppShell.svelte index f21e359..dab5782 100644 --- a/CollabTableServer/webui/src/lib/features/layout/AppShell.svelte +++ b/CollabTableServer/webui/src/lib/features/layout/AppShell.svelte @@ -1,15 +1,29 @@ -
-
-
- {@render children?.()} -
-
+ {#if auth.loading} +
Loading…
+ {:else if auth.error} +
+ {auth.error instanceof Error ? auth.error.message : 'Request failed.'} +
+ {:else if !auth.status || auth.status.setupRequired || !auth.status.authenticated} + + {:else} +
+
+
+ {@render children?.()} +
+
+ {/if}
diff --git a/CollabTableServer/webui/src/lib/features/layout/SettingsDialog.svelte b/CollabTableServer/webui/src/lib/features/layout/SettingsDialog.svelte index ba1c41d..3e7600d 100644 --- a/CollabTableServer/webui/src/lib/features/layout/SettingsDialog.svelte +++ b/CollabTableServer/webui/src/lib/features/layout/SettingsDialog.svelte @@ -1,10 +1,28 @@ @@ -47,8 +65,23 @@ +
+ Account +
+ + +
+
+ + diff --git a/README.md b/README.md index c39afbc..9412f93 100644 --- a/README.md +++ b/README.md @@ -64,23 +64,18 @@ CollabTable allows multiple users to collaboratively create and manage lists wit ```bash cp .env.example .env ``` - -3. **Configure authentication (optional):** - Edit `.env` and set `SERVER_PASSWORD` for API protection: - ```env - SERVER_PASSWORD=your_secure_password - ``` -4. **Start the server:** +3. **Start the server (this also starts a bundled PostgreSQL container):** ```bash docker-compose up -d ``` -Server runs on `http://localhost:3000` +Server runs on `http://localhost:3000`. Open it in a browser to create the admin account, +then generate an API token from the dashboard's Settings page for your sync clients/devices +— see `CollabTableServer/README.md`'s "Authentication" section for details. -**Database Options:** -- SQLite (default): Data persists in Docker volume `sqlite_data` -- PostgreSQL: Configure in `.env` with `DB_CLIENT=postgres` +**Database:** PostgreSQL, provisioned automatically via the bundled `postgres` service in +`docker-compose.yml`. ### Android App @@ -148,19 +143,19 @@ CollabTable/ - **Runtime:** Node.js 20+ - **Framework:** Express.js - **Language:** TypeScript -- **Database:** SQLite (better-sqlite3) or PostgreSQL (pg) +- **Database:** PostgreSQL (pg) - **Containerization:** Docker & Docker Compose - **Real-time:** WebSocket support ## API Endpoints -All endpoints are prefixed with `/api/` and can be protected with optional authentication. - -### Authentication -If `SERVER_PASSWORD` is set in the server's `.env` file, include this header in all requests: +All endpoints are prefixed with `/api/`. The sync/collaboration endpoints below (Lists, +Fields, Items, sync) require an API token generated from the web dashboard's Settings page: ``` -Authorization: Bearer your_password_here +Authorization: Bearer your_api_token_here ``` +The dashboard itself has its own separate single-admin-account login (session cookie, not a +bearer token) — see `CollabTableServer/README.md`'s "Authentication" section. ### Lists - `GET /api/lists` - Get all lists @@ -444,27 +439,10 @@ Response: ### Data Persistence -**SQLite (Default)** -- Database stored in Docker volume: `sqlite_data` -- Persists across container restarts -- Backup database: - ```bash - # Using container name (set in docker-compose.yml) - docker cp collabtable-server:/data/collabtable.db ./backup.db - - # Or using docker-compose (if in server directory) - docker-compose exec server cat /data/collabtable.db > ./backup.db - ``` -- Restore database: - ```bash - docker cp ./backup.db collabtable-server:/data/collabtable.db - docker-compose restart - ``` - **PostgreSQL** -- Configure in `.env`: `DB_CLIENT=postgres` - Use standard PostgreSQL backup tools (`pg_dump`, `pg_restore`) -- Docker volume manages persistence automatically +- The bundled `postgres` service's data is stored in a named Docker volume (`pg_data`), which + persists across container restarts ### Docker Commands @@ -498,16 +476,15 @@ docker ps **Environment Variables** Configure these in `.env` or docker-compose.yml: ```env -PORT=3000 # Server port -NODE_ENV=production # Environment -SERVER_PASSWORD=your_secure_pass # API authentication (recommended) -DB_CLIENT=sqlite # Database: sqlite or postgres -DB_PATH=/data/collabtable.db # SQLite path (in container) +PORT=3000 # Server port +NODE_ENV=production # Environment +DATABASE_URL=postgres://user:pass@postgres:5432/collabtable +COOKIE_SECURE=true # Requires HTTPS ``` **Security Recommendations** -1. Set `SERVER_PASSWORD` for production -2. Use HTTPS with a reverse proxy (nginx, Caddy) +1. Generate the admin account and an API token on first run (see "Authentication" above) +2. Use HTTPS with a reverse proxy (nginx, Caddy), and set `COOKIE_SECURE=true` 3. Regular database backups 4. Keep Docker images updated 5. Restrict network access to server ports