@jacebenson/jsn 5.5.8-dev.219.1 → 5.5.8-dev.220.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.8-dev.219.1",
3
+ "version": "5.5.8-dev.220.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": {
@@ -4,6 +4,7 @@ import crypto from 'node:crypto';
4
4
  import { isDeepStrictEqual } from 'node:util';
5
5
  import { execFileSync } from 'node:child_process';
6
6
  import { globalConfigDir } from '../config.js';
7
+ import { windowsCredentialOperation, legacyWindowsKey } from './windows-credential-store.js';
7
8
 
8
9
  // ─── Credential key helpers ───
9
10
 
@@ -52,7 +53,10 @@ function warnPlaintext() {
52
53
  process.stderr.write('Warning: plaintext credential storage explicitly enabled for this process; credentials are portable and backups can expose them.\n');
53
54
  }
54
55
  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.`);
56
+ const repair = process.platform === 'win32'
57
+ ? 'Windows Credential Manager requires Windows PowerShell 5.1 or PowerShell 7+ with FullLanguage/Add-Type and native API access allowed by policy.'
58
+ : 'Unlock/install secret-tool and retry.';
59
+ return storageError(`Secure credential storage unavailable or readback failed. ${repair} 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.`);
56
60
  }
57
61
 
58
62
  // Validate broad ancestors without chmod: only the leaf secret directory must
@@ -145,16 +149,18 @@ export function removePrivateState(kind, key) {
145
149
 
146
150
  // ─── Keyring via secret-tool (libsecret, same backend as Go's go-keyring) ───
147
151
 
148
- function keyringLookup(key) {
152
+ function keyringLookup(key, legacyKey) {
149
153
  try {
150
154
  // execFileSync with an arg array — no shell, so `key` can never
151
155
  // break out into command injection (issue #143 finding #2).
152
- const result = execFileSync(
156
+ const result = process.platform === 'win32'
157
+ ? (windowsCredentialOperation('read', key) ?? (legacyKey ? windowsCredentialOperation('read', legacyKey) : null))
158
+ : execFileSync(
153
159
  'secret-tool',
154
160
  ['lookup', KEYRING_ATTR_SERVICE, KEYRING_SERVICE, KEYRING_ATTR_USERNAME, key],
155
161
  { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf-8' }
156
162
  );
157
- const trimmed = result.trim();
163
+ const trimmed = result?.trim();
158
164
  if (!trimmed) return null;
159
165
  const parsed = JSON.parse(trimmed);
160
166
  // Spread all fields from keyring first, then normalize known fields
@@ -168,7 +174,10 @@ function keyringLookup(key) {
168
174
  created_at: parsed.created_at || parsed.CreatedAt || 0,
169
175
  auth_source: parsed.auth_method === 'gck' ? 'gck' : 'keyring',
170
176
  };
171
- } catch {
177
+ } catch (error) {
178
+ if (process.platform === 'win32' && !plaintextAllowed()) {
179
+ throw error.code === 'credential_storage_error' ? error : refusal();
180
+ }
172
181
  return null;
173
182
  }
174
183
  }
@@ -188,6 +197,12 @@ function keyringStore(key, creds) {
188
197
  }
189
198
 
190
199
  function storeVerified(key, creds) {
200
+ if (process.platform === 'win32') {
201
+ const value = JSON.stringify(creds);
202
+ windowsCredentialOperation('write', key, value);
203
+ const readback = windowsCredentialOperation('read', key);
204
+ return isDeepStrictEqual(JSON.parse(readback), JSON.parse(value));
205
+ }
191
206
  if (!keyringStore(key, creds)) return false;
192
207
  try {
193
208
  const value = execFileSync('secret-tool',
@@ -198,6 +213,11 @@ function storeVerified(key, creds) {
198
213
  }
199
214
 
200
215
  function keyringDelete(key) {
216
+ if (process.platform === 'win32') {
217
+ windowsCredentialOperation('delete', key);
218
+ if (windowsCredentialOperation('read', key) !== null) throw refusal();
219
+ return;
220
+ }
201
221
  try {
202
222
  execFileSync(
203
223
  'secret-tool',
@@ -219,7 +239,7 @@ function keyringDelete(key) {
219
239
  export function loadCredentials(instance, username, injectedStore) {
220
240
  if (injectedStore) return injectedStore.load(instance, username);
221
241
  const key = username ? credKey(instance, username) : credKey(instance);
222
- const keyringCreds = keyringLookup(key);
242
+ const keyringCreds = keyringLookup(key, !username ? legacyWindowsKey(instance) : undefined);
223
243
  if (keyringCreds) {
224
244
  return {
225
245
  ...keyringCreds,
@@ -248,12 +268,16 @@ export function saveCredentials(instance, creds, username, injectedStore) {
248
268
  const key = username ? credKey(instance, username) : credKey(instance);
249
269
  // Stamp last_seen on every credential save
250
270
  creds.last_seen = creds.last_seen || Math.floor(Date.now() / 1000);
251
- if (storeVerified(key, creds)) {
271
+ let verified = false;
272
+ let secureFailure;
273
+ try { verified = storeVerified(key, creds); }
274
+ catch (error) { secureFailure = error.code === 'credential_storage_error' ? error : refusal(); }
275
+ if (verified) {
252
276
  // Retire only this identity, and only after exact secure-store readback.
253
277
  removePrivateState('credentials', key);
254
278
  return;
255
279
  }
256
- if (!plaintextAllowed()) throw refusal();
280
+ if (!plaintextAllowed()) throw secureFailure || refusal();
257
281
  warnPlaintext();
258
282
  writePrivateState('credentials', key, creds);
259
283
  }
@@ -265,6 +289,7 @@ export function deleteCredentials(instance, username, injectedStore) {
265
289
  if (injectedStore) return injectedStore.delete(instance, username);
266
290
  const key = username ? credKey(instance, username) : credKey(instance);
267
291
  keyringDelete(key);
292
+ if (process.platform === 'win32' && !username) keyringDelete(legacyWindowsKey(instance));
268
293
  removePrivateState('credentials', key);
269
294
  }
270
295
 
@@ -0,0 +1,85 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const helper = fileURLToPath(new URL('./windows-credential-store.ps1', import.meta.url));
6
+ const reasons = {
7
+ unsupported: 'Windows PowerShell 5.1 or PowerShell 7+ on Windows is required.',
8
+ capability: 'PowerShell FullLanguage, Add-Type and the Windows Credential Manager native API must be permitted by system policy.',
9
+ policy: 'PowerShell execution policy explicitly restricts embedded credential operations. Ask your administrator for an approved storage route; no alternate host or plaintext fallback is selected automatically.',
10
+ oversized: 'Credential exceeds the Windows Credential Manager single-entry limit (2560 UTF-8 bytes); existing credentials were not replaced.',
11
+ native: 'Windows Credential Manager operation failed; check vault access and system policy.',
12
+ };
13
+ const stages = new Set([
14
+ 'host_check', 'language_mode', 'machine_policy_query', 'user_policy_query',
15
+ 'process_policy_query', 'current_user_policy_query', 'local_machine_policy_query',
16
+ 'input_encoding', 'output_encoding', 'native_compilation', 'request_decode',
17
+ 'native_read', 'native_write', 'native_delete',
18
+ ]);
19
+ function failure(reason, stage) {
20
+ const safeStage = stages.has(stage) ? stage : undefined;
21
+ const diagnostic = safeStage ? ` Stage: ${safeStage}.` : '';
22
+ const error = new Error(`Secure credential storage unavailable or readback failed. ${reason}${diagnostic} Existing plaintext credentials are preserved. No plaintext fallback is enabled automatically.`);
23
+ error.code = 'credential_storage_error';
24
+ if (safeStage) error.storageStage = safeStage;
25
+ return error;
26
+ }
27
+
28
+ // A process boundary injectable for offline tests; production never accepts a
29
+ // script/executable override from configuration or credential content.
30
+ export function windowsCredentialOperation(operation, key, value, run = execFileSync) {
31
+ if (!['read', 'write', 'delete'].includes(operation)) throw failure(reasons.native);
32
+ if (operation === 'write' && Buffer.byteLength(value, 'utf8') > 2560) throw failure(reasons.oversized);
33
+ const input = JSON.stringify({ operation, target: `servicenow-cli:${key}`, username: key, value });
34
+ let command;
35
+ try {
36
+ // Trusted installed code only. Command text is identical for every request;
37
+ // neither request data nor a caller-supplied script path enters the source.
38
+ // EncodedCommand is UTF-16LE on both supported PowerShell hosts.
39
+ command = Buffer.from(readFileSync(helper, 'utf8'), 'utf16le').toString('base64');
40
+ } catch { throw failure(reasons.capability); }
41
+ for (const executable of ['powershell.exe', 'pwsh.exe']) {
42
+ const env = { ...process.env };
43
+ if (executable === 'powershell.exe') {
44
+ // PS7 normalizes PSModulePath only for a directly launched PS5.1 child,
45
+ // not PS7 -> Node -> PS5.1. Let Windows PowerShell construct its own
46
+ // default module paths instead of autoloading incompatible PS7 modules.
47
+ // Preserve every other variable, including execution-policy preferences.
48
+ for (const key of Object.keys(env)) if (key.toUpperCase() === 'PSMODULEPATH') delete env[key];
49
+ }
50
+ let output;
51
+ try {
52
+ output = run(executable, ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', command], {
53
+ input, env, encoding: 'utf8', timeout: 20000, maxBuffer: 1024 * 1024,
54
+ windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'],
55
+ });
56
+ } catch (error) {
57
+ // Never expose child stdout/stderr, exception message or input. In
58
+ // particular policy/parser errors can quote the source or request.
59
+ if (error.code === 'ENOENT') continue;
60
+ throw failure(reasons.capability);
61
+ }
62
+ let response;
63
+ try { response = JSON.parse(output.replace(/^\uFEFF/, '')); }
64
+ catch { throw failure(reasons.capability); }
65
+ // Only an explicit unsupported host/version (or ENOENT above) permits
66
+ // discovery of another host. Never retry policy/capability/native denial.
67
+ if (response?.status === 'error' && response.reason === 'unsupported') continue;
68
+ if (response?.status === 'missing' && operation !== 'write') return null;
69
+ if (response?.status !== 'ok') throw failure(reasons[response?.reason] || reasons.native, response?.stage);
70
+ if (operation === 'read') {
71
+ if (typeof response.value !== 'string') throw failure(reasons.native);
72
+ return response.value;
73
+ }
74
+ return true;
75
+ }
76
+ throw failure(reasons.unsupported);
77
+ }
78
+
79
+ // Go v1 used normalizeURL(instance), not the sanitized file name. Only
80
+ // username-less legacy profiles may consult that identity: never borrow an
81
+ // instance-wide credential for a different named account.
82
+ export function legacyWindowsKey(instance) {
83
+ const trimmed = instance.replace(/\/$/, '');
84
+ return /^https?:\/\//.test(trimmed) ? trimmed : `https://${trimmed}`;
85
+ }
@@ -0,0 +1,163 @@
1
+ # Static command text: all request data (including secrets) arrives on stdin.
2
+ # See GLOSSARY.md, Windows credential helper, for the policy contract.
3
+ $ErrorActionPreference = 'Stop'
4
+ $ProgressPreference = 'SilentlyContinue'
5
+ $stage = 'host_check'
6
+ function Reply($status, $reason, $value) {
7
+ # Stage is assigned only from literals below; never emit exception/source,
8
+ # compiler diagnostics, paths, request data or environment values.
9
+ $result = @{ status = $status; reason = $reason; value = $value; stage = $stage }
10
+ [Console]::Out.Write(($result | ConvertTo-Json -Compress))
11
+ }
12
+ try {
13
+ if ($PSVersionTable.PSVersion -lt [Version]'5.1' -or
14
+ ($PSVersionTable.PSEdition -eq 'Core' -and $PSVersionTable.PSVersion.Major -lt 7) -or
15
+ [Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) {
16
+ Reply 'error' 'unsupported' $null
17
+ exit 0
18
+ }
19
+ $stage = 'language_mode'
20
+ if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') {
21
+ Reply 'error' 'capability' $null
22
+ exit 0
23
+ }
24
+ # Restricted with all scopes Undefined is the stock Windows client default:
25
+ # it permits individual command text, unlike -File. Never modify any scope.
26
+ # Refuse ALL explicitly configured enterprise policy, including RemoteSigned:
27
+ # embedded text cannot establish the original script's zone/signature status.
28
+ foreach ($scope in @('MachinePolicy', 'UserPolicy')) {
29
+ $stage = if ($scope -eq 'MachinePolicy') { 'machine_policy_query' } else { 'user_policy_query' }
30
+ $policy = [string](Microsoft.PowerShell.Security\Get-ExecutionPolicy -Scope $scope -ErrorAction Stop)
31
+ if ($policy -ne 'Undefined') {
32
+ Reply 'error' 'policy' $null
33
+ exit 0
34
+ }
35
+ }
36
+ # Also honor explicit local/session Restricted or AllSigned. Fail closed on
37
+ # unknown policy values. No Set-ExecutionPolicy, environment or registry writes.
38
+ foreach ($scope in @('Process', 'CurrentUser', 'LocalMachine')) {
39
+ $stage = switch ($scope) {
40
+ 'Process' { 'process_policy_query' }
41
+ 'CurrentUser' { 'current_user_policy_query' }
42
+ 'LocalMachine' { 'local_machine_policy_query' }
43
+ }
44
+ $policy = [string](Microsoft.PowerShell.Security\Get-ExecutionPolicy -Scope $scope -ErrorAction Stop)
45
+ if ($policy -notin @('Undefined', 'RemoteSigned', 'Unrestricted', 'Bypass')) {
46
+ Reply 'error' 'policy' $null
47
+ exit 0
48
+ }
49
+ }
50
+ $stage = 'input_encoding'
51
+ [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
52
+ $stage = 'output_encoding'
53
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
54
+ $stage = 'native_compilation'
55
+ Add-Type -TypeDefinition @'
56
+ using System;
57
+ using System.Runtime.InteropServices;
58
+ using System.Text;
59
+ public static class JsnCredentialNative {
60
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
61
+ public struct Credential {
62
+ public uint Flags;
63
+ public uint Type;
64
+ public string TargetName;
65
+ public string Comment;
66
+ public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
67
+ public uint CredentialBlobSize;
68
+ public IntPtr CredentialBlob;
69
+ public uint Persist;
70
+ public uint AttributeCount;
71
+ public IntPtr Attributes;
72
+ public string TargetAlias;
73
+ public string UserName;
74
+ }
75
+ [DllImport("advapi32.dll", EntryPoint="CredReadW", CharSet=CharSet.Unicode, SetLastError=true)]
76
+ private static extern bool NativeRead(string target, uint type, uint flags, out IntPtr credential);
77
+ [DllImport("advapi32.dll", EntryPoint="CredWriteW", CharSet=CharSet.Unicode, SetLastError=true)]
78
+ public static extern bool Write(ref Credential credential, uint flags);
79
+ [DllImport("advapi32.dll", EntryPoint="CredDeleteW", CharSet=CharSet.Unicode, SetLastError=true)]
80
+ private static extern bool NativeDelete(string target, uint type, uint flags);
81
+ [DllImport("advapi32.dll", EntryPoint="CredFree")]
82
+ public static extern void Free(IntPtr credential);
83
+ public class ReadResult {
84
+ public int Error;
85
+ public string Value;
86
+ }
87
+ public static ReadResult ReadCredential(string target) {
88
+ IntPtr pointer;
89
+ bool success = NativeRead(target, 1, 0, out pointer);
90
+ int error = Marshal.GetLastWin32Error();
91
+ if (!success) return new ReadResult { Error = error };
92
+ try { return new ReadResult { Error = 0, Value = ReadValue(pointer) }; }
93
+ finally { Free(pointer); }
94
+ }
95
+ public static int DeleteCredential(string target) {
96
+ bool success = NativeDelete(target, 1, 0);
97
+ int error = Marshal.GetLastWin32Error();
98
+ return success ? 0 : error;
99
+ }
100
+ private static string ReadValue(IntPtr pointer) {
101
+ Credential c = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential));
102
+ byte[] bytes = new byte[c.CredentialBlobSize];
103
+ Marshal.Copy(c.CredentialBlob, bytes, 0, bytes.Length);
104
+ return new UTF8Encoding(false, true).GetString(bytes);
105
+ }
106
+ public static bool WriteValue(string target, string username, string value) {
107
+ byte[] bytes = new UTF8Encoding(false, true).GetBytes(value);
108
+ if (bytes.Length > 2560) throw new ArgumentException();
109
+ IntPtr pointer = Marshal.AllocHGlobal(bytes.Length);
110
+ try {
111
+ Marshal.Copy(bytes, 0, pointer, bytes.Length);
112
+ Credential c = new Credential();
113
+ c.Type = 1; c.TargetName = target; c.UserName = username;
114
+ c.Persist = 2; c.CredentialBlobSize = (uint)bytes.Length; c.CredentialBlob = pointer;
115
+ return Write(ref c, 0);
116
+ } finally {
117
+ for (int i = 0; i < bytes.Length; i++) Marshal.WriteByte(pointer, i, 0);
118
+ Marshal.FreeHGlobal(pointer);
119
+ Array.Clear(bytes, 0, bytes.Length);
120
+ }
121
+ }
122
+ }
123
+ '@
124
+ } catch {
125
+ Reply 'error' 'capability' $null
126
+ exit 0
127
+ }
128
+ try {
129
+ $stage = 'request_decode'
130
+ $request = [Console]::In.ReadToEnd() | ConvertFrom-Json
131
+ if ($request.target -isnot [string] -or !$request.target.StartsWith('servicenow-cli:') -or
132
+ $request.target.Length -gt 32767 -or $request.target.Contains([char]0)) {
133
+ Reply 'error' 'native' $null
134
+ exit 0
135
+ }
136
+ switch ($request.operation) {
137
+ 'write' {
138
+ $stage = 'native_write'
139
+ if ($request.value -isnot [string] -or [Text.Encoding]::UTF8.GetByteCount($request.value) -gt 2560) {
140
+ Reply 'error' 'oversized' $null
141
+ } elseif ([JsnCredentialNative]::WriteValue($request.target, $request.username, $request.value)) {
142
+ Reply 'ok' $null $null
143
+ } else { Reply 'error' 'native' $null }
144
+ }
145
+ 'read' {
146
+ $stage = 'native_read'
147
+ $result = [JsnCredentialNative]::ReadCredential($request.target)
148
+ if ($result.Error -eq 0) { Reply 'ok' $null $result.Value }
149
+ elseif ($result.Error -eq 1168) { Reply 'missing' $null $null }
150
+ else { Reply 'error' 'native' $null }
151
+ }
152
+ 'delete' {
153
+ $stage = 'native_delete'
154
+ $errorCode = [JsnCredentialNative]::DeleteCredential($request.target)
155
+ if ($errorCode -eq 0) { Reply 'ok' $null $null }
156
+ elseif ($errorCode -eq 1168) { Reply 'missing' $null $null }
157
+ else { Reply 'error' 'native' $null }
158
+ }
159
+ default { Reply 'error' 'native' $null }
160
+ }
161
+ } catch {
162
+ Reply 'error' 'native' $null
163
+ }