salvo-db 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ Copyright (c) 2026 SALVO DB contributors. All rights reserved.
2
+
3
+ This software and associated documentation files (the "Software") are proprietary.
4
+
5
+ Permission is granted to download, install, and use the unmodified Software for
6
+ its intended purpose.
7
+
8
+ You may not modify, adapt, translate, reverse engineer, decompile, disassemble,
9
+ or create derivative works of the Software, in whole or in part, except with
10
+ prior explicit written permission from the copyright holder.
11
+
12
+ You may not redistribute, sublicense, sell, lease, rent, loan, or otherwise make
13
+ the Software available to third parties, except with prior explicit written
14
+ permission from the copyright holder.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER
20
+ IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN
21
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,138 @@
1
- # Temporary Holding Version
1
+ # SALVO DB
2
+
3
+ ![SALVO DB dot logo](assets/salvo-db-dots.svg)
4
+
5
+ SALVO DB is a JavaScript ES module package for a single-file key-value database
6
+ and its local HTTP service. It has no runtime npm dependencies.
7
+
8
+ ## Run the service
9
+
10
+ From this directory:
11
+
12
+ ```powershell
13
+ npm install
14
+ npm run cli -- init
15
+ npm start
16
+ ```
17
+
18
+ The service listens on `127.0.0.1:7410` and stores data in `salvo.db` in the
19
+ current working directory. It stays running until stopped with Ctrl+C. Set
20
+ `SALVO_DB_PORT` or `SALVO_DB_FILE` before starting to choose another port or
21
+ database file. The interactive `npm run cli` also offers key setup on first
22
+ run; non-interactive `npm start` requires initialization beforehand.
23
+
24
+ Open `http://127.0.0.1:7410/` for the local dashboard. It shows service health,
25
+ entry count, and database file size, and lets you read, write, and delete
26
+ UTF-8 text values. Dashboard writes create a key only if it does not exist;
27
+ replacing a value requires an explicit confirmation. Direct API `PUT` requests
28
+ retain their normal replace behavior unless they use `If-None-Match: *`.
29
+
30
+ The service exposes a versioned HTTP API:
31
+
32
+ - `GET /v1/health`
33
+ - `GET /v1/stats`
34
+ - `PUT /v1/kv/<url-encoded-key>` with raw bytes in the request body
35
+ - `GET /v1/kv/<url-encoded-key>`
36
+ - `DELETE /v1/kv/<url-encoded-key>`
37
+
38
+ Values are limited to 1 MiB per HTTP request. The service binds to loopback;
39
+ remote access is not enabled by default.
40
+
41
+ ## Encryption and backups
42
+
43
+ Database records use AES-256-GCM, with a fresh random nonce and authenticated
44
+ sequence number for each record. The cipher is fixed for this storage format;
45
+ the key and value are encrypted together, so they do not appear in the database
46
+ file.
47
+
48
+ Initialize encryption explicitly with `salvo-db init` (or `npm run cli -- init`).
49
+ The setup prompts you to generate a 32-byte key locally or import an existing
50
+ 32-byte key file. No key is created when the database is opened. An interactive
51
+ first run of `npm run cli` offers the same setup; non-interactive service startup
52
+ prints instructions instead.
53
+
54
+ Generated keys are stored separately in the user's configuration directory.
55
+ Imported key files are copied there. Set `SALVO_DB_KEY_FILE` to choose the
56
+ active key-file path, or pass `{ keyPath }` to `FileDatabase.open()` and
57
+ `FileDatabase.initializeKey()`. Back up the database and key file securely.
58
+ Losing the key makes the data unrecoverable; copying only `salvo.db` to another
59
+ machine is not sufficient.
60
+
61
+ On first open, an existing plaintext v1 database is atomically rewritten into
62
+ the encrypted format. Back up the database before upgrading. The migration
63
+ preserves current values but compacts prior changes and deleted records.
64
+
65
+ The server checks that the configured key file still exists and matches before
66
+ database operations and health/stat requests. If it is removed or replaced,
67
+ the running process locks access and clears its retained key and cached values;
68
+ restore the matching key and restart to unlock it. This is fail-closed process
69
+ behavior, not a guarantee that values already returned to a caller or copies in
70
+ process memory can be revoked.
71
+ Encryption at rest does not encrypt data while it is in process memory or
72
+ protect a database when both the file and its key are accessible to an attacker.
73
+ The HTTP service remains loopback-only; encrypted peer networking is not
74
+ implemented.
75
+
76
+ ## Developer Console
77
+
78
+ Run `npm run cli` to start the database service and Developer Console together.
79
+ The dashboard is available at `http://127.0.0.1:7410/` while the console is
80
+ running. Exiting the console also stops its service. For a service without the
81
+ console, run `npm start`.
82
+
83
+ The console supports `status`, `inspect`, `put`, `get`, and confirmed `delete`
84
+ commands. The project SVG dot mark is rendered as orange ASCII art.
85
+
86
+ ## Package API
87
+
88
+ ```js
89
+ import { FileDatabase } from "salvo-db";
90
+
91
+ await FileDatabase.initializeKey("./salvo.db");
92
+ const database = await FileDatabase.open("./salvo.db");
93
+ try {
94
+ await database.put("greeting", Buffer.from("hello"));
95
+ const value = await database.get("greeting");
96
+ await database.delete("greeting");
97
+ } finally {
98
+ await database.close();
99
+ }
100
+ ```
101
+
102
+ `salvo.db` is the single data file; its encryption key is stored separately.
103
+ Call `await FileDatabase.initializeKey("./salvo.db")` before the first open;
104
+ pass `{ importFrom: "./backup.key" }` to import an existing key. Set
105
+ `{ keyPath: "./salvo.db.key" }` on both methods to manage the key location
106
+ explicitly. Successful writes are synced before they resolve.
107
+ Restarting authenticates and replays complete records; an incomplete final
108
+ record is discarded and a malformed or unauthenticated record is reported as
109
+ corruption.
110
+
111
+ ## Development
112
+
113
+ ```powershell
114
+ npm run check
115
+ npm test
116
+ ```
2
117
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
118
+ ## Experimental split key (key on another server)
119
+
120
+ Split-key mode keeps the 32-byte AES key on a separate key server. The DB machine stores only a small JSON reference file (URL/key id/token metadata), not the key bytes.
121
+
122
+ ```powershell
123
+ # Key server machine (separate host recommended)
124
+ node src/key-server.js --key-file .\master.key --host 0.0.0.0 --port 7420 --token "<long-random-token>" --generate
125
+
126
+ # DB machine
127
+ node src/cli.js init
128
+ # choose: "3) Use remote key server (EXPERIMENTAL split key)"
129
+ # then enter key URL and token
130
+ ```
131
+
132
+ Key reference file format:
133
+
134
+ ```json
135
+ {"type":"salvo-db-key-ref","version":1,"url":"https://keys.example/v1/keys/<id>","token":"...","experimental":"split-key"}
136
+ ```
137
+
138
+ Notes (experimental): protect the key server with TLS + network ACLs; a leaked URL/token can expose the key; DB availability depends on key server availability; key server logs/metrics must not record keys/tokens.
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><circle cx="121.9" cy="121.9" r="8.9" fill="#FF6319"/><circle cx="121.9" cy="166.6" r="8.9" fill="#FF6319"/><circle cx="121.9" cy="188.9" r="8.9" fill="#FF6319"/><circle cx="121.9" cy="211.3" r="8.9" fill="#FF6319"/><circle cx="121.9" cy="256.0" r="8.9" fill="#FF6319"/><circle cx="121.9" cy="278.4" r="8.9" fill="#FF6319"/><circle cx="121.9" cy="300.7" r="8.9" fill="#FF6319"/><circle cx="121.9" cy="345.4" r="8.9" fill="#FF6319"/><circle cx="121.9" cy="367.8" r="8.9" fill="#FF6319"/><circle cx="121.9" cy="390.1" r="8.9" fill="#FF6319"/><circle cx="144.2" cy="99.5" r="8.9" fill="#FF6319"/><circle cx="144.2" cy="121.9" r="8.9" fill="#FF6319"/><circle cx="144.2" cy="144.2" r="8.9" fill="#FF6319"/><circle cx="144.2" cy="188.9" r="8.9" fill="#FF6319"/><circle cx="144.2" cy="211.3" r="8.9" fill="#FF6319"/><circle cx="144.2" cy="233.6" r="8.9" fill="#FF6319"/><circle cx="144.2" cy="278.4" r="8.9" fill="#FF6319"/><circle cx="144.2" cy="300.7" r="8.9" fill="#FF6319"/><circle cx="144.2" cy="323.1" r="8.9" fill="#FF6319"/><circle cx="144.2" cy="367.8" r="8.9" fill="#FF6319"/><circle cx="144.2" cy="390.1" r="8.9" fill="#FF6319"/><circle cx="144.2" cy="412.5" r="8.9" fill="#FF6319"/><circle cx="166.6" cy="99.5" r="8.9" fill="#FF6319"/><circle cx="166.6" cy="121.9" r="8.9" fill="#FF6319"/><circle cx="166.6" cy="144.2" r="8.9" fill="#FF6319"/><circle cx="166.6" cy="188.9" r="8.9" fill="#FF6319"/><circle cx="166.6" cy="211.3" r="8.9" fill="#FF6319"/><circle cx="166.6" cy="233.6" r="8.9" fill="#FF6319"/><circle cx="166.6" cy="278.4" r="8.9" fill="#FF6319"/><circle cx="166.6" cy="300.7" r="8.9" fill="#FF6319"/><circle cx="166.6" cy="323.1" r="8.9" fill="#FF6319"/><circle cx="166.6" cy="367.8" r="8.9" fill="#FF6319"/><circle cx="166.6" cy="390.1" r="8.9" fill="#FF6319"/><circle cx="166.6" cy="412.5" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="77.2" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="99.5" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="121.9" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="144.2" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="166.6" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="211.3" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="233.6" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="256.0" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="300.7" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="323.1" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="345.4" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="390.1" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="412.5" r="8.9" fill="#FF6319"/><circle cx="188.9" cy="434.8" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="77.2" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="99.5" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="121.9" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="144.2" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="166.6" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="211.3" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="233.6" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="256.0" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="300.7" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="323.1" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="345.4" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="390.1" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="412.5" r="8.9" fill="#FF6319"/><circle cx="211.3" cy="434.8" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="77.2" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="99.5" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="121.9" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="144.2" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="166.6" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="211.3" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="233.6" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="256.0" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="300.7" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="323.1" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="345.4" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="390.1" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="412.5" r="8.9" fill="#FF6319"/><circle cx="233.6" cy="434.8" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="77.2" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="99.5" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="121.9" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="144.2" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="166.6" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="211.3" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="233.6" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="256.0" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="300.7" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="323.1" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="345.4" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="390.1" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="412.5" r="8.9" fill="#FF6319"/><circle cx="256.0" cy="434.8" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="77.2" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="99.5" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="121.9" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="144.2" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="166.6" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="211.3" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="233.6" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="256.0" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="300.7" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="323.1" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="345.4" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="390.1" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="412.5" r="8.9" fill="#FF6319"/><circle cx="278.4" cy="434.8" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="77.2" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="99.5" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="121.9" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="144.2" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="166.6" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="211.3" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="233.6" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="256.0" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="300.7" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="323.1" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="345.4" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="390.1" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="412.5" r="8.9" fill="#FF6319"/><circle cx="300.7" cy="434.8" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="77.2" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="99.5" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="121.9" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="144.2" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="166.6" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="211.3" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="233.6" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="256.0" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="300.7" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="323.1" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="345.4" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="390.1" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="412.5" r="8.9" fill="#FF6319"/><circle cx="323.1" cy="434.8" r="8.9" fill="#FF6319"/><circle cx="345.4" cy="99.5" r="8.9" fill="#FF6319"/><circle cx="345.4" cy="121.9" r="8.9" fill="#FF6319"/><circle cx="345.4" cy="144.2" r="8.9" fill="#FF6319"/><circle cx="345.4" cy="188.9" r="8.9" fill="#FF6319"/><circle cx="345.4" cy="233.6" r="8.9" fill="#FF6319"/><circle cx="345.4" cy="278.4" r="8.9" fill="#FF6319"/><circle cx="345.4" cy="323.1" r="8.9" fill="#FF6319"/><circle cx="345.4" cy="367.8" r="8.9" fill="#FF6319"/><circle cx="345.4" cy="412.5" r="8.9" fill="#FF6319"/><circle cx="367.8" cy="99.5" r="8.9" fill="#FF6319"/><circle cx="367.8" cy="121.9" r="8.9" fill="#FF6319"/><circle cx="367.8" cy="144.2" r="8.9" fill="#FF6319"/><circle cx="367.8" cy="188.9" r="8.9" fill="#FF6319"/><circle cx="367.8" cy="211.3" r="8.9" fill="#FF6319"/><circle cx="367.8" cy="233.6" r="8.9" fill="#FF6319"/><circle cx="367.8" cy="278.4" r="8.9" fill="#FF6319"/><circle cx="367.8" cy="300.7" r="8.9" fill="#FF6319"/><circle cx="367.8" cy="323.1" r="8.9" fill="#FF6319"/><circle cx="367.8" cy="367.8" r="8.9" fill="#FF6319"/><circle cx="367.8" cy="390.1" r="8.9" fill="#FF6319"/><circle cx="367.8" cy="412.5" r="8.9" fill="#FF6319"/><circle cx="390.1" cy="121.9" r="8.9" fill="#FF6319"/><circle cx="390.1" cy="166.6" r="8.9" fill="#FF6319"/><circle cx="390.1" cy="188.9" r="8.9" fill="#FF6319"/><circle cx="390.1" cy="211.3" r="8.9" fill="#FF6319"/><circle cx="390.1" cy="256.0" r="8.9" fill="#FF6319"/><circle cx="390.1" cy="278.4" r="8.9" fill="#FF6319"/><circle cx="390.1" cy="300.7" r="8.9" fill="#FF6319"/><circle cx="390.1" cy="345.4" r="8.9" fill="#FF6319"/><circle cx="390.1" cy="367.8" r="8.9" fill="#FF6319"/><circle cx="390.1" cy="390.1" r="8.9" fill="#FF6319"/></svg>
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "salvo-db",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Single-file key-value database and local HTTP service.",
5
+ "type": "module",
6
+ "main": "./src/database.js",
7
+ "exports": {
8
+ ".": "./src/database.js",
9
+ "./server": "./src/server.js",
10
+ "./key-server": "./src/key-server.js"
11
+ },
12
+ "bin": {
13
+ "salvo-db": "src/cli.js",
14
+ "salvo-db-key-server": "src/key-server.js"
15
+ },
16
+ "files": [
17
+ "assets",
18
+ "src",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "scripts": {
23
+ "start": "node src/server.js",
24
+ "dev": "node src/server.js",
25
+ "cli": "node src/cli.js",
26
+ "check": "node --check src/database.js && node --check src/server.js && node --check src/cli.js && node --check src/dashboard.js && node --check src/key-server.js",
27
+ "test": "node --test",
28
+ "prepack": "npm run check && npm test",
29
+ "key-server": "node src/key-server.js"
30
+ },
31
+ "engines": {
32
+ "node": ">=22"
33
+ },
34
+ "license": "SEE LICENSE IN LICENSE",
35
+ "keywords": [
36
+ "database",
37
+ "key-value",
38
+ "embedded",
39
+ "single-file",
40
+ "encrypted",
41
+ "local"
42
+ ]
43
+ }
package/src/cli.js ADDED
@@ -0,0 +1,440 @@
1
+ #!/usr/bin/env node
2
+ import { createInterface } from "node:readline";
3
+ import { createInterface as createPromptInterface } from "node:readline/promises";
4
+ import { randomBytes, randomUUID } from "node:crypto";
5
+ import { networkInterfaces } from "node:os";
6
+ import { pathToFileURL } from "node:url";
7
+ import { resolve } from "node:path";
8
+ import { DEFAULT_PORT, startDatabaseServer } from "./server.js";
9
+ import { EncryptionKeyMissingError, FileDatabase } from "./database.js";
10
+
11
+ const colors = {
12
+ orange: "\u001b[38;5;208m",
13
+ bold: "\u001b[1m",
14
+ muted: "\u001b[38;5;244m",
15
+ red: "\u001b[31m",
16
+ reset: "\u001b[0m",
17
+ };
18
+
19
+ const logoRows = [
20
+ " ##############",
21
+ " ######################",
22
+ "##########################",
23
+ " ######################",
24
+ "## ############## ##",
25
+ "###### ######",
26
+ "#################### ####",
27
+ " ######################",
28
+ "## ############## ##",
29
+ "###### ######",
30
+ "#################### ####",
31
+ " ######################",
32
+ "## ############## ##",
33
+ "###### ######",
34
+ "#################### ####",
35
+ " ######################",
36
+ " ##############",
37
+ ];
38
+
39
+ function paint(value, style, enabled) {
40
+ return enabled ? `${style}${value}${colors.reset}` : value;
41
+ }
42
+
43
+ function fit(value, width) {
44
+ const characters = Array.from(value);
45
+ if (characters.length <= width) {
46
+ return value;
47
+ }
48
+ return `${characters.slice(0, Math.max(0, width - 3)).join("")}...`;
49
+ }
50
+
51
+ function renderWelcome(databasePath, baseUrl, color, terminalWidth) {
52
+ const width = Math.max(30, Math.min(76, terminalWidth - 2));
53
+ const sidePanel = [
54
+ paint("SALVO DB", `${colors.orange}${colors.bold}`, color),
55
+ paint("DEVELOPER CONSOLE", colors.bold, color),
56
+ "",
57
+ "DATABASE SINGLE FILE",
58
+ "API VERSION 1",
59
+ "SERVICE LOCAL",
60
+ "DASHBOARD AVAILABLE",
61
+ ];
62
+ const mark = width >= 64
63
+ ? logoRows.map((row, index) =>
64
+ `${paint(row.padEnd(28), colors.orange, color)} ${sidePanel[index] ?? ""}`,
65
+ )
66
+ : [
67
+ ...logoRows.map((row) => paint(row, colors.orange, color)),
68
+ "",
69
+ paint("SALVO DB DEVELOPER CONSOLE", `${colors.orange}${colors.bold}`, color),
70
+ ];
71
+ const rule = paint("-".repeat(width), colors.muted, color);
72
+
73
+ return [
74
+ "",
75
+ ...mark,
76
+ "",
77
+ rule,
78
+ ` ${paint("DATABASE FILE", colors.orange, color)}`,
79
+ ` ${fit(JSON.stringify(databasePath), width - 4)}`,
80
+ ` ${paint("HTTP SERVICE", colors.orange, color)}`,
81
+ ` ${baseUrl}`,
82
+ ` ${paint("DASHBOARD", colors.orange, color)}`,
83
+ ` ${baseUrl}/`,
84
+ rule,
85
+ "",
86
+ ].join("\n");
87
+ }
88
+
89
+ function renderHelp(color) {
90
+ const command = (name, description) =>
91
+ ` ${paint(name.padEnd(28), colors.orange, color)}${description}`;
92
+
93
+ return [
94
+ "",
95
+ paint("DEVELOPER COMMANDS", colors.bold, color),
96
+ command("help", "Show available commands"),
97
+ command("status", "Check the local database service"),
98
+ command("inspect", "Show database file diagnostics"),
99
+ command("put <key> <text>", "Write UTF-8 text"),
100
+ command("get <key>", "Read a value"),
101
+ command("delete <key>", "Delete a value after confirmation"),
102
+ command("exit", "Close the console"),
103
+ "",
104
+ ].join("\n");
105
+ }
106
+
107
+ function splitCommand(line) {
108
+ const match = /^(\S+)(?:\s+([\s\S]*))?$/.exec(line.trimStart());
109
+ const command = match?.[1];
110
+ return command === undefined
111
+ ? { command: "", args: "" }
112
+ : { command: command.toLowerCase(), args: match?.[2] ?? "" };
113
+ }
114
+
115
+ function getBaseUrl(value) {
116
+ const port = Number(process.env.SALVO_DB_PORT ?? DEFAULT_PORT);
117
+ const url = new URL(value ?? `http://127.0.0.1:${port}`);
118
+ if (
119
+ url.protocol !== "http:" ||
120
+ url.hostname !== "127.0.0.1" ||
121
+ url.username.length > 0 ||
122
+ url.password.length > 0 ||
123
+ url.pathname !== "/" ||
124
+ url.search.length > 0 ||
125
+ url.hash.length > 0
126
+ ) {
127
+ throw new TypeError("The developer console only connects to a local HTTP service.");
128
+ }
129
+ return url.origin;
130
+ }
131
+
132
+ async function request(baseUrl, path, options = {}) {
133
+ let response;
134
+ try {
135
+ response = await fetch(new URL(path, baseUrl), {
136
+ ...options,
137
+ signal: AbortSignal.timeout(5000),
138
+ });
139
+ } catch (error) {
140
+ throw new Error(
141
+ `Could not reach ${baseUrl}. Start the database service with "npm start".`,
142
+ { cause: error },
143
+ );
144
+ }
145
+
146
+ if (!response.ok) {
147
+ const body = await response.text();
148
+ let message = body;
149
+ try {
150
+ const parsed = JSON.parse(body);
151
+ message = parsed.error?.message ?? body;
152
+ } catch {
153
+ message = body || response.statusText;
154
+ }
155
+ throw new Error(`Service returned HTTP ${response.status}: ${message}`);
156
+ }
157
+ return response;
158
+ }
159
+
160
+ export async function runCli(options = {}) {
161
+ const input = options.input ?? process.stdin;
162
+ const output = options.output ?? process.stdout;
163
+ const databasePath = resolve(
164
+ options.databasePath ?? process.env.SALVO_DB_FILE ?? "salvo.db",
165
+ );
166
+ const baseUrl = getBaseUrl(options.baseUrl);
167
+ const terminalWidth = options.terminalWidth ?? output.columns ?? 80;
168
+ const color =
169
+ options.color ??
170
+ (input.isTTY === true &&
171
+ output.isTTY === true &&
172
+ process.env.NO_COLOR === undefined &&
173
+ process.env.TERM !== "dumb");
174
+
175
+ const terminal = createInterface({
176
+ input,
177
+ output,
178
+ terminal: input.isTTY === true && output.isTTY === true,
179
+ });
180
+ const lines = terminal[Symbol.asyncIterator]();
181
+ const ask = async (prompt) => {
182
+ output.write(prompt);
183
+ const line = await lines.next();
184
+ return line.done ? undefined : line.value;
185
+ };
186
+
187
+ try {
188
+ output.write(renderWelcome(databasePath, baseUrl, color, terminalWidth));
189
+ output.write(`${renderHelp(color)}\n`);
190
+
191
+ while (true) {
192
+ const line = await ask("salvodb-dev> ");
193
+ if (line === undefined) {
194
+ break;
195
+ }
196
+
197
+ const { command, args } = splitCommand(line);
198
+ if (command.length === 0) {
199
+ continue;
200
+ }
201
+ if (command === "exit" || command === "quit" || command === "q") {
202
+ break;
203
+ }
204
+
205
+ try {
206
+ if (command === "help") {
207
+ output.write(renderHelp(color));
208
+ } else if (command === "status") {
209
+ const response = await request(baseUrl, "/v1/health");
210
+ const health = await response.json();
211
+ output.write(
212
+ `\n Service: ${health.status}\n` +
213
+ ` Database: ${health.storage}\n` +
214
+ ` API: ${health.api}\n`,
215
+ );
216
+ } else if (command === "inspect" || command === "debug") {
217
+ const response = await request(baseUrl, "/v1/stats");
218
+ const stats = await response.json();
219
+ output.write(
220
+ `\n Database file: ${JSON.stringify(databasePath)}\n` +
221
+ ` Entries: ${stats.entries}\n` +
222
+ ` File size: ${stats.databaseBytes} bytes\n`,
223
+ );
224
+ } else if (command === "put") {
225
+ const separator = args.search(/\s/);
226
+ if (separator < 1) {
227
+ output.write("\n Usage: put <key> <text>\n");
228
+ continue;
229
+ }
230
+ const key = args.slice(0, separator);
231
+ const value = args.slice(separator + 1);
232
+ const response = await request(
233
+ baseUrl,
234
+ `/v1/kv/${encodeURIComponent(key)}`,
235
+ { method: "PUT", body: Buffer.from(value, "utf8") },
236
+ );
237
+ output.write(`\n Saved ${JSON.stringify(key)} (${value.length} text units).\n`);
238
+ await response.body?.cancel();
239
+ } else if (command === "get") {
240
+ const key = args.trim();
241
+ if (key.length === 0) {
242
+ output.write("\n Usage: get <key>\n");
243
+ continue;
244
+ }
245
+ const response = await request(
246
+ baseUrl,
247
+ `/v1/kv/${encodeURIComponent(key)}`,
248
+ );
249
+ const value = Buffer.from(await response.arrayBuffer());
250
+ output.write(`\n Value (${value.byteLength} bytes): ${JSON.stringify(value.toString("utf8"))}\n`);
251
+ } else if (command === "delete") {
252
+ const key = args.trim();
253
+ if (key.length === 0) {
254
+ output.write("\n Usage: delete <key>\n");
255
+ continue;
256
+ }
257
+ const confirmation = await ask(` Confirm delete ${JSON.stringify(key)}? [y/N]: `);
258
+ if (confirmation === undefined) {
259
+ break;
260
+ }
261
+ if (!/^y(es)?$/i.test(confirmation.trim())) {
262
+ output.write("\n Delete cancelled.\n");
263
+ } else {
264
+ await request(baseUrl, `/v1/kv/${encodeURIComponent(key)}`, {
265
+ method: "DELETE",
266
+ });
267
+ output.write(`\n Deleted ${JSON.stringify(key)}.\n`);
268
+ }
269
+ } else {
270
+ output.write(
271
+ `\n ${paint(`Unknown command: ${JSON.stringify(command)}`, colors.red, color)}. Try "help".\n`,
272
+ );
273
+ }
274
+ } catch (error) {
275
+ const message = error instanceof Error ? error.message : String(error);
276
+ output.write(
277
+ `\n ${paint("Command failed:", colors.red, color)} ${JSON.stringify(message)}\n`,
278
+ );
279
+ }
280
+ }
281
+
282
+ output.write("\n Developer console closed.\n");
283
+ } finally {
284
+ terminal.close();
285
+ }
286
+ }
287
+
288
+ export async function runCliWithServer(options = {}) {
289
+ const service = await startDatabaseServer({
290
+ databasePath: options.databasePath,
291
+ keyPath: options.keyPath,
292
+ host: options.host,
293
+ port: options.port,
294
+ });
295
+ const address = service.server.address();
296
+ if (address === null || typeof address !== "object") {
297
+ await service.close();
298
+ throw new Error("The database service did not provide a network address.");
299
+ }
300
+
301
+ try {
302
+ await runCli({
303
+ input: options.input,
304
+ output: options.output,
305
+ color: options.color,
306
+ terminalWidth: options.terminalWidth,
307
+ databasePath: service.database.databasePath,
308
+ baseUrl: `http://127.0.0.1:${address.port}`,
309
+ });
310
+ } finally {
311
+ await service.close();
312
+ }
313
+ }
314
+
315
+ async function main() {
316
+ const args = process.argv.slice(2);
317
+ if (args[0] === "init") {
318
+ await initializeEncryptionInteractively();
319
+ return;
320
+ }
321
+ if (args.includes("--help") || args.includes("-h")) {
322
+ process.stdout.write(
323
+ "SALVO DB Developer Console\n\n" +
324
+ "`salvo-db init` configures the local encryption key.\n" +
325
+ "`npm run cli` starts the database service and console together.\n" +
326
+ "`npm start` runs the service without the console.\n",
327
+ );
328
+ return;
329
+ }
330
+
331
+ try {
332
+ await runCliWithServer();
333
+ } catch (error) {
334
+ if (!(error instanceof EncryptionKeyMissingError) || process.stdin.isTTY !== true) {
335
+ throw error;
336
+ }
337
+ await initializeEncryptionInteractively();
338
+ await runCliWithServer();
339
+ }
340
+ }
341
+
342
+ function localAddresses() {
343
+ const out = [];
344
+ for (const entries of Object.values(networkInterfaces())) {
345
+ for (const entry of entries ?? []) {
346
+ if (!entry || entry.internal) continue;
347
+ if (entry.family === "IPv4") out.push(entry.address);
348
+ }
349
+ }
350
+ return [...new Set(out)];
351
+ }
352
+
353
+ async function initializeEncryptionInteractively() {
354
+ const databasePath = resolve(process.env.SALVO_DB_FILE ?? "salvo.db");
355
+ const prompts = createPromptInterface({
356
+ input: process.stdin,
357
+ output: process.stdout,
358
+ });
359
+
360
+ try {
361
+ process.stdout.write(
362
+ "\nSALVO DB encryption setup\n" +
363
+ "Database records use AES-256-GCM. Encryption is required.\n" +
364
+ "Choose a key source. Split key is experimental.\n\n",
365
+ );
366
+ let choice;
367
+ while (choice !== "1" && choice !== "2" && choice !== "3") {
368
+ choice = (await prompts.question(
369
+ "1) Generate a new local key (recommended)\n" +
370
+ "2) Import a local key file\n" +
371
+ "3) Use remote key server (EXPERIMENTAL split key)\n" +
372
+ "Choose [1]: ",
373
+ )).trim();
374
+ if (choice.length === 0) {
375
+ choice = "1";
376
+ }
377
+ if (choice !== "1" && choice !== "2" && choice !== "3") {
378
+ process.stdout.write("Choose 1, 2, or 3.\n");
379
+ }
380
+ }
381
+
382
+ const options = {};
383
+ if (choice === "2") {
384
+ options.importFrom = (await prompts.question("Path to existing 32-byte key file: ")).trim();
385
+ if (options.importFrom.length === 0) {
386
+ throw new Error("A key file path is required for import.");
387
+ }
388
+ }
389
+ if (choice === "3") {
390
+ const keyId = randomUUID();
391
+ const token = randomBytes(24).toString("base64url");
392
+ const port = 7420;
393
+ const ips = localAddresses();
394
+ const suggestedHost = ips[0] ?? "<key-server-ip>";
395
+ const suggestedUrl = `http://${suggestedHost}:${port}/v1/keys/${encodeURIComponent(keyId)}`;
396
+ const command =
397
+ `npx -y -p salvo-db salvo-db-key-server --generate --host 0.0.0.0 --port ${port} --key-file ./salvo-db-master.key --key-id ${keyId} --token ${token}`;
398
+ process.stdout.write(
399
+ "\nEXPERIMENTAL SPLIT KEY\n" +
400
+ "The DB stores only a key reference file. The real 32-byte key stays on the key server.\n" +
401
+ "Run this on the KEY SERVER machine (paste as-is):\n\n" +
402
+ command + "\n\n" +
403
+ "Detected local address(es): " + (ips.length > 0 ? ips.join(", ") : "none detected; use the key server IP") + "\n" +
404
+ "Suggested key URL: " + suggestedUrl + "\n" +
405
+ "After starting it, confirm the URL below (use the key server's reachable IP/hostname).\n" +
406
+ "Warning: protect the key server (firewall/VPN/TLS). Anyone with URL+token can fetch the key.\n\n",
407
+ );
408
+ const url = (await prompts.question(`Key server URL [${suggestedUrl}]: `)).trim() || suggestedUrl;
409
+ options.splitKey = { type: "salvo-db-key-ref", version: 1, url, keyId, token, experimental: "split-key" };
410
+ }
411
+
412
+ const result = await FileDatabase.initializeKey(databasePath, options);
413
+ const keyPath = typeof result === "string" ? result : result.keyPath;
414
+ if (choice === "3") {
415
+ process.stdout.write(
416
+ `\nSplit-key reference configured at ${JSON.stringify(keyPath)}.\n` +
417
+ "The database server will fetch the key from the configured key server. Keep the key server secure and backed up.\n\n",
418
+ );
419
+ } else {
420
+ process.stdout.write(
421
+ `\nEncryption key configured at ${JSON.stringify(keyPath)}.\n` +
422
+ "Back up this key securely. It cannot be recovered if lost.\n\n",
423
+ );
424
+ }
425
+ } finally {
426
+ prompts.close();
427
+ }
428
+ }
429
+
430
+ const invokedPath = process.argv[1];
431
+ if (
432
+ invokedPath !== undefined &&
433
+ pathToFileURL(resolve(invokedPath)).href === import.meta.url
434
+ ) {
435
+ main().catch((error) => {
436
+ const message = error instanceof Error ? error.message : String(error);
437
+ process.stderr.write(`SALVO DB Developer Console failed: ${JSON.stringify(message)}\n`);
438
+ process.exitCode = 1;
439
+ });
440
+ }