@onlyflows/servicenow-mcp 2.3.0-dev.4 → 2.3.0-dev.5

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 (164) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/README.md +111 -5
  3. package/dist/atf-policy.d.ts +1 -1
  4. package/dist/atf-policy.d.ts.map +1 -1
  5. package/dist/atf-policy.js +2 -0
  6. package/dist/atf-policy.js.map +1 -1
  7. package/dist/credential-tables.d.ts +32 -0
  8. package/dist/credential-tables.d.ts.map +1 -0
  9. package/dist/credential-tables.js +58 -0
  10. package/dist/credential-tables.js.map +1 -0
  11. package/dist/encoded-query-policy.d.ts.map +1 -1
  12. package/dist/encoded-query-policy.js +8 -1
  13. package/dist/encoded-query-policy.js.map +1 -1
  14. package/dist/execution-context.d.ts +14 -0
  15. package/dist/execution-context.d.ts.map +1 -1
  16. package/dist/execution-context.js +8 -0
  17. package/dist/execution-context.js.map +1 -1
  18. package/dist/field-policy.d.ts +34 -1
  19. package/dist/field-policy.d.ts.map +1 -1
  20. package/dist/field-policy.js +308 -25
  21. package/dist/field-policy.js.map +1 -1
  22. package/dist/hidden-values.d.ts +225 -0
  23. package/dist/hidden-values.d.ts.map +1 -0
  24. package/dist/hidden-values.js +748 -0
  25. package/dist/hidden-values.js.map +1 -0
  26. package/dist/http-entrypoint.d.ts.map +1 -1
  27. package/dist/http-entrypoint.js +7 -0
  28. package/dist/http-entrypoint.js.map +1 -1
  29. package/dist/index.js +7 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/metadata-cache.d.ts +38 -0
  32. package/dist/metadata-cache.d.ts.map +1 -1
  33. package/dist/metadata-cache.js +76 -3
  34. package/dist/metadata-cache.js.map +1 -1
  35. package/dist/policy-card.d.ts +16 -1
  36. package/dist/policy-card.d.ts.map +1 -1
  37. package/dist/policy-card.js +13 -2
  38. package/dist/policy-card.js.map +1 -1
  39. package/dist/profile-manager.d.ts +12 -0
  40. package/dist/profile-manager.d.ts.map +1 -1
  41. package/dist/profile-manager.js +23 -1
  42. package/dist/profile-manager.js.map +1 -1
  43. package/dist/setup.d.ts.map +1 -1
  44. package/dist/setup.js +5 -1
  45. package/dist/setup.js.map +1 -1
  46. package/dist/structured-query.d.ts.map +1 -1
  47. package/dist/structured-query.js +6 -1
  48. package/dist/structured-query.js.map +1 -1
  49. package/dist/table-policy.d.ts +34 -1
  50. package/dist/table-policy.d.ts.map +1 -1
  51. package/dist/table-policy.js +95 -10
  52. package/dist/table-policy.js.map +1 -1
  53. package/dist/tool-error.d.ts +8 -1
  54. package/dist/tool-error.d.ts.map +1 -1
  55. package/dist/tool-error.js +23 -0
  56. package/dist/tool-error.js.map +1 -1
  57. package/dist/tool-table-access.d.ts.map +1 -1
  58. package/dist/tool-table-access.js +25 -6
  59. package/dist/tool-table-access.js.map +1 -1
  60. package/dist/tools/aggregate.js +2 -2
  61. package/dist/tools/aggregate.js.map +1 -1
  62. package/dist/tools/all-fields-cap.d.ts.map +1 -1
  63. package/dist/tools/all-fields-cap.js +29 -7
  64. package/dist/tools/all-fields-cap.js.map +1 -1
  65. package/dist/tools/atf-author-module.d.ts +1 -7
  66. package/dist/tools/atf-author-module.d.ts.map +1 -1
  67. package/dist/tools/atf-author-module.js +16 -7
  68. package/dist/tools/atf-author-module.js.map +1 -1
  69. package/dist/tools/atf-contracts.d.ts +69 -4
  70. package/dist/tools/atf-contracts.d.ts.map +1 -1
  71. package/dist/tools/atf-contracts.js +32 -2
  72. package/dist/tools/atf-contracts.js.map +1 -1
  73. package/dist/tools/atf-renderers.js +2 -1
  74. package/dist/tools/atf-renderers.js.map +1 -1
  75. package/dist/tools/atf-results-module.d.ts.map +1 -1
  76. package/dist/tools/atf-results-module.js +5 -3
  77. package/dist/tools/atf-results-module.js.map +1 -1
  78. package/dist/tools/atf-run-module.js +3 -2
  79. package/dist/tools/atf-run-module.js.map +1 -1
  80. package/dist/tools/atf-shared.d.ts +6 -0
  81. package/dist/tools/atf-shared.d.ts.map +1 -1
  82. package/dist/tools/atf-shared.js +49 -10
  83. package/dist/tools/atf-shared.js.map +1 -1
  84. package/dist/tools/atf-step-catalog.d.ts +13 -8
  85. package/dist/tools/atf-step-catalog.d.ts.map +1 -1
  86. package/dist/tools/atf-step-catalog.js +169 -5
  87. package/dist/tools/atf-step-catalog.js.map +1 -1
  88. package/dist/tools/batch.d.ts.map +1 -1
  89. package/dist/tools/batch.js +4 -2
  90. package/dist/tools/batch.js.map +1 -1
  91. package/dist/tools/flow-view-contracts.d.ts +57 -1
  92. package/dist/tools/flow-view-contracts.d.ts.map +1 -1
  93. package/dist/tools/flow-view-contracts.js +34 -2
  94. package/dist/tools/flow-view-contracts.js.map +1 -1
  95. package/dist/tools/flow-view-graph.d.ts +14 -0
  96. package/dist/tools/flow-view-graph.d.ts.map +1 -1
  97. package/dist/tools/flow-view-graph.js +43 -1
  98. package/dist/tools/flow-view-graph.js.map +1 -1
  99. package/dist/tools/flow-view-module.js +1 -1
  100. package/dist/tools/flow-view-module.js.map +1 -1
  101. package/dist/tools/flow-view-policy.d.ts +3 -3
  102. package/dist/tools/flow-view-policy.d.ts.map +1 -1
  103. package/dist/tools/flow-view-policy.js +5 -4
  104. package/dist/tools/flow-view-policy.js.map +1 -1
  105. package/dist/tools/flow-view-renderers.d.ts.map +1 -1
  106. package/dist/tools/flow-view-renderers.js +9 -21
  107. package/dist/tools/flow-view-renderers.js.map +1 -1
  108. package/dist/tools/index.d.ts.map +1 -1
  109. package/dist/tools/index.js +80 -13
  110. package/dist/tools/index.js.map +1 -1
  111. package/dist/tools/platform-view-contracts.d.ts +189 -0
  112. package/dist/tools/platform-view-contracts.d.ts.map +1 -0
  113. package/dist/tools/platform-view-contracts.js +353 -0
  114. package/dist/tools/platform-view-contracts.js.map +1 -0
  115. package/dist/tools/platform-view-evaluate.d.ts +11 -0
  116. package/dist/tools/platform-view-evaluate.d.ts.map +1 -0
  117. package/dist/tools/platform-view-evaluate.js +19 -0
  118. package/dist/tools/platform-view-evaluate.js.map +1 -0
  119. package/dist/tools/platform-view-module.d.ts +28 -0
  120. package/dist/tools/platform-view-module.d.ts.map +1 -0
  121. package/dist/tools/platform-view-module.js +111 -0
  122. package/dist/tools/platform-view-module.js.map +1 -0
  123. package/dist/tools/platform-view-scan.d.ts +57 -0
  124. package/dist/tools/platform-view-scan.d.ts.map +1 -0
  125. package/dist/tools/platform-view-scan.js +375 -0
  126. package/dist/tools/platform-view-scan.js.map +1 -0
  127. package/dist/tools/platform-view-upgrades.d.ts +152 -0
  128. package/dist/tools/platform-view-upgrades.d.ts.map +1 -0
  129. package/dist/tools/platform-view-upgrades.js +545 -0
  130. package/dist/tools/platform-view-upgrades.js.map +1 -0
  131. package/dist/tools/profile.d.ts.map +1 -1
  132. package/dist/tools/profile.js +1 -0
  133. package/dist/tools/profile.js.map +1 -1
  134. package/dist/tools/query-module.js +1 -1
  135. package/dist/tools/query-module.js.map +1 -1
  136. package/dist/tools/record-write-shared.d.ts.map +1 -1
  137. package/dist/tools/record-write-shared.js +4 -3
  138. package/dist/tools/record-write-shared.js.map +1 -1
  139. package/dist/tools/result-envelope.d.ts +116 -36
  140. package/dist/tools/result-envelope.d.ts.map +1 -1
  141. package/dist/tools/result-envelope.js +38 -3
  142. package/dist/tools/result-envelope.js.map +1 -1
  143. package/dist/tools/syslog-cursor.d.ts +61 -0
  144. package/dist/tools/syslog-cursor.d.ts.map +1 -0
  145. package/dist/tools/syslog-cursor.js +146 -0
  146. package/dist/tools/syslog-cursor.js.map +1 -0
  147. package/dist/tools/syslog.d.ts +2 -0
  148. package/dist/tools/syslog.d.ts.map +1 -1
  149. package/dist/tools/syslog.js +126 -2
  150. package/dist/tools/syslog.js.map +1 -1
  151. package/dist/update-set-eval/secret-patterns.d.ts +75 -0
  152. package/dist/update-set-eval/secret-patterns.d.ts.map +1 -0
  153. package/dist/update-set-eval/secret-patterns.js +570 -0
  154. package/dist/update-set-eval/secret-patterns.js.map +1 -0
  155. package/dist/update-set-eval/xml-reader.d.ts +117 -0
  156. package/dist/update-set-eval/xml-reader.d.ts.map +1 -0
  157. package/dist/update-set-eval/xml-reader.js +561 -0
  158. package/dist/update-set-eval/xml-reader.js.map +1 -0
  159. package/dist/version.d.ts +1 -1
  160. package/dist/version.js +1 -1
  161. package/docs/FLOW-VIEW.md +14 -5
  162. package/docs/PRODUCTION-SECURITY.md +63 -0
  163. package/package.json +1 -1
  164. package/server.json +2 -2
