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.
This commit is contained in:
1 parent
240e1fda4a
commit
b150d835a1
18 files changed
+1022
-982
No files matched your search
+227
-304
@@ -1,304 +1,227 @@
|
||||
import dotenv from 'dotenv';
|
||||
import BetterSqlite3, { Database as SqliteDB } from 'better-sqlite3';
|
||||
import { Pool, PoolClient, QueryResult, types as pgTypes } from 'pg';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
type Param = any;
|
||||
|
||||
type ExecResult = { changes: number };
|
||||
|
||||
|
||||
interface DBAdapter {
|
||||
queryAll(sql: string, params?: Param[]): Promise<any[]>;
|
||||
queryOne(sql: string, params?: Param[]): Promise<any | undefined>;
|
||||
execute(sql: string, params?: Param[]): Promise<ExecResult>;
|
||||
transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T>;
|
||||
initialize(): Promise<void>;
|
||||
}
|
||||
|
||||
function ensureDataDir(dbPath: string) {
|
||||
const dir = path.dirname(dbPath);
|
||||
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
function replaceQuotedIdentifiers(sql: string) {
|
||||
// Convert backticks to double quotes for portability
|
||||
return sql.replace(/`([^`]+)`/g, '"$1"');
|
||||
}
|
||||
|
||||
function convertQMarksToPg(sql: string) {
|
||||
// Replace each ? with $1, $2, ...
|
||||
let idx = 0;
|
||||
return sql.replace(/\?/g, () => `$${++idx}`);
|
||||
}
|
||||
|
||||
// ---------- SQLite Adapter (wrapped async) ----------
|
||||
class SqliteAdapter implements DBAdapter {
|
||||
private db: SqliteDB;
|
||||
|
||||
constructor() {
|
||||
const DB_PATH = process.env.DB_PATH || './data/collabtable.db';
|
||||
ensureDataDir(DB_PATH);
|
||||
this.db = new BetterSqlite3(DB_PATH);
|
||||
this.db.pragma('foreign_keys = ON');
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
// Create tables and indexes
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS lists (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
createdAt INTEGER NOT NULL,
|
||||
updatedAt INTEGER NOT NULL,
|
||||
isDeleted INTEGER DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS fields (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
fieldType TEXT NOT NULL,
|
||||
fieldOptions TEXT,
|
||||
alignment TEXT NOT NULL DEFAULT 'start',
|
||||
listId TEXT NOT NULL,
|
||||
"order" INTEGER NOT NULL,
|
||||
createdAt INTEGER NOT NULL,
|
||||
updatedAt INTEGER NOT NULL,
|
||||
isDeleted INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (listId) REFERENCES lists(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS items (
|
||||
id TEXT PRIMARY KEY,
|
||||
listId TEXT NOT NULL,
|
||||
createdAt INTEGER NOT NULL,
|
||||
updatedAt INTEGER NOT NULL,
|
||||
isDeleted INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (listId) REFERENCES lists(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS item_values (
|
||||
id TEXT PRIMARY KEY,
|
||||
itemId TEXT NOT NULL,
|
||||
fieldId TEXT NOT NULL,
|
||||
value TEXT,
|
||||
updatedAt INTEGER NOT NULL,
|
||||
FOREIGN KEY (itemId) REFERENCES items(id),
|
||||
FOREIGN KEY (fieldId) REFERENCES fields(id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_fields_listId ON fields(listId);
|
||||
CREATE INDEX IF NOT EXISTS idx_items_listId ON items(listId);
|
||||
CREATE INDEX IF NOT EXISTS idx_item_values_itemId ON item_values(itemId);
|
||||
CREATE INDEX IF NOT EXISTS idx_item_values_fieldId ON item_values(fieldId);
|
||||
|
||||
-- Notification events table (for remote-change notifications)
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id TEXT PRIMARY KEY,
|
||||
deviceIdOrigin TEXT,
|
||||
eventType TEXT NOT NULL,
|
||||
entityType TEXT NOT NULL,
|
||||
entityId TEXT,
|
||||
listId TEXT,
|
||||
createdAt INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_notifications_createdAt ON notifications(createdAt);
|
||||
CREATE INDEX IF NOT EXISTS idx_notifications_listId ON notifications(listId);
|
||||
`);
|
||||
// Attempt to add alignment column if upgrading an existing DB (ignore error if exists)
|
||||
try {
|
||||
this.db.exec(`ALTER TABLE fields ADD COLUMN alignment TEXT NOT NULL DEFAULT 'start'`);
|
||||
} catch (e) {
|
||||
// Column may already exist; ignore
|
||||
}
|
||||
}
|
||||
|
||||
async queryAll(sql: string, params: Param[] = []): Promise<any[]> {
|
||||
const stmt = this.db.prepare(replaceQuotedIdentifiers(sql));
|
||||
return stmt.all(...params);
|
||||
}
|
||||
|
||||
async queryOne(sql: string, params: Param[] = []): Promise<any | undefined> {
|
||||
const stmt = this.db.prepare(replaceQuotedIdentifiers(sql));
|
||||
return stmt.get(...params);
|
||||
}
|
||||
|
||||
async execute(sql: string, params: Param[] = []): Promise<ExecResult> {
|
||||
const stmt = this.db.prepare(replaceQuotedIdentifiers(sql));
|
||||
const res = stmt.run(...params);
|
||||
return { changes: res.changes || 0 };
|
||||
}
|
||||
|
||||
async transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T> {
|
||||
const tx = this.db.transaction((innerFn: (tx: DBAdapter) => Promise<T>) => {
|
||||
// We can reuse the same adapter since better-sqlite3 is transactional per connection
|
||||
return innerFn(this);
|
||||
});
|
||||
return tx(fn);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Postgres Adapter ----------
|
||||
class PostgresAdapter implements DBAdapter {
|
||||
private pool: Pool;
|
||||
|
||||
constructor() {
|
||||
// Ensure BIGINT (int8) is parsed as number to avoid string timestamps
|
||||
// OID 20 = INT8, OID 1700 = NUMERIC (keep default for now)
|
||||
pgTypes.setTypeParser(20, (val: string) => parseInt(val, 10));
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
if (connectionString) {
|
||||
this.pool = new Pool({ connectionString });
|
||||
} else {
|
||||
this.pool = new Pool({
|
||||
host: process.env.PGHOST || 'localhost',
|
||||
port: parseInt(process.env.PGPORT || '5432', 10),
|
||||
user: process.env.PGUSER || 'postgres',
|
||||
password: process.env.PGPASSWORD || '',
|
||||
database: process.env.PGDATABASE || 'collabtable'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
// Create tables if not exist, keeping schema aligned with sqlite (isDeleted INTEGER 0/1)
|
||||
const client = await this.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS lists (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
createdAt BIGINT NOT NULL,
|
||||
updatedAt BIGINT NOT NULL,
|
||||
isDeleted INTEGER DEFAULT 0
|
||||
);
|
||||
`);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS fields (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
fieldType TEXT NOT NULL,
|
||||
fieldOptions TEXT,
|
||||
alignment TEXT NOT NULL DEFAULT 'start',
|
||||
listId TEXT NOT NULL,
|
||||
"order" INTEGER NOT NULL,
|
||||
createdAt BIGINT NOT NULL,
|
||||
updatedAt BIGINT NOT NULL,
|
||||
isDeleted INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (listId) REFERENCES lists(id)
|
||||
);
|
||||
`);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS items (
|
||||
id TEXT PRIMARY KEY,
|
||||
listId TEXT NOT NULL,
|
||||
createdAt BIGINT NOT NULL,
|
||||
updatedAt BIGINT NOT NULL,
|
||||
isDeleted INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (listId) REFERENCES lists(id)
|
||||
);
|
||||
`);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS item_values (
|
||||
id TEXT PRIMARY KEY,
|
||||
itemId TEXT NOT NULL,
|
||||
fieldId TEXT NOT NULL,
|
||||
value TEXT,
|
||||
updatedAt BIGINT NOT NULL,
|
||||
FOREIGN KEY (itemId) REFERENCES items(id),
|
||||
FOREIGN KEY (fieldId) REFERENCES fields(id)
|
||||
);
|
||||
`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_fields_listId ON fields(listId);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_items_listId ON items(listId);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_item_values_itemId ON item_values(itemId);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_item_values_fieldId ON item_values(fieldId);`);
|
||||
// Notifications table
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id TEXT PRIMARY KEY,
|
||||
deviceIdOrigin TEXT,
|
||||
eventType TEXT NOT NULL,
|
||||
entityType TEXT NOT NULL,
|
||||
entityId TEXT,
|
||||
listId TEXT,
|
||||
createdAt BIGINT NOT NULL
|
||||
);
|
||||
`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_notifications_createdAt ON notifications(createdAt);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_notifications_listId ON notifications(listId);`);
|
||||
// Migrate existing DBs: ensure alignment column exists
|
||||
await client.query(`ALTER TABLE fields ADD COLUMN IF NOT EXISTS alignment TEXT NOT NULL DEFAULT 'start';`);
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
private async runQuery(sql: string, params: Param[] = [], client?: PoolClient): Promise<QueryResult<any>> {
|
||||
// Replace backticks and convert ? to $1..$n
|
||||
const text = convertQMarksToPg(replaceQuotedIdentifiers(sql));
|
||||
const runner: Pool | PoolClient = client || this.pool;
|
||||
return runner.query(text, params);
|
||||
}
|
||||
|
||||
async queryAll(sql: string, params: Param[] = []): Promise<any[]> {
|
||||
const res = await this.runQuery(sql, params);
|
||||
return res.rows;
|
||||
}
|
||||
|
||||
async queryOne(sql: string, params: Param[] = []): Promise<any | undefined> {
|
||||
const res = await this.runQuery(sql, params);
|
||||
return res.rows[0];
|
||||
}
|
||||
|
||||
async execute(sql: string, params: Param[] = []): Promise<ExecResult> {
|
||||
const res = await this.runQuery(sql, params);
|
||||
return { changes: res.rowCount || 0 };
|
||||
}
|
||||
|
||||
async transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T> {
|
||||
const client = await this.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const txAdapter: DBAdapter = {
|
||||
initialize: async () => {},
|
||||
queryAll: (sql, params) => this.runQuery(sql, params, client).then(r => r.rows),
|
||||
queryOne: (sql, params) => this.runQuery(sql, params, client).then(r => r.rows[0]),
|
||||
execute: (sql, params) => this.runQuery(sql, params, client).then(r => ({ changes: r.rowCount || 0 })),
|
||||
transaction: async (inner) => {
|
||||
// Nested transactions are treated as flat for simplicity
|
||||
return inner(txAdapter);
|
||||
}
|
||||
} as DBAdapter;
|
||||
const result = await fn(txAdapter);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const clientType = (process.env.DB_CLIENT || process.env.DB_TYPE || 'sqlite').toLowerCase();
|
||||
const isPostgres = clientType === 'postgres' || clientType === 'postgresql';
|
||||
export const dbEngine = isPostgres ? 'PostgreSQL' : 'SQLite';
|
||||
export const dbAdapter: DBAdapter = isPostgres
|
||||
? new PostgresAdapter()
|
||||
: new SqliteAdapter();
|
||||
|
||||
export async function initializeDatabase() {
|
||||
await dbAdapter.initialize();
|
||||
}
|
||||
|
||||
export type { DBAdapter };
|
||||
import dotenv from 'dotenv';
|
||||
import { Pool, PoolClient, QueryResult, types as pgTypes } from 'pg';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
type Param = any;
|
||||
|
||||
type ExecResult = { changes: number };
|
||||
|
||||
|
||||
interface DBAdapter {
|
||||
queryAll(sql: string, params?: Param[]): Promise<any[]>;
|
||||
queryOne(sql: string, params?: Param[]): Promise<any | undefined>;
|
||||
execute(sql: string, params?: Param[]): Promise<ExecResult>;
|
||||
transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T>;
|
||||
initialize(): Promise<void>;
|
||||
}
|
||||
|
||||
function replaceQuotedIdentifiers(sql: string) {
|
||||
// Convert backticks to double quotes for portability
|
||||
return sql.replace(/`([^`]+)`/g, '"$1"');
|
||||
}
|
||||
|
||||
function convertQMarksToPg(sql: string) {
|
||||
// Replace each ? with $1, $2, ...
|
||||
let idx = 0;
|
||||
return sql.replace(/\?/g, () => `$${++idx}`);
|
||||
}
|
||||
|
||||
// ---------- Postgres Adapter ----------
|
||||
class PostgresAdapter implements DBAdapter {
|
||||
private pool: Pool;
|
||||
|
||||
constructor() {
|
||||
// Ensure BIGINT (int8) is parsed as number to avoid string timestamps
|
||||
// OID 20 = INT8, OID 1700 = NUMERIC (keep default for now)
|
||||
pgTypes.setTypeParser(20, (val: string) => parseInt(val, 10));
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
if (connectionString) {
|
||||
this.pool = new Pool({ connectionString });
|
||||
} else {
|
||||
this.pool = new Pool({
|
||||
host: process.env.PGHOST || 'localhost',
|
||||
port: parseInt(process.env.PGPORT || '5432', 10),
|
||||
user: process.env.PGUSER || 'postgres',
|
||||
password: process.env.PGPASSWORD || '',
|
||||
database: process.env.PGDATABASE || 'collabtable'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
// Create tables if not exist
|
||||
const client = await this.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS lists (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
createdAt BIGINT NOT NULL,
|
||||
updatedAt BIGINT NOT NULL,
|
||||
isDeleted INTEGER DEFAULT 0
|
||||
);
|
||||
`);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS fields (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
fieldType TEXT NOT NULL,
|
||||
fieldOptions TEXT,
|
||||
alignment TEXT NOT NULL DEFAULT 'start',
|
||||
listId TEXT NOT NULL,
|
||||
"order" INTEGER NOT NULL,
|
||||
createdAt BIGINT NOT NULL,
|
||||
updatedAt BIGINT NOT NULL,
|
||||
isDeleted INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (listId) REFERENCES lists(id)
|
||||
);
|
||||
`);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS items (
|
||||
id TEXT PRIMARY KEY,
|
||||
listId TEXT NOT NULL,
|
||||
createdAt BIGINT NOT NULL,
|
||||
updatedAt BIGINT NOT NULL,
|
||||
isDeleted INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (listId) REFERENCES lists(id)
|
||||
);
|
||||
`);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS item_values (
|
||||
id TEXT PRIMARY KEY,
|
||||
itemId TEXT NOT NULL,
|
||||
fieldId TEXT NOT NULL,
|
||||
value TEXT,
|
||||
updatedAt BIGINT NOT NULL,
|
||||
FOREIGN KEY (itemId) REFERENCES items(id),
|
||||
FOREIGN KEY (fieldId) REFERENCES fields(id)
|
||||
);
|
||||
`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_fields_listId ON fields(listId);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_items_listId ON items(listId);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_item_values_itemId ON item_values(itemId);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_item_values_fieldId ON item_values(fieldId);`);
|
||||
// Notifications table
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id TEXT PRIMARY KEY,
|
||||
deviceIdOrigin TEXT,
|
||||
eventType TEXT NOT NULL,
|
||||
entityType TEXT NOT NULL,
|
||||
entityId TEXT,
|
||||
listId TEXT,
|
||||
createdAt BIGINT NOT NULL
|
||||
);
|
||||
`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_notifications_createdAt ON notifications(createdAt);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_notifications_listId ON notifications(listId);`);
|
||||
// Migrate existing DBs: ensure alignment column exists
|
||||
await client.query(`ALTER TABLE fields ADD COLUMN IF NOT EXISTS alignment TEXT NOT NULL DEFAULT 'start';`);
|
||||
|
||||
// ---- Auth (single admin account for the web dashboard) ----
|
||||
// Matches the Bitmagnet/UnraidMonitor pattern: opaque session-cookie tokens (no JWT),
|
||||
// bcrypt-hashed passwords, schema created idempotently on every startup.
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS auth_users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
`);
|
||||
// Enforces a single admin account, matching a single-tenant dashboard.
|
||||
await client.query(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
|
||||
`);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);`);
|
||||
// Long-lived credential for sync clients/devices (replaces the old optional
|
||||
// SERVER_PASSWORD scheme, which silently disabled auth entirely when unset). Only
|
||||
// the SHA-256 hash is stored; the raw token is shown once, at creation/regeneration.
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS api_tokens (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens (user_id);`);
|
||||
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
private async runQuery(sql: string, params: Param[] = [], client?: PoolClient): Promise<QueryResult<any>> {
|
||||
// Replace backticks and convert ? to $1..$n
|
||||
const text = convertQMarksToPg(replaceQuotedIdentifiers(sql));
|
||||
const runner: Pool | PoolClient = client || this.pool;
|
||||
return runner.query(text, params);
|
||||
}
|
||||
|
||||
async queryAll(sql: string, params: Param[] = []): Promise<any[]> {
|
||||
const res = await this.runQuery(sql, params);
|
||||
return res.rows;
|
||||
}
|
||||
|
||||
async queryOne(sql: string, params: Param[] = []): Promise<any | undefined> {
|
||||
const res = await this.runQuery(sql, params);
|
||||
return res.rows[0];
|
||||
}
|
||||
|
||||
async execute(sql: string, params: Param[] = []): Promise<ExecResult> {
|
||||
const res = await this.runQuery(sql, params);
|
||||
return { changes: res.rowCount || 0 };
|
||||
}
|
||||
|
||||
async transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T> {
|
||||
const client = await this.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const txAdapter: DBAdapter = {
|
||||
initialize: async () => {},
|
||||
queryAll: (sql, params) => this.runQuery(sql, params, client).then(r => r.rows),
|
||||
queryOne: (sql, params) => this.runQuery(sql, params, client).then(r => r.rows[0]),
|
||||
execute: (sql, params) => this.runQuery(sql, params, client).then(r => ({ changes: r.rowCount || 0 })),
|
||||
transaction: async (inner) => {
|
||||
// Nested transactions are treated as flat for simplicity
|
||||
return inner(txAdapter);
|
||||
}
|
||||
} as DBAdapter;
|
||||
const result = await fn(txAdapter);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const dbEngine = 'PostgreSQL';
|
||||
export const dbAdapter: DBAdapter = new PostgresAdapter();
|
||||
|
||||
export async function initializeDatabase() {
|
||||
await dbAdapter.initialize();
|
||||
}
|
||||
|
||||
export type { DBAdapter };
|
||||
@@ -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);
|
||||
|
||||
@@ -1,101 +1,54 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
let warningLogged = false;
|
||||
const AUTH_LOG_THROTTLE_MS = Math.max(1000, Number(process.env.AUTH_LOG_THROTTLE_MS || 30000));
|
||||
const lastAuthLogAt = new Map<string, number>();
|
||||
const commonProbePathPatterns = [
|
||||
/^\/\./,
|
||||
/client_secret\.json$/i,
|
||||
/phpinfo/i,
|
||||
/\.git/i,
|
||||
/wp-admin/i,
|
||||
/wp-login/i,
|
||||
/id_rsa/i,
|
||||
/config(\.|$)/i
|
||||
];
|
||||
|
||||
function isCommonProbePath(pathname: string) {
|
||||
return commonProbePathPatterns.some(pattern => pattern.test(pathname));
|
||||
}
|
||||
|
||||
function shouldLogAuthWarning(kind: string, req: Request) {
|
||||
const key = `${kind}:${req.method}:${req.path}`;
|
||||
const now = Date.now();
|
||||
const lastSeen = lastAuthLogAt.get(key) || 0;
|
||||
if (now - lastSeen < AUTH_LOG_THROTTLE_MS) {
|
||||
return false;
|
||||
}
|
||||
lastAuthLogAt.set(key, now);
|
||||
return true;
|
||||
}
|
||||
|
||||
export const authenticatePassword = (req: Request, res: Response, next: NextFunction) => {
|
||||
const serverPassword = process.env.SERVER_PASSWORD;
|
||||
|
||||
// If no password is set in environment, skip authentication
|
||||
if (!serverPassword) {
|
||||
if (!warningLogged) {
|
||||
console.warn('Warning: SERVER_PASSWORD not set in environment variables. Authentication is disabled.');
|
||||
warningLogged = true;
|
||||
}
|
||||
return next();
|
||||
}
|
||||
|
||||
// Get password from Authorization header (format: "Bearer <password>")
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (!authHeader) {
|
||||
if (!isCommonProbePath(req.path) && shouldLogAuthWarning('missingHeader', req)) {
|
||||
console.warn('[AUTH] Missing Authorization header', {
|
||||
path: req.path,
|
||||
method: req.method,
|
||||
ip: req.ip,
|
||||
});
|
||||
}
|
||||
return res.status(401).json({
|
||||
error: 'Unauthorized',
|
||||
message: 'No authorization header provided'
|
||||
});
|
||||
}
|
||||
|
||||
// Parse the authorization header
|
||||
const parts = authHeader.split(' ');
|
||||
if (parts.length !== 2 || parts[0] !== 'Bearer') {
|
||||
if (shouldLogAuthWarning('invalidHeaderFormat', req)) {
|
||||
console.warn('[AUTH] Invalid authorization header format', {
|
||||
path: req.path,
|
||||
method: req.method,
|
||||
ip: req.ip,
|
||||
// Do not log full header to avoid leaking secrets; include prefix only
|
||||
headerPreview: authHeader.substring(0, Math.min(authHeader.length, 20)) + '...'
|
||||
});
|
||||
}
|
||||
return res.status(401).json({
|
||||
error: 'Unauthorized',
|
||||
message: 'Invalid authorization header format. Expected: Bearer <password>'
|
||||
});
|
||||
}
|
||||
|
||||
const providedPassword = parts[1];
|
||||
|
||||
// Validate password
|
||||
if (providedPassword !== serverPassword) {
|
||||
// Avoid logging the full password; log only length and a small preview
|
||||
if (shouldLogAuthWarning('invalidPassword', req)) {
|
||||
const safePreview = providedPassword ? `${providedPassword.substring(0, 2)}..(${providedPassword.length})` : 'null';
|
||||
console.warn('[AUTH] Invalid password', {
|
||||
path: req.path,
|
||||
method: req.method,
|
||||
ip: req.ip,
|
||||
providedPreview: safePreview,
|
||||
});
|
||||
}
|
||||
return res.status(401).json({
|
||||
error: 'Unauthorized',
|
||||
message: 'Invalid password'
|
||||
});
|
||||
}
|
||||
|
||||
// Password is valid, continue
|
||||
next();
|
||||
};
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import crypto from 'crypto';
|
||||
import { dbAdapter } from '../db';
|
||||
|
||||
export const SESSION_COOKIE_NAME = 'collabtable_session';
|
||||
|
||||
export function hashToken(token: string): string {
|
||||
return crypto.createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
export function randomToken(): string {
|
||||
return crypto.randomBytes(32).toString('base64url');
|
||||
}
|
||||
|
||||
/**
|
||||
* Gates the web dashboard (webRoutes' JSON endpoints) behind the single admin account's
|
||||
* session cookie. Matches the Bitmagnet/UnraidMonitor pattern - opaque cookie tokens, not JWT.
|
||||
*/
|
||||
export async function requireSession(req: Request, res: Response, next: NextFunction) {
|
||||
const token = req.cookies?.[SESSION_COOKIE_NAME];
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'Unauthorized', message: 'Authentication required' });
|
||||
}
|
||||
const user = await dbAdapter.queryOne(
|
||||
`SELECT u.id, u.username FROM auth_sessions s
|
||||
JOIN auth_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = ? AND s.expires_at > now()`,
|
||||
[hashToken(token)]
|
||||
);
|
||||
if (!user) {
|
||||
return res.status(401).json({ error: 'Unauthorized', message: 'Session expired or invalid' });
|
||||
}
|
||||
(req as any).user = user;
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gates the sync/collaboration API (lists/fields/items/sync/notifications) behind a
|
||||
* long-lived API token tied to the admin account - this is machine/multi-device traffic
|
||||
* shared by every collaborating client, not an interactive browser login. Replaces the old
|
||||
* optional SERVER_PASSWORD scheme, which silently disabled auth entirely when unset.
|
||||
*/
|
||||
export async function requireApiToken(req: Request, res: Response, next: NextFunction) {
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
return res.status(401).json({ error: 'Unauthorized', message: 'No bearer token provided' });
|
||||
}
|
||||
const token = authHeader.slice('Bearer '.length);
|
||||
const row = await dbAdapter.queryOne('SELECT user_id FROM api_tokens WHERE token_hash = ?', [hashToken(token)]);
|
||||
if (!row) {
|
||||
return res.status(401).json({ error: 'Unauthorized', message: 'Invalid API token' });
|
||||
}
|
||||
next();
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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');
|
||||
|
||||
Reference in new issue
Block a user