@jacebenson/jsn 5.5.6-dev.202.1 → 5.5.6-dev.204.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 +1 -1
- package/src/amb.js +15 -0
- package/src/app.js +4 -1
- package/src/auth/credential-store.js +131 -32
- package/src/auth/oauth.js +4 -28
- package/src/auth/transport.js +22 -0
- package/src/auth.js +22 -2
- package/src/config.js +18 -0
- package/src/midserver-install.js +3 -0
- package/src/sdk.js +9 -2
- package/src/session.js +6 -1
package/package.json
CHANGED
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
|
@@ -12,7 +12,7 @@ import { AuthManager } from './auth.js';
|
|
|
12
12
|
import { createAuthRecovery } from './auth-recovery.js';
|
|
13
13
|
import { SDKClient } from './sdk.js';
|
|
14
14
|
import { OutputWriter, FormatAuto, FormatJSON, FormatMarkdown, FormatQuiet, FormatStyled, hyperlink } from './output.js';
|
|
15
|
-
import { saveConfig } from './config.js';
|
|
15
|
+
import { saveConfig, isTrustedCredentialDestination } from './config.js';
|
|
16
16
|
import { resolveSession, applySession, contextFromSession, requireSessionInstance } from './session.js';
|
|
17
17
|
import { getCurrentUser, getCurrentApplication, getCurrentUpdateSet } from './context.js';
|
|
18
18
|
import { errUsage, errAuth } from './errors.js';
|
|
@@ -43,6 +43,9 @@ export class App {
|
|
|
43
43
|
getUsername: () => this.session?.username || null,
|
|
44
44
|
getEffectiveInstance: () => this.session?.instance || '',
|
|
45
45
|
getAuthMethod: () => this.session?.profile?.auth_method || null,
|
|
46
|
+
isTrustedCredentialDestination: instance => isTrustedCredentialDestination(this.config, instance,
|
|
47
|
+
this._authArgv?.instance || this._sessionArgv?.instance || (this.session?.profileExplicit ? '' : this.session?.override),
|
|
48
|
+
this.session?.profileExplicit ? this.session.profileName : ''),
|
|
46
49
|
});
|
|
47
50
|
|
|
48
51
|
if (this.session.instance) {
|
|
@@ -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
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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:
|
|
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
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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
|
-
|
|
153
|
-
|
|
154
|
-
|
|
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
|
-
|
|
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 {
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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);
|
|
@@ -433,7 +443,11 @@ export class AuthManager {
|
|
|
433
443
|
*/
|
|
434
444
|
async loginWithPassword(instanceURL, username = this._activeUsername(), suppliedCredentials) {
|
|
435
445
|
instanceURL = normalizeInstanceURL(instanceURL);
|
|
446
|
+
assertCredentialTransport(instanceURL);
|
|
436
447
|
const envCreds = getBasicAuthFromEnv(instanceURL);
|
|
448
|
+
if (!suppliedCredentials && envCreds && this.identity.isTrustedCredentialDestination?.(instanceURL) === false) {
|
|
449
|
+
throw errAuth('Project configuration cannot authorize an ambient credential destination. Select --instance explicitly or save the origin in global configuration.');
|
|
450
|
+
}
|
|
437
451
|
const storedCreds = this.loadCredentials(instanceURL, username);
|
|
438
452
|
const creds = suppliedCredentials
|
|
439
453
|
? { auth_method: 'basic', ...suppliedCredentials }
|
|
@@ -464,6 +478,7 @@ export class AuthManager {
|
|
|
464
478
|
}
|
|
465
479
|
|
|
466
480
|
async loginWithBrowser(instanceURL, options = {}, username = this._activeUsername()) {
|
|
481
|
+
assertCredentialTransport(normalizeInstanceURL(instanceURL));
|
|
467
482
|
if (options.launch) {
|
|
468
483
|
const { launchBrowserSession } = await import('./browser-launch.js');
|
|
469
484
|
const credentials = await launchBrowserSession(instanceURL, {
|
|
@@ -486,6 +501,7 @@ export class AuthManager {
|
|
|
486
501
|
|
|
487
502
|
async _verifyBrowserSession(instanceURL, creds, username, { requireIdentity = false, signal, timeout = this.httpClient.timeout } = {}) {
|
|
488
503
|
instanceURL = normalizeInstanceURL(instanceURL);
|
|
504
|
+
assertCredentialTransport(instanceURL);
|
|
489
505
|
const query = new URLSearchParams({
|
|
490
506
|
sysparm_limit: '1',
|
|
491
507
|
sysparm_fields: 'user_name',
|
|
@@ -547,6 +563,7 @@ export class AuthManager {
|
|
|
547
563
|
}
|
|
548
564
|
|
|
549
565
|
async exchangeCode(instanceURL, clientID, code, pkce) {
|
|
566
|
+
assertCredentialTransport(instanceURL);
|
|
550
567
|
const tokenURL = `${instanceURL.replace(/\/$/, '')}/oauth_token.do`;
|
|
551
568
|
const body = new URLSearchParams();
|
|
552
569
|
body.set('grant_type', 'authorization_code');
|
|
@@ -556,6 +573,7 @@ export class AuthManager {
|
|
|
556
573
|
body.set('code_verifier', pkce.code_verifier);
|
|
557
574
|
|
|
558
575
|
const resp = await fetch(tokenURL, {
|
|
576
|
+
redirect: 'error',
|
|
559
577
|
method: 'POST',
|
|
560
578
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
561
579
|
body: body.toString(),
|
|
@@ -580,6 +598,7 @@ export class AuthManager {
|
|
|
580
598
|
}
|
|
581
599
|
|
|
582
600
|
async refreshToken(instance, creds, targetUsername = undefined) {
|
|
601
|
+
assertCredentialTransport(instance);
|
|
583
602
|
if (creds.auth_method !== 'oauth') {
|
|
584
603
|
throw errAuth(`Cannot refresh ${creds.auth_method || 'unconfigured'} credentials; only OAuth credentials support refresh`);
|
|
585
604
|
}
|
|
@@ -591,6 +610,7 @@ export class AuthManager {
|
|
|
591
610
|
body.set('refresh_token', creds.refresh_token);
|
|
592
611
|
|
|
593
612
|
const resp = await fetch(tokenURL, {
|
|
613
|
+
redirect: 'error',
|
|
594
614
|
method: 'POST',
|
|
595
615
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
596
616
|
body: body.toString(),
|
package/src/config.js
CHANGED
|
@@ -101,6 +101,12 @@ export function loadConfig(overrides = {}) {
|
|
|
101
101
|
const cfg = createConfig();
|
|
102
102
|
|
|
103
103
|
loadFromFile(cfg, globalConfigPath(), 'global');
|
|
104
|
+
// Preserve provenance outside the serializable/user-controlled config shape.
|
|
105
|
+
// A project can select an origin, but cannot authorize ambient secrets for it.
|
|
106
|
+
Object.defineProperty(cfg, 'credentialTrust', { value: {
|
|
107
|
+
profiles: structuredClone(cfg.profiles),
|
|
108
|
+
origin: normalizeInstanceURL(getEffectiveInstance(cfg)),
|
|
109
|
+
} });
|
|
104
110
|
loadFromFile(cfg, localConfigPath(), 'local');
|
|
105
111
|
loadFromEnv(cfg);
|
|
106
112
|
|
|
@@ -123,6 +129,18 @@ export function loadConfig(overrides = {}) {
|
|
|
123
129
|
return cfg;
|
|
124
130
|
}
|
|
125
131
|
|
|
132
|
+
export function isTrustedCredentialDestination(cfg, instance, explicitInstance = '', explicitProfile = '') {
|
|
133
|
+
const origin = normalizeInstanceURL(instance);
|
|
134
|
+
// Hand-built configs are a programmatic API, not project-file input.
|
|
135
|
+
if (!cfg?.credentialTrust) return true;
|
|
136
|
+
const selectedProfile = explicitProfile && Object.hasOwn(cfg.credentialTrust.profiles, explicitProfile)
|
|
137
|
+
? cfg.credentialTrust.profiles[explicitProfile]?.instance_url : '';
|
|
138
|
+
// Bind ambient secrets to the global default, not every saved account.
|
|
139
|
+
// Only explicit process selectors may opt into another saved origin.
|
|
140
|
+
const binding = explicitInstance || selectedProfile || process.env.SERVICENOW_INSTANCE_URL || cfg.credentialTrust.origin;
|
|
141
|
+
return Boolean(binding) && normalizeInstanceURL(binding) === origin;
|
|
142
|
+
}
|
|
143
|
+
|
|
126
144
|
export function saveConfig(cfg) {
|
|
127
145
|
const dir = globalConfigDir();
|
|
128
146
|
fs.mkdirSync(dir, { recursive: true, mode: 0o750 });
|
package/src/midserver-install.js
CHANGED
|
@@ -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/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';
|
|
@@ -206,6 +207,7 @@ export class SDKClient {
|
|
|
206
207
|
timeout = this.timeout, prepare, skipOAuthSession = false, normalizeErrors = false,
|
|
207
208
|
allowMutationReplay = false, stateful = false,
|
|
208
209
|
}, consume = (response) => response) {
|
|
210
|
+
assertCredentialDestination(endpoint, this.baseURL);
|
|
209
211
|
const method = String(opts.method || 'GET').toUpperCase();
|
|
210
212
|
for (let attempt = 0; attempt <= MAX_SESSION_REPLAYS; attempt++) {
|
|
211
213
|
// Headers for this attempt belong to the session as it is right now.
|
|
@@ -214,7 +216,7 @@ export class SDKClient {
|
|
|
214
216
|
let timer;
|
|
215
217
|
let rejection;
|
|
216
218
|
try {
|
|
217
|
-
const req = new Request(endpoint, { ...opts, signal: controller.signal });
|
|
219
|
+
const req = new Request(endpoint, { ...opts, redirect: 'error', signal: controller.signal });
|
|
218
220
|
if (prepare) prepare(req);
|
|
219
221
|
// Header-authenticated REST skips UI warming for OAuth/token/GCK.
|
|
220
222
|
// Basic must still check for TOTP before dispatch; internal bootstrap
|
|
@@ -297,6 +299,7 @@ export class SDKClient {
|
|
|
297
299
|
* that they still belong to the selected identity.
|
|
298
300
|
*/
|
|
299
301
|
async _verifyRecoveredSession() {
|
|
302
|
+
assertCredentialTransport(this.baseURL);
|
|
300
303
|
const params = new URLSearchParams({
|
|
301
304
|
sysparm_query: 'user_name=javascript:gs.getUserName()',
|
|
302
305
|
sysparm_fields: 'user_name', sysparm_limit: '1', sysparm_display_value: 'false',
|
|
@@ -1183,6 +1186,7 @@ export class SDKClient {
|
|
|
1183
1186
|
* is an actionable error, never a silent fallback.
|
|
1184
1187
|
*/
|
|
1185
1188
|
async ambSession() {
|
|
1189
|
+
assertCredentialTransport(this.baseURL);
|
|
1186
1190
|
if (!this.authProvider) throw errAuth('No authentication configured');
|
|
1187
1191
|
const creds = await this.authProvider.getCredentials();
|
|
1188
1192
|
if (!creds) throw errAuth('No valid credentials');
|
|
@@ -1222,19 +1226,21 @@ export class SDKClient {
|
|
|
1222
1226
|
}
|
|
1223
1227
|
|
|
1224
1228
|
async _initializeSession() {
|
|
1229
|
+
assertCredentialTransport(this.baseURL);
|
|
1225
1230
|
let challenged = false;
|
|
1226
1231
|
try {
|
|
1227
1232
|
const creds = await this.authProvider.getCredentials();
|
|
1228
1233
|
if (creds.auth_method === 'oauth') {
|
|
1229
1234
|
const cookieJar = new Map();
|
|
1230
1235
|
const login = `${this.baseURL}/angular.do?sysparm_type=get_user`;
|
|
1231
|
-
collectSetCookies(cookieJar, await fetch(new Request(login, { method: 'POST' })));
|
|
1236
|
+
collectSetCookies(cookieJar, await fetch(new Request(login, { method: 'POST', redirect: 'error' })));
|
|
1232
1237
|
const scopeEndpoint = `${this.baseURL}/api/now/table/sys_scope?sysparm_fields=sys_id%2Csys_class_name&sysparm_limit=1`;
|
|
1233
1238
|
collectSetCookies(cookieJar, await this._fetchWithAuth(scopeEndpoint, {
|
|
1234
1239
|
method: 'GET',
|
|
1235
1240
|
headers: serializeCookies(cookieJar) ? { Cookie: serializeCookies(cookieJar) } : {},
|
|
1236
1241
|
}));
|
|
1237
1242
|
const finalLogin = await fetch(new Request(login, {
|
|
1243
|
+
redirect: 'error',
|
|
1238
1244
|
method: 'POST',
|
|
1239
1245
|
headers: serializeCookies(cookieJar) ? { Cookie: serializeCookies(cookieJar) } : {},
|
|
1240
1246
|
}));
|
|
@@ -1284,6 +1290,7 @@ export class SDKClient {
|
|
|
1284
1290
|
// Each network exchange, including its body, has a deadline independent of
|
|
1285
1291
|
// human code entry. The race also bounds streams that do not honor abort.
|
|
1286
1292
|
async _mfaExchange(path, options, cookieJar, consume = response => response) {
|
|
1293
|
+
assertCredentialTransport(this.baseURL);
|
|
1287
1294
|
const controller = new AbortController();
|
|
1288
1295
|
let timer;
|
|
1289
1296
|
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)
|