@jacebenson/jsn 5.5.6-dev.208.1 → 5.5.6-dev.210.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.6-dev.208.1",
3
+ "version": "5.5.6-dev.210.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": {
@@ -608,6 +608,18 @@ Find your instance URL in your browser's address bar when logged into ServiceNow
608
608
  }
609
609
  }
610
610
 
611
+ // A profile name selects an account; it does not approve a project-supplied
612
+ // replacement origin. Only a literal destination (also supplied by setup's
613
+ // destination prompt) may authorize a new global trust binding.
614
+ const literalDestination = !argv.profile && argv.instance && !app.config.profiles?.[argv.instance];
615
+ const trustedProfiles = app.config.credentialTrust?.profiles;
616
+ if (trustedProfiles && !literalDestination) {
617
+ const trustedOrigin = selectedProfileName ? trustedProfiles[selectedProfileName]?.instance_url : app.config.credentialTrust.origin;
618
+ if (!trustedOrigin || normalizeInstanceURL(trustedOrigin) !== normalizeInstanceURL(instanceURL)) {
619
+ throw errUsage('Project login destination is not globally trusted. Approve it explicitly with auth login <URL>.');
620
+ }
621
+ }
622
+
611
623
  const matchingProfiles = Object.entries(app.config.profiles || {})
612
624
  .filter(([, profile]) => normalizeInstanceURL(profile.instance_url) === instanceURL);
613
625
  if (!selectedProfileName && !argv.name && matchingProfiles.length > 1) {
@@ -615,10 +627,13 @@ Find your instance URL in your browser's address bar when logged into ServiceNow
615
627
  }
616
628
  const target = argv.name ? { name: argv.name, profile: null }
617
629
  : resolveTargetProfile({ ...argv, profile: selectedProfileName }, app.config, instanceURL);
618
- const targetProfile = target.profile;
630
+ const savedTarget = trustedProfiles?.[target.name];
631
+ const targetProfile = trustedProfiles
632
+ ? savedTarget && normalizeInstanceURL(savedTarget.instance_url) === normalizeInstanceURL(instanceURL) ? savedTarget : null
633
+ : target.profile;
619
634
  validateLoginSelectors(argv, targetProfile);
620
635
  let targetUsername = targetProfile?.username || '';
621
- const methodConfig = argv.name ? { profiles: {} } : app.config;
636
+ const methodConfig = { profiles: argv.name ? {} : trustedProfiles || app.config.profiles };
622
637
  const useBasic = shouldUseBasicAuth(argv, methodConfig, instanceURL, targetProfile);
623
638
  const useGck = shouldUseGckAuth(argv, methodConfig, instanceURL, targetProfile);
624
639
  const interactive = canUsePicker(app, argv);
@@ -631,9 +646,10 @@ Find your instance URL in your browser's address bar when logged into ServiceNow
631
646
  }
632
647
  const preliminary = argv.printUrl && !argv.waitFile;
633
648
  const explicitPreferences = ['read-only', 'skip-confirmations', 'include-counts'].every(flag => typeof argv[flag] === 'boolean');
649
+ const preferenceProfile = trustedProfiles ? trustedProfiles[target.name] || {} : targetProfile || {};
634
650
  const preferences = !targetProfile && interactive && !preliminary && !explicitPreferences
635
651
  ? await chooseConnectionPreferences(app.config, argv, { confirm: (await import('../prompts.js')).confirm })
636
- : await configureProfileOptions({ ...targetProfile, ...connectionPreferences(app.config, targetProfile || {}, argv) }, argv);
652
+ : await configureProfileOptions({ ...preferenceProfile, ...connectionPreferences(app.config, preferenceProfile, argv) }, argv);
637
653
  let setDefault = argv.makeDefault === true;
638
654
  if (!targetProfile && argv.makeDefault === undefined && interactive && !preliminary) {
639
655
  const { confirm } = await import('../prompts.js');
@@ -747,7 +763,7 @@ Find your instance URL in your browser's address bar when logged into ServiceNow
747
763
  }
748
764
 
749
765
  app.config.profiles[profileName] = {
750
- ...(app.config.profiles[profileName] || {}),
766
+ ...(trustedProfiles ? trustedProfiles[profileName] || {} : app.config.profiles[profileName] || {}),
751
767
  instance_url: instanceURL,
752
768
  auth_method: useGck ? 'gck' : useBasic ? 'basic' : 'oauth',
753
769
  username: username || undefined,
@@ -789,7 +805,7 @@ Find your instance URL in your browser's address bar when logged into ServiceNow
789
805
  }
790
806
 
791
807
  const { saveConfig } = await import('../config.js');
