admindb 2.2.1 → 2.3.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.
Files changed (87) hide show
  1. package/README.md +368 -364
  2. package/dist/app.js +6 -9
  3. package/dist/auth/config.d.ts +1 -1
  4. package/dist/auth/config.js +18 -30
  5. package/dist/auth/crypto.js +11 -21
  6. package/dist/auth/middleware.js +9 -16
  7. package/dist/auth/routes.js +9 -15
  8. package/dist/cli/args.d.ts +1 -1
  9. package/dist/cli/args.js +15 -26
  10. package/dist/cli/config.js +6 -16
  11. package/dist/cli/runner.js +4 -7
  12. package/dist/data/chain.d.ts +1 -1
  13. package/dist/data/chain.js +40 -617
  14. package/dist/data/datasets.d.ts +1 -1
  15. package/dist/data/datasets.js +43 -1
  16. package/dist/data/detector.js +45 -21
  17. package/dist/data/engine.d.ts +1 -1
  18. package/dist/data/engine.js +483 -142
  19. package/dist/data/index.d.ts +1 -1
  20. package/dist/data/index.js +8 -0
  21. package/dist/data/prng.d.ts +1 -0
  22. package/dist/data/prng.js +73 -0
  23. package/dist/data/registry.d.ts +1 -0
  24. package/dist/data/registry.js +805 -0
  25. package/dist/data/schema-graph.d.ts +1 -0
  26. package/dist/data/schema-graph.js +210 -0
  27. package/dist/data/strategies.d.ts +1 -1
  28. package/dist/data/strategies.js +44 -283
  29. package/dist/data/templates.d.ts +1 -0
  30. package/dist/data/templates.js +134 -0
  31. package/dist/data/types.d.ts +1 -1
  32. package/dist/data/validator.d.ts +1 -0
  33. package/dist/data/validator.js +160 -0
  34. package/dist/db/database.js +9 -14
  35. package/dist/db/export.js +32 -55
  36. package/dist/db/filters.d.ts +1 -1
  37. package/dist/db/filters.js +15 -38
  38. package/dist/db/introspection.js +4 -7
  39. package/dist/db/manager.js +27 -51
  40. package/dist/db/migrations.js +7 -14
  41. package/dist/db/postgres.js +30 -78
  42. package/dist/index.d.ts +1 -1
  43. package/dist/public/css/app.css +1 -1
  44. package/dist/public/js/browse.js +1 -1
  45. package/dist/public/js/inspector.js +1 -1
  46. package/dist/public/js/query.js +1 -1
  47. package/dist/public/js/seed.js +1 -1
  48. package/dist/routes/api/erd.js +3 -8
  49. package/dist/routes/api/helpers.d.ts +1 -1
  50. package/dist/routes/api/helpers.js +75 -25
  51. package/dist/routes/api/import-export.js +1 -2
  52. package/dist/routes/api/query.js +2 -6
  53. package/dist/routes/api/rows.js +4 -8
  54. package/dist/routes/api/seed.js +35 -21
  55. package/dist/routes/api/tables.js +15 -30
  56. package/dist/routes/databases.js +8 -26
  57. package/dist/routes/pages.js +67 -18
  58. package/dist/serverless.js +15 -40
  59. package/dist/sql/generator.d.ts +1 -1
  60. package/dist/sql/generator.js +35 -109
  61. package/dist/types/api.d.ts +1 -1
  62. package/dist/utils/common.d.ts +1 -1
  63. package/dist/utils/common.js +45 -85
  64. package/dist/utils/csv.d.ts +1 -1
  65. package/dist/utils/csv.js +11 -17
  66. package/dist/utils/datatype.js +46 -60
  67. package/dist/utils/icons.js +8 -8
  68. package/dist/views/layouts/main.hbs +1 -87
  69. package/dist/views/pages/databases.hbs +1 -233
  70. package/dist/views/pages/designer.hbs +1 -89
  71. package/dist/views/pages/erd.hbs +1 -1241
  72. package/dist/views/pages/error.hbs +1 -10
  73. package/dist/views/pages/form.hbs +1 -59
  74. package/dist/views/pages/home.hbs +1 -220
  75. package/dist/views/pages/info.hbs +1 -107
  76. package/dist/views/pages/login.hbs +1 -98
  77. package/dist/views/pages/query.hbs +1 -129
  78. package/dist/views/pages/schema.hbs +1 -298
  79. package/dist/views/pages/seed-select.hbs +251 -0
  80. package/dist/views/pages/seed.hbs +256 -414
  81. package/dist/views/pages/table.hbs +1 -327
  82. package/dist/views/partials/navbar.hbs +1 -83
  83. package/dist/views/partials/sidebar.hbs +1 -129
  84. package/docs/API.md +149 -149
  85. package/docs/EXAMPLES.md +579 -579
  86. package/docs/SECURITY.md +265 -265
  87. package/package.json +79 -79
