@jacebenson/jsn 5.5.6-dev.202.1 → 5.5.6-dev.203.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.202.1",
3
+ "version": "5.5.6-dev.203.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": {
@@ -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';