@scriptdb/server
v1.1.2
Published
server module resolver for script database
Readme
ScriptDB Server
Server module for hosting and running ScriptDB instances with authentication, sandboxing, and command execution.
Installation
npm install @scriptdb/server
# or
yarn add @scriptdb/server
# or
bun add @scriptdb/serverQuick Start
import { server } from '@scriptdb/server';
// Start the server with default configuration
server();Configuration
The server can be configured through:
- Configuration file (
scriptdb.config.json) - Programmatic configuration
Configuration File
Create a scriptdb.config.json file in your project root:
{
"host": "localhost",
"port": 1234,
"users": [
{
"username": "admin",
"password": "password123"
},
{
"username": "guest",
"password": "guest123"
}
],
"folder": "databases"
}Configuration Options
host(string): Server host (default: "localhost")port(number): Server port (default: 1234)users(array): Array of user objectsfolder(string): Database storage folder (default: "databases")
User Configuration
Each user object can contain:
{
"username": "string",
"password": "string",
"passwordHash": "string", // Pre-hashed password (bcrypt)
"signingSecret": "string" // Secret for message signing
}Programmatic Usage
Basic Server
import { server } from '@scriptdb/server';
// Start server with default settings
server();Advanced Configuration
import { server } from '@scriptdb/server';
// The server reads from scriptdb.config.json if it exists
// You can also modify the configuration programmatically before starting
// Create a custom config file before starting
import { writeFileSync } from 'fs';
const config = {
host: "0.0.0.0",
port: 8080,
users: [
{
username: "admin",
passwordHash: "$2b$10$..." // bcrypt hash
}
],
folder: "./data"
};
writeFileSync('./scriptdb.config.json', JSON.stringify(config, null, 2));
// Start the server
server();Security Features
Authentication
The server supports username/password authentication with bcrypt password hashing:
// Using plain text passwords (server will hash them)
{
"username": "user",
"password": "plain-text-password"
}
// Using pre-hashed passwords (bcrypt)
{
"username": "user",
"passwordHash": "$2b$10$N9qo8uLOickgx2ZMRZoMye.IcnmVoKSj.9iECkZXod4HPnywpQqWu"
}TLS/SSL Support
The server supports secure connections using TLS:
{
"host": "localhost",
"port": 1234,
"secure": true,
"tlsOptions": {
"key": "./server-key.pem",
"cert": "./server-cert.pem",
"ca": "./ca-cert.pem",
"rejectUnauthorized": true
},
"users": [
{
"username": "admin",
"password": "password"
}
]
}Message Signing
Configure message signing for additional security:
{
"users": [
{
"username": "admin",
"password": "password",
"signingSecret": "my-secret-key"
}
]
}API
server()
Starts the ScriptDB server using the configuration file.
import { server } from '@scriptdb/server';
server(): voidThe function:
- Reads
scriptdb.config.jsonfrom the base path - Validates configuration
- Creates the database folder if it doesn't exist
- Initializes the VM and protocol handler
- Starts the server
Database Management
Database Structure
databases/
├── mydb1/
│ ├── users.json
│ ├── products.json
│ └── ...
├── mydb2/
│ └── ...Command Execution
The server executes JavaScript commands in a sandboxed environment:
// Client can send commands like:
const users = db.users.find({ status: 'active' });
return users;
// Or more complex operations:
const result = db.collection('products').aggregate([
{ $match: { category: 'electronics' } },
{ $group: { _id: '$brand', count: { $sum: 1 } } }
]);
return result;Worker Threads
The server uses worker threads for:
- bcrypt operations: Password hashing and verification
- VM execution: Running user code in isolation
- Payload validation: Validating incoming requests
This ensures the main thread remains responsive and operations don't block each other.
Rate Limiting
The server implements IP-based and username-based rate limiting:
{
"rateLimiting": {
"ipFailWindowMs": 900000, // 15 minutes
"maxLoginAttempts": 5,
"lockDurationMs": 1800000 // 30 minutes
}
}Examples
Production Server Setup
import { server } from '@scriptdb/server';
import { writeFileSync } from 'fs';
// Production configuration
const productionConfig = {
host: "0.0.0.0",
port: 443,
secure: true,
tlsOptions: {
key: "/path/to/private.key",
cert: "/path/to/certificate.crt",
ca: "/path/to/ca_bundle.crt"
},
users: [
{
username: "api_user",
passwordHash: "$2b$10$...", // Pre-hashed password
signingSecret: "production-secret"
}
],
folder: "/var/lib/scriptdb",
rateLimiting: {
ipFailWindowMs: 900000,
maxLoginAttempts: 5,
lockDurationMs: 1800000
}
};
// Write configuration
writeFileSync('./scriptdb.config.json', JSON.stringify(productionConfig, null, 2));
// Start server
console.log("Starting ScriptDB server...");
server();Development Setup
import { server } from '@scriptdb/server';
import { writeFileSync } from 'fs';
// Development configuration
const devConfig = {
host: "localhost",
port: 1234,
secure: false, // Disable TLS for development
users: [
{
username: "dev",
password: "dev123"
},
{
username: "test",
password: "test123"
}
],
folder: "./dev_databases"
};
writeFileSync('./scriptdb.config.json', JSON.stringify(devConfig, null, 2));
// Start server
console.log("Starting ScriptDB development server...");
server();Multi-User Setup
// Create multiple users with different permissions
const multiUserConfig = {
host: "localhost",
port: 1234,
users: [
{
username: "admin",
password: "admin123",
signingSecret: "admin-signing-key"
},
{
username: "read_only",
password: "readonly123",
signingSecret: "readonly-signing-key"
},
{
username: "writer",
password: "writer123",
signingSecret: "writer-signing-key"
}
],
folder: "./shared_databases"
};Error Handling
The server handles various error conditions:
- Invalid Configuration: Validates and sanitizes configuration values
- Authentication Failures: Tracks failed attempts and implements lockouts
- File System Errors: Creates directories and handles permission issues
- Network Errors: Handles connection failures and timeouts
- VM Errors: Isolates and reports script execution errors
Logging
The server logs important events:
- Server startup and configuration
- Client connections and disconnections
- Authentication attempts and failures
- Command execution results
- Error conditions
Configure logging through environment variables or modify the server implementation.
Environment Variables
NODE_ENV: Set to 'production' for production modeSCRIPTDB_CONFIG_PATH: Custom path to configuration fileSCRIPTDB_LOG_LEVEL: Logging level (debug, info, warn, error)
Development
# Install dependencies
npm install
# Run in development mode
npm run dev
# Build the package
npm run build
# Run tests
npm test
# Type checking
npm run typecheck
# Lint code
npm run lintCLI Tool
ScriptDB provides a CLI tool for easy server management:
# Install CLI globally
npm install -g @scriptdb/cli
# Start server in foreground
scriptdb start
# Start server in background (daemon mode with PM2)
scriptdb start -d
# Check server status
scriptdb status
# View real-time logs
scriptdb logs
# Monitor performance
scriptdb monit
# Stop server
scriptdb stop
# Restart server
scriptdb restart -d
# Start interactive shell
scriptdb shell
# Install packages to ScriptDB
scriptdb add lodash
# Install packages locally
scriptdb add --local lodashCLI Configuration
The CLI reads configuration from ~/.scriptdb/config.json:
{
"host": "localhost",
"port": 1234,
"users": [
{
"username": "admin",
"password": "your-password",
"hash": false
}
],
"folder": "databases",
"secure": false
}Process Management
The CLI uses PM2 for daemon mode, providing:
- Automatic restart on failure
- Log management
- Performance monitoring
- Cluster mode support
PM2 files are stored in ~/.scriptdb/:
ecosystem.config.js- PM2 configurationpm2-*.log- Log files
Changelog
1.1.2 (2025-01-16)
Added
- Native
scriptdb logscommand to view real-time logs - Native
scriptdb monitcommand to monitor performance - Native
scriptdb restartcommand to restart the server - Native
scriptdb stopcommand to stop the server - ESLint configuration for TypeScript linting
Fixed
- Fixed TypeScript type mismatch in users config normalization
- Fixed TypeScript "used before assigned" error for storage variable
- Fixed TypeScript module resolution errors
- Improved error handling and Windows compatibility
License
MIT
