@jacebenson/jsn 5.5.6-dev.207.1 → 5.5.6-dev.209.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.207.1",
3
+ "version": "5.5.6-dev.209.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": {
@@ -25,7 +25,6 @@
25
25
  "dependencies": {
26
26
  "@inquirer/core": "^10.3.2",
27
27
  "@inquirer/prompts": "^7.10.1",
28
- "better-sqlite3": "^13.2.0",
29
28
  "commonmark": "^0.31.2",
30
29
  "js-yaml": "^5.5.0",
31
30
  "saxes": "^6.0.0",
@@ -42,5 +41,8 @@
42
41
  "skills/",
43
42
  "README.md",
44
43
  "LICENSE"
45
- ]
44
+ ],
45
+ "engines": {
46
+ "node": ">=24.0.0"
47
+ }
46
48
  }
@@ -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 = {
@@ -9,7 +9,7 @@ import path from 'node:path';
9
9
  import process from 'node:process';
10
10
  import TurndownService from 'turndown';
11
11
  import { parseFrontmatter, stringifyFrontmatter } from '../../frontmatter.js';
12
- import Database from 'better-sqlite3';
12
+ import Database from '../../sqlite.js';
13
13
  import { getDocsCommunityDir, resolveDocsDbPath, docsDbExists } from './db.js';
14
14
  import { refreshDocs } from './refresh.js';
15
15
  import { ingestDocs } from './ingest.js';
@@ -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
 
@@ -151,7 +151,8 @@ export function openDocsDb(opts = {}) {
151
151
  let db;
152
152
  try {
153
153
  db = new Database(dbPath);
154
- } catch (error) { release(); throw error; }
154
+ requireFts5(db);
155
+ } catch (error) { if (db) db.close(); release(); throw error; }
155
156
  const close = db.close.bind(db);
156
157
  db.close = () => { try { return close(); } finally { release(); } };
157
158
  try {
@@ -190,6 +191,7 @@ export function setSchemaVersion(db, version) {
190
191
  }
191
192
 
192
193
  export function initDocsSchema(db) {
194
+ requireFts5(db);
193
195
  db.exec(`
194
196
  CREATE TABLE IF NOT EXISTS docs (
195
197
  id INTEGER PRIMARY KEY,
@@ -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);
@@ -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,7 +5,7 @@ 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';
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) {
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/sqlite.js ADDED
@@ -0,0 +1,94 @@
1
+ // The small synchronous SQLite contract shared by docs and performance storage.
2
+ // Do not load node:sqlite until a local database is actually opened.
3
+ import fs from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import { types } from 'node:util';
6
+ const require = createRequire(import.meta.url);
7
+ let sqlite;
8
+ function runtime() {
9
+ if (!sqlite) {
10
+ if (Number(process.versions.node.split('.')[0]) < 24) {
11
+ throw new Error('Local SQLite storage requires Node.js 24 or newer. Upgrade Node.js, or use hosted documentation search.');
12
+ }
13
+ sqlite = require('node:sqlite');
14
+ }
15
+ return sqlite;
16
+ }
17
+ function row(value) {
18
+ if (value === undefined) return value;
19
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, item instanceof Uint8Array ? Buffer.from(item) : item]));
20
+ }
21
+ let savepoint = 0;
22
+ export default class Database {
23
+ constructor(filename, { readonly = false, fileMustExist = false, timeout = 5000 } = {}) {
24
+ if (fileMustExist && filename !== ':memory:') fs.accessSync(filename);
25
+ this.connection = new (runtime().DatabaseSync)(filename, {
26
+ readOnly: readonly, timeout, enableForeignKeyConstraints: true,
27
+ enableDoubleQuotedStringLiterals: true,
28
+ });
29
+ }
30
+ get open() { return this.connection.isOpen; }
31
+ get inTransaction() { return this.connection.isTransaction; }
32
+ close() { this.connection.close(); }
33
+ exec(sql) { this.connection.exec(sql); return this; }
34
+ prepare(sql) {
35
+ const statement = this.connection.prepare(sql);
36
+ // better-sqlite3 accepted unused keys in named parameter objects.
37
+ statement.setAllowUnknownNamedParameters(true);
38
+ const args = values => {
39
+ const bindings = values.length === 1 && Array.isArray(values[0]) ? values[0] : values;
40
+ // Node 26 accepts undefined as NULL, whereas Node 24 and better-sqlite3
41
+ // reject it. Keep accidental missing values from silently becoming NULL.
42
+ for (const value of bindings) {
43
+ const entries = value && typeof value === 'object' && !ArrayBuffer.isView(value) ? Object.values(value) : [value];
44
+ if (entries.includes(undefined)) throw new TypeError('SQLite bindings must not be undefined; use null explicitly');
45
+ }
46
+ return bindings;
47
+ };
48
+ return {
49
+ run: (...values) => statement.run(...args(values)),
50
+ get: (...values) => row(statement.get(...args(values))),
51
+ all: (...values) => statement.all(...args(values)).map(row),
52
+ };
53
+ }
54
+ pragma(sql, { simple = false } = {}) {
55
+ const rows = this.prepare(`PRAGMA ${sql}`).all();
56
+ return simple ? Object.values(rows[0] || {})[0] : rows;
57
+ }
58
+ backup(filename) { return runtime().backup(this.connection, filename); }
59
+ transaction(operation) {
60
+ // Reject declared async callbacks before invoking them: rolling back their
61
+ // first writes cannot stop their continuation writing after an await.
62
+ if (types.isAsyncFunction(operation)) throw new TypeError('SQLite transactions must be synchronous');
63
+ const db = this;
64
+ return function (...args) {
65
+ const nested = db.inTransaction;
66
+ const name = `jsn_${++savepoint}`;
67
+ db.exec(nested ? `SAVEPOINT ${name}` : 'BEGIN');
68
+ try {
69
+ const result = operation.apply(this, args);
70
+ if (result && typeof result.then === 'function') throw new TypeError('SQLite transactions must be synchronous');
71
+ db.exec(nested ? `RELEASE ${name}` : 'COMMIT');
72
+ return result;
73
+ } catch (error) {
74
+ if (db.inTransaction) {
75
+ try {
76
+ db.exec(nested ? `ROLLBACK TO ${name}; RELEASE ${name}` : 'ROLLBACK');
77
+ } catch { /* Preserve the operation's original failure. */ }
78
+ }
79
+ throw error;
80
+ }
81
+ };
82
+ }
83
+ }
84
+
85
+ // Check the actual library, not the Node major: some builds omit FTS5.
86
+ // pragma_module_list works on read-only snapshot connections too.
87
+ export function requireFts5(db) {
88
+ try {
89
+ if (db.prepare("SELECT 1 AS available FROM pragma_module_list WHERE name='fts5'").get()?.available) return;
90
+ } catch { /* Report the same actionable capability error. */ }
91
+ const error = new Error('This Node.js SQLite build has no FTS5 support. Upgrade to a current official Node.js 24 LTS or newer build with FTS5 for local docs indexing/search; hosted documentation search does not require SQLite.');
92
+ error.code = 'sqlite_fts5_unavailable';
93
+ throw error;
94
+ }