@onlyflows/servicenow-mcp 2.2.0-dev.5 → 2.2.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 (251) hide show
  1. package/.env.example +6 -3
  2. package/CHANGELOG.md +312 -0
  3. package/README.md +504 -101
  4. package/dist/atf-form.d.ts +3 -15
  5. package/dist/atf-form.d.ts.map +1 -1
  6. package/dist/atf-result-cache.d.ts +23 -59
  7. package/dist/atf-result-cache.d.ts.map +1 -1
  8. package/dist/auth.d.ts +1 -0
  9. package/dist/auth.d.ts.map +1 -1
  10. package/dist/auth.js +17 -0
  11. package/dist/auth.js.map +1 -1
  12. package/dist/batch-limits.d.ts +18 -0
  13. package/dist/batch-limits.d.ts.map +1 -0
  14. package/dist/batch-limits.js +21 -0
  15. package/dist/batch-limits.js.map +1 -0
  16. package/dist/bounded-input.d.ts +49 -0
  17. package/dist/bounded-input.d.ts.map +1 -0
  18. package/dist/bounded-input.js +81 -0
  19. package/dist/bounded-input.js.map +1 -0
  20. package/dist/client.d.ts +25 -0
  21. package/dist/client.d.ts.map +1 -1
  22. package/dist/client.js +92 -18
  23. package/dist/client.js.map +1 -1
  24. package/dist/command-resolution.d.ts +53 -0
  25. package/dist/command-resolution.d.ts.map +1 -0
  26. package/dist/command-resolution.js +154 -0
  27. package/dist/command-resolution.js.map +1 -0
  28. package/dist/encoded-query-policy.d.ts +11 -0
  29. package/dist/encoded-query-policy.d.ts.map +1 -1
  30. package/dist/encoded-query-policy.js +10 -1
  31. package/dist/encoded-query-policy.js.map +1 -1
  32. package/dist/field-policy.d.ts +82 -3
  33. package/dist/field-policy.d.ts.map +1 -1
  34. package/dist/field-policy.js +609 -80
  35. package/dist/field-policy.js.map +1 -1
  36. package/dist/html-response.d.ts +34 -0
  37. package/dist/html-response.d.ts.map +1 -0
  38. package/dist/html-response.js +72 -0
  39. package/dist/html-response.js.map +1 -0
  40. package/dist/http-runtime.d.ts.map +1 -1
  41. package/dist/http-runtime.js +8 -0
  42. package/dist/http-runtime.js.map +1 -1
  43. package/dist/incident-journal-policy.d.ts +27 -5
  44. package/dist/incident-journal-policy.d.ts.map +1 -1
  45. package/dist/incident-journal-policy.js +34 -21
  46. package/dist/incident-journal-policy.js.map +1 -1
  47. package/dist/json-shape-limits.d.ts +71 -0
  48. package/dist/json-shape-limits.d.ts.map +1 -0
  49. package/dist/json-shape-limits.js +131 -0
  50. package/dist/json-shape-limits.js.map +1 -0
  51. package/dist/metadata-cache.d.ts +46 -21
  52. package/dist/metadata-cache.d.ts.map +1 -1
  53. package/dist/metadata-cache.js +228 -195
  54. package/dist/metadata-cache.js.map +1 -1
  55. package/dist/policy-card.d.ts +131 -0
  56. package/dist/policy-card.d.ts.map +1 -0
  57. package/dist/policy-card.js +409 -0
  58. package/dist/policy-card.js.map +1 -0
  59. package/dist/profile-admin.d.ts.map +1 -1
  60. package/dist/profile-admin.js +3 -0
  61. package/dist/profile-admin.js.map +1 -1
  62. package/dist/profile-manager.d.ts +17 -3
  63. package/dist/profile-manager.d.ts.map +1 -1
  64. package/dist/profile-manager.js +98 -6
  65. package/dist/profile-manager.js.map +1 -1
  66. package/dist/record-identifier-policy.d.ts +2 -8
  67. package/dist/record-identifier-policy.d.ts.map +1 -1
  68. package/dist/risky-grants.d.ts +25 -0
  69. package/dist/risky-grants.d.ts.map +1 -0
  70. package/dist/risky-grants.js +77 -0
  71. package/dist/risky-grants.js.map +1 -0
  72. package/dist/server.d.ts.map +1 -1
  73. package/dist/server.js +74 -0
  74. package/dist/server.js.map +1 -1
  75. package/dist/setup-prompts.js +1 -0
  76. package/dist/setup-prompts.js.map +1 -1
  77. package/dist/setup.d.ts +8 -1
  78. package/dist/setup.d.ts.map +1 -1
  79. package/dist/setup.js +492 -111
  80. package/dist/setup.js.map +1 -1
  81. package/dist/stdio-runtime.d.ts +15 -0
  82. package/dist/stdio-runtime.d.ts.map +1 -1
  83. package/dist/stdio-runtime.js +60 -0
  84. package/dist/stdio-runtime.js.map +1 -1
  85. package/dist/structured-query.d.ts +100 -115
  86. package/dist/structured-query.d.ts.map +1 -1
  87. package/dist/structured-query.js +132 -16
  88. package/dist/structured-query.js.map +1 -1
  89. package/dist/table-policy.d.ts +10 -4
  90. package/dist/table-policy.d.ts.map +1 -1
  91. package/dist/table-policy.js +1 -1
  92. package/dist/table-policy.js.map +1 -1
  93. package/dist/tool-error.d.ts +18 -0
  94. package/dist/tool-error.d.ts.map +1 -1
  95. package/dist/tool-error.js +69 -0
  96. package/dist/tool-error.js.map +1 -1
  97. package/dist/tool-table-access.d.ts.map +1 -1
  98. package/dist/tool-table-access.js +32 -2
  99. package/dist/tool-table-access.js.map +1 -1
  100. package/dist/tools/aggregate.d.ts +13 -19
  101. package/dist/tools/aggregate.d.ts.map +1 -1
  102. package/dist/tools/aggregate.js +2 -3
  103. package/dist/tools/aggregate.js.map +1 -1
  104. package/dist/tools/all-fields-cap.d.ts.map +1 -1
  105. package/dist/tools/all-fields-cap.js +3 -38
  106. package/dist/tools/all-fields-cap.js.map +1 -1
  107. package/dist/tools/atf-author-module.d.ts +28 -7
  108. package/dist/tools/atf-author-module.d.ts.map +1 -1
  109. package/dist/tools/atf-author-module.js +4 -2
  110. package/dist/tools/atf-author-module.js.map +1 -1
  111. package/dist/tools/atf-contracts.d.ts +135 -829
  112. package/dist/tools/atf-contracts.d.ts.map +1 -1
  113. package/dist/tools/atf-shared.js +2 -2
  114. package/dist/tools/atf-shared.js.map +1 -1
  115. package/dist/tools/atf-step-catalog.d.ts +3 -7
  116. package/dist/tools/atf-step-catalog.d.ts.map +1 -1
  117. package/dist/tools/atf-step-catalog.js +12 -5
  118. package/dist/tools/atf-step-catalog.js.map +1 -1
  119. package/dist/tools/atf.d.ts +8 -24
  120. package/dist/tools/atf.d.ts.map +1 -1
  121. package/dist/tools/atf.js +2 -2
  122. package/dist/tools/atf.js.map +1 -1
  123. package/dist/tools/attach.d.ts +6 -22
  124. package/dist/tools/attach.d.ts.map +1 -1
  125. package/dist/tools/batch.d.ts +18 -71
  126. package/dist/tools/batch.d.ts.map +1 -1
  127. package/dist/tools/batch.js +544 -96
  128. package/dist/tools/batch.js.map +1 -1
  129. package/dist/tools/catalog.d.ts +2 -2
  130. package/dist/tools/catalog.d.ts.map +1 -1
  131. package/dist/tools/catalog.js +7 -1
  132. package/dist/tools/catalog.js.map +1 -1
  133. package/dist/tools/codesearch.d.ts +1 -13
  134. package/dist/tools/codesearch.d.ts.map +1 -1
  135. package/dist/tools/create-module.d.ts +9 -14
  136. package/dist/tools/create-module.d.ts.map +1 -1
  137. package/dist/tools/create-module.js +4 -8
  138. package/dist/tools/create-module.js.map +1 -1
  139. package/dist/tools/delete.d.ts +1 -9
  140. package/dist/tools/delete.d.ts.map +1 -1
  141. package/dist/tools/delete.js +2 -3
  142. package/dist/tools/delete.js.map +1 -1
  143. package/dist/tools/discover.d.ts +6 -14
  144. package/dist/tools/discover.d.ts.map +1 -1
  145. package/dist/tools/flow-view-contracts.d.ts +1023 -0
  146. package/dist/tools/flow-view-contracts.d.ts.map +1 -0
  147. package/dist/tools/flow-view-contracts.js +570 -0
  148. package/dist/tools/flow-view-contracts.js.map +1 -0
  149. package/dist/tools/flow-view-graph.d.ts +86 -0
  150. package/dist/tools/flow-view-graph.d.ts.map +1 -0
  151. package/dist/tools/flow-view-graph.js +993 -0
  152. package/dist/tools/flow-view-graph.js.map +1 -0
  153. package/dist/tools/flow-view-gzip.d.ts +52 -0
  154. package/dist/tools/flow-view-gzip.d.ts.map +1 -0
  155. package/dist/tools/flow-view-gzip.js +179 -0
  156. package/dist/tools/flow-view-gzip.js.map +1 -0
  157. package/dist/tools/flow-view-mermaid.d.ts +37 -0
  158. package/dist/tools/flow-view-mermaid.d.ts.map +1 -0
  159. package/dist/tools/flow-view-mermaid.js +337 -0
  160. package/dist/tools/flow-view-mermaid.js.map +1 -0
  161. package/dist/tools/flow-view-module.d.ts +61 -0
  162. package/dist/tools/flow-view-module.d.ts.map +1 -0
  163. package/dist/tools/flow-view-module.js +378 -0
  164. package/dist/tools/flow-view-module.js.map +1 -0
  165. package/dist/tools/flow-view-policy.d.ts +106 -0
  166. package/dist/tools/flow-view-policy.d.ts.map +1 -0
  167. package/dist/tools/flow-view-policy.js +461 -0
  168. package/dist/tools/flow-view-policy.js.map +1 -0
  169. package/dist/tools/flow-view-renderers.d.ts +68 -0
  170. package/dist/tools/flow-view-renderers.d.ts.map +1 -0
  171. package/dist/tools/flow-view-renderers.js +513 -0
  172. package/dist/tools/flow-view-renderers.js.map +1 -0
  173. package/dist/tools/flow-view-table.d.ts +115 -0
  174. package/dist/tools/flow-view-table.d.ts.map +1 -0
  175. package/dist/tools/flow-view-table.js +1002 -0
  176. package/dist/tools/flow-view-table.js.map +1 -0
  177. package/dist/tools/get-module.d.ts +36 -42
  178. package/dist/tools/get-module.d.ts.map +1 -1
  179. package/dist/tools/health.d.ts +9 -6
  180. package/dist/tools/health.d.ts.map +1 -1
  181. package/dist/tools/incident-journal-module.d.ts +8 -7
  182. package/dist/tools/incident-journal-module.d.ts.map +1 -1
  183. package/dist/tools/index.d.ts +4 -4
  184. package/dist/tools/index.d.ts.map +1 -1
  185. package/dist/tools/index.js +43 -6
  186. package/dist/tools/index.js.map +1 -1
  187. package/dist/tools/markdown.d.ts +27 -0
  188. package/dist/tools/markdown.d.ts.map +1 -1
  189. package/dist/tools/markdown.js +104 -1
  190. package/dist/tools/markdown.js.map +1 -1
  191. package/dist/tools/nl.d.ts +1 -11
  192. package/dist/tools/nl.d.ts.map +1 -1
  193. package/dist/tools/profile.d.ts +1 -1
  194. package/dist/tools/profile.d.ts.map +1 -1
  195. package/dist/tools/profile.js +19 -1
  196. package/dist/tools/profile.js.map +1 -1
  197. package/dist/tools/query-module.d.ts +59 -71
  198. package/dist/tools/query-module.d.ts.map +1 -1
  199. package/dist/tools/query-module.js +2 -2
  200. package/dist/tools/query-module.js.map +1 -1
  201. package/dist/tools/record-write-shared.d.ts.map +1 -1
  202. package/dist/tools/record-write-shared.js +19 -2
  203. package/dist/tools/record-write-shared.js.map +1 -1
  204. package/dist/tools/relationships.d.ts +6 -22
  205. package/dist/tools/relationships.d.ts.map +1 -1
  206. package/dist/tools/result-envelope.d.ts +2255 -1357
  207. package/dist/tools/result-envelope.d.ts.map +1 -1
  208. package/dist/tools/result-envelope.js +24 -2
  209. package/dist/tools/result-envelope.js.map +1 -1
  210. package/dist/tools/schema-module.d.ts +36 -21
  211. package/dist/tools/schema-module.d.ts.map +1 -1
  212. package/dist/tools/schema-module.js +106 -65
  213. package/dist/tools/schema-module.js.map +1 -1
  214. package/dist/tools/script.d.ts +1 -11
  215. package/dist/tools/script.d.ts.map +1 -1
  216. package/dist/tools/syslog.d.ts +11 -18
  217. package/dist/tools/syslog.d.ts.map +1 -1
  218. package/dist/tools/syslog.js +2 -3
  219. package/dist/tools/syslog.js.map +1 -1
  220. package/dist/tools/table-hierarchy.d.ts +35 -0
  221. package/dist/tools/table-hierarchy.d.ts.map +1 -0
  222. package/dist/tools/table-hierarchy.js +74 -0
  223. package/dist/tools/table-hierarchy.js.map +1 -0
  224. package/dist/tools/tool-module.d.ts +40 -15
  225. package/dist/tools/tool-module.d.ts.map +1 -1
  226. package/dist/tools/tool-module.js +755 -205
  227. package/dist/tools/tool-module.js.map +1 -1
  228. package/dist/tools/update-module.d.ts +11 -17
  229. package/dist/tools/update-module.d.ts.map +1 -1
  230. package/dist/tools/update-module.js +10 -12
  231. package/dist/tools/update-module.js.map +1 -1
  232. package/dist/version.d.ts +1 -1
  233. package/dist/version.d.ts.map +1 -1
  234. package/dist/version.js +1 -1
  235. package/dist/version.js.map +1 -1
  236. package/dist/write-value-policy.d.ts +20 -12
  237. package/dist/write-value-policy.d.ts.map +1 -1
  238. package/dist/write-value-policy.js +179 -67
  239. package/dist/write-value-policy.js.map +1 -1
  240. package/docs/ADDING-TOOLS.md +22 -13
  241. package/docs/CLIENT-SETUP.md +110 -52
  242. package/docs/CROSS-CLIENT-RELEASE-MATRIX.md +2 -2
  243. package/docs/FLOW-VIEW.md +214 -0
  244. package/docs/PRODUCTION-SECURITY.md +154 -25
  245. package/docs/RELEASE-VALIDATION.md +2 -2
  246. package/docs/TESTING-OAUTH.md +1 -1
  247. package/docs/V2-MIGRATION.md +404 -30
  248. package/package.json +21 -6
  249. package/scripts/release-validate.mjs +56 -0
  250. package/server.json +22 -0
  251. package/tools/inspector/package-lock.json +163 -201
