@jacebenson/jsn 5.5.7 → 5.5.8-dev.220.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.
Files changed (66) hide show
  1. package/README.md +16 -1
  2. package/package.json +5 -6
  3. package/skills/servicenow/SKILL.md +9 -1
  4. package/src/app.js +4 -79
  5. package/src/auth/credential-store.js +33 -8
  6. package/src/auth/windows-credential-store.js +85 -0
  7. package/src/auth/windows-credential-store.ps1 +163 -0
  8. package/src/bounded-reads.js +13 -0
  9. package/src/capabilities.js +8 -3
  10. package/src/cli-adapter.js +26 -3
  11. package/src/cli.js +13 -14
  12. package/src/command-families.js +68 -0
  13. package/src/commands/_generic.js +1 -0
  14. package/src/commands/_ticket.js +1 -1
  15. package/src/commands/actions.js +9 -4
  16. package/src/commands/approvals.js +1 -1
  17. package/src/commands/atf.js +1 -1
  18. package/src/commands/attachments.js +1 -1
  19. package/src/commands/auth.js +21 -2
  20. package/src/commands/codesearch.js +11 -2
  21. package/src/commands/compare.js +22 -0
  22. package/src/commands/customizations.js +3 -4
  23. package/src/commands/decisiontables.js +4 -0
  24. package/src/commands/docs/docs.js +5 -5
  25. package/src/commands/domains.js +1 -1
  26. package/src/commands/eval.js +11 -5
  27. package/src/commands/flows.js +24 -7
  28. package/src/commands/groupmembers.js +1 -1
  29. package/src/commands/grouproles.js +1 -1
  30. package/src/commands/groups.js +1 -1
  31. package/src/commands/midservers.js +4 -11
  32. package/src/commands/perf.js +2 -3
  33. package/src/commands/plugins.js +9 -0
  34. package/src/commands/records.js +12 -2
  35. package/src/commands/scopes.js +1 -1
  36. package/src/commands/scrapi.js +2 -2
  37. package/src/commands/setup.js +4 -34
  38. package/src/commands/skipped-updates.js +2 -3
  39. package/src/commands/store.js +4 -1
  40. package/src/commands/subscriptions.js +47 -0
  41. package/src/commands/tickets.js +1 -1
  42. package/src/commands/users.js +1 -1
  43. package/src/commands/workflows.js +3 -5
  44. package/src/config.js +1 -0
  45. package/src/context.js +8 -56
  46. package/src/docs-links.js +28 -0
  47. package/src/flow-create.js +9 -0
  48. package/src/help.js +4 -0
  49. package/src/helpers.js +17 -24
  50. package/src/instance-inventory.js +184 -0
  51. package/src/intended-context.js +68 -0
  52. package/src/mutation-context.js +69 -46
  53. package/src/output.js +1 -1
  54. package/src/paginated-search.js +146 -178
  55. package/src/picker-ui.js +20 -0
  56. package/src/prompt-engine.js +176 -0
  57. package/src/prompts.js +293 -43
  58. package/src/records/inspect.js +30 -16
  59. package/src/records-engine.js +2 -2
  60. package/src/schedule-cache.js +96 -0
  61. package/src/schedules/itom-2026-04-09.json +121 -0
  62. package/src/schedules/public-inventory.json +6224 -0
  63. package/src/sdk-batch.js +2 -1
  64. package/src/sdk.js +42 -16
  65. package/src/setup-preferences.js +2 -2
  66. package/src/subscriptions.js +176 -0
package/README.md CHANGED
@@ -15,7 +15,7 @@ jsn setup
15
15
 
