@jacebenson/jsn 5.5.8 → 5.5.9-dev.222.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/auth/credential-store.js +33 -8
- package/src/auth/windows-credential-store.js +85 -0
- package/src/auth/windows-credential-store.ps1 +163 -0
- package/src/command-families.js +1 -1
- package/src/commands/subscriptions.js +11 -1
- package/src/subscription-evidence.js +276 -0
package/package.json
CHANGED
|
@@ -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
|
-
|
|
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 =
|
|
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
|
|
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
|
-
|
|
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
|
+
}
|
package/src/command-families.js
CHANGED
|
@@ -33,7 +33,7 @@ declareCapabilities('midservers', { mutationContext: 'operational', mutationSubc
|
|
|
33
33
|
export const midserversCmd = wrap => ({ ...midserversCmdDefinition, load: () => require('./commands/midservers.js').midserversCmd(wrap) });
|
|
34
34
|
|
|
35
35
|
export const subscriptionsCmdDefinition = {
|
|
36
|
-
command: 'subscriptions [subcommand]', describe: 'Inspect local
|
|
36
|
+
command: 'subscriptions [subcommand]', describe: 'Inspect subscription evidence, local schedules and illustrative ITOM populations',
|
|
37
37
|
};
|
|
38
38
|
declareCapabilities('subscriptions', { noInstance: true, skipDailyChecks: true, mutationSubcommands: [] });
|
|
39
39
|
export const subscriptionsCmd = wrap => ({ ...subscriptionsCmdDefinition, load: () => require('./commands/subscriptions.js').subscriptionsCmd(wrap) });
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { subscriptionsCmdDefinition } from '../command-families.js';
|
|
2
|
+
import { subscriptionEvidence, formatSubscriptionEvidence, evidenceLimit } from '../subscription-evidence.js';
|
|
2
3
|
import { refreshSchedules } from '../schedule-cache.js';
|
|
3
4
|
import { loadSchedule, scheduleCatalog, scheduleSnapshot, formatSchedule, estimateSubscription, formatEstimate } from '../subscriptions.js';
|
|
4
5
|
|
|
@@ -22,7 +23,16 @@ export function subscriptionsCmd(wrap) {
|
|
|
22
23
|
};
|
|
23
24
|
return {
|
|
24
25
|
...subscriptionsCmdDefinition,
|
|
25
|
-
builder: y => y.command({ command: '
|
|
26
|
+
builder: y => y.command({ command: 'evidence', describe: 'Show subscription evidence and installed-app hints (read-only)',
|
|
27
|
+
builder: b => b.option('limit', { type: 'number', default: 50, describe: 'Maximum observations per source (integer 1–200)' }),
|
|
28
|
+
handler: wrap(async (argv, app) => {
|
|
29
|
+
const limit = evidenceLimit(argv.limit);
|
|
30
|
+
app.requireInstance();
|
|
31
|
+
const report = await subscriptionEvidence(app.sdk, { limit });
|
|
32
|
+
Object.defineProperty(report, '_formatted', { value: formatSubscriptionEvidence(report) });
|
|
33
|
+
app.ok(report, { summary: 'Bounded instance evidence; contractual authority and completeness unverified' });
|
|
34
|
+
}),
|
|
35
|
+
}).command({ command: 'refresh', describe: 'Explicitly download and validate schedule catalog; retain last-good on failure', builder: b => b.option('manifest-url', { type: 'string' }), handler: wrap(async (argv, app) => {
|
|
26
36
|
const origin = process.env.JSN_DOCS_URL || app.config?.docs?.url;
|
|
27
37
|
const manifest = argv.manifestUrl || process.env.JSN_SCHEDULES_MANIFEST_URL || app.config?.docs?.schedule_manifest_url || (origin ? new URL('/subscription-schedules/v1/manifest.json', origin).href : undefined);
|
|
28
38
|
const provenance = await refreshSchedules(manifest);
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { AppError, errUsage } from './errors.js';
|
|
2
|
+
import { inventorySources, readInventory } from './instance-inventory.js';
|
|
3
|
+
import { MAX_SESSION_REPLAYS } from './session-recovery.js';
|
|
4
|
+
|
|
5
|
+
const candidates = {
|
|
6
|
+
entitlements: ['license_details', 'subscription_entitlement'],
|
|
7
|
+
allocation: ['subscription_detail', 'account_subscription_entitlement', 'instance_subscription_entitlement'],
|
|
8
|
+
consumption: ['itom_lu_ci_counts', 'usageanalytics_count', 'itom_lu_licensable_cis'],
|
|
9
|
+
};
|
|
10
|
+
const limits = { metadata_requests: 96, data_requests: 16, inheritance_depth: 16, dictionary_rows: 200 };
|
|
11
|
+
const namePattern = /^[a-zA-Z0-9_]+$/;
|
|
12
|
+
const idPattern = /^[a-f0-9]{32}$/i;
|
|
13
|
+
const raw = value => value && typeof value === 'object' ? value.value : value;
|
|
14
|
+
const text = value => typeof raw(value) === 'string' ? raw(value) : '';
|
|
15
|
+
const fail = reason => { throw new AppError(reason, 'Evidence source unavailable.'); };
|
|
16
|
+
const numeric = ['integer', 'longint', 'decimal', 'float', 'numeric'];
|
|
17
|
+
const strings = ['string', 'choice'];
|
|
18
|
+
const dates = ['glide_date', 'glide_date_time'];
|
|
19
|
+
// Field names are a conservative projection vocabulary, not a product meter or
|
|
20
|
+
// a claim that any particular subscription table implements these fields.
|
|
21
|
+
const fields = {
|
|
22
|
+
product_name: strings, product_code: strings, sku: strings,
|
|
23
|
+
license_type: strings, subscription_type: strings, unit: strings,
|
|
24
|
+
status: [...strings, 'integer'], state: [...strings, 'integer'],
|
|
25
|
+
active: ['boolean'], is_latest: ['boolean'],
|
|
26
|
+
quantity: numeric, purchased_quantity: numeric, allocated_quantity: numeric,
|
|
27
|
+
allocated: numeric, used: numeric, consumption: numeric, count: numeric,
|
|
28
|
+
ci_count: numeric, licensable_count: numeric,
|
|
29
|
+
sample_date: dates, start_date: dates, end_date: dates, effective_date: dates,
|
|
30
|
+
sys_updated_on: dates,
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export function evidenceLimit(value = 50) {
|
|
34
|
+
if (!Number.isInteger(value) || value < 1 || value > 200) throw errUsage('--limit must be an integer from 1 to 200.');
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function reason(error) {
|
|
39
|
+
if (error?.status === 401 || error?.code === 'auth_error') throw new AppError('auth_error', 'Authentication failed while reading subscription evidence.');
|
|
40
|
+
if (error?.status === 403 || error?.code === 'forbidden') return 'forbidden';
|
|
41
|
+
if (error?.status === 404) return 'missing-or-hidden';
|
|
42
|
+
return ['malformed', 'schema-unavailable', 'metadata-cap', 'inheritance-limit', 'request-budget', 'ambiguous-schema'].includes(error?.code) ? error.code : 'unavailable';
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function safeValue(value, type) {
|
|
46
|
+
value = raw(value);
|
|
47
|
+
if (value === null || value === undefined || value === '') return null;
|
|
48
|
+
if (numeric.includes(type)) return /^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(String(value)) && Number.isFinite(Number(value)) ? String(value) : null;
|
|
49
|
+
if (type === 'boolean') return value === true || value === 'true' || value === '1' ? true : value === false || value === 'false' || value === '0' ? false : null;
|
|
50
|
+
if (dates.includes(type)) return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z?)?$/.test(value) ? value : null;
|
|
51
|
+
// Do not emit reference display values, URLs, emails, sys_ids, free-form
|
|
52
|
+
// descriptions, or control characters. Product/status labels remain observations.
|
|
53
|
+
return typeof value === 'string' && /^[\w ()+.,:/-]{1,120}$/.test(value)
|
|
54
|
+
&& !/https?:|www\.|[a-f0-9]{32}/i.test(value) ? value : null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// The inventory's single installed-tab page is a known read-only POST, not a
|
|
58
|
+
// general exception to GET-only evidence reads. Match its exact URL and payload
|
|
59
|
+
// before bypassing the SDK's method-based readOnly guard; retain no-touch auth.
|
|
60
|
+
export async function requestSubscriptionEvidence(sdk, endpoint, options = {}) {
|
|
61
|
+
const method = options.method || 'GET';
|
|
62
|
+
const installedURL = `${sdk.baseURL}/api/sn_appclient/appmanager/apps?${new URLSearchParams({ tab_context: 'installed', sysparm_limit: '200', sysparm_offset: '0' })}`;
|
|
63
|
+
const installedDiscovery = method === 'POST' && endpoint === installedURL && options.body === '{}'
|
|
64
|
+
&& Object.keys(options).every(key => key === 'method' || key === 'body');
|
|
65
|
+
const url = new URL(endpoint);
|
|
66
|
+
const tableRead = method === 'GET' && url.origin === new URL(sdk.baseURL).origin
|
|
67
|
+
&& !url.username && !url.password && !url.hash && /^\/api\/now\/(table|stats)\/[a-zA-Z0-9_]+$/.test(url.pathname);
|
|
68
|
+
if (!tableRead && !installedDiscovery) fail('unsafe-evidence-request');
|
|
69
|
+
return sdk.request(endpoint, { ...options, method, readOnly: !installedDiscovery, touchLastSeen: false, timeout: 10000 });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function subscriptionEvidence(sdk, { limit = 50 } = {}) {
|
|
73
|
+
evidenceLimit(limit);
|
|
74
|
+
const requests = { metadata: 0, data: 0 };
|
|
75
|
+
const cache = new Map();
|
|
76
|
+
async function request(kind, endpoint, options = {}) {
|
|
77
|
+
const cap = limits[`${kind}_requests`];
|
|
78
|
+
if (requests[kind] >= cap) fail('request-budget');
|
|
79
|
+
requests[kind]++;
|
|
80
|
+
try { return await requestSubscriptionEvidence(sdk, endpoint, options); }
|
|
81
|
+
catch (error) {
|
|
82
|
+
const code = reason(error);
|
|
83
|
+
throw new AppError(code, 'Evidence source unavailable.', '', code === 'forbidden' ? 403 : code === 'missing-or-hidden' ? 404 : 0);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
async function rows(kind, table, query, projection, cap) {
|
|
87
|
+
const params = new URLSearchParams({ sysparm_query: query, sysparm_fields: projection.join(','), sysparm_limit: String(cap), sysparm_display_value: 'false', sysparm_exclude_reference_link: 'true' });
|
|
88
|
+
const response = await request(kind, `${sdk.baseURL}/api/now/table/${table}?${params}`);
|
|
89
|
+
if (!Array.isArray(response?.result) || response.result.length > cap || response.result.some(r => !r || typeof r !== 'object' || Array.isArray(r))) fail('malformed');
|
|
90
|
+
return response.result;
|
|
91
|
+
}
|
|
92
|
+
function metadata(table, query, projection, cap) {
|
|
93
|
+
const key = `${table}:${query}`;
|
|
94
|
+
if (!cache.has(key)) cache.set(key, rows('metadata', table, query, projection, cap));
|
|
95
|
+
return cache.get(key);
|
|
96
|
+
}
|
|
97
|
+
async function schema(table) {
|
|
98
|
+
const selected = new Map(), references = [], visited = new Set();
|
|
99
|
+
let query = `name=${table}`;
|
|
100
|
+
for (let depth = 0; depth < limits.inheritance_depth; depth++) {
|
|
101
|
+
const definitions = await metadata('sys_db_object', query, ['sys_id', 'name', 'super_class'], 2);
|
|
102
|
+
if (!definitions.length) fail('schema-unavailable');
|
|
103
|
+
if (definitions.length !== 1) fail('ambiguous-schema');
|
|
104
|
+
const definition = definitions[0], name = text(definition.name), parent = text(definition.super_class);
|
|
105
|
+
if (!namePattern.test(name) || (depth === 0 && name !== table) || visited.has(name)
|
|
106
|
+
|| !idPattern.test(text(definition.sys_id)) || typeof raw(definition.super_class) !== 'string') fail('malformed');
|
|
107
|
+
visited.add(name);
|
|
108
|
+
const dictionary = await metadata('sys_dictionary', `name=${name}^elementISNOTEMPTY^ORDERBYelement`, ['name', 'element', 'internal_type', 'reference'], limits.dictionary_rows + 1);
|
|
109
|
+
if (dictionary.length > limits.dictionary_rows) fail('metadata-cap');
|
|
110
|
+
const local = new Set();
|
|
111
|
+
for (const row of dictionary) {
|
|
112
|
+
const element = text(row.element), type = text(row.internal_type), target = text(row.reference);
|
|
113
|
+
if (text(row.name) !== name || !namePattern.test(element) || !namePattern.test(type) || local.has(element)
|
|
114
|
+
|| !Object.hasOwn(row, 'reference') || typeof raw(row.reference) !== 'string') fail('malformed');
|
|
115
|
+
local.add(element);
|
|
116
|
+
if (selected.has(element)) continue;
|
|
117
|
+
if (target && !namePattern.test(target)) fail('malformed');
|
|
118
|
+
selected.set(element, { type, reference: target });
|
|
119
|
+
if (target) references.push({ table: name, field: element, target });
|
|
120
|
+
}
|
|
121
|
+
if (!parent) return { fields: selected, references, hierarchy: [...visited] };
|
|
122
|
+
if (!idPattern.test(parent)) fail('malformed');
|
|
123
|
+
query = `sys_id=${parent}`;
|
|
124
|
+
}
|
|
125
|
+
fail('inheritance-limit');
|
|
126
|
+
}
|
|
127
|
+
const capturedAt = new Date().toISOString();
|
|
128
|
+
const report = {
|
|
129
|
+
captured_at: capturedAt, authoritative: false,
|
|
130
|
+
limitations: [
|
|
131
|
+
'Provider-visible instance evidence only; not purchased rights, contract validity, compliance, billable seats or bills.',
|
|
132
|
+
'Installed apps/plugins are possibilities and hints only. Nonproduction installs do not prove production deployment or bills. Environment and production status are not detected.',
|
|
133
|
+
'No subscription-to-app joins, cross-source totals, SKU applicability, meters or 90-day averages are inferred. Source field labels do not establish charging semantics.',
|
|
134
|
+
'Missing/forbidden sources are unavailable, not zero. Successful empty results mean no visible rows, not absence of rights or use. ACL visibility and snapshot consistency are unknown.',
|
|
135
|
+
],
|
|
136
|
+
entitlements: [], allocation: [], consumption: [],
|
|
137
|
+
access: { source: 'sys_user_has_role', status: 'unavailable', reason: 'SDK aggregate supports count and groupBy, not a bounded distinct-user aggregate; role assignments are not allocated or billable seats. No user-role rows were fetched.' },
|
|
138
|
+
installed_hints: [],
|
|
139
|
+
request_budget: {
|
|
140
|
+
limits: { ...limits }, used: requests,
|
|
141
|
+
http_attempt_ceiling: { metadata: limits.metadata_requests * (1 + MAX_SESSION_REPLAYS), data: limits.data_requests * (1 + MAX_SESSION_REPLAYS) },
|
|
142
|
+
scope: 'Collector SDK dispatch caps and API HTTP attempt ceilings including bounded SDK session replay; authentication bootstrap/refresh is separate. Each API attempt has a 10-second timeout.',
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
function source(table) {
|
|
146
|
+
return { source: table, observed_at: capturedAt, status: 'unavailable', reason: null, observations: null,
|
|
147
|
+
freshness: { collection: capturedAt, source_updated_on: 'unknown; collection time is not source freshness' },
|
|
148
|
+
coverage: { complete: false, limit, truncated: null, visibility: 'provider-visible only; no completeness claim' } };
|
|
149
|
+
}
|
|
150
|
+
for (const [section, tables] of Object.entries(candidates)) for (const table of tables) {
|
|
151
|
+
const result = source(table);
|
|
152
|
+
report[section].push(result);
|
|
153
|
+
try {
|
|
154
|
+
const info = await schema(table);
|
|
155
|
+
const projection = [...info.fields].filter(([name, field]) => fields[name]?.includes(field.type) && !field.reference).map(([name]) => name);
|
|
156
|
+
result.schema = { status: 'verified-visible', hierarchy: info.hierarchy, fields: projection.map(name => ({ name, type: info.fields.get(name).type })), references: info.references };
|
|
157
|
+
if (!projection.length) fail('schema-unavailable');
|
|
158
|
+
const latest = table === 'subscription_detail' && projection.includes('is_latest');
|
|
159
|
+
result.query = `${latest ? 'is_latest=true^' : ''}ORDERBYsys_id`;
|
|
160
|
+
if (table === 'subscription_detail') result.latest_filter = latest ? 'verified boolean is_latest=true' : 'unavailable; current/latest allocation is not established';
|
|
161
|
+
const page = await rows('data', table, result.query, projection, limit + 1);
|
|
162
|
+
result.observations = page.slice(0, limit).map(row => Object.fromEntries(projection.map(name => [name, safeValue(row[name], info.fields.get(name).type)])));
|
|
163
|
+
result.status = page.length ? 'observed' : 'no-visible-rows';
|
|
164
|
+
result.coverage.truncated = page.length > limit;
|
|
165
|
+
result.coverage.returned = result.observations.length;
|
|
166
|
+
result.freshness.source_updated_on = projection.includes('sys_updated_on') ? 'Per-row sys_updated_on where visible and valid; not a source-wide freshness guarantee' : 'unavailable; no verified update timestamp';
|
|
167
|
+
} catch (error) { result.reason = reason(error); }
|
|
168
|
+
}
|
|
169
|
+
// Existing inventory readers preserve installation evidence and provider count
|
|
170
|
+
// uncertainty. The same schema gate applies before their known projections.
|
|
171
|
+
const verifiedInventoryFields = new Map();
|
|
172
|
+
const inventorySDK = {
|
|
173
|
+
baseURL: sdk.baseURL,
|
|
174
|
+
request: (endpoint, options) => request('data', endpoint, options),
|
|
175
|
+
listStrict: async (table, params, options) => {
|
|
176
|
+
const safeParams = new URLSearchParams(params);
|
|
177
|
+
safeParams.set('sysparm_fields', safeParams.get('sysparm_fields').split(',').filter(name => verifiedInventoryFields.get(table)?.has(name)).join(','));
|
|
178
|
+
const response = await request('data', `${sdk.baseURL}/api/now/table/${table}?${safeParams}`, options);
|
|
179
|
+
if (!Array.isArray(response?.result)) fail('malformed');
|
|
180
|
+
return response.result;
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
for (const kind of ['store', 'plugins']) {
|
|
184
|
+
const descriptor = inventorySources[kind], result = source(descriptor.table);
|
|
185
|
+
result.kind = kind;
|
|
186
|
+
report.installed_hints.push(result);
|
|
187
|
+
try {
|
|
188
|
+
const info = await schema(descriptor.table);
|
|
189
|
+
if (descriptor.fields.some(name => !info.fields.has(name) || info.fields.get(name).reference)) fail('schema-unavailable');
|
|
190
|
+
verifiedInventoryFields.set(descriptor.table, new Set([...info.fields].filter(([, field]) => !field.reference).map(([name]) => name)));
|
|
191
|
+
result.schema = { status: 'verified-visible', hierarchy: info.hierarchy, fields: descriptor.fields.map(name => ({ name, type: info.fields.get(name).type })) };
|
|
192
|
+
const inventory = await readInventory(inventorySDK, kind, 1);
|
|
193
|
+
if (inventory.coverage.reason === 'auth_error') fail('auth_error');
|
|
194
|
+
result.provider_coverage = inventory.coverage;
|
|
195
|
+
result.coverage.returned = Math.min(inventory.items.size, limit);
|
|
196
|
+
result.coverage.truncated = inventory.items.size > limit || inventory.coverage.status !== 'complete';
|
|
197
|
+
result.status = inventory.items.size ? 'observed' : inventory.coverage.status === 'complete' ? 'no-visible-rows' : 'unavailable';
|
|
198
|
+
result.reason = inventory.coverage.reason;
|
|
199
|
+
result.observations = result.status === 'unavailable' ? null : [...inventory.items.values()].slice(0, limit).map(item => ({
|
|
200
|
+
name: safeValue(item.name, 'string'), version: safeValue(item.version, 'string'), active: item.active,
|
|
201
|
+
...(kind === 'store' ? { installed: item.installed, installation_evidence: item.installation_evidence } : { installation_evidence: 'platform plugin state; activation is not purchased entitlement' }),
|
|
202
|
+
}));
|
|
203
|
+
result.freshness.source_updated_on = 'unavailable; observed inventory state, not deployment history';
|
|
204
|
+
} catch (error) { result.reason = reason(error); }
|
|
205
|
+
}
|
|
206
|
+
return report;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const sourceTitles = {
|
|
210
|
+
license_details: 'Subscription forms', subscription_entitlement: 'Subscription entitlements',
|
|
211
|
+
subscription_detail: 'Allocation observations', account_subscription_entitlement: 'Account allocation',
|
|
212
|
+
instance_subscription_entitlement: 'Instance allocation', itom_lu_ci_counts: 'ITOM CI counts',
|
|
213
|
+
usageanalytics_count: 'Usage analytics', itom_lu_licensable_cis: 'ITOM licensable CI observations',
|
|
214
|
+
sys_store_app: 'Store applications', v_plugin: 'Platform plugins',
|
|
215
|
+
};
|
|
216
|
+
const fieldLabels = {
|
|
217
|
+
product_name: 'Product', name: 'Name',
|
|
218
|
+
product_code: 'Product code', sku: 'SKU', license_type: 'License type', subscription_type: 'Subscription type',
|
|
219
|
+
unit: 'Unit', status: 'Status', state: 'State', active: 'Active', is_latest: 'Latest',
|
|
220
|
+
quantity: 'Quantity', purchased_quantity: 'Purchased quantity', allocated_quantity: 'Allocated quantity',
|
|
221
|
+
allocated: 'Allocated', used: 'Used', consumption: 'Consumption', count: 'Count', ci_count: 'CI count',
|
|
222
|
+
licensable_count: 'Licensable count', sample_date: 'Sample date', start_date: 'Start date',
|
|
223
|
+
end_date: 'End date', effective_date: 'Effective date', sys_updated_on: 'Updated', version: 'Version',
|
|
224
|
+
installed: 'Installed', installation_evidence: 'Install evidence',
|
|
225
|
+
};
|
|
226
|
+
const humanReasons = {
|
|
227
|
+
forbidden: 'access denied', 'missing-or-hidden': 'missing or hidden', 'schema-unavailable': 'schema unavailable',
|
|
228
|
+
malformed: 'incomplete or invalid response', 'metadata-cap': 'metadata limit reached',
|
|
229
|
+
'inheritance-limit': 'schema ancestry limit reached', 'request-budget': 'request limit reached',
|
|
230
|
+
'ambiguous-schema': 'ambiguous schema', page_limit_no_provider_total: 'no provider total; bounded page only',
|
|
231
|
+
};
|
|
232
|
+
const humanValue = value => value === null || value === undefined ? 'Unavailable'
|
|
233
|
+
: value === true ? 'Yes' : value === false ? 'No'
|
|
234
|
+
: value === 'appclient_installed_tab' ? 'Observed in installed Store tab'
|
|
235
|
+
: value === 'local_version_and_install_date' ? 'Local version and install date'
|
|
236
|
+
: value === 'platform plugin state; activation is not purchased entitlement' ? 'Plugin state, not purchased entitlement'
|
|
237
|
+
: String(value);
|
|
238
|
+
|
|
239
|
+
export function formatSubscriptionEvidence(report) {
|
|
240
|
+
const lines = ['Subscription evidence', `Observed: ${report.captured_at}`,
|
|
241
|
+
'Source observations only. Not a contract, compliance verdict, billable seats or bills.',
|
|
242
|
+
'Installed apps/plugins are possibilities, not proof of purchased rights.',
|
|
243
|
+
'Nonproduction installs do not prove production deployment or bills.',
|
|
244
|
+
'No environment detection, cross-source totals, licensing meters or 90-day averages.',
|
|
245
|
+
'Missing data is unavailable, not zero. Empty reads mean no visible rows.'];
|
|
246
|
+
for (const [section, title] of [
|
|
247
|
+
['entitlements', 'Entitlement evidence'], ['allocation', 'Allocation evidence'],
|
|
248
|
+
['consumption', 'Consumption evidence'], ['installed_hints', 'Installed app and plugin hints'],
|
|
249
|
+
]) {
|
|
250
|
+
lines.push('', title, '-'.repeat(title.length));
|
|
251
|
+
for (const source of report[section]) {
|
|
252
|
+
lines.push('', sourceTitles[source.source] || source.source);
|
|
253
|
+
if (source.status === 'unavailable') lines.push(` Unavailable: ${humanReasons[source.reason] || 'source could not be read'}.`);
|
|
254
|
+
else if (source.status === 'no-visible-rows') lines.push(' No visible rows.');
|
|
255
|
+
else if (source.reason) lines.push(` Note: ${humanReasons[source.reason] || source.reason.replaceAll('_', ' ')}.`);
|
|
256
|
+
for (const [index, row] of (source.observations || []).entries()) {
|
|
257
|
+
lines.push(` ${row.product_name || row.name || `Observation ${index + 1}`}`);
|
|
258
|
+
for (const [key, value] of Object.entries(row)) {
|
|
259
|
+
if ((key === 'product_name' || key === 'name') && value) continue;
|
|
260
|
+
const label = fieldLabels[key] || key.replaceAll('_', ' ');
|
|
261
|
+
lines.push(` ${label.padEnd(19)} ${humanValue(value)}`);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
lines.push(` Source: ${source.source}`);
|
|
265
|
+
const shown = source.coverage.returned === undefined ? 'not established' : `${source.coverage.returned} shown`;
|
|
266
|
+
const more = source.coverage.truncated === true ? '; more rows may exist' : '';
|
|
267
|
+
lines.push(` Coverage: ${shown}, limit ${source.coverage.limit}${more}; completeness unknown.`);
|
|
268
|
+
lines.push(` Freshness: ${source.freshness.source_updated_on.startsWith('Per-row') ? 'See Updated values; source-wide freshness unknown.' : 'Not established.'}`);
|
|
269
|
+
if (source.latest_filter) lines.push(` Latest allocation: ${source.latest_filter.startsWith('verified') ? 'latest rows only (is_latest=true).' : 'not established.'}`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
lines.push('', 'Access evidence', '---------------', 'Unavailable: bounded distinct-user aggregation is not supported by this SDK.',
|
|
273
|
+
'No user-role rows fetched. Role assignments are not allocated or billable seats.',
|
|
274
|
+
`Source: ${report.access.source} (not queried).`);
|
|
275
|
+
return lines.join('\n');
|
|
276
|
+
}
|