@@ -5,13 +5,15 @@
5
5
  * Table authorization answers whether a tool may reach a table. This module
6
6
  * supplies the second, independent boundary: which fields may be requested,
7
7
  * written, or returned for the supported V2 table domains. Built-in defaults
8
- * can be extended or overridden with SN_FIELD_POLICY_DEFINITIONS, including a
9
- * generic "*" table fallback for operator-approved custom-table access.
8
+ * can be narrowed per profile (`fieldPolicy`, `readableTableFields`,
9
+ * `writableTableFields`), including a generic "*" table fallback. The
10
+ * SN_FIELD_POLICY_DEFINITIONS variable feeds only the SN_PROFILE_NAME
11
+ * environment profile; this module never reads the process environment.
10
12
  *
11
13
  * @module field-policy
12
14
  */
13
15
  Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.FieldPolicyError = exports.SAFE_DEFAULT_FIELDS = exports.MAX_TOOL_ARGUMENT_OWN_KEYS = exports.MAX_FIELD_OBJECT_OWN_KEYS = exports.MAX_FIELD_ARRAY_LENGTH = exports.MAX_FIELD_VALUE_NODES = exports.MAX_FIELD_VALUE_DEPTH = exports.MAX_FIELDS_PER_OPERATION = void 0;
16
+ exports.FieldPolicyConfigurationError = exports.EXPLICIT_WRITE_FIELD_NAMES = exports.FieldPolicyError = exports.SAFE_DEFAULT_FIELDS = exports.BUILT_IN_TABLE_CLASSES = exports.MAX_TOOL_ARGUMENT_OWN_KEYS = exports.MAX_FIELD_OBJECT_OWN_KEYS = exports.MAX_FIELD_ARRAY_LENGTH = exports.MAX_FIELD_VALUE_NODES = exports.MAX_FIELD_VALUE_DEPTH = exports.MAX_FIELDS_PER_OPERATION = void 0;
15
17
  exports.fieldPolicyDenialMessage = fieldPolicyDenialMessage;