package/README.md CHANGED
@@ -1,364 +1,368 @@
1
- # AdminDB
2
-
3
- [![Version](https://img.shields.io/npm/v/admindb.svg)](https://www.npmjs.com/package/admindb)
4
- [![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
5
- [![Node.js](https://img.shields.io/badge/node-%3E%3D20.0.0-brightgreen.svg)](https://nodejs.org/)
6
- [![Downloads](https://img.shields.io/npm/dm/admindb.svg)](https://www.npmjs.com/package/admindb)
7
- [![Publish](https://github.com/MIbnEKhalid/admindb/actions/workflows/publish.yml/badge.svg?branch=main)](https://github.com/MIbnEKhalid/admindb/actions/workflows/publish.yml)
8
-
9
- **A modern, browser-based SQLite and PostgreSQL database administration tool.** Manage SQLite and PostgreSQL databases entirely from your browser — browse and edit rows, run arbitrary SQL queries, design schemas visually, seed realistic test data, inspect complex data types, and import/export CSV/JSON — with zero frontend build step.
10
-
11
- - **SQLite & PostgreSQL Multi-Engine:** Seamlessly manage local SQLite files, remote PostgreSQL connections, or multi-database environments with distinct engine badges and credentials protection.
12
- - **Secure JSON Config Files:** Pass database credentials securely in `.json` files (`name.postgres.json`) without exposing secrets on the CLI.
13
- - **Zero frontend build step:** Server-rendered Handlebars UI + vanilla JS + heavily refined DaisyUI/TailwindCSS styling; a single lightweight Express process serves pages, static assets, and the REST API.
14
- - **Standalone CLI or embeddable library:** Run instantly via `npx admindb` or mount it directly into your existing Express application under any subpath.
15
- - **Intelligent SQL Error Analyzer:** Intercepts raw SQL errors and provides human-readable explanations and suggested fixes for syntax errors, missing columns, and constraint violations.
16
- - **Modern terminal experience:** Clean, colorized startup banner with auto-detected local/network URLs and streamlined runtime logs.
17
- - **Rich Data Types & Calendar Controls:** In-place calendar pickers with presets (`Now`, `Yesterday`, `Tomorrow`, `+7 Days`, `+30 Days`), PostgreSQL Array chip managers, JSON modal inspector, UUID generators, and byte dump inspector.
18
- - **Interactive ER Diagram & Relationship Graph:** Interactive SVG schema visualizer with 3 layout modes (Hierarchy, Force, Circular), relationship filtering, hover edge inspectors, and clean SVG export.
19
- - **Safe SQL by construction:** Quoted identifiers, escaped literals, parameterized queries, and non-executing SQL preview modes.
20
-
21
- ---
22
-
23
- ![Home dashboard](docs/screenshots/home.png)
24
-
25
- > 📸 **Visual Tour:** See [`docs/screenshots/`](docs/screenshots/) for screenshots of the Table Browser, Inline Grid Editor, Read-Only Mode, Query Workbench, Visual Schema Designer, Universal Data Inspector, Mock Data Seeder, and Multi-Database Manager.
26
-
27
- ---
28
-
29
- ## ⚡ 30-Second Quickstart
30
-
31
- No installation required:
32
-
33
- ```bash
34
- npx admindb
35
- ```
36
-
37
- By default, AdminDB opens in **Manager Mode** on `http://localhost:45531`, allowing you to browse the filesystem, create new SQLite databases, or open existing `.db` / `.sqlite` / `.sqlite3` files.
38
-
39
- ### 1. Load database connections securely from a JSON file:
40
-
41
- Create `name.postgres.json`:
42
- ```json
43
- {
44
- "prod": "postgresql://postgres:secret@localhost:5432/prod_db",
45
- "staging": "postgresql://postgres:secret@localhost:5432/staging_db",
46
- "local": "./data/local.db"
47
- }
48
- ```
49
-
50
- Run:
51
- ```bash
52
- npx admindb name.postgres.json
53
- ```
54
-
55
- ### 2. Point directly to a database file or PostgreSQL URI:
56
-
57
- ```bash
58
- npx admindb ./data/app.db # Open a single SQLite database directly
59
- npx admindb postgresql://postgres:secret@localhost:5432/mydb # Open a PostgreSQL database directly
60
- npx admindb -d ./databases # Manage a folder of SQLite databases
61
- npx admindb -p 8080 -r # Run on port 8080 in read-only mode
62
- ```
63
-
64
- ### Install globally:
65
-
66
- ```bash
67
- npm install -g admindb
68
- admindb
69
- ```
70
-
71
- ---
72
-
73
- ## 🖥️ Modern Terminal Experience
74
-
75
- AdminDB features a clean, colorized CLI startup banner and streamlined, low-noise runtime logging:
76
-
77
- ```text
78
- ⚡ AdminDB v2.2.1
79
-
80
- ➜ Local: http://localhost:45531/
81
- ➜ Network: http://192.168.1.15:45531/
82
- ➜ Mode: Manager
83
- ➜ Config: name.postgres.json (2 connection(s))
84
- • prod: PostgreSQL postgresql://postgres:****@localhost:5432/prod_db
85
- • staging: PostgreSQL postgresql://postgres:****@localhost:5432/staging_db
86
- ➜ Auth: User: admin (default password)
87
-
88
- ⚠ Default password in use (admin). Generate a secure hash with:
89
- npm run generatehash and set ADMINDB_PASSWORD or -P <hash>
90
- ```
91
-
92
- Runtime operations produce crisp, color-coded status logs:
93
-
94
- ```text
95
- 16:38:13 [info] Initialized PostgreSQL pool for postgresql://postgres:****@localhost:5432/prod_db
96
- 16:38:15 [info] Executed query in 2.4ms (42 rows returned)
97
- 16:38:18 [warn] Failed login attempt for user "unknown"
98
- ```
99
-
100
- ---
101
-
102
- ## 🌟 Core Features
103
-
104
- ### 🔍 Browse & Edit Rows
105
- * **Table Browser:** High-density compact grid by default, column-header sorting, sticky headers, and pinned right-aligned action columns. Composite primary keys are fully supported.
106
- * **Spreadsheet-Style Inline Editing & Keyboard Navigation:**
107
- * **Full Grid Navigation:** Navigate cells with <kbd>↑</kbd> <kbd>↓</kbd> <kbd>←</kbd> <kbd>→</kbd> or <kbd>Tab</kbd> / <kbd>Shift+Tab</kbd>.
108
- * **In-Place Type-Aware Controls:** Double-click or press <kbd>Enter</kbd> to edit in place (FK dropdowns, boolean toggles, date/time pickers with instant calendar triggers, array tags, numeric inputs). Pressing <kbd>Enter</kbd> commits and shifts focus to the cell below. Pressing <kbd>Space</kbd> on boolean cells toggles immediately.
109
- * **Interactive Date & Time Presets:** Calendar widget with quick shortcuts (`Now / Today`, `Yesterday`, `Tomorrow`, `+7 Days`, `+30 Days`, `Start of Day`, `End of Day`, `Clear`).
110
- * **PostgreSQL Array Tag Manager:** Interactive chip manager with Enter key chip addition, removal, and `{item1,item2}` array serialization.
111
- * **Quick Copy Shortcut:** Press <kbd>Ctrl+C</kbd> / <kbd>Cmd+C</kbd> on any focused cell to copy its raw value to the clipboard.
112
- * **Granular Staging & Single-Cell Revert:** Staged edits are marked with amber indicators (`.cell-dirty`). Hovering reveals an individual undo button (`↺`) to revert a single field without losing the rest of your pending batch.
113
- * **Staged Changes Diff & Review Drawer:** Floating dock displays pending edit count; click **Review Diff** to inspect a side-by-side comparison of original vs staged values across all modified rows before applying atomically in a single transaction.
114
- * **Universal Data Inspector:** Rich interactive modal for deep data inspection:
115
- * **JSON / JSONB Viewer & Editor:** Interactive syntax-highlighted tree viewer, expandable nodes, real-time JSON editor, and format **Beautify** & **Minify** tools.
116
- * **BLOB / BYTEA & Media Previews:** Automatic MIME sniffing (PNG, JPEG, WebP, GIF, SVG, PDF, audio/video), inline image thumbnails, direct binary download, and drag-and-drop file upload. Supports PostgreSQL `\x...` and `0x...` hex strings.
117
- * **3-Column Hex Dump:** Professional byte offset, hexadecimal, and printable ASCII viewer for raw binary blobs.
118
- * **Text & Code Inspector:** Full-height editor for lengthy text fields, SQL strings, markdown, UUIDs, and config blobs with copy shortcuts.
119
- * **Row Quick Actions:** 3-dots dropdown menu on each row for *Edit*, *Duplicate Row*, *Copy as JSON*, *Copy SQL INSERT*, and *Delete Row*.
120
- * **Type-Aware Filters:** Filter by exact match, comparison (`>5`, `<=10`), prefix (`pre*`), substring, boolean state, or date/numeric ranges.
121
- * **Bulk Operations:** Select rows to delete in one transaction (with foreign-key impact previews) or export selected rows as CSV/JSON.
122
- * **Related Rows:** Cross-table foreign key indicators show how many child records reference each row, with one-click nested table exploration.
123
-
124
- ### ⚡ Query Runner & SQL Tools
125
- * **Arbitrary SQL Runner:** Execute queries with results formatted as clean tables; `COUNT` queries display a concise summary, and mutations report affected row counts. Double-click or click inspect on any cell in query results to open the universal inspector.
126
- * **Saved Named Queries:** Save frequently used queries in the database and reload them from a dropdown menu.
127
- * **Safe SQL Preview:** Generate `CREATE`, `INSERT`, or `UPDATE` SQL without executing it.
128
- * **Full Database Dump:** Download the entire database as a standard SQL file (`CREATE TABLE` + `INSERT` statements).
129
-
130
- ### 🗂️ Visual Schema Designer & Indexes
131
- * **Database Info & Settings:** View active database configuration parameters (e.g. `journal_mode`, `max_connections`) and a complete database-wide syntax-highlighted Schema DDL extraction with an easy 1-click copy tool.
132
- * **Visual Table Designer:** Create tables interactively with column types (including `UUID`, `JSONB`, `TIMESTAMP`, `TIMESTAMPTZ`, `INTERVAL`, `BYTEA`, `INET`, `SERIAL`, `BIGINT`), primary keys, autoincrement, nullable/unique constraints, default values, and foreign keys.
133
- * **Relationship-Safe Schema Editor:** Rename tables, add columns, modify column types, rename columns, and drop columns/tables with safety checks to protect active foreign keys and unique constraints.
134
- * **Index Manager:** Create single or multi-column indexes (plain or unique) with live SQL previews, and drop existing indexes safely.
135
-
136
- ### 📊 Interactive ER Diagram & Relationship Visualization
137
- * **3 Layout Modes:**
138
- * **Hierarchy (default):** Layered topological layout organizing master/root tables on the left with dependencies progressing to the right, barycenter-sorted to minimize edge crossings.
139
- * **Force-Directed:** Organic physics simulation balancing node repulsion and edge spring tension.
140
- * **Circular:** Clean circular arrangement for connected tables with isolated/unreferenced tables placed cleanly in a side column.
141
- * **Interactive Canvas & Controls:** Smooth zoom & pan, node dragging, minimap overview, live table search filter with auto-pan, compact mode toggle, and keyboard shortcuts (<kbd>F</kbd> fit, <kbd>L</kbd> cycle layout, <kbd>C</kbd> compact).
142
- * **Relationship Highlighting & Inspector:** Select any table to highlight its incoming & outgoing foreign-key connections with dimmed backdrop, hover relationship curves to inspect column mappings, and access direct Schema / Browse shortcuts from the sliding side panel or right-click context menu.
143
- * **Standalone SVG Export:** Export clean, production-ready SVG diagrams with inlined styling and proper viewBox bounds for documentation and architecture reviews.
144
-
145
- ### 🔄 Import, Export & Seed Data Generation
146
- * **CSV Import:** Upload or paste CSV files with column matching, executed transactionally.
147
- * **Data Export:** Download table data or arbitrary SQL query results as CSV or JSON.
148
- * **Intelligent Seed Generator:** Populate tables with up to 5,000 realistic rows using intelligent heuristic strategy detection (names, emails, phones, addresses, dates, UUIDs, custom templates, or sampled foreign keys). Includes live table preview before execution.
149
- * **Cross-Table Relational Chain Seeder:** Automatically detects and resolves foreign key dependencies, allowing you to seed an entire branch of related tables in topological order in a single click.
150
-
151
- ### 📁 Multi-Database Manager & Schema Operations
152
- * **Bulk Table Operations:** Select multiple tables from the home dashboard to bulk drop or bulk truncate them simultaneously, with force cascade options that temporarily disable and bypass foreign key checks.
153
- * Manage directories of SQLite files, explicit file lists, or named JSON connections.
154
- * Dedicated landing page with engine badges (`PostgreSQL` / `SQLite`), table counts, connection paths, and seamless database switching.
155
-
156
- ### 🛡️ Strict Read-Only & Serverless Mode
157
- * **Serverless Ready:** Auto-detects ephemeral serverless environments (Vercel, AWS Lambda, Cloudflare Pages, Netlify, GCP Cloud Functions).
158
- * **Smart Serverless Editability Rule:**
159
- * **SQLite** defaults to **read-only** in serverless mode to prevent data loss on ephemeral filesystems.
160
- * **PostgreSQL** is **fully editable and writable** in serverless mode because it connects to persistent remote database services.
161
- * Includes ready-to-use `createServerlessHandler` and `createLambdaHandler` wrappers.
162
-
163
- ---
164
-
165
- ## 🚀 Embed AdminDB in Express
166
-
167
- AdminDB is built to work natively with both **CommonJS (`require`)** and **ES Modules (`import`)**. You can mount it directly into any existing Express application under any subpath:
168
-
169
- ### ES Modules (ESM) or TypeScript
170
- ```ts
171
- import express from 'express';
172
- import { createRouter } from 'admindb';
173
-
174
- const app = express();
175
-
176
- // Mount AdminDB for SQLite
177
- app.use('/admin', createRouter({
178
- dbPath: './data/app.db',
179
- basePath: '/admin',
180
- }));
181
-
182
- app.listen(45531);
183
- ```
184
-
185
- ### CommonJS (CJS)
186
- ```js
187
- const express = require('express');
188
- const { createRouter } = require('admindb');
189
-
190
- const app = express();
191
-
192
- app.use('/admin', createRouter({
193
- connection: 'postgresql://postgres:secret@localhost:5432/mydb',
194
- basePath: '/admin',
195
- }));
196
-
197
- app.listen(45531);
198
- ```
199
-
200
- > **💡 Try the Embedded Test App:**
201
- > You can see a complete, working example of an embedded host application by running `npm run testapp` from the project root. This spins up a standalone Express server that imports and mounts AdminDB.
202
-
203
- > 📖 **Full Options & Advanced Embedding Recipes:**
204
- > See [**`docs/EXAMPLES.md`**](docs/EXAMPLES.md#-part-2-programmatic-code-examples-express--typescript) for the complete `createRouter` options reference, multi-database management (`DbManager`), custom loggers, read-only mode, and custom authentication configurations.
205
-
206
- ---
207
-
208
- ## ⚙️ CLI & Environment Variables
209
-
210
- Every setting can be configured via **CLI flags**, **Environment Variables**, or **JSON Configuration Files** (CLI flags override JSON config, which overrides environment variables):
211
-
212
- | Setting | CLI Flag & Aliases | Environment Variable & Aliases | Default | Description |
213
- | :--- | :--- | :--- | :--- | :--- |
214
- | **Config File** | `-C, --config <file.json>` | `ADMINDB_CONFIG` | — | Path to a JSON configuration file containing database credentials & settings |
215
- | **Port** | `-p, --port <port>` | `PORT`, `ADMINDB_PORT` | `45531` | Port to listen on |
216
- | **Host** | `-H, --host <host>` | `HOST`, `ADMINDB_HOST` | `0.0.0.0` | Host / interface to bind |
217
- | **Connection URI** | `-c, --connection, --pg <uri>` | `DATABASE_URL`, `ADMINDB_CONNECTION`, `PG_CONNECTION` | — | PostgreSQL connection URI or path |
218
- | **Single DB** | `-o, --open, --db-path <file>` | `DB_PATH`, `ADMINDB_DB_PATH`, `ADMINDB_PATH` | — | Open a single database file directly |
219
- | **Database Dir** | `-d, --dir, --db-dir <dir>` | `DB_DIR`, `ADMINDB_DB_DIR`, `ADMINDB_DIR` | — | Folder of database files to manage |
220
- | **Explicit Files** | `--files, --db-files <list>` | `DB_FILES`, `ADMINDB_DB_FILES` | — | Comma-separated database file paths |
221
- | **Base Path** | `-b, --base-path, --base <p>` | `BASE_PATH`, `ADMINDB_BASE_PATH` | `''` (`/`) | URL prefix to serve under (e.g. `/admin`) |
222
- | **Read-Only** | `-r, --readonly, --read-only`| `READONLY`, `ADMINDB_READONLY` | `false` | Open databases read-only (writes disabled) |
223
- | **Serverless**| `--serverless` | `SERVERLESS`, `ADMINDB_SERVERLESS` | `false` *(auto)* | Serverless mode (SQLite read-only, Postgres editable) |
224
- | **Auth** | `--auth` / `--no-auth` | `ADMINDB_AUTH`, `ADMINDB_NO_AUTH` | `true` | Enable or disable built-in authentication |
225
- | **Username** | `-u, --username, --user <user>` | `ADMINDB_USERNAME`, `ADMINDB_USER` | `admin` | Admin username |
226
- | **Password** | `-P, --password, --pass <pass>` | `ADMINDB_PASSWORD`, `ADMINDB_PASS` | `admin` *(hash)* | Admin password or salted `scrypt:...` hash |
227
- | **Session Secret**| `--auth-secret, --secret <sec>` | `ADMINDB_SECRET`, `SESSION_SECRET` | *(auto)* | Secret key for signing session cookies |
228
- | **Log Level** | `-l, --log-level <level>` | `LOG_LEVEL`, `ADMINDB_LOG_LEVEL` | `info` | `debug` \| `info` \| `warn` \| `error` |
229
- | **Help** | `-h, --help` | — | — | Show CLI help |
230
- | **Version** | `-v, --version` | — | — | Show version |
231
-
232
- Quick CLI examples:
233
-
234
- ```bash
235
- admindb name.postgres.json # Load credentials from JSON file
236
- admindb postgresql://user:pass@host:5432/db # Open PostgreSQL database
237
- admindb ./data/app.db # Open SQLite database
238
- admindb -d ./databases # Manage a folder of databases
239
- admindb -p 8080 # Run on port 8080
240
- admindb --no-auth # Authentication disabled
241
- ```
242
-
243
- > 📖 **Full Configuration Reference & Deployment Recipes:**
244
- > See [**`docs/EXAMPLES.md`**](docs/EXAMPLES.md) for detailed variable explanations, reasons/use cases, and ready-to-run recipes for Bash, PowerShell, Docker, Docker Compose, and Nginx.
245
-
246
- ---
247
-
248
- ## 🔒 Authentication & Security
249
-
250
- > [!WARNING]
251
- > **Important Security Notice:**
252
- > AdminDB's built-in native authentication provides **basic single-user access control** for local development and private internal tools.
253
- > For production environments and internet-facing networks, **it is entirely the user's responsibility to protect AdminDB** by placing it behind your own web application's authentication (e.g. NextAuth, Passport, OAuth2/OIDC middleware), an IP-restricted VPN, or a secure reverse proxy with TLS/HTTPS.
254
-
255
- ### Generate a Secure Password Hash
256
-
257
- To configure custom credentials with a salted cryptographic `scrypt` hash:
258
-
259
- ```bash
260
- npm run generatehash
261
- ```
262
-
263
- Paste the resulting hash into `ADMINDB_PASSWORD`, CLI `-P`, or your Express configuration:
264
-
265
- ```bash
266
- ADMINDB_USERNAME="ops" ADMINDB_PASSWORD="scrypt:8011bcda...:85465796..." npx admindb
267
- ```
268
-
269
- ### Wrapping with Your Own Express Authentication (Recommended for Production)
270
-
271
- When embedding AdminDB in your Express application, turn off built-in auth (`auth: false`) and protect the route with your existing auth middleware:
272
-
273
- ```ts
274
- import express from 'express';
275
- import { createRouter } from 'admindb';
276
-
277
- const app = express();
278
-
279
- app.use('/admin', requireYourAppAuth, createRouter({
280
- connection: process.env.DATABASE_URL,
281
- basePath: '/admin',
282
- auth: false, // Turn off built-in login form; rely on requireYourAppAuth
283
- }));
284
-
285
- app.listen(45531);
286
- ```
287
-
288
- ### Disabling Built-in Authentication
289
-
290
- When deploying behind an external gateway (Cloudflare Zero Trust, OAuth2 Proxy, Authelia):
291
-
292
- ```bash
293
- admindb --no-auth
294
- # or
295
- ADMINDB_AUTH=false npx admindb
296
- ```
297
-
298
- > 📖 **Full Security Guide:** See [**`docs/SECURITY.md`**](docs/SECURITY.md) for the shared security model, filesystem sandboxing, PostgreSQL remote protection, and production deployment checklists.
299
-
300
-
301
- ---
302
-
303
- ## 📡 REST API
304
-
305
- AdminDB exposes a comprehensive REST API under `basePath` returning `{ success, data?, error? }`:
306
-
307
- ```text
308
- GET /api/tables List tables
309
- GET /api/tables/:table/rows Paginated rows (with filtering & sorting)
310
- GET /api/tables/:table/row/:id Get a single row
311
- GET /api/tables/:table/row/:id/blob/:column Stream raw BLOB / BYTEA binary data
312
- GET /api/tables/:table/row/:id/blob/:col/meta BLOB / BYTEA metadata, MIME analysis & hex dump
313
- PUT /api/tables/:table/row/:id/blob/:column Upload / update binary content
314
- POST /api/tables/:table/rows Insert row (single or batch)
315
- PUT /api/tables/:table/row/:id Update row
316
- DELETE /api/tables/:table/row/:id Delete row
317
- POST /api/tables/:table/rows/bulk-update Apply staged inline edits atomically
318
- POST /api/tables/:table/rows/bulk-delete Delete selected rows atomically
319
- POST /api/tables/:table/seed Generate & insert realistic seed rows
320
- POST /api/tables Create a new table
321
- GET /api/tables/:table/schema Inspect table schema & constraints
322
- GET /api/tables/:table/ddl Get table CREATE SQL & indexes
323
- POST /api/query Execute arbitrary SQL
324
- GET /api/databases List managed database connections & files
325
- ```
326
-
327
- > 📖 **Full API Reference:** See [**`docs/API.md`**](docs/API.md) for detailed documentation of all 30+ endpoints, query parameters, payload schemas, and TypeScript types.
328
-
329
- ---
330
-
331
- ## 📚 Documentation Index
332
-
333
- | Document | Description |
334
- | :--- | :--- |
335
- | [**`docs/EXAMPLES.md`**](docs/EXAMPLES.md) | Comprehensive Environment Variables reference, JSON configs, Express code examples, and deployment recipes. |
336
- | [**`docs/SECURITY.md`**](docs/SECURITY.md) | Authentication architecture, password hashing, reverse proxy setup, and security checklist. |
337
- | [**`docs/API.md`**](docs/API.md) | Complete REST API endpoint reference and TypeScript type exports. |
338
- | [**`CONTRIBUTING.md`**](CONTRIBUTING.md) | Development workflow, running tests, project layout, and contribution guidelines. |
339
-
340
- ---
341
-
342
- ## 🤝 Contributing
343
-
344
- Contributions are welcome! Please check out [**`CONTRIBUTING.md`**](CONTRIBUTING.md) for development setup and testing instructions.
345
-
346
- ```bash
347
- git clone https://github.com/MIbnEKhalid/admindb.git
348
- cd admindb
349
- npm install
350
- npm run dev # Live reload development server
351
- npm test # Run comprehensive unit test suite
352
- ```
353
-
354
- ---
355
-
356
- ## 🙌 Credits
357
-
358
- AdminDB is built and maintained by **[Muhammad Bin Khalid](https://github.com/MIbnEKhalid)** under the umbrella of **[MBKTech.org](https://mbktech.org)**.
359
-
360
- ---
361
-
362
- ## 📄 License
363
-
364
- [MIT](./LICENSE) © MIbnEKhalid
1
+ # AdminDB
2
+
3
+ [![Version](https://img.shields.io/npm/v/admindb.svg)](https://www.npmjs.com/package/admindb)
4
+ [![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
5
+ [![Node.js](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg)](https://nodejs.org/)
6
+ [![Downloads](https://img.shields.io/npm/dm/admindb.svg)](https://www.npmjs.com/package/admindb)
7
+ [![Publish](https://github.com/MIbnEKhalid/admindb/actions/workflows/publish.yml/badge.svg?branch=main)](https://github.com/MIbnEKhalid/admindb/actions/workflows/publish.yml)
8
+
9
+ **A modern, browser-based SQLite and PostgreSQL database administration tool.** Manage SQLite and PostgreSQL databases entirely from your browser — browse and edit rows, run arbitrary SQL queries, design schemas visually, seed realistic test data, inspect complex data types, and import/export CSV/JSON — with zero frontend build step.
10
+
11
+ - **SQLite & PostgreSQL Multi-Engine:** Seamlessly manage local SQLite files, remote PostgreSQL connections, or multi-database environments with distinct engine badges and credentials protection.
12
+ - **Secure JSON Config Files:** Pass database credentials securely in `.json` files (`name.postgres.json`) without exposing secrets on the CLI.
13
+ - **Zero frontend build step:** Server-rendered Handlebars UI + vanilla JS + heavily refined DaisyUI/TailwindCSS styling; a single lightweight Express process serves pages, static assets, and the REST API.
14
+ - **Standalone CLI or embeddable library:** Run instantly via `npx admindb` or mount it directly into your existing Express application under any subpath.
15
+ - **Intelligent SQL Error Analyzer:** Intercepts raw SQL errors and provides human-readable explanations and suggested fixes for syntax errors, missing columns, and constraint violations.
16
+ - **Modern terminal experience:** Clean, colorized startup banner with auto-detected local/network URLs and streamlined runtime logs.
17
+ - **Rich Data Types & Calendar Controls:** In-place calendar pickers with presets (`Now`, `Yesterday`, `Tomorrow`, `+7 Days`, `+30 Days`), PostgreSQL Array chip managers, JSON modal inspector, UUID generators, and byte dump inspector.
18
+ - **Interactive ER Diagram & Relationship Graph:** Interactive SVG schema visualizer with 3 layout modes (Hierarchy, Force, Circular), relationship filtering, hover edge inspectors, and clean SVG export.
19
+ - **Safe SQL by construction:** Quoted identifiers, escaped literals, parameterized queries, and non-executing SQL preview modes.
20
+
21
+ ---
22
+
23
+ ![Home dashboard](docs/screenshots/home.png)
24
+
25
+ > 📸 **Visual Tour:** See [`docs/screenshots/`](docs/screenshots/) for screenshots of the Table Browser, Inline Grid Editor, Read-Only Mode, Query Workbench, Visual Schema Designer, Universal Data Inspector, Mock Data Seeder, and Multi-Database Manager.
26
+
27
+ ---
28
+
29
+ ## ⚡ 30-Second Quickstart
30
+
31
+ No installation required:
32
+
33
+ ```bash
34
+ npx admindb
35
+ ```
36
+
37
+ By default, AdminDB opens in **Manager Mode** on `http://localhost:45531`, allowing you to browse the filesystem, create new SQLite databases, or open existing `.db` / `.sqlite` / `.sqlite3` files.
38
+
39
+ ### 1. Load database connections securely from a JSON file:
40
+
41
+ Create `name.postgres.json`:
42
+ ```json
43
+ {
44
+ "prod": "postgresql://postgres:secret@localhost:5432/prod_db",
45
+ "staging": "postgresql://postgres:secret@localhost:5432/staging_db",
46
+ "local": "./data/local.db"
47
+ }
48
+ ```
49
+
50
+ Run:
51
+ ```bash
52
+ npx admindb name.postgres.json
53
+ ```
54
+
55
+ ### 2. Point directly to a database file or PostgreSQL URI:
56
+
57
+ ```bash
58
+ npx admindb ./data/app.db # Open a single SQLite database directly
59
+ npx admindb postgresql://postgres:secret@localhost:5432/mydb # Open a PostgreSQL database directly
60
+ npx admindb -d ./databases # Manage a folder of SQLite databases
61
+ npx admindb -p 8080 -r # Run on port 8080 in read-only mode
62
+ ```
63
+
64
+ ### Install globally:
65
+
66
+ ```bash
67
+ npm install -g admindb
68
+ admindb
69
+ ```
70
+
71
+ ---
72
+
73
+ ## 🖥️ Modern Terminal Experience
74
+
75
+ AdminDB features a clean, colorized CLI startup banner and streamlined, low-noise runtime logging:
76
+
77
+ ```text
78
+ ⚡ AdminDB v2.2.1
79
+
80
+ ➜ Local: http://localhost:45531/
81
+ ➜ Network: http://192.168.1.15:45531/
82
+ ➜ Mode: Manager
83
+ ➜ Config: name.postgres.json (2 connection(s))
84
+ • prod: PostgreSQL postgresql://postgres:****@localhost:5432/prod_db
85
+ • staging: PostgreSQL postgresql://postgres:****@localhost:5432/staging_db
86
+ ➜ Auth: User: admin (default password)
87
+
88
+ ⚠ Default password in use (admin). Generate a secure hash with:
89
+ npm run generatehash and set ADMINDB_PASSWORD or -P <hash>
90
+ ```
91
+
92
+ Runtime operations produce crisp, color-coded status logs:
93
+
94
+ ```text
95
+ 16:38:13 [info] Initialized PostgreSQL pool for postgresql://postgres:****@localhost:5432/prod_db
96
+ 16:38:15 [info] Executed query in 2.4ms (42 rows returned)
97
+ 16:38:18 [warn] Failed login attempt for user "unknown"
98
+ ```
99
+
100
+ ---
101
+
102
+ ## 🌟 Core Features
103
+
104
+ ### 🔍 Browse & Edit Rows
105
+ * **Table Browser:** High-density compact grid by default, column-header sorting, sticky headers, and pinned right-aligned action columns. Composite primary keys are fully supported.
106
+ * **Column Manager (Visibility, Custom Ordering & Sticky Freezing):**
107
+ * **Interactive Column Drawer/Modal:** Click **Columns** in the table toolbar to toggle column visibility, reorder columns via drag-and-drop or <kbd>↑</kbd> <kbd>↓</kbd> buttons, and freeze columns on the left (sticky pinning).
108
+ * **Instant Search & Presets:** Filter columns instantly with live search, or use fast presets like *Show All*, *PKs only*, or *Reset*.
109
+ * **Persistent Per-Table Preferences:** Automatically stores your customized layout, hidden fields, and pinned columns in `localStorage`.
110
+ * **Spreadsheet-Style Inline Editing & Keyboard Navigation:**
111
+ * **Full Grid Navigation:** Navigate cells with <kbd>↑</kbd> <kbd>↓</kbd> <kbd>←</kbd> <kbd>→</kbd> or <kbd>Tab</kbd> / <kbd>Shift+Tab</kbd>.
112
+ * **In-Place Type-Aware Controls:** Double-click or press <kbd>Enter</kbd> to edit in place (FK dropdowns, boolean toggles, date/time pickers with instant calendar triggers, array tags, numeric inputs). Pressing <kbd>Enter</kbd> commits and shifts focus to the cell below. Pressing <kbd>Space</kbd> on boolean cells toggles immediately.
113
+ * **Interactive Date & Time Presets:** Calendar widget with quick shortcuts (`Now / Today`, `Yesterday`, `Tomorrow`, `+7 Days`, `+30 Days`, `Start of Day`, `End of Day`, `Clear`).
114
+ * **PostgreSQL Array Tag Manager:** Interactive chip manager with Enter key chip addition, removal, and `{item1,item2}` array serialization.
115
+ * **Quick Copy Shortcut:** Press <kbd>Ctrl+C</kbd> / <kbd>Cmd+C</kbd> on any focused cell to copy its raw value to the clipboard.
116
+ * **Granular Staging & Single-Cell Revert:** Staged edits are marked with amber indicators (`.cell-dirty`). Hovering reveals an individual undo button (`↺`) to revert a single field without losing the rest of your pending batch.
117
+ * **Staged Changes Diff & Review Drawer:** Floating dock displays pending edit count; click **Review Diff** to inspect a side-by-side comparison of original vs staged values across all modified rows before applying atomically in a single transaction.
118
+ * **Universal Data Inspector:** Rich interactive modal for deep data inspection:
119
+ * **JSON / JSONB Viewer & Editor:** Interactive syntax-highlighted tree viewer, expandable nodes, real-time JSON editor, and format **Beautify** & **Minify** tools.
120
+ * **BLOB / BYTEA & Media Previews:** Automatic MIME sniffing (PNG, JPEG, WebP, GIF, SVG, PDF, audio/video), inline image thumbnails, direct binary download, and drag-and-drop file upload. Supports PostgreSQL `\x...` and `0x...` hex strings.
121
+ * **3-Column Hex Dump:** Professional byte offset, hexadecimal, and printable ASCII viewer for raw binary blobs.
122
+ * **Text & Code Inspector:** Full-height editor for lengthy text fields, SQL strings, markdown, UUIDs, and config blobs with copy shortcuts.
123
+ * **Row Quick Actions:** 3-dots dropdown menu on each row for *Edit*, *Duplicate Row*, *Copy as JSON*, *Copy SQL INSERT*, and *Delete Row*.
124
+ * **Type-Aware Filters:** Filter by exact match, comparison (`>5`, `<=10`), prefix (`pre*`), substring, boolean state, or date/numeric ranges.
125
+ * **Bulk Operations:** Select rows to delete in one transaction (with foreign-key impact previews) or export selected rows as CSV/JSON.
126
+ * **Related Rows:** Cross-table foreign key indicators show how many child records reference each row, with one-click nested table exploration.
127
+
128
+ ### ⚡ Query Runner & SQL Tools
129
+ * **Arbitrary SQL Runner:** Execute queries with results formatted as clean tables; `COUNT` queries display a concise summary, and mutations report affected row counts. Double-click or click inspect on any cell in query results to open the universal inspector.
130
+ * **Saved Named Queries:** Save frequently used queries in the database and reload them from a dropdown menu.
131
+ * **Safe SQL Preview:** Generate `CREATE`, `INSERT`, or `UPDATE` SQL without executing it.
132
+ * **Full Database Dump:** Download the entire database as a standard SQL file (`CREATE TABLE` + `INSERT` statements).
133
+
134
+ ### 🗂️ Visual Schema Designer & Indexes
135
+ * **Database Info & Settings:** View active database configuration parameters (e.g. `journal_mode`, `max_connections`) and a complete database-wide syntax-highlighted Schema DDL extraction with an easy 1-click copy tool.
136
+ * **Visual Table Designer:** Create tables interactively with column types (including `UUID`, `JSONB`, `TIMESTAMP`, `TIMESTAMPTZ`, `INTERVAL`, `BYTEA`, `INET`, `SERIAL`, `BIGINT`), primary keys, autoincrement, nullable/unique constraints, default values, and foreign keys.
137
+ * **Relationship-Safe Schema Editor:** Rename tables, add columns, modify column types, rename columns, and drop columns/tables with safety checks to protect active foreign keys and unique constraints.
138
+ * **Index Manager:** Create single or multi-column indexes (plain or unique) with live SQL previews, and drop existing indexes safely.
139
+
140
+ ### 📊 Interactive ER Diagram & Relationship Visualization
141
+ * **3 Layout Modes:**
142
+ * **Hierarchy (default):** Layered topological layout organizing master/root tables on the left with dependencies progressing to the right, barycenter-sorted to minimize edge crossings.
143
+ * **Force-Directed:** Organic physics simulation balancing node repulsion and edge spring tension.
144
+ * **Circular:** Clean circular arrangement for connected tables with isolated/unreferenced tables placed cleanly in a side column.
145
+ * **Interactive Canvas & Controls:** Smooth zoom & pan, node dragging, minimap overview, live table search filter with auto-pan, compact mode toggle, and keyboard shortcuts (<kbd>F</kbd> fit, <kbd>L</kbd> cycle layout, <kbd>C</kbd> compact).
146
+ * **Relationship Highlighting & Inspector:** Select any table to highlight its incoming & outgoing foreign-key connections with dimmed backdrop, hover relationship curves to inspect column mappings, and access direct Schema / Browse shortcuts from the sliding side panel or right-click context menu.
147
+ * **Standalone SVG Export:** Export clean, production-ready SVG diagrams with inlined styling and proper viewBox bounds for documentation and architecture reviews.
148
+
149
+ ### 🔄 Import, Export & Seed Data Generation
150
+ * **CSV Import:** Upload or paste CSV files with column matching, executed transactionally.
151
+ * **Data Export:** Download table data or arbitrary SQL query results as CSV or JSON.
152
+ * **Intelligent Seed Generator:** Populate tables with up to 5,000 realistic rows using intelligent heuristic strategy detection (names, emails, phones, addresses, dates, UUIDs, custom templates, or sampled foreign keys). Includes live table preview before execution.
153
+ * **Cross-Table Relational Chain Seeder:** Automatically detects and resolves foreign key dependencies, allowing you to seed an entire branch of related tables in topological order in a single click.
154
+
155
+ ### 📁 Multi-Database Manager & Schema Operations
156
+ * **Bulk Table Operations:** Select multiple tables from the home dashboard to bulk drop or bulk truncate them simultaneously, with force cascade options that temporarily disable and bypass foreign key checks.
157
+ * Manage directories of SQLite files, explicit file lists, or named JSON connections.
158
+ * Dedicated landing page with engine badges (`PostgreSQL` / `SQLite`), table counts, connection paths, and seamless database switching.
159
+
160
+ ### 🛡️ Strict Read-Only & Serverless Mode
161
+ * **Serverless Ready:** Auto-detects ephemeral serverless environments (Vercel, AWS Lambda, Cloudflare Pages, Netlify, GCP Cloud Functions).
162
+ * **Smart Serverless Editability Rule:**
163
+ * **SQLite** defaults to **read-only** in serverless mode to prevent data loss on ephemeral filesystems.
164
+ * **PostgreSQL** is **fully editable and writable** in serverless mode because it connects to persistent remote database services.
165
+ * Includes ready-to-use `createServerlessHandler` and `createLambdaHandler` wrappers.
166
+
167
+ ---
168
+
169
+ ## 🚀 Embed AdminDB in Express
170
+
171
+ AdminDB is built to work natively with both **CommonJS (`require`)** and **ES Modules (`import`)**. You can mount it directly into any existing Express application under any subpath:
172
+
173
+ ### ES Modules (ESM) or TypeScript
174
+ ```ts
175
+ import express from 'express';
176
+ import { createRouter } from 'admindb';
177
+
178
+ const app = express();
179
+
180
+ // Mount AdminDB for SQLite
181
+ app.use('/admin', createRouter({
182
+ dbPath: './data/app.db',
183
+ basePath: '/admin',
184
+ }));
185
+
186
+ app.listen(45531);
187
+ ```
188
+
189
+ ### CommonJS (CJS)
190
+ ```js
191
+ const express = require('express');
192
+ const { createRouter } = require('admindb');
193
+
194
+ const app = express();
195
+
196
+ app.use('/admin', createRouter({
197
+ connection: 'postgresql://postgres:secret@localhost:5432/mydb',
198
+ basePath: '/admin',
199
+ }));
200
+
201
+ app.listen(45531);
202
+ ```
203
+
204
+ > **💡 Try the Embedded Test App:**
205
+ > You can see a complete, working example of an embedded host application by running `npm run testapp` from the project root. This spins up a standalone Express server that imports and mounts AdminDB.
206
+
207
+ > 📖 **Full Options & Advanced Embedding Recipes:**
208
+ > See [**`docs/EXAMPLES.md`**](docs/EXAMPLES.md#-part-2-programmatic-code-examples-express--typescript) for the complete `createRouter` options reference, multi-database management (`DbManager`), custom loggers, read-only mode, and custom authentication configurations.
209
+
210
+ ---
211
+
212
+ ## ⚙️ CLI & Environment Variables
213
+
214
+ Every setting can be configured via **CLI flags**, **Environment Variables**, or **JSON Configuration Files** (CLI flags override JSON config, which overrides environment variables):
215
+
216
+ | Setting | CLI Flag & Aliases | Environment Variable & Aliases | Default | Description |
217
+ | :--- | :--- | :--- | :--- | :--- |
218
+ | **Config File** | `-C, --config <file.json>` | `ADMINDB_CONFIG` | — | Path to a JSON configuration file containing database credentials & settings |
219
+ | **Port** | `-p, --port <port>` | `PORT`, `ADMINDB_PORT` | `45531` | Port to listen on |
220
+ | **Host** | `-H, --host <host>` | `HOST`, `ADMINDB_HOST` | `0.0.0.0` | Host / interface to bind |
221
+ | **Connection URI** | `-c, --connection, --pg <uri>` | `DATABASE_URL`, `ADMINDB_CONNECTION`, `PG_CONNECTION` | — | PostgreSQL connection URI or path |
222
+ | **Single DB** | `-o, --open, --db-path <file>` | `DB_PATH`, `ADMINDB_DB_PATH`, `ADMINDB_PATH` | — | Open a single database file directly |
223
+ | **Database Dir** | `-d, --dir, --db-dir <dir>` | `DB_DIR`, `ADMINDB_DB_DIR`, `ADMINDB_DIR` | — | Folder of database files to manage |
224
+ | **Explicit Files** | `--files, --db-files <list>` | `DB_FILES`, `ADMINDB_DB_FILES` | — | Comma-separated database file paths |
225
+ | **Base Path** | `-b, --base-path, --base <p>` | `BASE_PATH`, `ADMINDB_BASE_PATH` | `''` (`/`) | URL prefix to serve under (e.g. `/admin`) |
226
+ | **Read-Only** | `-r, --readonly, --read-only`| `READONLY`, `ADMINDB_READONLY` | `false` | Open databases read-only (writes disabled) |
227
+ | **Serverless**| `--serverless` | `SERVERLESS`, `ADMINDB_SERVERLESS` | `false` *(auto)* | Serverless mode (SQLite read-only, Postgres editable) |
228
+ | **Auth** | `--auth` / `--no-auth` | `ADMINDB_AUTH`, `ADMINDB_NO_AUTH` | `true` | Enable or disable built-in authentication |
229
+ | **Username** | `-u, --username, --user <user>` | `ADMINDB_USERNAME`, `ADMINDB_USER` | `admin` | Admin username |
230
+ | **Password** | `-P, --password, --pass <pass>` | `ADMINDB_PASSWORD`, `ADMINDB_PASS` | `admin` *(hash)* | Admin password or salted `scrypt:...` hash |
231
+ | **Session Secret**| `--auth-secret, --secret <sec>` | `ADMINDB_SECRET`, `SESSION_SECRET` | *(auto)* | Secret key for signing session cookies |
232
+ | **Log Level** | `-l, --log-level <level>` | `LOG_LEVEL`, `ADMINDB_LOG_LEVEL` | `info` | `debug` \| `info` \| `warn` \| `error` |
233
+ | **Help** | `-h, --help` | — | — | Show CLI help |
234
+ | **Version** | `-v, --version` | — | — | Show version |
235
+
236
+ Quick CLI examples:
237
+
238
+ ```bash
239
+ admindb name.postgres.json # Load credentials from JSON file
240
+ admindb postgresql://user:pass@host:5432/db # Open PostgreSQL database
241
+ admindb ./data/app.db # Open SQLite database
242
+ admindb -d ./databases # Manage a folder of databases
243
+ admindb -p 8080 # Run on port 8080
244
+ admindb --no-auth # Authentication disabled
245
+ ```
246
+
247
+ > 📖 **Full Configuration Reference & Deployment Recipes:**
248
+ > See [**`docs/EXAMPLES.md`**](docs/EXAMPLES.md) for detailed variable explanations, reasons/use cases, and ready-to-run recipes for Bash, PowerShell, Docker, Docker Compose, and Nginx.
249
+
250
+ ---
251
+
252
+ ## 🔒 Authentication & Security
253
+
254
+ > [!WARNING]
255
+ > **Important Security Notice:**
256
+ > AdminDB's built-in native authentication provides **basic single-user access control** for local development and private internal tools.
257
+ > For production environments and internet-facing networks, **it is entirely the user's responsibility to protect AdminDB** by placing it behind your own web application's authentication (e.g. NextAuth, Passport, OAuth2/OIDC middleware), an IP-restricted VPN, or a secure reverse proxy with TLS/HTTPS.
258
+
259
+ ### Generate a Secure Password Hash
260
+
261
+ To configure custom credentials with a salted cryptographic `scrypt` hash:
262
+
263
+ ```bash
264
+ npm run generatehash
265
+ ```
266
+
267
+ Paste the resulting hash into `ADMINDB_PASSWORD`, CLI `-P`, or your Express configuration:
268
+
269
+ ```bash
270
+ ADMINDB_USERNAME="ops" ADMINDB_PASSWORD="scrypt:8011bcda...:85465796..." npx admindb
271
+ ```
272
+
273
+ ### Wrapping with Your Own Express Authentication (Recommended for Production)
274
+
275
+ When embedding AdminDB in your Express application, turn off built-in auth (`auth: false`) and protect the route with your existing auth middleware:
276
+
277
+ ```ts
278
+ import express from 'express';
279
+ import { createRouter } from 'admindb';
280
+
281
+ const app = express();
282
+
283
+ app.use('/admin', requireYourAppAuth, createRouter({
284
+ connection: process.env.DATABASE_URL,
285
+ basePath: '/admin',
286
+ auth: false, // Turn off built-in login form; rely on requireYourAppAuth
287
+ }));
288
+
289
+ app.listen(45531);
290
+ ```
291
+
292
+ ### Disabling Built-in Authentication
293
+
294
+ When deploying behind an external gateway (Cloudflare Zero Trust, OAuth2 Proxy, Authelia):
295
+
296
+ ```bash
297
+ admindb --no-auth
298
+ # or
299
+ ADMINDB_AUTH=false npx admindb
300
+ ```
301
+
302
+ > 📖 **Full Security Guide:** See [**`docs/SECURITY.md`**](docs/SECURITY.md) for the shared security model, filesystem sandboxing, PostgreSQL remote protection, and production deployment checklists.
303
+
304
+
305
+ ---
306
+
307
+ ## 📡 REST API
308
+
309
+ AdminDB exposes a comprehensive REST API under `basePath` returning `{ success, data?, error? }`:
310
+
311
+ ```text
312
+ GET /api/tables List tables
313
+ GET /api/tables/:table/rows Paginated rows (with filtering & sorting)
314
+ GET /api/tables/:table/row/:id Get a single row
315
+ GET /api/tables/:table/row/:id/blob/:column Stream raw BLOB / BYTEA binary data
316
+ GET /api/tables/:table/row/:id/blob/:col/meta BLOB / BYTEA metadata, MIME analysis & hex dump
317
+ PUT /api/tables/:table/row/:id/blob/:column Upload / update binary content
318
+ POST /api/tables/:table/rows Insert row (single or batch)
319
+ PUT /api/tables/:table/row/:id Update row
320
+ DELETE /api/tables/:table/row/:id Delete row
321
+ POST /api/tables/:table/rows/bulk-update Apply staged inline edits atomically
322
+ POST /api/tables/:table/rows/bulk-delete Delete selected rows atomically
323
+ POST /api/tables/:table/seed Generate & insert realistic seed rows
324
+ POST /api/tables Create a new table
325
+ GET /api/tables/:table/schema Inspect table schema & constraints
326
+ GET /api/tables/:table/ddl Get table CREATE SQL & indexes
327
+ POST /api/query Execute arbitrary SQL
328
+ GET /api/databases List managed database connections & files
329
+ ```
330
+
331
+ > 📖 **Full API Reference:** See [**`docs/API.md`**](docs/API.md) for detailed documentation of all 30+ endpoints, query parameters, payload schemas, and TypeScript types.
332
+
333
+ ---
334
+
335
+ ## 📚 Documentation Index
336
+
337
+ | Document | Description |
338
+ | :--- | :--- |
339
+ | [**`docs/EXAMPLES.md`**](docs/EXAMPLES.md) | Comprehensive Environment Variables reference, JSON configs, Express code examples, and deployment recipes. |
340
+ | [**`docs/SECURITY.md`**](docs/SECURITY.md) | Authentication architecture, password hashing, reverse proxy setup, and security checklist. |
341
+ | [**`docs/API.md`**](docs/API.md) | Complete REST API endpoint reference and TypeScript type exports. |
342
+ | [**`CONTRIBUTING.md`**](CONTRIBUTING.md) | Development workflow, running tests, project layout, and contribution guidelines. |
343
+
344
+ ---
345
+
346
+ ## 🤝 Contributing
347
+
348
+ Contributions are welcome! Please check out [**`CONTRIBUTING.md`**](CONTRIBUTING.md) for development setup and testing instructions.
349
+
350
+ ```bash
351
+ git clone https://github.com/MIbnEKhalid/admindb.git
352
+ cd admindb
353
+ npm install
354
+ npm run dev # Live reload development server
355
+ npm test # Run comprehensive unit test suite
356
+ ```
357
+
358
+ ---
359
+
360
+ ## 🙌 Credits
361
+
362
+ AdminDB is built and maintained by **[Muhammad Bin Khalid](https://github.com/MIbnEKhalid)** under the umbrella of **[MBKTech.org](https://mbktech.org)**.
363
+
364
+ ---
365
+
366
+ ## 📄 License
367
+
368
+ [MIT](./LICENSE) © MIbnEKhalid