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 PORT=3000
NODE_ENV=production 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 # PostgreSQL configuration
# - 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)
# You can either provide a single DATABASE_URL or the PG* variables below # You can either provide a single DATABASE_URL or the PG* variables below
################################################################# #################################################################
# Example URL: postgres://user:password@localhost:5432/collabtable # Example URL: postgres://user:password@localhost:5432/collabtable
@@ -35,7 +22,7 @@ PGPASSWORD=
PGDATABASE=collabtable 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 in milliseconds (default: 5000)
DB_INIT_RETRY_INTERVAL_MS=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) # Max DB init retry attempts. 0 means retry forever (default: 0)
DB_INIT_RETRY_MAX_ATTEMPTS=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) # 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. # Keep this at 0 to prevent future-dated rows from being re-sent in hot loops.
SYNC_MAX_FUTURE_SKEW_MS=0 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/) # Built webui, served by webRoutes.ts from ./web (sibling of dist/)
COPY --from=webui-builder /webui/build ./web COPY --from=webui-builder /webui/build ./web
# Create data directory for SQLite
RUN mkdir -p /data
# Expose port # Expose port
EXPOSE 3000 EXPOSE 3000
+32 -37
View File
@@ -1,19 +1,21 @@
# CollabTable Server # 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 ## Features
- RESTful API for managing lists, fields, items, and values - RESTful API for managing lists, fields, items, and values
- Real-time synchronization via WebSocket (primary) with HTTP fallback - 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 - Dockerized deployment with persistent storage
- TypeScript for type safety - TypeScript for type safety
## Prerequisites ## Prerequisites
- Docker and Docker Compose - 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 ## Quick Start with Docker
@@ -28,14 +30,13 @@ A collaborative table management server built with Node.js, Express, TypeScript,
cp .env.example .env cp .env.example .env
``` ```
4. Start the services: 4. Start the services (this also starts a bundled PostgreSQL container):
```bash ```bash
docker-compose up -d docker-compose up -d
``` ```
The server will be available at `http://localhost:3000` 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.
**Important:** The default backend is SQLite with a Docker volume `sqlite_data` for persistence. You can also switch to PostgreSQL by setting environment variables.
## Local Development ## Local Development
@@ -49,21 +50,18 @@ The server will be available at `http://localhost:3000`
cp .env.example .env 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) DATABASE_URL=postgres://user:password@localhost:5432/collabtable
DB_CLIENT=sqlite # OR, as discrete variables:
# SQLite
DB_PATH=./data/collabtable.db
# OR PostgreSQL
# DATABASE_URL=postgres://user:password@localhost:5432/collabtable
# PGHOST=localhost # PGHOST=localhost
# PGPORT=5432 # PGPORT=5432
# PGUSER=postgres # PGUSER=postgres
# PGPASSWORD=yourpassword # PGPASSWORD=yourpassword
# PGDATABASE=collabtable # PGDATABASE=collabtable
# Set to "true" once served over HTTPS
COOKIE_SECURE=false
``` ```
4. Start the development server: 4. Start the development server:
@@ -102,7 +100,7 @@ The server will be available at `http://localhost:3000`
- `{"type":"ping"}` → `{"type":"pong"}` - `{"type":"ping"}` → `{"type":"pong"}`
- `{"type":"sync", "id":"<uuid>", "payload": { ...SyncRequest }}` → `{"type":"syncResponse", "id":"<uuid>", "payload": { ...SyncResponse }}` - `{"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 ### Health Check
- `GET /health` - Check server health - `GET /health` - Check server health
@@ -225,34 +223,31 @@ docker-compose up -d --build
- `PORT` - Server port (default: 3000) - `PORT` - Server port (default: 3000)
- `NODE_ENV` - Environment (development/production) - `NODE_ENV` - Environment (development/production)
- `SERVER_PASSWORD` - Optional shared password for API and WebSocket (recommended) - `COOKIE_SECURE` - Set to `true` to mark the admin session cookie `Secure` (requires HTTPS); default `false`
- `DB_CLIENT` - `sqlite` (default) or `postgres`
- `DB_PATH` - Path to SQLite database file (default: ./data/collabtable.db for local, /data/collabtable.db in Docker)
- `DATABASE_URL` - PostgreSQL connection URL (optional alternative to PG* variables) - `DATABASE_URL` - PostgreSQL connection URL (optional alternative to PG* variables)
- `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE` - PostgreSQL connection parameters - `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_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`) - `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`) - `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 ## Data Persistence
### SQLite Use your normal PostgreSQL backup/restore procedures (e.g., `pg_dump`, `pg_restore`). If
The SQLite database file is stored in a Docker volume, ensuring data persists across container lifecycle events. using the bundled Dockerized Postgres service, the data is stored in a named volume (see
`docker-compose.yml`).
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`).
## License ## License
+50 -58
View File
@@ -1,58 +1,50 @@
version: '3.8' version: '3.8'
services: services:
server: postgres:
build: . image: postgres:17-alpine
container_name: collabtable-server container_name: collabtable-postgres
restart: unless-stopped restart: unless-stopped
environment: environment:
- PORT=3000 - POSTGRES_DB=collabtable
- NODE_ENV=production - POSTGRES_USER=collabtable
# Authentication (optional but recommended) - POSTGRES_PASSWORD=collabtable
- SERVER_PASSWORD=change_me volumes:
# Database selection: sqlite | postgres (default sqlite) - pg_data:/var/lib/postgresql/data
- DB_CLIENT=sqlite networks:
# SQLite path (used when DB_CLIENT=sqlite) - collabtable-network
- DB_PATH=/data/collabtable.db healthcheck:
# Retry DB initialization instead of crashing immediately on startup races test: ["CMD-SHELL", "pg_isready -U collabtable"]
- DB_INIT_RETRY_INTERVAL_MS=5000 interval: 10s
- DB_INIT_RETRY_MAX_ATTEMPTS=0 timeout: 5s
# Clamp future client timestamps during sync to avoid resend loops retries: 5
- SYNC_MAX_FUTURE_SKEW_MS=0
# PostgreSQL (used when DB_CLIENT=postgres) - choose either DATABASE_URL or the PG* vars server:
# - DATABASE_URL=postgres://user:password@postgres:5432/collabtable build: .
# - PGHOST=postgres container_name: collabtable-server
# - PGPORT=5432 restart: unless-stopped
# - PGUSER=postgres environment:
# - PGPASSWORD=yourpassword - PORT=3000
# - PGDATABASE=collabtable - NODE_ENV=production
ports: # Session cookie for the admin web dashboard (see src/routes/authRoutes.ts)
- "3000:3000" - COOKIE_SECURE=false
volumes: # Retry DB initialization instead of crashing immediately on startup races
- sqlite_data:/data - DB_INIT_RETRY_INTERVAL_MS=5000
networks: - DB_INIT_RETRY_MAX_ATTEMPTS=0
- collabtable-network # Clamp future client timestamps during sync to avoid resend loops
- SYNC_MAX_FUTURE_SKEW_MS=0
# Optional PostgreSQL database - DATABASE_URL=postgres://collabtable:collabtable@postgres:5432/collabtable
# postgres: ports:
# image: postgres:16-alpine - "3000:3000"
# container_name: collabtable-postgres depends_on:
# restart: unless-stopped postgres:
# environment: condition: service_healthy
# - POSTGRES_DB=collabtable networks:
# - POSTGRES_USER=postgres - collabtable-network
# - POSTGRES_PASSWORD=yourpassword
# ports: volumes:
# - "5432:5432" pg_data:
# volumes:
# - pg_data:/var/lib/postgresql/data networks:
# networks: collabtable-network:
# - collabtable-network driver: bridge
volumes:
sqlite_data:
# pg_data:
networks:
collabtable-network:
driver: bridge
+47 -385
View File
@@ -11,7 +11,8 @@
"dependencies": { "dependencies": {
"@typescript-eslint/eslint-plugin": "^7.0.2", "@typescript-eslint/eslint-plugin": "^7.0.2",
"@typescript-eslint/parser": "^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", "cors": "^2.8.5",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"eslint": "^8.57.0", "eslint": "^8.57.0",
@@ -21,7 +22,8 @@
"prettier": "^3.3.3" "prettier": "^3.3.3"
}, },
"devDependencies": { "devDependencies": {
"@types/better-sqlite3": "^7.6.11", "@types/bcryptjs": "^2.4.6",
"@types/cookie-parser": "^1.4.7",
"@types/cors": "^2.8.17", "@types/cors": "^2.8.17",
"@types/express": "^4.17.21", "@types/express": "^4.17.21",
"@types/node": "^20.10.6", "@types/node": "^20.10.6",
@@ -286,15 +288,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/better-sqlite3": { "node_modules/@types/bcryptjs": {
"version": "7.6.13", "version": "2.4.6",
"resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz", "resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz",
"integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==", "integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT"
"dependencies": {
"@types/node": "*"
}
}, },
"node_modules/@types/body-parser": { "node_modules/@types/body-parser": {
"version": "1.19.6", "version": "1.19.6",
@@ -317,6 +316,16 @@
"@types/node": "*" "@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": { "node_modules/@types/cors": {
"version": "2.8.19", "version": "2.8.19",
"resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz", "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz",
@@ -869,37 +878,12 @@
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/base64-js": { "node_modules/bcryptjs": {
"version": "1.5.1", "version": "2.4.3",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", "integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==",
"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" "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": { "node_modules/binary-extensions": {
"version": "2.3.0", "version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
@@ -913,26 +897,6 @@
"url": "https://github.com/sponsors/sindresorhus" "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": { "node_modules/body-parser": {
"version": "1.20.3", "version": "1.20.3",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz",
@@ -979,30 +943,6 @@
"node": ">=8" "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": { "node_modules/buffer-from": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
@@ -1098,12 +1038,6 @@
"fsevents": "~2.3.2" "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": { "node_modules/color-convert": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -1158,6 +1092,28 @@
"node": ">= 0.6" "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": { "node_modules/cookie-signature": {
"version": "1.0.6", "version": "1.0.6",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
@@ -1207,30 +1163,6 @@
"ms": "2.0.0" "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": { "node_modules/deep-is": {
"version": "0.1.4", "version": "0.1.4",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
@@ -1256,15 +1188,6 @@
"npm": "1.2.8000 || >= 1.4.16" "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": { "node_modules/diff": {
"version": "4.0.2", "version": "4.0.2",
"resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz",
@@ -1350,15 +1273,6 @@
"node": ">= 0.8" "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": { "node_modules/es-define-property": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
@@ -1606,15 +1520,6 @@
"node": ">= 0.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": { "node_modules/express": {
"version": "4.21.2", "version": "4.21.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz", "resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz",
@@ -1716,12 +1621,6 @@
"node": "^10.12.0 || >=12.0.0" "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": { "node_modules/fill-range": {
"version": "7.1.1", "version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@@ -1822,12 +1721,6 @@
"node": ">= 0.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": { "node_modules/fs.realpath": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
@@ -1895,12 +1788,6 @@
"node": ">= 0.4" "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": { "node_modules/glob": {
"version": "7.2.3", "version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
@@ -2048,26 +1935,6 @@
"node": ">=0.10.0" "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": { "node_modules/ignore": {
"version": "5.3.2", "version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
@@ -2119,12 +1986,6 @@
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC" "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": { "node_modules/ipaddr.js": {
"version": "1.9.1", "version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
@@ -2379,18 +2240,6 @@
"node": ">= 0.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": { "node_modules/minimatch": {
"version": "3.1.2", "version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
@@ -2407,6 +2256,7 @@
"version": "1.2.8", "version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"dev": true,
"license": "MIT", "license": "MIT",
"funding": { "funding": {
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
@@ -2425,24 +2275,12 @@
"node": ">=10" "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": { "node_modules/ms": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT" "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": { "node_modules/natural-compare": {
"version": "1.4.0", "version": "1.4.0",
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
@@ -2458,18 +2296,6 @@
"node": ">= 0.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": { "node_modules/normalize-path": {
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
@@ -2779,32 +2605,6 @@
"node": ">=0.10.0" "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": { "node_modules/prelude-ls": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
@@ -2842,16 +2642,6 @@
"node": ">= 0.10" "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": { "node_modules/punycode": {
"version": "2.3.1", "version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@@ -2920,35 +2710,6 @@
"node": ">= 0.8" "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": { "node_modules/readdirp": {
"version": "3.6.0", "version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
@@ -3230,51 +2991,6 @@
"url": "https://github.com/sponsors/ljharb" "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": { "node_modules/slash": {
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz",
@@ -3323,15 +3039,6 @@
"node": ">= 0.8" "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": { "node_modules/strip-ansi": {
"version": "6.0.1", "version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
@@ -3358,6 +3065,7 @@
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
"integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
@@ -3388,34 +3096,6 @@
"url": "https://github.com/sponsors/ljharb" "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": { "node_modules/text-table": {
"version": "0.2.0", "version": "0.2.0",
"resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz",
@@ -3557,18 +3237,6 @@
"strip-json-comments": "^2.0.0" "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": { "node_modules/type-check": {
"version": "0.4.0", "version": "0.4.0",
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
@@ -3644,12 +3312,6 @@
"punycode": "^2.1.0" "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": { "node_modules/utils-merge": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
+4 -2
View File
@@ -17,7 +17,8 @@
"dependencies": { "dependencies": {
"express": "^4.18.2", "express": "^4.18.2",
"cors": "^2.8.5", "cors": "^2.8.5",
"better-sqlite3": "^11.0.0", "cookie-parser": "^1.4.6",
"bcryptjs": "^2.4.3",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"@typescript-eslint/eslint-plugin": "^7.0.2", "@typescript-eslint/eslint-plugin": "^7.0.2",
"@typescript-eslint/parser": "^7.0.2", "@typescript-eslint/parser": "^7.0.2",
@@ -29,8 +30,9 @@
"devDependencies": { "devDependencies": {
"@types/express": "^4.17.21", "@types/express": "^4.17.21",
"@types/cors": "^2.8.17", "@types/cors": "^2.8.17",
"@types/cookie-parser": "^1.4.7",
"@types/bcryptjs": "^2.4.6",
"@types/node": "^20.10.6", "@types/node": "^20.10.6",
"@types/better-sqlite3": "^7.6.11",
"@types/pg": "^8.10.2", "@types/pg": "^8.10.2",
"typescript": "5.5.4", "typescript": "5.5.4",
"ts-node-dev": "^2.0.0" "ts-node-dev": "^2.0.0"
+227 -304
View File
@@ -1,304 +1,227 @@
import dotenv from 'dotenv'; import dotenv from 'dotenv';
import BetterSqlite3, { Database as SqliteDB } from 'better-sqlite3'; import { Pool, PoolClient, QueryResult, types as pgTypes } from 'pg';
import { Pool, PoolClient, QueryResult, types as pgTypes } from 'pg';
import path from 'path'; dotenv.config();
import fs from 'fs';
type Param = any;
dotenv.config();
type ExecResult = { changes: number };
type Param = any;
type ExecResult = { changes: number }; interface DBAdapter {
queryAll(sql: string, params?: Param[]): Promise<any[]>;
queryOne(sql: string, params?: Param[]): Promise<any | undefined>;
interface DBAdapter { execute(sql: string, params?: Param[]): Promise<ExecResult>;
queryAll(sql: string, params?: Param[]): Promise<any[]>; transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T>;
queryOne(sql: string, params?: Param[]): Promise<any | undefined>; initialize(): Promise<void>;
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 ensureDataDir(dbPath: string) { }
const dir = path.dirname(dbPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); function convertQMarksToPg(sql: string) {
} // Replace each ? with $1, $2, ...
let idx = 0;
function replaceQuotedIdentifiers(sql: string) { return sql.replace(/\?/g, () => `$${++idx}`);
// Convert backticks to double quotes for portability }
return sql.replace(/`([^`]+)`/g, '"$1"');
} // ---------- Postgres Adapter ----------
class PostgresAdapter implements DBAdapter {
function convertQMarksToPg(sql: string) { private pool: Pool;
// Replace each ? with $1, $2, ...
let idx = 0; constructor() {
return sql.replace(/\?/g, () => `$${++idx}`); // 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));
// ---------- SQLite Adapter (wrapped async) ---------- const connectionString = process.env.DATABASE_URL;
class SqliteAdapter implements DBAdapter { if (connectionString) {
private db: SqliteDB; this.pool = new Pool({ connectionString });
} else {
constructor() { this.pool = new Pool({
const DB_PATH = process.env.DB_PATH || './data/collabtable.db'; host: process.env.PGHOST || 'localhost',
ensureDataDir(DB_PATH); port: parseInt(process.env.PGPORT || '5432', 10),
this.db = new BetterSqlite3(DB_PATH); user: process.env.PGUSER || 'postgres',
this.db.pragma('foreign_keys = ON'); password: process.env.PGPASSWORD || '',
} database: process.env.PGDATABASE || 'collabtable'
});
async initialize(): Promise<void> { }
// Create tables and indexes }
this.db.exec(`
CREATE TABLE IF NOT EXISTS lists ( async initialize(): Promise<void> {
id TEXT PRIMARY KEY, // Create tables if not exist
name TEXT NOT NULL, const client = await this.pool.connect();
createdAt INTEGER NOT NULL, try {
updatedAt INTEGER NOT NULL, await client.query('BEGIN');
isDeleted INTEGER DEFAULT 0 await client.query(`
); CREATE TABLE IF NOT EXISTS lists (
id TEXT PRIMARY KEY,
CREATE TABLE IF NOT EXISTS fields ( name TEXT NOT NULL,
id TEXT PRIMARY KEY, createdAt BIGINT NOT NULL,
name TEXT NOT NULL, updatedAt BIGINT NOT NULL,
fieldType TEXT NOT NULL, isDeleted INTEGER DEFAULT 0
fieldOptions TEXT, );
alignment TEXT NOT NULL DEFAULT 'start', `);
listId TEXT NOT NULL, await client.query(`
"order" INTEGER NOT NULL, CREATE TABLE IF NOT EXISTS fields (
createdAt INTEGER NOT NULL, id TEXT PRIMARY KEY,
updatedAt INTEGER NOT NULL, name TEXT NOT NULL,
isDeleted INTEGER DEFAULT 0, fieldType TEXT NOT NULL,
FOREIGN KEY (listId) REFERENCES lists(id) fieldOptions TEXT,
); alignment TEXT NOT NULL DEFAULT 'start',
listId TEXT NOT NULL,
CREATE TABLE IF NOT EXISTS items ( "order" INTEGER NOT NULL,
id TEXT PRIMARY KEY, createdAt BIGINT NOT NULL,
listId TEXT NOT NULL, updatedAt BIGINT NOT NULL,
createdAt INTEGER NOT NULL, isDeleted INTEGER DEFAULT 0,
updatedAt INTEGER NOT NULL, FOREIGN KEY (listId) REFERENCES lists(id)
isDeleted INTEGER DEFAULT 0, );
FOREIGN KEY (listId) REFERENCES lists(id) `);
); await client.query(`
CREATE TABLE IF NOT EXISTS items (
CREATE TABLE IF NOT EXISTS item_values ( id TEXT PRIMARY KEY,
id TEXT PRIMARY KEY, listId TEXT NOT NULL,
itemId TEXT NOT NULL, createdAt BIGINT NOT NULL,
fieldId TEXT NOT NULL, updatedAt BIGINT NOT NULL,
value TEXT, isDeleted INTEGER DEFAULT 0,
updatedAt INTEGER NOT NULL, FOREIGN KEY (listId) REFERENCES lists(id)
FOREIGN KEY (itemId) REFERENCES items(id), );
FOREIGN KEY (fieldId) REFERENCES fields(id) `);
); await client.query(`
CREATE TABLE IF NOT EXISTS item_values (
CREATE INDEX IF NOT EXISTS idx_fields_listId ON fields(listId); id TEXT PRIMARY KEY,
CREATE INDEX IF NOT EXISTS idx_items_listId ON items(listId); itemId TEXT NOT NULL,
CREATE INDEX IF NOT EXISTS idx_item_values_itemId ON item_values(itemId); fieldId TEXT NOT NULL,
CREATE INDEX IF NOT EXISTS idx_item_values_fieldId ON item_values(fieldId); value TEXT,
updatedAt BIGINT NOT NULL,
-- Notification events table (for remote-change notifications) FOREIGN KEY (itemId) REFERENCES items(id),
CREATE TABLE IF NOT EXISTS notifications ( FOREIGN KEY (fieldId) REFERENCES fields(id)
id TEXT PRIMARY KEY, );
deviceIdOrigin TEXT, `);
eventType TEXT NOT NULL, await client.query(`CREATE INDEX IF NOT EXISTS idx_fields_listId ON fields(listId);`);
entityType TEXT NOT NULL, await client.query(`CREATE INDEX IF NOT EXISTS idx_items_listId ON items(listId);`);
entityId TEXT, await client.query(`CREATE INDEX IF NOT EXISTS idx_item_values_itemId ON item_values(itemId);`);
listId TEXT, await client.query(`CREATE INDEX IF NOT EXISTS idx_item_values_fieldId ON item_values(fieldId);`);
createdAt INTEGER NOT NULL // Notifications table
); await client.query(`
CREATE INDEX IF NOT EXISTS idx_notifications_createdAt ON notifications(createdAt); CREATE TABLE IF NOT EXISTS notifications (
CREATE INDEX IF NOT EXISTS idx_notifications_listId ON notifications(listId); id TEXT PRIMARY KEY,
`); deviceIdOrigin TEXT,
// Attempt to add alignment column if upgrading an existing DB (ignore error if exists) eventType TEXT NOT NULL,
try { entityType TEXT NOT NULL,
this.db.exec(`ALTER TABLE fields ADD COLUMN alignment TEXT NOT NULL DEFAULT 'start'`); entityId TEXT,
} catch (e) { listId TEXT,
// Column may already exist; ignore createdAt BIGINT NOT NULL
} );
} `);
await client.query(`CREATE INDEX IF NOT EXISTS idx_notifications_createdAt ON notifications(createdAt);`);
async queryAll(sql: string, params: Param[] = []): Promise<any[]> { await client.query(`CREATE INDEX IF NOT EXISTS idx_notifications_listId ON notifications(listId);`);
const stmt = this.db.prepare(replaceQuotedIdentifiers(sql)); // Migrate existing DBs: ensure alignment column exists
return stmt.all(...params); 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) ----
async queryOne(sql: string, params: Param[] = []): Promise<any | undefined> { // Matches the Bitmagnet/UnraidMonitor pattern: opaque session-cookie tokens (no JWT),
const stmt = this.db.prepare(replaceQuotedIdentifiers(sql)); // bcrypt-hashed passwords, schema created idempotently on every startup.
return stmt.get(...params); await client.query(`
} CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY,
async execute(sql: string, params: Param[] = []): Promise<ExecResult> { username TEXT NOT NULL UNIQUE,
const stmt = this.db.prepare(replaceQuotedIdentifiers(sql)); password_hash TEXT NOT NULL,
const res = stmt.run(...params); created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
return { changes: res.changes || 0 }; updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
} );
`);
async transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T> { // Enforces a single admin account, matching a single-tenant dashboard.
const tx = this.db.transaction((innerFn: (tx: DBAdapter) => Promise<T>) => { await client.query(`
// We can reuse the same adapter since better-sqlite3 is transactional per connection CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
return innerFn(this); `);
}); await client.query(`
return tx(fn); 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,
// ---------- Postgres Adapter ---------- expires_at TIMESTAMPTZ NOT NULL,
class PostgresAdapter implements DBAdapter { created_at TIMESTAMPTZ NOT NULL DEFAULT now()
private pool: Pool; );
`);
constructor() { await client.query(`CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);`);
// Ensure BIGINT (int8) is parsed as number to avoid string timestamps await client.query(`CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);`);
// OID 20 = INT8, OID 1700 = NUMERIC (keep default for now) // Long-lived credential for sync clients/devices (replaces the old optional
pgTypes.setTypeParser(20, (val: string) => parseInt(val, 10)); // SERVER_PASSWORD scheme, which silently disabled auth entirely when unset). Only
const connectionString = process.env.DATABASE_URL; // the SHA-256 hash is stored; the raw token is shown once, at creation/regeneration.
if (connectionString) { await client.query(`
this.pool = new Pool({ connectionString }); CREATE TABLE IF NOT EXISTS api_tokens (
} else { id BIGSERIAL PRIMARY KEY,
this.pool = new Pool({ user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
host: process.env.PGHOST || 'localhost', token_hash TEXT NOT NULL UNIQUE,
port: parseInt(process.env.PGPORT || '5432', 10), created_at TIMESTAMPTZ NOT NULL DEFAULT now()
user: process.env.PGUSER || 'postgres', );
password: process.env.PGPASSWORD || '', `);
database: process.env.PGDATABASE || 'collabtable' 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');
async initialize(): Promise<void> { throw e;
// Create tables if not exist, keeping schema aligned with sqlite (isDeleted INTEGER 0/1) } finally {
const client = await this.pool.connect(); client.release();
try { }
await client.query('BEGIN'); }
await client.query(`
CREATE TABLE IF NOT EXISTS lists ( private async runQuery(sql: string, params: Param[] = [], client?: PoolClient): Promise<QueryResult<any>> {
id TEXT PRIMARY KEY, // Replace backticks and convert ? to $1..$n
name TEXT NOT NULL, const text = convertQMarksToPg(replaceQuotedIdentifiers(sql));
createdAt BIGINT NOT NULL, const runner: Pool | PoolClient = client || this.pool;
updatedAt BIGINT NOT NULL, return runner.query(text, params);
isDeleted INTEGER DEFAULT 0 }
);
`); async queryAll(sql: string, params: Param[] = []): Promise<any[]> {
await client.query(` const res = await this.runQuery(sql, params);
CREATE TABLE IF NOT EXISTS fields ( return res.rows;
id TEXT PRIMARY KEY, }
name TEXT NOT NULL,
fieldType TEXT NOT NULL, async queryOne(sql: string, params: Param[] = []): Promise<any | undefined> {
fieldOptions TEXT, const res = await this.runQuery(sql, params);
alignment TEXT NOT NULL DEFAULT 'start', return res.rows[0];
listId TEXT NOT NULL, }
"order" INTEGER NOT NULL,
createdAt BIGINT NOT NULL, async execute(sql: string, params: Param[] = []): Promise<ExecResult> {
updatedAt BIGINT NOT NULL, const res = await this.runQuery(sql, params);
isDeleted INTEGER DEFAULT 0, return { changes: res.rowCount || 0 };
FOREIGN KEY (listId) REFERENCES lists(id) }
);
`); async transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T> {
await client.query(` const client = await this.pool.connect();
CREATE TABLE IF NOT EXISTS items ( try {
id TEXT PRIMARY KEY, await client.query('BEGIN');
listId TEXT NOT NULL, const txAdapter: DBAdapter = {
createdAt BIGINT NOT NULL, initialize: async () => {},
updatedAt BIGINT NOT NULL, queryAll: (sql, params) => this.runQuery(sql, params, client).then(r => r.rows),
isDeleted INTEGER DEFAULT 0, queryOne: (sql, params) => this.runQuery(sql, params, client).then(r => r.rows[0]),
FOREIGN KEY (listId) REFERENCES lists(id) 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
await client.query(` return inner(txAdapter);
CREATE TABLE IF NOT EXISTS item_values ( }
id TEXT PRIMARY KEY, } as DBAdapter;
itemId TEXT NOT NULL, const result = await fn(txAdapter);
fieldId TEXT NOT NULL, await client.query('COMMIT');
value TEXT, return result;
updatedAt BIGINT NOT NULL, } catch (e) {
FOREIGN KEY (itemId) REFERENCES items(id), await client.query('ROLLBACK');
FOREIGN KEY (fieldId) REFERENCES fields(id) throw e;
); } finally {
`); client.release();
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 export const dbEngine = 'PostgreSQL';
await client.query(` export const dbAdapter: DBAdapter = new PostgresAdapter();
CREATE TABLE IF NOT EXISTS notifications (
id TEXT PRIMARY KEY, export async function initializeDatabase() {
deviceIdOrigin TEXT, await dbAdapter.initialize();
eventType TEXT NOT NULL, }
entityType TEXT NOT NULL,
entityId TEXT, export type { DBAdapter };
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 };
+18 -13
View File
@@ -1,9 +1,11 @@
import express from 'express'; import express from 'express';
import cors from 'cors'; import cors from 'cors';
import cookieParser from 'cookie-parser';
import dotenv from 'dotenv'; import dotenv from 'dotenv';
import { initializeDatabase } from './db'; import { initializeDatabase } from './db';
import { authenticatePassword } from './middleware/auth'; import { requireApiToken } from './middleware/auth';
import { deviceIdMiddleware } from './middleware/device'; import { deviceIdMiddleware } from './middleware/device';
import authRoutes from './routes/authRoutes';
import listRoutes from './routes/listRoutes'; import listRoutes from './routes/listRoutes';
import fieldRoutes from './routes/fieldRoutes'; import fieldRoutes from './routes/fieldRoutes';
import itemRoutes from './routes/itemRoutes'; import itemRoutes from './routes/itemRoutes';
@@ -51,27 +53,35 @@ async function initializeDatabaseWithRetry() {
} }
// Middleware // Middleware
app.use(cors()); app.use(cors({ credentials: true, origin: true }));
app.use(express.json()); app.use(express.json());
app.use(cookieParser());
// Health check (no auth required) // Health check (no auth required)
app.get('/health', (req, res) => { app.get('/health', (req, res) => {
res.json({ status: 'ok', timestamp: Date.now() }); res.json({ status: 'ok', timestamp: Date.now() });
}); });
// Apply authentication middleware to all API routes // Auth bootstrap routes (status/setup/login/logout/credentials/token) - must stay
app.use('/api', authenticatePassword); // 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 // Attach device id for downstream routes
app.use('/api', deviceIdMiddleware); app.use('/api', deviceIdMiddleware);
// Routes (protected by auth) // Routes (protected by the API token above)
app.use('/api/lists', listRoutes); app.use('/api/lists', listRoutes);
app.use('/api/fields', fieldRoutes); app.use('/api/fields', fieldRoutes);
app.use('/api/items', itemRoutes); app.use('/api/items', itemRoutes);
app.use('/api', syncRoutes); app.use('/api', syncRoutes);
app.use('/api', notificationRoutes); 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); app.use('/', webRoutes);
// Initialize database and start server // Initialize database and start server
@@ -92,13 +102,8 @@ app.use('/', webRoutes);
app.listen(PORT, () => { app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`); console.log(`Server is running on port ${PORT}`);
console.log(`Environment: ${process.env.NODE_ENV || 'development'}`); console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
const dbClient = (process.env.DB_CLIENT || process.env.DB_TYPE || 'sqlite').toLowerCase(); const source = process.env.DATABASE_URL ? 'DATABASE_URL' : 'PGHOST/PGDATABASE';
if (dbClient === 'postgres' || dbClient === 'postgresql') { console.log(`Database: PostgreSQL (${source})`);
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'}`);
}
}); });
} catch (error) { } catch (error) {
console.error('Database initialization error:', error); console.error('Database initialization error:', error);
+54 -101
View File
@@ -1,101 +1,54 @@
import { Request, Response, NextFunction } from 'express'; import { Request, Response, NextFunction } from 'express';
import crypto from 'crypto';
let warningLogged = false; import { dbAdapter } from '../db';
const AUTH_LOG_THROTTLE_MS = Math.max(1000, Number(process.env.AUTH_LOG_THROTTLE_MS || 30000));
const lastAuthLogAt = new Map<string, number>(); export const SESSION_COOKIE_NAME = 'collabtable_session';
const commonProbePathPatterns = [
/^\/\./, export function hashToken(token: string): string {
/client_secret\.json$/i, return crypto.createHash('sha256').update(token).digest('hex');
/phpinfo/i, }
/\.git/i,
/wp-admin/i, export function randomToken(): string {
/wp-login/i, return crypto.randomBytes(32).toString('base64url');
/id_rsa/i, }
/config(\.|$)/i
]; /**
* Gates the web dashboard (webRoutes' JSON endpoints) behind the single admin account's
function isCommonProbePath(pathname: string) { * session cookie. Matches the Bitmagnet/UnraidMonitor pattern - opaque cookie tokens, not JWT.
return commonProbePathPatterns.some(pattern => pattern.test(pathname)); */
} export async function requireSession(req: Request, res: Response, next: NextFunction) {
const token = req.cookies?.[SESSION_COOKIE_NAME];
function shouldLogAuthWarning(kind: string, req: Request) { if (!token) {
const key = `${kind}:${req.method}:${req.path}`; return res.status(401).json({ error: 'Unauthorized', message: 'Authentication required' });
const now = Date.now(); }
const lastSeen = lastAuthLogAt.get(key) || 0; const user = await dbAdapter.queryOne(
if (now - lastSeen < AUTH_LOG_THROTTLE_MS) { `SELECT u.id, u.username FROM auth_sessions s
return false; JOIN auth_users u ON u.id = s.user_id
} WHERE s.token_hash = ? AND s.expires_at > now()`,
lastAuthLogAt.set(key, now); [hashToken(token)]
return true; );
} if (!user) {
return res.status(401).json({ error: 'Unauthorized', message: 'Session expired or invalid' });
export const authenticatePassword = (req: Request, res: Response, next: NextFunction) => { }
const serverPassword = process.env.SERVER_PASSWORD; (req as any).user = user;
next();
// 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.'); * Gates the sync/collaboration API (lists/fields/items/sync/notifications) behind a
warningLogged = true; * 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
return next(); * optional SERVER_PASSWORD scheme, which silently disabled auth entirely when unset.
} */
export async function requireApiToken(req: Request, res: Response, next: NextFunction) {
// Get password from Authorization header (format: "Bearer <password>") const authHeader = req.headers.authorization;
const authHeader = req.headers.authorization; if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized', message: 'No bearer token provided' });
if (!authHeader) { }
if (!isCommonProbePath(req.path) && shouldLogAuthWarning('missingHeader', req)) { const token = authHeader.slice('Bearer '.length);
console.warn('[AUTH] Missing Authorization header', { const row = await dbAdapter.queryOne('SELECT user_id FROM api_tokens WHERE token_hash = ?', [hashToken(token)]);
path: req.path, if (!row) {
method: req.method, return res.status(401).json({ error: 'Unauthorized', message: 'Invalid API token' });
ip: req.ip, }
}); next();
} }
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();
};
+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 fs from 'fs';
import path from 'path'; import path from 'path';
import { dbAdapter, dbEngine } from '../db'; import { dbAdapter, dbEngine } from '../db';
import { requireSession } from '../middleware/auth';
const router = Router(); const router = Router();
@@ -28,22 +29,22 @@ function depVersion(name: string): string {
return deps[name] ? deps[name].replace(/^[^\d]*/, '') : 'unknown'; return deps[name] ? deps[name].replace(/^[^\d]*/, '') : 'unknown';
} }
// API endpoint to get server tech stack info (no auth required for web UI) // API endpoint to get server tech stack info (requires the admin session)
router.get('/web/info', (req: Request, res: Response) => { router.get('/web/info', requireSession, (req: Request, res: Response) => {
res.json({ res.json({
appVersion: packageJson.version ?? 'unknown', appVersion: packageJson.version ?? 'unknown',
stack: [ stack: [
{ label: 'Runtime', value: `Node.js ${process.version}` }, { label: 'Runtime', value: `Node.js ${process.version}` },
{ label: 'Language', value: `TypeScript ${depVersion('typescript')}` }, { label: 'Language', value: `TypeScript ${depVersion('typescript')}` },
{ label: 'Web Framework', value: `Express ${depVersion('express')}` }, { 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')}` }, { label: 'CORS', value: `cors ${depVersion('cors')}` },
], ],
}); });
}); });
// API endpoint to get all data (no auth required for web UI) // API endpoint to get all data (requires the admin session)
router.get('/web/data', async (req: Request, res: Response) => { router.get('/web/data', requireSession, async (req: Request, res: Response) => {
try { try {
// Add cache control headers to prevent stale data // Add cache control headers to prevent stale data
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
+46 -3
View File
@@ -1,9 +1,29 @@
async function getJson(url) { async function request(url, options) {
const res = await fetch(url, { cache: 'no-store' }); const res = await fetch(url, {
if (!res.ok) throw new Error(`HTTP ${res.status}`); ...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(); return res.json();
} }
async function getJson(url) {
return request(url);
}
export async function fetchOverview() { export async function fetchOverview() {
return getJson('/web/data'); return getJson('/web/data');
} }
@@ -16,3 +36,26 @@ export async function fetchHealth() {
const res = await fetch('/health'); const res = await fetch('/health');
return { up: res.ok }; 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> <script>
import { Tooltip } from 'bits-ui'; import { Tooltip } from 'bits-ui';
import Header from '$lib/components/Header.svelte'; 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(); let { children } = $props();
const auth = createAuthStore();
</script> </script>
<Tooltip.Provider delayDuration={300}> <Tooltip.Provider delayDuration={300}>
<div class="flex min-h-screen flex-col"> {#if auth.loading}
<Header /> <div class="flex min-h-screen items-center justify-center text-sm text-muted-fg">Loading…</div>
<main class="flex min-w-0 flex-1 flex-col"> {:else if auth.error}
{@render children?.()} <div class="flex min-h-screen items-center justify-center px-4 text-sm text-danger">
</main> {auth.error instanceof Error ? auth.error.message : 'Request failed.'}
</div> </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> </Tooltip.Provider>
@@ -1,10 +1,28 @@
<script> <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 Button from '$lib/components/ui/button.svelte';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '$lib/components/ui/dialog'; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '$lib/components/ui/dialog';
import { themeState } from '$lib/theme.svelte.js'; 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(); 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> </script>
<Dialog bind:open> <Dialog bind:open>
@@ -47,8 +65,23 @@
</Button> </Button>
</div> </div>
</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> <DialogFooter>
<Button type="button" variant="secondary" onclick={() => (open = false)}>Dismiss</Button> <Button type="button" variant="secondary" onclick={() => (open = false)}>Dismiss</Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
<CredentialsDialog bind:open={credentialsOpen} currentUsername={auth.status?.username ?? ''} />
+20 -43
View File
@@ -64,23 +64,18 @@ CollabTable allows multiple users to collaboratively create and manage lists wit
```bash ```bash
cp .env.example .env 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 ```bash
docker-compose up -d 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:** **Database:** PostgreSQL, provisioned automatically via the bundled `postgres` service in
- SQLite (default): Data persists in Docker volume `sqlite_data` `docker-compose.yml`.
- PostgreSQL: Configure in `.env` with `DB_CLIENT=postgres`
### Android App ### Android App
@@ -148,19 +143,19 @@ CollabTable/
- **Runtime:** Node.js 20+ - **Runtime:** Node.js 20+
- **Framework:** Express.js - **Framework:** Express.js
- **Language:** TypeScript - **Language:** TypeScript
- **Database:** SQLite (better-sqlite3) or PostgreSQL (pg) - **Database:** PostgreSQL (pg)
- **Containerization:** Docker & Docker Compose - **Containerization:** Docker & Docker Compose
- **Real-time:** WebSocket support - **Real-time:** WebSocket support
## API Endpoints ## API Endpoints
All endpoints are prefixed with `/api/` and can be protected with optional authentication. 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:
### Authentication
If `SERVER_PASSWORD` is set in the server's `.env` file, include this header in all requests:
``` ```
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 ### Lists
- `GET /api/lists` - Get all lists - `GET /api/lists` - Get all lists
@@ -444,27 +439,10 @@ Response:
### Data Persistence ### 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** **PostgreSQL**
- Configure in `.env`: `DB_CLIENT=postgres`
- Use standard PostgreSQL backup tools (`pg_dump`, `pg_restore`) - 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 ### Docker Commands
@@ -498,16 +476,15 @@ docker ps
**Environment Variables** **Environment Variables**
Configure these in `.env` or docker-compose.yml: Configure these in `.env` or docker-compose.yml:
```env ```env
PORT=3000 # Server port PORT=3000 # Server port
NODE_ENV=production # Environment NODE_ENV=production # Environment
SERVER_PASSWORD=your_secure_pass # API authentication (recommended) DATABASE_URL=postgres://user:pass@postgres:5432/collabtable
DB_CLIENT=sqlite # Database: sqlite or postgres COOKIE_SECURE=true # Requires HTTPS
DB_PATH=/data/collabtable.db # SQLite path (in container)
``` ```
**Security Recommendations** **Security Recommendations**
1. Set `SERVER_PASSWORD` for production 1. Generate the admin account and an API token on first run (see "Authentication" above)
2. Use HTTPS with a reverse proxy (nginx, Caddy) 2. Use HTTPS with a reverse proxy (nginx, Caddy), and set `COOKIE_SECURE=true`
3. Regular database backups 3. Regular database backups
4. Keep Docker images updated 4. Keep Docker images updated
5. Restrict network access to server ports 5. Restrict network access to server ports