admindb 2.1.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 (119) hide show
  1. package/README.md +368 -335
  2. package/dist/app.js +227 -1
  3. package/dist/auth/config.d.ts +1 -1
  4. package/dist/auth/config.js +109 -1
  5. package/dist/auth/crypto.js +98 -1
  6. package/dist/auth/index.js +21 -1
  7. package/dist/auth/middleware.js +78 -1
  8. package/dist/auth/routes.js +64 -1
  9. package/dist/auth/types.js +7 -1
  10. package/dist/cli/args.d.ts +1 -1
  11. package/dist/cli/args.js +309 -1
  12. package/dist/cli/config.js +118 -1
  13. package/dist/cli/index.js +20 -1
  14. package/dist/cli/runner.js +208 -1
  15. package/dist/cli.js +4 -1
  16. package/dist/data/chain.d.ts +1 -0
  17. package/dist/data/chain.js +130 -0
  18. package/dist/data/datasets.d.ts +1 -1
  19. package/dist/data/datasets.js +171 -1
  20. package/dist/data/detector.d.ts +1 -1
  21. package/dist/data/detector.js +535 -1
  22. package/dist/data/engine.d.ts +1 -1
  23. package/dist/data/engine.js +586 -1
  24. package/dist/data/index.d.ts +1 -1
  25. package/dist/data/index.js +30 -1
  26. package/dist/data/prng.d.ts +1 -0
  27. package/dist/data/prng.js +73 -0
  28. package/dist/data/registry.d.ts +1 -0
  29. package/dist/data/registry.js +805 -0
  30. package/dist/data/schema-graph.d.ts +1 -0
  31. package/dist/data/schema-graph.js +210 -0
  32. package/dist/data/strategies.d.ts +1 -1
  33. package/dist/data/strategies.js +100 -1
  34. package/dist/data/templates.d.ts +1 -0
  35. package/dist/data/templates.js +134 -0
  36. package/dist/data/types.d.ts +1 -1
  37. package/dist/data/types.js +5 -1
  38. package/dist/data/validator.d.ts +1 -0
  39. package/dist/data/validator.js +160 -0
  40. package/dist/db/database.d.ts +1 -1
  41. package/dist/db/database.js +472 -1
  42. package/dist/db/export.d.ts +1 -1
  43. package/dist/db/export.js +67 -1
  44. package/dist/db/filters.d.ts +1 -1
  45. package/dist/db/filters.js +119 -1
  46. package/dist/db/index.js +24 -1
  47. package/dist/db/introspection.js +164 -1
  48. package/dist/db/manager.js +327 -1
  49. package/dist/db/migrations.js +100 -1
  50. package/dist/db/postgres.d.ts +1 -1
  51. package/dist/db/postgres.js +687 -1
  52. package/dist/db/types.d.ts +1 -1
  53. package/dist/db/types.js +6 -1
  54. package/dist/index.d.ts +1 -1
  55. package/dist/index.js +52 -1
  56. package/dist/public/css/app.css +1 -1
  57. package/dist/public/js/api.js +1 -1
  58. package/dist/public/js/browse.js +1 -1
  59. package/dist/public/js/common.js +1 -0
  60. package/dist/public/js/databases.js +1 -1
  61. package/dist/public/js/designer.js +1 -1
  62. package/dist/public/js/forms.js +1 -1
  63. package/dist/public/js/home.js +1 -0
  64. package/dist/public/js/inspector.js +1 -1
  65. package/dist/public/js/query.js +1 -1
  66. package/dist/public/js/schema.js +1 -1
  67. package/dist/public/js/seed.js +1 -1
  68. package/dist/routes/api/erd.d.ts +1 -0
  69. package/dist/routes/api/erd.js +45 -0
  70. package/dist/routes/api/helpers.d.ts +1 -1
  71. package/dist/routes/api/helpers.js +213 -1
  72. package/dist/routes/api/import-export.js +82 -1
  73. package/dist/routes/api/index.js +48 -1
  74. package/dist/routes/api/query.js +74 -1
  75. package/dist/routes/api/rows.js +358 -1
  76. package/dist/routes/api/seed.js +167 -1
  77. package/dist/routes/api/tables.js +216 -1
  78. package/dist/routes/databases.js +210 -1
  79. package/dist/routes/index.js +19 -1
  80. package/dist/routes/pages.js +446 -1
  81. package/dist/serverless.js +149 -1
  82. package/dist/sql/classifier.js +24 -1
  83. package/dist/sql/error-analyzer.d.ts +1 -0
  84. package/dist/sql/error-analyzer.js +550 -0
  85. package/dist/sql/generator.d.ts +1 -1
  86. package/dist/sql/generator.js +245 -1
  87. package/dist/sql/index.js +18 -1
  88. package/dist/types/api.d.ts +1 -1
  89. package/dist/types/api.js +2 -1
  90. package/dist/utils/colors.js +54 -1
  91. package/dist/utils/common.d.ts +1 -1
  92. package/dist/utils/common.js +185 -1
  93. package/dist/utils/csv.d.ts +1 -1
  94. package/dist/utils/csv.js +61 -1
  95. package/dist/utils/datatype.js +167 -1
  96. package/dist/utils/icons.js +81 -1
  97. package/dist/utils/index.js +20 -1
  98. package/dist/utils/logger.js +36 -1
  99. package/dist/views/layouts/main.hbs +1 -74
  100. package/dist/views/pages/databases.hbs +1 -233
  101. package/dist/views/pages/designer.hbs +1 -89
  102. package/dist/views/pages/erd.hbs +1 -0
  103. package/dist/views/pages/error.hbs +1 -10
  104. package/dist/views/pages/form.hbs +1 -59
  105. package/dist/views/pages/home.hbs +1 -124
  106. package/dist/views/pages/info.hbs +1 -0
  107. package/dist/views/pages/login.hbs +1 -98
  108. package/dist/views/pages/query.hbs +1 -87
  109. package/dist/views/pages/schema.hbs +1 -298
  110. package/dist/views/pages/seed-select.hbs +251 -0
  111. package/dist/views/pages/seed.hbs +273 -167
  112. package/dist/views/pages/table.hbs +1 -327
  113. package/dist/views/partials/navbar.hbs +1 -83
  114. package/dist/views/partials/sidebar.hbs +1 -117
  115. package/docs/API.md +149 -144
  116. package/docs/EXAMPLES.md +579 -576
  117. package/docs/SECURITY.md +265 -265
  118. package/package.json +79 -78
  119. package/dist/public/js/icons.js +0 -1