16
18
  exports.isFieldPolicyError = isFieldPolicyError;
17
19
  exports.snapshotPlainDataArguments = snapshotPlainDataArguments;
@@ -20,6 +22,7 @@ exports.resolveReadableFields = resolveReadableFields;
20
22
  exports.validateWritableFields = validateWritableFields;
21
23
  exports.prepareReadFieldArguments = prepareReadFieldArguments;
22
24
  exports.prepareAdditionalReadFieldArguments = prepareAdditionalReadFieldArguments;
25
+ exports.resolveWriteResponseFields = resolveWriteResponseFields;
23
26
  exports.prepareWriteFieldArguments = prepareWriteFieldArguments;
24
27
  exports.preparedReadableFields = preparedReadableFields;
25
28
  exports.filterReadableRecord = filterReadableRecord;
@@ -29,6 +32,9 @@ exports.runWithFieldPolicyConfiguration = runWithFieldPolicyConfiguration;
29
32
  exports.isAllFieldSelection = isAllFieldSelection;
30
33
  exports.fieldSelectionToSysparmFields = fieldSelectionToSysparmFields;
31
34
  exports.isSensitiveFieldName = isSensitiveFieldName;
35
+ exports.describeFieldPolicy = describeFieldPolicy;
36
+ exports.validateFieldPolicyConfiguration = validateFieldPolicyConfiguration;
37
+ exports.fieldPolicyInputFromEnvironment = fieldPolicyInputFromEnvironment;
32
38
  const node_async_hooks_1 = require("node:async_hooks");
33
39
  const node_util_1 = require("node:util");
34
40
  const FIELD_NAME = /^[a-z][a-z0-9_]{0,79}$/u;
@@ -49,6 +55,42 @@ const ALL_FIELDS_SELECTION = Object.freeze([FIELD_POLICY_WILDCARD]);
49
55
  * defaults the operator did not state. An unstated default must stay finite:
50
56
  * "may read any field" is not "return every field on every query". */
51
57
  const GENERIC_DEFAULT_FIELDS = Object.freeze(["sys_id"]);
