@jacebenson/jsn 5.5.7-dev.212.1 → 5.5.7-dev.213.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.7-dev.212.1",
3
+ "version": "5.5.7-dev.213.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": {
package/src/cli.js CHANGED
@@ -79,6 +79,7 @@ import { b4rulesCmd } from './commands/b4rules.js';
79
79
  import { atfCmd } from './commands/atf.js';
80
80
  import { scanCmd } from './commands/scan.js';
81
81
  import { storeCmd } from './commands/store.js';
82
+ import { subscriptionsCmd } from './commands/subscriptions.js';
82
83
  import { approvalsCmd } from './commands/approvals.js';
83
84
  import { perfCmd } from './commands/perf.js';
84
85
  import { customizationsCmd } from './commands/customizations.js';
@@ -444,6 +445,7 @@ export function buildCLI() {
444
445
  .command(atfCmd(wrap))
445
446
  .command(scanCmd(wrap))
446
447
  .command(storeCmd(wrap))
448
+ .command(subscriptionsCmd(wrap))
447
449
  .command(approvalsCmd(wrap))
448
450
  .command(skippedUpdatesCmd(wrap))
449
451
  .command(perfCmd(wrap))
@@ -0,0 +1,47 @@
1
+ import { refreshSchedules } from '../schedule-cache.js';
2
+ import { declareCapabilities } from '../capabilities.js';
3
+ import { loadSchedule, scheduleCatalog, scheduleSnapshot, formatSchedule, estimateSubscription, formatEstimate } from '../subscriptions.js';
4
+
5
+ declareCapabilities('subscriptions', { noInstance: true, skipDailyChecks: true, mutationSubcommands: [] });
6
+ export function subscriptionsCmd(wrap) {
7
+ const local = (argv, app) => {
8
+ const snapshot = scheduleSnapshot();
9
+ const schedules = scheduleCatalog({ product: argv.product, sku: argv.sku, id: argv.id, snapshot });
10
+ const data = { provenance: snapshot.provenance, schedules, coverage: { index_documents: new Set(snapshot.schedules.map(s => s.source_url)).size, archive: 'unavailable', sku_mapping: 'only explicitly normalized codes; empty results do not establish absence of rights' } };
11
+ Object.defineProperty(data, '_formatted', { value: [
12
+ `Local catalog snapshot (${data.provenance.source}; ${data.provenance.freshness}; revision ${data.provenance.revision || 'bundled'}; retrieved ${data.provenance.retrieved_at || 'bundled'}; stale ${data.provenance.stale}); contractual applicability unverified. Archive unavailable.`,
13
+ ...schedules.flatMap(s => [
14
+ `${s.id} | ${s.product} | ${s.effective_date || s.source_version || 'date unverified'} | ${s.normalization_status || 'not specified'}`,
15
+ s.source_url,
16
+ `Measurement: ${s.measurement || 'not specified; inspection only'}. SKU mapping: ${(s.skus || []).join(', ') || 'unverified'}`,
17
+ ...(s.unknowns || s.limitations || []),
18
+ ...(argv.id ? [formatSchedule(s)] : []),
19
+ ]),
20
+ ].join('\n') });
21
+ app.ok(data, { summary: 'Local dated metering schedules, not purchased rights' });
22
+ };
23
+ return {
24
+ command: 'subscriptions [subcommand]', describe: 'Inspect local metering schedules and compare illustrative ITOM populations',
25
+ builder: y => y.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
+ const origin = process.env.JSN_DOCS_URL || app.config?.docs?.url;
27
+ 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
+ const provenance = await refreshSchedules(manifest);
29
+ app.ok({ provenance }, { summary: 'Validated schedule cache refreshed' });
30
+ }) }).command({ command: 'schedules', describe: 'Inspect validated cache or bundled source-backed schedules offline', builder: b => b.option('product', { type: 'string' }).option('sku', { type: 'string' }).option('id', { type: 'string' }), handler: wrap(local) })
31
+ .command({ command: 'estimate <product>', describe: 'Read-only ITOM population comparison, not billing or a 90-day meter',
32
+ builder: b => b.positional('product', { type: 'string', describe: 'ITOM; arbitrary SKUs and HRSD unsupported' })
33
+ .option('schedule', { type: 'string', describe: 'Explicit dated schedule ID from subscriptions schedules' })
34
+ .option('assume-eligible', { type: 'boolean', default: false, describe: 'Hypothetically treat mapped populations as managed and component-eligible, exclusions unknown' }),
35
+ handler: wrap(async (argv, app) => {
36
+ // Validate unsupported selections before requesting an instance.
37
+ const selected = loadSchedule(argv.schedule);
38
+ if (String(argv.product).toUpperCase() !== 'ITOM' || selected.measurement !== 'illustrative-population') await estimateSubscription(null, argv.product, { schedule: argv.schedule });
39
+ app.requireInstance();
40
+ const report = await estimateSubscription(app.sdk, argv.product, { schedule: argv.schedule, assumeEligible: argv.assumeEligible });
41
+ Object.defineProperty(report, '_formatted', { value: formatEstimate(report) });
42
+ app.ok(report, { summary: 'Incomplete illustrative ITOM population comparison; no authoritative total' });
43
+ }),
44
+ }),
45
+ handler: wrap(local),
46
+ };
47
+ }
@@ -0,0 +1,96 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { cacheDir } from './config.js';
5
+ import { AppError } from './errors.js';
6
+
7
+ const MAX = 4 * 1024 * 1024;
8
+ const digest = bytes => createHash('sha256').update(bytes).digest('hex');
9
+ const fail = message => { throw new AppError('invalid_catalog', message); };
10
+ const file = () => path.join(cacheDir(), 'subscription-schedules-v1.json');
11
+ const hash = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
12
+ export function validateCatalog(catalog) {
13
+ const checkDepth = (value, depth = 0) => {
14
+ if (depth > 32) fail('Catalog nesting exceeds schema limit.');
15
+ if (value && typeof value === 'object') for (const child of Object.values(value)) checkDepth(child, depth + 1);
16
+ };
17
+ checkDepth(catalog);
18
+ if (catalog?.schema_version !== 1 || !hash(catalog.revision) || !Array.isArray(catalog.schedules) || !catalog.schedules.length) fail('Invalid catalog schema.');
19
+ const ids = new Set();
20
+ for (const r of catalog.schedules) {
21
+ if (!r || typeof r.id !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(r.id) || ids.has(r.id) || typeof r.product !== 'string' || !r.product.trim()) fail('Invalid or duplicate schedule ID/product.');
22
+ ids.add(r.id);
23
+ for (const key of ['title', 'source_version', 'effective_date', 'applicability', 'measurement', 'normalization_status']) {
24
+ if (r[key] !== undefined && r[key] !== null && typeof r[key] !== 'string') fail(`Invalid record ${key}.`);
25
+ }
26
+ for (const key of ['source_sections', 'skus', 'unknowns', 'exceptions', 'limitations']) {
27
+ if (r[key] !== undefined && (!Array.isArray(r[key]) || r[key].some(v => typeof v !== 'string'))) fail(`Invalid record ${key}.`);
28
+ }
29
+ if (r.definitions !== undefined && (!r.definitions || typeof r.definitions !== 'object')) fail('Invalid definitions.');
30
+ if (Array.isArray(r.definitions) && r.definitions.some(d => !d || typeof d.term !== 'string' || typeof d.definition !== 'string' || !Array.isArray(d.source_sections) || d.source_sections.some(v => typeof v !== 'string'))) fail('Invalid definition provenance.');
31
+ if (r.meter !== undefined && (!r.meter || typeof r.meter !== 'object' || Array.isArray(r.meter))) fail('Invalid meter.');
32
+ if (r.meter?.rules !== undefined && (!Array.isArray(r.meter.rules) || r.meter.rules.some(v => !v || typeof v !== 'object' || Array.isArray(v)))) fail('Invalid meter rules.');
33
+ for (const key of ['packages', 'entitlements', 'section_coverage', 'capability_lists']) {
34
+ if (r[key] !== undefined && (!r[key] || typeof r[key] !== 'object')) fail(`Invalid record ${key}.`);
35
+ }
36
+ let source;
37
+ try { source = new URL(r.source_url); } catch { fail('Missing source provenance.'); }
38
+ if (source.protocol !== 'https:' || source.hostname !== 'www.servicenow.com' || source.username || source.password || !source.pathname.endsWith('.pdf') || !Number.isFinite(Date.parse(r.retrieved_at || r.fetched_at))) fail('Unsafe or missing source provenance.');
39
+ if (r.id !== 'itom-2026-04-09' && (!Array.isArray(r.source_sections) || !r.source_sections.length || !Array.isArray(r.skus) || !['normalized', 'partial'].includes(r.normalization_status))) fail('Invalid normalized record schema.');
40
+ }
41
+ return catalog;
42
+ }
43
+ function safeURL(value, origin) {
44
+ let u;
45
+ try { u = new URL(value); } catch { fail('Invalid catalog URL.'); }
46
+ if (u.username || u.password || u.hash || (u.protocol !== 'https:' && !(u.protocol === 'http:' && ['127.0.0.1', '[::1]', 'localhost'].includes(u.hostname))) || (origin && u.origin !== origin)) fail('Catalog URL must use HTTPS and the approved manifest origin (explicit loopback HTTP is allowed).');
47
+ return u;
48
+ }
49
+ async function download(url, cap) {
50
+ const response = await fetch(url, { redirect: 'error', signal: AbortSignal.timeout(10000), credentials: 'omit' });
51
+ if (!response.ok) fail(`Catalog HTTP ${response.status}.`);
52
+ if (Number(response.headers.get('content-length')) > cap) fail('Catalog exceeds size cap.');
53
+ const chunks = []; let size = 0;
54
+ for await (const chunk of response.body) {
55
+ size += chunk.length;
56
+ if (size > cap) { fail('Catalog exceeds size cap.'); }
57
+ chunks.push(chunk);
58
+ }
59
+ return Buffer.concat(chunks);
60
+ }
61
+ export async function refreshSchedules(manifestURL) {
62
+ if (!manifestURL) fail('Specify --manifest-url or configure JSN_DOCS_URL / global docs.url.');
63
+ const url = safeURL(manifestURL);
64
+ const manifest = JSON.parse(await download(url, 16384));
65
+ if (manifest.schema_version !== 1 || !hash(manifest.revision) || !hash(manifest.sha256) || !Number.isSafeInteger(manifest.bytes) || manifest.bytes < 1 || manifest.bytes > MAX || !Number.isFinite(Date.parse(manifest.published_at))) fail('Invalid manifest schema or size.');
66
+ const artifactURL = safeURL(manifest.catalog_url, url.origin);
67
+ const bytes = await download(artifactURL, MAX);
68
+ if (bytes.length !== manifest.bytes || digest(bytes) !== manifest.sha256) fail('Catalog byte length or SHA256 mismatch.');
69
+ const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
70
+ const catalog = validateCatalog(JSON.parse(text));
71
+ if (catalog.revision !== manifest.revision) fail('Catalog revision mismatch.');
72
+ const entry = { manifest, manifest_url: url.href, retrieved_at: new Date().toISOString(), artifact: text };
73
+ const serialized = JSON.stringify(entry);
74
+ if (Buffer.byteLength(serialized) > MAX * 2) fail('Serialized cache exceeds size cap.');
75
+ fs.mkdirSync(path.dirname(file()), { recursive: true, mode: 0o700 });
76
+ const temp = `${file()}.${randomUUID()}.tmp`;
77
+ try { fs.writeFileSync(temp, serialized, { mode: 0o600, flag: 'wx' }); fs.renameSync(temp, file()); }
78
+ finally { fs.rmSync(temp, { force: true }); }
79
+ return cachedSchedules().provenance;
80
+ }
81
+ export function cachedSchedules() {
82
+ try {
83
+ if (fs.statSync(file()).size > MAX * 2) return null;
84
+ const entry = JSON.parse(fs.readFileSync(file(), 'utf8'));
85
+ const m = entry.manifest;
86
+ if (m?.schema_version !== 1 || !hash(m.revision) || !hash(m.sha256) || !Number.isSafeInteger(m.bytes) || m.bytes < 1 || m.bytes > MAX || !Number.isFinite(Date.parse(m.published_at))) return null;
87
+ const approved = safeURL(entry.manifest_url);
88
+ safeURL(m.catalog_url, approved.origin);
89
+ if (typeof entry.artifact !== 'string') return null;
90
+ const bytes = Buffer.from(entry.artifact);
91
+ if (bytes.length > MAX || bytes.length !== entry.manifest.bytes || digest(bytes) !== entry.manifest.sha256) return null;
92
+ const catalog = validateCatalog(JSON.parse(bytes));
93
+ if (catalog.revision !== entry.manifest.revision || !Number.isFinite(Date.parse(entry.retrieved_at))) return null;
94
+ return { schedules: catalog.schedules, provenance: { source: 'validated-cache', revision: catalog.revision, sha256: entry.manifest.sha256, retrieved_at: entry.retrieved_at, manifest_url: entry.manifest_url, stale: Date.now() - Date.parse(entry.retrieved_at) > 86400000, freshness: 'last-good snapshot; no network freshness check' } };
95
+ } catch { return null; }
96
+ }
@@ -0,0 +1,121 @@
1
+ {
2
+ "id": "itom-2026-04-09",
3
+ "product": "ITOM",
4
+ "effective_for_skus_introduced": "2026-04-09",
5
+ "source_url": "https://www.servicenow.com/content/dam/servicenow-assets/public/en-us/doc-type/legal/it-operations-management-itom-servicenow-subscription-unit-overview.pdf",
6
+ "source_version": "Effective for SKUs introduced on April 9, 2026; sections 1.1 and 1.2",
7
+ "fetched_at": "2026-11-19T07:47:54.276651+00:00",
8
+ "retrieval": "Independent web_extract PDF text retrieval; direct download returned 403. Binary hash unavailable.",
9
+ "categories": [
10
+ {
11
+ "id": "server",
12
+ "resources_per_su": 1,
13
+ "classes": [
14
+ "cmdb_ci_server",
15
+ "cmdb_ci_vm_instance",
16
+ "cmdb_ci_ucs_rack_unit",
17
+ "cmdb_ci_ucs_blade",
18
+ "cmdb_ci_mainframe_hardware"
19
+ ]
20
+ },
21
+ {
22
+ "id": "paas",
23
+ "resources_per_su": 3,
24
+ "classes": [
25
+ "cmdb_ci_cloud_appserver",
26
+ "cmdb_ci_could_database",
27
+ "cmdb_ci_dynamodb_table",
28
+ "cmdb_ci_cloud_directory",
29
+ "cmdb_ci_cloud_gateway",
30
+ "cmdb_ci_cloud_messaging_service",
31
+ "cmdb_ci_cloud_webserver"
32
+ ]
33
+ },
34
+ {
35
+ "id": "container",
36
+ "resources_per_su": 10,
37
+ "classes": [
38
+ "cmdb_ci_oslv_container"
39
+ ]
40
+ },
41
+ {
42
+ "id": "image",
43
+ "resources_per_su": 3,
44
+ "classes": [
45
+ "cmdb_ci_oslv_image",
46
+ "cmdb_ci_oslv_local_image",
47
+ "cmdb_ci_openshift_images"
48
+ ]
49
+ },
50
+ {
51
+ "id": "end_user_device",
52
+ "resources_per_su": 4,
53
+ "classes": [
54
+ "cmdb_ci_computer"
55
+ ]
56
+ },
57
+ {
58
+ "id": "faas",
59
+ "resources_per_su": 20,
60
+ "classes": [
61
+ "cmdb_ci_cloud_function"
62
+ ]
63
+ },
64
+ {
65
+ "id": "gpu",
66
+ "resources_per_su": 1,
67
+ "classes": [
68
+ "cmdb_ci_gpu"
69
+ ]
70
+ },
71
+ {
72
+ "id": "api",
73
+ "resources_per_su": 1,
74
+ "classes": [
75
+ "cmdb_ci_api"
76
+ ]
77
+ },
78
+ {
79
+ "id": "ai_agent",
80
+ "resources_per_su": 3,
81
+ "classes": [
82
+ "cmdb_ci_function_ai"
83
+ ]
84
+ },
85
+ {
86
+ "id": "service_instance",
87
+ "resources_per_su": 1,
88
+ "classes": [
89
+ "cmdb_ci_service_auto"
90
+ ]
91
+ },
92
+ {
93
+ "id": "unresolved_object",
94
+ "resources_per_su": 4,
95
+ "classes": []
96
+ }
97
+ ],
98
+ "definitions": {
99
+ "provenance": "Paraphrases of section 1.1, not independent eligibility rules. All CI resource types must be represented in the listed classes or descendants and managed by an ITOM application.",
100
+ "server": "Physical or virtual server.",
101
+ "paas": "Cloud-based platform service.",
102
+ "container": "Operating system-level virtualization.",
103
+ "image": "Operating system-level virtualization image.",
104
+ "end_user_device": "Physical or virtual computing device not defined as another Managed IT Resource Type, with an ITOM component such as Agent Client Collector installed.",
105
+ "faas": "Serverless compute function-as-a-service instance.",
106
+ "gpu": "Graphics Processing Unit.",
107
+ "api": "Application programming interface.",
108
+ "ai_agent": "Service for machine learning, data processing and AI-driven tasks.",
109
+ "service_instance": "Interconnected applications and IT resources configured to offer a digital service.",
110
+ "unresolved_object": "IT resource receiving an ITOM event, performance metric or log, not represented as a CMDB CI; recorded in em_unique_nodes with type=unknown. Counting this source is unsupported in this slice."
111
+ },
112
+ "unresolved_mapping": "cmdb_ci_could_database is literal source text; no corrected mapping is assumed.",
113
+ "limitations": [
114
+ "CMDB populations are not managed or billable counts, nor a ceiling.",
115
+ "Managed-by-ITOM eligibility and product scope are unverified.",
116
+ "End-user devices require an installed ITOM component and exclusion of other resource types.",
117
+ "Container/image relationship exclusions are not evaluated.",
118
+ "Rounding and contract applicability are unknown.",
119
+ "Observed 90-day usage and purchased entitlements are not implemented."
120
+ ]
121
+ }