@onlyflows/servicenow-mcp 1.0.0 → 2.0.0

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.
Files changed (281) hide show
  1. package/.env.example +56 -0
  2. package/CHANGELOG.md +153 -0
  3. package/README.md +939 -101
  4. package/dist/auth.d.ts +88 -0
  5. package/dist/auth.d.ts.map +1 -0
  6. package/dist/auth.js +396 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/client.d.ts +111 -17
  9. package/dist/client.d.ts.map +1 -1
  10. package/dist/client.js +554 -79
  11. package/dist/client.js.map +1 -1
  12. package/dist/config.d.ts +41 -4
  13. package/dist/config.d.ts.map +1 -1
  14. package/dist/config.js +44 -34
  15. package/dist/config.js.map +1 -1
  16. package/dist/encoded-query-policy.d.ts +72 -0
  17. package/dist/encoded-query-policy.d.ts.map +1 -0
  18. package/dist/encoded-query-policy.js +409 -0
  19. package/dist/encoded-query-policy.js.map +1 -0
  20. package/dist/execution-context.d.ts +235 -0
  21. package/dist/execution-context.d.ts.map +1 -0
  22. package/dist/execution-context.js +439 -0
  23. package/dist/execution-context.js.map +1 -0
  24. package/dist/field-policy.d.ts +117 -0
  25. package/dist/field-policy.d.ts.map +1 -0
  26. package/dist/field-policy.js +1684 -0
  27. package/dist/field-policy.js.map +1 -0
  28. package/dist/http-auth.d.ts +131 -0
  29. package/dist/http-auth.d.ts.map +1 -0
  30. package/dist/http-auth.js +347 -0
  31. package/dist/http-auth.js.map +1 -0
  32. package/dist/http-entrypoint.d.ts +26 -0
  33. package/dist/http-entrypoint.d.ts.map +1 -0
  34. package/dist/http-entrypoint.js +255 -0
  35. package/dist/http-entrypoint.js.map +1 -0
  36. package/dist/http-observability.d.ts +147 -0
  37. package/dist/http-observability.d.ts.map +1 -0
  38. package/dist/http-observability.js +703 -0
  39. package/dist/http-observability.js.map +1 -0
  40. package/dist/http-request-policy.d.ts +72 -0
  41. package/dist/http-request-policy.d.ts.map +1 -0
  42. package/dist/http-request-policy.js +463 -0
  43. package/dist/http-request-policy.js.map +1 -0
  44. package/dist/http-request-signal.d.ts +12 -0
  45. package/dist/http-request-signal.d.ts.map +1 -0
  46. package/dist/http-request-signal.js +39 -0
  47. package/dist/http-request-signal.js.map +1 -0
  48. package/dist/http-runtime.d.ts +77 -0
  49. package/dist/http-runtime.d.ts.map +1 -0
  50. package/dist/http-runtime.js +1321 -0
  51. package/dist/http-runtime.js.map +1 -0
  52. package/dist/incident-journal-policy.d.ts +22 -0
  53. package/dist/incident-journal-policy.d.ts.map +1 -0
  54. package/dist/incident-journal-policy.js +115 -0
  55. package/dist/incident-journal-policy.js.map +1 -0
  56. package/dist/incident-write-policy.d.ts +20 -0
  57. package/dist/incident-write-policy.d.ts.map +1 -0
  58. package/dist/incident-write-policy.js +196 -0
  59. package/dist/incident-write-policy.js.map +1 -0
  60. package/dist/index.d.ts +14 -4
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +140 -36
  63. package/dist/index.js.map +1 -1
  64. package/dist/metadata-cache.d.ts +71 -0
  65. package/dist/metadata-cache.d.ts.map +1 -0
  66. package/dist/metadata-cache.js +397 -0
  67. package/dist/metadata-cache.js.map +1 -0
  68. package/dist/profile-admin.d.ts +64 -0
  69. package/dist/profile-admin.d.ts.map +1 -0
  70. package/dist/profile-admin.js +351 -0
  71. package/dist/profile-admin.js.map +1 -0
  72. package/dist/profile-credentials.d.ts +68 -0
  73. package/dist/profile-credentials.d.ts.map +1 -0
  74. package/dist/profile-credentials.js +329 -0
  75. package/dist/profile-credentials.js.map +1 -0
  76. package/dist/profile-manager.d.ts +187 -0
  77. package/dist/profile-manager.d.ts.map +1 -0
  78. package/dist/profile-manager.js +1026 -0
  79. package/dist/profile-manager.js.map +1 -0
  80. package/dist/record-identifier-policy.d.ts +39 -0
  81. package/dist/record-identifier-policy.d.ts.map +1 -0
  82. package/dist/record-identifier-policy.js +203 -0
  83. package/dist/record-identifier-policy.js.map +1 -0
  84. package/dist/runtime-environment.d.ts +23 -0
  85. package/dist/runtime-environment.d.ts.map +1 -0
  86. package/dist/runtime-environment.js +58 -0
  87. package/dist/runtime-environment.js.map +1 -0
  88. package/dist/server.d.ts +33 -0
  89. package/dist/server.d.ts.map +1 -0
  90. package/dist/server.js +73 -0
  91. package/dist/server.js.map +1 -0
  92. package/dist/servicenow-identifiers.d.ts +8 -0
  93. package/dist/servicenow-identifiers.d.ts.map +1 -0
  94. package/dist/servicenow-identifiers.js +22 -0
  95. package/dist/servicenow-identifiers.js.map +1 -0
  96. package/dist/setup-prompts.d.ts +7 -0
  97. package/dist/setup-prompts.d.ts.map +1 -0
  98. package/dist/setup-prompts.js +123 -0
  99. package/dist/setup-prompts.js.map +1 -0
  100. package/dist/setup.d.ts +109 -0
  101. package/dist/setup.d.ts.map +1 -0
  102. package/dist/setup.js +1903 -0
  103. package/dist/setup.js.map +1 -0
  104. package/dist/startup.d.ts +43 -0
  105. package/dist/startup.d.ts.map +1 -0
  106. package/dist/startup.js +75 -0
  107. package/dist/startup.js.map +1 -0
  108. package/dist/stdio-runtime.d.ts +106 -0
  109. package/dist/stdio-runtime.d.ts.map +1 -0
  110. package/dist/stdio-runtime.js +231 -0
  111. package/dist/stdio-runtime.js.map +1 -0
  112. package/dist/structured-query.d.ts +187 -0
  113. package/dist/structured-query.d.ts.map +1 -0
  114. package/dist/structured-query.js +503 -0
  115. package/dist/structured-query.js.map +1 -0
  116. package/dist/table-defaults.d.ts +28 -0
  117. package/dist/table-defaults.d.ts.map +1 -0
  118. package/dist/table-defaults.js +85 -0
  119. package/dist/table-defaults.js.map +1 -0
  120. package/dist/table-policy.d.ts +71 -0
  121. package/dist/table-policy.d.ts.map +1 -0
  122. package/dist/table-policy.js +290 -0
  123. package/dist/table-policy.js.map +1 -0
  124. package/dist/tool-error.d.ts +48 -0
  125. package/dist/tool-error.d.ts.map +1 -0
  126. package/dist/tool-error.js +139 -0
  127. package/dist/tool-error.js.map +1 -0
  128. package/dist/tool-table-access.d.ts +19 -0
  129. package/dist/tool-table-access.d.ts.map +1 -0
  130. package/dist/tool-table-access.js +388 -0
  131. package/dist/tool-table-access.js.map +1 -0
  132. package/dist/tools/aggregate.d.ts +22 -42
  133. package/dist/tools/aggregate.d.ts.map +1 -1
  134. package/dist/tools/aggregate.js +103 -47
  135. package/dist/tools/aggregate.js.map +1 -1
  136. package/dist/tools/all-fields-cap.d.ts +45 -0
  137. package/dist/tools/all-fields-cap.d.ts.map +1 -0
  138. package/dist/tools/all-fields-cap.js +151 -0
  139. package/dist/tools/all-fields-cap.js.map +1 -0
  140. package/dist/tools/atf.d.ts +21 -60
  141. package/dist/tools/atf.d.ts.map +1 -1
  142. package/dist/tools/atf.js +180 -116
  143. package/dist/tools/atf.js.map +1 -1
  144. package/dist/tools/attach.d.ts +31 -45
  145. package/dist/tools/attach.d.ts.map +1 -1
  146. package/dist/tools/attach.js +175 -137
  147. package/dist/tools/attach.js.map +1 -1
  148. package/dist/tools/batch.d.ts +78 -42
  149. package/dist/tools/batch.d.ts.map +1 -1
  150. package/dist/tools/batch.js +172 -68
  151. package/dist/tools/batch.js.map +1 -1
  152. package/dist/tools/catalog.d.ts +6 -0
  153. package/dist/tools/catalog.d.ts.map +1 -0
  154. package/dist/tools/catalog.js +203 -0
  155. package/dist/tools/catalog.js.map +1 -0
  156. package/dist/tools/codesearch.d.ts +14 -25
  157. package/dist/tools/codesearch.d.ts.map +1 -1
  158. package/dist/tools/codesearch.js +60 -48
  159. package/dist/tools/codesearch.js.map +1 -1
  160. package/dist/tools/create-module.d.ts +48 -0
  161. package/dist/tools/create-module.d.ts.map +1 -0
  162. package/dist/tools/create-module.js +94 -0
  163. package/dist/tools/create-module.js.map +1 -0
  164. package/dist/tools/create.d.ts +2 -38
  165. package/dist/tools/create.d.ts.map +1 -1
  166. package/dist/tools/create.js +9 -41
  167. package/dist/tools/create.js.map +1 -1
  168. package/dist/tools/delete.d.ts +13 -23
  169. package/dist/tools/delete.d.ts.map +1 -1
  170. package/dist/tools/delete.js +30 -33
  171. package/dist/tools/delete.js.map +1 -1
  172. package/dist/tools/discover.d.ts +15 -27
  173. package/dist/tools/discover.d.ts.map +1 -1
  174. package/dist/tools/discover.js +103 -60
  175. package/dist/tools/discover.js.map +1 -1
  176. package/dist/tools/get-module.d.ts +85 -0
  177. package/dist/tools/get-module.d.ts.map +1 -0
  178. package/dist/tools/get-module.js +221 -0
  179. package/dist/tools/get-module.js.map +1 -0
  180. package/dist/tools/get.d.ts +2 -51
  181. package/dist/tools/get.d.ts.map +1 -1
  182. package/dist/tools/get.js +9 -49
  183. package/dist/tools/get.js.map +1 -1
  184. package/dist/tools/handler-result.d.ts +14 -0
  185. package/dist/tools/handler-result.d.ts.map +1 -0
  186. package/dist/tools/handler-result.js +177 -0
  187. package/dist/tools/handler-result.js.map +1 -0
  188. package/dist/tools/health.d.ts +12 -15
  189. package/dist/tools/health.d.ts.map +1 -1
  190. package/dist/tools/health.js +55 -36
  191. package/dist/tools/health.js.map +1 -1
  192. package/dist/tools/incident-journal-module.d.ts +12 -0
  193. package/dist/tools/incident-journal-module.d.ts.map +1 -0
  194. package/dist/tools/incident-journal-module.js +61 -0
  195. package/dist/tools/incident-journal-module.js.map +1 -0
  196. package/dist/tools/incident-write-shared.d.ts +6 -0
  197. package/dist/tools/incident-write-shared.d.ts.map +1 -0
  198. package/dist/tools/incident-write-shared.js +64 -0
  199. package/dist/tools/incident-write-shared.js.map +1 -0
  200. package/dist/tools/index.d.ts +47 -36
  201. package/dist/tools/index.d.ts.map +1 -1
  202. package/dist/tools/index.js +795 -35
  203. package/dist/tools/index.js.map +1 -1
  204. package/dist/tools/nl.d.ts +10 -24
  205. package/dist/tools/nl.d.ts.map +1 -1
  206. package/dist/tools/nl.js +37 -147
  207. package/dist/tools/nl.js.map +1 -1
  208. package/dist/tools/profile.d.ts +37 -0
  209. package/dist/tools/profile.d.ts.map +1 -0
  210. package/dist/tools/profile.js +39 -0
  211. package/dist/tools/profile.js.map +1 -0
  212. package/dist/tools/query-module.d.ts +119 -0
  213. package/dist/tools/query-module.d.ts.map +1 -0
  214. package/dist/tools/query-module.js +324 -0
  215. package/dist/tools/query-module.js.map +1 -0
  216. package/dist/tools/query.d.ts +2 -72
  217. package/dist/tools/query.d.ts.map +1 -1
  218. package/dist/tools/query.js +8 -72
  219. package/dist/tools/query.js.map +1 -1
  220. package/dist/tools/relationships.d.ts +21 -42
  221. package/dist/tools/relationships.d.ts.map +1 -1
  222. package/dist/tools/relationships.js +70 -56
  223. package/dist/tools/relationships.js.map +1 -1
  224. package/dist/tools/result-envelope.d.ts +603 -0
  225. package/dist/tools/result-envelope.d.ts.map +1 -0
  226. package/dist/tools/result-envelope.js +767 -0
  227. package/dist/tools/result-envelope.js.map +1 -0
  228. package/dist/tools/schema-module.d.ts +64 -0
  229. package/dist/tools/schema-module.d.ts.map +1 -0
  230. package/dist/tools/schema-module.js +367 -0
  231. package/dist/tools/schema-module.js.map +1 -0
  232. package/dist/tools/schema.d.ts +2 -37
  233. package/dist/tools/schema.d.ts.map +1 -1
  234. package/dist/tools/schema.js +6 -57
  235. package/dist/tools/schema.js.map +1 -1
  236. package/dist/tools/script.d.ts +33 -27
  237. package/dist/tools/script.d.ts.map +1 -1
  238. package/dist/tools/script.js +43 -37
  239. package/dist/tools/script.js.map +1 -1
  240. package/dist/tools/syslog.d.ts +19 -46
  241. package/dist/tools/syslog.d.ts.map +1 -1
  242. package/dist/tools/syslog.js +101 -67
  243. package/dist/tools/syslog.js.map +1 -1
  244. package/dist/tools/tool-module.d.ts +143 -0
  245. package/dist/tools/tool-module.d.ts.map +1 -0
  246. package/dist/tools/tool-module.js +1095 -0
  247. package/dist/tools/tool-module.js.map +1 -0
  248. package/dist/tools/update-module.d.ts +51 -0
  249. package/dist/tools/update-module.d.ts.map +1 -0
  250. package/dist/tools/update-module.js +107 -0
  251. package/dist/tools/update-module.js.map +1 -0
  252. package/dist/tools/update.d.ts +2 -45
  253. package/dist/tools/update.d.ts.map +1 -1
  254. package/dist/tools/update.js +9 -41
  255. package/dist/tools/update.js.map +1 -1
  256. package/dist/utils.d.ts +68 -1
  257. package/dist/utils.d.ts.map +1 -1
  258. package/dist/utils.js +114 -16
  259. package/dist/utils.js.map +1 -1
  260. package/dist/version.d.ts +10 -0
  261. package/dist/version.d.ts.map +1 -0
  262. package/dist/version.js +13 -0
  263. package/dist/version.js.map +1 -0
  264. package/docs/ADDING-TOOLS.md +227 -0
  265. package/docs/CLIENT-SETUP.md +914 -0
  266. package/docs/CONTAINER-DEPLOYMENT.md +310 -0
  267. package/docs/CROSS-CLIENT-RELEASE-MATRIX.md +63 -0
  268. package/docs/ENTERPRISE-RELEASE-BOUNDARY.md +149 -0
  269. package/docs/OPERATIONS-RUNBOOK.md +383 -0
  270. package/docs/PRIVATE-CHATGPT-CONNECTIVITY.md +347 -0
  271. package/docs/PRODUCTION-SECURITY.md +368 -0
  272. package/docs/PROFILE-CREDENTIALS.md +126 -0
  273. package/docs/RELEASE-VALIDATION.md +140 -0
  274. package/docs/TESTING-OAUTH.md +101 -0
  275. package/docs/V2-MIGRATION.md +493 -0
  276. package/package.json +60 -13
  277. package/scripts/inspector.mjs +140 -0
  278. package/scripts/release-validate.mjs +201 -0
  279. package/scripts/smoke-test.mjs +274 -0
  280. package/tools/inspector/package-lock.json +3812 -0
  281. package/tools/inspector/package.json +12 -0
