wide-cli 0.0.0-stage → 0.5.161126

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 (184) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +81 -2
  3. package/bin/wide.js +17 -0
  4. package/dist/agent/context.d.ts +7 -0
  5. package/dist/agent/context.d.ts.map +1 -0
  6. package/dist/agent/context.js +42 -0
  7. package/dist/agent/context.js.map +1 -0
  8. package/dist/agent/index.d.ts +45 -0
  9. package/dist/agent/index.d.ts.map +1 -0
  10. package/dist/agent/index.js +272 -0
  11. package/dist/agent/index.js.map +1 -0
  12. package/dist/completion.d.ts +13 -0
  13. package/dist/completion.d.ts.map +1 -0
  14. package/dist/completion.js +170 -0
  15. package/dist/completion.js.map +1 -0
  16. package/dist/config/index.d.ts +32 -0
  17. package/dist/config/index.d.ts.map +1 -0
  18. package/dist/config/index.js +94 -0
  19. package/dist/config/index.js.map +1 -0
  20. package/dist/config/logger.d.ts +4 -0
  21. package/dist/config/logger.d.ts.map +1 -0
  22. package/dist/config/logger.js +13 -0
  23. package/dist/config/logger.js.map +1 -0
  24. package/dist/config/workspace.d.ts +7 -0
  25. package/dist/config/workspace.d.ts.map +1 -0
  26. package/dist/config/workspace.js +31 -0
  27. package/dist/config/workspace.js.map +1 -0
  28. package/dist/decision/index.d.ts +113 -0
  29. package/dist/decision/index.d.ts.map +1 -0
  30. package/dist/decision/index.js +487 -0
  31. package/dist/decision/index.js.map +1 -0
  32. package/dist/index.d.ts +2 -0
  33. package/dist/index.d.ts.map +1 -0
  34. package/dist/index.js +332 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/providers/claude.d.ts +10 -0
  37. package/dist/providers/claude.d.ts.map +1 -0
  38. package/dist/providers/claude.js +163 -0
  39. package/dist/providers/claude.js.map +1 -0
  40. package/dist/providers/gemini.d.ts +10 -0
  41. package/dist/providers/gemini.d.ts.map +1 -0
  42. package/dist/providers/gemini.js +145 -0
  43. package/dist/providers/gemini.js.map +1 -0
  44. package/dist/providers/index.d.ts +10 -0
  45. package/dist/providers/index.d.ts.map +1 -0
  46. package/dist/providers/index.js +63 -0
  47. package/dist/providers/index.js.map +1 -0
  48. package/dist/providers/ollama.d.ts +15 -0
  49. package/dist/providers/ollama.d.ts.map +1 -0
  50. package/dist/providers/ollama.js +169 -0
  51. package/dist/providers/ollama.js.map +1 -0
  52. package/dist/providers/openai.d.ts +11 -0
  53. package/dist/providers/openai.d.ts.map +1 -0
  54. package/dist/providers/openai.js +158 -0
  55. package/dist/providers/openai.js.map +1 -0
  56. package/dist/providers/retry.d.ts +7 -0
  57. package/dist/providers/retry.d.ts.map +1 -0
  58. package/dist/providers/retry.js +72 -0
  59. package/dist/providers/retry.js.map +1 -0
  60. package/dist/providers/types.d.ts +23 -0
  61. package/dist/providers/types.d.ts.map +1 -0
  62. package/dist/providers/types.js +2 -0
  63. package/dist/providers/types.js.map +1 -0
  64. package/dist/repl/commands.d.ts +18 -0
  65. package/dist/repl/commands.d.ts.map +1 -0
  66. package/dist/repl/commands.js +351 -0
  67. package/dist/repl/commands.js.map +1 -0
  68. package/dist/repl/history.d.ts +3 -0
  69. package/dist/repl/history.d.ts.map +1 -0
  70. package/dist/repl/history.js +57 -0
  71. package/dist/repl/history.js.map +1 -0
  72. package/dist/repl/index.d.ts +10 -0
  73. package/dist/repl/index.d.ts.map +1 -0
  74. package/dist/repl/index.js +345 -0
  75. package/dist/repl/index.js.map +1 -0
  76. package/dist/repl/mentions.d.ts +8 -0
  77. package/dist/repl/mentions.d.ts.map +1 -0
  78. package/dist/repl/mentions.js +100 -0
  79. package/dist/repl/mentions.js.map +1 -0
  80. package/dist/repl/sessions.d.ts +21 -0
  81. package/dist/repl/sessions.d.ts.map +1 -0
  82. package/dist/repl/sessions.js +117 -0
  83. package/dist/repl/sessions.js.map +1 -0
  84. package/dist/repl/setup.d.ts +4 -0
  85. package/dist/repl/setup.d.ts.map +1 -0
  86. package/dist/repl/setup.js +73 -0
  87. package/dist/repl/setup.js.map +1 -0
  88. package/dist/security/fuzzer.d.ts +30 -0
  89. package/dist/security/fuzzer.d.ts.map +1 -0
  90. package/dist/security/fuzzer.js +180 -0
  91. package/dist/security/fuzzer.js.map +1 -0
  92. package/dist/security/loader.d.ts +31 -0
  93. package/dist/security/loader.d.ts.map +1 -0
  94. package/dist/security/loader.js +366 -0
  95. package/dist/security/loader.js.map +1 -0
  96. package/dist/security/payloads.d.ts +9 -0
  97. package/dist/security/payloads.d.ts.map +1 -0
  98. package/dist/security/payloads.js +88 -0
  99. package/dist/security/payloads.js.map +1 -0
  100. package/dist/security/rules.d.ts +16 -0
  101. package/dist/security/rules.d.ts.map +1 -0
  102. package/dist/security/rules.js +381 -0
  103. package/dist/security/rules.js.map +1 -0
  104. package/dist/security/sca.d.ts +39 -0
  105. package/dist/security/sca.d.ts.map +1 -0
  106. package/dist/security/sca.js +464 -0
  107. package/dist/security/sca.js.map +1 -0
  108. package/dist/security/scanner.d.ts +47 -0
  109. package/dist/security/scanner.d.ts.map +1 -0
  110. package/dist/security/scanner.js +353 -0
  111. package/dist/security/scanner.js.map +1 -0
  112. package/dist/security/secrets.d.ts +5 -0
  113. package/dist/security/secrets.d.ts.map +1 -0
  114. package/dist/security/secrets.js +109 -0
  115. package/dist/security/secrets.js.map +1 -0
  116. package/dist/security/taint.d.ts +14 -0
  117. package/dist/security/taint.d.ts.map +1 -0
  118. package/dist/security/taint.js +517 -0
  119. package/dist/security/taint.js.map +1 -0
  120. package/dist/tools/browser.d.ts +110 -0
  121. package/dist/tools/browser.d.ts.map +1 -0
  122. package/dist/tools/browser.js +2105 -0
  123. package/dist/tools/browser.js.map +1 -0
  124. package/dist/tools/db.d.ts +106 -0
  125. package/dist/tools/db.d.ts.map +1 -0
  126. package/dist/tools/db.js +1526 -0
  127. package/dist/tools/db.js.map +1 -0
  128. package/dist/tools/fs.d.ts +5 -0
  129. package/dist/tools/fs.d.ts.map +1 -0
  130. package/dist/tools/fs.js +165 -0
  131. package/dist/tools/fs.js.map +1 -0
  132. package/dist/tools/git.d.ts +3 -0
  133. package/dist/tools/git.d.ts.map +1 -0
  134. package/dist/tools/git.js +50 -0
  135. package/dist/tools/git.js.map +1 -0
  136. package/dist/tools/http.d.ts +3 -0
  137. package/dist/tools/http.d.ts.map +1 -0
  138. package/dist/tools/http.js +74 -0
  139. package/dist/tools/http.js.map +1 -0
  140. package/dist/tools/index.d.ts +5 -0
  141. package/dist/tools/index.d.ts.map +1 -0
  142. package/dist/tools/index.js +72 -0
  143. package/dist/tools/index.js.map +1 -0
  144. package/dist/tools/risk.d.ts +9 -0
  145. package/dist/tools/risk.d.ts.map +1 -0
  146. package/dist/tools/risk.js +156 -0
  147. package/dist/tools/risk.js.map +1 -0
  148. package/dist/tools/search.d.ts +4 -0
  149. package/dist/tools/search.d.ts.map +1 -0
  150. package/dist/tools/search.js +133 -0
  151. package/dist/tools/search.js.map +1 -0
  152. package/dist/tools/security.d.ts +5 -0
  153. package/dist/tools/security.d.ts.map +1 -0
  154. package/dist/tools/security.js +147 -0
  155. package/dist/tools/security.js.map +1 -0
  156. package/dist/tools/shell.d.ts +10 -0
  157. package/dist/tools/shell.d.ts.map +1 -0
  158. package/dist/tools/shell.js +189 -0
  159. package/dist/tools/shell.js.map +1 -0
  160. package/dist/tools/types.d.ts +45 -0
  161. package/dist/tools/types.d.ts.map +1 -0
  162. package/dist/tools/types.js +2 -0
  163. package/dist/tools/types.js.map +1 -0
  164. package/dist/ui/banner.d.ts +24 -0
  165. package/dist/ui/banner.d.ts.map +1 -0
  166. package/dist/ui/banner.js +394 -0
  167. package/dist/ui/banner.js.map +1 -0
  168. package/dist/ui/colors.d.ts +18 -0
  169. package/dist/ui/colors.d.ts.map +1 -0
  170. package/dist/ui/colors.js +19 -0
  171. package/dist/ui/colors.js.map +1 -0
  172. package/dist/ui/diff.d.ts +14 -0
  173. package/dist/ui/diff.d.ts.map +1 -0
  174. package/dist/ui/diff.js +55 -0
  175. package/dist/ui/diff.js.map +1 -0
  176. package/dist/ui/markdown.d.ts +2 -0
  177. package/dist/ui/markdown.d.ts.map +1 -0
  178. package/dist/ui/markdown.js +32 -0
  179. package/dist/ui/markdown.js.map +1 -0
  180. package/dist/ui/spinner.d.ts +14 -0
  181. package/dist/ui/spinner.d.ts.map +1 -0
  182. package/dist/ui/spinner.js +59 -0
  183. package/dist/ui/spinner.js.map +1 -0
  184. package/package.json +61 -4