792
- saveConfig(app.config);
808
+ saveConfig(app.config, { approvedProfile: profileName, approveDefault: setDefault });
793
809
  syncSession(app);
794
810
 
795
811
  const result = {
@@ -118,20 +118,52 @@ export function ensureDocsCacheDir() {
118
118
  * { dir, prefix } so community content can live under a `community/` prefix
119
119
  * without colliding with the ServiceNowDocs markdown tree.
120
120
  */
121
+ // The caller-selected lexical root is the authorization boundary, not whatever
122
+ // realpath happens to point at. Reject aliases in *every* component (including
123
+ // junctions on Windows), before using realpath to pin that boundary. Missing
124
+ // optional roots remain optional; dangling links are not missing directories.
125
+ export function resolveDocsRoot(dir) {
126
+ const absolute = path.resolve(dir);
127
+ const anchor = path.parse(absolute).root;
128
+ let current = anchor;
129
+ for (const component of absolute.slice(anchor.length).split(path.sep).filter(Boolean)) {
130
+ current = path.join(current, component);
131
+ let stat;
132
+ try { stat = fs.lstatSync(current); }
133
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
134
+ if (stat.isSymbolicLink()) throw new Error(`Documentation source contains a symbolic link or junction alias: ${current}`);
135
+ if (!stat.isDirectory()) throw new Error(`Documentation source is not a directory: ${current}`);
136
+ }
137
+ const canonical = fs.realpathSync(absolute);
138
+ if (path.relative(absolute, canonical) !== '') throw new Error(`Documentation source resolves through an alias: ${absolute}`);
139
+ return canonical;
140
+ }
141
+
142
+ function containedDocsPath(root, file) {
143
+ const relative = path.relative(root, fs.realpathSync(file));
144
+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
145
+ throw new Error(`Documentation source escapes its root: ${file}`);
146
+ }
147
+ }
148
+
121
149
  export function* walkDocs(roots) {
122
150
  function* walk(dir, root, prefix) {
151
+ containedDocsPath(root, dir);
123
152
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
124
153
  const full = path.join(dir, entry.name);
125
154
  if (entry.isDirectory()) {
126
155
  yield* walk(full, root, prefix);
127
156
  } else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) {
157
+ containedDocsPath(root, full);
128
158
  const rel = prefix + path.relative(root, full).split(path.sep).join('/');
129
159
  yield { file: full, rel };
130
160
  }
131
161
  }
132
162
  }
133
- for (const root of roots) {
134
- if (!fs.existsSync(root.dir)) continue;
163
+ // Validate every root before yielding any document from any root.
164
+ const validated = roots.map(root => ({ ...root, dir: resolveDocsRoot(root.dir) }));
165
+ for (const root of validated) {
166
+ if (!root.dir) continue;
135
167
  yield* walk(root.dir, root.dir, root.prefix || '');
136
168
  }
137
169
  }
@@ -7,7 +7,7 @@ import { docsReaderLease } from './locks.js';
7
7
  import { errUsageHint } from '../../errors.js';
8
8
  import { createHash } from 'node:crypto';
9
9
  import { parseFrontmatter } from '../../frontmatter.js';
10
- import { withDocsDb, resolveDocsDbPath, walkDocs, defaultDocsRoots, getDocsSourceDir } from './db.js';
10
+ import { withDocsDb, resolveDocsDbPath, resolveDocsRoot, walkDocs, defaultDocsRoots, getDocsSourceDir } from './db.js';
11
11
  import { encodeText, phasesToBytes, docSurface, DEFAULT_DIM } from './hrr.js';
12
12
 