58
+ /** Write-response projection for a write-only table (`readable: []`). The
59
+ * record's own handle is all a write returns there; denying the write instead
60
+ * would make a write-only policy unable to write anything. */
61
+ const WRITE_ONLY_RESPONSE_FIELDS = Object.freeze(["sys_id"]);
62
+ /** Configuration keys a scoped field policy may carry. */
63
+ const FIELD_POLICY_CONFIGURATION_KEYS = Object.freeze([
64
+ "fieldPolicy",
65
+ "readableTableFields",
66
+ "writableTableFields",
67
+ ]);
68
+ /** The two table-list keys; neither may be combined with `fieldPolicy`. */
69
+ const TABLE_FIELD_LIST_KEYS = Object.freeze([
70
+ "readableTableFields",
71
+ "writableTableFields",
72
+ ]);
73
+ /** Keys a `fieldPolicy` table entry may state. */
74
+ const TABLE_ENTRY_KEYS = Object.freeze(["defaults", "readable", "writable"]);
75
+ /** Keys a `{ table, fields }` list entry may state. */
76
+ const LIST_ENTRY_KEYS = Object.freeze(["table", "fields"]);
77
+ const FIELD_NAME_RULE = "letters, digits, and underscores, starting with a letter, at most 80 characters";
78
+ /**
79
+ * Fields that change what a record is rather than what it says:
80
+ * sys_class_name moves it to another class (table), and sys_domain moves it
81
+ * to another domain. sys_class_path and sys_domain_path encode the same
82
+ * class and domain (domain visibility matches on sys_domain_path), so a
83
+ * direct write to either could move the record without touching the other
84
+ * two. A writable wildcard, including the open built-in default, never
85
+ * covers any of them. They are writable only where a profile lists them in
86
+ * `writable`.
87
+ */
88
+ const EXPLICIT_WRITE_FIELDS = new Set([
89
+ "sys_class_name",
90
+ "sys_class_path",
91
+ "sys_domain",
92
+ "sys_domain_path",
93
+ ]);
52
94
  const INCIDENT_DEFAULTS = [
53
95
  "sys_id",
54
96
  "number",
@@ -62,6 +104,13 @@ const INCIDENT_DEFAULTS = [
62
104
  "sys_updated_on",
63
105
  "active",
64
106
  ];
107
+ /**
108
+ * Built-in table entries. Only `defaults`, the bounded projection a read gets
109
+ * when it names no fields, is applied (see FIELD_POLICY_BASE). The `readable`
110
+ * and `writable` lists below are not read by any code path: a `writable: []`
111
+ * here denies nothing. What a profile may read or write is decided by its
112
+ * own field policy, its tableAccess grant, and ServiceNow's ACLs.
113
+ */
65
114
  const POLICY_DEFINITIONS = {
66
115
  incident: {
67
116
  defaults: INCIDENT_DEFAULTS,
@@ -295,11 +344,12 @@ const POLICY_DEFINITIONS = {
295
344
  ],
296
345
  writable: [],
297
346
  },
298
- // Group membership grants every role the group holds. A write here escalates
299
- // the integration account to instance admin as surely as a sys_script write,
300
- // so the writable set is empty for the same reason. sys_user_role,
301
- // sys_user_has_role, and sys_group_has_role are hard-denied at the table
302
- // boundary (table-policy.ts); this table is not, so it is denied here.
347
+ // Group membership grants every role the group holds, so a write here can
348
+ // escalate the integration account as surely as a sys_script write. Nothing
349
+ // in this module denies it: like sys_user_role, sys_user_has_role, and
350
+ // sys_group_has_role (which have no entry here and no table-level block in
351
+ // table-policy.ts), it is writable exactly when the profile's tableAccess
352
+ // grants it and its field policy does not narrow it. Grant it deliberately.
303
353
  sys_user_grmember: {
304
354
  defaults: ["sys_id", "user", "group"],
305
355
  readable: ["sys_id", "user", "group", "sys_created_on", "sys_updated_on"],
@@ -589,6 +639,11 @@ const POLICY_DEFINITIONS = {
589
639
  *
590
640
  * The "*" entry makes every other table resolvable with the same posture, so
591
641
  * a granted custom table needs no field-policy entry to be usable.
642
+ *
643
+ * A profile's own "*" entry reaches further: it also covers the ITSM tables
644
+ * (ITSM_TABLES) and every table the profile names, key by key, wherever the
645
+ * table's own entry is silent. Only the system tables (SYSTEM_TABLES) are
646
+ * never covered by a "*" entry.
592
647
  */
593
648
  const FIELD_POLICY_BASE = Object.freeze({
594
649
  ...Object.fromEntries(Object.entries(POLICY_DEFINITIONS).map(([table, definition]) => [
@@ -606,6 +661,71 @@ const FIELD_POLICY_BASE = Object.freeze({
606
661
  }),
607
662
  });
608
663
  const BUILT_IN_TABLE_FIELD_POLICIES = buildFieldPolicyMap(FIELD_POLICY_BASE);
664
+ /**
665
+ * Built-in tables whose field policy belongs to the profile, like every
666
+ * custom table. For these, `readable` and `writable` resolve from the
667
+ * profile's own table entry, then the profile's "*" entry, then the built-in
668
+ * "*" (open). Their built-in `defaults` stay as a read-projection
669
+ * convenience, clamped to the effective readable set.
670
+ */
671
+ const ITSM_TABLES = new Set([
672
+ "incident",
673
+ "change_request",
674
+ "problem",
675
+ "sc_request",
676
+ "sc_req_item",
677
+ "sc_task",
678
+ "task",
679
+ "cmdb_ci",
680
+ "cmdb_ci_server",
681
+ "cmdb_ci_computer",
682
+ "kb_knowledge",
683
+ ]);
684
+ /**
685
+ * Every other built-in table is a system table (scripts, users and groups,
686
+ * ATF, application and dictionary metadata, syslog). It keeps its own
687
+ * built-in entry, a "*" entry never covers it, and it is narrowed only by
688
+ * naming it.
689
+ *
690
+ * This list is written out rather than derived as "built-in minus ITSM", so
691
+ * a new built-in entry never escapes every profile's "*" entry by default.
692
+ * Each built-in entry must be in exactly one of ITSM_TABLES and
693
+ * SYSTEM_TABLES; a test enforces this through BUILT_IN_TABLE_CLASSES.
694
+ */
695
+ const SYSTEM_TABLES = new Set([
696
+ "sys_user",
697
+ "sys_user_group",
698
+ "sys_user_grmember",
699
+ "syslog",
700
+ "sys_script",
701
+ "sys_script_include",
702
+ "sys_ui_script",
703
+ "sys_script_client",
704
+ "sys_ws_operation",
705
+ "sys_db_object",
706
+ "sys_app",
707
+ "sys_store_app",
708
+ "v_plugin",
709
+ "sys_atf_test",
710
+ "sys_atf_test_suite",
711
+ "sys_atf_test_suite_test",
712
+ "sys_atf_test_result",
713
+ "sys_atf_step",
714
+ "sys_element_mapping",
715
+ "sys_variable_value",
716
+ "sys_atf_test_suite_result",
717
+ "sys_atf_test_result_step",
718
+ "sys_atf_agent",
719
+ ]);
720
+ /**
721
+ * The built-in tables and how each is classified for a profile's "*" entry.
722
+ * Frozen copies for tests; the policy reads the sets above.
723
+ */
724
+ exports.BUILT_IN_TABLE_CLASSES = Object.freeze({
725
+ builtIn: Object.freeze(Object.keys(POLICY_DEFINITIONS)),
726
+ itsm: Object.freeze([...ITSM_TABLES]),
727
+ system: Object.freeze([...SYSTEM_TABLES]),
728
+ });
609
729
  const GENERIC_RECORD_TABLES = new Set([
610
730
  "incident",
611
731
  "change_request",
@@ -687,6 +807,20 @@ function fieldPolicyDenialMessage(error) {
687
807
  : "Access denied by policy: the requested table has no field policy entry.";
688
808
  case "sensitive_field":
689
809
  return "Access denied by policy: a requested field is denied by name as sensitive and cannot be granted by configuration.";
810
+ case "explicit_field_required":
811
+ // Only the EXPLICIT_WRITE_FIELDS names reach this case; each is a fixed
812
+ // name that passed FIELD_NAME.
813
+ return table && field
814
+ ? `Write denied by policy: field "${field}" on "${table}" changes the record's ` +
815
+ "class or domain, so a writable wildcard never covers it. List it explicitly " +
816
+ `in fieldPolicy.${table}.writable to allow this write.`
817
+ : "Write denied by policy: a class or domain field must be listed explicitly in the writable set.";
818
+ case "unsupported_field_path":
819
+ // The key itself is not echoed: as a whole it did not pass FIELD_NAME.
820
+ return (`Write denied by policy: write keys${table ? ` on "${table}"` : ""} must be plain field names. ` +
821
+ "Dot-walked names (such as caller_id.email) and catalog variables (variables.*) " +
822
+ "cannot be written through this tool. To change a dot-walked value, update the " +
823
+ "referenced record itself.");
690
824
  default:
691
825
  return `Access denied by policy (${error.reason}).`;
692
826
  }
@@ -782,13 +916,18 @@ function validateWritableFields(tableCandidate, payloadCandidate) {
782
916
  if (!("value" in descriptor)) {
783
917
  throw new FieldPolicyError("invalid_write_payload");
784
918
  }
785
- const field = normalizeFieldName(candidate);
919
+ const field = normalizeWriteFieldName(candidate, policy.table);
786
920
  if (Object.hasOwn(output, field)) {
787
921
  throw new FieldPolicyError("invalid_write_payload");
788
922
  }
789
923
  if (isSensitiveFieldName(field)) {
790
924
  throw new FieldPolicyError("sensitive_field", { table: policy.table });
791
925
  }
926
+ // policy.writable holds only explicitly listed names; it is empty when
927
+ // the writable set is a wildcard.
928
+ if (EXPLICIT_WRITE_FIELDS.has(field) && !policy.writable.includes(field)) {
929
+ throw new FieldPolicyError("explicit_field_required", { table: policy.table, field });
930
+ }
792
931
  if (!fieldSetAllows(policy.writable, policy.allowAnyWritable, field)) {
793
932
  throw new FieldPolicyError("non_writable_field", { table: policy.table, field });
794
933
  }
@@ -823,14 +962,21 @@ function prepareAdditionalReadFieldArguments(args, table, fields) {
823
962
  safeDefineArgument(prepared, PREPARED_FIELD_ACCESS, issuePreparedAccess(canonicalArgs, table, readableFields));
824
963
  return prepared;
825
964
  }
965
+ /**
966
+ * The projection a write returns for one table: the table's readable set, or
967
+ * `sys_id` alone when an operator made the table write-only (`readable: []`).
968
+ * A write is authorized by the writable set; an empty readable set narrows
969
+ * what comes back, it does not turn the write into a denial.
970
+ */
971
+ function resolveWriteResponseFields(tableCandidate) {
972
+ const selection = readableSelection(requirePolicy(tableCandidate));
973
+ return selection.length === 0 ? WRITE_ONLY_RESPONSE_FIELDS : selection;
974
+ }
826
975
  /** Validate write keys and prepare the corresponding safe response projection. */
827
976
  function prepareWriteFieldArguments(args, table) {
828
977
  const canonicalArgs = withFieldPolicyArgumentValues(args);
829
978
  const fields = validateWritableFields(table, canonicalArgs.fields);
830
- const readableFields = resolveReadableFields(table, {
831
- fields: "all",
832
- responseFormat: "detailed",
833
- });
979
+ const readableFields = resolveWriteResponseFields(table);
834
980
  const prepared = withFieldPolicyArgumentValues(canonicalArgs, { table, fields });
835
981
  safeDefineArgument(prepared, PREPARED_FIELD_ACCESS, issuePreparedAccess(canonicalArgs, table, readableFields));
836
982
  return prepared;
@@ -976,6 +1122,18 @@ function isSensitiveFieldName(candidate) {
976
1122
  return (/(?:^|_)(?:password|passwd|credential|credentials|secret|token|api_key|private_key|encryption_key|ssn)(?:_|$)/u.test(normalized) ||
977
1123
  normalized === "social_security_number");
978
1124
  }
1125
+ /** Names the writable wildcard never covers; a profile must list each one. */
1126
+ exports.EXPLICIT_WRITE_FIELD_NAMES = Object.freeze([
1127
+ ...EXPLICIT_WRITE_FIELDS,
1128
+ ]);
1129
+ function describeFieldPolicy(tableCandidate) {
1130
+ const policy = requirePolicy(tableCandidate);
1131
+ return Object.freeze({
1132
+ readable: policy.allowAnyReadable ? "*" : Object.freeze([...policy.readable]),
1133
+ writable: policy.allowAnyWritable ? "*" : Object.freeze([...policy.writable]),
1134
+ explicitWritable: Object.freeze(exports.EXPLICIT_WRITE_FIELD_NAMES.filter((field) => policy.writable.includes(field))),
1135
+ });
1136
+ }
979
1137
  function requirePolicy(tableCandidate) {
980
1138
  const table = normalizeTableName(tableCandidate);
981
1139
  const policies = currentTableFieldPolicies();
@@ -990,30 +1148,140 @@ function requirePolicy(tableCandidate) {
990
1148
  function fieldSetAllows(fields, allowAny, field) {
991
1149
  return allowAny || fields.includes(field);
992
1150
  }
1151
+ /**
1152
+ * Policy maps for configurations that validateFieldPolicyConfiguration
1153
+ * accepted, keyed by the identity of their three parts (fieldPolicy,
1154
+ * readableTableFields, writableTableFields; ABSENT_CONFIGURATION_PART for an
1155
+ * unstated one). Only deep-frozen parts are recorded, so an entry can never
1156
+ * describe content that changed after validation. The keys are the profile
1157
+ * snapshots ProfileManager hands out, so entries go when the snapshots go.
1158
+ */
1159
+ const VALIDATED_POLICY_MAPS = new WeakMap();
1160
+ const ABSENT_CONFIGURATION_PART = Object.freeze({});
1161
+ /** Deeper than any valid field policy: fieldPolicy.table.kind[entry]. */
1162
+ const MAX_CACHED_CONFIGURATION_DEPTH = 8;
993
1163
  function currentTableFieldPolicies() {
994
- const configured = readConfiguredFieldPolicyDefinitions();
1164
+ // Only the profile scope configures field policy. SN_FIELD_POLICY_DEFINITIONS
1165
+ // reaches this point solely as the SN_PROFILE_NAME environment profile's
1166
+ // own keys (profile-manager.ts), never as a process-wide fallback.
1167
+ const scoped = FIELD_POLICY_CONFIGURATION_SCOPE.getStore();
1168
+ if (!scoped ||
1169
+ (scoped.fieldPolicy === undefined &&
1170
+ scoped.readableTableFields === undefined &&
1171
+ scoped.writableTableFields === undefined)) {
1172
+ return BUILT_IN_TABLE_FIELD_POLICIES;
1173
+ }
1174
+ // A configuration that passed profile load was built once, there.
1175
+ const validated = validatedPolicyMap(scoped);
1176
+ if (validated)
1177
+ return validated;
1178
+ // Anything else takes the full fail-closed path on every call.
1179
+ const configured = normalizeConfiguredFieldPolicy(scoped);
995
1180
  if (!configured)
996
1181
  return BUILT_IN_TABLE_FIELD_POLICIES;
997
1182
  // Configuration narrows the base; it is the only thing that denies a field.
998
1183
  return buildFieldPolicyMap(mergeFieldPolicyDefinitions(FIELD_POLICY_BASE, configured.definitions));
999
1184
  }
1185
+ function configurationParts(input) {
1186
+ const parts = [input.fieldPolicy, input.readableTableFields, input.writableTableFields].map((part) => (part === undefined ? ABSENT_CONFIGURATION_PART : part));
1187
+ return parts.every((part) => typeof part === "object" && part !== null)
1188
+ ? parts
1189
+ : undefined;
1190
+ }
1191
+ function validatedPolicyMap(input) {
1192
+ const parts = configurationParts(input);
1193
+ if (!parts)
1194
+ return undefined;
1195
+ return VALIDATED_POLICY_MAPS.get(parts[0])?.get(parts[1])?.get(parts[2]);
1196
+ }
1197
+ /** Record a validated map, but only for parts that can no longer change. */
1198
+ function rememberValidatedPolicyMap(input, map) {
1199
+ const parts = configurationParts(input);
1200
+ if (!parts || !parts.every((part) => isDeepFrozen(part, 0)))
1201
+ return;
1202
+ let second = VALIDATED_POLICY_MAPS.get(parts[0]);
1203
+ if (!second) {
1204
+ second = new WeakMap();
1205
+ VALIDATED_POLICY_MAPS.set(parts[0], second);
1206
+ }
1207
+ let third = second.get(parts[1]);
1208
+ if (!third) {
1209
+ third = new WeakMap();
1210
+ second.set(parts[1], third);
1211
+ }
1212
+ third.set(parts[2], map);
1213
+ }
1214
+ function isDeepFrozen(candidate, depth) {
1215
+ if (typeof candidate !== "object" || candidate === null)
1216
+ return true;
1217
+ if (depth > MAX_CACHED_CONFIGURATION_DEPTH ||
1218
+ node_util_1.types.isProxy(candidate) ||
1219
+ !Object.isFrozen(candidate)) {
1220
+ return false;
1221
+ }
1222
+ return Object.values(candidate).every((value) => isDeepFrozen(value, depth + 1));
1223
+ }
1000
1224
  function mergeFieldPolicyDefinitions(base, configured) {
1001
1225
  const merged = { ...base };
1002
- for (const [table, definition] of Object.entries(configured)) {
1226
+ // A profile's "*" entry also covers the ITSM tables it does not name, so
1227
+ // they are merged even without an entry of their own.
1228
+ const profileWildcard = Object.hasOwn(configured, FIELD_POLICY_WILDCARD)
1229
+ ? configured[FIELD_POLICY_WILDCARD]
1230
+ : undefined;
1231
+ const tables = new Set(Object.keys(configured));
1232
+ if (profileWildcard !== undefined) {
1233
+ for (const table of ITSM_TABLES)
1234
+ tables.add(table);
1235
+ }
1236
+ for (const table of tables) {
1237
+ const definition = Object.hasOwn(configured, table)
1238
+ ? configured[table]
1239
+ : {};
1003
1240
  const existing = merged[table];
1241
+ // Every table but the system tables (ITSM and custom alike) resolves each
1242
+ // set from its own entry, then the profile's "*" entry, then the base. A
1243
+ // named custom table therefore cannot escape a narrowing "*" by stating
1244
+ // only the other key. System tables never take the "*" entry.
1245
+ const fallback = table === FIELD_POLICY_WILDCARD || SYSTEM_TABLES.has(table)
1246
+ ? undefined
1247
+ : profileWildcard;
1248
+ const readable = definition.readable ?? fallback?.readable;
1004
1249
  merged[table] = {
1005
1250
  defaults: definition.defaults ??
1006
- inheritedDefaults(existing?.defaults, definition.readable),
1251
+ (existing === undefined && definition.readable === undefined
1252
+ ? // A named custom table that leaves readable to the "*" entry
1253
+ // projects what an unnamed table does: the "*" entry's defaults,
1254
+ // else sys_id, clamped. Inheriting the whole "*" readable list
1255
+ // made a concise read ask for every readable column.
1256
+ clampedDefaults(fallback?.defaults ?? GENERIC_DEFAULT_FIELDS, readable)
1257
+ : // Built-in defaults are clamped to the effective readable set, so
1258
+ // a narrowed "*" never leaves a default the table may not read.
1259
+ // sys_id leads every built-in list and stays whenever readable.
1260
+ inheritedDefaults(existing?.defaults, readable)),
1007
1261
  // An entry that states only `defaults` reads exactly those fields.
1008
- readable: definition.readable ?? existing?.readable ?? definition.defaults,
1262
+ readable: readable ?? existing?.readable ?? definition.defaults,
1009
1263
  // Omission no longer denies. An operator who states nothing about
1010
1264
  // writes has not asked for a restriction, and tableAccess already
1011
1265
  // decided whether this table is reachable at all.
1012
- writable: definition.writable ?? existing?.writable,
1266
+ writable: definition.writable ?? fallback?.writable ?? existing?.writable,
1013
1267
  };
1014
1268
  }
1015
1269
  return merged;
1016
1270
  }
1271
+ /**
1272
+ * Clamp a default projection to a readable set, the way the "*" entry's own
1273
+ * defaults are clamped for an unnamed table: keep the defaults the set
1274
+ * allows, and fall back to the set itself only when none survive.
1275
+ */
1276
+ function clampedDefaults(defaults, readable) {
1277
+ if (readable === undefined || readable === FIELD_POLICY_WILDCARD)
1278
+ return defaults;
1279
+ if (defaults === FIELD_POLICY_WILDCARD)
1280
+ return readable;
1281
+ const allowed = new Set(readable);
1282
+ const permitted = defaults.filter((field) => allowed.has(field));
1283
+ return permitted.length > 0 ? permitted : readable;
1284
+ }
1017
1285
  /**
1018
1286
  * Carry inherited defaults across a configured `readable` replacement.
1019
1287
  *
@@ -1036,7 +1304,11 @@ function inheritedDefaults(existingDefaults, configuredReadable) {
1036
1304
  const permitted = existingDefaults.filter((field) => configuredReadable.includes(field));
1037
1305
  return permitted.length > 0 ? permitted : configuredReadable;
1038
1306
  }
1039
- function buildFieldPolicyMap(definitions) {
1307
+ /**
1308
+ * @param root Configuration key the definitions came from. Given only while a
1309
+ * configuration is validated at load, so a contradiction names its table.
1310
+ */
1311
+ function buildFieldPolicyMap(definitions, root) {
1040
1312
  return new Map(Object.entries(definitions).map(([tableCandidate, definition]) => {
1041
1313
  const table = normalizePolicyTableName(tableCandidate);
1042
1314
  // An unstated set is open. Only an explicit operator list narrows.
@@ -1047,13 +1319,21 @@ function buildFieldPolicyMap(definitions) {
1047
1319
  const defaults = defaultsCandidate === FIELD_POLICY_WILDCARD ? ALL_FIELDS_SELECTION : defaultsCandidate;
1048
1320
  const readableFields = readable === FIELD_POLICY_WILDCARD ? [] : readable;
1049
1321
  const writableFields = writable === FIELD_POLICY_WILDCARD ? [] : writable;
1050
- if (!isAllFieldSelection(defaults)) {
1322
+ if (isAllFieldSelection(defaults)) {
1323
+ // "Return every column by default" contradicts a narrowed readable
1324
+ // set: a concise read would ask ServiceNow for every field.
1325
+ if (readable !== FIELD_POLICY_WILDCARD) {
1326
+ rejectConfiguration(root === undefined ? undefined : { key: `${root}.${table}.defaults` }, `is "*" (every field), which ${root}.${table}.readable does not allow. ` +
1327
+ 'List the default fields, or make readable "*".');
1328
+ }
1329
+ }
1330
+ else {
1051
1331
  for (const field of defaults) {
1052
1332
  if (!fieldSetAllows(readableFields, readable === FIELD_POLICY_WILDCARD, field)) {
1053
1333
  // Branded so a contradictory operator policy is classified as a
1054
1334
  // policy denial instead of escaping the request path as a raw
1055
1335
  // TypeError.
1056
- throw new FieldPolicyError("invalid_argument_shape");
1336
+ rejectConfiguration(root === undefined ? undefined : { key: `${root}.${table}.defaults` }, `lists "${field}", which ${root}.${table}.readable does not allow.`);
1057
1337
  }
1058
1338
  }
1059
1339
  }
@@ -1070,68 +1350,240 @@ function buildFieldPolicyMap(definitions) {
1070
1350
  ];
1071
1351
  }));
1072
1352
  }
1073
- function readConfiguredFieldPolicyDefinitions() {
1074
- const scoped = FIELD_POLICY_CONFIGURATION_SCOPE.getStore();
1075
- if (scoped && (scoped.fieldPolicy !== undefined || scoped.readableTableFields !== undefined || scoped.writableTableFields !== undefined)) {
1076
- return normalizeConfiguredFieldPolicy(scoped);
1077
- }
1078
- const text = process.env[FIELD_POLICY_DEFINITIONS_ENV];
1353
+ /**
1354
+ * A malformed field-policy configuration, raised when a profile is loaded.
1355
+ *
1356
+ * The message names the key path to fix, and with it the table. It never
1357
+ * repeats a configured value that failed validation; a table or field name
1358
+ * appears only once it has passed FIELD_NAME.
1359
+ */
1360
+ class FieldPolicyConfigurationError extends Error {
1361
+ name = "FieldPolicyConfigurationError";
1362
+ }
1363
+ exports.FieldPolicyConfigurationError = FieldPolicyConfigurationError;
1364
+ const PROFILE_CONFIGURATION_LABELS = Object.freeze({
1365
+ fieldPolicy: "fieldPolicy",
1366
+ readableTableFields: "readableTableFields",
1367
+ writableTableFields: "writableTableFields",
1368
+ });
1369
+ /**
1370
+ * Reject a malformed profile field policy at load instead of on every request.
1371
+ *
1372
+ * The request path normalizes the same configuration on each call and fails
1373
+ * closed, so a malformed entry used to deny every call on the profile, reads
1374
+ * included, with an opaque reason. This runs the same normalizers with a key
1375
+ * path attached and throws FieldPolicyConfigurationError naming the table and
1376
+ * key. A configuration that passes cannot fail normalization on a request.
1377
+ *
1378
+ * Beyond malformed names and shapes, it rejects what used to load and then
1379
+ * silently fail open: `fieldPolicy` stated beside a table list (the request
1380
+ * path applied only the lists), unknown keys in a table or list entry (a
1381
+ * `writeable` typo narrowed nothing), table keys that differ only in case,
1382
+ * and a table repeated within one list (the last entry won).
1383
+ *
1384
+ * The map built here is kept for the request path when every part is deep
1385
+ * frozen, as ProfileManager's snapshots are: requests on a loaded profile
1386
+ * then reuse it instead of rebuilding it on each lookup.
1387
+ */
1388
+ function validateFieldPolicyConfiguration(input) {
1389
+ const map = validateConfiguration(input, PROFILE_CONFIGURATION_LABELS);
1390
+ if (map !== undefined)
1391
+ rememberValidatedPolicyMap(input, map);
1392
+ }
1393
+ /**
1394
+ * Map SN_FIELD_POLICY_DEFINITIONS onto the field-policy keys of the
1395
+ * SN_PROFILE_NAME environment profile. The caller passes the environment:
1396
+ * this module never reads process.env, so the variable cannot reach a
1397
+ * file-backed profile.
1398
+ *
1399
+ * The value is either a table map (`{"incident":{...}}`) or an object holding
1400
+ * the profile keys themselves (`fieldPolicy`, `readableTableFields`,
1401
+ * `writableTableFields`); both keep their previous meaning. A value that
1402
+ * mixes the two is rejected: the table keys used to be dropped silently.
1403
+ */
1404
+ function fieldPolicyInputFromEnvironment(environment) {
1405
+ const text = environment.SN_FIELD_POLICY_DEFINITIONS;
1079
1406
  if (text === undefined || text.trim() === "")
1080
- return undefined;
1407
+ return Object.freeze({});
1081
1408
  if (text.length > MAX_FIELD_POLICY_DEFINITIONS_TEXT_LENGTH) {
1082
- throw new FieldPolicyError("invalid_argument_shape");
1409
+ throw new FieldPolicyConfigurationError(`${FIELD_POLICY_DEFINITIONS_ENV} exceeds ${MAX_FIELD_POLICY_DEFINITIONS_TEXT_LENGTH} characters.`);
1083
1410
  }
1084
1411
  let parsed;
1085
1412
  try {
1086
1413
  parsed = JSON.parse(text);
1087
1414
  }
1088
1415
  catch {
1089
- throw new FieldPolicyError("invalid_argument_shape");
1416
+ throw new FieldPolicyConfigurationError(`${FIELD_POLICY_DEFINITIONS_ENV} is not valid JSON.`);
1417
+ }
1418
+ if (!isPlainRecordCandidate(parsed)) {
1419
+ throw new FieldPolicyConfigurationError(`${FIELD_POLICY_DEFINITIONS_ENV} must be a JSON object.`);
1420
+ }
1421
+ const record = definedOwnProperties(parsed);
1422
+ const stated = FIELD_POLICY_CONFIGURATION_KEYS.filter((key) => Object.hasOwn(record, key));
1423
+ if (stated.length > 0 && Object.keys(record).length > stated.length) {
1424
+ // The other keys are table names; they are not repeated here.
1425
+ throw new FieldPolicyConfigurationError(`${FIELD_POLICY_DEFINITIONS_ENV} mixes table keys with the profile keys ` +
1426
+ `${stated.join(", ")}. Use either a table map or the profile keys ` +
1427
+ `(${FIELD_POLICY_CONFIGURATION_KEYS.join(", ")}), not both.`);
1428
+ }
1429
+ const input = stated.length > 0
1430
+ ? Object.freeze(Object.fromEntries(stated.map((key) => [key, record[key]])))
1431
+ : Object.freeze({ fieldPolicy: record });
1432
+ validateConfiguration(input, stated.length > 0
1433
+ ? {
1434
+ fieldPolicy: `${FIELD_POLICY_DEFINITIONS_ENV}.fieldPolicy`,
1435
+ readableTableFields: `${FIELD_POLICY_DEFINITIONS_ENV}.readableTableFields`,
1436
+ writableTableFields: `${FIELD_POLICY_DEFINITIONS_ENV}.writableTableFields`,
1437
+ }
1438
+ : {
1439
+ ...PROFILE_CONFIGURATION_LABELS,
1440
+ fieldPolicy: FIELD_POLICY_DEFINITIONS_ENV,
1441
+ });
1442
+ return input;
1443
+ }
1444
+ /**
1445
+ * @returns The policy map the request path would build for this input, or
1446
+ * undefined when the input states no field policy at all (the request path
1447
+ * then uses the built-in map).
1448
+ */
1449
+ function validateConfiguration(input, labels) {
1450
+ if (!isPlainRecordCandidate(input)) {
1451
+ throw new FieldPolicyConfigurationError("Field policy configuration must be an object.");
1452
+ }
1453
+ const record = definedOwnProperties(input);
1454
+ if (!FIELD_POLICY_CONFIGURATION_KEYS.some((key) => Object.hasOwn(record, key))) {
1455
+ return undefined;
1456
+ }
1457
+ const statedLists = TABLE_FIELD_LIST_KEYS.filter((key) => Object.hasOwn(record, key));
1458
+ if (Object.hasOwn(record, "fieldPolicy") && statedLists.length > 0) {
1459
+ // The request path applied only the lists and dropped every narrowing in
1460
+ // fieldPolicy. There is no unambiguous merge, so the two forms exclude
1461
+ // each other.
1462
+ throw new FieldPolicyConfigurationError(`${labels.fieldPolicy} cannot be combined with ` +
1463
+ `${statedLists.map((key) => labels[key]).join(" and ")}. State the field ` +
1464
+ "policy in one form: fieldPolicy alone, or readableTableFields and " +
1465
+ "writableTableFields without fieldPolicy.");
1090
1466
  }
1091
- return normalizeConfiguredFieldPolicy(parsed);
1467
+ try {
1468
+ // The same normalizers the request path runs, with key paths attached.
1469
+ // The labels only shape error messages, so the map is the one a request
1470
+ // would build.
1471
+ if (Object.hasOwn(record, "fieldPolicy")) {
1472
+ return buildFieldPolicyMap(mergeFieldPolicyDefinitions(FIELD_POLICY_BASE, fieldPolicyDefinitions(record.fieldPolicy, labels.fieldPolicy)), labels.fieldPolicy);
1473
+ }
1474
+ return buildFieldPolicyMap(mergeFieldPolicyDefinitions(FIELD_POLICY_BASE, tableFieldListDefinitions(record, labels)));
1475
+ }
1476
+ catch (error) {
1477
+ if (error instanceof FieldPolicyConfigurationError)
1478
+ throw error;
1479
+ if (isFieldPolicyError(error)) {
1480
+ throw new FieldPolicyConfigurationError(`Field policy configuration is invalid (${error.reason}).`);
1481
+ }
1482
+ throw error;
1483
+ }
1484
+ }
1485
+ function configurationLocation(key, table) {
1486
+ if (key === undefined)
1487
+ return undefined;
1488
+ return table === undefined ? { key } : { key, table };
1489
+ }
1490
+ function rejectConfiguration(location, problem, entry = "") {
1491
+ if (location === undefined)
1492
+ throw new FieldPolicyError("invalid_argument_shape");
1493
+ const table = location.table === undefined ? "" : ` (table "${location.table}")`;
1494
+ throw new FieldPolicyConfigurationError(`${location.key}${entry}${table} ${problem}`);
1092
1495
  }
1093
1496
  function normalizeConfiguredFieldPolicy(parsed) {
1094
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed) || node_util_1.types.isProxy(parsed)) {
1497
+ if (!isPlainRecordCandidate(parsed)) {
1095
1498
  throw new FieldPolicyError("invalid_argument_shape");
1096
1499
  }
1097
1500
  const outerRecord = definedOwnProperties(parsed);
1098
- const policySource = Object.hasOwn(outerRecord, "fieldPolicy")
1099
- ? outerRecord.fieldPolicy
1100
- : outerRecord;
1101
- if (Object.hasOwn(outerRecord, "readableTableFields") ||
1102
- Object.hasOwn(outerRecord, "writableTableFields")) {
1103
- const definitions = {};
1104
- applyTableFieldList(definitions, outerRecord.readableTableFields, "readable");
1105
- applyTableFieldList(definitions, outerRecord.writableTableFields, "writable");
1106
- return Object.freeze({ definitions });
1107
- }
1108
- if (policySource === undefined)
1501
+ if (TABLE_FIELD_LIST_KEYS.some((key) => Object.hasOwn(outerRecord, key))) {
1502
+ // Profile load rejects this combination. A scope that skipped the load
1503
+ // fails closed rather than applying one form and dropping the other.
1504
+ if (Object.hasOwn(outerRecord, "fieldPolicy")) {
1505
+ throw new FieldPolicyError("invalid_argument_shape");
1506
+ }
1507
+ return Object.freeze({ definitions: tableFieldListDefinitions(outerRecord) });
1508
+ }
1509
+ if (outerRecord.fieldPolicy === undefined)
1109
1510
  return undefined;
1110
- if (typeof policySource !== "object" || policySource === null || Array.isArray(policySource) || node_util_1.types.isProxy(policySource)) {
1111
- throw new FieldPolicyError("invalid_argument_shape");
1511
+ return Object.freeze({
1512
+ definitions: fieldPolicyDefinitions(outerRecord.fieldPolicy),
1513
+ });
1514
+ }
1515
+ /**
1516
+ * Normalize a `fieldPolicy` table map.
1517
+ *
1518
+ * @param root Configuration key the map came from; given only at load.
1519
+ */
1520
+ function fieldPolicyDefinitions(source, root) {
1521
+ if (!isPlainRecordCandidate(source)) {
1522
+ rejectConfiguration(configurationLocation(root), "must be an object that maps table names to { defaults, readable, writable }.");
1112
1523
  }
1113
- const record = policySource;
1524
+ const record = source;
1114
1525
  const definitions = {};
1115
- for (const key of Object.keys(record)) {
1116
- const table = normalizePolicyTableName(key);
1526
+ const firstPosition = new Map();
1527
+ const keys = Object.keys(record);
1528
+ for (let position = 0; position < keys.length; position += 1) {
1529
+ const key = keys[position];
1530
+ const keyLocation = configurationLocation(root === undefined ? undefined : `${root} key ${position + 1}`);
1531
+ const table = normalizePolicyTableName(key, keyLocation);
1532
+ // Table names are case-insensitive, so "INCIDENT" and "incident" are one
1533
+ // table, and the later entry used to replace the earlier one silently.
1534
+ const earlier = firstPosition.get(table);
1535
+ if (earlier !== undefined) {
1536
+ rejectConfiguration(keyLocation, `names table "${table}" again (table names are case-insensitive); ` +
1537
+ `it repeats key ${earlier + 1}. State each table once.`);
1538
+ }
1539
+ firstPosition.set(table, position);
1540
+ const path = root === undefined ? undefined : `${root}.${table}`;
1117
1541
  const value = record[key];
1118
- if (typeof value !== "object" || value === null || Array.isArray(value) || node_util_1.types.isProxy(value)) {
1119
- throw new FieldPolicyError("invalid_argument_shape");
1542
+ if (!isPlainRecordCandidate(value)) {
1543
+ rejectConfiguration(configurationLocation(path), "must be an object with defaults, readable, or writable.");
1120
1544
  }
1121
1545
  const candidate = definedOwnProperties(value);
1546
+ rejectUnknownKeys(candidate, TABLE_ENTRY_KEYS, configurationLocation(path), "A table entry accepts only defaults, readable, and writable.");
1122
1547
  const definition = {};
1123
- if (Object.hasOwn(candidate, "defaults")) {
1124
- definition.defaults = normalizePolicyFieldSet(candidate.defaults);
1125
- }
1126
- if (Object.hasOwn(candidate, "readable")) {
1127
- definition.readable = normalizePolicyFieldSet(candidate.readable);
1128
- }
1129
- if (Object.hasOwn(candidate, "writable")) {
1130
- definition.writable = normalizePolicyFieldSet(candidate.writable);
1548
+ for (const kind of TABLE_ENTRY_KEYS) {
1549
+ if (Object.hasOwn(candidate, kind)) {
1550
+ definition[kind] = normalizePolicyFieldSet(candidate[kind], configurationLocation(path === undefined ? undefined : `${path}.${kind}`));
1551
+ }
1131
1552
  }
1132
1553
  definitions[table] = Object.freeze(definition);
1133
1554
  }
1134
- return Object.freeze({ definitions });
1555
+ return definitions;
1556
+ }
1557
+ /**
1558
+ * Reject a key outside `allowed`. An unknown key used to be ignored, so a
1559
+ * typo such as `writeable` loaded and narrowed nothing. The key is named only
1560
+ * when it is a valid identifier; anything else is identified by position.
1561
+ */
1562
+ function rejectUnknownKeys(record, allowed, location, accepted) {
1563
+ const keys = Object.keys(record);
1564
+ for (let position = 0; position < keys.length; position += 1) {
1565
+ const key = keys[position];
1566
+ if (allowed.includes(key))
1567
+ continue;
1568
+ rejectConfiguration(location, `has an unknown key ${FIELD_NAME.test(key) ? `"${key}"` : `at position ${position + 1}`}. ${accepted}`);
1569
+ }
1570
+ }
1571
+ /**
1572
+ * Normalize the `readableTableFields` / `writableTableFields` form.
1573
+ *
1574
+ * @param labels Configuration keys the lists came from; given only at load.
1575
+ */
1576
+ function tableFieldListDefinitions(record, labels) {
1577
+ const definitions = {};
1578
+ applyTableFieldList(definitions, record.readableTableFields, "readable", labels?.readableTableFields);
1579
+ applyTableFieldList(definitions, record.writableTableFields, "writable", labels?.writableTableFields);
1580
+ return definitions;
1581
+ }
1582
+ function isPlainRecordCandidate(candidate) {
1583
+ return (typeof candidate === "object" &&
1584
+ candidate !== null &&
1585
+ !Array.isArray(candidate) &&
1586
+ !node_util_1.types.isProxy(candidate));
1135
1587
  }
1136
1588
  /**
1137
1589
  * Drop own keys whose value is `undefined`.
@@ -1141,23 +1593,40 @@ function normalizeConfiguredFieldPolicy(parsed) {
1141
1593
  * Normalizing here keeps an object built with optional keys spread in
1142
1594
  * identical to one that never carried the key at all, so the same policy
1143
1595
  * cannot mean different things depending on how the caller constructed it.
1596
+ *
1597
+ * The copy has no prototype. On a plain `{}`, assigning a JSON own key
1598
+ * `__proto__` would replace the copy's prototype instead of defining a key,
1599
+ * so the unknown-key and mixed-key checks would never see it, and stated keys
1600
+ * could then be read through that prototype.
1144
1601
  */
1145
1602
  function definedOwnProperties(record) {
1146
- const defined = {};
1603
+ const defined = Object.create(null);
1147
1604
  for (const [key, value] of Object.entries(record)) {
1148
1605
  if (value !== undefined)
1149
1606
  defined[key] = value;
1150
1607
  }
1151
1608
  return defined;
1152
1609
  }
1153
- function applyTableFieldList(definitions, candidate, kind) {
1610
+ /**
1611
+ * @param root Configuration key the list came from; given only at load.
1612
+ */
1613
+ function applyTableFieldList(definitions, candidate, kind, root) {
1154
1614
  if (candidate === undefined)
1155
1615
  return;
1156
1616
  if (!Array.isArray(candidate) || node_util_1.types.isProxy(candidate)) {
1157
- throw new FieldPolicyError("invalid_argument_shape");
1158
- }
1159
- for (const entry of candidate) {
1160
- const normalized = normalizeTableFieldListDefinition(entry);
1617
+ rejectConfiguration(configurationLocation(root), "must be a list of { table, fields } entries.");
1618
+ }
1619
+ // A table may appear in both lists, but only once in each: a repeated
1620
+ // entry used to replace the earlier one, so the last entry won.
1621
+ const firstIndex = new Map();
1622
+ for (let index = 0; index < candidate.length; index += 1) {
1623
+ const path = root === undefined ? undefined : `${root}[${index}]`;
1624
+ const normalized = normalizeTableFieldListDefinition(candidate[index], path);
1625
+ const earlier = firstIndex.get(normalized.table);
1626
+ if (earlier !== undefined) {
1627
+ rejectConfiguration(configurationLocation(path, normalized.table), `repeats a table already listed at ${root}[${earlier}]. List each table once.`);
1628
+ }
1629
+ firstIndex.set(normalized.table, index);
1161
1630
  const previous = definitions[normalized.table] ?? {};
1162
1631
  definitions[normalized.table] = Object.freeze({
1163
1632
  ...previous,
@@ -1165,13 +1634,14 @@ function applyTableFieldList(definitions, candidate, kind) {
1165
1634
  });
1166
1635
  }
1167
1636
  }
1168
- function normalizeTableFieldListDefinition(candidate) {
1169
- if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate) || node_util_1.types.isProxy(candidate)) {
1170
- throw new FieldPolicyError("invalid_argument_shape");
1637
+ function normalizeTableFieldListDefinition(candidate, path) {
1638
+ if (!isPlainRecordCandidate(candidate)) {
1639
+ rejectConfiguration(configurationLocation(path), "must be an object with table and fields.");
1171
1640
  }
1172
1641
  const record = candidate;
1173
- const table = normalizePolicyTableName(record.table);
1174
- const fields = normalizePolicyFieldSet(record.fields);
1642
+ const table = normalizePolicyTableName(record.table, configurationLocation(path === undefined ? undefined : `${path}.table`));
1643
+ rejectUnknownKeys(definedOwnProperties(record), LIST_ENTRY_KEYS, configurationLocation(path, table), "A list entry accepts only table and fields.");
1644
+ const fields = normalizePolicyFieldSet(record.fields, configurationLocation(path === undefined ? undefined : `${path}.fields`, table));
1175
1645
  return Object.freeze({ table, fields });
1176
1646
  }
1177
1647
  function readableSelection(policy) {
@@ -1187,10 +1657,17 @@ function requireNonEmptySelection(selection) {
1187
1657
  throw new FieldPolicyError("unreadable_field");
1188
1658
  return selection;
1189
1659
  }
1190
- function normalizePolicyTableName(candidate) {
1660
+ function normalizePolicyTableName(candidate, location) {
1191
1661
  if (candidate === FIELD_POLICY_WILDCARD)
1192
1662
  return FIELD_POLICY_WILDCARD;
1193
- return normalizeTableName(candidate);
1663
+ try {
1664
+ return normalizeTableName(candidate);
1665
+ }
1666
+ catch (error) {
1667
+ if (location === undefined)
1668
+ throw error;
1669
+ rejectConfiguration(location, `is not a valid table name. Use a table name (${FIELD_NAME_RULE}) or "*".`);
1670
+ }
1194
1671
  }
1195
1672
  function normalizeTableName(candidate) {
1196
1673
  if (typeof candidate !== "string") {
@@ -1212,6 +1689,32 @@ function normalizeFieldName(candidate) {
1212
1689
  }
1213
1690
  return normalized;
1214
1691
  }
1692
+ /** Longest dotted write key inspected for a specific denial message. */
1693
+ const MAX_FIELD_PATH_LENGTH = 1_024;
1694
+ /**
1695
+ * Normalize one write key. A dotted key whose every segment is a field name,
1696
+ * such as the dot-walk caller_id.email or variables.requested_for, is still
1697
+ * denied: Table API write support for those names is unverified. It gets its
1698
+ * own reason so the denial says why instead of reading as a malformed name.
1699
+ */
1700
+ function normalizeWriteFieldName(candidate, table) {
1701
+ try {
1702
+ return normalizeFieldName(candidate);
1703
+ }
1704
+ catch (error) {
1705
+ if (isFieldPath(candidate)) {
1706
+ throw new FieldPolicyError("unsupported_field_path", { table });
1707
+ }
1708
+ throw error;
1709
+ }
1710
+ }
1711
+ function isFieldPath(candidate) {
1712
+ if (typeof candidate !== "string" || candidate.length > MAX_FIELD_PATH_LENGTH) {
1713
+ return false;
1714
+ }
1715
+ const segments = candidate.trim().toLowerCase().split(".");
1716
+ return segments.length > 1 && segments.every((segment) => FIELD_NAME.test(segment));
1717
+ }
1215
1718
  function normalizeResponseFormat(candidate) {
1216
1719
  if (candidate === undefined || candidate === "concise")
1217
1720
  return "concise";
@@ -1219,20 +1722,46 @@ function normalizeResponseFormat(candidate) {
1219
1722
  return "detailed";
1220
1723
  throw new FieldPolicyError("invalid_field_selection");
1221
1724
  }
1222
- function normalizePolicyFieldSet(candidates) {
1223
- if (candidates === FIELD_POLICY_WILDCARD)
1725
+ function normalizePolicyFieldSet(candidates, location) {
1726
+ if (candidates === FIELD_POLICY_WILDCARD || isWildcardFieldList(candidates)) {
1224
1727
  return FIELD_POLICY_WILDCARD;
1225
- return normalizePolicyFields(candidates);
1728
+ }
1729
+ return normalizePolicyFields(candidates, location);
1730
+ }
1731
+ /**
1732
+ * `["*"]` is how `tableAccess.writeTables` spells "everything", so an operator
1733
+ * writes it here too. It means exactly what the string `"*"` means.
1734
+ */
1735
+ function isWildcardFieldList(candidate) {
1736
+ return (Array.isArray(candidate) &&
1737
+ !node_util_1.types.isProxy(candidate) &&
1738
+ candidate.length === 1 &&
1739
+ candidate[0] === FIELD_POLICY_WILDCARD);
1226
1740
  }
1227
- function normalizePolicyFields(candidates) {
1741
+ function normalizePolicyFields(candidates, location) {
1228
1742
  // Operator policy is normalized on the request path, so a malformed set
1229
1743
  // must surface as a branded policy denial rather than a raw TypeError.
1230
1744
  if (!Array.isArray(candidates) || node_util_1.types.isProxy(candidates)) {
1231
- throw new FieldPolicyError("invalid_argument_shape");
1745
+ rejectConfiguration(location, 'must be "*" or a list of field names.');
1232
1746
  }
1233
- const fields = candidates.map((field) => normalizeFieldName(field));
1234
- if (new Set(fields).size !== fields.length) {
1235
- throw new FieldPolicyError("invalid_argument_shape");
1747
+ const fields = [];
1748
+ const seen = new Set();
1749
+ for (let index = 0; index < candidates.length; index += 1) {
1750
+ let field;
1751
+ try {
1752
+ field = normalizeFieldName(candidates[index]);
1753
+ }
1754
+ catch (error) {
1755
+ if (location === undefined)
1756
+ throw error;
1757
+ rejectConfiguration(location, `is not a field name. List exact field names (${FIELD_NAME_RULE}), or use "*" ` +
1758
+ 'on its own for every field; patterns such as "u_*" are not supported.', `[${index}]`);
1759
+ }
1760
+ if (seen.has(field)) {
1761
+ rejectConfiguration(location, `repeats the field "${field}".`, `[${index}]`);
1762
+ }
1763
+ seen.add(field);
1764
+ fields.push(field);
1236
1765
  }
1237
1766
  return Object.freeze(fields);
1238
1767
  }