@@ -0,0 +1,1526 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
2
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync, openSync, readSync, closeSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, extname, join, relative, resolve } from "node:path";
5
+ import pc from "picocolors";
6
+ import { debugLog } from "../config/logger.js";
7
+ import { assessSqlRisk, isQueryReadOnly } from "./risk.js";
8
+ const SECRET_COLUMN_RE = /(password|passwd|pwd|pass_hash|password_hash|secret|token|refresh_token|access_token|api_key|private_key|salt|ssn|credit_card|card_number|cvv)/i;
9
+ const PII_COLUMN_RE = /(email|e_mail|phone|mobile|ssn|social_security|tax_id|passport|birth_date|dob|address|street|ip_address|credit_card|card_number|iban)/i;
10
+ const SQLITE_EXTENSIONS = new Set([".db", ".sqlite", ".sqlite3", ".db3"]);
11
+ const DISCOVERY_SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", ".next", "target", "coverage", "__pycache__"]);
12
+ function getWideDir() {
13
+ const dir = join(homedir(), ".wide");
14
+ if (!existsSync(dir)) {
15
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
16
+ }
17
+ return dir;
18
+ }
19
+ function getOrCreateDbKey() {
20
+ const wideDir = getWideDir();
21
+ const keyPath = join(wideDir, ".db.key");
22
+ if (existsSync(keyPath)) {
23
+ const raw = readFileSync(keyPath, "utf8").trim();
24
+ const buf = Buffer.from(raw, "hex");
25
+ if (buf.length === 32)
26
+ return buf;
27
+ const secretsPath = join(wideDir, "db-secrets.enc");
28
+ if (existsSync(secretsPath)) {
29
+ const backupPath = join(wideDir, `.db.key.corrupt.${Date.now()}`);
30
+ try {
31
+ copyFileSync(keyPath, backupPath);
32
+ }
33
+ catch { }
34
+ debugLog("db", `Backed up corrupt .db.key to ${backupPath}`);
35
+ }
36
+ }
37
+ const key = randomBytes(32);
38
+ writeFileSync(keyPath, key.toString("hex"), { encoding: "utf8", mode: 0o600 });
39
+ return key;
40
+ }
41
+ function encryptSecretsMap(data) {
42
+ const key = getOrCreateDbKey();
43
+ const iv = randomBytes(12);
44
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
45
+ const ciphertext = Buffer.concat([cipher.update(JSON.stringify(data), "utf8"), cipher.final()]);
46
+ const tag = cipher.getAuthTag();
47
+ return JSON.stringify({
48
+ v: 1,
49
+ iv: iv.toString("base64"),
50
+ tag: tag.toString("base64"),
51
+ data: ciphertext.toString("base64"),
52
+ });
53
+ }
54
+ function decryptSecretsMap(raw) {
55
+ try {
56
+ const parsed = JSON.parse(raw);
57
+ if (!parsed || parsed.v !== 1 || !parsed.iv || !parsed.tag || !parsed.data)
58
+ return {};
59
+ const key = getOrCreateDbKey();
60
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(parsed.iv, "base64"));
61
+ decipher.setAuthTag(Buffer.from(parsed.tag, "base64"));
62
+ const plain = Buffer.concat([
63
+ decipher.update(Buffer.from(parsed.data, "base64")),
64
+ decipher.final(),
65
+ ]).toString("utf8");
66
+ const obj = JSON.parse(plain);
67
+ return obj && typeof obj === "object" ? obj : {};
68
+ }
69
+ catch {
70
+ return {};
71
+ }
72
+ }
73
+ function loadStore() {
74
+ const file = join(getWideDir(), "db-connections.json");
75
+ if (!existsSync(file))
76
+ return { connections: [] };
77
+ try {
78
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
79
+ return {
80
+ activeId: typeof parsed.activeId === "string" ? parsed.activeId : undefined,
81
+ connections: Array.isArray(parsed.connections) ? parsed.connections : [],
82
+ };
83
+ }
84
+ catch {
85
+ return { connections: [] };
86
+ }
87
+ }
88
+ function saveStore(store) {
89
+ const file = join(getWideDir(), "db-connections.json");
90
+ writeFileSync(file, JSON.stringify(store, null, 2), { encoding: "utf8", mode: 0o600 });
91
+ }
92
+ function loadSecrets() {
93
+ const file = join(getWideDir(), "db-secrets.enc");
94
+ if (!existsSync(file))
95
+ return {};
96
+ return decryptSecretsMap(readFileSync(file, "utf8"));
97
+ }
98
+ function saveSecret(id, secret) {
99
+ const file = join(getWideDir(), "db-secrets.enc");
100
+ const current = loadSecrets();
101
+ if (secret === undefined) {
102
+ delete current[id];
103
+ }
104
+ else {
105
+ current[id] = secret;
106
+ }
107
+ writeFileSync(file, encryptSecretsMap(current), { encoding: "utf8", mode: 0o600 });
108
+ }
109
+ export function loadDbHistory() {
110
+ const file = join(getWideDir(), "recent-queries.json");
111
+ if (!existsSync(file))
112
+ return [];
113
+ try {
114
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
115
+ return Array.isArray(parsed) ? parsed : [];
116
+ }
117
+ catch {
118
+ return [];
119
+ }
120
+ }
121
+ export function clearDbHistory(connectionId) {
122
+ const file = join(getWideDir(), "recent-queries.json");
123
+ if (!connectionId) {
124
+ writeFileSync(file, "[]", { encoding: "utf8", mode: 0o600 });
125
+ return;
126
+ }
127
+ const filtered = loadDbHistory().filter((item) => item && item.connectionId !== connectionId);
128
+ writeFileSync(file, JSON.stringify(filtered.slice(0, 50), null, 2), { encoding: "utf8", mode: 0o600 });
129
+ }
130
+ function recordDbHistoryEntry(entry) {
131
+ try {
132
+ const cleanSql = maskDsn(String(entry.sql || "")).trim().slice(0, 8000);
133
+ if (!cleanSql)
134
+ return;
135
+ const item = {
136
+ id: `${Date.now()}_${randomBytes(3).toString("hex")}`,
137
+ connectionId: entry.connectionId,
138
+ sql: cleanSql,
139
+ durationMs: entry.durationMs,
140
+ rowCount: entry.rowCount,
141
+ ...(entry.error ? { error: maskDsn(entry.error).slice(0, 500) } : {}),
142
+ ranAt: Date.now(),
143
+ };
144
+ const next = [item, ...loadDbHistory().slice(0, 49)];
145
+ const file = join(getWideDir(), "recent-queries.json");
146
+ writeFileSync(file, JSON.stringify(next, null, 2), { encoding: "utf8", mode: 0o600 });
147
+ }
148
+ catch { }
149
+ }
150
+ export function maskDsn(text) {
151
+ return String(text || "").replace(/([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^:\s/@]+):([^@\s/]+)@/g, "$1:****@");
152
+ }
153
+ function formatMaskedConnectionTarget(conn) {
154
+ if (conn.kind === "sqlite")
155
+ return conn.filePath || "(sqlite)";
156
+ const userPart = conn.username ? `${conn.username}@` : "";
157
+ const host = conn.host || "localhost";
158
+ const port = conn.port ? `:${conn.port}` : "";
159
+ const db = conn.database ? `/${conn.database}` : "";
160
+ const scheme = conn.kind === "postgres" ? "postgresql" : conn.kind;
161
+ return `${scheme}://${userPart}${host}${port}${db}`;
162
+ }
163
+ function slugifyId(raw) {
164
+ const base = raw.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
165
+ return base || `db-${Date.now().toString(36)}`;
166
+ }
167
+ export function parseConnectionTarget(target, workingDirectory, opts = {}) {
168
+ const trimmed = target.trim();
169
+ const env = opts.environment || "local";
170
+ const readOnly = Boolean(opts.readOnly);
171
+ if (trimmed.startsWith("sqlite://") || trimmed.startsWith("file:") || !trimmed.includes("://")) {
172
+ let filePath = trimmed;
173
+ if (filePath.startsWith("sqlite://"))
174
+ filePath = filePath.slice("sqlite://".length);
175
+ if (filePath.startsWith("file:"))
176
+ filePath = filePath.slice("file:".length);
177
+ const resolved = filePath === ":memory:" ? ":memory:" : resolve(workingDirectory, filePath);
178
+ const name = opts.name || (resolved === ":memory:" ? "memory-sqlite" : basename(resolved));
179
+ return {
180
+ meta: {
181
+ id: slugifyId(name),
182
+ name,
183
+ kind: "sqlite",
184
+ environment: env,
185
+ readOnly,
186
+ filePath: resolved,
187
+ createdAt: new Date().toISOString(),
188
+ },
189
+ };
190
+ }
191
+ let url;
192
+ try {
193
+ url = new URL(trimmed);
194
+ }
195
+ catch {
196
+ throw new Error(`Invalid connection URI or SQLite path: ${maskDsn(trimmed)}`);
197
+ }
198
+ const proto = url.protocol.replace(/:$/, "").toLowerCase();
199
+ let kind;
200
+ if (proto === "postgres" || proto === "postgresql")
201
+ kind = "postgres";
202
+ else if (proto === "mysql" || proto === "mysql2")
203
+ kind = "mysql";
204
+ else if (proto === "redis" || proto === "rediss")
205
+ kind = "redis";
206
+ else
207
+ throw new Error(`Unsupported database scheme '${proto}'. Use sqlite, postgres, mysql, or redis.`);
208
+ const host = url.hostname || "localhost";
209
+ const defaultPort = kind === "postgres" ? 5432 : kind === "mysql" ? 3306 : 6379;
210
+ const port = url.port ? Number(url.port) : defaultPort;
211
+ const database = url.pathname ? url.pathname.replace(/^\/+/, "") : (kind === "redis" ? "0" : "");
212
+ const username = url.username ? decodeURIComponent(url.username) : undefined;
213
+ const secret = url.password ? decodeURIComponent(url.password) : undefined;
214
+ const sslParam = (url.searchParams.get("sslmode") || url.searchParams.get("ssl") || "").toLowerCase();
215
+ let sslMode = "default";
216
+ let rejectUnauthorized;
217
+ if (proto === "rediss" || sslParam === "require" || sslParam === "true" || sslParam === "1") {
218
+ sslMode = "require";
219
+ rejectUnauthorized = false;
220
+ }
221
+ else if (sslParam === "verify-full" || sslParam === "verify-ca") {
222
+ sslMode = "verify-full";
223
+ rejectUnauthorized = true;
224
+ }
225
+ else if (sslParam === "disable" || sslParam === "false" || sslParam === "0") {
226
+ sslMode = "disable";
227
+ rejectUnauthorized = false;
228
+ }
229
+ const name = opts.name || `${kind}-${host}-${database || port}`;
230
+ return {
231
+ meta: {
232
+ id: slugifyId(name),
233
+ name,
234
+ kind,
235
+ environment: env,
236
+ readOnly,
237
+ host,
238
+ port,
239
+ database,
240
+ username,
241
+ sslMode,
242
+ rejectUnauthorized,
243
+ createdAt: new Date().toISOString(),
244
+ },
245
+ secret,
246
+ };
247
+ }
248
+ function isLocalHost(host) {
249
+ const h = (host || "").trim().toLowerCase();
250
+ return !h || h === "localhost" || h === "127.0.0.1" || h === "::1";
251
+ }
252
+ function buildPgSsl(meta) {
253
+ if (meta.sslMode === "disable")
254
+ return false;
255
+ if (meta.sslMode === "verify-full")
256
+ return { rejectUnauthorized: true };
257
+ if (meta.sslMode === "require")
258
+ return { rejectUnauthorized: meta.rejectUnauthorized ?? false };
259
+ return undefined;
260
+ }
261
+ function buildMysqlSsl(meta) {
262
+ if (meta.sslMode === "disable" || meta.sslMode === "default")
263
+ return undefined;
264
+ return { rejectUnauthorized: meta.sslMode === "verify-full" ? true : (meta.rejectUnauthorized ?? false) };
265
+ }
266
+ async function openSqlite(filePath, readOnly) {
267
+ if (readOnly && filePath !== ":memory:" && !existsSync(filePath)) {
268
+ throw new Error(`SQLite database not found: ${filePath}`);
269
+ }
270
+ let sqliteMod;
271
+ try {
272
+ sqliteMod = await import("node:sqlite");
273
+ }
274
+ catch (err) {
275
+ throw new Error(`Built-in node:sqlite unavailable (requires Node >= 22.5): ${err?.message || String(err)}`);
276
+ }
277
+ const DatabaseSync = sqliteMod.DatabaseSync;
278
+ if (typeof DatabaseSync !== "function") {
279
+ throw new Error("node:sqlite DatabaseSync export missing.");
280
+ }
281
+ return new DatabaseSync(filePath, { readOnly: Boolean(readOnly) });
282
+ }
283
+ function normalizeRows(rawRows) {
284
+ const colSet = new Set();
285
+ const rows = [];
286
+ for (const r of rawRows) {
287
+ if (r && typeof r === "object" && !Array.isArray(r)) {
288
+ const copy = {};
289
+ for (const [k, v] of Object.entries(r)) {
290
+ colSet.add(k);
291
+ copy[k] = typeof v === "bigint" ? v.toString() : v instanceof Uint8Array ? `<Buffer ${v.length}B>` : v;
292
+ }
293
+ rows.push(copy);
294
+ }
295
+ }
296
+ return { columns: [...colSet], rows };
297
+ }
298
+ function redactRowsForAi(columns, rows) {
299
+ const secretCols = new Set(columns.filter((c) => SECRET_COLUMN_RE.test(c)));
300
+ if (secretCols.size === 0)
301
+ return rows;
302
+ return rows.map((row) => {
303
+ const out = {};
304
+ for (const col of columns) {
305
+ out[col] = secretCols.has(col) && row[col] !== null && row[col] !== undefined ? "[REDACTED]" : row[col];
306
+ }
307
+ return out;
308
+ });
309
+ }
310
+ async function withDbDriver(meta, secret, fn) {
311
+ if (meta.kind === "sqlite") {
312
+ const db = await openSqlite(meta.filePath || ":memory:", meta.readOnly);
313
+ try {
314
+ return await fn({ kind: "sqlite", db });
315
+ }
316
+ finally {
317
+ try {
318
+ db.close();
319
+ }
320
+ catch { }
321
+ }
322
+ }
323
+ if (meta.kind === "postgres") {
324
+ const pgMod = await import("pg");
325
+ const Client = pgMod.Client || pgMod.default?.Client;
326
+ const client = new Client({
327
+ host: meta.host || "localhost",
328
+ port: meta.port || 5432,
329
+ database: meta.database || "postgres",
330
+ user: meta.username,
331
+ password: secret,
332
+ ssl: buildPgSsl(meta),
333
+ connectionTimeoutMillis: 8000,
334
+ query_timeout: 20000,
335
+ });
336
+ client.on?.("error", (err) => debugLog("db:pg", err.message));
337
+ try {
338
+ await client.connect();
339
+ return await fn({ kind: "postgres", db: client });
340
+ }
341
+ finally {
342
+ await client.end().catch(() => { });
343
+ }
344
+ }
345
+ if (meta.kind === "mysql") {
346
+ const mysqlMod = await import("mysql2/promise");
347
+ const createConnection = mysqlMod.createConnection || mysqlMod.default?.createConnection;
348
+ const conn = await createConnection({
349
+ host: meta.host || "localhost",
350
+ port: meta.port || 3306,
351
+ database: meta.database || undefined,
352
+ user: meta.username,
353
+ password: secret,
354
+ ssl: buildMysqlSsl(meta),
355
+ connectTimeout: 8000,
356
+ });
357
+ try {
358
+ return await fn({ kind: "mysql", db: conn });
359
+ }
360
+ finally {
361
+ await conn.end().catch(() => { });
362
+ }
363
+ }
364
+ const redisMod = await import("ioredis");
365
+ const RedisCtor = redisMod.default || redisMod.Redis || redisMod;
366
+ const redis = new RedisCtor({
367
+ host: meta.host || "localhost",
368
+ port: meta.port || 6379,
369
+ username: meta.username || undefined,
370
+ password: secret || undefined,
371
+ db: meta.database ? Number(meta.database) || 0 : 0,
372
+ tls: meta.sslMode === "require" || meta.sslMode === "verify-full"
373
+ ? { rejectUnauthorized: meta.sslMode === "verify-full" }
374
+ : undefined,
375
+ connectTimeout: 8000,
376
+ lazyConnect: true,
377
+ maxRetriesPerRequest: 1,
378
+ });
379
+ redis.on?.("error", (err) => debugLog("db:redis", err.message));
380
+ try {
381
+ await redis.connect();
382
+ return await fn({ kind: "redis", db: redis });
383
+ }
384
+ finally {
385
+ await redis.quit().catch(() => {
386
+ try {
387
+ redis.disconnect();
388
+ }
389
+ catch { }
390
+ });
391
+ }
392
+ }
393
+ export async function testDatabaseConnection(meta, secret) {
394
+ return withDbDriver(meta, secret, async ({ kind, db }) => {
395
+ if (kind === "sqlite") {
396
+ const row = db.prepare("SELECT sqlite_version() AS version").get();
397
+ return `SQLite ${row?.version || "connected"}`;
398
+ }
399
+ if (kind === "postgres") {
400
+ const res = await db.query("SELECT version() AS version");
401
+ return String(res.rows?.[0]?.version || "PostgreSQL connected").split(",")[0];
402
+ }
403
+ if (kind === "mysql") {
404
+ const [rows] = await db.query("SELECT VERSION() AS version");
405
+ const first = Array.isArray(rows) ? rows[0] : null;
406
+ return `MySQL ${first?.version || "connected"}`;
407
+ }
408
+ const pong = await db.ping();
409
+ return `Redis (${pong})`;
410
+ });
411
+ }
412
+ function quoteSqliteIdent(name) {
413
+ return `"${String(name).replace(/"/g, '""')}"`;
414
+ }
415
+ export async function inspectDatabaseSchema(meta, secret) {
416
+ return withDbDriver(meta, secret, async ({ kind, db }) => {
417
+ const target = formatMaskedConnectionTarget(meta);
418
+ if (kind === "redis") {
419
+ const infoText = String(await db.info("server").catch(() => ""));
420
+ const memText = String(await db.info("memory").catch(() => ""));
421
+ const version = infoText.match(/redis_version:([^\r\n]+)/)?.[1]?.trim();
422
+ const usedMemory = memText.match(/used_memory_human:([^\r\n]+)/)?.[1]?.trim();
423
+ const dbSize = Number(await db.dbsize().catch(() => 0));
424
+ const scanRes = await db.scan("0", "COUNT", "50").catch(() => ["0", []]);
425
+ const keys = Array.isArray(scanRes?.[1]) ? scanRes[1] : [];
426
+ const sampleKeys = [];
427
+ for (const k of keys.slice(0, 30)) {
428
+ const [type, ttl] = await Promise.all([
429
+ db.type(k).catch(() => "unknown"),
430
+ db.ttl(k).catch(() => -1),
431
+ ]);
432
+ sampleKeys.push({ key: String(k), type: String(type), ttl: Number(ttl) });
433
+ }
434
+ return {
435
+ kind,
436
+ target,
437
+ tables: [],
438
+ redis: { version, usedMemory, dbSize, sampleKeys },
439
+ };
440
+ }
441
+ const tables = [];
442
+ if (kind === "sqlite") {
443
+ const entries = db.prepare("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' ORDER BY name").all();
444
+ for (const entry of entries) {
445
+ const qName = quoteSqliteIdent(entry.name);
446
+ const colsRaw = db.prepare(`PRAGMA table_info(${qName})`).all();
447
+ const fksRaw = db.prepare(`PRAGMA foreign_key_list(${qName})`).all();
448
+ let rowCount;
449
+ try {
450
+ const c = db.prepare(`SELECT COUNT(*) AS cnt FROM ${qName}`).get();
451
+ rowCount = Number(c?.cnt ?? 0);
452
+ }
453
+ catch { }
454
+ tables.push({
455
+ name: entry.name,
456
+ type: entry.type === "view" ? "view" : "table",
457
+ rowCount,
458
+ columns: colsRaw.map((c) => ({
459
+ name: String(c.name),
460
+ type: String(c.type || "ANY"),
461
+ nullable: c.notnull === 0 && c.pk === 0,
462
+ primaryKey: Number(c.pk) > 0,
463
+ defaultValue: c.dflt_value !== undefined && c.dflt_value !== null ? String(c.dflt_value) : null,
464
+ })),
465
+ foreignKeys: fksRaw.map((fk) => ({
466
+ column: String(fk.from),
467
+ refTable: String(fk.table),
468
+ refColumn: String(fk.to),
469
+ })),
470
+ });
471
+ }
472
+ return { kind, target, tables };
473
+ }
474
+ if (kind === "postgres") {
475
+ const tRes = await db.query(`SELECT table_name, table_type FROM information_schema.tables
476
+ WHERE table_schema = 'public' ORDER BY table_name`);
477
+ const cRes = await db.query(`SELECT table_name, column_name, data_type, is_nullable, column_default
478
+ FROM information_schema.columns WHERE table_schema = 'public'
479
+ ORDER BY table_name, ordinal_position`);
480
+ const pkRes = await db.query(`SELECT kcu.table_name, kcu.column_name
481
+ FROM information_schema.table_constraints tc
482
+ JOIN information_schema.key_column_usage kcu
483
+ ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
484
+ WHERE tc.table_schema = 'public' AND tc.constraint_type = 'PRIMARY KEY'`);
485
+ const fkRes = await db.query(`SELECT kcu.table_name, kcu.column_name, ccu.table_name AS ref_table, ccu.column_name AS ref_column
486
+ FROM information_schema.table_constraints tc
487
+ JOIN information_schema.key_column_usage kcu
488
+ ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
489
+ JOIN information_schema.constraint_column_usage ccu
490
+ ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
491
+ WHERE tc.table_schema = 'public' AND tc.constraint_type = 'FOREIGN KEY'`);
492
+ const pkSet = new Set(pkRes.rows.map((r) => `${r.table_name}.${r.column_name}`));
493
+ for (const t of tRes.rows) {
494
+ tables.push({
495
+ name: String(t.table_name),
496
+ type: String(t.table_type).toUpperCase().includes("VIEW") ? "view" : "table",
497
+ columns: cRes.rows
498
+ .filter((c) => c.table_name === t.table_name)
499
+ .map((c) => ({
500
+ name: String(c.column_name),
501
+ type: String(c.data_type),
502
+ nullable: c.is_nullable === "YES",
503
+ primaryKey: pkSet.has(`${t.table_name}.${c.column_name}`),
504
+ defaultValue: c.column_default !== null ? String(c.column_default) : null,
505
+ })),
506
+ foreignKeys: fkRes.rows
507
+ .filter((f) => f.table_name === t.table_name)
508
+ .map((f) => ({
509
+ column: String(f.column_name),
510
+ refTable: String(f.ref_table),
511
+ refColumn: String(f.ref_column),
512
+ })),
513
+ });
514
+ }
515
+ return { kind, target, tables };
516
+ }
517
+ const dbName = meta.database;
518
+ const [tRows] = await db.query("SELECT TABLE_NAME AS table_name, TABLE_TYPE AS table_type FROM information_schema.TABLES WHERE TABLE_SCHEMA = COALESCE(?, DATABASE()) ORDER BY TABLE_NAME", [dbName || null]);
519
+ const [cRows] = await db.query("SELECT TABLE_NAME AS table_name, COLUMN_NAME AS column_name, DATA_TYPE AS data_type, IS_NULLABLE AS is_nullable, COLUMN_KEY AS column_key, COLUMN_DEFAULT AS column_default FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = COALESCE(?, DATABASE()) ORDER BY TABLE_NAME, ORDINAL_POSITION", [dbName || null]);
520
+ const [fkRows] = await db.query("SELECT TABLE_NAME AS table_name, COLUMN_NAME AS column_name, REFERENCED_TABLE_NAME AS ref_table, REFERENCED_COLUMN_NAME AS ref_column FROM information_schema.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = COALESCE(?, DATABASE()) AND REFERENCED_TABLE_NAME IS NOT NULL", [dbName || null]);
521
+ for (const t of tRows) {
522
+ tables.push({
523
+ name: String(t.table_name),
524
+ type: String(t.table_type).toUpperCase().includes("VIEW") ? "view" : "table",
525
+ columns: cRows
526
+ .filter((c) => c.table_name === t.table_name)
527
+ .map((c) => ({
528
+ name: String(c.column_name),
529
+ type: String(c.data_type),
530
+ nullable: c.is_nullable === "YES",
531
+ primaryKey: c.column_key === "PRI",
532
+ defaultValue: c.column_default !== null ? String(c.column_default) : null,
533
+ })),
534
+ foreignKeys: fkRows
535
+ .filter((f) => f.table_name === t.table_name)
536
+ .map((f) => ({
537
+ column: String(f.column_name),
538
+ refTable: String(f.ref_table),
539
+ refColumn: String(f.ref_column),
540
+ })),
541
+ });
542
+ }
543
+ return { kind, target, tables };
544
+ });
545
+ }
546
+ export function splitShellLikeArgs(input) {
547
+ const tokens = [];
548
+ let cur = "";
549
+ let quote = null;
550
+ for (let i = 0; i < input.length; i++) {
551
+ const ch = input[i];
552
+ if (quote) {
553
+ if (ch === quote && input[i - 1] !== "\\") {
554
+ quote = null;
555
+ }
556
+ else if (ch === "\\" && (input[i + 1] === quote || input[i + 1] === "\\")) {
557
+ i++;
558
+ cur += input[i];
559
+ }
560
+ else {
561
+ cur += ch;
562
+ }
563
+ continue;
564
+ }
565
+ if (ch === '"' || ch === "'") {
566
+ quote = ch;
567
+ continue;
568
+ }
569
+ if (/\s/.test(ch)) {
570
+ if (cur.length > 0) {
571
+ tokens.push(cur);
572
+ cur = "";
573
+ }
574
+ continue;
575
+ }
576
+ cur += ch;
577
+ }
578
+ if (cur.length > 0)
579
+ tokens.push(cur);
580
+ return tokens;
581
+ }
582
+ export async function executeDatabaseQuery(meta, secret, query, maxRows = 500) {
583
+ if (meta.readOnly && !isQueryReadOnly(query, meta.kind)) {
584
+ throw new Error(`Connection '${meta.name}' is configured as read-only; write/DDL queries are blocked.`);
585
+ }
586
+ const start = Date.now();
587
+ try {
588
+ const result = await withDbDriver(meta, secret, async ({ kind, db }) => {
589
+ if (kind === "redis") {
590
+ const parts = splitShellLikeArgs(query);
591
+ const cmd = parts[0]?.toLowerCase();
592
+ if (!cmd)
593
+ throw new Error("Empty Redis command.");
594
+ const raw = await db.call(cmd, ...parts.slice(1));
595
+ const rows = Array.isArray(raw)
596
+ ? raw.slice(0, maxRows).map((val, index) => ({ index, value: typeof val === "object" ? JSON.stringify(val) : String(val ?? "") }))
597
+ : [{ result: typeof raw === "object" && raw !== null ? JSON.stringify(raw) : String(raw ?? "OK") }];
598
+ return {
599
+ columns: Object.keys(rows[0] || { result: "" }),
600
+ rows,
601
+ rowCount: rows.length,
602
+ elapsedMs: Date.now() - start,
603
+ truncated: Array.isArray(raw) && raw.length > maxRows,
604
+ };
605
+ }
606
+ if (kind === "sqlite") {
607
+ const trimmed = query.trim();
608
+ if (isQueryReadOnly(trimmed, "sqlite") && !trimmed.includes(";")) {
609
+ const stmt = db.prepare(trimmed);
610
+ const rawRows = stmt.all();
611
+ const truncated = rawRows.length > maxRows;
612
+ const sliced = truncated ? rawRows.slice(0, maxRows) : rawRows;
613
+ const { columns, rows } = normalizeRows(sliced);
614
+ return { columns, rows, rowCount: rows.length, elapsedMs: Date.now() - start, truncated };
615
+ }
616
+ db.exec(trimmed);
617
+ let changes = 0;
618
+ try {
619
+ const ch = db.prepare("SELECT changes() AS changes").get();
620
+ changes = Number(ch?.changes ?? 0);
621
+ }
622
+ catch { }
623
+ return { columns: [], rows: [], rowCount: 0, changes, elapsedMs: Date.now() - start };
624
+ }
625
+ if (kind === "postgres") {
626
+ const res = await db.query(query);
627
+ const rawRows = Array.isArray(res.rows) ? res.rows : [];
628
+ const truncated = rawRows.length > maxRows;
629
+ const sliced = truncated ? rawRows.slice(0, maxRows) : rawRows;
630
+ const { columns, rows } = normalizeRows(sliced);
631
+ return {
632
+ columns: columns.length ? columns : (res.fields || []).map((f) => String(f.name)),
633
+ rows,
634
+ rowCount: rows.length,
635
+ changes: typeof res.rowCount === "number" && rows.length === 0 ? res.rowCount : undefined,
636
+ elapsedMs: Date.now() - start,
637
+ truncated,
638
+ };
639
+ }
640
+ const [res] = await db.query(query);
641
+ if (Array.isArray(res)) {
642
+ const truncated = res.length > maxRows;
643
+ const sliced = truncated ? res.slice(0, maxRows) : res;
644
+ const { columns, rows } = normalizeRows(sliced);
645
+ return { columns, rows, rowCount: rows.length, elapsedMs: Date.now() - start, truncated };
646
+ }
647
+ return {
648
+ columns: [],
649
+ rows: [],
650
+ rowCount: 0,
651
+ changes: Number(res?.affectedRows ?? 0),
652
+ elapsedMs: Date.now() - start,
653
+ };
654
+ });
655
+ recordDbHistoryEntry({
656
+ connectionId: meta.id,
657
+ sql: query,
658
+ durationMs: result.elapsedMs,
659
+ rowCount: result.columns.length > 0 ? result.rowCount : Number(result.changes ?? 0),
660
+ });
661
+ return result;
662
+ }
663
+ catch (err) {
664
+ recordDbHistoryEntry({
665
+ connectionId: meta.id,
666
+ sql: query,
667
+ durationMs: Date.now() - start,
668
+ rowCount: 0,
669
+ error: err?.message || String(err),
670
+ });
671
+ throw err;
672
+ }
673
+ }
674
+ function classifyPasswordSample(val) {
675
+ if (typeof val !== "string" || !val.trim())
676
+ return "skip";
677
+ const s = val.trim();
678
+ if (/^\$2[aby]\$/.test(s) || /^\$argon2(id|i|d)\$/.test(s) || /^\$scrypt\$/.test(s) || /^pbkdf2[:$]/.test(s)) {
679
+ return "strong";
680
+ }
681
+ if (/^[a-f0-9]{32}$/i.test(s))
682
+ return "weak_md5";
683
+ if (/^[a-f0-9]{40}$/i.test(s))
684
+ return "weak_sha1";
685
+ return "weak_plain_or_short";
686
+ }
687
+ export async function auditDatabaseSecurity(meta, secret) {
688
+ const findings = [];
689
+ if (meta.environment === "prod" && !meta.readOnly) {
690
+ findings.push({
691
+ severity: "HIGH",
692
+ category: "access-control",
693
+ target: meta.name,
694
+ message: "Production connection is configured with write access (readOnly=false).",
695
+ recommendation: "Reconnect or mark production profiles with --readonly unless mutations are explicitly required.",
696
+ });
697
+ }
698
+ if (meta.kind !== "sqlite") {
699
+ if (meta.sslMode === "disable") {
700
+ findings.push({
701
+ severity: isLocalHost(meta.host) ? "MEDIUM" : "CRITICAL",
702
+ category: "transport-security",
703
+ target: `${meta.host}:${meta.port}`,
704
+ message: "TLS is explicitly disabled (sslmode=disable); credentials and query data travel in cleartext.",
705
+ recommendation: "Enable TLS with verify-full (sslmode=verify-full or rediss://).",
706
+ });
707
+ }
708
+ else if (!isLocalHost(meta.host) && meta.sslMode === "default") {
709
+ findings.push({
710
+ severity: "HIGH",
711
+ category: "transport-security",
712
+ target: `${meta.host}:${meta.port}`,
713
+ message: "Remote database connection does not enforce TLS certificate verification.",
714
+ recommendation: "Configure sslmode=verify-full or rediss:// with strict certificate verification.",
715
+ });
716
+ }
717
+ else if (meta.rejectUnauthorized === false) {
718
+ findings.push({
719
+ severity: "MEDIUM",
720
+ category: "transport-security",
721
+ target: `${meta.host}:${meta.port}`,
722
+ message: "TLS certificate verification is relaxed (rejectUnauthorized=false), allowing MITM spoofing.",
723
+ recommendation: "Use sslmode=verify-full with trusted CA certificates.",
724
+ });
725
+ }
726
+ }
727
+ else if (meta.filePath && meta.filePath !== ":memory:" && existsSync(meta.filePath)) {
728
+ try {
729
+ const fd = openSync(meta.filePath, "r");
730
+ const header = Buffer.alloc(16);
731
+ readSync(fd, header, 0, 16, 0);
732
+ closeSync(fd);
733
+ if (header.toString("ascii", 0, 15) === "SQLite format 3") {
734
+ findings.push({
735
+ severity: "INFO",
736
+ category: "storage-encryption",
737
+ target: meta.filePath,
738
+ message: "SQLite file is unencrypted on disk (standard SQLite format 3 header).",
739
+ recommendation: "Do not commit database files containing PII/credentials; use SQLCipher or disk encryption in production.",
740
+ });
741
+ }
742
+ if (process.platform !== "win32") {
743
+ const mode = statSync(meta.filePath).mode & 0o777;
744
+ if ((mode & 0o077) !== 0) {
745
+ findings.push({
746
+ severity: "MEDIUM",
747
+ category: "file-permissions",
748
+ target: meta.filePath,
749
+ message: `SQLite file permissions (${mode.toString(8)}) allow group/world access.`,
750
+ recommendation: `Restrict file permissions to owner-only (chmod 600 ${meta.filePath}).`,
751
+ });
752
+ }
753
+ }
754
+ }
755
+ catch { }
756
+ }
757
+ const schema = await inspectDatabaseSchema(meta, secret);
758
+ if (schema.kind === "redis" && schema.redis) {
759
+ if (schema.redis.sampleKeys.some((k) => /(session|token|secret|password|auth)/i.test(k.key) && k.ttl === -1)) {
760
+ findings.push({
761
+ severity: "MEDIUM",
762
+ category: "key-hygiene",
763
+ target: meta.name,
764
+ message: "Sensitive auth/session keys detected without TTL expiration (TTL = -1).",
765
+ recommendation: "Set bounded TTL expirations on session, token, and auth cache keys.",
766
+ });
767
+ }
768
+ return findings;
769
+ }
770
+ const piiTables = [];
771
+ const authColumns = [];
772
+ for (const table of schema.tables) {
773
+ const piiCols = table.columns.filter((c) => PII_COLUMN_RE.test(c.name)).map((c) => c.name);
774
+ if (piiCols.length > 0) {
775
+ piiTables.push(`${table.name} (${piiCols.join(", ")})`);
776
+ }
777
+ for (const col of table.columns) {
778
+ if (/(password|passwd|pass_hash|password_hash)/i.test(col.name)) {
779
+ authColumns.push({ table: table.name, column: col.name });
780
+ }
781
+ }
782
+ }
783
+ if (piiTables.length > 0) {
784
+ findings.push({
785
+ severity: "INFO",
786
+ category: "pii-discovery",
787
+ target: meta.name,
788
+ message: `PII-bearing columns found in ${piiTables.length} table(s): ${piiTables.slice(0, 6).join("; ")}`,
789
+ recommendation: "Apply least-privilege access, encryption at rest, and retention/anonymization policies.",
790
+ });
791
+ }
792
+ if (authColumns.length > 0 && (meta.kind === "sqlite" || meta.kind === "postgres" || meta.kind === "mysql")) {
793
+ await withDbDriver(meta, secret, async ({ kind, db }) => {
794
+ for (const { table, column } of authColumns.slice(0, 8)) {
795
+ try {
796
+ const qt = kind === "mysql" ? `\`${table.replace(/`/g, "``")}\`` : quoteSqliteIdent(table);
797
+ const qc = kind === "mysql" ? `\`${column.replace(/`/g, "``")}\`` : quoteSqliteIdent(column);
798
+ const sql = `SELECT ${qc} AS val FROM ${qt} WHERE ${qc} IS NOT NULL LIMIT 20`;
799
+ let vals = [];
800
+ if (kind === "sqlite") {
801
+ vals = db.prepare(sql).all().map((r) => r?.val);
802
+ }
803
+ else if (kind === "postgres") {
804
+ vals = (await db.query(sql)).rows.map((r) => r?.val);
805
+ }
806
+ else if (kind === "mysql") {
807
+ const [rows] = await db.query(sql);
808
+ vals = (Array.isArray(rows) ? rows : []).map((r) => r?.val);
809
+ }
810
+ const counts = { weak_plain_or_short: 0, weak_md5: 0, weak_sha1: 0, strong: 0 };
811
+ for (const v of vals) {
812
+ const cls = classifyPasswordSample(v);
813
+ if (cls !== "skip")
814
+ counts[cls]++;
815
+ }
816
+ if (counts.weak_plain_or_short > 0 || counts.weak_md5 > 0 || counts.weak_sha1 > 0) {
817
+ const details = [];
818
+ if (counts.weak_plain_or_short)
819
+ details.push(`${counts.weak_plain_or_short} plaintext/unrecognized`);
820
+ if (counts.weak_md5)
821
+ details.push(`${counts.weak_md5} MD5-like`);
822
+ if (counts.weak_sha1)
823
+ details.push(`${counts.weak_sha1} SHA1-like`);
824
+ findings.push({
825
+ severity: "CRITICAL",
826
+ category: "weak-credential-storage",
827
+ target: `${table}.${column}`,
828
+ message: `Weak or unhashed credential values sampled in '${table}.${column}' (${details.join(", ")}).`,
829
+ recommendation: "Migrate password storage to Argon2id, scrypt, or bcrypt.",
830
+ });
831
+ }
832
+ }
833
+ catch { }
834
+ }
835
+ });
836
+ }
837
+ return findings;
838
+ }
839
+ export function discoverWorkspaceDatabases(workingDirectory) {
840
+ const results = [];
841
+ const walk = (dir, depth) => {
842
+ if (depth > 3 || results.length >= 40)
843
+ return;
844
+ let entries;
845
+ try {
846
+ entries = readdirSync(dir, { withFileTypes: true });
847
+ }
848
+ catch {
849
+ return;
850
+ }
851
+ for (const entry of entries) {
852
+ if (DISCOVERY_SKIP_DIRS.has(entry.name))
853
+ continue;
854
+ if (entry.name.startsWith(".env"))
855
+ continue;
856
+ const fullPath = join(dir, entry.name);
857
+ const rel = relative(workingDirectory, fullPath);
858
+ if (entry.isDirectory()) {
859
+ walk(fullPath, depth + 1);
860
+ }
861
+ else if (entry.isFile()) {
862
+ const lower = entry.name.toLowerCase();
863
+ const ext = extname(lower);
864
+ if (SQLITE_EXTENSIONS.has(ext)) {
865
+ results.push({ kind: "sqlite", path: rel });
866
+ }
867
+ else if (lower === "schema.prisma") {
868
+ results.push({ kind: "prisma", path: rel });
869
+ }
870
+ else if (lower.startsWith("drizzle.config.")) {
871
+ results.push({ kind: "drizzle", path: rel });
872
+ }
873
+ else if (lower === "docker-compose.yml" || lower === "docker-compose.yaml" || lower === "compose.yml" || lower === "compose.yaml") {
874
+ results.push({ kind: "compose", path: rel });
875
+ }
876
+ }
877
+ }
878
+ };
879
+ walk(workingDirectory, 0);
880
+ return results;
881
+ }
882
+ function resolveTargetConnection(refOrEmpty, workingDirectory) {
883
+ const store = loadStore();
884
+ const secrets = loadSecrets();
885
+ if (!refOrEmpty) {
886
+ if (!store.activeId) {
887
+ throw new Error("No active database connection. Run '/db connect <sqlite-path-or-uri>' or provide a connection id/path.");
888
+ }
889
+ const found = store.connections.find((c) => c.id === store.activeId);
890
+ if (!found)
891
+ throw new Error(`Active connection '${store.activeId}' no longer exists.`);
892
+ return { meta: found, secret: secrets[found.id] };
893
+ }
894
+ const bySaved = store.connections.find((c) => c.id.toLowerCase() === refOrEmpty.toLowerCase() || c.name.toLowerCase() === refOrEmpty.toLowerCase());
895
+ if (bySaved) {
896
+ return { meta: bySaved, secret: secrets[bySaved.id] };
897
+ }
898
+ const maybePath = resolve(workingDirectory, refOrEmpty);
899
+ if (existsSync(maybePath) || refOrEmpty === ":memory:" || refOrEmpty.startsWith("sqlite://")) {
900
+ return parseConnectionTarget(refOrEmpty, workingDirectory, { readOnly: true });
901
+ }
902
+ if (refOrEmpty.includes("://")) {
903
+ return parseConnectionTarget(refOrEmpty, workingDirectory, { readOnly: true });
904
+ }
905
+ throw new Error(`Database connection or file not found: '${refOrEmpty}'.`);
906
+ }
907
+ function formatAsciiTable(columns, rows) {
908
+ if (columns.length === 0)
909
+ return "(no columns)";
910
+ const maxColWidth = 38;
911
+ const stringifyCell = (val) => {
912
+ if (val === null || val === undefined)
913
+ return "NULL";
914
+ const s = typeof val === "object" ? JSON.stringify(val) : String(val);
915
+ return s.length > maxColWidth ? s.slice(0, maxColWidth - 3) + "..." : s.replace(/[\r\n]+/g, " ");
916
+ };
917
+ const widths = columns.map((col) => {
918
+ let w = col.length;
919
+ for (const r of rows) {
920
+ w = Math.max(w, stringifyCell(r[col]).length);
921
+ }
922
+ return Math.min(maxColWidth, w);
923
+ });
924
+ const sep = "+-" + widths.map((w) => "-".repeat(w)).join("-+-") + "-+";
925
+ const header = "| " + columns.map((c, i) => pc.bold(c.padEnd(widths[i]))).join(" | ") + " |";
926
+ const body = rows.map((r) => "| " + columns.map((c, i) => stringifyCell(r[c]).padEnd(widths[i])).join(" | ") + " |");
927
+ return [sep, header, sep, ...body, sep].join("\n");
928
+ }
929
+ function formatSchemaText(schema) {
930
+ const lines = [`Database Schema (${schema.kind}) - ${schema.target}`];
931
+ if (schema.kind === "redis" && schema.redis) {
932
+ lines.push(`Redis ${schema.redis.version || ""} | Keys: ${schema.redis.dbSize} | Memory: ${schema.redis.usedMemory || "n/a"}`);
933
+ for (const k of schema.redis.sampleKeys) {
934
+ lines.push(` ${k.key} [${k.type}] (ttl: ${k.ttl})`);
935
+ }
936
+ return lines.join("\n");
937
+ }
938
+ if (schema.tables.length === 0) {
939
+ lines.push(" (no tables or views found)");
940
+ return lines.join("\n");
941
+ }
942
+ for (const t of schema.tables) {
943
+ const countStr = t.rowCount !== undefined ? ` (${t.rowCount} rows)` : "";
944
+ lines.push(`\n[${t.type.toUpperCase()}] ${t.name}${countStr}`);
945
+ for (const c of t.columns) {
946
+ const flags = [c.primaryKey ? "PK" : "", c.nullable ? "NULL" : "NOT NULL"].filter(Boolean).join(", ");
947
+ lines.push(` - ${c.name}: ${c.type}${flags ? ` [${flags}]` : ""}`);
948
+ }
949
+ for (const fk of t.foreignKeys) {
950
+ lines.push(` -> FK ${fk.column} REFERENCES ${fk.refTable}(${fk.refColumn})`);
951
+ }
952
+ }
953
+ return lines.join("\n");
954
+ }
955
+ function escapeCsvCell(val) {
956
+ if (val === null || val === undefined)
957
+ return "";
958
+ const raw = typeof val === "object" ? JSON.stringify(val) : String(val);
959
+ if (/[",\r\n]/.test(raw)) {
960
+ return `"${raw.replace(/"/g, '""')}"`;
961
+ }
962
+ return raw;
963
+ }
964
+ function escapeSqlLiteral(val) {
965
+ if (val === null || val === undefined)
966
+ return "NULL";
967
+ if (typeof val === "number")
968
+ return Number.isFinite(val) ? String(val) : "NULL";
969
+ if (typeof val === "boolean")
970
+ return val ? "TRUE" : "FALSE";
971
+ const raw = typeof val === "object" ? JSON.stringify(val) : String(val);
972
+ return `'${raw.replace(/'/g, "''")}'`;
973
+ }
974
+ function quoteExportIdent(ident, kind = "sqlite") {
975
+ return kind === "mysql" ? `\`${ident.replace(/`/g, "``")}\`` : quoteSqliteIdent(ident);
976
+ }
977
+ export function exportDbData(format, tableName, columns, rows, kind = "sqlite") {
978
+ if (format === "json") {
979
+ return JSON.stringify(rows, null, 2);
980
+ }
981
+ const cols = columns.length > 0 ? columns : (rows[0] ? Object.keys(rows[0]) : []);
982
+ if (format === "csv") {
983
+ const header = cols.map((c) => escapeCsvCell(c)).join(",");
984
+ const body = rows.map((row) => cols.map((c) => escapeCsvCell(row[c])).join(","));
985
+ return [header, ...body].join("\n");
986
+ }
987
+ if (cols.length === 0 || rows.length === 0)
988
+ return "";
989
+ const qTable = quoteExportIdent(tableName || "query_result", kind);
990
+ const qCols = cols.map((c) => quoteExportIdent(c, kind)).join(", ");
991
+ return rows
992
+ .map((row) => `INSERT INTO ${qTable} (${qCols}) VALUES (${cols.map((c) => escapeSqlLiteral(row[c])).join(", ")});`)
993
+ .join("\n");
994
+ }
995
+ export function formatSchemaMermaidEr(schema) {
996
+ if (schema.kind === "redis") {
997
+ return `erDiagram\n REDIS_STORE {\n string database "${schema.target}"\n }`;
998
+ }
999
+ const lines = ["erDiagram"];
1000
+ const fkColsByTable = new Map();
1001
+ for (const table of schema.tables) {
1002
+ const fromIdent = table.name.replace(/[^a-zA-Z0-9_]/g, "_") || "table";
1003
+ for (const fk of table.foreignKeys) {
1004
+ if (!fkColsByTable.has(table.name))
1005
+ fkColsByTable.set(table.name, new Set());
1006
+ fkColsByTable.get(table.name).add(fk.column);
1007
+ const toIdent = fk.refTable.replace(/[^a-zA-Z0-9_]/g, "_") || "table";
1008
+ lines.push(` ${fromIdent} }o--|| ${toIdent} : "${fk.column} -> ${fk.refColumn}"`);
1009
+ }
1010
+ }
1011
+ for (const table of schema.tables) {
1012
+ const tIdent = table.name.replace(/[^a-zA-Z0-9_]/g, "_") || "table";
1013
+ lines.push(` ${tIdent} {`);
1014
+ for (const col of table.columns) {
1015
+ const cType = (col.type || "TEXT").replace(/[^a-zA-Z0-9_]/g, "_");
1016
+ const cName = col.name.replace(/[^a-zA-Z0-9_]/g, "_");
1017
+ const badges = [col.primaryKey ? "PK" : "", fkColsByTable.get(table.name)?.has(col.name) ? "FK" : ""].filter(Boolean).join(",");
1018
+ lines.push(` ${cType} ${cName}${badges ? ` ${badges}` : ""}`);
1019
+ }
1020
+ lines.push(" }");
1021
+ }
1022
+ return lines.join("\n");
1023
+ }
1024
+ export async function handleDbCommand(trimmedLine, ctx) {
1025
+ const args = splitShellLikeArgs(trimmedLine);
1026
+ const sub = (args[1] || "help").toLowerCase();
1027
+ if (sub === "help" || sub === "-h" || sub === "--help") {
1028
+ console.log(`\n${pc.bold("Database Commands:")}`);
1029
+ console.log(` ${pc.cyan("/db list")} List saved connections & workspace DB files`);
1030
+ console.log(` ${pc.cyan("/db connect <uri|path> [--name n] [--env local|staging|prod] [--readonly]")}`);
1031
+ console.log(` ${pc.cyan("/db use <id|name>")} Set active database connection`);
1032
+ console.log(` ${pc.cyan("/db remove <id|name>")} Remove saved database connection`);
1033
+ console.log(` ${pc.cyan("/db schema [id|path]")} Inspect tables, columns & foreign keys`);
1034
+ console.log(` ${pc.cyan("/db erd [id|path]")} Print Mermaid ER diagram from schema`);
1035
+ console.log(` ${pc.cyan('/db query [id|path] "<sql>"')} Run SQL / Redis query (risk-gated)`);
1036
+ console.log(` ${pc.cyan('/db export [id|path] <csv|json|sql> "<sql>" [--out file]')}`);
1037
+ console.log(` ${pc.cyan("/db history [clear]")} Inspect or clear query history`);
1038
+ console.log(` ${pc.cyan("/db audit [id|path]")} Audit PII, weak hashes & TLS hygiene\n`);
1039
+ return;
1040
+ }
1041
+ if (sub === "list" || sub === "ls") {
1042
+ const store = loadStore();
1043
+ console.log(`\n${pc.bold("Saved Database Connections:")}`);
1044
+ if (store.connections.length === 0) {
1045
+ console.log(pc.dim(" (none saved yet; use /db connect <sqlite-path-or-uri>)"));
1046
+ }
1047
+ else {
1048
+ for (const c of store.connections) {
1049
+ const active = c.id === store.activeId ? pc.green(" *active*") : "";
1050
+ const ro = c.readOnly ? pc.yellow(" [read-only]") : "";
1051
+ console.log(` ${pc.cyan(c.id)} (${c.kind}/${c.environment})${ro}${active} -> ${pc.dim(formatMaskedConnectionTarget(c))}`);
1052
+ }
1053
+ }
1054
+ const discovered = discoverWorkspaceDatabases(ctx.workingDirectory);
1055
+ if (discovered.length > 0) {
1056
+ console.log(`\n${pc.bold("Workspace Discovered Targets:")}`);
1057
+ for (const item of discovered) {
1058
+ console.log(` ${pc.cyan(item.kind.padEnd(8))} ${item.path}`);
1059
+ }
1060
+ }
1061
+ console.log("");
1062
+ return;
1063
+ }
1064
+ if (sub === "connect") {
1065
+ const rest = args.slice(2);
1066
+ let target = "";
1067
+ let name;
1068
+ let environment = "local";
1069
+ let readOnly = false;
1070
+ for (let i = 0; i < rest.length; i++) {
1071
+ const tok = rest[i];
1072
+ if (tok === "--name" && rest[i + 1]) {
1073
+ name = rest[++i];
1074
+ }
1075
+ else if (tok === "--env" && rest[i + 1]) {
1076
+ const val = rest[++i].toLowerCase();
1077
+ if (val === "local" || val === "staging" || val === "prod")
1078
+ environment = val;
1079
+ }
1080
+ else if (tok === "--readonly" || tok === "--ro") {
1081
+ readOnly = true;
1082
+ }
1083
+ else if (!target) {
1084
+ target = tok;
1085
+ }
1086
+ }
1087
+ if (!target) {
1088
+ console.log(`Usage: ${pc.cyan("/db connect <uri|sqlite-path> [--name alias] [--env local|staging|prod] [--readonly]")}\n`);
1089
+ return;
1090
+ }
1091
+ try {
1092
+ const { meta, secret } = parseConnectionTarget(target, ctx.workingDirectory, { name, environment, readOnly });
1093
+ const info = await testDatabaseConnection(meta, secret);
1094
+ const store = loadStore();
1095
+ store.connections = store.connections.filter((c) => c.id !== meta.id);
1096
+ store.connections.push(meta);
1097
+ store.activeId = meta.id;
1098
+ saveStore(store);
1099
+ saveSecret(meta.id, secret);
1100
+ console.log(`${pc.green("[OK]")} Connected & saved '${pc.cyan(meta.id)}' (${info}) [env=${meta.environment}${meta.readOnly ? ", read-only" : ""}]\n`);
1101
+ }
1102
+ catch (err) {
1103
+ console.log(`${pc.red("Error:")} ${maskDsn(err?.message || String(err))}\n`);
1104
+ }
1105
+ return;
1106
+ }
1107
+ if (sub === "use") {
1108
+ const ref = args[2];
1109
+ if (!ref) {
1110
+ console.log(`Usage: ${pc.cyan("/db use <id|name>")}\n`);
1111
+ return;
1112
+ }
1113
+ const store = loadStore();
1114
+ const match = store.connections.find((c) => c.id === ref || c.name === ref);
1115
+ if (!match) {
1116
+ console.log(`${pc.red("Error:")} Saved connection '${ref}' not found.\n`);
1117
+ return;
1118
+ }
1119
+ store.activeId = match.id;
1120
+ saveStore(store);
1121
+ console.log(`${pc.green("[OK]")} Active database switched to ${pc.cyan(match.id)}\n`);
1122
+ return;
1123
+ }
1124
+ if (sub === "remove" || sub === "disconnect" || sub === "rm") {
1125
+ const ref = args[2];
1126
+ const store = loadStore();
1127
+ const targetId = ref || store.activeId;
1128
+ if (!targetId) {
1129
+ console.log(`Usage: ${pc.cyan("/db remove <id|name>")}\n`);
1130
+ return;
1131
+ }
1132
+ const before = store.connections.length;
1133
+ store.connections = store.connections.filter((c) => c.id !== targetId && c.name !== targetId);
1134
+ if (store.connections.length === before) {
1135
+ console.log(`${pc.red("Error:")} Saved connection '${targetId}' not found.\n`);
1136
+ return;
1137
+ }
1138
+ if (store.activeId === targetId) {
1139
+ store.activeId = store.connections[0]?.id;
1140
+ }
1141
+ saveStore(store);
1142
+ saveSecret(targetId, undefined);
1143
+ console.log(`${pc.green("[OK]")} Removed database connection '${targetId}'.\n`);
1144
+ return;
1145
+ }
1146
+ if (sub === "schema") {
1147
+ try {
1148
+ const { meta, secret } = resolveTargetConnection(args[2], ctx.workingDirectory);
1149
+ const schema = await inspectDatabaseSchema(meta, secret);
1150
+ console.log(`\n${formatSchemaText(schema)}\n`);
1151
+ }
1152
+ catch (err) {
1153
+ console.log(`${pc.red("Error:")} ${maskDsn(err?.message || String(err))}\n`);
1154
+ }
1155
+ return;
1156
+ }
1157
+ if (sub === "audit") {
1158
+ try {
1159
+ const { meta, secret } = resolveTargetConnection(args[2], ctx.workingDirectory);
1160
+ const findings = await auditDatabaseSecurity(meta, secret);
1161
+ console.log(`\n${pc.bold(`Database Security Audit (${meta.name}):`)}`);
1162
+ if (findings.length === 0) {
1163
+ console.log(` ${pc.green("[PASS]")} No database security issues detected.`);
1164
+ }
1165
+ else {
1166
+ for (const f of findings) {
1167
+ const badge = f.severity === "CRITICAL" ? pc.bgRed(pc.white(` ${f.severity} `))
1168
+ : f.severity === "HIGH" ? pc.red(`[${f.severity}]`)
1169
+ : f.severity === "MEDIUM" ? pc.yellow(`[${f.severity}]`)
1170
+ : pc.cyan(`[${f.severity}]`);
1171
+ console.log(` ${badge} ${pc.bold(f.target)} (${f.category}): ${f.message}`);
1172
+ console.log(` ${pc.dim("Fix:")} ${f.recommendation}`);
1173
+ }
1174
+ }
1175
+ console.log("");
1176
+ }
1177
+ catch (err) {
1178
+ console.log(`${pc.red("Error:")} ${maskDsn(err?.message || String(err))}\n`);
1179
+ }
1180
+ return;
1181
+ }
1182
+ if (sub === "query") {
1183
+ const rest = args.slice(2);
1184
+ if (rest.length === 0) {
1185
+ console.log(`Usage: ${pc.cyan('/db query [id|path] "<sql>"')}\n`);
1186
+ return;
1187
+ }
1188
+ let connRef;
1189
+ let queryParts = rest;
1190
+ const store = loadStore();
1191
+ if (rest.length >= 2) {
1192
+ const candidate = rest[0];
1193
+ const matchesSaved = store.connections.some((c) => c.id === candidate || c.name === candidate);
1194
+ const matchesFile = existsSync(resolve(ctx.workingDirectory, candidate));
1195
+ if (matchesSaved || matchesFile || candidate.includes("://")) {
1196
+ connRef = candidate;
1197
+ queryParts = rest.slice(1);
1198
+ }
1199
+ }
1200
+ const sql = queryParts.join(" ").trim();
1201
+ if (!sql) {
1202
+ console.log(`Usage: ${pc.cyan('/db query [id|path] "<sql>"')}\n`);
1203
+ return;
1204
+ }
1205
+ try {
1206
+ const { meta, secret } = resolveTargetConnection(connRef, ctx.workingDirectory);
1207
+ if (meta.readOnly && !isQueryReadOnly(sql, meta.kind)) {
1208
+ console.log(`${pc.red("[BLOCKED]")} Connection '${meta.name}' is read-only. Mutating queries are disallowed.\n`);
1209
+ return;
1210
+ }
1211
+ const risk = assessSqlRisk(sql, meta.kind);
1212
+ if (risk.destructive) {
1213
+ console.log(`\n${pc.bgRed(pc.white(" DESTRUCTIVE SQL "))} ${pc.red(risk.reason)}`);
1214
+ console.log(` Target: ${pc.cyan(meta.name)} (${meta.environment})`);
1215
+ console.log(` Query: ${pc.bold(sql)}`);
1216
+ const answer = (await ctx.ask(` ${pc.red("Execute destructive query?")} ${pc.dim("[y]es / [n]o (default n):")} `)).trim().toLowerCase();
1217
+ if (answer !== "y" && answer !== "yes") {
1218
+ console.log(pc.yellow("Cancelled destructive SQL execution.\n"));
1219
+ return;
1220
+ }
1221
+ }
1222
+ const res = await executeDatabaseQuery(meta, secret, sql, 500);
1223
+ if (res.columns.length > 0) {
1224
+ console.log(`\n${formatAsciiTable(res.columns, res.rows)}`);
1225
+ console.log(pc.dim(`${res.rowCount} row(s)${res.truncated ? " (truncated at 500)" : ""} in ${res.elapsedMs}ms\n`));
1226
+ }
1227
+ else {
1228
+ console.log(`${pc.green("[OK]")} Statement executed${res.changes !== undefined ? ` (${res.changes} row(s) affected)` : ""} in ${res.elapsedMs}ms\n`);
1229
+ }
1230
+ }
1231
+ catch (err) {
1232
+ console.log(`${pc.red("Error:")} ${maskDsn(err?.message || String(err))}\n`);
1233
+ }
1234
+ return;
1235
+ }
1236
+ if (sub === "history") {
1237
+ const action = (args[2] || "").toLowerCase();
1238
+ if (action === "clear") {
1239
+ clearDbHistory();
1240
+ console.log(`${pc.green("[OK]")} Cleared database query history.\n`);
1241
+ return;
1242
+ }
1243
+ const items = loadDbHistory();
1244
+ console.log(`\n${pc.bold("Recent Database Queries:")}`);
1245
+ if (items.length === 0) {
1246
+ console.log(pc.dim(" (no recent queries recorded)\n"));
1247
+ return;
1248
+ }
1249
+ for (const item of items.slice(0, 20)) {
1250
+ const status = item.error ? pc.red("ERR") : pc.green(`${item.rowCount} row(s)`);
1251
+ const ts = new Date(item.ranAt).toISOString().replace("T", " ").slice(0, 19);
1252
+ console.log(` ${pc.dim(ts)} ${pc.cyan(item.connectionId)} ${status} ${pc.dim(`${item.durationMs}ms`)} -> ${item.sql}`);
1253
+ }
1254
+ console.log("");
1255
+ return;
1256
+ }
1257
+ if (sub === "erd" || sub === "diagram") {
1258
+ try {
1259
+ const { meta, secret } = resolveTargetConnection(args[2], ctx.workingDirectory);
1260
+ const schema = await inspectDatabaseSchema(meta, secret);
1261
+ console.log(`\n${formatSchemaMermaidEr(schema)}\n`);
1262
+ }
1263
+ catch (err) {
1264
+ console.log(`${pc.red("Error:")} ${maskDsn(err?.message || String(err))}\n`);
1265
+ }
1266
+ return;
1267
+ }
1268
+ if (sub === "export") {
1269
+ const rest = args.slice(2);
1270
+ let outPath;
1271
+ const positional = [];
1272
+ for (let i = 0; i < rest.length; i++) {
1273
+ if (rest[i] === "--out" && rest[i + 1]) {
1274
+ outPath = rest[++i];
1275
+ }
1276
+ else {
1277
+ positional.push(rest[i]);
1278
+ }
1279
+ }
1280
+ const fmtIdx = positional.findIndex((tok) => {
1281
+ const low = tok.toLowerCase();
1282
+ return low === "csv" || low === "json" || low === "sql";
1283
+ });
1284
+ if (fmtIdx < 0 || !positional[fmtIdx + 1]) {
1285
+ console.log(`Usage: ${pc.cyan('/db export [id|path] <csv|json|sql> "<sql>" [--out file]')}\n`);
1286
+ return;
1287
+ }
1288
+ const connRef = fmtIdx > 0 ? positional[0] : undefined;
1289
+ const fmt = positional[fmtIdx].toLowerCase();
1290
+ const sql = positional.slice(fmtIdx + 1).join(" ").trim();
1291
+ try {
1292
+ const { meta, secret } = resolveTargetConnection(connRef, ctx.workingDirectory);
1293
+ if (!isQueryReadOnly(sql, meta.kind)) {
1294
+ console.log(`${pc.red("[BLOCKED]")} Export only permits read-only SELECT queries.\n`);
1295
+ return;
1296
+ }
1297
+ const res = await executeDatabaseQuery(meta, secret, sql, 5000);
1298
+ const tableMatch = sql.match(/\bFROM\s+[`"\[]?([a-zA-Z0-9_.]+)[`"\]]?/i);
1299
+ const tableName = tableMatch ? tableMatch[1].split(".").pop() || "query_result" : "query_result";
1300
+ const content = exportDbData(fmt, tableName, res.columns, res.rows, meta.kind);
1301
+ if (outPath) {
1302
+ const target = resolve(ctx.workingDirectory, outPath);
1303
+ const rel = relative(ctx.workingDirectory, target);
1304
+ if (rel.startsWith("..") || rel === "") {
1305
+ console.log(`${pc.red("Error:")} Export path must stay inside workspace.\n`);
1306
+ return;
1307
+ }
1308
+ writeFileSync(target, content, "utf8");
1309
+ console.log(`${pc.green("[OK]")} Exported ${res.rowCount} row(s) (${fmt.toUpperCase()}) -> ${target}\n`);
1310
+ }
1311
+ else {
1312
+ console.log(`\n${content}\n`);
1313
+ }
1314
+ }
1315
+ catch (err) {
1316
+ console.log(`${pc.red("Error:")} ${maskDsn(err?.message || String(err))}\n`);
1317
+ }
1318
+ return;
1319
+ }
1320
+ console.log(`${pc.yellow("[WARN]")} Unknown /db subcommand '${sub}'. Run ${pc.cyan("/db help")} for usage.\n`);
1321
+ }
1322
+ export const dbListTool = {
1323
+ definition: {
1324
+ name: "db_list",
1325
+ description: "List saved database connections (credentials masked) and discover SQLite/ORM/Compose database targets in the workspace.",
1326
+ parameters: { type: "object", properties: {}, required: [] },
1327
+ },
1328
+ async execute(_params, context) {
1329
+ const store = loadStore();
1330
+ const saved = store.connections.map((c) => ({
1331
+ id: c.id,
1332
+ name: c.name,
1333
+ kind: c.kind,
1334
+ environment: c.environment,
1335
+ readOnly: c.readOnly,
1336
+ active: c.id === store.activeId,
1337
+ target: formatMaskedConnectionTarget(c),
1338
+ }));
1339
+ const discovered = discoverWorkspaceDatabases(context.workingDirectory);
1340
+ return {
1341
+ success: true,
1342
+ output: JSON.stringify({ saved, discovered }, null, 2),
1343
+ };
1344
+ },
1345
+ };
1346
+ export const dbInspectSchemaTool = {
1347
+ definition: {
1348
+ name: "db_inspect_schema",
1349
+ description: "Inspect database tables, columns, primary keys, and foreign keys for a saved connection ID or workspace SQLite path.",
1350
+ parameters: {
1351
+ type: "object",
1352
+ properties: {
1353
+ connection: { type: "string", description: "Saved connection id/name or relative SQLite file path (optional if active connection exists)." },
1354
+ },
1355
+ required: [],
1356
+ },
1357
+ },
1358
+ async execute(params, context) {
1359
+ try {
1360
+ const { meta, secret } = resolveTargetConnection(params.connection, context.workingDirectory);
1361
+ const schema = await inspectDatabaseSchema(meta, secret);
1362
+ return { success: true, output: formatSchemaText(schema) };
1363
+ }
1364
+ catch (err) {
1365
+ return { success: false, output: "", error: maskDsn(err?.message || String(err)) };
1366
+ }
1367
+ },
1368
+ };
1369
+ export const dbAuditTool = {
1370
+ definition: {
1371
+ name: "db_audit",
1372
+ description: "Audit a database connection or SQLite file for PII columns, weak password hashes, TLS misconfigurations, and read-only safety.",
1373
+ parameters: {
1374
+ type: "object",
1375
+ properties: {
1376
+ connection: { type: "string", description: "Saved connection id/name or relative SQLite file path (optional if active connection exists)." },
1377
+ },
1378
+ required: [],
1379
+ },
1380
+ },
1381
+ async execute(params, context) {
1382
+ try {
1383
+ const { meta, secret } = resolveTargetConnection(params.connection, context.workingDirectory);
1384
+ const findings = await auditDatabaseSecurity(meta, secret);
1385
+ return { success: true, output: JSON.stringify({ connection: meta.id, findings }, null, 2) };
1386
+ }
1387
+ catch (err) {
1388
+ return { success: false, output: "", error: maskDsn(err?.message || String(err)) };
1389
+ }
1390
+ },
1391
+ };
1392
+ export const dbQueryTool = {
1393
+ definition: {
1394
+ name: "db_query",
1395
+ description: "Execute a SQL query (or Redis command) against a saved connection or SQLite file. Read-only connections block writes; destructive SQL requires explicit interactive confirmation; sensitive columns are redacted in AI results.",
1396
+ parameters: {
1397
+ type: "object",
1398
+ properties: {
1399
+ connection: { type: "string", description: "Saved connection id/name or SQLite file path (optional if an active connection is configured)." },
1400
+ query: { type: "string", description: "SQL statement or Redis command to run." },
1401
+ maxRows: { type: "number", description: "Maximum number of rows to return (default 200)." },
1402
+ },
1403
+ required: ["query"],
1404
+ },
1405
+ },
1406
+ async execute(params, context) {
1407
+ const query = String(params.query || "").trim();
1408
+ if (!query)
1409
+ return { success: false, output: "", error: "db_query requires a non-empty query." };
1410
+ let meta;
1411
+ let secret;
1412
+ try {
1413
+ const resolved = resolveTargetConnection(params.connection, context.workingDirectory);
1414
+ meta = resolved.meta;
1415
+ secret = resolved.secret;
1416
+ }
1417
+ catch (err) {
1418
+ return { success: false, output: "", error: maskDsn(err?.message || String(err)) };
1419
+ }
1420
+ const readOnlyQuery = isQueryReadOnly(query, meta.kind);
1421
+ if (meta.readOnly && !readOnlyQuery) {
1422
+ return {
1423
+ success: false,
1424
+ output: "",
1425
+ error: `Connection '${meta.name}' is read-only. Mutating queries are blocked.`,
1426
+ };
1427
+ }
1428
+ const risk = assessSqlRisk(query, meta.kind);
1429
+ const sessionAllowed = !risk.destructive && context.sessionApprovedTools?.has("db_query");
1430
+ const needsApproval = risk.destructive
1431
+ ? true
1432
+ : readOnlyQuery
1433
+ ? context.autoApproveRead === false
1434
+ : (!context.autoApproveWrite && !sessionAllowed);
1435
+ if (needsApproval) {
1436
+ if (!context.requestApproval) {
1437
+ return {
1438
+ success: false,
1439
+ output: "",
1440
+ error: risk.destructive
1441
+ ? `Blocked destructive SQL (${risk.reason}). Interactive confirmation required.`
1442
+ : "Database mutation rejected: approval required (run interactively or enable auto-approve write).",
1443
+ };
1444
+ }
1445
+ const decision = await context.requestApproval({
1446
+ tool: "db_query",
1447
+ title: risk.destructive
1448
+ ? `Destructive SQL blocked for confirmation (${risk.reason})`
1449
+ : `Allow SQL mutation on ${meta.name} (${meta.environment})?`,
1450
+ detail: `${meta.name}: ${query}`,
1451
+ destructive: risk.destructive,
1452
+ sessionKey: risk.destructive ? undefined : "db_query",
1453
+ });
1454
+ if (decision === "deny" || (risk.destructive && decision !== "once")) {
1455
+ return { success: false, output: "", error: "SQL query declined by user." };
1456
+ }
1457
+ if (decision === "always" && !risk.destructive && !readOnlyQuery) {
1458
+ context.sessionApprovedTools?.add("db_query");
1459
+ }
1460
+ }
1461
+ try {
1462
+ const limit = Math.min(500, Math.max(1, Number(params.maxRows || 200)));
1463
+ const res = await executeDatabaseQuery(meta, secret, query, limit);
1464
+ const redactedRows = redactRowsForAi(res.columns, res.rows);
1465
+ return {
1466
+ success: true,
1467
+ output: JSON.stringify({
1468
+ connection: meta.id,
1469
+ columns: res.columns,
1470
+ rows: redactedRows,
1471
+ rowCount: res.rowCount,
1472
+ changes: res.changes,
1473
+ elapsedMs: res.elapsedMs,
1474
+ }, null, 2),
1475
+ truncated: res.truncated,
1476
+ };
1477
+ }
1478
+ catch (err) {
1479
+ return { success: false, output: "", error: maskDsn(err?.message || String(err)) };
1480
+ }
1481
+ },
1482
+ };
1483
+ export const dbExportTool = {
1484
+ definition: {
1485
+ name: "db_export",
1486
+ description: "Export rows from a read-only SQL query to CSV, JSON, or SQL INSERT format with secret column redaction.",
1487
+ parameters: {
1488
+ type: "object",
1489
+ properties: {
1490
+ connection: { type: "string", description: "Saved connection id/name or SQLite file path (optional if an active connection is configured)." },
1491
+ query: { type: "string", description: "Read-only SELECT SQL query." },
1492
+ format: { type: "string", description: "Output format: csv, json, or sql.", enum: ["csv", "json", "sql"] },
1493
+ tableName: { type: "string", description: "Target table name for SQL INSERT statements (default query_result)." },
1494
+ maxRows: { type: "number", description: "Maximum number of rows to export (default 1000, max 5000)." },
1495
+ },
1496
+ required: ["query", "format"],
1497
+ },
1498
+ },
1499
+ async execute(params, context) {
1500
+ const query = String(params.query || "").trim();
1501
+ const fmt = String(params.format || "csv").toLowerCase();
1502
+ if (!query || (fmt !== "csv" && fmt !== "json" && fmt !== "sql")) {
1503
+ return { success: false, output: "", error: "db_export requires query and format (csv|json|sql)." };
1504
+ }
1505
+ try {
1506
+ const { meta, secret } = resolveTargetConnection(params.connection, context.workingDirectory);
1507
+ if (!isQueryReadOnly(query, meta.kind)) {
1508
+ return { success: false, output: "", error: "db_export only permits read-only SELECT queries." };
1509
+ }
1510
+ const limit = Math.min(5000, Math.max(1, Number(params.maxRows || 1000)));
1511
+ const res = await executeDatabaseQuery(meta, secret, query, limit);
1512
+ const redactedRows = redactRowsForAi(res.columns, res.rows);
1513
+ const tableName = String(params.tableName || "query_result").trim() || "query_result";
1514
+ const content = exportDbData(fmt, tableName, res.columns, redactedRows, meta.kind);
1515
+ return {
1516
+ success: true,
1517
+ output: content,
1518
+ truncated: res.truncated,
1519
+ };
1520
+ }
1521
+ catch (err) {
1522
+ return { success: false, output: "", error: maskDsn(err?.message || String(err)) };
1523
+ }
1524
+ },
1525
+ };
1526
+ //# sourceMappingURL=db.js.map