server module resolver for script database
npm install @scriptdb/serverServer module for hosting and running ScriptDB instances with authentication, sandboxing, and command execution.
``bash`
npm install @scriptdb/serveror
yarn add @scriptdb/serveror
bun add @scriptdb/server
`typescript
import { server } from '@scriptdb/server';
// Start the server with default configuration
server();
`
The server can be configured through:
1. Configuration file (scriptdb.config.json)
2. Programmatic configuration
Create a scriptdb.config.json file in your project root:
`json`
{
"host": "localhost",
"port": 1234,
"users": [
{
"username": "admin",
"password": "password123"
},
{
"username": "guest",
"password": "guest123"
}
],
"folder": "databases"
}
- host (string): Server host (default: "localhost")port
- (number): Server port (default: 1234)users
- (array): Array of user objectsfolder
- (string): Database storage folder (default: "databases")
Each user object can contain:
`json`
{
"username": "string",
"password": "string",
"passwordHash": "string", // Pre-hashed password (bcrypt)
"signingSecret": "string" // Secret for message signing
}
`typescript
import { server } from '@scriptdb/server';
// Start server with default settings
server();
`
`typescript
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();
`
The server supports username/password authentication with bcrypt password hashing:
`typescript
// 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"
}
`
The server supports secure connections using TLS:
`json`
{
"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"
}
]
}
Configure message signing for additional security:
`json`
{
"users": [
{
"username": "admin",
"password": "password",
"signingSecret": "my-secret-key"
}
]
}
Starts the ScriptDB server using the configuration file.
`typescript
import { server } from '@scriptdb/server';
server(): void
`
The function:
1. Reads scriptdb.config.json from the base path
2. Validates configuration
3. Creates the database folder if it doesn't exist
4. Initializes the VM and protocol handler
5. Starts the server
``
databases/
├── mydb1/
│ ├── users.json
│ ├── products.json
│ └── ...
├── mydb2/
│ └── ...
The server executes JavaScript commands in a sandboxed environment:
`javascript
// 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;
`
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.
The server implements IP-based and username-based rate limiting:
`json`
{
"rateLimiting": {
"ipFailWindowMs": 900000, // 15 minutes
"maxLoginAttempts": 5,
"lockDurationMs": 1800000 // 30 minutes
}
}
`typescript
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();
`
`typescript
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();
`
`typescript`
// 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"
};
The server handles various error conditions:
1. Invalid Configuration: Validates and sanitizes configuration values
2. Authentication Failures: Tracks failed attempts and implements lockouts
3. File System Errors: Creates directories and handles permission issues
4. Network Errors: Handles connection failures and timeouts
5. VM Errors: Isolates and reports script execution errors
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.
- NODE_ENV: Set to 'production' for production modeSCRIPTDB_CONFIG_PATH
- : Custom path to configuration fileSCRIPTDB_LOG_LEVEL
- : Logging level (debug, info, warn, error)
`bashInstall dependencies
npm install
CLI Tool
ScriptDB provides a CLI tool for easy server management:
`bash
Install CLI globally
npm install -g @scriptdb/cliStart server in foreground
scriptdb startStart server in background (daemon mode with PM2)
scriptdb start -dCheck server status
scriptdb statusView real-time logs
scriptdb logsMonitor performance
scriptdb monitStop server
scriptdb stopRestart server
scriptdb restart -dStart interactive shell
scriptdb shellInstall packages to ScriptDB
scriptdb add lodashInstall packages locally
scriptdb add --local lodash
`$3
The CLI reads configuration from
~/.scriptdb/config.json:`json
{
"host": "localhost",
"port": 1234,
"users": [
{
"username": "admin",
"password": "your-password",
"hash": false
}
],
"folder": "databases",
"secure": false
}
`$3
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 configuration
- pm2-*.log - Log filesChangelog
$3
Added
- Native
scriptdb logs command to view real-time logs
- Native scriptdb monit command to monitor performance
- Native scriptdb restart command to restart the server
- Native scriptdb stop` command to stop the serverFixed
- 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
MIT