@jacebenson/jsn 5.5.6 → 5.5.7-dev.212.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 (43) hide show
  1. package/README.md +16 -1
  2. package/package.json +9 -8
  3. package/src/amb.js +15 -0
  4. package/src/app.js +4 -15
  5. package/src/auth/credential-store.js +131 -32
  6. package/src/auth/oauth.js +4 -28
  7. package/src/auth/transport.js +22 -0
  8. package/src/auth.js +23 -2
  9. package/src/cli-adapter.js +18 -1
  10. package/src/cli.js +0 -3
  11. package/src/commands/auth.js +21 -5
  12. package/src/commands/codesearch.js +11 -2
  13. package/src/commands/docs/community.js +1 -1
  14. package/src/commands/docs/db.js +38 -4
  15. package/src/commands/docs/docs.js +14 -13
  16. package/src/commands/docs/index.js +2 -1
  17. package/src/commands/docs/refresh.js +2 -1
  18. package/src/commands/docs/releases.js +1 -1
  19. package/src/commands/docs/replace.js +1 -1
  20. package/src/commands/docs/service-snapshot.js +1 -1
  21. package/src/commands/docs/snapshot.js +2 -1
  22. package/src/commands/docs/sync-service.js +5 -3
  23. package/src/commands/flows.js +7 -2
  24. package/src/commands/setup.js +28 -31
  25. package/src/commands/skill.js +3 -8
  26. package/src/commands/version.js +5 -1
  27. package/src/config.js +93 -18
  28. package/src/docs-links.js +28 -0
  29. package/src/help.js +4 -0
  30. package/src/midserver-install.js +3 -0
  31. package/src/paginated-search.js +146 -178
  32. package/src/perf.js +1 -1
  33. package/src/prompt-engine.js +169 -0
  34. package/src/prompts.js +304 -42
  35. package/src/sdk.js +10 -44
  36. package/src/session.js +6 -1
  37. package/src/sqlite.js +94 -0
  38. package/src/commands/docs/public/index.html +0 -178
  39. package/src/commands/docs/public/vendor/marked.min.js +0 -69
  40. package/src/commands/docs/public/vendor/purify.min.js +0 -3
  41. package/src/commands/docs/serve.js +0 -287
  42. package/src/commands/history.js +0 -57
  43. package/src/mutation-history.js +0 -75
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.6",
3
+ "version": "5.5.7-dev.212.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,9 +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
- "better-sqlite3": "^13.2.0",
29
27
  "commonmark": "^0.31.2",
30
28
  "js-yaml": "^5.5.0",
31
29
  "saxes": "^6.0.0",
@@ -33,7 +31,7 @@
33
31
  },
34
32
  "devDependencies": {
35
33
  "@eslint/js": "^10.0.1",
36
- "@stryker-mutator/core": "^10.0.0",
34
+ "eslint": "^10.15.0",
37
35
  "globals": "^17.6.0"
38
36
  },
39
37
  "files": [
@@ -42,5 +40,8 @@
42
40
  "skills/",
43
41
  "README.md",
44
42
  "LICENSE"
45
- ]
43
+ ],
44
+ "engines": {
45
+ "node": ">=24.0.0"
46
+ }
46
47
  }
package/src/amb.js CHANGED
@@ -20,6 +20,7 @@
20
20
  // src/record-watch.js.
21
21
 
22
22
  import { AppError, CodeAPI, CodeAuth, CodeNetwork, CodeUsage } from './errors.js';
23
+ import { assertCredentialTransport, assertCredentialDestination } from './auth/transport.js';
23
24
 
24
25
  const BAYEUX_VERSION = '1.0';
25
26
  const DEFAULT_CONNECT_TIMEOUT = 60000;