@@ -0,0 +1,748 @@
1
+ "use strict";
2
+ /**
3
+ * Which field values are hidden by what a field *is*, not what it is called.
4
+ *
5
+ * Field policy hides a value by name (`isSensitiveFieldName`), but a field of
6
+ * internal type `password` (a one-way hash) or `password2` (two-way
7
+ * encrypted) can be called anything: `ssh_passphrase`, `key`, `answer`,
8
+ * `secure_value`, `temppassword`. Their stored values are never returned, in
9
+ * any display shape. This module is the one place that decides type-based
10
+ * hiding:
11
+ *
12
+ * - {@link HIDDEN_FIELD_TYPES}, the internal types whose values are hidden;
13
+ * - {@link loadFieldTypes}, which builds a table's hidden-typed fields from
14
+ * ONE instance-wide `sys_dictionary` read (fields of those types only),
15
+ * projected over each table's extension chain, with database views
16
+ * resolved to the tables they join;
17
+ * - {@link classifyField}, the per-field verdict (including dot-walks) with a
18
+ * reason, for tools that show a value-hidden marker instead of dropping;
19
+ * - {@link withoutFields}, whole-field removal for every response shape;
20
+ * - row rules for tables whose secrecy is a per-row value (`sys_properties`).
21
+ *
22
+ * The loader never returns an empty map for "could not read": an unreadable
23
+ * dictionary is the explicit `unavailable` state, and a table it could not
24
+ * resolve has no entry (so every field on it is `unknown_type`).
25
+ *
26
+ * The scope at the bottom carries one call's resolved sets to field policy,
27
+ * which enforces them; see `field-policy.ts`.
28
+ *
29
+ * @module hidden-values
30
+ */
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.FieldTypesConfigurationError = exports.FIELD_TYPES_UNAVAILABLE_MESSAGE = exports.MAX_HIDDEN_DICTIONARY_ROWS = exports.FIELD_TYPES_UNAVAILABLE_TTL_MS = exports.FIELD_TYPES_TTL_MS = exports.FIELD_TYPES_UNAVAILABLE = exports.HIDDEN_FIELD_TYPES = void 0;
33
+ exports.isHiddenFieldType = isHiddenFieldType;
34
+ exports.hiddenTypedFields = hiddenTypedFields;
35
+ exports.classifyField = classifyField;
36
+ exports.fieldTypesFromRows = fieldTypesFromRows;
37
+ exports.withoutFields = withoutFields;
38
+ exports.rowValueRule = rowValueRule;
39
+ exports.rowValueHidden = rowValueHidden;
40
+ exports.loadFieldTypes = loadFieldTypes;
41
+ exports.runWithHiddenFieldScope = runWithHiddenFieldScope;
42
+ exports.currentHiddenFieldScope = currentHiddenFieldScope;
43
+ exports.hiddenFieldScope = hiddenFieldScope;
44
+ exports.validateFieldTypesConfig = validateFieldTypesConfig;
45
+ exports.fieldTypesConfigFromEnvironment = fieldTypesConfigFromEnvironment;
46
+ exports.dictionaryNotRequired = dictionaryNotRequired;
47
+ exports.fieldTypesOptOutWarning = fieldTypesOptOutWarning;
48
+ const node_async_hooks_1 = require("node:async_hooks");
49
+ const client_js_1 = require("./client.js");
50
+ const credential_tables_js_1 = require("./credential-tables.js");
51
+ const metadata_cache_js_1 = require("./metadata-cache.js");
52
+ /**
53
+ * Internal types whose stored values are never returned. `password` and
54
+ * `password2` are the ones found on instances; `masked` and `encrypted_text`
55
+ * are kept as a precaution (Flow Designer uses the same spellings).
56
+ */
57
+ exports.HIDDEN_FIELD_TYPES = Object.freeze([
58
+ "password",
59
+ "password2",
60
+ "masked",
61
+ "encrypted_text",
62
+ ]);
63
+ const HIDDEN_TYPE_SET = new Set(exports.HIDDEN_FIELD_TYPES);
64
+ /** True when `type` (an internal type name) is one whose values are hidden. */
65
+ function isHiddenFieldType(type) {
66
+ return typeof type === "string" && HIDDEN_TYPE_SET.has(type.trim().toLowerCase());
67
+ }
68
+ exports.FIELD_TYPES_UNAVAILABLE = Object.freeze({ state: "unavailable" });
69
+ /**
70
+ * The hidden-typed fields of `table`, or undefined when `table` could not be
71
+ * resolved (or the types are unavailable). Undefined means unknown: a caller
72
+ * must treat every field of the table as hidden, never as visible.
73
+ */
74
+ function hiddenTypedFields(types, table) {
75
+ if (types.state !== "available")
76
+ return undefined;
77
+ return types.tables.get(normalizeName(table) ?? "")?.hiddenNames;
78
+ }
79
+ /**
80
+ * The verdict for one field path on `table`.
81
+ *
82
+ * A dot-walked path (`caller_id.user_password`) is decided on the table it
83
+ * ends at, for both the type and the credential-table check; each hop's
84
+ * target comes from `referenceTarget`, and a hop it cannot resolve makes the
85
+ * path `unknown_type`. Field policy rejects dot-walked names outright today;
86
+ * this is for tools that read paths from the instance (history, payloads).
87
+ */
88
+ function classifyField(types, table, path, options = {}) {
89
+ if (types.state !== "available" || typeof path !== "string")
90
+ return "unknown_type";
91
+ const parts = path.trim().toLowerCase().split(".");
92
+ if (parts.length === 0 || parts.length > MAX_DOT_WALK_HOPS + 1)
93
+ return "unknown_type";
94
+ if (!parts.every((part) => FIELD_NAME.test(part)))
95
+ return "unknown_type";
96
+ let current = normalizeName(table);
97
+ for (const hop of parts.slice(0, -1)) {
98
+ if (current === undefined)
99
+ return "unknown_type";
100
+ const resolved = types.tables.get(current);
101
+ if (resolved === undefined)
102
+ return "unknown_type";
103
+ // A reference that is itself hidden-typed is never walked through.
104
+ if (resolved.hiddenNames.has(hop))
105
+ return "type";
106
+ let next;
107
+ try {
108
+ next = normalizeName(options.referenceTarget?.(current, hop));
109
+ }
110
+ catch {
111
+ next = undefined;
112
+ }
113
+ current = next;
114
+ }
115
+ if (current === undefined)
116
+ return "unknown_type";
117
+ const terminal = types.tables.get(current);
118
+ if (terminal === undefined)
119
+ return "unknown_type";
120
+ const field = parts[parts.length - 1];
121
+ if ((0, credential_tables_js_1.isCredentialTableHierarchy)(terminal.hierarchy))
122
+ return "credential_table";
123
+ if (terminal.hiddenNames.has(field))
124
+ return "type";
125
+ if (terminal.allTypes !== undefined) {
126
+ const type = terminal.allTypes.get(field);
127
+ if (type === undefined)
128
+ return "unknown_type";
129
+ if (isHiddenFieldType(type))
130
+ return "type";
131
+ }
132
+ return "visible";
133
+ }
134
+ /**
135
+ * Field types from dictionary rows the caller has already read, so the read
136
+ * stays inside that caller's own declared plan. `hierarchies` maps each table
137
+ * the caller will ask about to its chain (the table first). With
138
+ * `complete: true` the rows are every field of those chains, so a field with
139
+ * no row is `unknown_type`; otherwise only hidden-typed rows matter.
140
+ */
141
+ function fieldTypesFromRows(rows, hierarchies, options = {}) {
142
+ const byTable = new Map();
143
+ for (const row of rows) {
144
+ const table = normalizeName(row?.table);
145
+ const element = normalizeName(row?.element);
146
+ const type = typeof row?.internal_type === "string" ? row.internal_type.trim().toLowerCase() : "";
147
+ if (table === undefined || element === undefined || type === "")
148
+ continue;
149
+ let fields = byTable.get(table);
150
+ if (!fields)
151
+ byTable.set(table, (fields = new Map()));
152
+ if (!fields.has(element))
153
+ fields.set(element, type);
154
+ }
155
+ const tables = new Map();
156
+ for (const [name, chain] of Object.entries(hierarchies)) {
157
+ const table = normalizeName(name);
158
+ const hierarchy = chain.map(normalizeName);
159
+ if (table === undefined || hierarchy.length === 0 || hierarchy.some((entry) => entry === undefined)) {
160
+ continue;
161
+ }
162
+ const all = new Map();
163
+ // Nearest definition first: a child's own row overrides an inherited one.
164
+ for (const owner of hierarchy) {
165
+ for (const [element, type] of byTable.get(owner) ?? []) {
166
+ if (!all.has(element))
167
+ all.set(element, type);
168
+ }
169
+ }
170
+ const hidden = new Map([...all].filter(([, type]) => isHiddenFieldType(type)));
171
+ tables.set(table, resolvedTable(hierarchy, hidden, options.complete === true ? all : undefined));
172
+ }
173
+ return Object.freeze({ state: "available", tables });
174
+ }
175
+ /**
176
+ * A copy of `record` without the named fields. The whole entry goes, whatever
177
+ * its shape: a plain value, `{value, display_value, link}`, or the
178
+ * `sysparm_display_value=all` pair. A display value is never kept on its own:
179
+ * it is treated as secret as the stored value.
180
+ */
181
+ function withoutFields(record, fields) {
182
+ const output = {};
183
+ for (const [key, value] of Object.entries(record)) {
184
+ if (fields.has(key.trim().toLowerCase()))
185
+ continue;
186
+ Object.defineProperty(output, key, {
187
+ value,
188
+ enumerable: true,
189
+ writable: true,
190
+ configurable: true,
191
+ });
192
+ }
193
+ return output;
194
+ }
195
+ /**
196
+ * `sys_properties`: `value` is shown only for a property whose `type` is one
197
+ * of these. A secret type (`password`, `password2`), an empty or missing type,
198
+ * and any type not listed hide the value. The list is the non-secret choices;
199
+ * an unknown label (another language, a custom type) hides, never shows.
200
+ */
201
+ const SYS_PROPERTIES_RULE = Object.freeze({
202
+ table: "sys_properties",
203
+ valueField: "value",
204
+ typeField: "type",
205
+ queryDenied: Object.freeze(new Set(["value"])),
206
+ visibleTypes: Object.freeze(new Set([
207
+ "string",
208
+ "short_string",
209
+ "integer",
210
+ "boolean",
211
+ "true|false",
212
+ "choicelist",
213
+ "color",
214
+ "date_format",
215
+ "time_format",
216
+ "timezone",
217
+ "image",
218
+ "uploaded_image",
219
+ ])),
220
+ });
221
+ const ROW_RULES = new Map([
222
+ [SYS_PROPERTIES_RULE.table, SYS_PROPERTIES_RULE],
223
+ ]);
224
+ /** The row rule for `table`, if it has one. */
225
+ function rowValueRule(table) {
226
+ const normalized = normalizeName(table);
227
+ return normalized === undefined ? undefined : ROW_RULES.get(normalized);
228
+ }
229
+ /**
230
+ * True when the rule hides this row's value. The type is read from the row
231
+ * in any display shape: a plain string, or an object's `value` (the stored
232
+ * value of `sysparm_display_value=all`) or else its `display_value`.
233
+ */
234
+ function rowValueHidden(rule, row) {
235
+ const type = typeText(row[rule.typeField]);
236
+ if (type === undefined)
237
+ return true;
238
+ return !rule.visibleTypes.has(type.replace(/\s+/gu, "").toLowerCase());
239
+ }
240
+ function typeText(candidate) {
241
+ if (typeof candidate === "string")
242
+ return candidate.trim() === "" ? undefined : candidate;
243
+ if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) {
244
+ return undefined;
245
+ }
246
+ const record = candidate;
247
+ for (const key of ["value", "display_value"]) {
248
+ const value = Object.hasOwn(record, key) ? record[key] : undefined;
249
+ if (typeof value === "string" && value.trim() !== "")
250
+ return value;
251
+ }
252
+ return undefined;
253
+ }
254
+ // ── Loader ─────────────────────────────────────────────────────────
255
+ /**
256
+ * How long a loaded map serves without any request. A field that becomes
257
+ * hidden-typed within this window is still hidden by name if its name is
258
+ * sensitive; otherwise it is hidden from the next load. Capped by the
259
+ * profile's metadata-cache TTL.
260
+ */
261
+ exports.FIELD_TYPES_TTL_MS = 60 * 60 * 1000;
262
+ /** How long an unreadable dictionary is remembered before it is retried. */
263
+ exports.FIELD_TYPES_UNAVAILABLE_TTL_MS = 30 * 1000;
264
+ /** A read that returns this many rows may be cut short, so it is unavailable. */
265
+ exports.MAX_HIDDEN_DICTIONARY_ROWS = 10_000;
266
+ const MAX_HIERARCHY_DEPTH = 12;
267
+ const MAX_VIEW_SOURCE_ROWS = 1_000;
268
+ const MAX_DOT_WALK_HOPS = 8;
269
+ const FIELD_NAME = /^[a-z][a-z0-9_]{0,79}$/u;
270
+ const DICTIONARY_MEMO_KEY = "hidden-values:dictionary:v1";
271
+ const TABLE_MEMO_PREFIX = "hidden-values:table:v1:";
272
+ const CHAIN_FLIGHT_PREFIX = "hidden-values:chain-read:v1:";
273
+ /**
274
+ * Resolve the hidden-typed fields of every table in `tables`.
275
+ *
276
+ * Requests, made with the call's own credentials and no table grant (the
277
+ * implicit metadata path the all-fields projection uses): one instance-wide
278
+ * `sys_dictionary` read of the hidden types, one `sys_db_object` read for the
279
+ * chains of all the tables not yet known, and, only for a name with no
280
+ * `sys_db_object` row, one `sys_db_view_table` read (plus the joined tables'
281
+ * chains). Each result is kept in the metadata cache's per-credential memo
282
+ * (`derivedMetadataMemo`), so a later call that finds everything there makes
283
+ * no request at all; the reads skip the cache's watermark, since the memo is
284
+ * their cache. The dictionary and chain reads run in parallel, and concurrent
285
+ * calls in one scope share each read in flight (one per key). `forceRecache`
286
+ * skips the memo.
287
+ *
288
+ * The dictionary read failing, returning no rows, or returning a full page
289
+ * gives `unavailable`. A table whose chain or view cannot be resolved is left
290
+ * out of `tables`, so its fields are `unknown_type`. A cancelled read rethrows.
291
+ */
292
+ async function loadFieldTypes(client, tablesCandidate, options = {}) {
293
+ const memo = (0, metadata_cache_js_1.derivedMetadataMemo)(client);
294
+ const force = options.forceRecache === true;
295
+ // The memo is the cache for these reads. Through the metadata cache each
296
+ // would also cost a watermark read, and a sys_dictionary watermark costs
297
+ // more than the plain read (see SMALL_READ_BYTES), so they go straight up.
298
+ const reader = (0, metadata_cache_js_1.uncachedOperations)(client);
299
+ const requested = [...new Set([...tablesCandidate].map(normalizeName))].filter((name) => name !== undefined);
300
+ const chains = new Map();
301
+ const views = new Map();
302
+ const remember = (table, entry) => memo?.set(TABLE_MEMO_PREFIX + table, entry, 128 + JSON.stringify(entry).length, exports.FIELD_TYPES_TTL_MS);
303
+ const recall = (table) => {
304
+ const known = force ? undefined : memo?.get(TABLE_MEMO_PREFIX + table);
305
+ if (!isTableShape(known))
306
+ return false;
307
+ if (known.kind === "table")
308
+ chains.set(table, known.chain);
309
+ else {
310
+ chains.set(table, null);
311
+ views.set(table, known.sources);
312
+ }
313
+ return true;
314
+ };
315
+ const pending = requested.filter((table) => !recall(table));
316
+ // The dictionary and the chains do not depend on each other: one round trip.
317
+ const [dictionary, read] = await Promise.all([
318
+ hiddenDictionary(reader, memo, force),
319
+ pending.length === 0
320
+ ? Promise.resolve(new Map())
321
+ : sharedChains(reader, memo, pending),
322
+ ]);
323
+ if (dictionary === "unavailable")
324
+ return exports.FIELD_TYPES_UNAVAILABLE;
325
+ if (pending.length > 0) {
326
+ for (const [table, chain] of read) {
327
+ chains.set(table, chain);
328
+ if (chain !== null)
329
+ remember(table, Object.freeze({ kind: "table", chain }));
330
+ }
331
+ const absent = pending.filter((table) => read.get(table) === null);
332
+ if (absent.length > 0) {
333
+ for (const [view, sources] of await viewSources(reader, absent)) {
334
+ views.set(view, sources);
335
+ remember(view, Object.freeze({ kind: "view", sources: Object.freeze(sources) }));
336
+ }
337
+ }
338
+ }
339
+ // The tables joined by a view need their own chains.
340
+ const joined = [...new Set([...views.values()].flat().map((source) => source.table))].filter((table) => !chains.has(table) && !recall(table));
341
+ if (joined.length > 0) {
342
+ for (const [table, chain] of await sharedChains(reader, memo, joined)) {
343
+ chains.set(table, chain);
344
+ if (chain !== null)
345
+ remember(table, Object.freeze({ kind: "table", chain }));
346
+ }
347
+ }
348
+ const tables = new Map();
349
+ for (const table of requested) {
350
+ const resolved = resolveTable(table, chains, views, dictionary);
351
+ if (resolved !== undefined)
352
+ tables.set(table, resolved);
353
+ }
354
+ return Object.freeze({ state: "available", tables });
355
+ }
356
+ function isTableShape(candidate) {
357
+ if (typeof candidate !== "object" || candidate === null)
358
+ return false;
359
+ const shape = candidate;
360
+ return ((shape.kind === "table" && Array.isArray(shape.chain)) ||
361
+ (shape.kind === "view" && Array.isArray(shape.sources)));
362
+ }
363
+ function resolveTable(table, chains, views, dictionary) {
364
+ const chain = chains.get(table);
365
+ if (chain === undefined)
366
+ return undefined;
367
+ if (chain !== null)
368
+ return resolvedTable(chain, inheritedHidden(chain, dictionary));
369
+ // No sys_db_object row: only a database view resolves; a view column is
370
+ // `<prefix>_<field>` of the table joined under that prefix.
371
+ const sources = views.get(table);
372
+ if (sources === undefined || sources.length === 0)
373
+ return undefined;
374
+ const hidden = new Map();
375
+ const hierarchy = [table];
376
+ for (const source of sources) {
377
+ const sourceChain = chains.get(source.table);
378
+ if (sourceChain === undefined || sourceChain === null)
379
+ return undefined;
380
+ hierarchy.push(...sourceChain.filter((entry) => !hierarchy.includes(entry)));
381
+ for (const [element, type] of inheritedHidden(sourceChain, dictionary)) {
382
+ const column = `${source.prefix}_${element}`;
383
+ if (FIELD_NAME.test(column))
384
+ hidden.set(column, type);
385
+ }
386
+ }
387
+ return resolvedTable(hierarchy, hidden);
388
+ }
389
+ function inheritedHidden(chain, dictionary) {
390
+ const hidden = new Map();
391
+ for (const owner of chain) {
392
+ for (const [element, type] of dictionary.get(owner) ?? []) {
393
+ if (!hidden.has(element))
394
+ hidden.set(element, type);
395
+ }
396
+ }
397
+ return hidden;
398
+ }
399
+ function resolvedTable(hierarchy, hidden, allTypes) {
400
+ return Object.freeze({
401
+ hierarchy: Object.freeze([...hierarchy]),
402
+ hidden,
403
+ hiddenNames: new Set(hidden.keys()),
404
+ ...(allTypes === undefined ? {} : { allTypes }),
405
+ });
406
+ }
407
+ /**
408
+ * The instance-wide map of hidden-typed fields, by defining table. The same
409
+ * implicit metadata read the all-fields projection makes (`sys_dictionary`
410
+ * through the call's cached operations), so it needs no table grant.
411
+ */
412
+ async function hiddenDictionary(client, memo, force) {
413
+ const known = force ? undefined : memo?.get(DICTIONARY_MEMO_KEY);
414
+ if (known === "unavailable" || known instanceof Map)
415
+ return known;
416
+ return singleFlight(memo, DICTIONARY_MEMO_KEY, () => readDictionary(client, memo));
417
+ }
418
+ /**
419
+ * Run `start` once for every concurrent caller in the credential scope: a
420
+ * caller that finds the same key in flight waits for that read instead of
421
+ * making its own. Neither read here rejects for an instance's answer (a
422
+ * refusal or an error is the `unavailable` state, which every waiter gets);
423
+ * only a cancelled read rejects, and then the cancellation was the reading
424
+ * call's own, so a waiter reads for itself instead of failing.
425
+ */
426
+ async function singleFlight(memo, key, start) {
427
+ for (let attempt = 0; attempt < 2; attempt += 1) {
428
+ const pending = memo?.pending(key);
429
+ if (pending === undefined)
430
+ break;
431
+ try {
432
+ return await pending;
433
+ }
434
+ catch {
435
+ // The reading call was cancelled; look again, or read.
436
+ }
437
+ }
438
+ const promise = start();
439
+ return memo === undefined ? promise : memo.track(key, promise);
440
+ }
441
+ /**
442
+ * {@link tableChains} with one read in flight per table across concurrent
443
+ * calls: tables another call is reading are waited for, the rest are read
444
+ * together in one request.
445
+ */
446
+ async function sharedChains(client, memo, tables) {
447
+ const waiting = [];
448
+ const own = [];
449
+ for (const table of tables) {
450
+ const pending = memo?.pending(CHAIN_FLIGHT_PREFIX + table);
451
+ if (pending === undefined)
452
+ own.push(table);
453
+ else
454
+ waiting.push([table, pending]);
455
+ }
456
+ const chains = new Map();
457
+ if (own.length > 0) {
458
+ const batch = tableChains(client, own);
459
+ for (const table of own) {
460
+ memo?.track(CHAIN_FLIGHT_PREFIX + table, batch.then((read) => read.get(table)));
461
+ }
462
+ for (const [table, chain] of await batch)
463
+ chains.set(table, chain);
464
+ }
465
+ const retry = [];
466
+ for (const [table, pending] of waiting) {
467
+ try {
468
+ const chain = await pending;
469
+ if (chain !== undefined)
470
+ chains.set(table, chain);
471
+ }
472
+ catch {
473
+ retry.push(table);
474
+ }
475
+ }
476
+ if (retry.length > 0) {
477
+ for (const [table, chain] of await tableChains(client, retry))
478
+ chains.set(table, chain);
479
+ }
480
+ return chains;
481
+ }
482
+ async function readDictionary(client, memo) {
483
+ let rows;
484
+ try {
485
+ const response = await client.getWithMeta("/api/now/table/sys_dictionary", {
486
+ sysparm_query: `internal_typeIN${exports.HIDDEN_FIELD_TYPES.join(",")}` + "^ORDERBYname^ORDERBYelement",
487
+ sysparm_fields: "name,element,internal_type",
488
+ sysparm_limit: String(exports.MAX_HIDDEN_DICTIONARY_ROWS),
489
+ sysparm_display_value: "false",
490
+ sysparm_exclude_reference_link: "true",
491
+ });
492
+ rows = response.status === 200 ? response.data?.result : undefined;
493
+ }
494
+ catch (error) {
495
+ if ((0, client_js_1.isServiceNowRequestCancellation)(error))
496
+ throw error;
497
+ memo?.set(DICTIONARY_MEMO_KEY, "unavailable", 64, exports.FIELD_TYPES_UNAVAILABLE_TTL_MS);
498
+ return "unavailable";
499
+ }
500
+ const parsed = parseDictionaryRows(rows);
501
+ if (parsed === "unavailable") {
502
+ memo?.set(DICTIONARY_MEMO_KEY, "unavailable", 64, exports.FIELD_TYPES_UNAVAILABLE_TTL_MS);
503
+ return parsed;
504
+ }
505
+ let bytes = 256;
506
+ for (const [table, fields] of parsed) {
507
+ bytes += table.length + 64;
508
+ for (const [element, type] of fields)
509
+ bytes += element.length + type.length + 32;
510
+ }
511
+ memo?.set(DICTIONARY_MEMO_KEY, parsed, bytes, exports.FIELD_TYPES_TTL_MS);
512
+ return parsed;
513
+ }
514
+ /**
515
+ * Rows to a frozen map. No rows at all means the rows were hidden from this
516
+ * user (every instance has hidden-typed fields, `sys_user.user_password`
517
+ * among them), and a full page may be cut short: both are unavailable.
518
+ */
519
+ function parseDictionaryRows(rows) {
520
+ if (!Array.isArray(rows) || rows.length === 0 || rows.length >= exports.MAX_HIDDEN_DICTIONARY_ROWS) {
521
+ return "unavailable";
522
+ }
523
+ const byTable = new Map();
524
+ for (const row of rows) {
525
+ if (typeof row !== "object" || row === null)
526
+ continue;
527
+ const record = row;
528
+ const table = normalizeName(storedText(record.name));
529
+ const element = normalizeName(storedText(record.element));
530
+ const type = storedText(record.internal_type)?.trim().toLowerCase();
531
+ if (table === undefined || element === undefined || !isHiddenFieldType(type))
532
+ continue;
533
+ let fields = byTable.get(table);
534
+ if (!fields)
535
+ byTable.set(table, (fields = new Map()));
536
+ fields.set(element, type);
537
+ }
538
+ if (byTable.size === 0)
539
+ return "unavailable";
540
+ return byTable;
541
+ }
542
+ /** Chains for `tables`, in one read. Unread tables are left out of the map. */
543
+ async function tableChains(client, tables) {
544
+ const chains = new Map();
545
+ const ancestorFields = Array.from({ length: MAX_HIERARCHY_DEPTH - 1 }, (_, index) => `${"super_class.".repeat(index + 1)}name`);
546
+ let rows;
547
+ try {
548
+ const response = await client.getWithMeta("/api/now/table/sys_db_object", {
549
+ sysparm_query: `nameIN${tables.join(",")}`,
550
+ sysparm_fields: ["name", ...ancestorFields].join(","),
551
+ sysparm_limit: String(tables.length),
552
+ sysparm_display_value: "false",
553
+ sysparm_exclude_reference_link: "true",
554
+ });
555
+ rows = response.status === 200 ? response.data?.result : undefined;
556
+ }
557
+ catch (error) {
558
+ if ((0, client_js_1.isServiceNowRequestCancellation)(error))
559
+ throw error;
560
+ return chains;
561
+ }
562
+ if (!Array.isArray(rows))
563
+ return chains;
564
+ for (const row of rows) {
565
+ if (typeof row !== "object" || row === null)
566
+ continue;
567
+ const record = row;
568
+ const table = normalizeName(storedText(record.name));
569
+ if (table === undefined || !tables.includes(table))
570
+ continue;
571
+ const chain = [table];
572
+ for (const field of ancestorFields) {
573
+ const ancestor = normalizeName(storedText(record[field]));
574
+ if (ancestor === undefined || chain.includes(ancestor))
575
+ break;
576
+ chain.push(ancestor);
577
+ }
578
+ chains.set(table, Object.freeze(chain));
579
+ }
580
+ // The read succeeded: a table it did not return has no sys_db_object row.
581
+ for (const table of tables)
582
+ if (!chains.has(table))
583
+ chains.set(table, null);
584
+ return chains;
585
+ }
586
+ /** Joined tables of the database views among `tables`. Unread views are left out. */
587
+ async function viewSources(client, tables) {
588
+ const views = new Map();
589
+ let rows;
590
+ try {
591
+ const response = await client.getWithMeta("/api/now/table/sys_db_view_table", {
592
+ sysparm_query: `view.nameIN${tables.join(",")}`,
593
+ sysparm_fields: "view.name,table,variable_prefix",
594
+ sysparm_limit: String(MAX_VIEW_SOURCE_ROWS),
595
+ sysparm_display_value: "false",
596
+ sysparm_exclude_reference_link: "true",
597
+ });
598
+ rows = response.status === 200 ? response.data?.result : undefined;
599
+ }
600
+ catch (error) {
601
+ if ((0, client_js_1.isServiceNowRequestCancellation)(error))
602
+ throw error;
603
+ return views;
604
+ }
605
+ if (!Array.isArray(rows) || rows.length >= MAX_VIEW_SOURCE_ROWS)
606
+ return views;
607
+ const broken = new Set();
608
+ for (const row of rows) {
609
+ if (typeof row !== "object" || row === null)
610
+ continue;
611
+ const record = row;
612
+ const view = normalizeName(storedText(record["view.name"]));
613
+ if (view === undefined || !tables.includes(view))
614
+ continue;
615
+ const table = normalizeName(storedText(record.table));
616
+ const prefix = normalizeName(storedText(record.variable_prefix));
617
+ // A joined table without a name or prefix cannot be projected: the view
618
+ // stays unresolved rather than missing that table's hidden fields.
619
+ if (table === undefined || prefix === undefined) {
620
+ broken.add(view);
621
+ continue;
622
+ }
623
+ let sources = views.get(view);
624
+ if (!sources)
625
+ views.set(view, (sources = []));
626
+ sources.push(Object.freeze({ table, prefix }));
627
+ }
628
+ for (const view of broken)
629
+ views.delete(view);
630
+ return views;
631
+ }
632
+ function storedText(candidate) {
633
+ if (typeof candidate === "string")
634
+ return candidate;
635
+ if (typeof candidate === "object" && candidate !== null && !Array.isArray(candidate)) {
636
+ const value = candidate.value;
637
+ if (typeof value === "string")
638
+ return value;
639
+ }
640
+ return undefined;
641
+ }
642
+ function normalizeName(candidate) {
643
+ if (typeof candidate !== "string")
644
+ return undefined;
645
+ const normalized = candidate.trim().toLowerCase();
646
+ return FIELD_NAME.test(normalized) ? normalized : undefined;
647
+ }
648
+ const HIDDEN_FIELD_SCOPE = new node_async_hooks_1.AsyncLocalStorage();
649
+ /** Run `callback` with `scope` as the call's hidden-typed fields. */
650
+ function runWithHiddenFieldScope(scope, callback) {
651
+ return HIDDEN_FIELD_SCOPE.run(Object.freeze({ tables: scope.tables, unresolved: scope.unresolved }), callback);
652
+ }
653
+ /** The scope of the running call, if the dispatcher set one. */
654
+ function currentHiddenFieldScope() {
655
+ return HIDDEN_FIELD_SCOPE.getStore();
656
+ }
657
+ /**
658
+ * The scope for a call over `tables`. Unavailable types, or a table that did
659
+ * not resolve, deny unless `namesOnly` (the profile's opt-out) is set; then
660
+ * they fall back to name-only hiding and `degraded` is true so the caller can
661
+ * warn.
662
+ */
663
+ function hiddenFieldScope(types, tables, namesOnly) {
664
+ const resolved = new Map();
665
+ let missing = types.state !== "available";
666
+ for (const candidate of tables) {
667
+ const table = normalizeName(candidate);
668
+ if (table === undefined)
669
+ continue;
670
+ const hidden = hiddenTypedFields(types, table);
671
+ if (hidden === undefined) {
672
+ missing = true;
673
+ if (namesOnly)
674
+ resolved.set(table, EMPTY_SET);
675
+ continue;
676
+ }
677
+ resolved.set(table, hidden);
678
+ }
679
+ if (missing && !namesOnly)
680
+ return { degraded: false };
681
+ return {
682
+ scope: Object.freeze({ tables: resolved, unresolved: namesOnly ? "names_only" : "deny" }),
683
+ degraded: missing,
684
+ };
685
+ }
686
+ const EMPTY_SET = Object.freeze(new Set());
687
+ /**
688
+ * The fixed refusal when field types cannot be read and the profile has not
689
+ * opted out. It names what to grant; it carries no table or field name.
690
+ */
691
+ exports.FIELD_TYPES_UNAVAILABLE_MESSAGE = "Access denied by policy: field types could not be read from the instance, so " +
692
+ "password-type fields cannot be told apart from other fields. Grant the integration " +
693
+ "user read access to sys_dictionary and sys_db_object (and sys_db_view_table for " +
694
+ "database views), or set \"fieldTypes\": { \"dictionary\": \"not_required\" } on this " +
695
+ "profile to hide fields by name only.";
696
+ const FIELD_TYPES_CONFIG_KEYS = Object.freeze(["dictionary"]);
697
+ const FIELD_TYPES_DICTIONARY_ENV = "SN_FIELD_TYPES_DICTIONARY";
698
+ /** A profile's `fieldTypes` is invalid; the message names only the key. */
699
+ class FieldTypesConfigurationError extends Error {
700
+ constructor(message) {
701
+ super(message);
702
+ this.name = "FieldTypesConfigurationError";
703
+ }
704
+ }
705
+ exports.FieldTypesConfigurationError = FieldTypesConfigurationError;
706
+ /** Validate a profile's `fieldTypes` block; throws on any other shape. */
707
+ function validateFieldTypesConfig(candidate) {
708
+ if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) {
709
+ throw new FieldTypesConfigurationError("fieldTypes must be an object");
710
+ }
711
+ for (const key of Object.keys(candidate)) {
712
+ if (!FIELD_TYPES_CONFIG_KEYS.includes(key)) {
713
+ throw new FieldTypesConfigurationError(`fieldTypes supports only ${FIELD_TYPES_CONFIG_KEYS.join(", ")}`);
714
+ }
715
+ }
716
+ const dictionary = candidate.dictionary;
717
+ if (dictionary !== undefined && dictionary !== "required" && dictionary !== "not_required") {
718
+ throw new FieldTypesConfigurationError('fieldTypes.dictionary must be "required" or "not_required"');
719
+ }
720
+ return Object.freeze(dictionary === undefined ? {} : { dictionary });
721
+ }
722
+ /** The environment profile's `fieldTypes`, from SN_FIELD_TYPES_DICTIONARY. */
723
+ function fieldTypesConfigFromEnvironment(environment = process.env) {
724
+ const raw = environment[FIELD_TYPES_DICTIONARY_ENV]?.trim();
725
+ if (raw === undefined || raw === "")
726
+ return Object.freeze({});
727
+ if (raw !== "required" && raw !== "not_required") {
728
+ throw new FieldTypesConfigurationError(`${FIELD_TYPES_DICTIONARY_ENV} must be "required" or "not_required"`);
729
+ }
730
+ return Object.freeze({ dictionary: raw });
731
+ }
732
+ /** True when the profile opted out of requiring the field types. */
733
+ function dictionaryNotRequired(config) {
734
+ return config?.dictionary === "not_required";
735
+ }
736
+ /**
737
+ * The startup warning for profiles that opted out of requiring the field
738
+ * types, or undefined when none did. Profile names are JSON-quoted.
739
+ */
740
+ function fieldTypesOptOutWarning(profiles) {
741
+ if (profiles.length === 0)
742
+ return undefined;
743
+ return (`[servicenow-mcp] WARNING: ${profiles.length} profile(s) set fieldTypes.dictionary ` +
744
+ `to "not_required" (${profiles.map((name) => JSON.stringify(name)).join(", ")}): while ` +
745
+ "the instance's field types cannot be read, their tools hide password-type fields " +
746
+ "by name only.\n");
747
+ }
748
+ //# sourceMappingURL=hidden-values.js.map