@jacebenson/jsn 5.5.6 → 5.5.7

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.
@@ -3,7 +3,7 @@
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import os from 'node:os';
6
- import Database from 'better-sqlite3';
6
+ import Database, { requireFts5 } from '../../sqlite.js';
7
7
  import { docsReaderLease } from './locks.js';
8
8
  import { AppError } from '../../errors.js';
9
9
 
@@ -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
  }
@@ -151,7 +183,8 @@ export function openDocsDb(opts = {}) {
151
183
  let db;
152
184
  try {
153
185
  db = new Database(dbPath);
154
- } catch (error) { release(); throw error; }
186
+ requireFts5(db);
187
+ } catch (error) { if (db) db.close(); release(); throw error; }
155
188
  const close = db.close.bind(db);
156
189
  db.close = () => { try { return close(); } finally { release(); } };
157
190
  try {
@@ -190,6 +223,7 @@ export function setSchemaVersion(db, version) {
190
223
  }
191
224
 
192
225
  export function initDocsSchema(db) {
226
+ requireFts5(db);
193
227
  db.exec(`
194
228
  CREATE TABLE IF NOT EXISTS docs (
195
229
  id INTEGER PRIMARY KEY,
@@ -1,7 +1,7 @@
1
1
  // Documentation search always uses the same API, hosted or self-hosted.
2
2
  import { searchHostedDocs, getHostedDoc, getHostedDocsStatus, configuredDocsService } from './client.js';
3
3
  import { documentationService } from './local.js';
4
- import { startDocumentationServer } from './server.js';
4
+
5
5
  import { declareCapabilities } from '../../capabilities.js';
6
6
  import { AppError } from '../../errors.js';
7
7
  import { resolveDocsRelease } from './db.js';
@@ -47,7 +47,15 @@ async function read(argv, app) {
47
47
  app.ok(presented(row, `Doc ${row.id}: ${title} in ${row.release}\n${provenance}${context}\n${content}\n`), { summary: `Doc ${row.id}: ${title} in ${row.release}` });
48
48
  }
49
49
 
50
- export function docsCmd(wrap) {
50
+ export function docsCmd(wrapHandler) {
51
+ // The adapter tolerates unknown options; retired server flags must fail closed
52
+ // on every docs spelling rather than becoming an accidental search request.
53
+ const wrap = handler => wrapHandler(async (argv, app) => {
54
+ for (const name of ['serve', 'no-serve', 'host', 'no-host', 'port', 'no-port']) {
55
+ if (Object.hasOwn(argv, name)) throw new AppError('usage_error', `Unknown option --${name}: the CLI documentation server flags have been removed. Use terminal search or configure a documentation service in jsn setup.`);
56
+ }
57
+ return handler(argv, app);
58
+ });
51
59
  return {
52
60
  command: 'docs [query..]',
53
61
  defaultPositionals: true,
@@ -56,9 +64,7 @@ export function docsCmd(wrap) {
56
64
  .usage('Usage: jsn docs "search terms" [options]')
57
65
  .positional('query', { type: 'string', describe: 'Search words (up to 200 characters)' })
58
66
  .option('release', { type: 'string', describe: 'Documentation family (docs.release config, otherwise australia)' })
59
- .option('serve', { type: 'boolean', describe: 'Run the shared documentation server (downloads its index automatically)' })
60
- .option('host', { type: 'string', default: '127.0.0.1', describe: 'Server bind address with --serve' })
61
- .option('port', { type: 'number', default: 3000, describe: 'Server port with --serve' })
67
+
62
68
  .option('limit', { type: 'number', default: 20, describe: 'Results per page (1–50)' })
63
69
  .option('offset', { type: 'number', default: 0, describe: 'Result offset (0–10000)' })
64
70
  .option('bundle', { type: 'string', describe: 'Filter by documentation bundle' })
@@ -95,14 +101,7 @@ export function docsCmd(wrap) {
95
101
  app.ok(data, { summary: `Documentation service: ${data.state} in ${data.release}` });
96
102
  }) }),
97
103
  handler: wrap(async (argv, app) => {
98
- if (argv.serve) {
99
- if (!Number.isInteger(argv.port) || argv.port < 0 || argv.port > 65535) throw new AppError('usage_error', 'Use a port between 0 and 65535.');
100
- const release = resolveDocsRelease(argv.release, app.config);
101
- const { server, url } = await startDocumentationServer({ host: argv.host, port: argv.port, release });
102
- app.ok({ url, release, state: 'listening' }, { summary: `Documentation server started for ${release}; the index updates automatically.` });
103
- for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => server.close());
104
- return;
105
- }
104
+
106
105
  if ((argv.outline || argv.section !== undefined) && !argv.path) throw new AppError('usage_error', 'Use --path with --outline or --section.');
107
106
  if (argv.path) return read(argv, app);
108
107
  if (argv.query?.length) return search(argv, app);
@@ -2,7 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import { selectDocument } from './sections.js';
4
4
  import path from 'node:path';
5
- import Database from 'better-sqlite3';
5
+ import Database, { requireFts5 } from '../../sqlite.js';
6
6
  import { resolveDocsDbPath } from './db.js';
7
7
 
8
8
  export class DocumentationError extends Error {
@@ -56,6 +56,7 @@ export class DocumentationIndex {
56
56
  close() { this.db.close(); }
57
57
  revision() { return this.db.prepare("SELECT value FROM meta WHERE key = 'source_revision'").get()?.value || this.db.prepare("SELECT value FROM meta WHERE key = 'snapshot_revision'").get()?.value || ''; }
58
58
  search({ query, limit = 20, offset = 0, bundle } = {}) {
59
+ requireFts5(this.db);
59
60
  const text = String(query || '').trim();
60
61
  if (!text || text.length > 200) throw new DocumentationError('Enter a search of 1 to 200 characters.', 400);
61
62
  const tokens = text.match(/[\p{L}\p{N}_]+/gu)?.slice(0, 20);
@@ -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
  }
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import Database from 'better-sqlite3';
3
+ import Database from '../../sqlite.js';
4
4
  import { DEFAULT_DOCS_RELEASE, resolveDocsDbPath, getMeta } from './db.js';
5
5
  import { docsReaderLease } from './locks.js';
6
6
 
@@ -1,5 +1,5 @@
1
1
  import fs from 'node:fs';
2
- import Database from 'better-sqlite3';
2
+ import Database from '../../sqlite.js';
3
3
  import { docsInstallLease, docsHaveReaders } from './locks.js';
4
4
  import { errUsageHint } from '../../errors.js';
5
5
 
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { createHash } from 'node:crypto';
5
5
  import { gzipSync } from 'node:zlib';
6
- import Database from 'better-sqlite3';
6
+ import Database from '../../sqlite.js';
7
7
  import { validateDatabase, validateManifest } from './snapshot.js';
8
8
 
9
9
  export async function publishServiceSnapshot(storage, { dbPath = path.join(storage, 'docs.sqlite3'), release } = {}) {
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { createHash, randomUUID } from 'node:crypto';
5
5
  import { gzipSync, gunzipSync } from 'node:zlib';
6
- import Database from 'better-sqlite3';
6
+ import Database, { requireFts5 } from '../../sqlite.js';
7
7
  import { resolveDocsDbPath, resolveDocsRelease, DEFAULT_DOCS_RELEASE } from './db.js';
8
8
  import { docsServiceUrl } from './client.js';
9
9
  import { docsReaderLease } from './locks.js';
@@ -29,6 +29,7 @@ export function validateManifest(manifest) {
29
29
  export function validateDatabase(filename) {
30
30
  const db = new Database(filename, { readonly: true, fileMustExist: true });
31
31
  try {
32
+ requireFts5(db);
32
33
  if (db.pragma('integrity_check', { simple: true }) !== 'ok') throw new Error('Snapshot SQLite integrity check failed');
33
34
  if (db.prepare("SELECT value FROM meta WHERE key='schema_version'").get()?.value !== String(SNAPSHOT_SCHEMA)) throw new Error('Incompatible snapshot database schema');
34
35
  const count = db.prepare('SELECT count(*) AS n FROM docs').get().n;
@@ -5,12 +5,12 @@ import { fileURLToPath } from 'node:url';
5
5
  import { randomUUID } from 'node:crypto';
6
6
  import os from 'node:os';
7
7
  import { spawnSync } from 'node:child_process';
8
- import Database from 'better-sqlite3';
8
+ import Database from '../../sqlite.js';
9
9
  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 });
@@ -4,8 +4,6 @@ import os from 'node:os';
4
4
  import process from 'node:process';
5
5
  import { fileURLToPath } from 'node:url';
6
6
 
7
- import { execSync } from 'node:child_process';
8
-
9
7
  import { globalConfigPath } from '../config.js';
10
8
  import { declareCapabilities } from '../capabilities.js';
11
9
  import { canUsePicker } from '../helpers.js';
@@ -22,15 +20,12 @@ const SKILL_REPO_PATH = path.join(
22
20
  * Resolve the user's real home directory, even when Hermes overrides $HOME.
23
21
  */
24
22
  function realHomeDir() {
25
- // getent doesn't exist on Windows; os.homedir() is reliable there.
26
- if (process.platform === 'win32') return os.homedir();
27
-
28
23
  try {
29
- const result = execSync('getent passwd ' + process.env.USER + ' 2>/dev/null', { encoding: 'utf-8', timeout: 3000 });
30
- const home = result.trim().split(':')[5];
24
+ // OS account data is independent of inherited USER/HOME and needs no shell.
25
+ const home = os.userInfo().homedir;
31
26
  if (home) return home;
32
27
  } catch {
33
- // fall through
28
+ // Account lookup may be unavailable in minimal/container environments.
34
29
  }
35
30
  return os.homedir();
36
31
  }
@@ -59,7 +59,11 @@ export function versionCmd(wrap) {
59
59
  alias: 'c',
60
60
  type: 'boolean',
61
61
  describe: 'Check npm registry for newer version',
62
- }),
62
+ })
63
+ .epilogue('Update jsn with the upgrade command:\n'
64
+ + ' jsn upgrade Update within the current channel\n'
65
+ + ' jsn upgrade --channel latest Switch to stable\n'
66
+ + ' jsn upgrade --channel dev Switch to dev'),
63
67
  handler: wrap(async (argv, app) => {
64
68
  const version = getVersion();
65
69
 
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,13 @@ export function loadConfig(overrides = {}) {
101
108
  const cfg = createConfig();
102
109
 
103
110
  loadFromFile(cfg, globalConfigPath(), 'global');
111
+ const global = snapshot(cfg);
112
+ // Preserve provenance outside the serializable/user-controlled config shape.
113
+ // A project can select an origin, but cannot authorize ambient secrets for it.
114
+ Object.defineProperty(cfg, 'credentialTrust', { value: {
115
+ profiles: structuredClone(cfg.profiles),
116
+ origin: normalizeInstanceURL(getEffectiveInstance(cfg)),
117
+ } });
104
118
  loadFromFile(cfg, localConfigPath(), 'local');
105
119
  loadFromEnv(cfg);
106
120
 
@@ -120,37 +134,98 @@ export function loadConfig(overrides = {}) {
120
134
  }
121
135
  }
122
136
 
137
+ persistence.set(cfg, { global, effective: snapshot(cfg) });
123
138
  return cfg;
124
139
  }
125
140
 
126
- export function saveConfig(cfg) {
141
+ export function isTrustedCredentialDestination(cfg, instance, explicitInstance = '', explicitProfile = '') {
142
+ const origin = normalizeInstanceURL(instance);
143
+ // Hand-built configs are a programmatic API, not project-file input.
144
+ if (!cfg?.credentialTrust) return true;
145
+ const selectedProfile = explicitProfile && Object.hasOwn(cfg.credentialTrust.profiles, explicitProfile)
146
+ ? cfg.credentialTrust.profiles[explicitProfile]?.instance_url : '';
147
+ // Bind ambient secrets to the global default, not every saved account.
148
+ // Only explicit process selectors may opt into another saved origin.
149
+ const binding = explicitInstance || selectedProfile || process.env.SERVICENOW_INSTANCE_URL || cfg.credentialTrust.origin;
150
+ return Boolean(binding) && normalizeInstanceURL(binding) === origin;
151
+ }
152
+
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
+ }
127
194
  const dir = globalConfigDir();
128
195
  fs.mkdirSync(dir, { recursive: true, mode: 0o750 });
129
196
  const payload = {
130
- connection_defaults: cfg.connectionDefaults || undefined,
131
- docs: cfg.docs || undefined,
132
- instance_url: cfg.instanceURL || undefined,
133
- profiles: Object.keys(cfg.profiles).length > 0 ? cfg.profiles : undefined,
134
- default_profile: cfg.defaultProfile || undefined,
135
- 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,
136
203
  };
137
204
  fs.writeFileSync(globalConfigPath(), JSON.stringify(payload, null, 2), { mode: 0o600 });
138
205
 
139
- // Sync managed fields to local config if it exists, so profile operations
140
- // (use, remove, create, auth login) aren't silently reverted on next load.
141
- 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())) {
142
209
  try {
143
- const localData = JSON.parse(fs.readFileSync(localConfigPath(), 'utf-8'));
144
- const merged = { ...localData };
145
- if (payload.profiles !== undefined) merged.profiles = payload.profiles;
146
- if (payload.default_profile !== undefined) merged.default_profile = payload.default_profile;
147
- if (payload.instance_url !== undefined) merged.instance_url = payload.instance_url;
148
- if (payload.format !== undefined) merged.format = payload.format;
149
- 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
+ }
150
224
  } catch {
151
- // Local config unreadable — skip sync, global save already succeeded
225
+ // Local config unreadable — skip sync, global save already succeeded.
152
226
  }
153
227
  }
228
+ if (state) persistence.set(cfg, { global: next, effective: snapshot(cfg) });
154
229
  }
155
230
 
156
231
  export function saveLocalConfig(cfg) {
@@ -3,6 +3,7 @@ import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import process from 'node:process';
5
5
  import { execFileSync } from 'node:child_process';
6
+ import { assertCredentialDestination } from './auth/transport.js';
6
7
 
7
8
  const INSTALL_HOST = 'install.service-now.com';
8
9
 
@@ -41,9 +42,11 @@ export function buildMidRecipeUrl(releaseName) {
41
42
  export async function validateMidCredentials(instanceURL, username, password, fetchImpl = fetch) {
42
43
  if (!username || !password) throw new Error('MID Server username and password are required');
43
44
  const endpoint = `${String(instanceURL).replace(/\/$/, '')}/api/now/table/sys_properties?sysparm_query=name=mid.version&sysparm_fields=value&sysparm_limit=1`;
45
+ assertCredentialDestination(endpoint, instanceURL);
44
46
  let response;
45
47
  try {
46
48
  response = await fetchImpl(endpoint, {
49
+ redirect: 'error',
47
50
  headers: {
48
51
  Accept: 'application/json',
49
52
  Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`,
package/src/perf.js CHANGED
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import crypto from 'node:crypto';
5
- import Database from 'better-sqlite3';
5
+ import Database from './sqlite.js';
6
6
  import { getVersion } from './commands/version.js';
7
7
  import { capturePerformance } from './perf-capture.js';
8
8
 
package/src/sdk.js CHANGED
@@ -4,6 +4,7 @@ import { batchRead } from './sdk-batch.js';
4
4
  import { tableReadParams } from './table-read-params.js';
5
5
  import { gunzipSync } from 'node:zlib';
6
6
  import { AppError, CodeAPI, CodeAuth, errAuth, errAuthHint, errAPI, errNetwork, errUsage } from './errors.js';
7
+ import { assertCredentialTransport, assertCredentialDestination } from './auth/transport.js';
7
8
  import { canPrompt, getStringField } from './helpers.js';
8
9
  import { errMfaRequired, errMfaRejected, isTerminalAuthError } from './errors.js';
9
10
  import { buildMfaVerificationBody, extractMfaFormTokens, normalizeTotpCode, parseLoginStatus } from './auth/mfa.js';
@@ -82,7 +83,6 @@ export class SDKClient {
82
83
  this.baseURL = baseURL.replace(/\/$/, '');
83
84
  this.authProvider = authProvider;
84
85
  this.recovery = opts.recovery;
85
- this.onMutation = opts.onMutation;
86
86
  this.timeout = opts.timeout || DEFAULT_TIMEOUT;
87
87
  this.domain = opts.domain || '';
88
88
  this.includeReferenceLinks = opts.includeReferenceLinks === true;
@@ -163,49 +163,14 @@ export class SDKClient {
163
163
  // Keep the timeout alive through body consumption for text/JSON requests.
164
164
  // Raw-response callers retain their existing timeout boundary at headers.
165
165
  async _withAuthenticatedRequest(endpoint, opts, settings, consume = (response) => response) {
166
- const url = new URL(endpoint);
167
- const match = url.pathname.match(/^\/api\/now\/table\/([^/]+)(?:\/([^/]+))?\/?$/);
168
- const operation = { POST: 'create', PUT: 'update', PATCH: 'update', DELETE: 'delete' }[(opts.method || 'GET').toUpperCase()];
169
- const event = match && operation && this.onMutation ? {
170
- table: decodeURIComponent(match[1]), sys_id: match[2] ? decodeURIComponent(match[2]) : null, operation,
171
- } : null;
172
- let result;
173
- try {
174
- result = await this._performAuthenticatedRequest(endpoint, opts, settings, async response => {
175
- if (event) event.http_status = response.status;
176
- const value = await consume(response);
177
- if (event && value instanceof Response && response.ok && operation === 'create') {
178
- try { event.sys_id = (await response.clone().json())?.result?.sys_id || null; } catch { /* ID remains unknown. */ }
179
- }
180
- return value;
181
- });
182
- } catch (error) {
183
- if (event && !error?.notSent && error?.name !== 'PromptCancelled') await this._reportMutation({ ...event, outcome: error.status >= 400 && error.status < 500 && error.status !== 408
184
- ? 'failed' : 'unknown', http_status: error.status || null });
185
- throw error;
186
- }
187
- if (event) {
188
- let body = result;
189
- if (typeof body === 'string') { try { body = JSON.parse(body); } catch { body = null; } }
190
- const id = body?.result?.sys_id;
191
- if (typeof id === 'string') event.sys_id = id;
192
- else if (typeof id?.value === 'string') event.sys_id = id.value;
193
- await this._reportMutation({ ...event, outcome: event.http_status >= 400
194
- ? (event.http_status < 500 && event.http_status !== 408 ? 'failed' : 'unknown')
195
- : (event.sys_id ? 'succeeded' : 'unknown') });
196
- }
197
- return result;
198
- }
199
-
200
- async _reportMutation(event) {
201
- // History failures must never change the outcome of a completed remote write.
202
- try { await this.onMutation(event); } catch { /* App callback reports local storage failures. */ }
166
+ return this._performAuthenticatedRequest(endpoint, opts, settings, consume);
203
167
  }
204
168
 
205
169
  async _performAuthenticatedRequest(endpoint, opts, {
206
170
  timeout = this.timeout, prepare, skipOAuthSession = false, normalizeErrors = false,
207
171
  allowMutationReplay = false, stateful = false,
208
172
  }, consume = (response) => response) {
173
+ assertCredentialDestination(endpoint, this.baseURL);
209
174
  const method = String(opts.method || 'GET').toUpperCase();
210
175
  for (let attempt = 0; attempt <= MAX_SESSION_REPLAYS; attempt++) {
211
176
  // Headers for this attempt belong to the session as it is right now.
@@ -214,7 +179,7 @@ export class SDKClient {
214
179
  let timer;
215
180
  let rejection;
216
181
  try {
217
- const req = new Request(endpoint, { ...opts, signal: controller.signal });
182
+ const req = new Request(endpoint, { ...opts, redirect: 'error', signal: controller.signal });
218
183
  if (prepare) prepare(req);
219
184
  // Header-authenticated REST skips UI warming for OAuth/token/GCK.
220
185
  // Basic must still check for TOTP before dispatch; internal bootstrap
@@ -297,6 +262,7 @@ export class SDKClient {
297
262
  * that they still belong to the selected identity.
298
263
  */
299
264
  async _verifyRecoveredSession() {
265
+ assertCredentialTransport(this.baseURL);
300
266
  const params = new URLSearchParams({
301
267
  sysparm_query: 'user_name=javascript:gs.getUserName()',
302
268
  sysparm_fields: 'user_name', sysparm_limit: '1', sysparm_display_value: 'false',
@@ -972,7 +938,6 @@ export class SDKClient {
972
938
  form.set('sysparm_upload_prefix', '');
973
939
  form.set('sysparm_referring_url', 'sys_remote_update_set_list.do');
974
940
  form.set('attachFile', new Blob([xml], { type: 'application/xml' }), filename);
975
- let outcome = 'unknown';
976
941
  try {
977
942
  await this.rawRequest(`${this.baseURL}/sys_upload.do`, { method: 'POST', body: form,
978
943
  headers: { ...(cookies ? { Cookie: cookies } : {}), 'X-UserToken': csrf, Referer: formURL },
@@ -998,12 +963,9 @@ export class SDKClient {
998
963
  const member = actual.get(expected.sys_id);
999
964
  return !member || getStringField(member, 'name') !== expected.name || getStringField(member, 'action') !== expected.action;
1000
965
  })) throw new Error('Uploaded update set members did not match the XML export');
1001
- outcome = 'succeeded';
1002
966
  return { sys_id: importedID, state, count: members.length, link: `${this.baseURL}/sys_remote_update_set.do?sys_id=${importedID}` };
1003
967
  } catch (error) {
1004
968
  throw new AppError(CodeAPI, `XML import could not be verified: ${error.message}. It may have partially loaded; inspect Retrieved Update Sets before retrying. No automatic retry was attempted.`, 'Inspect Retrieved Update Sets before retrying.', 0, error);
1005
- } finally {
1006
- if (this.onMutation) await this._reportMutation({ table: 'sys_remote_update_set', sys_id: id, operation: 'create', outcome });
1007
969
  }
1008
970
  }
1009
971
 
@@ -1183,6 +1145,7 @@ export class SDKClient {
1183
1145
  * is an actionable error, never a silent fallback.
1184
1146
  */
1185
1147
  async ambSession() {
1148
+ assertCredentialTransport(this.baseURL);
1186
1149
  if (!this.authProvider) throw errAuth('No authentication configured');
1187
1150
  const creds = await this.authProvider.getCredentials();
1188
1151
  if (!creds) throw errAuth('No valid credentials');
@@ -1222,19 +1185,21 @@ export class SDKClient {
1222
1185
  }
1223
1186
 
1224
1187
  async _initializeSession() {
1188
+ assertCredentialTransport(this.baseURL);
1225
1189
  let challenged = false;
1226
1190
  try {
1227
1191
  const creds = await this.authProvider.getCredentials();
1228
1192
  if (creds.auth_method === 'oauth') {
1229
1193
  const cookieJar = new Map();
1230
1194
  const login = `${this.baseURL}/angular.do?sysparm_type=get_user`;
1231
- collectSetCookies(cookieJar, await fetch(new Request(login, { method: 'POST' })));
1195
+ collectSetCookies(cookieJar, await fetch(new Request(login, { method: 'POST', redirect: 'error' })));
1232
1196
  const scopeEndpoint = `${this.baseURL}/api/now/table/sys_scope?sysparm_fields=sys_id%2Csys_class_name&sysparm_limit=1`;
1233
1197
  collectSetCookies(cookieJar, await this._fetchWithAuth(scopeEndpoint, {
1234
1198
  method: 'GET',
1235
1199
  headers: serializeCookies(cookieJar) ? { Cookie: serializeCookies(cookieJar) } : {},
1236
1200
  }));
1237
1201
  const finalLogin = await fetch(new Request(login, {
1202
+ redirect: 'error',
1238
1203
  method: 'POST',
1239
1204
  headers: serializeCookies(cookieJar) ? { Cookie: serializeCookies(cookieJar) } : {},
1240
1205
  }));
@@ -1284,6 +1249,7 @@ export class SDKClient {
1284
1249
  // Each network exchange, including its body, has a deadline independent of
1285
1250
  // human code entry. The race also bounds streams that do not honor abort.
1286
1251
  async _mfaExchange(path, options, cookieJar, consume = response => response) {
1252
+ assertCredentialTransport(this.baseURL);
1287
1253
  const controller = new AbortController();
1288
1254
  let timer;
1289
1255
  const deadline = new Promise((resolve, reject) => {
package/src/session.js CHANGED
@@ -57,7 +57,12 @@ import { errUsage } from './errors.js';
57
57
  */
58
58
  export function resolveSession(argv = {}, config) {
59
59
  const cfg = config || {};
60
- const profiles = cfg.profiles || {};
60
+ const profiles = { ...(cfg.profiles || {}) };
61
+ // Explicitly selecting a globally saved profile must not select a project
62
+ // shadow with the same name and a different destination.
63
+ if (argv.profile && cfg.credentialTrust?.profiles[argv.profile]) {
64
+ profiles[argv.profile] = cfg.credentialTrust.profiles[argv.profile];
65
+ }
61
66
 
62
67
  // --profile selects the active profile for this run. Unknown names are
63
68
  // surfaced as data (unknownProfile) — the caller (cli.js middleware)