@@ -164,8 +165,10 @@ export class AmbClient {
164
165
  if (!baseUrl) throw new AmbError(CodeUsage, 'AMB needs an instance URL.');
165
166
  if (typeof session !== 'function') throw new AmbError(CodeUsage, 'AMB needs a session provider.');
166
167
  this.baseUrl = String(baseUrl).replace(/\/$/, '');
168
+ this.instanceOrigin = assertCredentialTransport(this.baseUrl).origin;
167
169
  this.session = session;
168
170
  this.fetchImpl = fetchImpl;
171
+ if (/^[a-z][a-z\d+.-]*:/i.test(path)) throw ambAuthError('AMB path must be an instance-local route');
169
172
  this.path = path.startsWith('/') ? path : `/${path}`;
170
173
  this.connectTimeoutMs = connectTimeoutMs;
171
174
  this.requestTimeoutMs = requestTimeoutMs;
@@ -180,6 +183,7 @@ export class AmbClient {
180
183
  async _send(messages, { op, timeoutMs, signal }) {
181
184
  const endpoint = op === 'handshake' ? 'handshake' : 'connect';
182
185
  const url = `${this.baseUrl}${this.path}/${endpoint}`;
186
+ this._validateDestination(url);
183
187
  const headers = { Accept: 'application/json', 'Content-Type': 'application/json' };
184
188
  const cookies = serializeCookies(this.cookieJar);
185
189
  if (cookies) headers.Cookie = cookies;
@@ -195,6 +199,7 @@ export class AmbClient {
195
199
  }
196
200
  try {
197
201
  const response = await this.fetchImpl(url, {
202
+ redirect: 'error',
198
203
  method: 'POST',
199
204
  headers,
200
205
  body: JSON.stringify(messages),
@@ -282,6 +287,7 @@ export class AmbClient {
282
287
  * delivery, and the gap is reported by the caller.
283
288
  */
284
289
  async start(channels = []) {
290
+ this._validateDestination(`${this.baseUrl}${this.path}/handshake`);
285
291
  const session = await this.session();
286
292
  if (!session?.cookies) {
287
293
  throw ambAuthError('AMB needs a browser session and the active profile has none.',
@@ -318,6 +324,15 @@ export class AmbClient {
318
324
  return { clientId: this.clientId, sessionStatus: this.sessionStatus, channels: [...channels] };
319
325
  }
320
326
 
327
+ _validateDestination(url) {
328
+ // AMB paths are local routes, never URL references. Reject ambiguous
329
+ // authority/backslash/query forms before asking the session for secrets.
330
+ if (!this.path.startsWith('/') || this.path.startsWith('//') || /[\\?#]/.test(this.path)) {
331
+ throw ambAuthError('AMB path must be an instance-local route');
332
+ }
333
+ assertCredentialDestination(url, this.instanceOrigin);
334
+ }
335
+
321
336
  /**
322
337
  * One long-poll: returns the non-meta Bayeux messages it received. A local
323
338
  * timeout returns an empty array (the loop just polls again) unless the
package/src/app.js CHANGED
@@ -7,12 +7,11 @@
7
7
  // setEffectiveInstance() are thin session-backed shims kept for the many
8
8
  // command handlers that already call them.
9
9
 
10
- import { appendMutation } from './mutation-history.js';
11
10
  import { AuthManager } from './auth.js';
12
11
  import { createAuthRecovery } from './auth-recovery.js';
13
12
  import { SDKClient } from './sdk.js';
14
13
  import { OutputWriter, FormatAuto, FormatJSON, FormatMarkdown, FormatQuiet, FormatStyled, hyperlink } from './output.js';
15
- import { saveConfig } from './config.js';
14
+ import { saveConfig, isTrustedCredentialDestination } from './config.js';
16
15
  import { resolveSession, applySession, contextFromSession, requireSessionInstance } from './session.js';
17
16
  import { getCurrentUser, getCurrentApplication, getCurrentUpdateSet } from './context.js';
18
17
  import { errUsage, errAuth } from './errors.js';
@@ -43,6 +42,9 @@ export class App {
43
42
  getUsername: () => this.session?.username || null,
44
43
  getEffectiveInstance: () => this.session?.instance || '',
45
44
  getAuthMethod: () => this.session?.profile?.auth_method || null,
45
+ isTrustedCredentialDestination: instance => isTrustedCredentialDestination(this.config, instance,
46
+ this._authArgv?.instance || this._sessionArgv?.instance || (this.session?.profileExplicit ? '' : this.session?.override),
47
+ this.session?.profileExplicit ? this.session.profileName : ''),
46
48
  });
47
49
 
48
50
  if (this.session.instance) {
@@ -62,7 +64,6 @@ export class App {
62
64
  includeReferenceLinks: this._authArgv?.includeReferenceLinks === true,
63
65
  username: session?.username || '',
64
66
  recovery: createAuthRecovery({ app: this, session }),
65
- onMutation: event => this.recordMutation(instance, session?.profileName, event),
66
67
  canInteract: () => canUsePicker(this, this._authArgv || {}),
67
68
  });
68
69
  }
@@ -73,22 +74,10 @@ export class App {
73
74
  return new SDKClient(instance, this.auth.createProfileProvider(instance, options), {
74
75
  domain: options.domain ?? profile.domain ?? '',
75
76
  username: options.username || '',
76
- onMutation: event => this.recordMutation(instance, options.profileName || null, event),
77
77
  canInteract: () => canUsePicker(this, this._authArgv || {}),
78
78
  });
79
79
  }
80
80
 
81
- recordMutation(instance, profile, event) {
82
- if (!this._authArgv) return;
83
- try { appendMutation({ ...event, instance, profile, reason: this._authArgv.reason }); }
84
- catch {
85
- if (!this._historyWarningShown) {
86
- process.stderr.write('Warning: local mutation history could not be saved. The remote result is unchanged.\n');
87
- this._historyWarningShown = true;
88
- }
89
- }
90
- }
91
-
92
81
  loadContext() {
93
82
  this.context = contextFromSession(this.session, this.config);
94
83
  }
@@ -1,5 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { isDeepStrictEqual } from 'node:util';
3
5
  import { execFileSync } from 'node:child_process';
4
6
  import { globalConfigDir } from '../config.js';
5
7
 
@@ -35,17 +37,110 @@ const KEYRING_SERVICE = 'servicenow-cli';
35
37
  const KEYRING_ATTR_SERVICE = 'service';
36
38
  const KEYRING_ATTR_USERNAME = 'username';
37
39
 
38
- function credentialsFilePath(key) {
39
- const dir = path.join(globalConfigDir(), 'credentials');
40
- // Match Go's filename encoding: replace :// and / and : with _
41
- const filename = key + '.json';
42
- return path.join(dir, filename);
40
+ // Only this process environment can authorize portable plaintext storage.
41
+ const PLAINTEXT_ENV = 'JSN_ALLOW_PLAINTEXT_CREDENTIAL_STORAGE';
42
+ function plaintextAllowed() { return process.env[PLAINTEXT_ENV] === '1'; }
43
+ function storageError(message) {
44
+ const error = new Error(message);
45
+ error.code = 'credential_storage_error';
46
+ return error;
47
+ }
48
+ let plaintextWarningShown = false;
49
+ function warnPlaintext() {
50
+ if (plaintextWarningShown) return;
51
+ plaintextWarningShown = true;
52
+ process.stderr.write('Warning: plaintext credential storage explicitly enabled for this process; credentials are portable and backups can expose them.\n');
53
+ }
54
+ 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.`);
43
56
  }
44
57
 
45
- function credentialsPath(key) {
46
- const filePath = credentialsFilePath(key);
47
- fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
48
- return filePath;
58
+ // Validate broad ancestors without chmod: only the leaf secret directory must
59
+ // be private. Root-owned sticky temporary ancestors are permitted, not leaves.
60
+ function checkPath(target, directory, privateMode = false) {
61
+ const stat = fs.lstatSync(target);
62
+ // Windows stat mode/uid fields do not describe DACL access. Retain type,
63
+ // symlink/junction and hardlink checks there; do not claim POSIX privacy.
64
+ // Windows files inherit their parent's ACL; see the documented storage policy.
65
+ const posix = process.platform !== 'win32';
66
+ const uid = posix ? process.getuid?.() : undefined;
67
+ if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()) ||
68
+ (uid !== undefined && stat.uid !== uid && !(directory && !privateMode && stat.uid === 0)) ||
69
+ (!directory && stat.nlink !== 1) ||
70
+ (posix && (privateMode ? (stat.mode & 0o7777) !== (directory ? 0o700 : 0o600) :
71
+ ((stat.mode & 0o022) !== 0 && !(directory && stat.uid === 0 && (stat.mode & 0o1000)))))) {
72
+ throw storageError(posix
73
+ ? 'Unsafe credential/PKCE path: require owned regular 0600 files and private 0700 secret directories; reject symlinks, links and writable ancestors. Repair or move the path manually, then retry.'
74
+ : 'Unsafe credential/PKCE path: require regular files/directories without symlinks, junctions or hard links. Windows ACL privacy must be managed separately.');
75
+ }
76
+ return stat;
77
+ }
78
+ // Enumerate below the parsed root: a drive/UNC prefix is not a component.
79
+ export function privateStateDirectories(dir, pathAPI = path) {
80
+ const root = pathAPI.parse(dir).root;
81
+ let current = root;
82
+ return dir.slice(root.length).split(pathAPI.sep).filter(Boolean).map(part => {
83
+ current = pathAPI.join(current, part);
84
+ return current;
85
+ });
86
+ }
87
+ function privateStatePath(kind, key, create = false) {
88
+ if (!['credentials', 'pkce'].includes(kind) || !/^[a-zA-Z0-9._@-]+$/.test(key) || key === '.' || key === '..') {
89
+ throw storageError('Invalid credential/PKCE storage key.');
90
+ }
91
+ // Resolve once so traversal, leaf comparison and IO share the same path,
92
+ // including when the configured XDG directory is relative.
93
+ const dir = path.resolve(globalConfigDir(), kind);
94
+ for (const current of privateStateDirectories(dir)) {
95
+ try { checkPath(current, true, current === dir); }
96
+ catch (error) {
97
+ if (error.code !== 'ENOENT') throw error;
98
+ if (!create) return path.join(dir, key + '.json');
99
+ fs.mkdirSync(current, { mode: 0o700 });
100
+ checkPath(current, true, current === dir);
101
+ }
102
+ }
103
+ const file = path.join(dir, key + '.json');
104
+ try { checkPath(file, false, true); }
105
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
106
+ return file;
107
+ }
108
+ export function readPrivateState(kind, key) {
109
+ const file = privateStatePath(kind, key);
110
+ let fd;
111
+ try {
112
+ fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
113
+ const before = checkPath(file, false, true);
114
+ const opened = fs.fstatSync(fd);
115
+ if (before.ino !== opened.ino || before.dev !== opened.dev) throw storageError('Credential/PKCE path changed while opening.');
116
+ return JSON.parse(fs.readFileSync(fd, 'utf8'));
117
+ } catch (error) {
118
+ if (error.code === 'ENOENT') return null;
119
+ if (error.code === 'credential_storage_error') throw error;
120
+ throw storageError('Unable to read credential/PKCE state safely; original file preserved.');
121
+ } finally { if (fd !== undefined) fs.closeSync(fd); }
122
+ }
123
+ export function writePrivateState(kind, key, value) {
124
+ const file = privateStatePath(kind, key, true);
125
+ const temp = path.join(path.dirname(file), `.pending-${crypto.randomUUID()}`);
126
+ let fd;
127
+ try {
128
+ fd = fs.openSync(temp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
129
+ fs.fchmodSync(fd, 0o600);
130
+ fs.writeFileSync(fd, JSON.stringify(value, null, 2));
131
+ fs.fsyncSync(fd);
132
+ fs.closeSync(fd); fd = undefined;
133
+ privateStatePath(kind, key);
134
+ fs.renameSync(temp, file);
135
+ } finally {
136
+ if (fd !== undefined) fs.closeSync(fd);
137
+ if (fs.existsSync(temp)) fs.unlinkSync(temp);
138
+ }
139
+ }
140
+ export function removePrivateState(kind, key) {
141
+ const file = privateStatePath(kind, key);
142
+ try { fs.unlinkSync(file); }
143
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
49
144
  }
50
145
 
51
146
  // ─── Keyring via secret-tool (libsecret, same backend as Go's go-keyring) ───
@@ -71,9 +166,7 @@ function keyringLookup(key) {
71
166
  refresh_token: parsed.refresh_token || parsed.RefreshToken || '',
72
167
  expires_at: parsed.expires_at || parsed.ExpiresAt || 0,
73
168
  created_at: parsed.created_at || parsed.CreatedAt || 0,
74
- auth_source: ['oauth', 'env_token', 'env_basic', undefined].includes(parsed.auth_source)
75
- ? (parsed.auth_method === 'gck' ? 'gck' : 'keyring')
76
- : parsed.auth_source,
169
+ auth_source: parsed.auth_method === 'gck' ? 'gck' : 'keyring',
77
170
  };
78
171
  } catch {
79
172
  return null;
@@ -94,6 +187,16 @@ function keyringStore(key, creds) {
94
187
  }
95
188
  }
96
189
 
190
+ function storeVerified(key, creds) {
191
+ if (!keyringStore(key, creds)) return false;
192
+ try {
193
+ const value = execFileSync('secret-tool',
194
+ ['lookup', KEYRING_ATTR_SERVICE, KEYRING_SERVICE, KEYRING_ATTR_USERNAME, key],
195
+ { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf8' });
196
+ return isDeepStrictEqual(JSON.parse(value), JSON.parse(JSON.stringify(creds)));
197
+ } catch { return false; }
198
+ }
199
+
97
200
  function keyringDelete(key) {
98
201
  try {
99
202
  execFileSync(
@@ -123,18 +226,14 @@ export function loadCredentials(instance, username, injectedStore) {
123
226
  auth_source: keyringCreds.auth_source || (keyringCreds.auth_method === 'gck' ? 'gck' : 'keyring'),
124
227
  };
125
228
  }
126
- try {
127
- const data = fs.readFileSync(credentialsFilePath(key), 'utf-8');
128
- const creds = JSON.parse(data);
129
- return {
130
- ...creds,
131
- auth_source: ['oauth', 'env_token', 'env_basic', undefined].includes(creds.auth_source)
132
- ? (creds.auth_method === 'gck' ? 'gck' : 'file')
133
- : creds.auth_source,
134
- };
135
- } catch {
136
- return null;
137
- }
229
+ const file = privateStatePath('credentials', key);
230
+ if (!fs.existsSync(file)) return null;
231
+ // Reads (including local status) never persist or migrate credentials. A
232
+ // subsequent explicit login/save or token refresh performs verified retirement.
233
+ if (!plaintextAllowed()) throw refusal();
234
+ warnPlaintext();
235
+ const creds = readPrivateState('credentials', key);
236
+ return creds ? { ...creds, auth_source: 'file' } : null;
138
237
  }
139
238
 
140
239
  /**
@@ -149,10 +248,14 @@ export function saveCredentials(instance, creds, username, injectedStore) {
149
248
  const key = username ? credKey(instance, username) : credKey(instance);
150
249
  // Stamp last_seen on every credential save
151
250
  creds.last_seen = creds.last_seen || Math.floor(Date.now() / 1000);
152
- // Try keyring first, fall back to file
153
- if (!keyringStore(key, creds)) {
154
- fs.writeFileSync(credentialsPath(key), JSON.stringify(creds, null, 2), { mode: 0o600 });
251
+ if (storeVerified(key, creds)) {
252
+ // Retire only this identity, and only after exact secure-store readback.
253
+ removePrivateState('credentials', key);
254
+ return;
155
255
  }
256
+ if (!plaintextAllowed()) throw refusal();
257
+ warnPlaintext();
258
+ writePrivateState('credentials', key, creds);
156
259
  }
157
260
 
158
261
  /**
@@ -162,11 +265,7 @@ export function deleteCredentials(instance, username, injectedStore) {
162
265
  if (injectedStore) return injectedStore.delete(instance, username);
163
266
  const key = username ? credKey(instance, username) : credKey(instance);
164
267
  keyringDelete(key);
165
- try {
166
- fs.unlinkSync(credentialsPath(key));
167
- } catch {
168
- // ignore
169
- }
268
+ removePrivateState('credentials', key);
170
269
  }
171
270
 
172
271
  export const defaultCredentialStore = {
package/src/auth/oauth.js CHANGED
@@ -1,40 +1,16 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
1
  import crypto from 'node:crypto';
4
- import { globalConfigDir } from '../config.js';
5
- import { credKey } from './credential-store.js';
6
-
7
- // ─── PKCE state persistence (shared with Go version) ───
8
-
9
- function pkceStatePath(instance, username) {
10
- const dir = path.join(globalConfigDir(), 'pkce');
11
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
12
- // A known profile identity gets its own pending-login slot. Keep the bare
13
- // instance slot for legacy/no-profile flows, where no identity exists yet.
14
- const filename = credKey(instance, username) + '.json';
15
- return path.join(dir, filename);
16
- }
2
+ import { credKey, writePrivateState, readPrivateState, removePrivateState } from './credential-store.js';
17
3
 
18
4
  export function savePKCEState(instance, pkce, username) {
19
- const filePath = pkceStatePath(instance, username);
20
- fs.writeFileSync(filePath, JSON.stringify(pkce, null, 2), { mode: 0o600 });
5
+ writePrivateState('pkce', credKey(instance, username), pkce);
21
6
  }
22
7
 
23
8
  export function loadPKCEState(instance, username) {
24
- try {
25
- const data = fs.readFileSync(pkceStatePath(instance, username), 'utf-8');
26
- return JSON.parse(data);
27
- } catch {
28
- return null;
29
- }
9
+ return readPrivateState('pkce', credKey(instance, username));
30
10
  }
31
11
 
32
12
  export function removePKCEState(instance, username) {
33
- try {
34
- fs.unlinkSync(pkceStatePath(instance, username));
35
- } catch {
36
- // ignore
37
- }
13
+ removePrivateState('pkce', credKey(instance, username));
38
14
  }
39
15
 
40
16
  const DEFAULT_OAUTH_CLIENT_ID = '543e5655f77746a28228c6009a599dfb';
@@ -0,0 +1,22 @@
1
+ // Credential transport policy. Only process state can enable legacy HTTP;
2
+ // project configuration must never relax this boundary.
3
+ import { errAuth } from '../errors.js';
4
+
5
+ export function assertCredentialTransport(destination) {
6
+ let url;
7
+ try { url = new URL(destination); } catch { throw errAuth('Invalid credential destination'); }
8
+ const hostname = url.hostname.toLowerCase();
9
+ const loopback = hostname === 'localhost' || hostname === '[::1]' || /^127(?:\.\d{1,3}){3}$/.test(hostname);
10
+ if (url.username || url.password || !['http:', 'https:'].includes(url.protocol)) throw errAuth('Invalid credential destination');
11
+ if (url.protocol !== 'https:' && !loopback && process.env.JSN_ALLOW_INSECURE_HTTP !== '1') {
12
+ throw errAuth('HTTPS is required for credential destinations (except loopback development). Set JSN_ALLOW_INSECURE_HTTP=1 in this process only to explicitly allow legacy HTTP.');
13
+ }
14
+ return url;
15
+ }
16
+
17
+ export function assertCredentialDestination(destination, instance) {
18
+ const url = assertCredentialTransport(destination);
19
+ const origin = assertCredentialTransport(instance).origin;
20
+ if (url.origin !== origin) throw errAuth('Refusing to send credentials outside the configured instance origin');
21
+ return url;
22
+ }
package/src/auth.js CHANGED
@@ -6,7 +6,8 @@
6
6
 
7
7
  import fs from 'node:fs';
8
8
  import { password as passwordPrompt } from './prompts.js';
9
- import { normalizeInstanceURL } from './config.js';
9
+ import { normalizeInstanceURL, isTrustedCredentialDestination } from './config.js';
10
+ import { assertCredentialTransport } from './auth/transport.js';
10
11
  import { errAuth } from './errors.js';
11
12
  import { pendingBrowserLogin } from './browser-auth.js';
12
13
  import { defaultCredentialStore } from './auth/credential-store.js';
@@ -86,6 +87,7 @@ export class AuthManager {
86
87
  return (name && cfg.profiles?.[name]?.username) || null;
87
88
  },
88
89
  getEffectiveInstance: () => provider.getEffectiveInstance(),
90
+ isTrustedCredentialDestination: instance => isTrustedCredentialDestination(provider.config, instance),
89
91
  getAuthMethod: () => {
90
92
  const cfg = provider.config;
91
93
  const name = cfg.activeProfile || cfg.defaultProfile;
@@ -323,15 +325,22 @@ export class AuthManager {
323
325
  }
324
326
 
325
327
  getCredentialsFor(instance, username, options = {}) {
328
+ assertCredentialTransport(instance);
326
329
  const method = this._selectedMethod(options);
330
+ const assertAmbientTrust = () => {
331
+ if (this.identity.isTrustedCredentialDestination?.(instance) === false) {
332
+ throw errAuth('Project configuration cannot authorize an ambient credential destination. Select --instance explicitly or save the origin in global configuration.');
333
+ }
334
+ };
327
335
  // With no configured method, preserve the legacy environment precedence:
328
336
  // OAuth token first, then Basic credentials, then stored credentials.
329
337
  if ((method === 'unconfigured' || method === 'oauth') && process.env.SERVICENOW_OAUTH_TOKEN) {
338
+ assertAmbientTrust();
330
339
  return { auth_method: 'oauth', access_token: process.env.SERVICENOW_OAUTH_TOKEN, auth_source: 'env_token' };
331
340
  }
332
341
  if (method === 'unconfigured' || method === 'basic') {
333
342
  const basicCreds = getBasicAuthFromEnv(instance);
334
- if (basicCreds) return basicCreds;
343
+ if (basicCreds) { assertAmbientTrust(); return basicCreds; }
335
344
  }
336
345
  const credentialUsername = Object.hasOwn(options, 'username') ? options.username : (username ?? this._activeUsername());
337
346
  const creds = this.credentialStore.load(instance, credentialUsername);
@@ -355,6 +364,7 @@ export class AuthManager {
355
364
 
356
365
  async login(instanceURL, username = this._activeUsername()) {
357
366
  instanceURL = normalizeInstanceURL(instanceURL);
367
+ assertCredentialTransport(instanceURL);
358
368
  const clientID = getOAuthClientID();
359
369
  const pkce = generatePKCE();
360
370
  const authURL = buildAuthURL(instanceURL, clientID, pkce);
@@ -393,6 +403,7 @@ export class AuthManager {
393
403
  */
394
404
  buildAuthURL(instanceURL, waitFile, username = this._activeUsername()) {
395
405
  instanceURL = normalizeInstanceURL(instanceURL);
406
+ assertCredentialTransport(instanceURL);
396
407
  const clientID = getOAuthClientID();
397
408
  const pkce = generatePKCE();
398
409
  savePKCEState(instanceURL, pkce, username);
@@ -433,7 +444,11 @@ export class AuthManager {
433
444
  */
434
445
  async loginWithPassword(instanceURL, username = this._activeUsername(), suppliedCredentials) {
435
446
  instanceURL = normalizeInstanceURL(instanceURL);
447
+ assertCredentialTransport(instanceURL);
436
448
  const envCreds = getBasicAuthFromEnv(instanceURL);
449
+ if (!suppliedCredentials && envCreds && this.identity.isTrustedCredentialDestination?.(instanceURL) === false) {
450
+ throw errAuth('Project configuration cannot authorize an ambient credential destination. Select --instance explicitly or save the origin in global configuration.');
451
+ }
437
452
  const storedCreds = this.loadCredentials(instanceURL, username);
438
453
  const creds = suppliedCredentials
439
454
  ? { auth_method: 'basic', ...suppliedCredentials }
@@ -464,6 +479,7 @@ export class AuthManager {
464
479
  }
465
480
 
466
481
  async loginWithBrowser(instanceURL, options = {}, username = this._activeUsername()) {
482
+ assertCredentialTransport(normalizeInstanceURL(instanceURL));
467
483
  if (options.launch) {
468
484
  const { launchBrowserSession } = await import('./browser-launch.js');
469
485
  const credentials = await launchBrowserSession(instanceURL, {
@@ -486,6 +502,7 @@ export class AuthManager {
486
502
 
487
503
  async _verifyBrowserSession(instanceURL, creds, username, { requireIdentity = false, signal, timeout = this.httpClient.timeout } = {}) {
488
504
  instanceURL = normalizeInstanceURL(instanceURL);
505
+ assertCredentialTransport(instanceURL);
489
506
  const query = new URLSearchParams({
490
507
  sysparm_limit: '1',
491
508
  sysparm_fields: 'user_name',
@@ -547,6 +564,7 @@ export class AuthManager {
547
564
  }
548
565
 
549
566
  async exchangeCode(instanceURL, clientID, code, pkce) {
567
+ assertCredentialTransport(instanceURL);
550
568
  const tokenURL = `${instanceURL.replace(/\/$/, '')}/oauth_token.do`;
551
569
  const body = new URLSearchParams();
552
570
  body.set('grant_type', 'authorization_code');
@@ -556,6 +574,7 @@ export class AuthManager {
556
574
  body.set('code_verifier', pkce.code_verifier);
557
575
 
558
576
  const resp = await fetch(tokenURL, {
577
+ redirect: 'error',
559
578
  method: 'POST',
560
579
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
561
580
  body: body.toString(),
@@ -580,6 +599,7 @@ export class AuthManager {
580
599
  }
581
600
 
582
601
  async refreshToken(instance, creds, targetUsername = undefined) {
602
+ assertCredentialTransport(instance);
583
603
  if (creds.auth_method !== 'oauth') {
584
604
  throw errAuth(`Cannot refresh ${creds.auth_method || 'unconfigured'} credentials; only OAuth credentials support refresh`);
585
605
  }
@@ -591,6 +611,7 @@ export class AuthManager {
591
611
  body.set('refresh_token', creds.refresh_token);
592
612
 
593
613
  const resp = await fetch(tokenURL, {
614
+ redirect: 'error',
594
615
  method: 'POST',
595
616
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
596
617
  body: body.toString(),
@@ -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 || []);
@@ -398,9 +399,25 @@ export class LocalCLI {
398
399
  description: node.definition.describe,
399
400
  commands,
400
401
  options: this._optionRows(node),
401
- epilogue: node.epilogueText,
402
+ epilogue: this._docsEpilogue(node, path),
402
403
  }));
403
404
  }
405
+
406
+ /**
407
+ * Every help page names the maintained documentation for its command family.
408
+ * The family comes from the parser's canonical resolved path, so aliases
409
+ * (`jsn flow`) and nested commands (`jsn records list`) reach the same
410
+ * registered topic without a per-subcommand footer. A page whose authored
411
+ * epilogue already prints that URL keeps its own wording rather than repeating
412
+ * it, and a family with no migrated guide gains no invented URL.
413
+ */
414
+ _docsEpilogue(node, path) {
415
+ const base = node.epilogueText;
416
+ const link = path.length ? resolveDocLink(path[0]) : null;
417
+ if (!link || (base && base.includes(link))) return base;
418
+ const line = `Documentation: ${link}`;
419
+ return base ? `${base}\n${line}` : line;
420
+ }
404
421
  async parse() {
405
422
  // Reject stale installed shell snippets instead of dispatching their words
406
423
  // as ordinary commands (for example the `r` alias).
package/src/cli.js CHANGED
@@ -80,7 +80,6 @@ import { atfCmd } from './commands/atf.js';
80
80
  import { scanCmd } from './commands/scan.js';
81
81
  import { storeCmd } from './commands/store.js';
82
82
  import { approvalsCmd } from './commands/approvals.js';
83
- import { historyCmd } from './commands/history.js';
84
83
  import { perfCmd } from './commands/perf.js';
85
84
  import { customizationsCmd } from './commands/customizations.js';
86
85
  import { midserversCmd } from './commands/midservers.js';
@@ -155,7 +154,6 @@ export function buildCLI() {
155
154
  ])
156
155
  .options({
157
156
  'all-commands': { type: 'boolean', describe: 'Show the full command list, including admin and developer tools' },
158
- reason: { type: 'string', describe: 'Optional non-sensitive reason saved in local mutation history' },
159
157
 
160
158
  force: {
161
159
  type: 'boolean',
@@ -449,7 +447,6 @@ export function buildCLI() {
449
447
  .command(approvalsCmd(wrap))
450
448
  .command(skippedUpdatesCmd(wrap))
451
449
  .command(perfCmd(wrap))
452
- .command(historyCmd(wrap))
453
450
  .command(customizationsCmd(wrap))
454
451
  .command(midserversCmd(wrap))
455
452
  .command(diffCmd(wrap))