16
16
  Setup connects a named profile to your instance. Its default preset allows writes, so enable read-only mode before exploring. See [setup and authentication](https://jsn.jace.pro/docs/setup/).
17
17
 
18
- For unreleased changes, use `npm install -g @jacebenson/jsn@dev`; see [channels and updates](https://github.com/jacebenson/jsn/blob/main/docs/releases.md).
18
+ For unreleased changes, use `npm install -g @jacebenson/jsn@dev`; see [channels and updates](https://github.com/jacebenson/jsn/blob/main/site/docs/maintainers/releases.md).
19
19
 
20
20
  ## Read and discover
21
21
 
@@ -42,6 +42,21 @@ Writes are not universally dry-run operations or confirmation prompts. Inspect e
42
42
 
43
43
  Inspect the bundled skill with `jsn skill show`, then use `jsn skill install` to select your agent or `jsn skill install --target hermes` for Hermes. Reinstall after upgrading JSN; reinstalling replaces recorded copies, including local edits. See [agent installation](https://jsn.jace.pro/docs/agents/).
44
44
 
45
+ ## Local prompt experiment
46
+
47
+ From the repository root, run `node cli/scripts/prompt-demo.mjs` in a terminal.
48
+ It uses synthetic servers only. Nothing connects to ServiceNow or changes profiles.
49
+ Type to filter, use arrows to move and Enter to select. Down past the last loaded
50
+ server fetches another page. Escape cancels. Ctrl+C or Ctrl+D exits the prompt.
51
+ The forms menu includes masked input, confirmation and a checklist. The editor
52
+ menu uses your `$VISUAL` or `$EDITOR`, falling back to `vi`.
53
+
54
+ From `cli/`, `npm ci` installs lint and test dependencies without Inquirer.
55
+ Run `npm run test:pty` for the Linux Python 3 PTY checks. `npm test` also collects
56
+ them. Mutation tooling is not part of normal installs. `npm run test:mutation`
57
+ fetches pinned Stryker 10.1.1 on demand and uses `stryker.config.json`, retaining
58
+ the offline mutation-safety tests. Its execution is separate from normal tests.
59
+
45
60
  ## Go deeper
46
61
 
47
62
  - [CLI guide and feature workflows](https://jsn.jace.pro/docs/cli-guide/)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.7",
3
+ "version": "5.5.8-dev.220.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -9,8 +9,9 @@
9
9
  "main": "src/cli.js",
10
10
  "scripts": {
11
11
  "test": "node scripts/test.mjs",
12
- "test:mutation": "stryker run",
13
- "lint": "npx eslint src/ bin/ test/",
12
+ "test:mutation": "npm exec --yes --package=@stryker-mutator/core@10.1.1 -- stryker run stryker.config.json",
13
+ "test:pty": "node --test test/pty/prompts-pty.test.js",
14
+ "lint": "eslint src/ bin/ test/",
14
15
  "start": "node bin/jsn.js"
15
16
  },
16
17
  "keywords": [
@@ -23,8 +24,6 @@
23
24
  "repository": "https://github.com/jacebenson/jsn",
24
25
  "license": "MIT",
25
26
  "dependencies": {
26
- "@inquirer/core": "^10.3.2",
27
- "@inquirer/prompts": "^7.10.1",
28
27
  "commonmark": "^0.31.2",
29
28
  "js-yaml": "^5.5.0",
30
29
  "saxes": "^6.0.0",
@@ -32,7 +31,7 @@
32
31
  },
33
32
  "devDependencies": {
34
33
  "@eslint/js": "^10.0.1",
35
- "@stryker-mutator/core": "^10.0.0",
34
+ "eslint": "^10.15.0",
36
35
  "globals": "^17.6.0"
37
36
  },
38
37
  "files": [
@@ -22,7 +22,15 @@ Discover commands with `jsn --help`, `jsn discover "search words"`, and
22
22
  For development:
23
23
 
24
24
  1. Choose or create the application scope and update set.
25
- 2. Do the work, keeping related changes together.
25
+ 2. Supply task-owned `--expect-scope <scope/name/id>` and
26
+ `--expect-update-set <name/id>` on customization writes, or explicitly save
27
+ profile-and-instance-bound `write_context` in local `.servicenow/config.json`.
28
+ Never derive intended values from current preferences. `--force` cannot bypass
29
+ missing intent, unknown context or mismatches. Domain-scoped customization
30
+ currently refuses, including `--expect-domain`, because `X-Now-Domain` does not
31
+ prove effective domain. Inspect with `auth status --context`; `--local` is offline.
32
+ Reads never print or fetch automatic context. Ordinary ticket/data edits do not
33
+ need customization expectations. Keep related development changes together.
26
34
  3. Verify the results on the instance and report where changes were captured.
27
35
  4. Offer to run relevant existing ATFs and instance scans, or create missing checks.
28
36
  5. Ask whether anything else belongs in the update set. If the user confirms
package/src/app.js CHANGED
@@ -10,14 +10,12 @@
10
10
  import { AuthManager } from './auth.js';
11
11
  import { createAuthRecovery } from './auth-recovery.js';
12
12
  import { SDKClient } from './sdk.js';
13
- import { OutputWriter, FormatAuto, FormatJSON, FormatMarkdown, FormatQuiet, FormatStyled, hyperlink } from './output.js';
13
+ import { OutputWriter, FormatAuto, FormatJSON, FormatMarkdown, FormatQuiet, FormatStyled } from './output.js';
14
14
  import { saveConfig, isTrustedCredentialDestination } from './config.js';
15
15
  import { resolveSession, applySession, contextFromSession, requireSessionInstance } from './session.js';
16
- import { getCurrentUser, getCurrentApplication, getCurrentUpdateSet } from './context.js';
17
16
  import { errUsage, errAuth } from './errors.js';
18
17
  import { canPrompt, canUsePicker } from './helpers.js';
19
18
  import { guardMutationContext } from './mutation-context.js';
20
- import process from 'node:process';
21
19
 
22
20
 
23
21
  export class App {
@@ -86,85 +84,12 @@ export class App {
86
84
  return this.session?.instance || '';
87
85
  }
88
86
 
89
- async printContextHeader(argv = {}) {
90
- if (!this.getEffectiveInstance() || !this.sdk) return;
91
- if (process.env.JSN_NO_HEADER) return;
92
- if (this.output.getFormat() === FormatJSON || this.output.getFormat() === FormatQuiet) return;
93
-
94
- // The banner is a terminal affordance, never data. `--get`/`--select`
95
- // prints an extracted JSON value while the format still reports pretty, so
96
- // a banner on stderr merged with `2>&1` landed in front of the JSON and
97
- // broke `jsn ... 2>&1 | jq` / `json.load(sys.stdin)` at character 0. Skip
98
- // it whenever an extraction was requested or stderr is not a terminal
99
- // (nobody reads it there, and it costs five HTTP requests per command:
100
- // user, application preference, update-set preference, scope, update set).
101
- if (argv.get !== undefined && argv.get !== null && argv.get !== false) return;
102
- if (process.stderr.isTTY !== true) return;
103
-
104
- let userDisplayName = 'Unknown';
105
- let userSysID = '';
106
-
107
- try {
108
- const user = await getCurrentUser(this.sdk);
109
- if (user) {
110
- userDisplayName = user.name || user.user_name;
111
- userSysID = user.sys_id;
112
- this.context.username = userDisplayName;
113
- }
114
- } catch {
115
- // ignore
116
- }
117
-
118
- let displayUserName = userDisplayName;
119
- if (displayUserName.length > 10) {
120
- displayUserName = displayUserName.slice(0, 6) + '...';
121
- }
122
-
123
- // Both lookups depend on the user, but not on one another.
124
- const [application, selectedUpdateSet] = userSysID ? await Promise.all([
125
- getCurrentApplication(this.sdk, userSysID, { unknownWhenMissing: true }).catch(() => null),
126
- getCurrentUpdateSet(this.sdk, userSysID).catch(() => null),
127
- ]) : [null, null];
128
- const scope = application?.scope || 'unknown';
129
- const updateSet = selectedUpdateSet?.name && selectedUpdateSet.name !== '-'
130
- ? selectedUpdateSet.name : 'unknown';
131
- const updateSetSysID = selectedUpdateSet?.name && selectedUpdateSet.name !== '-'
132
- ? selectedUpdateSet.sys_id : '';
133
- this.context.scope = scope;
134
- this.context.updateSet = updateSet;
135
-
136
- const instance = this.getEffectiveInstance();
137
- const instanceLink = instance;
138
- const userLink = `${instance}/sys_user_list.do?sysparm_query=sys_id=${userSysID}`;
139
- const scopeLink = `${instance}/sys_scope.do?sysparm_query=scope=${scope}`;
140
- const updateSetLink = updateSetSysID
141
- ? `${instance}/sys_update_set.do?sys_id=${updateSetSysID}`
142
- : `${instance}/sys_update_set_list.do`;
143
-
144
- const scopeFormatted = `[${scope}]`;
145
-
146
- // Terminal hyperlinks are invisible in a TTY and garbage in a pipe, so the
147
- // banner only wraps values when stderr is actually a terminal.
148
- const link = (text, url) => (process.stderr.isTTY === true ? hyperlink(text, url) : text);
149
-
150
- // Read-only profiles get a lock badge on every command run, so the
151
- // armed safety is always visible (not just in `auth status`).
152
- const roBadge = this.session?.readOnly === true ? ' 🔒' : '';
153
-
154
- process.stderr.write('# Use `jsn scopes` to change scope, `jsn updatesets set` to change updateset\n');
155
- process.stderr.write('PROFILE USER [SCOPE] UPDATE SET\n');
156
-
157
- const profileStr = `${link(String(this.context.profileName).padEnd(9), instanceLink)}${roBadge}`;
158
- const userStr = link(String(displayUserName).padEnd(9), userLink);
159
- const scopeStr = link(String(scopeFormatted).padEnd(17), scopeLink);
160
- const updateSetStr = link(String(updateSet), updateSetLink);
161
-
162
- process.stderr.write(`${profileStr} ${userStr} ${scopeStr} ${updateSetStr}\n\n`);
163
-
164
- }
87
+ // Retained for SDK consumers. Automatic context banners are retired.
88
+ async printContextHeader() {}
165
89
 
166
90
  async guardMutationContext(argv) {
167
91
  this.mutationContext = await guardMutationContext(this, argv);
92
+ if (this.sdk) this.sdk.mutationContext = this.mutationContext;
168
93
  }
169
94
 
170
95
  ok(data, opts = {}) {
@@ -4,6 +4,7 @@ import crypto from 'node:crypto';
4
4
  import { isDeepStrictEqual } from 'node:util';
5
5
  import { execFileSync } from 'node:child_process';
6
6
  import { globalConfigDir } from '../config.js';
7
+ import { windowsCredentialOperation, legacyWindowsKey } from './windows-credential-store.js';
7
8
 
8
9
  // ─── Credential key helpers ───
9
10
 
@@ -52,7 +53,10 @@ function warnPlaintext() {
52
53
  process.stderr.write('Warning: plaintext credential storage explicitly enabled for this process; credentials are portable and backups can expose them.\n');
53
54
  }
54
55
  function refusal() {
55
- return storageError(`Secure credential storage unavailable or readback failed. Unlock/install secret-tool and retry. Existing plaintext credentials are preserved; to use or migrate them on a headless host, explicitly set ${PLAINTEXT_ENV}=1 for this process. Never commit or share credential files.`);
56
+ const repair = process.platform === 'win32'
57
+ ? 'Windows Credential Manager requires Windows PowerShell 5.1 or PowerShell 7+ with FullLanguage/Add-Type and native API access allowed by policy.'
58
+ : 'Unlock/install secret-tool and retry.';
59
+ return storageError(`Secure credential storage unavailable or readback failed. ${repair} Existing plaintext credentials are preserved; to use or migrate them on a headless host, explicitly set ${PLAINTEXT_ENV}=1 for this process. Never commit or share credential files.`);
56
60
  }
57
61
 
58
62
  // Validate broad ancestors without chmod: only the leaf secret directory must
@@ -145,16 +149,18 @@ export function removePrivateState(kind, key) {
145
149
 
146
150
  // ─── Keyring via secret-tool (libsecret, same backend as Go's go-keyring) ───
147
151
 
148
- function keyringLookup(key) {
152
+ function keyringLookup(key, legacyKey) {
149
153
  try {
150
154
  // execFileSync with an arg array — no shell, so `key` can never
151
155
  // break out into command injection (issue #143 finding #2).
152
- const result = execFileSync(
156
+ const result = process.platform === 'win32'
157
+ ? (windowsCredentialOperation('read', key) ?? (legacyKey ? windowsCredentialOperation('read', legacyKey) : null))
158
+ : execFileSync(
153
159
  'secret-tool',
154
160
  ['lookup', KEYRING_ATTR_SERVICE, KEYRING_SERVICE, KEYRING_ATTR_USERNAME, key],
155
161
  { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf-8' }
156
162
  );
157
- const trimmed = result.trim();
163
+ const trimmed = result?.trim();
158
164
  if (!trimmed) return null;
159
165
  const parsed = JSON.parse(trimmed);
160
166
  // Spread all fields from keyring first, then normalize known fields
@@ -168,7 +174,10 @@ function keyringLookup(key) {
168
174
  created_at: parsed.created_at || parsed.CreatedAt || 0,
169
175
  auth_source: parsed.auth_method === 'gck' ? 'gck' : 'keyring',
170
176
  };
171
- } catch {
177
+ } catch (error) {
178
+ if (process.platform === 'win32' && !plaintextAllowed()) {
179
+ throw error.code === 'credential_storage_error' ? error : refusal();
180
+ }
172
181
  return null;
173
182
  }
174
183
  }
@@ -188,6 +197,12 @@ function keyringStore(key, creds) {
188
197
  }
189
198
 
190
199
  function storeVerified(key, creds) {
200
+ if (process.platform === 'win32') {
201
+ const value = JSON.stringify(creds);
202
+ windowsCredentialOperation('write', key, value);
203
+ const readback = windowsCredentialOperation('read', key);
204
+ return isDeepStrictEqual(JSON.parse(readback), JSON.parse(value));
205
+ }
191
206
  if (!keyringStore(key, creds)) return false;
192
207
  try {
193
208
  const value = execFileSync('secret-tool',
@@ -198,6 +213,11 @@ function storeVerified(key, creds) {
198
213
  }
199
214
 
200
215
  function keyringDelete(key) {
216
+ if (process.platform === 'win32') {
217
+ windowsCredentialOperation('delete', key);
218
+ if (windowsCredentialOperation('read', key) !== null) throw refusal();
219
+ return;
220
+ }
201
221
  try {
202
222
  execFileSync(
203
223
  'secret-tool',
@@ -219,7 +239,7 @@ function keyringDelete(key) {
219
239
  export function loadCredentials(instance, username, injectedStore) {
220
240
  if (injectedStore) return injectedStore.load(instance, username);
221
241
  const key = username ? credKey(instance, username) : credKey(instance);
222
- const keyringCreds = keyringLookup(key);
242
+ const keyringCreds = keyringLookup(key, !username ? legacyWindowsKey(instance) : undefined);
223
243
  if (keyringCreds) {
224
244
  return {
225
245
  ...keyringCreds,
@@ -248,12 +268,16 @@ export function saveCredentials(instance, creds, username, injectedStore) {
248
268
  const key = username ? credKey(instance, username) : credKey(instance);
249
269
  // Stamp last_seen on every credential save
250
270
  creds.last_seen = creds.last_seen || Math.floor(Date.now() / 1000);
251
- if (storeVerified(key, creds)) {
271
+ let verified = false;
272
+ let secureFailure;
273
+ try { verified = storeVerified(key, creds); }
274
+ catch (error) { secureFailure = error.code === 'credential_storage_error' ? error : refusal(); }
275
+ if (verified) {
252
276
  // Retire only this identity, and only after exact secure-store readback.
253
277
  removePrivateState('credentials', key);
254
278
  return;
255
279
  }
256
- if (!plaintextAllowed()) throw refusal();
280
+ if (!plaintextAllowed()) throw secureFailure || refusal();
257
281
  warnPlaintext();
258
282
  writePrivateState('credentials', key, creds);
259
283
  }
@@ -265,6 +289,7 @@ export function deleteCredentials(instance, username, injectedStore) {
265
289
  if (injectedStore) return injectedStore.delete(instance, username);
266
290
  const key = username ? credKey(instance, username) : credKey(instance);
267
291
  keyringDelete(key);
292
+ if (process.platform === 'win32' && !username) keyringDelete(legacyWindowsKey(instance));
268
293
  removePrivateState('credentials', key);
269
294
  }
270
295
 
@@ -0,0 +1,85 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const helper = fileURLToPath(new URL('./windows-credential-store.ps1', import.meta.url));
6
+ const reasons = {
7
+ unsupported: 'Windows PowerShell 5.1 or PowerShell 7+ on Windows is required.',
8
+ capability: 'PowerShell FullLanguage, Add-Type and the Windows Credential Manager native API must be permitted by system policy.',
9
+ policy: 'PowerShell execution policy explicitly restricts embedded credential operations. Ask your administrator for an approved storage route; no alternate host or plaintext fallback is selected automatically.',
10
+ oversized: 'Credential exceeds the Windows Credential Manager single-entry limit (2560 UTF-8 bytes); existing credentials were not replaced.',
11
+ native: 'Windows Credential Manager operation failed; check vault access and system policy.',
12
+ };
13
+ const stages = new Set([
14
+ 'host_check', 'language_mode', 'machine_policy_query', 'user_policy_query',
15
+ 'process_policy_query', 'current_user_policy_query', 'local_machine_policy_query',
16
+ 'input_encoding', 'output_encoding', 'native_compilation', 'request_decode',
17
+ 'native_read', 'native_write', 'native_delete',
18
+ ]);
19
+ function failure(reason, stage) {
20
+ const safeStage = stages.has(stage) ? stage : undefined;
21
+ const diagnostic = safeStage ? ` Stage: ${safeStage}.` : '';
22
+ const error = new Error(`Secure credential storage unavailable or readback failed. ${reason}${diagnostic} Existing plaintext credentials are preserved. No plaintext fallback is enabled automatically.`);
23
+ error.code = 'credential_storage_error';
24
+ if (safeStage) error.storageStage = safeStage;
25
+ return error;
26
+ }
27
+
28
+ // A process boundary injectable for offline tests; production never accepts a
29
+ // script/executable override from configuration or credential content.
30
+ export function windowsCredentialOperation(operation, key, value, run = execFileSync) {
31
+ if (!['read', 'write', 'delete'].includes(operation)) throw failure(reasons.native);
32
+ if (operation === 'write' && Buffer.byteLength(value, 'utf8') > 2560) throw failure(reasons.oversized);
33
+ const input = JSON.stringify({ operation, target: `servicenow-cli:${key}`, username: key, value });
34
+ let command;
35
+ try {
36
+ // Trusted installed code only. Command text is identical for every request;
37
+ // neither request data nor a caller-supplied script path enters the source.
38
+ // EncodedCommand is UTF-16LE on both supported PowerShell hosts.
39
+ command = Buffer.from(readFileSync(helper, 'utf8'), 'utf16le').toString('base64');
40
+ } catch { throw failure(reasons.capability); }
41
+ for (const executable of ['powershell.exe', 'pwsh.exe']) {
42
+ const env = { ...process.env };
43
+ if (executable === 'powershell.exe') {
44
+ // PS7 normalizes PSModulePath only for a directly launched PS5.1 child,
45
+ // not PS7 -> Node -> PS5.1. Let Windows PowerShell construct its own
46
+ // default module paths instead of autoloading incompatible PS7 modules.
47
+ // Preserve every other variable, including execution-policy preferences.
48
+ for (const key of Object.keys(env)) if (key.toUpperCase() === 'PSMODULEPATH') delete env[key];
49
+ }
50
+ let output;
51
+ try {
52
+ output = run(executable, ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', command], {
53
+ input, env, encoding: 'utf8', timeout: 20000, maxBuffer: 1024 * 1024,
54
+ windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'],
55
+ });
56
+ } catch (error) {
57
+ // Never expose child stdout/stderr, exception message or input. In
58
+ // particular policy/parser errors can quote the source or request.
59
+ if (error.code === 'ENOENT') continue;
60
+ throw failure(reasons.capability);
61
+ }
62
+ let response;
63
+ try { response = JSON.parse(output.replace(/^\uFEFF/, '')); }
64
+ catch { throw failure(reasons.capability); }
65
+ // Only an explicit unsupported host/version (or ENOENT above) permits
66
+ // discovery of another host. Never retry policy/capability/native denial.
67
+ if (response?.status === 'error' && response.reason === 'unsupported') continue;
68
+ if (response?.status === 'missing' && operation !== 'write') return null;
69
+ if (response?.status !== 'ok') throw failure(reasons[response?.reason] || reasons.native, response?.stage);
70
+ if (operation === 'read') {
71
+ if (typeof response.value !== 'string') throw failure(reasons.native);
72
+ return response.value;
73
+ }
74
+ return true;
75
+ }
76
+ throw failure(reasons.unsupported);
77
+ }
78
+
79
+ // Go v1 used normalizeURL(instance), not the sanitized file name. Only
80
+ // username-less legacy profiles may consult that identity: never borrow an
81
+ // instance-wide credential for a different named account.
82
+ export function legacyWindowsKey(instance) {
83
+ const trimmed = instance.replace(/\/$/, '');
84
+ return /^https?:\/\//.test(trimmed) ? trimmed : `https://${trimmed}`;
85
+ }
@@ -0,0 +1,163 @@
1
+ # Static command text: all request data (including secrets) arrives on stdin.
2
+ # See GLOSSARY.md, Windows credential helper, for the policy contract.
3
+ $ErrorActionPreference = 'Stop'
4
+ $ProgressPreference = 'SilentlyContinue'
5
+ $stage = 'host_check'
6
+ function Reply($status, $reason, $value) {
7
+ # Stage is assigned only from literals below; never emit exception/source,
8
+ # compiler diagnostics, paths, request data or environment values.
9
+ $result = @{ status = $status; reason = $reason; value = $value; stage = $stage }
10
+ [Console]::Out.Write(($result | ConvertTo-Json -Compress))
11
+ }
12
+ try {
13
+ if ($PSVersionTable.PSVersion -lt [Version]'5.1' -or
14
+ ($PSVersionTable.PSEdition -eq 'Core' -and $PSVersionTable.PSVersion.Major -lt 7) -or
15
+ [Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) {
16
+ Reply 'error' 'unsupported' $null
17
+ exit 0
18
+ }
19
+ $stage = 'language_mode'
20
+ if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') {
21
+ Reply 'error' 'capability' $null
22
+ exit 0
23
+ }
24
+ # Restricted with all scopes Undefined is the stock Windows client default:
25
+ # it permits individual command text, unlike -File. Never modify any scope.
26
+ # Refuse ALL explicitly configured enterprise policy, including RemoteSigned:
27
+ # embedded text cannot establish the original script's zone/signature status.
28
+ foreach ($scope in @('MachinePolicy', 'UserPolicy')) {
29
+ $stage = if ($scope -eq 'MachinePolicy') { 'machine_policy_query' } else { 'user_policy_query' }
30
+ $policy = [string](Microsoft.PowerShell.Security\Get-ExecutionPolicy -Scope $scope -ErrorAction Stop)
31
+ if ($policy -ne 'Undefined') {
32
+ Reply 'error' 'policy' $null
33
+ exit 0
34
+ }
35
+ }
36
+ # Also honor explicit local/session Restricted or AllSigned. Fail closed on
37
+ # unknown policy values. No Set-ExecutionPolicy, environment or registry writes.
38
+ foreach ($scope in @('Process', 'CurrentUser', 'LocalMachine')) {
39
+ $stage = switch ($scope) {
40
+ 'Process' { 'process_policy_query' }
41
+ 'CurrentUser' { 'current_user_policy_query' }
42
+ 'LocalMachine' { 'local_machine_policy_query' }
43
+ }
44
+ $policy = [string](Microsoft.PowerShell.Security\Get-ExecutionPolicy -Scope $scope -ErrorAction Stop)
45
+ if ($policy -notin @('Undefined', 'RemoteSigned', 'Unrestricted', 'Bypass')) {
46
+ Reply 'error' 'policy' $null
47
+ exit 0
48
+ }
49
+ }
50
+ $stage = 'input_encoding'
51
+ [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
52
+ $stage = 'output_encoding'
53
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
54
+ $stage = 'native_compilation'
55
+ Add-Type -TypeDefinition @'
56
+ using System;
57
+ using System.Runtime.InteropServices;
58
+ using System.Text;
59
+ public static class JsnCredentialNative {
60
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
61
+ public struct Credential {
62
+ public uint Flags;
63
+ public uint Type;
64
+ public string TargetName;
65
+ public string Comment;
66
+ public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
67
+ public uint CredentialBlobSize;
68
+ public IntPtr CredentialBlob;
69
+ public uint Persist;
70
+ public uint AttributeCount;
71
+ public IntPtr Attributes;
72
+ public string TargetAlias;
73
+ public string UserName;
74
+ }
75
+ [DllImport("advapi32.dll", EntryPoint="CredReadW", CharSet=CharSet.Unicode, SetLastError=true)]
76
+ private static extern bool NativeRead(string target, uint type, uint flags, out IntPtr credential);
77
+ [DllImport("advapi32.dll", EntryPoint="CredWriteW", CharSet=CharSet.Unicode, SetLastError=true)]
78
+ public static extern bool Write(ref Credential credential, uint flags);
79
+ [DllImport("advapi32.dll", EntryPoint="CredDeleteW", CharSet=CharSet.Unicode, SetLastError=true)]
80
+ private static extern bool NativeDelete(string target, uint type, uint flags);
81
+ [DllImport("advapi32.dll", EntryPoint="CredFree")]
82
+ public static extern void Free(IntPtr credential);
83
+ public class ReadResult {
84
+ public int Error;
85
+ public string Value;
86
+ }
87
+ public static ReadResult ReadCredential(string target) {
88
+ IntPtr pointer;
89
+ bool success = NativeRead(target, 1, 0, out pointer);
90
+ int error = Marshal.GetLastWin32Error();
91
+ if (!success) return new ReadResult { Error = error };
92
+ try { return new ReadResult { Error = 0, Value = ReadValue(pointer) }; }
93
+ finally { Free(pointer); }
94
+ }
95
+ public static int DeleteCredential(string target) {
96
+ bool success = NativeDelete(target, 1, 0);
97
+ int error = Marshal.GetLastWin32Error();
98
+ return success ? 0 : error;
99
+ }
100
+ private static string ReadValue(IntPtr pointer) {
101
+ Credential c = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential));
102
+ byte[] bytes = new byte[c.CredentialBlobSize];
103
+ Marshal.Copy(c.CredentialBlob, bytes, 0, bytes.Length);
104
+ return new UTF8Encoding(false, true).GetString(bytes);
105
+ }
106
+ public static bool WriteValue(string target, string username, string value) {
107
+ byte[] bytes = new UTF8Encoding(false, true).GetBytes(value);
108
+ if (bytes.Length > 2560) throw new ArgumentException();
109
+ IntPtr pointer = Marshal.AllocHGlobal(bytes.Length);
110
+ try {
111
+ Marshal.Copy(bytes, 0, pointer, bytes.Length);
112
+ Credential c = new Credential();
113
+ c.Type = 1; c.TargetName = target; c.UserName = username;
114
+ c.Persist = 2; c.CredentialBlobSize = (uint)bytes.Length; c.CredentialBlob = pointer;
115
+ return Write(ref c, 0);
116
+ } finally {
117
+ for (int i = 0; i < bytes.Length; i++) Marshal.WriteByte(pointer, i, 0);
118
+ Marshal.FreeHGlobal(pointer);
119
+ Array.Clear(bytes, 0, bytes.Length);
120
+ }
121
+ }
122
+ }
123
+ '@
124
+ } catch {
125
+ Reply 'error' 'capability' $null
126
+ exit 0
127
+ }
128
+ try {
129
+ $stage = 'request_decode'
130
+ $request = [Console]::In.ReadToEnd() | ConvertFrom-Json
131
+ if ($request.target -isnot [string] -or !$request.target.StartsWith('servicenow-cli:') -or
132
+ $request.target.Length -gt 32767 -or $request.target.Contains([char]0)) {
133
+ Reply 'error' 'native' $null
134
+ exit 0
135
+ }
136
+ switch ($request.operation) {
137
+ 'write' {
138
+ $stage = 'native_write'
139
+ if ($request.value -isnot [string] -or [Text.Encoding]::UTF8.GetByteCount($request.value) -gt 2560) {
140
+ Reply 'error' 'oversized' $null
141
+ } elseif ([JsnCredentialNative]::WriteValue($request.target, $request.username, $request.value)) {
142
+ Reply 'ok' $null $null
143
+ } else { Reply 'error' 'native' $null }
144
+ }
145
+ 'read' {
146
+ $stage = 'native_read'
147
+ $result = [JsnCredentialNative]::ReadCredential($request.target)
148
+ if ($result.Error -eq 0) { Reply 'ok' $null $result.Value }
149
+ elseif ($result.Error -eq 1168) { Reply 'missing' $null $null }
150
+ else { Reply 'error' 'native' $null }
151
+ }
152
+ 'delete' {
153
+ $stage = 'native_delete'
154
+ $errorCode = [JsnCredentialNative]::DeleteCredential($request.target)
155
+ if ($errorCode -eq 0) { Reply 'ok' $null $null }
156
+ elseif ($errorCode -eq 1168) { Reply 'missing' $null $null }
157
+ else { Reply 'error' 'native' $null }
158
+ }
159
+ default { Reply 'error' 'native' $null }
160
+ }
161
+ } catch {
162
+ Reply 'error' 'native' $null
163
+ }
@@ -0,0 +1,13 @@
1
+ // Ordered results with at most four independent reads in flight. Callers must
2
+ // finish dependency discovery before scheduling; this helper never retries.
3
+ export async function boundedReads(items, read) {
4
+ const results = new Array(items.length);
5
+ let next = 0;
6
+ await Promise.all(Array.from({ length: Math.min(4, items.length) }, async () => {
7
+ while (next < items.length) {
8
+ const index = next++;
9
+ results[index] = await read(items[index], index);
10
+ }
11
+ }));
12
+ return results;
13
+ }
@@ -8,6 +8,11 @@
8
8
  // // Subcommand verbs that mutate instance state. The mutation guard
9
9
  // // (src/mutations.js) derives its command-path list from these.
10
10
  // mutationSubcommands: ['create', 'update', 'delete'],
11
+ // // Omitted means conservative customization; operational skips capture
12
+ // // requirements, table follows sys_db_object ancestry to sys_metadata.
13
+ // mutationContext: 'table', table: 'sys_script',
14
+ // // Only declared flags are transaction overrides, not creation fields.
15
+ // transactionScopeOption: 'scope',
11
16
  // // Command runs without a configured instance (joins the middleware
12
17
  // // skip-list for the instance guard).
13
18
  // noInstance: true,
@@ -31,9 +36,9 @@
31
36
  // Note: yargs strips custom properties off command modules when it
32
37
  // registers them (only original/description/handler/builder survive in
33
38
  // getCommandHandlers()), so declarations live in this module-level map,
34
- // keyed by root command name. Declaration happens when the command module
35
- // factory runs — i.e. during cli.js's registration chain — so the registry
36
- // is complete once buildCLI() returns.
39
+ // keyed by root command name. Eager factories declare during registration;
40
+ // lazy families declare in command-families.js, never in a deferred factory.
41
+ // The registry is complete once buildCLI() returns, before path resolution.
37
42
 
38
43
  const REGISTRY = new Map();
39
44
 
@@ -1,6 +1,7 @@
1
1
  import { parseArgs } from 'node:util';
2
2
  import process from 'node:process';
3
3
  import { renderSubcommandHelp } from './help.js';
4
+ import { resolveDocLink } from './docs-links.js';
4
5
 
5
6
  const camel = (name) => name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
6
7
  const names = (x) => typeof x === 'string' ? [x] : (x || []);
@@ -37,6 +38,12 @@ class CommandNode {
37
38
 
38
39
  build() {
39
40
  if (this.built) return;
41
+ if (this.definition.load) {
42
+ const definition = this.definition.load();
43
+ // Root identity is lightweight and authoritative. Implementations only
44
+ // supply builders/handlers; loading must not change token ownership.
45
+ this.definition = { ...definition, ...this.definition, load: undefined };
46
+ }
40
47
  this.built = true;
41
48
  if (typeof this.definition.builder === 'function') this.definition.builder(this.api());
42
49
  }
@@ -292,10 +299,10 @@ export class LocalCLI {
292
299
  * help page. Machine discovery leaves it out, so the JSON schema and bytes
293
300
  * stay unchanged.
294
301
  */
295
- commandRegistry({ summaries = false } = {}) {
302
+ commandRegistry({ summaries = false, shallow = false } = {}) {
296
303
  const visible = (node) => !node.definition.hidden;
297
304
  const serialize = (node) => {
298
- node.build();
305
+ if (!shallow) node.build();
299
306
  const entry = {
300
307
  name: node.name,
301
308
  command: node.definition.command || node.name,
@@ -398,9 +405,25 @@ export class LocalCLI {
398
405
  description: node.definition.describe,
399
406
  commands,
400
407
  options: this._optionRows(node),
401
- epilogue: node.epilogueText,
408
+ epilogue: this._docsEpilogue(node, path),
402
409
  }));
403
410
  }
411
+
412
+ /**
413
+ * Every help page names the maintained documentation for its command family.
414
+ * The family comes from the parser's canonical resolved path, so aliases
415
+ * (`jsn flow`) and nested commands (`jsn records list`) reach the same
416
+ * registered topic without a per-subcommand footer. A page whose authored
417
+ * epilogue already prints that URL keeps its own wording rather than repeating
418
+ * it, and a family with no migrated guide gains no invented URL.
419
+ */
420
+ _docsEpilogue(node, path) {
421
+ const base = node.epilogueText;
422
+ const link = path.length ? resolveDocLink(path[0]) : null;
423
+ if (!link || (base && base.includes(link))) return base;
424
+ const line = `Documentation: ${link}`;
425
+ return base ? `${base}\n${line}` : line;
426
+ }
404
427
  async parse() {
405
428
  // Reject stale installed shell snippets instead of dispatching their words
406
429
  // as ordinary commands (for example the `r` alias).