@@ -0,0 +1,1026 @@
1
+ "use strict";
2
+ /**
3
+ * Multi-instance profile manager for ServiceNow MCP server.
4
+ *
5
+ * Supports named profiles stored in ~/.servicenow-mcp/config.json.
6
+ * When no file exists, canonical SN_* connection values are available only
7
+ * through an explicitly named out-of-band SN_PROFILE_NAME mapping. Bare SN_*
8
+ * values never create a synthetic/default routing target.
9
+ *
10
+ * @module profiles
11
+ */
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
25
+ }) : function(o, v) {
26
+ o["default"] = v;
27
+ });
28
+ var __importStar = (this && this.__importStar) || (function () {
29
+ var ownKeys = function(o) {
30
+ ownKeys = Object.getOwnPropertyNames || function (o) {
31
+ var ar = [];
32
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
33
+ return ar;
34
+ };
35
+ return ownKeys(o);
36
+ };
37
+ return function (mod) {
38
+ if (mod && mod.__esModule) return mod;
39
+ var result = {};
40
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41
+ __setModuleDefault(result, mod);
42
+ return result;
43
+ };
44
+ })();
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.ProfileManager = void 0;
47
+ exports.instanceHostError = instanceHostError;
48
+ exports.normalizeInstanceUrl = normalizeInstanceUrl;
49
+ exports.credentialFingerprint = credentialFingerprint;
50
+ const fs = __importStar(require("fs"));
51
+ const path = __importStar(require("path"));
52
+ const os = __importStar(require("os"));
53
+ const node_crypto_1 = require("node:crypto");
54
+ const config_js_1 = require("./config.js");
55
+ const table_policy_js_1 = require("./table-policy.js");
56
+ const metadata_cache_js_1 = require("./metadata-cache.js");
57
+ const client_js_1 = require("./client.js");
58
+ const profile_credentials_js_1 = require("./profile-credentials.js");
59
+ // ── Constants ──────────────────────────────────────────────────────
60
+ const CONFIG_DIR = ".servicenow-mcp";
61
+ const CONFIG_FILE = "config.json";
62
+ const CONFIG_VERSION = 2;
63
+ const LOCK_WAIT_MS = 2_000;
64
+ const MAX_PROFILE_CONFIG_BYTES = 1024 * 1024;
65
+ const POSIX_PERMISSIONS = process.platform !== "win32";
66
+ const PROFILE_KEYS = new Set([
67
+ "instance", "username", "credential", "scope", "scope_sys_id",
68
+ "vendor_code", "description", "authType", "clientId", "clientSecret",
69
+ "grantType", "apiKey", "apiKeyHeader", "timeoutMs", "maxConcurrentRequests", "schemaCacheTtlMs",
70
+ "tableAccess", "fieldPolicy", "readableTableFields", "writableTableFields", "metadataCache",
71
+ ]);
72
+ // ── ProfileManager ─────────────────────────────────────────────────
73
+ class ProfileManager {
74
+ config;
75
+ clientCache = new Map();
76
+ configFilePath;
77
+ secretResolvers;
78
+ encryptionKeyProvider;
79
+ constructor(options = {}) {
80
+ this.configFilePath = normalizeConfigFilePath(options.configFilePath ?? path.join(os.homedir(), CONFIG_DIR, CONFIG_FILE));
81
+ const resolvers = options.secretResolvers ?? [new profile_credentials_js_1.EnvironmentSecretResolver()];
82
+ const resolverMap = new Map();
83
+ for (const resolver of resolvers) {
84
+ if (!resolver ||
85
+ typeof resolver.provider !== "string" ||
86
+ !/^[a-z][a-z0-9_-]{0,31}$/u.test(resolver.provider) ||
87
+ typeof resolver.resolve !== "function" ||
88
+ resolverMap.has(resolver.provider)) {
89
+ throw new Error("Credential resolver configuration is invalid");
90
+ }
91
+ resolverMap.set(resolver.provider, resolver);
92
+ }
93
+ this.secretResolvers = resolverMap;
94
+ this.encryptionKeyProvider =
95
+ options.encryptionKeyProvider ??
96
+ new profile_credentials_js_1.EnvironmentProfileEncryptionKeyProvider();
97
+ const fileConfig = this.loadConfigFile();
98
+ if (fileConfig) {
99
+ this.config = fileConfig;
100
+ }
101
+ else {
102
+ this.config = this.buildExplicitEnvironmentProfile();
103
+ }
104
+ }
105
+ /**
106
+ * Get a profile by its explicit configured name.
107
+ * Throws if the profile does not exist.
108
+ */
109
+ getProfile(name) {
110
+ if (!Object.hasOwn(this.config.profiles, name)) {
111
+ const available = Object.keys(this.config.profiles).join(", ");
112
+ throw new Error(`Profile "${name}" not found. Available profiles: ${available || "(none)"}`);
113
+ }
114
+ return this.config.profiles[name];
115
+ }
116
+ /**
117
+ * Resolve the credential for a profile.
118
+ * If the credential starts with "env:", reads the value from the named
119
+ * environment variable. Otherwise returns the plain string and emits
120
+ * a warning to stderr about storing credentials in plain text.
121
+ */
122
+ resolveCredential(profile) {
123
+ const { credential } = profile;
124
+ if (!credential) {
125
+ throw new Error(`Profile "${this.getProfileNameFor(profile)}" has no credential configured`);
126
+ }
127
+ return this.resolveSecret(credential, this.getProfileNameFor(profile), "credential");
128
+ }
129
+ /**
130
+ * Resolve a secret value that supports "env:VAR_NAME" indirection
131
+ * (credential, clientSecret, apiKey). Plain values are returned as-is
132
+ * with a stderr warning.
133
+ */
134
+ resolveSecret(source, profile, field) {
135
+ return (0, profile_credentials_js_1.resolveCredentialSource)(source, Object.freeze({ profile, field }), this.secretResolvers, this.encryptionKeyProvider);
136
+ }
137
+ /** List all configured profiles without selecting or activating one. */
138
+ listProfiles() {
139
+ return Object.entries(this.config.profiles).map(([name, profile]) => ({
140
+ name,
141
+ instance: profile.instance,
142
+ authType: profile.authType ?? "basic",
143
+ description: profile.description,
144
+ }));
145
+ }
146
+ /**
147
+ * Names of configured profiles that authenticate with basic auth.
148
+ * Used for the startup deprecation warning (ServiceNow's inbound
149
+ * Basic Auth restriction program). Unconfigured placeholder profiles
150
+ * (empty instance) are skipped.
151
+ */
152
+ getBasicAuthProfileNames() {
153
+ return Object.entries(this.config.profiles)
154
+ .filter(([, profile]) => (profile.authType ?? "basic") === "basic" && profile.instance)
155
+ .map(([name]) => name);
156
+ }
157
+ /**
158
+ * Return a ServiceNowClient for an explicitly named profile.
159
+ * Clients are cached per profile name -- the same instance is returned on
160
+ * subsequent calls for the same profile.
161
+ */
162
+ getClient(name, resolvedConfig) {
163
+ // The dispatcher supplies its one request-local resolution. Direct callers
164
+ // resolve here. In both cases the bounded cache is reusable only when the
165
+ // resolved authentication material is unchanged, so missing keys and
166
+ // provider-side rotations cannot be bypassed by a previously used client.
167
+ const config = resolvedConfig ?? this.getConfig(name);
168
+ const fingerprint = credentialFingerprint(config);
169
+ const cached = this.clientCache.get(name);
170
+ if (cached?.fingerprint === fingerprint)
171
+ return cached.client;
172
+ const client = new client_js_1.ServiceNowClient(config);
173
+ this.clientCache.set(name, { fingerprint, client });
174
+ return client;
175
+ }
176
+ /** Return a ServiceNowConfig for an explicitly named profile. */
177
+ getConfig(name) {
178
+ const profile = this.getProfile(name);
179
+ const authType = profile.authType ?? "basic";
180
+ const grantType = profile.grantType ?? "client_credentials";
181
+ // Canonicalize the destination before resolving any credential material.
182
+ // Tool preflight uses this same function, preventing validation/use drift.
183
+ const instance = normalizeInstanceUrl(profile.instance);
184
+ // The user password is only needed for basic auth and the OAuth
185
+ // "password" grant -- don't demand a credential for other schemes.
186
+ const needsPassword = authType === "basic" || (authType === "oauth" && grantType === "password");
187
+ const password = needsPassword ? this.resolveCredential(profile) : "";
188
+ return Object.freeze({
189
+ instance,
190
+ user: profile.username ?? "",
191
+ password,
192
+ displayValue: process.env.SN_DISPLAY_VALUE ?? "true",
193
+ relDepth: parseRelDepth(process.env.SN_REL_DEPTH),
194
+ authType,
195
+ grantType,
196
+ clientId: profile.clientId,
197
+ // Only resolve the secrets the chosen auth scheme actually uses: a
198
+ // stray reference for another scheme (e.g. apiKey on an oauth
199
+ // profile) pointing at an unset env var must not break auth that
200
+ // never needed it.
201
+ clientSecret: authType === "oauth" && profile.clientSecret
202
+ ? this.resolveSecret(profile.clientSecret, name, "clientSecret")
203
+ : undefined,
204
+ apiKey: authType === "apikey" && profile.apiKey
205
+ ? this.resolveSecret(profile.apiKey, name, "apiKey")
206
+ : undefined,
207
+ apiKeyHeader: profile.apiKeyHeader,
208
+ timeoutMs: profile.timeoutMs ?? (0, config_js_1.parseTimeoutMs)(process.env.SN_TIMEOUT_MS),
209
+ maxConcurrentRequests: profile.maxConcurrentRequests ??
210
+ (0, config_js_1.parsePositiveIntegerEnv)(process.env.SN_MAX_CONCURRENT_REQUESTS, "SN_MAX_CONCURRENT_REQUESTS", { max: 32 }),
211
+ schemaCacheTtlMs: profile.schemaCacheTtlMs ??
212
+ (0, config_js_1.parsePositiveIntegerEnv)(process.env.SN_SCHEMA_CACHE_TTL_MS, "SN_SCHEMA_CACHE_TTL_MS", { max: 3_600_000 }),
213
+ ...resolvedMetadataCache(profile),
214
+ });
215
+ }
216
+ /**
217
+ * Add a new profile at runtime and persist the updated config to disk.
218
+ * If a profile with the same name already exists, it is overwritten.
219
+ */
220
+ addProfile(name, profile) {
221
+ validateProfileName(name);
222
+ validateProfileKeys(profile);
223
+ // A profile binds secret env-var references (SN_PASSWORD, SN_CLIENT_
224
+ // SECRET, SN_API_KEY, ...) to an instance URL: on the next call the
225
+ // resolved secret is TRANSMITTED to that host. Runtime-added profiles
226
+ // may therefore only target ServiceNow domains (or hosts the operator
227
+ // explicitly allowlisted via SN_ALLOWED_INSTANCE_HOSTS) -- otherwise a
228
+ // prompt-injected add + switch would silently exfiltrate a real secret
229
+ // to an attacker-controlled host.
230
+ const hostProblem = instanceHostError(profile.instance);
231
+ if (hostProblem) {
232
+ throw new Error(hostProblem);
233
+ }
234
+ // Never persist plain-text secrets: everything addProfile writes to
235
+ // disk must reference an environment variable via "env:VAR_NAME".
236
+ validatePersistedCredentialSource(profile.credential, "credential");
237
+ validatePersistedCredentialSource(profile.clientSecret, "clientSecret");
238
+ validatePersistedCredentialSource(profile.apiKey, "apiKey");
239
+ this.mutateConfig((config) => {
240
+ Object.defineProperty(config.profiles, name, {
241
+ value: canonicalizeProfile(profile),
242
+ writable: true,
243
+ enumerable: true,
244
+ configurable: true,
245
+ });
246
+ });
247
+ // Invalidate cached client for this profile if it existed
248
+ this.clientCache.delete(name);
249
+ }
250
+ /** Replace one credential source without exposing it through an MCP tool. */
251
+ rotateCredential(name, field, source) {
252
+ validateProfileName(name);
253
+ validatePersistedCredentialSource(source, field);
254
+ this.mutateConfig((config) => {
255
+ if (!Object.hasOwn(config.profiles, name)) {
256
+ throw new Error(`Profile "${name}" not found`);
257
+ }
258
+ const current = config.profiles[name];
259
+ config.profiles[name] = canonicalizeProfile({ ...current, [field]: source });
260
+ });
261
+ this.clientCache.delete(name);
262
+ }
263
+ /** Remove one named profile through the out-of-band administration boundary. */
264
+ removeProfile(name) {
265
+ validateProfileName(name);
266
+ this.mutateConfig((config) => {
267
+ if (!Object.hasOwn(config.profiles, name)) {
268
+ throw new Error(`Profile "${name}" not found`);
269
+ }
270
+ delete config.profiles[name];
271
+ });
272
+ this.clientCache.delete(name);
273
+ }
274
+ /**
275
+ * Return the path to the config file on disk.
276
+ */
277
+ getConfigPath() {
278
+ return this.configFilePath;
279
+ }
280
+ // ── Private helpers ────────────────────────────────────────────────
281
+ /**
282
+ * Attempt to load the config file from disk.
283
+ * Returns null if the file does not exist or is not valid JSON.
284
+ */
285
+ loadConfigFile() {
286
+ let descriptor;
287
+ let directoryDescriptor;
288
+ try {
289
+ const parentsBefore = inspectParentComponents(this.configFilePath);
290
+ if (parentsBefore.missing) {
291
+ assertParentPathRemainsAbsent(this.configFilePath, parentsBefore);
292
+ return null;
293
+ }
294
+ directoryDescriptor = openSecureConfigDirectory(path.dirname(this.configFilePath));
295
+ descriptor = openExistingConfigFile(this.configFilePath);
296
+ if (descriptor === undefined) {
297
+ assertConfigEntryRemainsAbsent(this.configFilePath, parentsBefore);
298
+ return null;
299
+ }
300
+ secureConfigFileDescriptor(descriptor);
301
+ const status = fs.fstatSync(descriptor);
302
+ if (status.size > MAX_PROFILE_CONFIG_BYTES) {
303
+ throw new Error("Profile configuration exceeds the size limit");
304
+ }
305
+ const raw = fs.readFileSync(descriptor, { encoding: "utf8" });
306
+ assertPathIdentity(this.configFilePath, status, parentsBefore);
307
+ const parsed = JSON.parse(raw);
308
+ // Basic validation
309
+ if (typeof parsed !== "object" || parsed === null ||
310
+ !("version" in parsed) || typeof parsed.version !== "number" ||
311
+ !("profiles" in parsed) || typeof parsed.profiles !== "object" ||
312
+ parsed.profiles === null || Array.isArray(parsed.profiles)) {
313
+ throw new Error("Profile configuration has invalid structure");
314
+ }
315
+ const profiles = validateLoadedProfiles(parsed.profiles);
316
+ return {
317
+ version: parsed.version,
318
+ profiles,
319
+ };
320
+ }
321
+ catch (err) {
322
+ const reason = err instanceof Error && err.message.includes("legacy plaintext")
323
+ ? "Legacy plaintext profile credentials are rejected; replace them through the profile administration CLI"
324
+ : "Profile configuration could not be loaded safely";
325
+ throw new Error(reason);
326
+ }
327
+ finally {
328
+ if (descriptor !== undefined)
329
+ fs.closeSync(descriptor);
330
+ if (directoryDescriptor !== undefined)
331
+ fs.closeSync(directoryDescriptor);
332
+ }
333
+ }
334
+ /**
335
+ * Build one explicitly named, process-local profile from canonical SN_*
336
+ * variables. SN_PROFILE_NAME is the required out-of-band mapping: without
337
+ * it, even fully populated connection variables produce no profile. This
338
+ * preserves SN_* support without a default/active/omitted routing path.
339
+ * Additional env vars configure the auth scheme:
340
+ * SN_AUTH_TYPE, SN_CLIENT_ID, SN_CLIENT_SECRET, SN_GRANT_TYPE,
341
+ * SN_API_KEY, SN_API_KEY_HEADER, SN_TIMEOUT_MS.
342
+ */
343
+ buildExplicitEnvironmentProfile() {
344
+ const profileName = process.env.SN_PROFILE_NAME;
345
+ if (profileName === undefined) {
346
+ return { version: CONFIG_VERSION, profiles: Object.create(null) };
347
+ }
348
+ validateProfileName(profileName);
349
+ const instance = process.env.SN_INSTANCE;
350
+ const user = process.env.SN_USER;
351
+ if (!instance?.trim()) {
352
+ throw new Error("SN_PROFILE_NAME requires SN_INSTANCE");
353
+ }
354
+ // Secret values remain environment references. If later persisted by an
355
+ // operator administration action, no plaintext credential is written.
356
+ const profile = {
357
+ instance,
358
+ username: user ?? "",
359
+ credential: "env:SN_PASSWORD",
360
+ };
361
+ const authTypeValue = process.env.SN_AUTH_TYPE;
362
+ const authType = (0, config_js_1.parseAuthType)(authTypeValue);
363
+ if (authTypeValue !== undefined && authType === undefined) {
364
+ throw new Error("SN_AUTH_TYPE must be basic, oauth, or apikey");
365
+ }
366
+ if (authType) {
367
+ profile.authType = authType;
368
+ }
369
+ if (process.env.SN_CLIENT_ID) {
370
+ profile.clientId = process.env.SN_CLIENT_ID;
371
+ }
372
+ if (process.env.SN_CLIENT_SECRET) {
373
+ profile.clientSecret = "env:SN_CLIENT_SECRET";
374
+ }
375
+ const grantTypeValue = process.env.SN_GRANT_TYPE;
376
+ const grantType = (0, config_js_1.parseGrantType)(grantTypeValue);
377
+ if (grantTypeValue !== undefined && grantType === undefined) {
378
+ throw new Error("SN_GRANT_TYPE must be client_credentials or password");
379
+ }
380
+ if (grantType) {
381
+ profile.grantType = grantType;
382
+ }
383
+ if (process.env.SN_API_KEY) {
384
+ profile.apiKey = "env:SN_API_KEY";
385
+ }
386
+ if (process.env.SN_API_KEY_HEADER) {
387
+ profile.apiKeyHeader = process.env.SN_API_KEY_HEADER;
388
+ }
389
+ const timeoutMs = (0, config_js_1.parseTimeoutMs)(process.env.SN_TIMEOUT_MS);
390
+ if (timeoutMs !== undefined) {
391
+ profile.timeoutMs = timeoutMs;
392
+ }
393
+ const maxConcurrentRequests = (0, config_js_1.parsePositiveIntegerEnv)(process.env.SN_MAX_CONCURRENT_REQUESTS, "SN_MAX_CONCURRENT_REQUESTS", { max: 32 });
394
+ if (maxConcurrentRequests !== undefined) {
395
+ profile.maxConcurrentRequests = maxConcurrentRequests;
396
+ }
397
+ const schemaCacheTtlMs = (0, config_js_1.parsePositiveIntegerEnv)(process.env.SN_SCHEMA_CACHE_TTL_MS, "SN_SCHEMA_CACHE_TTL_MS", { max: 3_600_000 });
398
+ if (schemaCacheTtlMs !== undefined) {
399
+ profile.schemaCacheTtlMs = schemaCacheTtlMs;
400
+ }
401
+ const tableAccess = (0, table_policy_js_1.tableAccessPolicyInputFromEnvironment)();
402
+ if (tableAccess.readTables !== undefined ||
403
+ tableAccess.writeTables !== undefined ||
404
+ tableAccess.targets !== undefined) {
405
+ profile.tableAccess = tableAccess;
406
+ }
407
+ const metadataCache = (0, metadata_cache_js_1.metadataCacheConfigFromEnvironment)();
408
+ if (Object.keys(metadataCache).length > 0) {
409
+ profile.metadataCache = metadataCache;
410
+ }
411
+ return {
412
+ version: CONFIG_VERSION,
413
+ profiles: Object.assign(Object.create(null), {
414
+ [profileName]: canonicalizeProfile(profile),
415
+ }),
416
+ };
417
+ }
418
+ /**
419
+ * Persist the current config to disk, creating the directory if needed.
420
+ */
421
+ persistConfig(config = this.config) {
422
+ const dir = path.dirname(this.configFilePath);
423
+ const parentsBefore = ensureSecureConfigDirectory(this.configFilePath);
424
+ const directoryDescriptor = openSecureConfigDirectory(dir);
425
+ const canonical = {
426
+ version: CONFIG_VERSION,
427
+ profiles: Object.fromEntries(Object.entries(config.profiles).map(([name, profile]) => [
428
+ name,
429
+ canonicalizeProfile(profile),
430
+ ])),
431
+ };
432
+ const json = JSON.stringify(canonical, null, 2) + "\n";
433
+ const temporary = path.join(dir, `.${CONFIG_FILE}.${(0, node_crypto_1.randomUUID)()}.tmp`);
434
+ let descriptor;
435
+ let persistedDescriptor;
436
+ try {
437
+ descriptor = fs.openSync(temporary, fs.constants.O_CREAT |
438
+ fs.constants.O_EXCL |
439
+ fs.constants.O_WRONLY |
440
+ noFollowFlag(), 0o600);
441
+ if (POSIX_PERMISSIONS)
442
+ fs.fchmodSync(descriptor, 0o600);
443
+ fs.writeFileSync(descriptor, json, "utf8");
444
+ fs.fsyncSync(descriptor);
445
+ fs.closeSync(descriptor);
446
+ descriptor = undefined;
447
+ fs.renameSync(temporary, this.configFilePath);
448
+ persistedDescriptor = openExistingConfigFile(this.configFilePath);
449
+ if (persistedDescriptor === undefined) {
450
+ throw new Error("Persisted profile configuration disappeared");
451
+ }
452
+ secureConfigFileDescriptor(persistedDescriptor);
453
+ const persistedStatus = fs.fstatSync(persistedDescriptor);
454
+ assertPathIdentity(this.configFilePath, persistedStatus, parentsBefore);
455
+ syncDirectoryDescriptor(directoryDescriptor);
456
+ }
457
+ finally {
458
+ if (descriptor !== undefined)
459
+ fs.closeSync(descriptor);
460
+ if (persistedDescriptor !== undefined)
461
+ fs.closeSync(persistedDescriptor);
462
+ if (directoryDescriptor !== undefined)
463
+ fs.closeSync(directoryDescriptor);
464
+ unlinkIfPresent(temporary);
465
+ }
466
+ this.config = canonical;
467
+ }
468
+ mutateConfig(mutator) {
469
+ const release = acquireConfigLock(this.configFilePath);
470
+ try {
471
+ const onDisk = this.loadConfigFile();
472
+ const next = cloneConfig(onDisk ?? this.config);
473
+ mutator(next);
474
+ this.persistConfig(next);
475
+ }
476
+ finally {
477
+ release();
478
+ }
479
+ }
480
+ /**
481
+ * Find the profile name for a given Profile object.
482
+ * Used for warning messages.
483
+ */
484
+ getProfileNameFor(profile) {
485
+ for (const [name, p] of Object.entries(this.config.profiles)) {
486
+ if (p === profile) {
487
+ return name;
488
+ }
489
+ }
490
+ return "(unknown)";
491
+ }
492
+ }
493
+ exports.ProfileManager = ProfileManager;
494
+ // ── Module-level helpers ───────────────────────────────────────────
495
+ function resolvedMetadataCache(profile) {
496
+ const environmentCache = (0, metadata_cache_js_1.metadataCacheConfigFromEnvironment)();
497
+ const merged = Object.freeze({
498
+ ...environmentCache,
499
+ ...(profile.metadataCache ?? {}),
500
+ });
501
+ return Object.keys(merged).length === 0 ? Object.freeze({}) : Object.freeze({ metadataCache: merged });
502
+ }
503
+ function validatePersistedCredentialSource(value, field) {
504
+ if (value === undefined)
505
+ return;
506
+ if (typeof value === "string" &&
507
+ !/^env:SN_[A-Z0-9_]+$/u.test(value)) {
508
+ throw new Error(`Profile ${field} must use a canonical SN_* environment reference, a ` +
509
+ "secret reference, or an encrypted envelope");
510
+ }
511
+ if (!(0, profile_credentials_js_1.isCredentialSourceDescriptor)(value)) {
512
+ throw new Error(`Profile ${field} must use a valid secret reference or encrypted envelope; ` +
513
+ "legacy plaintext secrets are never persisted");
514
+ }
515
+ }
516
+ function validateLoadedProfiles(value) {
517
+ const profiles = Object.create(null);
518
+ for (const [name, candidate] of Object.entries(value)) {
519
+ validateProfileName(name);
520
+ if (typeof candidate !== "object" ||
521
+ candidate === null ||
522
+ Array.isArray(candidate)) {
523
+ throw new Error("Profile configuration has invalid structure");
524
+ }
525
+ const profile = candidate;
526
+ validateProfileKeys(profile);
527
+ for (const field of ["credential", "clientSecret", "apiKey"]) {
528
+ const source = profile[field];
529
+ if (source === undefined)
530
+ continue;
531
+ if (typeof source === "string" && !(0, profile_credentials_js_1.legacyEnvironmentReference)(source)) {
532
+ throw new Error("Profile configuration contains legacy plaintext credentials");
533
+ }
534
+ if (!(0, profile_credentials_js_1.isCredentialSourceDescriptor)(source)) {
535
+ throw new Error("Profile configuration contains an invalid credential source");
536
+ }
537
+ }
538
+ Object.defineProperty(profiles, name, {
539
+ value: canonicalizeProfile(profile),
540
+ writable: true,
541
+ enumerable: true,
542
+ configurable: true,
543
+ });
544
+ }
545
+ return profiles;
546
+ }
547
+ function canonicalizeProfile(profile) {
548
+ validateProfileKeys(profile);
549
+ const canonical = { ...profile };
550
+ for (const field of ["credential", "clientSecret", "apiKey"]) {
551
+ const source = canonical[field];
552
+ if (typeof source === "string") {
553
+ const migrated = (0, profile_credentials_js_1.legacyEnvironmentReference)(source);
554
+ if (!migrated) {
555
+ throw new Error("Legacy plaintext profile credentials are rejected");
556
+ }
557
+ // Preserve readable non-canonical V1 env references until the operator
558
+ // explicitly rotates them. Canonical SN_* refs migrate to V2 objects.
559
+ if (/^SN_[A-Z0-9_]+$/u.test(migrated.reference)) {
560
+ canonical[field] = migrated;
561
+ }
562
+ }
563
+ }
564
+ return immutableProfileSnapshot(canonical);
565
+ }
566
+ function immutableProfileSnapshot(profile) {
567
+ const snapshot = { ...profile };
568
+ if (snapshot.tableAccess !== undefined) {
569
+ snapshot.tableAccess = deepFreezeJsonClone(snapshot.tableAccess);
570
+ }
571
+ if (snapshot.fieldPolicy !== undefined) {
572
+ snapshot.fieldPolicy = deepFreezeJsonClone(snapshot.fieldPolicy);
573
+ }
574
+ if (snapshot.readableTableFields !== undefined) {
575
+ snapshot.readableTableFields = deepFreezeJsonClone(snapshot.readableTableFields);
576
+ }
577
+ if (snapshot.writableTableFields !== undefined) {
578
+ snapshot.writableTableFields = deepFreezeJsonClone(snapshot.writableTableFields);
579
+ }
580
+ if (snapshot.metadataCache !== undefined) {
581
+ snapshot.metadataCache = deepFreezeJsonClone(snapshot.metadataCache);
582
+ }
583
+ for (const field of ["credential", "clientSecret", "apiKey"]) {
584
+ const source = snapshot[field];
585
+ if (source !== undefined && typeof source !== "string") {
586
+ snapshot[field] = Object.freeze({ ...source });
587
+ }
588
+ }
589
+ return Object.freeze(snapshot);
590
+ }
591
+ function deepFreezeJsonClone(value) {
592
+ const clone = JSON.parse(JSON.stringify(value));
593
+ return deepFreeze(clone);
594
+ }
595
+ function deepFreeze(value) {
596
+ if (typeof value !== "object" || value === null)
597
+ return value;
598
+ for (const nested of Object.values(value)) {
599
+ deepFreeze(nested);
600
+ }
601
+ return Object.freeze(value);
602
+ }
603
+ function validateProfileName(name) {
604
+ if (typeof name !== "string" ||
605
+ !/^[A-Za-z0-9_][A-Za-z0-9._-]{0,63}$/u.test(name)) {
606
+ throw new Error("Profile name is invalid");
607
+ }
608
+ }
609
+ function validateProfileKeys(profile) {
610
+ if (typeof profile !== "object" || profile === null || Array.isArray(profile)) {
611
+ throw new Error("Profile configuration has invalid structure");
612
+ }
613
+ for (const key of Object.keys(profile)) {
614
+ if (!PROFILE_KEYS.has(key)) {
615
+ throw new Error("Profile configuration contains an unsupported field");
616
+ }
617
+ }
618
+ }
619
+ function normalizeConfigFilePath(candidate) {
620
+ const resolved = path.resolve(candidate);
621
+ // Darwin exposes /var and /tmp as stable OS-managed aliases into /private.
622
+ // Canonicalize only these platform roots before applying the no-symlink
623
+ // policy so ordinary temporary HOME directories remain testable without
624
+ // accepting operator-created parent symlinks.
625
+ if (process.platform === "darwin") {
626
+ if (resolved === "/var" || resolved.startsWith("/var/")) {
627
+ return `/private${resolved}`;
628
+ }
629
+ if (resolved === "/tmp" || resolved.startsWith("/tmp/")) {
630
+ return `/private${resolved}`;
631
+ }
632
+ }
633
+ return resolved;
634
+ }
635
+ function inspectParentComponents(configPath) {
636
+ const directory = path.dirname(configPath);
637
+ const root = path.parse(directory).root;
638
+ const relative = path.relative(root, directory);
639
+ const components = relative ? relative.split(path.sep).filter(Boolean) : [];
640
+ const identities = [];
641
+ let current = root;
642
+ for (const component of components) {
643
+ current = path.join(current, component);
644
+ let status;
645
+ try {
646
+ status = fs.lstatSync(current);
647
+ }
648
+ catch (error) {
649
+ if (error.code === "ENOENT") {
650
+ return Object.freeze({
651
+ missing: true,
652
+ identities: Object.freeze(identities),
653
+ });
654
+ }
655
+ throw error;
656
+ }
657
+ if (status.isSymbolicLink() || !status.isDirectory()) {
658
+ throw new Error("Profile configuration parent path is unsafe");
659
+ }
660
+ identities.push(Object.freeze({
661
+ target: current,
662
+ device: status.dev,
663
+ inode: status.ino,
664
+ }));
665
+ }
666
+ return Object.freeze({
667
+ missing: false,
668
+ identities: Object.freeze(identities),
669
+ });
670
+ }
671
+ function ensureSecureConfigDirectory(configPath) {
672
+ let inspection = inspectParentComponents(configPath);
673
+ if (inspection.missing) {
674
+ fs.mkdirSync(path.dirname(configPath), { recursive: true, mode: 0o700 });
675
+ inspection = inspectParentComponents(configPath);
676
+ if (inspection.missing) {
677
+ throw new Error("Profile configuration directory could not be created safely");
678
+ }
679
+ }
680
+ const descriptor = openSecureConfigDirectory(path.dirname(configPath));
681
+ try {
682
+ syncDirectoryDescriptor(descriptor);
683
+ }
684
+ finally {
685
+ if (descriptor !== undefined)
686
+ fs.closeSync(descriptor);
687
+ }
688
+ return inspectParentComponents(configPath);
689
+ }
690
+ function openSecureConfigDirectory(directory) {
691
+ if (!POSIX_PERMISSIONS)
692
+ return undefined;
693
+ const descriptor = fs.openSync(directory, fs.constants.O_RDONLY | directoryFlag() | noFollowFlag());
694
+ try {
695
+ let status = fs.fstatSync(descriptor);
696
+ if (!status.isDirectory()) {
697
+ throw new Error("Profile configuration parent is not a directory");
698
+ }
699
+ assertOwnedByCurrentUser(status, "Profile configuration directory");
700
+ if ((status.mode & 0o777) !== 0o700) {
701
+ fs.fchmodSync(descriptor, 0o700);
702
+ status = fs.fstatSync(descriptor);
703
+ }
704
+ if ((status.mode & 0o777) !== 0o700) {
705
+ throw new Error("Profile configuration directory permissions are unsafe");
706
+ }
707
+ return descriptor;
708
+ }
709
+ catch (error) {
710
+ fs.closeSync(descriptor);
711
+ throw error;
712
+ }
713
+ }
714
+ function openExistingConfigFile(configPath) {
715
+ if (!POSIX_PERMISSIONS) {
716
+ try {
717
+ const status = fs.lstatSync(configPath);
718
+ if (status.isSymbolicLink()) {
719
+ throw new Error("Profile configuration symlinks are not allowed");
720
+ }
721
+ }
722
+ catch (error) {
723
+ if (error.code === "ENOENT")
724
+ return undefined;
725
+ throw error;
726
+ }
727
+ }
728
+ try {
729
+ return fs.openSync(configPath, fs.constants.O_RDONLY | noFollowFlag());
730
+ }
731
+ catch (error) {
732
+ if (error.code !== "ENOENT")
733
+ throw error;
734
+ // A broken symlink is not a truly absent configuration. lstat distinguishes
735
+ // it from a missing directory entry even on platforms without O_NOFOLLOW.
736
+ try {
737
+ fs.lstatSync(configPath);
738
+ }
739
+ catch (lstatError) {
740
+ if (lstatError.code === "ENOENT")
741
+ return undefined;
742
+ }
743
+ throw new Error("Profile configuration path is unsafe");
744
+ }
745
+ }
746
+ function secureConfigFileDescriptor(descriptor) {
747
+ let status = fs.fstatSync(descriptor);
748
+ if (!status.isFile()) {
749
+ throw new Error("Profile configuration is not a regular file");
750
+ }
751
+ if (status.size > MAX_PROFILE_CONFIG_BYTES) {
752
+ throw new Error("Profile configuration exceeds the size limit");
753
+ }
754
+ if (!POSIX_PERMISSIONS)
755
+ return;
756
+ assertOwnedByCurrentUser(status, "Profile configuration");
757
+ if ((status.mode & 0o777) !== 0o600) {
758
+ fs.fchmodSync(descriptor, 0o600);
759
+ status = fs.fstatSync(descriptor);
760
+ }
761
+ if ((status.mode & 0o777) !== 0o600) {
762
+ throw new Error("Profile configuration permissions are unsafe");
763
+ }
764
+ }
765
+ function assertOwnedByCurrentUser(status, subject) {
766
+ const userId = process.getuid?.();
767
+ if (userId !== undefined && status.uid !== userId) {
768
+ throw new Error(`${subject} is not owned by the current user`);
769
+ }
770
+ }
771
+ function assertPathIdentity(configPath, descriptorStatus, parentsBefore) {
772
+ const parentsAfter = inspectParentComponents(configPath);
773
+ if (parentsAfter.missing ||
774
+ parentsBefore.missing ||
775
+ parentsAfter.identities.length !== parentsBefore.identities.length) {
776
+ throw new Error("Profile configuration parent changed during access");
777
+ }
778
+ for (let index = 0; index < parentsBefore.identities.length; index += 1) {
779
+ const before = parentsBefore.identities[index];
780
+ const after = parentsAfter.identities[index];
781
+ if (before.target !== after.target ||
782
+ before.device !== after.device ||
783
+ before.inode !== after.inode) {
784
+ throw new Error("Profile configuration parent changed during access");
785
+ }
786
+ }
787
+ let pathStatus;
788
+ try {
789
+ pathStatus = fs.lstatSync(configPath);
790
+ }
791
+ catch {
792
+ throw new Error("Profile configuration changed during access");
793
+ }
794
+ if (pathStatus.isSymbolicLink() ||
795
+ !pathStatus.isFile() ||
796
+ pathStatus.dev !== descriptorStatus.dev ||
797
+ pathStatus.ino !== descriptorStatus.ino) {
798
+ throw new Error("Profile configuration changed during access");
799
+ }
800
+ }
801
+ function assertParentPathRemainsAbsent(configPath, parentsBefore) {
802
+ const parentsAfter = inspectParentComponents(configPath);
803
+ if (!parentsBefore.missing ||
804
+ !parentsAfter.missing ||
805
+ !samePathIdentities(parentsBefore.identities, parentsAfter.identities)) {
806
+ throw new Error("Profile configuration parent changed during access");
807
+ }
808
+ }
809
+ function assertConfigEntryRemainsAbsent(configPath, parentsBefore) {
810
+ const parentsAfter = inspectParentComponents(configPath);
811
+ if (parentsBefore.missing ||
812
+ parentsAfter.missing ||
813
+ !samePathIdentities(parentsBefore.identities, parentsAfter.identities)) {
814
+ throw new Error("Profile configuration parent changed during access");
815
+ }
816
+ try {
817
+ fs.lstatSync(configPath);
818
+ }
819
+ catch (error) {
820
+ if (error.code === "ENOENT")
821
+ return;
822
+ throw error;
823
+ }
824
+ throw new Error("Profile configuration appeared during access");
825
+ }
826
+ function samePathIdentities(before, after) {
827
+ return before.length === after.length && before.every((identity, index) => {
828
+ const candidate = after[index];
829
+ return (identity.target === candidate.target &&
830
+ identity.device === candidate.device &&
831
+ identity.inode === candidate.inode);
832
+ });
833
+ }
834
+ function noFollowFlag() {
835
+ if (!POSIX_PERMISSIONS)
836
+ return 0;
837
+ return fs.constants.O_NOFOLLOW ?? 0;
838
+ }
839
+ function directoryFlag() {
840
+ return fs.constants.O_DIRECTORY ?? 0;
841
+ }
842
+ function syncDirectoryDescriptor(descriptor) {
843
+ if (POSIX_PERMISSIONS && descriptor !== undefined)
844
+ fs.fsyncSync(descriptor);
845
+ }
846
+ function unlinkIfPresent(target) {
847
+ try {
848
+ fs.unlinkSync(target);
849
+ }
850
+ catch (error) {
851
+ if (error.code !== "ENOENT")
852
+ throw error;
853
+ }
854
+ }
855
+ function cloneConfig(config) {
856
+ const profiles = Object.create(null);
857
+ for (const [name, profile] of Object.entries(config.profiles)) {
858
+ Object.defineProperty(profiles, name, {
859
+ value: { ...profile },
860
+ writable: true,
861
+ enumerable: true,
862
+ configurable: true,
863
+ });
864
+ }
865
+ return { version: config.version, profiles };
866
+ }
867
+ function acquireConfigLock(configPath) {
868
+ const lockPath = `${configPath}.lock`;
869
+ ensureSecureConfigDirectory(configPath);
870
+ const deadline = Date.now() + LOCK_WAIT_MS;
871
+ let descriptor;
872
+ while (descriptor === undefined) {
873
+ try {
874
+ descriptor = fs.openSync(lockPath, fs.constants.O_CREAT |
875
+ fs.constants.O_EXCL |
876
+ fs.constants.O_WRONLY |
877
+ noFollowFlag(), 0o600);
878
+ if (POSIX_PERMISSIONS)
879
+ fs.fchmodSync(descriptor, 0o600);
880
+ }
881
+ catch (error) {
882
+ const code = error.code;
883
+ if (code !== "EEXIST" || Date.now() >= deadline) {
884
+ throw new Error("Profile configuration is busy");
885
+ }
886
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
887
+ }
888
+ }
889
+ return () => {
890
+ try {
891
+ fs.closeSync(descriptor);
892
+ }
893
+ finally {
894
+ try {
895
+ fs.unlinkSync(lockPath);
896
+ }
897
+ catch (error) {
898
+ if (error.code !== "ENOENT")
899
+ throw error;
900
+ }
901
+ }
902
+ };
903
+ }
904
+ /**
905
+ * Hostname suffixes runtime-added profiles may target without operator
906
+ * opt-in: ServiceNow's commercial and government SaaS domains.
907
+ */
908
+ const ALLOWED_INSTANCE_SUFFIXES = [".service-now.com", ".servicenowservices.com"];
909
+ /**
910
+ * Validate the instance URL of a profile that is being added at runtime
911
+ * (sn_profile add). Returns an error message, or undefined when the URL
912
+ * is acceptable.
913
+ *
914
+ * Secrets configured for one instance must not be redirectable to an
915
+ * arbitrary host: a profile stores env-var REFERENCES, and the resolved
916
+ * secret is sent to the profile's instance on the next authenticated
917
+ * call. So runtime adds require https and a *.service-now.com /
918
+ * *.servicenowservices.com host. Self-hosted or custom-domain instances
919
+ * are supported via the SN_ALLOWED_INSTANCE_HOSTS environment variable
920
+ * (comma-separated hostnames; a "*.example.com" entry allows any
921
+ * subdomain) -- set by the operator, never by the model.
922
+ *
923
+ * Profiles hand-written into config.json are not affected: the operator
924
+ * edits that file directly and this check only runs in addProfile.
925
+ */
926
+ function instanceHostError(instance) {
927
+ let url;
928
+ try {
929
+ url = new URL(normalizeInstanceUrl(instance));
930
+ }
931
+ catch (error) {
932
+ return error instanceof Error
933
+ ? error.message
934
+ : "ServiceNow instance URL is invalid";
935
+ }
936
+ const host = url.hostname.toLowerCase();
937
+ if (ALLOWED_INSTANCE_SUFFIXES.some((suffix) => host.endsWith(suffix))) {
938
+ return undefined;
939
+ }
940
+ const allowlist = (process.env.SN_ALLOWED_INSTANCE_HOSTS ?? "")
941
+ .split(",")
942
+ .map((entry) => entry.trim().toLowerCase())
943
+ .filter((entry) => entry.length > 0);
944
+ for (const entry of allowlist) {
945
+ if (entry.startsWith("*.")) {
946
+ if (host.endsWith(entry.slice(1)))
947
+ return undefined;
948
+ }
949
+ else if (host === entry) {
950
+ return undefined;
951
+ }
952
+ }
953
+ return (`instance host "${host}" is not a ServiceNow domain ` +
954
+ `(*.service-now.com, *.servicenowservices.com). Profiles bind secret ` +
955
+ `environment-variable references to an instance, so runtime-added ` +
956
+ `profiles may only target allowlisted hosts. For a self-hosted or ` +
957
+ `custom-domain instance, set SN_ALLOWED_INSTANCE_HOSTS in the MCP ` +
958
+ `server's environment (comma-separated hostnames; "*.corp.example.com" ` +
959
+ `wildcards allowed).`);
960
+ }
961
+ /**
962
+ * Normalize an instance URL: strip trailing slashes, ensure https://.
963
+ */
964
+ function normalizeInstanceUrl(instance) {
965
+ const raw = instance.trim();
966
+ if (!raw) {
967
+ throw new Error("ServiceNow instance URL must not be empty");
968
+ }
969
+ const candidate = /^[a-z][a-z\d+.-]*:/i.test(raw) ? raw : `https://${raw}`;
970
+ let url;
971
+ try {
972
+ url = new URL(candidate);
973
+ }
974
+ catch {
975
+ throw new Error("ServiceNow instance URL is invalid");
976
+ }
977
+ if (url.protocol !== "https:") {
978
+ throw new Error("ServiceNow instance URL must use https://");
979
+ }
980
+ if (url.username || url.password || url.search || url.hash) {
981
+ throw new Error("ServiceNow instance URL must not contain credentials, query parameters, or a fragment");
982
+ }
983
+ if (url.pathname !== "" && url.pathname !== "/") {
984
+ throw new Error("ServiceNow instance URL must identify the instance origin only");
985
+ }
986
+ return url.origin;
987
+ }
988
+ /**
989
+ * Parse the SN_REL_DEPTH env var with a default of 3.
990
+ */
991
+ function parseRelDepth(value) {
992
+ if (!value)
993
+ return 3;
994
+ const parsed = parseInt(value, 10);
995
+ return isNaN(parsed) ? 3 : parsed;
996
+ }
997
+ /**
998
+ * Stable, non-reversible discriminator for the exact credential material a
999
+ * resolved configuration will present to ServiceNow. Two configurations that
1000
+ * differ in any credential input produce different fingerprints, so it is
1001
+ * usable wherever per-identity state must not be shared. Never log it.
1002
+ */
1003
+ function credentialFingerprint(config) {
1004
+ const hash = (0, node_crypto_1.createHash)("sha256");
1005
+ for (const value of [
1006
+ config.instance,
1007
+ config.authType ?? "basic",
1008
+ config.grantType ?? "client_credentials",
1009
+ config.user,
1010
+ config.password,
1011
+ config.clientId ?? "",
1012
+ config.clientSecret ?? "",
1013
+ config.apiKey ?? "",
1014
+ config.apiKeyHeader ?? "",
1015
+ ]) {
1016
+ const encoded = Buffer.from(value, "utf8");
1017
+ const length = Buffer.allocUnsafe(4);
1018
+ length.writeUInt32BE(encoded.byteLength);
1019
+ hash.update(length);
1020
+ hash.update(encoded);
1021
+ length.fill(0);
1022
+ encoded.fill(0);
1023
+ }
1024
+ return hash.digest("base64url");
1025
+ }
1026
+ //# sourceMappingURL=profile-manager.js.map