package/README.md CHANGED
@@ -1,335 +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 + Tailwind/DaisyUI; 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
- - **Modern terminal experience:** Clean, colorized startup banner with auto-detected local/network URLs and streamlined runtime logs.
16
- - **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.
17
- - **Safe SQL by construction:** Quoted identifiers, escaped literals, parameterized queries, and non-executing SQL preview modes.
18
-
19
- ---
20
-
21
- ![Home dashboard](docs/screenshots/home.png)
22
-
23
- > 📸 **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.
24
-
25
- ---
26
-
27
- ## ⚡ 30-Second Quickstart
28
-
29
- No installation required:
30
-
31
- ```bash
32
- npx admindb
33
- ```
34
-
35
- 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.
36
-
37
- ### 1. Load database connections securely from a JSON file:
38
-
39
- Create `name.postgres.json`:
40
- ```json
41
- {
42
- "prod": "postgresql://postgres:secret@localhost:5432/prod_db",
43
- "staging": "postgresql://postgres:secret@localhost:5432/staging_db",
44
- "local": "./data/local.db"
45
- }
46
- ```
47
-
48
- Run:
49
- ```bash
50
- npx admindb name.postgres.json
51
- ```
52
-
53
- ### 2. Point directly to a database file or PostgreSQL URI:
54
-
55
- ```bash
56
- npx admindb ./data/app.db # Open a single SQLite database directly
57
- npx admindb postgresql://postgres:secret@localhost:5432/mydb # Open a PostgreSQL database directly
58
- npx admindb -d ./databases # Manage a folder of SQLite databases
59
- npx admindb -p 8080 -r # Run on port 8080 in read-only mode
60
- ```
61
-
62
- ### Install globally:
63
-
64
- ```bash
65
- npm install -g admindb
66
- admindb
67
- ```
68
-
69
- ---
70
-
71
- ## 🖥️ Modern Terminal Experience
72
-
73
- AdminDB features a clean, colorized CLI startup banner and streamlined, low-noise runtime logging:
74
-
75
- ```text
76
- ⚡ AdminDB v2.1.1
77
-
78
- ➜ Local: http://localhost:45531/
79
- ➜ Network: http://192.168.1.15:45531/
80
- ➜ Mode: Manager
81
- ➜ Config: name.postgres.json (2 connection(s))
82
- • prod: PostgreSQL postgresql://postgres:****@localhost:5432/prod_db
83
- • staging: PostgreSQL postgresql://postgres:****@localhost:5432/staging_db
84
- ➜ Auth: User: admin (default password)
85
-
86
- ⚠ Default password in use (admin). Generate a secure hash with:
87
- npm run generatehash and set ADMINDB_PASSWORD or -P <hash>
88
- ```
89
-
90
- Runtime operations produce crisp, color-coded status logs:
91
-
92
- ```text
93
- 16:38:13 [info] Initialized PostgreSQL pool for postgresql://postgres:****@localhost:5432/prod_db
94
- 16:38:15 [info] Executed query in 2.4ms (42 rows returned)
95
- 16:38:18 [warn] Failed login attempt for user "unknown"
96
- ```
97
-
98
- ---
99
-
100
- ## 🌟 Core Features
101
-
102
- ### 🔍 Browse & Edit Rows
103
- * **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.
104
- * **Spreadsheet-Style Inline Editing & Keyboard Navigation:**
105
- * **Full Grid Navigation:** Navigate cells with <kbd>↑</kbd> <kbd>↓</kbd> <kbd>←</kbd> <kbd>→</kbd> or <kbd>Tab</kbd> / <kbd>Shift+Tab</kbd>.
106
- * **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.
107
- * **Interactive Date & Time Presets:** Calendar widget with quick shortcuts (`Now / Today`, `Yesterday`, `Tomorrow`, `+7 Days`, `+30 Days`, `Start of Day`, `End of Day`, `Clear`).
108
- * **PostgreSQL Array Tag Manager:** Interactive chip manager with Enter key chip addition, removal, and `{item1,item2}` array serialization.
109
- * **Quick Copy Shortcut:** Press <kbd>Ctrl+C</kbd> / <kbd>Cmd+C</kbd> on any focused cell to copy its raw value to the clipboard.
110
- * **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.
111
- * **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.
112
- * **Universal Data Inspector:** Rich interactive modal for deep data inspection:
113
- * **JSON / JSONB Viewer & Editor:** Interactive syntax-highlighted tree viewer, expandable nodes, real-time JSON editor, and format **Beautify** & **Minify** tools.
114
- * **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.
115
- * **3-Column Hex Dump:** Professional byte offset, hexadecimal, and printable ASCII viewer for raw binary blobs.
116
- * **Text & Code Inspector:** Full-height editor for lengthy text fields, SQL strings, markdown, UUIDs, and config blobs with copy shortcuts.
117
- * **Row Quick Actions:** 3-dots dropdown menu on each row for *Edit*, *Duplicate Row*, *Copy as JSON*, *Copy SQL INSERT*, and *Delete Row*.
118
- * **Type-Aware Filters:** Filter by exact match, comparison (`>5`, `<=10`), prefix (`pre*`), substring, boolean state, or date/numeric ranges.
119
- * **Bulk Operations:** Select rows to delete in one transaction (with foreign-key impact previews) or export selected rows as CSV/JSON.
120
- * **Related Rows:** Cross-table foreign key indicators show how many child records reference each row, with one-click nested table exploration.
121
-
122
- ### ⚡ Query Runner & SQL Tools
123
- * **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.
124
- * **Saved Named Queries:** Save frequently used queries in the database and reload them from a dropdown menu.
125
- * **Safe SQL Preview:** Generate `CREATE`, `INSERT`, or `UPDATE` SQL without executing it.
126
- * **Full Database Dump:** Download the entire database as a standard SQL file (`CREATE TABLE` + `INSERT` statements).
127
-
128
- ### 🗂️ Visual Schema Designer & Indexes
129
- * **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.
130
- * **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.
131
- * **Index Manager:** Create single or multi-column indexes (plain or unique) with live SQL previews, and drop existing indexes safely.
132
-
133
- ### 🔄 Import, Export & Seed Data Generation
134
- * **CSV Import:** Upload or paste CSV files with column matching, executed transactionally.
135
- * **Data Export:** Download table data or arbitrary SQL query results as CSV or JSON.
136
- * **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.
137
-
138
- ### 📁 Multi-Database Manager
139
- * Manage directories of SQLite files, explicit file lists, or named JSON connections.
140
- * Dedicated landing page with engine badges (`PostgreSQL` / `SQLite`), table counts, connection paths, and seamless database switching.
141
-
142
- ### 🛡️ Strict Read-Only & Serverless Mode
143
- * **Serverless Ready:** Auto-detects ephemeral serverless environments (Vercel, AWS Lambda, Cloudflare Pages, Netlify, GCP Cloud Functions).
144
- * **Smart Serverless Editability Rule:**
145
- * **SQLite** defaults to **read-only** in serverless mode to prevent data loss on ephemeral filesystems.
146
- * **PostgreSQL** is **fully editable and writable** in serverless mode because it connects to persistent remote database services.
147
- * Includes ready-to-use `createServerlessHandler` and `createLambdaHandler` wrappers.
148
-
149
- ---
150
-
151
- ## 🚀 Embed AdminDB in Express
152
-
153
- AdminDB can be mounted directly into any existing Express application under any subpath on the same port:
154
-
155
- ```ts
156
- import express from 'express';
157
- import { createRouter } from 'admindb';
158
-
159
- const app = express();
160
-
161
- app.get('/', (_req, res) => res.send('Main App'));
162
-
163
- // Mount AdminDB for SQLite
164
- app.use('/admin', createRouter({
165
- dbPath: './data/app.db',
166
- basePath: '/admin',
167
- }));
168
-
169
- // Or mount AdminDB for PostgreSQL
170
- app.use('/admin-pg', createRouter({
171
- connection: 'postgresql://postgres:secret@localhost:5432/mydb',
172
- basePath: '/admin-pg',
173
- }));
174
-
175
- app.listen(45531, () => {
176
- console.log('App running on http://localhost:45531 (Admin: http://localhost:45531/admin)');
177
- });
178
- ```
179
-
180
- > 📖 **Full Options & Advanced Embedding Recipes:**
181
- > 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.
182
-
183
- ---
184
-
185
- ## ⚙️ CLI & Environment Variables
186
-
187
- Every setting can be configured via **CLI flags**, **Environment Variables**, or **JSON Configuration Files** (CLI flags override JSON config, which overrides environment variables):
188
-
189
- | Setting | CLI Flag & Aliases | Environment Variable & Aliases | Default | Description |
190
- | :--- | :--- | :--- | :--- | :--- |
191
- | **Config File** | `-C, --config <file.json>` | `ADMINDB_CONFIG` | — | Path to a JSON configuration file containing database credentials & settings |
192
- | **Port** | `-p, --port <port>` | `PORT`, `ADMINDB_PORT` | `45531` | Port to listen on |
193
- | **Host** | `-H, --host <host>` | `HOST`, `ADMINDB_HOST` | `0.0.0.0` | Host / interface to bind |
194
- | **Connection URI** | `-c, --connection, --pg <uri>` | `DATABASE_URL`, `ADMINDB_CONNECTION`, `PG_CONNECTION` | — | PostgreSQL connection URI or path |
195
- | **Single DB** | `-o, --open, --db-path <file>` | `DB_PATH`, `ADMINDB_DB_PATH`, `ADMINDB_PATH` | — | Open a single database file directly |
196
- | **Database Dir** | `-d, --dir, --db-dir <dir>` | `DB_DIR`, `ADMINDB_DB_DIR`, `ADMINDB_DIR` | — | Folder of database files to manage |
197
- | **Explicit Files** | `--files, --db-files <list>` | `DB_FILES`, `ADMINDB_DB_FILES` | — | Comma-separated database file paths |
198
- | **Base Path** | `-b, --base-path, --base <p>` | `BASE_PATH`, `ADMINDB_BASE_PATH` | `''` (`/`) | URL prefix to serve under (e.g. `/admin`) |
199
- | **Read-Only** | `-r, --readonly, --read-only`| `READONLY`, `ADMINDB_READONLY` | `false` | Open databases read-only (writes disabled) |
200
- | **Serverless**| `--serverless` | `SERVERLESS`, `ADMINDB_SERVERLESS` | `false` *(auto)* | Serverless mode (SQLite read-only, Postgres editable) |
201
- | **Auth** | `--auth` / `--no-auth` | `ADMINDB_AUTH`, `ADMINDB_NO_AUTH` | `true` | Enable or disable built-in authentication |
202
- | **Username** | `-u, --username, --user <user>` | `ADMINDB_USERNAME`, `ADMINDB_USER` | `admin` | Admin username |
203
- | **Password** | `-P, --password, --pass <pass>` | `ADMINDB_PASSWORD`, `ADMINDB_PASS` | `admin` *(hash)* | Admin password or salted `scrypt:...` hash |
204
- | **Session Secret**| `--auth-secret, --secret <sec>` | `ADMINDB_SECRET`, `SESSION_SECRET` | *(auto)* | Secret key for signing session cookies |
205
- | **Log Level** | `-l, --log-level <level>` | `LOG_LEVEL`, `ADMINDB_LOG_LEVEL` | `info` | `debug` \| `info` \| `warn` \| `error` |
206
- | **Help** | `-h, --help` | — | — | Show CLI help |
207
- | **Version** | `-v, --version` | — | — | Show version |
208
-
209
- Quick CLI examples:
210
-
211
- ```bash
212
- admindb name.postgres.json # Load credentials from JSON file
213
- admindb postgresql://user:pass@host:5432/db # Open PostgreSQL database
214
- admindb ./data/app.db # Open SQLite database
215
- admindb -d ./databases # Manage a folder of databases
216
- admindb -p 8080 # Run on port 8080
217
- admindb --no-auth # Authentication disabled
218
- ```
219
-
220
- > 📖 **Full Configuration Reference & Deployment Recipes:**
221
- > 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.
222
-
223
- ---
224
-
225
- ## 🔒 Authentication & Security
226
-
227
- > [!WARNING]
228
- > **Important Security Notice:**
229
- > AdminDB's built-in native authentication provides **basic single-user access control** for local development and private internal tools.
230
- > 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.
231
-
232
- ### Generate a Secure Password Hash
233
-
234
- To configure custom credentials with a salted cryptographic `scrypt` hash:
235
-
236
- ```bash
237
- npm run generatehash
238
- ```
239
-
240
- Paste the resulting hash into `ADMINDB_PASSWORD`, CLI `-P`, or your Express configuration:
241
-
242
- ```bash
243
- ADMINDB_USERNAME="ops" ADMINDB_PASSWORD="scrypt:8011bcda...:85465796..." npx admindb
244
- ```
245
-
246
- ### Wrapping with Your Own Express Authentication (Recommended for Production)
247
-
248
- When embedding AdminDB in your Express application, turn off built-in auth (`auth: false`) and protect the route with your existing auth middleware:
249
-
250
- ```ts
251
- import express from 'express';
252
- import { createRouter } from 'admindb';
253
-
254
- const app = express();
255
-
256
- app.use('/admin', requireYourAppAuth, createRouter({
257
- connection: process.env.DATABASE_URL,
258
- basePath: '/admin',
259
- auth: false, // Turn off built-in login form; rely on requireYourAppAuth
260
- }));
261
-
262
- app.listen(45531);
263
- ```
264
-
265
- ### Disabling Built-in Authentication
266
-
267
- When deploying behind an external gateway (Cloudflare Zero Trust, OAuth2 Proxy, Authelia):
268
-
269
- ```bash
270
- admindb --no-auth
271
- # or
272
- ADMINDB_AUTH=false npx admindb
273
- ```
274
-
275
- > 📖 **Full Security Guide:** See [**`docs/SECURITY.md`**](docs/SECURITY.md) for the shared security model, filesystem sandboxing, PostgreSQL remote protection, and production deployment checklists.
276
-
277
-
278
- ---
279
-
280
- ## 📡 REST API
281
-
282
- AdminDB exposes a comprehensive REST API under `basePath` returning `{ success, data?, error? }`:
283
-
284
- ```text
285
- GET /api/tables List tables
286
- GET /api/tables/:table/rows Paginated rows (with filtering & sorting)
287
- GET /api/tables/:table/row/:id Get a single row
288
- GET /api/tables/:table/row/:id/blob/:column Stream raw BLOB / BYTEA binary data
289
- GET /api/tables/:table/row/:id/blob/:col/meta BLOB / BYTEA metadata, MIME analysis & hex dump
290
- PUT /api/tables/:table/row/:id/blob/:column Upload / update binary content
291
- POST /api/tables/:table/rows Insert row (single or batch)
292
- PUT /api/tables/:table/row/:id Update row
293
- DELETE /api/tables/:table/row/:id Delete row
294
- POST /api/tables/:table/rows/bulk-update Apply staged inline edits atomically
295
- POST /api/tables/:table/rows/bulk-delete Delete selected rows atomically
296
- POST /api/tables/:table/seed Generate & insert realistic seed rows
297
- POST /api/tables Create a new table
298
- GET /api/tables/:table/schema Inspect table schema & constraints
299
- GET /api/tables/:table/ddl Get table CREATE SQL & indexes
300
- POST /api/query Execute arbitrary SQL
301
- GET /api/databases List managed database connections & files
302
- ```
303
-
304
- > 📖 **Full API Reference:** See [**`docs/API.md`**](docs/API.md) for detailed documentation of all 30+ endpoints, query parameters, payload schemas, and TypeScript types.
305
-
306
- ---
307
-
308
- ## 📚 Documentation Index
309
-
310
- | Document | Description |
311
- | :--- | :--- |
312
- | [**`docs/EXAMPLES.md`**](docs/EXAMPLES.md) | Comprehensive Environment Variables reference, JSON configs, Express code examples, and deployment recipes. |
313
- | [**`docs/SECURITY.md`**](docs/SECURITY.md) | Authentication architecture, password hashing, reverse proxy setup, and security checklist. |
314
- | [**`docs/API.md`**](docs/API.md) | Complete REST API endpoint reference and TypeScript type exports. |
315
- | [**`CONTRIBUTING.md`**](CONTRIBUTING.md) | Development workflow, running tests, project layout, and contribution guidelines. |
316
-
317
- ---
318
-
319
- ## 🤝 Contributing
320
-
321
- Contributions are welcome! Please check out [**`CONTRIBUTING.md`**](CONTRIBUTING.md) for development setup and testing instructions.
322
-
323
- ```bash
324
- git clone https://github.com/MIbnEKhalid/admindb.git
325
- cd admindb
326
- npm install
327
- npm run dev # Live reload development server
328
- npm test # Run comprehensive unit test suite
329
- ```
330
-
331
- ---
332
-
333
- ## 📄 License
334
-
335
- [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