@fadhilp/stateql 0.15.1 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/cli.js CHANGED
@@ -7,6 +7,7 @@ import { BSON } from "mongodb";
7
7
  import { exitCodeFor } from "./errors.js";
8
8
  import { StateQL } from "./stateql.js";
9
9
  import { agentResponse } from "./agent-response.js";
10
+ import { askPassword, cliCredentialResolver, deleteOsPassword, saveOsPassword } from "./os-credentials.js";
10
11
  const parsed = parseArgs({
11
12
  allowPositionals: true,
12
13
  strict: true,
@@ -15,6 +16,7 @@ const parsed = parseArgs({
15
16
  profile: { type: "string" },
16
17
  env: { type: "string" },
17
18
  "credential-ref": { type: "string" },
19
+ "ask-password": { type: "boolean" },
18
20
  "read-only": { type: "boolean" },
19
21
  "read-write": { type: "boolean" },
20
22
  params: { type: "string" },
@@ -76,6 +78,7 @@ const stateql = new StateQL({
76
78
  ...(values["max-cell-characters"] === undefined
77
79
  ? {}
78
80
  : { maxCellCharacters: Number(values["max-cell-characters"]) }),
81
+ credentialResolver: cliCredentialResolver,
79
82
  signal: abortController.signal,
80
83
  });
81
84
  try {
@@ -350,30 +353,62 @@ async function dispatchSession(action, args) {
350
353
  }
351
354
  async function dispatchProfile(action, args) {
352
355
  switch (action) {
353
- case "add":
356
+ case "add": {
354
357
  if (values["read-only"] && values["read-write"]) {
355
358
  throw new Error("--read-only and --read-write are mutually exclusive.");
356
359
  }
357
- return stateql.addProfile(requireValue(args[0], "profile name"), args[1], {
360
+ const name = requireValue(args[0], "profile name");
361
+ const passwordRef = values["ask-password"]
362
+ ? await saveOsPassword(await askPassword(name, requireValue(args[1], "TARGET for --ask-password")))
363
+ : undefined;
364
+ const added = await stateql.addProfile(name, args[1], {
358
365
  ...(values.env ? { secretEnv: values.env } : {}),
359
366
  ...(values["credential-ref"] ? { credentialRef: values["credential-ref"] } : {}),
367
+ ...(passwordRef ? { passwordRef } : {}),
360
368
  readOnly: !values["read-write"],
361
369
  });
362
- case "update":
370
+ if (!added.ok)
371
+ await deleteOsPassword(passwordRef);
372
+ return added;
373
+ }
374
+ case "update": {
363
375
  if (values["read-only"] && values["read-write"])
364
376
  throw new Error("--read-only and --read-write are mutually exclusive.");
365
- return stateql.updateProfile(requireValue(args[0], "profile name"), {
377
+ const name = requireValue(args[0], "profile name");
378
+ const before = await stateql.showProfile(name);
379
+ if (!before.ok)
380
+ return before;
381
+ const target = args[1] ?? before.data.target;
382
+ const passwordRef = values["ask-password"]
383
+ ? await saveOsPassword(await askPassword(name, requireValue(target ?? undefined, "TARGET for --ask-password")))
384
+ : undefined;
385
+ const updated = await stateql.updateProfile(name, {
366
386
  ...(args[1] !== undefined ? { target: args[1] } : {}),
367
387
  ...(values.env ? { secretEnv: values.env } : {}),
368
388
  ...(values["credential-ref"] ? { credentialRef: values["credential-ref"] } : {}),
389
+ ...(passwordRef ? { passwordRef } : {}),
369
390
  ...(values["read-only"] ? { readOnly: true } : values["read-write"] ? { readOnly: false } : {}),
370
391
  });
392
+ if (!updated.ok) {
393
+ await deleteOsPassword(passwordRef);
394
+ return updated;
395
+ }
396
+ if (updated.data.password_ref !== before.data.password_ref)
397
+ await deleteOsPassword(before.data.password_ref);
398
+ return updated;
399
+ }
371
400
  case "list":
372
401
  return stateql.listProfiles();
373
402
  case "show":
374
403
  return stateql.showProfile(requireValue(args[0], "profile name"));
375
- case "remove":
376
- return stateql.removeProfile(requireValue(args[0], "profile name"));
404
+ case "remove": {
405
+ const name = requireValue(args[0], "profile name");
406
+ const before = await stateql.showProfile(name);
407
+ const removed = await stateql.removeProfile(name);
408
+ if (removed.ok && before.ok)
409
+ await deleteOsPassword(before.data.password_ref);
410
+ return removed;
411
+ }
377
412
  default:
378
413
  throw new Error(`Unknown profile command "${action ?? ""}".`);
379
414
  }
@@ -580,7 +615,7 @@ Commands:
580
615
  connect TARGET | --env ENV | --credential-ref REF | --profile NAME
581
616
  disconnect, status
582
617
  actor show | set-name NAME
583
- profile add|update NAME [TARGET | --env ENV | --credential-ref REF]
618
+ profile add|update NAME [TARGET [--ask-password] | --env ENV | --credential-ref REF]
584
619
  profile list|show|remove
585
620
  query, filter, exec, show, rows, count, columns, export
586
621
  mongo query|exec|plan '<EJSON command>'
@@ -598,7 +633,8 @@ SQL parameters: --params JSON, repeated --param VALUE, or --params-file FILE.
598
633
  Query preview: --preview-rows N (default: 5, maximum: 200).
599
634
  Long cells: --max-cell-characters N (default: 200); use export for full values.
600
635
  Deadline: --timeout-ms N (default: 30000). Ctrl+C cancels database work.
601
- Credential refs require a trusted host CredentialResolver; the standalone CLI cannot resolve them.
636
+ Saved passwords: --ask-password opens a dialog and keeps the password in the OS credential store.
637
+ Other credential refs require a trusted host CredentialResolver; the standalone CLI cannot resolve them.
602
638
  State: --max-state-bytes N, --cache-ttl-seconds N, --result-ttl-seconds N.
603
639
  Output: --output agent|json|jsonl|text|silent (default: agent).
604
640
  Agent rows: arrays in "columns" order (objects when shapes differ). next_offset only when more rows exist.
@@ -0,0 +1,6 @@
1
+ import type { CredentialRequest } from "./types.js";
2
+ export declare function isOsPasswordRef(reference: string | null | undefined): reference is string;
3
+ export declare function cliCredentialResolver(request: CredentialRequest): Promise<string | undefined>;
4
+ export declare function saveOsPassword(password: string): Promise<string>;
5
+ export declare function deleteOsPassword(reference: string | null | undefined): Promise<void>;
6
+ export declare function askPassword(profile: string, target: string): Promise<string>;
@@ -0,0 +1,96 @@
1
+ import { execFile } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { env, platform } from "node:process";
4
+ import { promisify } from "node:util";
5
+ const SERVICE = "stql";
6
+ const PREFIX = "os:";
7
+ const run = promisify(execFile);
8
+ export function isOsPasswordRef(reference) {
9
+ return reference?.startsWith(PREFIX) ?? false;
10
+ }
11
+ export async function cliCredentialResolver(request) {
12
+ if (request.source === "credential_ref")
13
+ return undefined;
14
+ if (request.source !== "password_ref")
15
+ return env[request.reference];
16
+ if (!isOsPasswordRef(request.reference))
17
+ return undefined;
18
+ return (await osEntry(request.reference)).getPassword() ?? undefined;
19
+ }
20
+ export async function saveOsPassword(password) {
21
+ const reference = `${PREFIX}${randomUUID()}`;
22
+ (await osEntry(reference)).setPassword(password);
23
+ return reference;
24
+ }
25
+ export async function deleteOsPassword(reference) {
26
+ if (!isOsPasswordRef(reference))
27
+ return;
28
+ (await osEntry(reference)).deletePassword();
29
+ }
30
+ async function osEntry(reference) {
31
+ const { Entry } = await import("@napi-rs/keyring");
32
+ return new Entry(SERVICE, reference.slice(PREFIX.length));
33
+ }
34
+ export async function askPassword(profile, target) {
35
+ const url = new URL(target);
36
+ const user = decodeURIComponent(url.username);
37
+ const message = `Password for ${user ? `${user}@` : ""}${url.host} (StateQL profile "${profile}")`;
38
+ let output;
39
+ try {
40
+ output = await passwordDialog(message);
41
+ }
42
+ catch (error) {
43
+ if (isMissingCommand(error)) {
44
+ throw new Error("--ask-password needs a password dialog: zenity on Linux, osascript on macOS.");
45
+ }
46
+ throw new Error("Password entry was cancelled.");
47
+ }
48
+ const password = platform === "win32" ? output : output.replace(/\r?\n$/, "");
49
+ if (password === "")
50
+ throw new Error("No password was entered.");
51
+ return password;
52
+ }
53
+ async function passwordDialog(message) {
54
+ if (platform === "win32") {
55
+ // Get-Credential opens behind the active window; a TopMost form stays visible.
56
+ // windowsHide makes the first ShowWindow hide the form, so show it again explicitly.
57
+ const script = [
58
+ "$ErrorActionPreference = 'Stop'",
59
+ "[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false",
60
+ "Add-Type -AssemblyName System.Windows.Forms",
61
+ "Add-Type -Namespace StateQL -Name Win32 -MemberDefinition '[DllImport(\"user32.dll\")] public static extern bool ShowWindow(IntPtr window, int command);'",
62
+ "[Windows.Forms.Application]::EnableVisualStyles()",
63
+ "$form = New-Object Windows.Forms.Form -Property @{ Text = 'StateQL'; TopMost = $true; StartPosition = 'CenterScreen'; FormBorderStyle = 'FixedDialog'; MaximizeBox = $false; MinimizeBox = $false; AutoSize = $true; AutoSizeMode = 'GrowAndShrink'; Padding = 12 }",
64
+ "$layout = New-Object Windows.Forms.FlowLayoutPanel -Property @{ FlowDirection = 'TopDown'; AutoSize = $true }",
65
+ "$label = New-Object Windows.Forms.Label -Property @{ Text = $env:STQL_PROMPT_MESSAGE; AutoSize = $true; MaximumSize = '360,0' }",
66
+ "$box = New-Object Windows.Forms.TextBox -Property @{ UseSystemPasswordChar = $true; Width = 360 }",
67
+ "$buttons = New-Object Windows.Forms.FlowLayoutPanel -Property @{ FlowDirection = 'RightToLeft'; Width = 366; Height = 34 }",
68
+ "$cancel = New-Object Windows.Forms.Button -Property @{ Text = 'Cancel'; DialogResult = 'Cancel' }",
69
+ "$ok = New-Object Windows.Forms.Button -Property @{ Text = 'OK'; DialogResult = 'OK' }",
70
+ "$buttons.Controls.AddRange(@($cancel, $ok))",
71
+ "$layout.Controls.AddRange(@($label, $box, $buttons))",
72
+ "$form.Controls.Add($layout)",
73
+ "$form.AcceptButton = $ok",
74
+ "$form.CancelButton = $cancel",
75
+ "$form.Add_Shown({ [void][StateQL.Win32]::ShowWindow($form.Handle, 5); $form.Activate(); [void]$box.Focus() })",
76
+ "if ($form.ShowDialog() -ne 'OK') { exit 1 }",
77
+ "[Console]::Out.Write($box.Text)",
78
+ ].join("\n");
79
+ const { stdout } = await run("powershell.exe", ["-NoProfile", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { env: { ...env, STQL_PROMPT_MESSAGE: message }, windowsHide: true });
80
+ return stdout;
81
+ }
82
+ if (platform === "darwin") {
83
+ const { stdout } = await run("osascript", [
84
+ "-e", "on run argv",
85
+ "-e", 'text returned of (display dialog (item 1 of argv) default answer "" with hidden answer with title "StateQL")',
86
+ "-e", "end run",
87
+ message,
88
+ ]);
89
+ return stdout;
90
+ }
91
+ const { stdout } = await run("zenity", ["--password", "--title", message]);
92
+ return stdout;
93
+ }
94
+ function isMissingCommand(error) {
95
+ return error.code === "ENOENT";
96
+ }
package/docs/cli.md CHANGED
@@ -11,7 +11,7 @@ stql disconnect
11
11
  stql status
12
12
  stql actor show
13
13
  stql actor set-name <display-name>
14
- stql profile add|update NAME [TARGET | --env ENV | --credential-ref REF]
14
+ stql profile add|update NAME [TARGET [--ask-password] | --env ENV | --credential-ref REF]
15
15
  [--read-only|--read-write]
16
16
  stql profile list|show|remove
17
17
  stql session start|list|show|summary|close
@@ -45,9 +45,10 @@ export SQLITE_DATABASE='sqlite:./app.sqlite'
45
45
  stql connect --env SQLITE_DATABASE --name local --read-only
46
46
  ```
47
47
 
48
- StateQL stores no PostgreSQL, MySQL, MongoDB, or Redis password.
48
+ StateQL stores no PostgreSQL, MySQL, MongoDB, or Redis password in its state.
49
49
  Credential-bearing URLs must be supplied through `--env` or an opaque full-URL
50
- credential reference. SQLite paths remain persisted as connection metadata.
50
+ credential reference, or the password can be [saved in the OS credential
51
+ store](#saved-passwords). SQLite paths remain persisted as connection metadata.
51
52
 
52
53
  ## Local profiles
53
54
 
@@ -70,15 +71,36 @@ stql connect --profile production
70
71
  ```
71
72
 
72
73
  Credential references are bounded nonempty opaque strings; StateQL does not
73
- apply environment-variable syntax or normalization to them. They can only be
74
- resolved by a trusted host `CredentialResolver`, so the standalone CLI may
75
- store them in profiles but cannot connect with them.
74
+ apply environment-variable syntax or normalization to them. Apart from the
75
+ `os:` password references below, they can only be resolved by a trusted host
76
+ `CredentialResolver`, so the standalone CLI may store them in profiles but
77
+ cannot connect with them.
78
+
79
+ ## Saved passwords
80
+
81
+ `--ask-password` opens a password dialog and saves the password in the OS
82
+ credential store: Windows Credential Manager, macOS Keychain, or Linux Secret
83
+ Service. The profile keeps the password-free target and an `os:` password
84
+ reference.
85
+
86
+ ```bash
87
+ stql profile add charlie 'postgres://reader@db.example.com:5432/app?sslmode=verify-full' --ask-password --read-only
88
+ stql profile update charlie --ask-password # replace the saved password
89
+ stql profile remove charlie # also deletes the saved password
90
+ ```
91
+
92
+ The dialog uses Windows PowerShell on Windows, `osascript` on macOS, and `zenity`
93
+ on Linux, so it also works when an agent runs the command. Replacing the
94
+ password, changing the target or source, or removing the profile deletes the
95
+ old saved password; reconnect sessions that used it. Any program running as
96
+ your OS user can read the store, so give agent profiles a read-only database
97
+ user.
76
98
 
77
99
  A bare connection target matching a profile name resolves to that profile;
78
100
  otherwise it remains a path or database URL.
79
101
 
80
102
  `profile update` changes subsequent connections, not an already-open connection.
81
103
  Omitting the source keeps it; supplying a new source replaces the old one.
82
- Password references are configured through the library or batch API, not a CLI
83
- `--password-ref` flag. See [safe profile updates](library.md#safe-profile-updates)
104
+ Other password references are configured through the library or batch API, not
105
+ a CLI `--password-ref` flag. See [safe profile updates](library.md#safe-profile-updates)
84
106
  for source-replacement and downgrade restrictions.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fadhilp/stateql",
3
- "version": "0.15.1",
3
+ "version": "0.16.0",
4
4
  "description": "Stateful, agent-oriented database CLI for safe result reuse",
5
5
  "repository": {
6
6
  "type": "git",
@@ -47,6 +47,7 @@
47
47
  "node": ">=22.16"
48
48
  },
49
49
  "dependencies": {
50
+ "@napi-rs/keyring": "^2.1.1",
50
51
  "@redis/client": "^5.12.1",
51
52
  "bson": "^6.10.4",
52
53
  "mongodb": "^6.21.0",
@@ -22,7 +22,7 @@ If `stql --version` fails, ask the user before installing
22
22
  3. Never add `--allow-destructive`, `--allow-unbounded`, or `--replay` unless the
23
23
  user explicitly approved that operation. They are approvals, not fixes.
24
24
  4. Never put a password in a command. Remote URLs go in an environment variable
25
- that you pass with `--env`.
25
+ that you pass with `--env`, or in a profile with a saved password (below).
26
26
  5. Pass values as parameters (`--param`), never by building SQL strings.
27
27
  6. Do not rerun a query to see more rows. Use its handle.
28
28
 
@@ -37,6 +37,11 @@ stql connect --env DATABASE_URL --read-write # only for requested changes
37
37
 
38
38
  `status` without a `connection` field means no connection is open.
39
39
 
40
+ To save a remote database with its password, run
41
+ `stql profile add <name> '<password-free URL>' --ask-password`. The user types
42
+ the password in a dialog; then use `stql connect <name>`. `stql profile list`
43
+ shows saved profiles.
44
+
40
45
  ## Read workflow
41
46
 
42
47
  1. Find objects: `stql objects table --search order`