@carllee1983/dbcli 1.46.0 → 1.47.1

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dbcli-agent",
3
- "version": "1.46.0",
3
+ "version": "1.47.1",
4
4
  "description": "Database CLI skill and command reference for AI agents.",
5
5
  "author": {
6
6
  "name": "Carl Lee",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dbcli-agent",
3
- "version": "1.46.0",
3
+ "version": "1.47.1",
4
4
  "description": "Database CLI skill and command reference for AI agents",
5
5
  "author": {
6
6
  "name": "Carl Lee",
@@ -77,7 +77,10 @@ When reporting a check's outcome use the vocabulary `verified` (evidence matched
77
77
  `not_verified` (check ran and contradicted) / `indeterminate` (ran but ambiguous) /
78
78
  `blocked` (could not run due to config, permission, schema, placeholder, or safety gate).
79
79
 
80
- Prefer `--format json` for agent-friendly output.
80
+ Prefer `--format json` for agent-friendly output. Diagnostics (auto-limit notices,
81
+ warnings) go to stderr so stdout stays parseable — when piping JSON into a parser,
82
+ use `2>/dev/null` or leave stderr alone. **Never `2>&1`**: it merges those lines back
83
+ into stdout and the parse fails.
81
84
 
82
85
  ## Agent Task Packs
83
86
 
@@ -214,7 +217,10 @@ or `doctor` / `status` reports a missing or invalid config, follow this flow.
214
217
  `--password` / `--name` (and `--system`).
215
218
  3. **What permission tier?** Default to the **lowest** that satisfies the task:
216
219
  `query-only` → `read-write` → `data-admin` → `admin`. Set with `--permission`
217
- (defaults to `query-only`).
220
+ (defaults to `query-only`). Tiers judge what a statement does, not how it
221
+ opens: below `admin`, multi-statement SQL is rejected; snippets must be free
222
+ of write and DDL keywords; MongoDB `$out` / `$merge` need `data-admin` and are
223
+ refused entirely in snippets and `export`.
218
224
  4. **Verify, never assume.** After init: `dbcli status` (system + permission +
219
225
  blacklist summary, no creds) and `dbcli doctor --format json` (env, config
220
226
  shape, connectivity, schema-cache age, Mongo SRV path).
@@ -553,4 +559,4 @@ schema. Raw `query` / `export` invocations render a sortable table only.
553
559
  - Blacklisted tables and columns are redacted from query output.
554
560
  - `schema` reports `estimatedRowCount` and `sizeCategory` (small / medium / large / huge). For large/huge tables add `WHERE` or `LIMIT` — bands in reference.md.
555
561
  - `doctor` on `mongodb+srv://` reports whether SRV resolves natively or through the DoH fallback — useful when the runtime restricts DNS.
556
- - **Global flags:** `--version`, `--config <path>`, `--global`, `--use <name>`, `-v` / `--verbose` / `-vv`, `-q` / `--quiet`, `--no-color` (also honours `NO_COLOR`). Root-level flags must precede the command unless the command explicitly declares a command-level option.
562
+ - **Global flags:** `--version`, `--config <path>`, `--global`, `--use <name>`, `--timeout <ms>`, `-v` / `--verbose` / `-vv`, `-q` / `--quiet`, `--no-color` (also honours `NO_COLOR`). Root-level flags must precede the command unless the command explicitly declares a command-level option.
@@ -19,6 +19,28 @@ command-level option is only valid after the command that declares it.
19
19
  | `--config <path>` | Select the `.dbcli` configuration path. |
20
20
  | `--global` | Select the user-global registry at `~/.config/dbcli/config.json` instead of the current project's `.dbcli` config. Place it before the command path. |
21
21
  | `--use <connection>` | Select a named connection for this invocation; place it before the command path unless that command explicitly lists a command-level `--use`. |
22
+ | `--timeout <ms>` | Connection timeout in milliseconds (integer, 100–600000), overriding the connection config's `timeout` field for this invocation. Applies to every engine adapter. Without either the flag or the config field, adapters fall back to their built-in 5000ms default. |
23
+
24
+ `--timeout` is applied only when the adapter is constructed for this invocation — it is
25
+ never written back to `config.json`. Set the connection's `timeout` field instead for a
26
+ value that persists across runs. On PostgreSQL, the same value is also used as the
27
+ session's `statement_timeout` (not just the connection timeout), so a low value can cut
28
+ off a long-running query with an error that looks like a connection timeout; the 100ms
29
+ floor exists specifically to keep that failure mode from being too easy to trigger.
30
+ Elasticsearch applies its timeout per request rather than once for the whole connection.
31
+ The `timeout` field itself always takes a literal number — unlike other connection
32
+ fields, it does not accept an `{"$env": "..."}` reference.
33
+
34
+ ### Redirecting output
35
+
36
+ Results go to stdout; diagnostics (auto-limit notices, warnings, update hints) go to
37
+ stderr. That split is what keeps `--format json` machine-parseable, so do not collapse
38
+ it with `2>&1` — the diagnostic lines land in front of the JSON document and the parse
39
+ fails. Pipe stdout alone, or add `2>/dev/null` when the diagnostics are not wanted:
40
+
41
+ ```bash
42
+ dbcli query '{}' --collection events --format json 2>/dev/null | jq '.rows | length'
43
+ ```
22
44
 
23
45
  ## Commands
24
46
 
@@ -118,6 +140,10 @@ agent mode disabled. A host that needs protection from a same-user hostile
118
140
  process can set `DBCLI_CONFIG_INTEGRITY_ANCHOR_DIR` to a protected or read-only
119
141
  directory; trusted writes publish detached digests there.
120
142
 
143
+ When a connection's config fails schema validation, dbcli reports the specific field
144
+ path(s) that are wrong for that connection's declared `system` — not the raw Zod union
145
+ error tree — so a broken `.dbcli` can be fixed without guessing which branch applies.
146
+
121
147
  ### list
122
148
 
123
149
  List all tables (SQL), collections (MongoDB), keys (Redis), or indices (Elasticsearch).
@@ -197,6 +223,13 @@ dbcli query "SELECT * FROM orders" --format html > orders.html # pipe to stdou
197
223
  **Options:** `--format <table|json|csv|html>`, `--ui` (open the dashboard in the system browser; implies `--format html`), `--limit <number>`, `--no-limit`, `--collection <name>` (MongoDB / Elasticsearch), `--index <name>` (Elasticsearch alias for `--collection`), `--fields <list>`, `--truncate <number>` / `--no-truncate`, `-f, --query-file <path>`, `--use <name[,name]>`, `--recovery`
198
224
  **Permission:** query-only+ (Redis: per-command; Elasticsearch: per HTTP method/path)
199
225
 
226
+ Below `admin`, SQL holding more than one statement is rejected, because only the
227
+ first statement would decide the permission check while a driver on the simple
228
+ query protocol executes them all. Semicolons inside string literals, backtick
229
+ identifiers, and `#` comments are not separators. A MongoDB pipeline containing
230
+ `$out` or `$merge` requires `data-admin`, and is rejected outright on `export`,
231
+ in snippets, and in multi-connection fan-out.
232
+
200
233
  #### Field projection (`--fields`)
201
234
 
202
235
  ```bash
@@ -253,7 +286,7 @@ instead of silently running its only connection.
253
286
  An explicit comma-separated `--use primary,staging` fans one query out to several named
254
287
  connections. `DBCLI_CONNECTION` always names one literal connection and never enables
255
288
  fan-out. SQL permits `SELECT`, `SHOW`, `DESCRIBE`, and `EXPLAIN`; MongoDB permits filters and
256
- read-only pipelines without top-level `$out` / `$merge`; Elasticsearch permits searches.
289
+ read-only pipelines without `$out` / `$merge`; Elasticsearch permits searches.
257
290
  Redis, writes, `--recovery`, `--ui`, CSV, and HTML are rejected before execution. Each
258
291
  connection keeps its own blacklist, limit metadata, audit entry, and error. Aggregate exit
259
292
  codes are `0` when all succeed, `2` for mixed outcomes, and `1` when all fail or preflight
@@ -505,6 +538,13 @@ dbcli q @analytics/revenue --param days=30 --format html > report.html
505
538
 
506
539
  Each `.sql` file is plain SQL with optional YAML frontmatter inside a leading `-- ---` block. Lines outside frontmatter form the SQL body.
507
540
 
541
+ Snippets are read-only by contract, at every permission level including `admin`.
542
+ A body must be a single statement opening with `SELECT` or `WITH` **and** free of
543
+ write or DDL keywords, so a data-modifying CTE (`WITH x AS (DELETE … RETURNING *)
544
+ SELECT * FROM x`) and `SELECT … INTO` are rejected at parse time rather than at
545
+ execution. A MongoDB body may not contain `$out` or `$merge`. The same rule
546
+ applies to `verify.query` in frontmatter, which `q --verify` executes verbatim.
547
+
508
548
  ```sql
509
549
  -- ---
510
550
  -- name: DAU
@@ -2605,6 +2645,8 @@ MongoDB connections use a JSON-based query model instead of SQL. Treat MongoDB s
2605
2645
 
2606
2646
  `init --system mongodb` defaults to a field-by-field wizard (`host`, `srv`, `port`, `user`, `password` + `authSource`, then optional `replicaSet` / `tls`); a full `uri` is an explicit advanced choice in the interactive flow and the unchanged non-interactive path via `--uri`. Optional fields `authSource`, `replicaSet`, `tls`, and `srv` express what previously required embedding options in the `uri` query string. Atlas-style `mongodb+srv://` URIs are supported both as a full `uri` and via the per-field `srv: true` option. `list` and `query` run against the database configured for the connection, and `query` always requires `--collection <name>`.
2607
2647
 
2648
+ The 5000ms default server-selection timeout is often too tight for a connection over a VPN or to Atlas. Set a `timeout` field (ms) in the connection config, or override it per invocation with root-level `--timeout`, e.g. `dbcli --timeout 20000 --use <conn> list`.
2649
+
2608
2650
  **Supported commands:** `init`, `use`, `list`, `schema`, `query`, `q`, `insert`, `update`, `delete`, `export`, `status`, `shell`, `doctor`, `upgrade`, `completion`
2609
2651
 
2610
2652
  **Limited support:**
@@ -2669,7 +2711,7 @@ Redis connections speak Redis commands rather than SQL. The adapter uses Bun's n
2669
2711
 
2670
2712
  - Required fields: `system: redis`, `host`, `port`. `password` and `database` are optional.
2671
2713
  - `database` is the **logical DB index** (`"0"` … `"15"`), kept as a string to play nicely with env-ref bindings. `list` and the connection metadata both label it as the active DB.
2672
- - `connection.timeout` (ms, default 5000) maps to the client's `connectionTimeout`.
2714
+ - `connection.timeout` (ms, default 5000) maps to the client's `connectionTimeout`; root-level `--timeout <ms>` overrides it for a single invocation.
2673
2715
 
2674
2716
  ### Permission classification
2675
2717
 
@@ -2799,7 +2841,7 @@ Elasticsearch connections speak the REST API. The adapter is fetch-based (no SDK
2799
2841
  - Either `host` + `port` (default `https://localhost:9200`) or `nodes: [...]` (first node is used) or `cloudId`.
2800
2842
  - Auth precedence: `apiKey` → `user`/`password` (HTTP Basic). Leave both unset for an open cluster.
2801
2843
  - `protocol` defaults to `https`. For TLS quirks: `caPath` (path to a PEM bundle) and `rejectUnauthorized: false` (last resort).
2802
- - `connection.timeout` (ms, default 5000) is wired to `AbortController` on every request.
2844
+ - `connection.timeout` (ms, default 5000) is wired to `AbortController` on every request; root-level `--timeout <ms>` overrides it for a single invocation.
2803
2845
 
2804
2846
  ### Permission classification
2805
2847
 
@@ -2,7 +2,7 @@
2
2
  "name": "dbcli-agent",
3
3
  "displayName": "dbcli Agent",
4
4
  "description": "Database CLI skill and command reference for AI agents.",
5
- "version": "1.46.0",
5
+ "version": "1.47.1",
6
6
  "author": {
7
7
  "name": "Carl Lee",
8
8
  "url": "https://github.com/CarlLee1983"
@@ -77,7 +77,10 @@ When reporting a check's outcome use the vocabulary `verified` (evidence matched
77
77
  `not_verified` (check ran and contradicted) / `indeterminate` (ran but ambiguous) /
78
78
  `blocked` (could not run due to config, permission, schema, placeholder, or safety gate).
79
79
 
80
- Prefer `--format json` for agent-friendly output.
80
+ Prefer `--format json` for agent-friendly output. Diagnostics (auto-limit notices,
81
+ warnings) go to stderr so stdout stays parseable — when piping JSON into a parser,
82
+ use `2>/dev/null` or leave stderr alone. **Never `2>&1`**: it merges those lines back
83
+ into stdout and the parse fails.
81
84
 
82
85
  ## Agent Task Packs
83
86
 
@@ -214,7 +217,10 @@ or `doctor` / `status` reports a missing or invalid config, follow this flow.
214
217
  `--password` / `--name` (and `--system`).
215
218
  3. **What permission tier?** Default to the **lowest** that satisfies the task:
216
219
  `query-only` → `read-write` → `data-admin` → `admin`. Set with `--permission`
217
- (defaults to `query-only`).
220
+ (defaults to `query-only`). Tiers judge what a statement does, not how it
221
+ opens: below `admin`, multi-statement SQL is rejected; snippets must be free
222
+ of write and DDL keywords; MongoDB `$out` / `$merge` need `data-admin` and are
223
+ refused entirely in snippets and `export`.
218
224
  4. **Verify, never assume.** After init: `dbcli status` (system + permission +
219
225
  blacklist summary, no creds) and `dbcli doctor --format json` (env, config
220
226
  shape, connectivity, schema-cache age, Mongo SRV path).
@@ -553,4 +559,4 @@ schema. Raw `query` / `export` invocations render a sortable table only.
553
559
  - Blacklisted tables and columns are redacted from query output.
554
560
  - `schema` reports `estimatedRowCount` and `sizeCategory` (small / medium / large / huge). For large/huge tables add `WHERE` or `LIMIT` — bands in reference.md.
555
561
  - `doctor` on `mongodb+srv://` reports whether SRV resolves natively or through the DoH fallback — useful when the runtime restricts DNS.
556
- - **Global flags:** `--version`, `--config <path>`, `--global`, `--use <name>`, `-v` / `--verbose` / `-vv`, `-q` / `--quiet`, `--no-color` (also honours `NO_COLOR`). Root-level flags must precede the command unless the command explicitly declares a command-level option.
562
+ - **Global flags:** `--version`, `--config <path>`, `--global`, `--use <name>`, `--timeout <ms>`, `-v` / `--verbose` / `-vv`, `-q` / `--quiet`, `--no-color` (also honours `NO_COLOR`). Root-level flags must precede the command unless the command explicitly declares a command-level option.
@@ -19,6 +19,28 @@ command-level option is only valid after the command that declares it.
19
19
  | `--config <path>` | Select the `.dbcli` configuration path. |
20
20
  | `--global` | Select the user-global registry at `~/.config/dbcli/config.json` instead of the current project's `.dbcli` config. Place it before the command path. |
21
21
  | `--use <connection>` | Select a named connection for this invocation; place it before the command path unless that command explicitly lists a command-level `--use`. |
22
+ | `--timeout <ms>` | Connection timeout in milliseconds (integer, 100–600000), overriding the connection config's `timeout` field for this invocation. Applies to every engine adapter. Without either the flag or the config field, adapters fall back to their built-in 5000ms default. |
23
+
24
+ `--timeout` is applied only when the adapter is constructed for this invocation — it is
25
+ never written back to `config.json`. Set the connection's `timeout` field instead for a
26
+ value that persists across runs. On PostgreSQL, the same value is also used as the
27
+ session's `statement_timeout` (not just the connection timeout), so a low value can cut
28
+ off a long-running query with an error that looks like a connection timeout; the 100ms
29
+ floor exists specifically to keep that failure mode from being too easy to trigger.
30
+ Elasticsearch applies its timeout per request rather than once for the whole connection.
31
+ The `timeout` field itself always takes a literal number — unlike other connection
32
+ fields, it does not accept an `{"$env": "..."}` reference.
33
+
34
+ ### Redirecting output
35
+
36
+ Results go to stdout; diagnostics (auto-limit notices, warnings, update hints) go to
37
+ stderr. That split is what keeps `--format json` machine-parseable, so do not collapse
38
+ it with `2>&1` — the diagnostic lines land in front of the JSON document and the parse
39
+ fails. Pipe stdout alone, or add `2>/dev/null` when the diagnostics are not wanted:
40
+
41
+ ```bash
42
+ dbcli query '{}' --collection events --format json 2>/dev/null | jq '.rows | length'
43
+ ```
22
44
 
23
45
  ## Commands
24
46
 
@@ -118,6 +140,10 @@ agent mode disabled. A host that needs protection from a same-user hostile
118
140
  process can set `DBCLI_CONFIG_INTEGRITY_ANCHOR_DIR` to a protected or read-only
119
141
  directory; trusted writes publish detached digests there.
120
142
 
143
+ When a connection's config fails schema validation, dbcli reports the specific field
144
+ path(s) that are wrong for that connection's declared `system` — not the raw Zod union
145
+ error tree — so a broken `.dbcli` can be fixed without guessing which branch applies.
146
+
121
147
  ### list
122
148
 
123
149
  List all tables (SQL), collections (MongoDB), keys (Redis), or indices (Elasticsearch).
@@ -197,6 +223,13 @@ dbcli query "SELECT * FROM orders" --format html > orders.html # pipe to stdou
197
223
  **Options:** `--format <table|json|csv|html>`, `--ui` (open the dashboard in the system browser; implies `--format html`), `--limit <number>`, `--no-limit`, `--collection <name>` (MongoDB / Elasticsearch), `--index <name>` (Elasticsearch alias for `--collection`), `--fields <list>`, `--truncate <number>` / `--no-truncate`, `-f, --query-file <path>`, `--use <name[,name]>`, `--recovery`
198
224
  **Permission:** query-only+ (Redis: per-command; Elasticsearch: per HTTP method/path)
199
225
 
226
+ Below `admin`, SQL holding more than one statement is rejected, because only the
227
+ first statement would decide the permission check while a driver on the simple
228
+ query protocol executes them all. Semicolons inside string literals, backtick
229
+ identifiers, and `#` comments are not separators. A MongoDB pipeline containing
230
+ `$out` or `$merge` requires `data-admin`, and is rejected outright on `export`,
231
+ in snippets, and in multi-connection fan-out.
232
+
200
233
  #### Field projection (`--fields`)
201
234
 
202
235
  ```bash
@@ -253,7 +286,7 @@ instead of silently running its only connection.
253
286
  An explicit comma-separated `--use primary,staging` fans one query out to several named
254
287
  connections. `DBCLI_CONNECTION` always names one literal connection and never enables
255
288
  fan-out. SQL permits `SELECT`, `SHOW`, `DESCRIBE`, and `EXPLAIN`; MongoDB permits filters and
256
- read-only pipelines without top-level `$out` / `$merge`; Elasticsearch permits searches.
289
+ read-only pipelines without `$out` / `$merge`; Elasticsearch permits searches.
257
290
  Redis, writes, `--recovery`, `--ui`, CSV, and HTML are rejected before execution. Each
258
291
  connection keeps its own blacklist, limit metadata, audit entry, and error. Aggregate exit
259
292
  codes are `0` when all succeed, `2` for mixed outcomes, and `1` when all fail or preflight
@@ -505,6 +538,13 @@ dbcli q @analytics/revenue --param days=30 --format html > report.html
505
538
 
506
539
  Each `.sql` file is plain SQL with optional YAML frontmatter inside a leading `-- ---` block. Lines outside frontmatter form the SQL body.
507
540
 
541
+ Snippets are read-only by contract, at every permission level including `admin`.
542
+ A body must be a single statement opening with `SELECT` or `WITH` **and** free of
543
+ write or DDL keywords, so a data-modifying CTE (`WITH x AS (DELETE … RETURNING *)
544
+ SELECT * FROM x`) and `SELECT … INTO` are rejected at parse time rather than at
545
+ execution. A MongoDB body may not contain `$out` or `$merge`. The same rule
546
+ applies to `verify.query` in frontmatter, which `q --verify` executes verbatim.
547
+
508
548
  ```sql
509
549
  -- ---
510
550
  -- name: DAU
@@ -2605,6 +2645,8 @@ MongoDB connections use a JSON-based query model instead of SQL. Treat MongoDB s
2605
2645
 
2606
2646
  `init --system mongodb` defaults to a field-by-field wizard (`host`, `srv`, `port`, `user`, `password` + `authSource`, then optional `replicaSet` / `tls`); a full `uri` is an explicit advanced choice in the interactive flow and the unchanged non-interactive path via `--uri`. Optional fields `authSource`, `replicaSet`, `tls`, and `srv` express what previously required embedding options in the `uri` query string. Atlas-style `mongodb+srv://` URIs are supported both as a full `uri` and via the per-field `srv: true` option. `list` and `query` run against the database configured for the connection, and `query` always requires `--collection <name>`.
2607
2647
 
2648
+ The 5000ms default server-selection timeout is often too tight for a connection over a VPN or to Atlas. Set a `timeout` field (ms) in the connection config, or override it per invocation with root-level `--timeout`, e.g. `dbcli --timeout 20000 --use <conn> list`.
2649
+
2608
2650
  **Supported commands:** `init`, `use`, `list`, `schema`, `query`, `q`, `insert`, `update`, `delete`, `export`, `status`, `shell`, `doctor`, `upgrade`, `completion`
2609
2651
 
2610
2652
  **Limited support:**
@@ -2669,7 +2711,7 @@ Redis connections speak Redis commands rather than SQL. The adapter uses Bun's n
2669
2711
 
2670
2712
  - Required fields: `system: redis`, `host`, `port`. `password` and `database` are optional.
2671
2713
  - `database` is the **logical DB index** (`"0"` … `"15"`), kept as a string to play nicely with env-ref bindings. `list` and the connection metadata both label it as the active DB.
2672
- - `connection.timeout` (ms, default 5000) maps to the client's `connectionTimeout`.
2714
+ - `connection.timeout` (ms, default 5000) maps to the client's `connectionTimeout`; root-level `--timeout <ms>` overrides it for a single invocation.
2673
2715
 
2674
2716
  ### Permission classification
2675
2717
 
@@ -2799,7 +2841,7 @@ Elasticsearch connections speak the REST API. The adapter is fetch-based (no SDK
2799
2841
  - Either `host` + `port` (default `https://localhost:9200`) or `nodes: [...]` (first node is used) or `cloudId`.
2800
2842
  - Auth precedence: `apiKey` → `user`/`password` (HTTP Basic). Leave both unset for an open cluster.
2801
2843
  - `protocol` defaults to `https`. For TLS quirks: `caPath` (path to a PEM bundle) and `rejectUnauthorized: false` (last resort).
2802
- - `connection.timeout` (ms, default 5000) is wired to `AbortController` on every request.
2844
+ - `connection.timeout` (ms, default 5000) is wired to `AbortController` on every request; root-level `--timeout <ms>` overrides it for a single invocation.
2803
2845
 
2804
2846
  ### Permission classification
2805
2847
 
package/CHANGELOG.md CHANGED
@@ -5,6 +5,50 @@ All notable changes to dbcli are documented here.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.47.1] - 2026-08-05 - 唯讀保證涵蓋所有執行路徑(安全性修復)
9
+
10
+ 決策記錄:`docs/adr/0004-database-access-stays-a-cli-surface.md`。
11
+
12
+ ### Security
13
+
14
+ 修復五個「看起來是讀、實際會寫」的繞過,它們都能在設定為 `permission: query-only` 的連線上寫入資料。**建議所有把資料庫交給 AI agent 操作的使用者升級。**
15
+
16
+ - **MongoDB `$out` / `$merge` 未被擋下(`query`、`q`、`export`)。** 這兩個 aggregation stage 只在多連線 fan-out 路徑被檢查,單連線 `dbcli query`、saved snippet、以及 `dbcli export` 全都會執行它們,不論 permission 等級。`$out` 可覆寫任意 collection。`--dry-run` 會把這種 pipeline 預覽成安全操作。影響 MongoDB 連線。
17
+ - **PostgreSQL 多語句堆疊。** 權限分類只讀第一個關鍵字,而 PostgreSQL 的 simple query protocol 會執行字串裡每一個以分號分隔的語句,因此 `SELECT 1 LIMIT 1; DELETE FROM users` 會以 SELECT 的身分通過 `query-only`。影響 PostgreSQL;MySQL / MariaDB 走 prepared statement,不受影響。
18
+ - **snippet 的偽唯讀語句。** snippet 只要求開頭是 `SELECT` 或 `WITH`,因此 `WITH x AS (DELETE FROM users RETURNING *) SELECT * FROM x` 與 `SELECT … INTO` 都能通過。一個 commit 進 repo、看起來是唯讀報表的 `.sql` 檔可以寫入資料庫。影響 PostgreSQL / MariaDB。
19
+ - **snippet frontmatter 的 `verify.query` 未經驗證。** 過去只檢查它是非空字串,然後由 `dbcli q <name> --verify` 原封執行。
20
+ - **唯讀證明只接在多連線 fan-out 上,單連線 `query` / `export` / REPL 沒有。** 權限判定只看第一個關鍵字,因此 `query-only` 連線接受並執行下列語句:`WITH gone AS (DELETE FROM users RETURNING *) SELECT * FROM gone`(data-modifying CTE)、`SELECT * INTO evil_copy FROM users`(建表)、`EXPLAIN ANALYZE DELETE FROM users`(`EXPLAIN ANALYZE` 會真的執行該語句)。同一句 SQL 加上 `--use a,b` 會被擋,不加就執行。auto-limit 補的 `LIMIT 1000` 對 CTE 無效,整張表仍會被刪。**這條在 1.47.0 以前就存在**,且不需要任何特殊語法。影響 PostgreSQL 與 MariaDB。
21
+ - **PostgreSQL 識別字中的 `$` 被誤判為 dollar-quote 起點。** PostgreSQL 的識別字從第二個字元起允許 `$`,因此 `a$q$` 是**一個識別字**;但語句剖析器把它讀成字串起點,於是 `SELECT 1 AS a$q$ LIMIT 1; DELETE FROM users; SELECT 1 AS b$q$` 中間整段對所有安全檢查隱形,資料庫卻照常執行三段。**這條在 1.47.0 以前就存在**:多連線 fan-out 的唯讀斷言(`dbcli query --use a,b`)用的正是同一個剖析器,因此可被此手法繞過。影響 PostgreSQL。
22
+
23
+ 利用這些繞過需要能下達指令的一方送出 payload,也就是 agent 本身 —— 而 dbcli 的威脅模型前提正是 agent 不完全可信,因此這些屬於權限繞過,不以「使用者自己下的指令」論。
24
+
25
+ ### Changed
26
+
27
+ - **⚠️ 行為收緊:開頭讀取但夾帶寫入的語句一律需要 `admin`。** 例如 `WITH x AS (INSERT … RETURNING *) SELECT …`、`SELECT … INTO`、`EXPLAIN ANALYZE <寫入>`、`DESCRIBE ANALYZE <寫入>`(`DESCRIBE` 在 MySQL/MariaDB 是 `EXPLAIN` 的同義字)。過去這些一律不檢查;中間曾嘗試「比照該寫入的等級」,但那需要為 `INSERT INTO` 的 `INTO` 加文字例外,而例外之間會互相作用出新的繞過,因此改為單一規則。**升級後需要改用 `admin` 的用法有三類**:`data-admin` 連線上的可寫 CTE;對寫入語句做 `EXPLAIN ANALYZE` / `DESCRIBE ANALYZE` 效能分析(它會真的執行該語句);以及 MySQL/MariaDB 的 `SELECT … INTO @variable`——後者其實是純讀取,只是與 PostgreSQL 會建表的 `SELECT … INTO <table>` 共用關鍵字,為它加例外正是本次反覆出問題的來源,因此選擇留下這個誤擋。被擋時的錯誤訊息會指出是哪一個關鍵字觸發的。 不含 `ANALYZE` 的 `EXPLAIN` 只做計畫、不執行,維持唯讀;`SHOW` / `DESCRIBE` 不接受子查詢,因此 `SHOW CREATE TABLE users` 仍是讀取;`replace()` / `TRUNCATE()` / `INSERT()` 是函式不是語句,維持唯讀。
28
+ - **admin 以下的權限等級拒絕多語句 SQL。** 因為只有第一個語句會決定權限判定。`admin` 不受影響(它本來就允許所有語句類型)。分隔符依**該連線實際的方言**判定:`$$…$$` 只在 PostgreSQL 是字串、反引號只在 MySQL/MariaDB 引號化識別字、`#` 只在 MySQL/MariaDB 起始註解(在 PostgreSQL 是運算子)。方言未知時從嚴。
29
+ - **snippet 的唯讀證明依 `engine` 宣告的方言判定。** 因此 `SELECT \`update\` FROM t`(MySQL 反引號識別字)、`# drop …` 註解、`a.create` 這類欄位名不再被誤判為寫入;`FOR UPDATE` / `FOR SHARE` 是取鎖的讀取,同樣不算寫入。
30
+ - **無法解析的 snippet 只跳過該檔並發出警告,不再讓整個 snippet 目錄失效。** `queries check` 仍會回報它們並以 exit 1 結束。
31
+ - **snippet 一律拒絕寫入關鍵字。** snippet 依合約唯讀,這條規則不看 permission 等級,`admin` 連線亦然。
32
+ - **MongoDB 寫入 stage 在單連線 `query` 需要 `data-admin` 以上;在 snippet 與 `export` 一律拒絕。**
33
+
34
+ ### Added
35
+
36
+ - **執行路徑契約測試。** `src/adapters/` 以外每一處 `<x>Adapter.execute(...)` 都必須登記它倚賴的 gate,未登記的新路徑會讓測試失敗。這五個洞裡有兩個正是靠列舉全部路徑才發現的 —— 逐一稽核指令找不到它們。
37
+
38
+ ## [1.47.0] - 2026-08-05 - 連線逾時可設定
39
+
40
+ 決策記錄:`docs/adr/0003-connection-timeout-override-resolved-at-adapter-construction.md`。
41
+
42
+ ### Added
43
+
44
+ - **新的 root-level 全域旗標 `--timeout <ms>`。** 覆寫連線設定中的 `timeout`;兩者都沒有時沿用各 adapter 內建的 5000ms。合法值為 100~600000 的整數,須放在子指令之前(和 `--global` / `--use` 一樣是 root-level flag)。對所有引擎有效,典型用途是 MongoDB 跨 VPN 或連 Atlas 時,預設 5 秒的 server selection timeout 太緊:`dbcli --timeout 20000 --use <conn> list`。這個覆寫只在建立連線時套用,不會寫回設定檔;要永久生效請在連線設定裡寫 `timeout` 欄位。
45
+ - **連線設定檔新增 `timeout` 欄位。** 四種連線 schema 皆支援,毫秒、100~600000 整數、可省略。
46
+
47
+ ### Changed
48
+
49
+ - **設定檔驗證失敗的錯誤訊息改為可讀格式。** 過去會吐出整包 Zod `unionErrors` 巢狀 JSON;現在只列出與該連線 `system` 相符的分支問題,逐欄列出欄位路徑。
50
+ - **文件明確禁止 `2>&1`。** 診斷訊息走 stderr、結果走 stdout,合併兩者會讓 `--format json` 的輸出無法解析;SKILL 與 reference 都補上導管寫法。
51
+
8
52
  ## [1.46.0] - 2026-08-04 - MongoDB 逐欄連線設定
9
53
 
10
54
  決策記錄:`docs/adr/0002-mongodb-connection-field-first-config.md`;規格:`docs/specs/2026-08-04-mongodb-field-first-connection.md`。
package/assets/SKILL.md CHANGED
@@ -77,7 +77,10 @@ When reporting a check's outcome use the vocabulary `verified` (evidence matched
77
77
  `not_verified` (check ran and contradicted) / `indeterminate` (ran but ambiguous) /
78
78
  `blocked` (could not run due to config, permission, schema, placeholder, or safety gate).
79
79
 
80
- Prefer `--format json` for agent-friendly output.
80
+ Prefer `--format json` for agent-friendly output. Diagnostics (auto-limit notices,
81
+ warnings) go to stderr so stdout stays parseable — when piping JSON into a parser,
82
+ use `2>/dev/null` or leave stderr alone. **Never `2>&1`**: it merges those lines back
83
+ into stdout and the parse fails.
81
84
 
82
85
  ## Agent Task Packs
83
86
 
@@ -214,7 +217,10 @@ or `doctor` / `status` reports a missing or invalid config, follow this flow.
214
217
  `--password` / `--name` (and `--system`).
215
218
  3. **What permission tier?** Default to the **lowest** that satisfies the task:
216
219
  `query-only` → `read-write` → `data-admin` → `admin`. Set with `--permission`
217
- (defaults to `query-only`).
220
+ (defaults to `query-only`). Tiers judge what a statement does, not how it
221
+ opens: below `admin`, multi-statement SQL is rejected; snippets must be free
222
+ of write and DDL keywords; MongoDB `$out` / `$merge` need `data-admin` and are
223
+ refused entirely in snippets and `export`.
218
224
  4. **Verify, never assume.** After init: `dbcli status` (system + permission +
219
225
  blacklist summary, no creds) and `dbcli doctor --format json` (env, config
220
226
  shape, connectivity, schema-cache age, Mongo SRV path).
@@ -553,4 +559,4 @@ schema. Raw `query` / `export` invocations render a sortable table only.
553
559
  - Blacklisted tables and columns are redacted from query output.
554
560
  - `schema` reports `estimatedRowCount` and `sizeCategory` (small / medium / large / huge). For large/huge tables add `WHERE` or `LIMIT` — bands in reference.md.
555
561
  - `doctor` on `mongodb+srv://` reports whether SRV resolves natively or through the DoH fallback — useful when the runtime restricts DNS.
556
- - **Global flags:** `--version`, `--config <path>`, `--global`, `--use <name>`, `-v` / `--verbose` / `-vv`, `-q` / `--quiet`, `--no-color` (also honours `NO_COLOR`). Root-level flags must precede the command unless the command explicitly declares a command-level option.
562
+ - **Global flags:** `--version`, `--config <path>`, `--global`, `--use <name>`, `--timeout <ms>`, `-v` / `--verbose` / `-vv`, `-q` / `--quiet`, `--no-color` (also honours `NO_COLOR`). Root-level flags must precede the command unless the command explicitly declares a command-level option.
@@ -60,7 +60,9 @@ legacy 單檔 `.dbcli`。若要防護同一 OS 使用者的惡意 process,host
60
60
 
61
61
  回報驗證結果時使用詞彙:`verified`(證據符合)/ `not_verified`(驗證執行但結果矛盾)/ `indeterminate`(執行但證據不明確)/ `blocked`(因 config、權限、schema、placeholder 或安全閘門導致無法執行)。
62
62
 
63
- 優先用 `--format json` 取得代理友善的輸出。
63
+ 優先用 `--format json` 取得代理友善的輸出。診斷訊息(auto-limit 提示、警告)一律走 stderr,
64
+ stdout 保持可解析——把 JSON 導進 parser 時請用 `2>/dev/null` 或不要動 stderr。
65
+ **絕對不要用 `2>&1`**:那會把那些訊息併回 stdout,解析必定失敗。
64
66
 
65
67
  ## Agent Task Packs
66
68
 
@@ -426,4 +428,4 @@ dbcli export "SELECT * FROM orders" --format html --output orders.html
426
428
  - 被 blacklist 的 table / column 會從查詢輸出中遮蔽。
427
429
  - `schema` 回報 `estimatedRowCount` 與 `sizeCategory`(small / medium / large / huge)。大 / 巨大表要加 `WHERE` 或 `LIMIT` — 分界值見 reference.md。
428
430
  - 對 `mongodb+srv://` 連線,`doctor` 會回報 SRV 是用原生解析或走 DoH fallback — 在執行環境限制 DNS 時很有用。
429
- - **全域旗標:** `--version`、`--config <path>`、`--global`、`--use <name>`、`-v` / `--verbose` / `-vv`、`-q` / `--quiet`、`--no-color`(也尊重 `NO_COLOR`)。除非指令明確宣告 command-level 選項,否則 root-level 旗標必須放在指令之前。
431
+ - **全域旗標:** `--version`、`--config <path>`、`--global`、`--use <name>`、`--timeout <ms>`、`-v` / `--verbose` / `-vv`、`-q` / `--quiet`、`--no-color`(也尊重 `NO_COLOR`)。除非指令明確宣告 command-level 選項,否則 root-level 旗標必須放在指令之前。
@@ -19,6 +19,28 @@ command-level option is only valid after the command that declares it.
19
19
  | `--config <path>` | Select the `.dbcli` configuration path. |
20
20
  | `--global` | Select the user-global registry at `~/.config/dbcli/config.json` instead of the current project's `.dbcli` config. Place it before the command path. |
21
21
  | `--use <connection>` | Select a named connection for this invocation; place it before the command path unless that command explicitly lists a command-level `--use`. |
22
+ | `--timeout <ms>` | Connection timeout in milliseconds (integer, 100–600000), overriding the connection config's `timeout` field for this invocation. Applies to every engine adapter. Without either the flag or the config field, adapters fall back to their built-in 5000ms default. |
23
+
24
+ `--timeout` is applied only when the adapter is constructed for this invocation — it is
25
+ never written back to `config.json`. Set the connection's `timeout` field instead for a
26
+ value that persists across runs. On PostgreSQL, the same value is also used as the
27
+ session's `statement_timeout` (not just the connection timeout), so a low value can cut
28
+ off a long-running query with an error that looks like a connection timeout; the 100ms
29
+ floor exists specifically to keep that failure mode from being too easy to trigger.
30
+ Elasticsearch applies its timeout per request rather than once for the whole connection.
31
+ The `timeout` field itself always takes a literal number — unlike other connection
32
+ fields, it does not accept an `{"$env": "..."}` reference.
33
+
34
+ ### Redirecting output
35
+
36
+ Results go to stdout; diagnostics (auto-limit notices, warnings, update hints) go to
37
+ stderr. That split is what keeps `--format json` machine-parseable, so do not collapse
38
+ it with `2>&1` — the diagnostic lines land in front of the JSON document and the parse
39
+ fails. Pipe stdout alone, or add `2>/dev/null` when the diagnostics are not wanted:
40
+
41
+ ```bash
42
+ dbcli query '{}' --collection events --format json 2>/dev/null | jq '.rows | length'
43
+ ```
22
44
 
23
45
  ## Commands
24
46
 
@@ -118,6 +140,10 @@ agent mode disabled. A host that needs protection from a same-user hostile
118
140
  process can set `DBCLI_CONFIG_INTEGRITY_ANCHOR_DIR` to a protected or read-only
119
141
  directory; trusted writes publish detached digests there.
120
142
 
143
+ When a connection's config fails schema validation, dbcli reports the specific field
144
+ path(s) that are wrong for that connection's declared `system` — not the raw Zod union
145
+ error tree — so a broken `.dbcli` can be fixed without guessing which branch applies.
146
+
121
147
  ### list
122
148
 
123
149
  List all tables (SQL), collections (MongoDB), keys (Redis), or indices (Elasticsearch).
@@ -197,6 +223,13 @@ dbcli query "SELECT * FROM orders" --format html > orders.html # pipe to stdou
197
223
  **Options:** `--format <table|json|csv|html>`, `--ui` (open the dashboard in the system browser; implies `--format html`), `--limit <number>`, `--no-limit`, `--collection <name>` (MongoDB / Elasticsearch), `--index <name>` (Elasticsearch alias for `--collection`), `--fields <list>`, `--truncate <number>` / `--no-truncate`, `-f, --query-file <path>`, `--use <name[,name]>`, `--recovery`
198
224
  **Permission:** query-only+ (Redis: per-command; Elasticsearch: per HTTP method/path)
199
225
 
226
+ Below `admin`, SQL holding more than one statement is rejected, because only the
227
+ first statement would decide the permission check while a driver on the simple
228
+ query protocol executes them all. Semicolons inside string literals, backtick
229
+ identifiers, and `#` comments are not separators. A MongoDB pipeline containing
230
+ `$out` or `$merge` requires `data-admin`, and is rejected outright on `export`,
231
+ in snippets, and in multi-connection fan-out.
232
+
200
233
  #### Field projection (`--fields`)
201
234
 
202
235
  ```bash
@@ -253,7 +286,7 @@ instead of silently running its only connection.
253
286
  An explicit comma-separated `--use primary,staging` fans one query out to several named
254
287
  connections. `DBCLI_CONNECTION` always names one literal connection and never enables
255
288
  fan-out. SQL permits `SELECT`, `SHOW`, `DESCRIBE`, and `EXPLAIN`; MongoDB permits filters and
256
- read-only pipelines without top-level `$out` / `$merge`; Elasticsearch permits searches.
289
+ read-only pipelines without `$out` / `$merge`; Elasticsearch permits searches.
257
290
  Redis, writes, `--recovery`, `--ui`, CSV, and HTML are rejected before execution. Each
258
291
  connection keeps its own blacklist, limit metadata, audit entry, and error. Aggregate exit
259
292
  codes are `0` when all succeed, `2` for mixed outcomes, and `1` when all fail or preflight
@@ -505,6 +538,13 @@ dbcli q @analytics/revenue --param days=30 --format html > report.html
505
538
 
506
539
  Each `.sql` file is plain SQL with optional YAML frontmatter inside a leading `-- ---` block. Lines outside frontmatter form the SQL body.
507
540
 
541
+ Snippets are read-only by contract, at every permission level including `admin`.
542
+ A body must be a single statement opening with `SELECT` or `WITH` **and** free of
543
+ write or DDL keywords, so a data-modifying CTE (`WITH x AS (DELETE … RETURNING *)
544
+ SELECT * FROM x`) and `SELECT … INTO` are rejected at parse time rather than at
545
+ execution. A MongoDB body may not contain `$out` or `$merge`. The same rule
546
+ applies to `verify.query` in frontmatter, which `q --verify` executes verbatim.
547
+
508
548
  ```sql
509
549
  -- ---
510
550
  -- name: DAU
@@ -2605,6 +2645,8 @@ MongoDB connections use a JSON-based query model instead of SQL. Treat MongoDB s
2605
2645
 
2606
2646
  `init --system mongodb` defaults to a field-by-field wizard (`host`, `srv`, `port`, `user`, `password` + `authSource`, then optional `replicaSet` / `tls`); a full `uri` is an explicit advanced choice in the interactive flow and the unchanged non-interactive path via `--uri`. Optional fields `authSource`, `replicaSet`, `tls`, and `srv` express what previously required embedding options in the `uri` query string. Atlas-style `mongodb+srv://` URIs are supported both as a full `uri` and via the per-field `srv: true` option. `list` and `query` run against the database configured for the connection, and `query` always requires `--collection <name>`.
2607
2647
 
2648
+ The 5000ms default server-selection timeout is often too tight for a connection over a VPN or to Atlas. Set a `timeout` field (ms) in the connection config, or override it per invocation with root-level `--timeout`, e.g. `dbcli --timeout 20000 --use <conn> list`.
2649
+
2608
2650
  **Supported commands:** `init`, `use`, `list`, `schema`, `query`, `q`, `insert`, `update`, `delete`, `export`, `status`, `shell`, `doctor`, `upgrade`, `completion`
2609
2651
 
2610
2652
  **Limited support:**
@@ -2669,7 +2711,7 @@ Redis connections speak Redis commands rather than SQL. The adapter uses Bun's n
2669
2711
 
2670
2712
  - Required fields: `system: redis`, `host`, `port`. `password` and `database` are optional.
2671
2713
  - `database` is the **logical DB index** (`"0"` … `"15"`), kept as a string to play nicely with env-ref bindings. `list` and the connection metadata both label it as the active DB.
2672
- - `connection.timeout` (ms, default 5000) maps to the client's `connectionTimeout`.
2714
+ - `connection.timeout` (ms, default 5000) maps to the client's `connectionTimeout`; root-level `--timeout <ms>` overrides it for a single invocation.
2673
2715
 
2674
2716
  ### Permission classification
2675
2717
 
@@ -2799,7 +2841,7 @@ Elasticsearch connections speak the REST API. The adapter is fetch-based (no SDK
2799
2841
  - Either `host` + `port` (default `https://localhost:9200`) or `nodes: [...]` (first node is used) or `cloudId`.
2800
2842
  - Auth precedence: `apiKey` → `user`/`password` (HTTP Basic). Leave both unset for an open cluster.
2801
2843
  - `protocol` defaults to `https`. For TLS quirks: `caPath` (path to a PEM bundle) and `rejectUnauthorized: false` (last resort).
2802
- - `connection.timeout` (ms, default 5000) is wired to `AbortController` on every request.
2844
+ - `connection.timeout` (ms, default 5000) is wired to `AbortController` on every request; root-level `--timeout <ms>` overrides it for a single invocation.
2803
2845
 
2804
2846
  ### Permission classification
2805
2847