13
13
  export function refreshDocs(opts = {}) {
@@ -20,6 +20,7 @@ function refreshDocsLocked(opts = {}) {
20
20
  const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
21
21
  const roots = opts.roots || defaultDocsRoots(opts);
22
22
 
23
+ for (const root of roots) resolveDocsRoot(root.dir);
23
24
  if (roots.some(root => (!root.prefix || opts.roots) && (!fs.existsSync(root.dir) || !fs.statSync(root.dir).isDirectory()))) {
24
25
  throw errUsageHint('Raw documentation source is missing; existing index retained.', 'Use jsn docs install --source snapshot to update a prebuilt index, or --source github to install raw source before refreshing.');
25
26
  }
@@ -10,7 +10,7 @@ import { ingestDocs } from './ingest.js';
10
10
  import { refreshDocs } from './refresh.js';
11
11
  import { installSnapshot } from './snapshot.js';
12
12
  import { publishServiceSnapshot } from './service-snapshot.js';
13
- import { DEFAULT_DOCS_RELEASE, resolveDocsDbPath, resolveDocsRelease } from './db.js';
13
+ import { DEFAULT_DOCS_RELEASE, resolveDocsDbPath, resolveDocsRelease, resolveDocsRoot } from './db.js';
14
14
 
15
15
  const defaultStorage = path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service');
16
16
  function git(args) {
@@ -30,6 +30,8 @@ async function performSync(options = {}) {
30
30
  const branch = family ? resolveDocsRelease(family) : options.branch || process.env.DOCS_SOURCE_BRANCH || DEFAULT_DOCS_RELEASE;
31
31
  fs.mkdirSync(storage, { recursive: true });
32
32
  const repo = path.join(storage, 'source');
33
+ resolveDocsRoot(repo);
34
+ resolveDocsRoot(path.join(repo, 'markdown'));
33
35
  const live = family ? resolveDocsDbPath(family) : path.join(storage, 'docs.sqlite3');
34
36
  const staging = path.join(storage, `build-${randomUUID()}.sqlite3`);
35
37
  let previous = {};
@@ -89,7 +91,7 @@ async function performSync(options = {}) {
89
91
  }
90
92
  const revision = git(['-C', repo, 'rev-parse', 'HEAD']);
91
93
  const markdown = path.join(repo, 'markdown');
92
- if (!fs.statSync(markdown).isDirectory()) throw new Error('Source has no markdown directory');
94
+ if (!resolveDocsRoot(markdown)) throw new Error('Source has no markdown directory');
93
95
  let oldRevision;
94
96
  if (fs.existsSync(live)) {
95
97
  const db = new Database(live, { readonly: true });
package/src/config.js CHANGED
@@ -5,6 +5,13 @@ import path from 'node:path';
5
5
  import os from 'node:os';
6
6
 
7
7
  const APP_NAME = 'servicenow';
8
+ // Persistence provenance is private: project JSON cannot forge it.
9
+ const persistence = new WeakMap();
10
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
11
+ const fields = ['instanceURL', 'defaultProfile', 'format', 'connectionDefaults', 'docs'];
12
+ function snapshot(cfg) {
13
+ return structuredClone(Object.fromEntries([...fields, 'profiles'].map(key => [key, cfg[key]])));
14
+ }
8
15
 
9
16
  export function globalConfigDir() {
10
17
  const xdg = process.env.XDG_CONFIG_HOME;
@@ -101,6 +108,7 @@ export function loadConfig(overrides = {}) {
101
108
  const cfg = createConfig();
102
109
 
103
110
  loadFromFile(cfg, globalConfigPath(), 'global');
111
+ const global = snapshot(cfg);
104
112
  // Preserve provenance outside the serializable/user-controlled config shape.
105
113
  // A project can select an origin, but cannot authorize ambient secrets for it.
106
114
  Object.defineProperty(cfg, 'credentialTrust', { value: {
@@ -126,6 +134,7 @@ export function loadConfig(overrides = {}) {
126
134
  }
127
135
  }
128
136
 
137
+ persistence.set(cfg, { global, effective: snapshot(cfg) });
129
138
  return cfg;
130
139
  }
131
140
 
@@ -141,34 +150,82 @@ export function isTrustedCredentialDestination(cfg, instance, explicitInstance =
141
150
  return Boolean(binding) && normalizeInstanceURL(binding) === origin;
142
151
  }
143
152
 
144
- export function saveConfig(cfg) {
153
+ export function saveConfig(cfg, { approvedProfile = '', approveDefault = false } = {}) {
154
+ const state = persistence.get(cfg);
155
+ const next = state ? structuredClone(state.global) : snapshot(cfg);
156
+ const changedProfiles = new Set();
157
+ const changedFields = new Set();
158
+ const refuse = () => {
159
+ const error = new Error('Project configuration cannot be promoted to global trust. Edit the global profile outside this project, or explicitly approve the destination with auth login <URL>.');
160
+ error.code = 'usage_error';
161
+ throw error;
162
+ };
163
+ if (state) {
164
+ for (const name of new Set([...Object.keys(state.effective.profiles), ...Object.keys(cfg.profiles)])) {
165
+ if (name !== approvedProfile && same(cfg.profiles[name], state.effective.profiles[name])) continue;
166
+ // A changed project-derived profile must not be copied wholesale, even
167
+ // when the user only changed an innocuous preference on that profile.
168
+ if (name !== approvedProfile && cfg.profiles[name] !== undefined
169
+ && !same(state.effective.profiles[name], state.global.profiles[name])) refuse();
170
+ if (cfg.profiles[name] === undefined) delete next.profiles[name];
171
+ else next.profiles[name] = structuredClone(cfg.profiles[name]);
172
+ changedProfiles.add(name);
173
+ }
174
+ for (const key of fields) {
175
+ if (same(cfg[key], state.effective[key]) && !(approveDefault && ['instanceURL', 'defaultProfile'].includes(key))) continue;
176
+ // Removing a locally selected profile must not clear an unrelated global
177
+ // default. The caller explicitly removed that profile, not this one.
178
+ if (key === 'defaultProfile' && !cfg[key] && !approveDefault
179
+ && state.effective.defaultProfile !== state.global.defaultProfile) {
180
+ changedFields.add(key);
181
+ continue;
182
+ }
183
+ if (key === 'instanceURL' && !approveDefault && cfg[key]) {
184
+ // Switching is selection, not authorization of a project origin.
185
+ const name = cfg.defaultProfile;
186
+ if (name && (!same(cfg.profiles[name], next.profiles[name]) || !next.profiles[name])) refuse();
187
+ }
188
+ if (key === 'defaultProfile' && cfg[key] && !approveDefault
189
+ && (!next.profiles[cfg[key]] || !same(cfg.profiles[cfg[key]], next.profiles[cfg[key]]))) refuse();
190
+ next[key] = structuredClone(cfg[key]);
191
+ changedFields.add(key);
192
+ }
193
+ }
145
194
  const dir = globalConfigDir();
146
195
  fs.mkdirSync(dir, { recursive: true, mode: 0o750 });
147
196
  const payload = {
148
- connection_defaults: cfg.connectionDefaults || undefined,
149
- docs: cfg.docs || undefined,
150
- instance_url: cfg.instanceURL || undefined,
151
- profiles: Object.keys(cfg.profiles).length > 0 ? cfg.profiles : undefined,
152
- default_profile: cfg.defaultProfile || undefined,
153
- format: cfg.format || undefined,
197
+ connection_defaults: next.connectionDefaults || undefined,
198
+ docs: next.docs || undefined,
199
+ instance_url: next.instanceURL || undefined,
200
+ profiles: Object.keys(next.profiles).length > 0 ? next.profiles : undefined,
201
+ default_profile: next.defaultProfile || undefined,
202
+ format: next.format || undefined,
154
203
  };
155
204
  fs.writeFileSync(globalConfigPath(), JSON.stringify(payload, null, 2), { mode: 0o600 });
156
205
 
157
- // Sync managed fields to local config if it exists, so profile operations
158
- // (use, remove, create, auth login) aren't silently reverted on next load.
159
- if (fs.existsSync(localConfigPath())) {
206
+ // Synchronize only authored changes. Never replace the project's entire
207
+ // profile map with the effective (or global) map.
208
+ if (state && fs.existsSync(localConfigPath())) {
160
209
  try {
161
- const localData = JSON.parse(fs.readFileSync(localConfigPath(), 'utf-8'));
162
- const merged = { ...localData };
163
- if (payload.profiles !== undefined) merged.profiles = payload.profiles;
164
- if (payload.default_profile !== undefined) merged.default_profile = payload.default_profile;
165
- if (payload.instance_url !== undefined) merged.instance_url = payload.instance_url;
166
- if (payload.format !== undefined) merged.format = payload.format;
167
- fs.writeFileSync(localConfigPath(), JSON.stringify(merged, null, 2), { mode: 0o600 });
210
+ const local = JSON.parse(fs.readFileSync(localConfigPath(), 'utf-8'));
211
+ for (const name of changedProfiles) {
212
+ local.profiles ||= {};
213
+ if (next.profiles[name] === undefined) delete local.profiles[name];
214
+ else local.profiles[name] = next.profiles[name];
215
+ }
216
+ const keys = { instanceURL: 'instance_url', defaultProfile: 'default_profile', format: 'format' };
217
+ for (const key of changedFields) if (keys[key]) {
218
+ if (next[key]) local[keys[key]] = next[key];
219
+ else delete local[keys[key]];
220
+ }
221
+ if (changedProfiles.size || [...changedFields].some(key => keys[key])) {
222
+ fs.writeFileSync(localConfigPath(), JSON.stringify(local, null, 2), { mode: 0o600 });
223
+ }
168
224
  } catch {
169
- // Local config unreadable — skip sync, global save already succeeded
225
+ // Local config unreadable — skip sync, global save already succeeded.
170
226
  }
171
227
  }
228
+ if (state) persistence.set(cfg, { global: next, effective: snapshot(cfg) });
172
229
  }
173
230
 
174
231
  export function saveLocalConfig(cfg) {