@onlyflows/servicenow-mcp 2.2.0-dev.6 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/.env.example +6 -3
  2. package/CHANGELOG.md +404 -0
  3. package/README.md +580 -104
  4. package/dist/atf-form.d.ts +3 -15
  5. package/dist/atf-form.d.ts.map +1 -1
  6. package/dist/atf-policy.d.ts +1 -1
  7. package/dist/atf-policy.d.ts.map +1 -1
  8. package/dist/atf-policy.js +2 -0
  9. package/dist/atf-policy.js.map +1 -1
  10. package/dist/atf-result-cache.d.ts +23 -59
  11. package/dist/atf-result-cache.d.ts.map +1 -1
  12. package/dist/auth.d.ts +1 -0
  13. package/dist/auth.d.ts.map +1 -1
  14. package/dist/auth.js +17 -0
  15. package/dist/auth.js.map +1 -1
  16. package/dist/batch-limits.d.ts +18 -0
  17. package/dist/batch-limits.d.ts.map +1 -0
  18. package/dist/batch-limits.js +21 -0
  19. package/dist/batch-limits.js.map +1 -0
  20. package/dist/bounded-input.d.ts +49 -0
  21. package/dist/bounded-input.d.ts.map +1 -0
  22. package/dist/bounded-input.js +81 -0
  23. package/dist/bounded-input.js.map +1 -0
  24. package/dist/client.d.ts +25 -0
  25. package/dist/client.d.ts.map +1 -1
  26. package/dist/client.js +92 -18
  27. package/dist/client.js.map +1 -1
  28. package/dist/credential-tables.d.ts +32 -0
  29. package/dist/credential-tables.d.ts.map +1 -0
  30. package/dist/credential-tables.js +58 -0
  31. package/dist/credential-tables.js.map +1 -0
  32. package/dist/encoded-query-policy.d.ts +11 -0
  33. package/dist/encoded-query-policy.d.ts.map +1 -1
  34. package/dist/encoded-query-policy.js +18 -2
  35. package/dist/encoded-query-policy.js.map +1 -1
  36. package/dist/execution-context.d.ts +14 -0
  37. package/dist/execution-context.d.ts.map +1 -1
  38. package/dist/execution-context.js +8 -0
  39. package/dist/execution-context.js.map +1 -1
  40. package/dist/field-policy.d.ts +115 -3
  41. package/dist/field-policy.d.ts.map +1 -1
  42. package/dist/field-policy.js +909 -97
  43. package/dist/field-policy.js.map +1 -1
  44. package/dist/hidden-values.d.ts +225 -0
  45. package/dist/hidden-values.d.ts.map +1 -0
  46. package/dist/hidden-values.js +748 -0
  47. package/dist/hidden-values.js.map +1 -0
  48. package/dist/html-response.d.ts +34 -0
  49. package/dist/html-response.d.ts.map +1 -0
  50. package/dist/html-response.js +72 -0
  51. package/dist/html-response.js.map +1 -0
  52. package/dist/http-entrypoint.d.ts.map +1 -1
  53. package/dist/http-entrypoint.js +7 -0
  54. package/dist/http-entrypoint.js.map +1 -1
  55. package/dist/http-runtime.d.ts.map +1 -1
  56. package/dist/http-runtime.js +8 -0
  57. package/dist/http-runtime.js.map +1 -1
  58. package/dist/incident-journal-policy.d.ts +27 -5
  59. package/dist/incident-journal-policy.d.ts.map +1 -1
  60. package/dist/incident-journal-policy.js +34 -21
  61. package/dist/incident-journal-policy.js.map +1 -1
  62. package/dist/index.js +7 -0
  63. package/dist/index.js.map +1 -1
  64. package/dist/json-shape-limits.d.ts +71 -0
  65. package/dist/json-shape-limits.d.ts.map +1 -0
  66. package/dist/json-shape-limits.js +131 -0
  67. package/dist/json-shape-limits.js.map +1 -0
  68. package/dist/metadata-cache.d.ts +84 -21
  69. package/dist/metadata-cache.d.ts.map +1 -1
  70. package/dist/metadata-cache.js +316 -196
  71. package/dist/metadata-cache.js.map +1 -1
  72. package/dist/policy-card.d.ts +146 -0
  73. package/dist/policy-card.d.ts.map +1 -0
  74. package/dist/policy-card.js +420 -0
  75. package/dist/policy-card.js.map +1 -0
  76. package/dist/profile-manager.d.ts +19 -3
  77. package/dist/profile-manager.d.ts.map +1 -1
  78. package/dist/profile-manager.js +89 -4
  79. package/dist/profile-manager.js.map +1 -1
  80. package/dist/record-identifier-policy.d.ts +2 -8
  81. package/dist/record-identifier-policy.d.ts.map +1 -1
  82. package/dist/risky-grants.d.ts +25 -0
  83. package/dist/risky-grants.d.ts.map +1 -0
  84. package/dist/risky-grants.js +77 -0
  85. package/dist/risky-grants.js.map +1 -0
  86. package/dist/server.d.ts.map +1 -1
  87. package/dist/server.js +26 -5
  88. package/dist/server.js.map +1 -1
  89. package/dist/setup-prompts.js +1 -0
  90. package/dist/setup-prompts.js.map +1 -1
  91. package/dist/setup.d.ts +1 -1
  92. package/dist/setup.d.ts.map +1 -1
  93. package/dist/setup.js +305 -59
  94. package/dist/setup.js.map +1 -1
  95. package/dist/stdio-runtime.d.ts +15 -0
  96. package/dist/stdio-runtime.d.ts.map +1 -1
  97. package/dist/stdio-runtime.js +60 -0
  98. package/dist/stdio-runtime.js.map +1 -1
  99. package/dist/structured-query.d.ts +100 -115
  100. package/dist/structured-query.d.ts.map +1 -1
  101. package/dist/structured-query.js +138 -17
  102. package/dist/structured-query.js.map +1 -1
  103. package/dist/table-policy.d.ts +41 -4
  104. package/dist/table-policy.d.ts.map +1 -1
  105. package/dist/table-policy.js +82 -10
  106. package/dist/table-policy.js.map +1 -1
  107. package/dist/tool-error.d.ts +34 -0
  108. package/dist/tool-error.d.ts.map +1 -1
  109. package/dist/tool-error.js +109 -1
  110. package/dist/tool-error.js.map +1 -1
  111. package/dist/tool-table-access.d.ts.map +1 -1
  112. package/dist/tool-table-access.js +35 -5
  113. package/dist/tool-table-access.js.map +1 -1
  114. package/dist/tools/aggregate.d.ts +13 -19
  115. package/dist/tools/aggregate.d.ts.map +1 -1
  116. package/dist/tools/aggregate.js +4 -5
  117. package/dist/tools/aggregate.js.map +1 -1
  118. package/dist/tools/all-fields-cap.d.ts.map +1 -1
  119. package/dist/tools/all-fields-cap.js +32 -45
  120. package/dist/tools/all-fields-cap.js.map +1 -1
  121. package/dist/tools/atf-author-module.d.ts +29 -14
  122. package/dist/tools/atf-author-module.d.ts.map +1 -1
  123. package/dist/tools/atf-author-module.js +11 -5
  124. package/dist/tools/atf-author-module.js.map +1 -1
  125. package/dist/tools/atf-contracts.d.ts +135 -829
  126. package/dist/tools/atf-contracts.d.ts.map +1 -1
  127. package/dist/tools/atf-shared.js +2 -2
  128. package/dist/tools/atf-shared.js.map +1 -1
  129. package/dist/tools/atf-step-catalog.d.ts +16 -15
  130. package/dist/tools/atf-step-catalog.d.ts.map +1 -1
  131. package/dist/tools/atf-step-catalog.js +181 -10
  132. package/dist/tools/atf-step-catalog.js.map +1 -1
  133. package/dist/tools/atf.d.ts +8 -24
  134. package/dist/tools/atf.d.ts.map +1 -1
  135. package/dist/tools/atf.js +2 -2
  136. package/dist/tools/atf.js.map +1 -1
  137. package/dist/tools/attach.d.ts +6 -22
  138. package/dist/tools/attach.d.ts.map +1 -1
  139. package/dist/tools/batch.d.ts +18 -71
  140. package/dist/tools/batch.d.ts.map +1 -1
  141. package/dist/tools/batch.js +566 -100
  142. package/dist/tools/batch.js.map +1 -1
  143. package/dist/tools/catalog.d.ts +2 -2
  144. package/dist/tools/catalog.d.ts.map +1 -1
  145. package/dist/tools/catalog.js +7 -1
  146. package/dist/tools/catalog.js.map +1 -1
  147. package/dist/tools/codesearch.d.ts +1 -13
  148. package/dist/tools/codesearch.d.ts.map +1 -1
  149. package/dist/tools/create-module.d.ts +9 -14
  150. package/dist/tools/create-module.d.ts.map +1 -1
  151. package/dist/tools/create-module.js +4 -8
  152. package/dist/tools/create-module.js.map +1 -1
  153. package/dist/tools/delete.d.ts +1 -9
  154. package/dist/tools/delete.d.ts.map +1 -1
  155. package/dist/tools/delete.js +2 -3
  156. package/dist/tools/delete.js.map +1 -1
  157. package/dist/tools/discover.d.ts +6 -14
  158. package/dist/tools/discover.d.ts.map +1 -1
  159. package/dist/tools/flow-view-contracts.d.ts +1023 -0
  160. package/dist/tools/flow-view-contracts.d.ts.map +1 -0
  161. package/dist/tools/flow-view-contracts.js +570 -0
  162. package/dist/tools/flow-view-contracts.js.map +1 -0
  163. package/dist/tools/flow-view-graph.d.ts +86 -0
  164. package/dist/tools/flow-view-graph.d.ts.map +1 -0
  165. package/dist/tools/flow-view-graph.js +993 -0
  166. package/dist/tools/flow-view-graph.js.map +1 -0
  167. package/dist/tools/flow-view-gzip.d.ts +52 -0
  168. package/dist/tools/flow-view-gzip.d.ts.map +1 -0
  169. package/dist/tools/flow-view-gzip.js +179 -0
  170. package/dist/tools/flow-view-gzip.js.map +1 -0
  171. package/dist/tools/flow-view-mermaid.d.ts +37 -0
  172. package/dist/tools/flow-view-mermaid.d.ts.map +1 -0
  173. package/dist/tools/flow-view-mermaid.js +337 -0
  174. package/dist/tools/flow-view-mermaid.js.map +1 -0
  175. package/dist/tools/flow-view-module.d.ts +61 -0
  176. package/dist/tools/flow-view-module.d.ts.map +1 -0
  177. package/dist/tools/flow-view-module.js +378 -0
  178. package/dist/tools/flow-view-module.js.map +1 -0
  179. package/dist/tools/flow-view-policy.d.ts +106 -0
  180. package/dist/tools/flow-view-policy.d.ts.map +1 -0
  181. package/dist/tools/flow-view-policy.js +462 -0
  182. package/dist/tools/flow-view-policy.js.map +1 -0
  183. package/dist/tools/flow-view-renderers.d.ts +68 -0
  184. package/dist/tools/flow-view-renderers.d.ts.map +1 -0
  185. package/dist/tools/flow-view-renderers.js +513 -0
  186. package/dist/tools/flow-view-renderers.js.map +1 -0
  187. package/dist/tools/flow-view-table.d.ts +115 -0
  188. package/dist/tools/flow-view-table.d.ts.map +1 -0
  189. package/dist/tools/flow-view-table.js +1002 -0
  190. package/dist/tools/flow-view-table.js.map +1 -0
  191. package/dist/tools/get-module.d.ts +36 -42
  192. package/dist/tools/get-module.d.ts.map +1 -1
  193. package/dist/tools/health.d.ts +9 -6
  194. package/dist/tools/health.d.ts.map +1 -1
  195. package/dist/tools/incident-journal-module.d.ts +8 -7
  196. package/dist/tools/incident-journal-module.d.ts.map +1 -1
  197. package/dist/tools/index.d.ts +4 -4
  198. package/dist/tools/index.d.ts.map +1 -1
  199. package/dist/tools/index.js +118 -18
  200. package/dist/tools/index.js.map +1 -1
  201. package/dist/tools/markdown.d.ts +27 -0
  202. package/dist/tools/markdown.d.ts.map +1 -1
  203. package/dist/tools/markdown.js +104 -1
  204. package/dist/tools/markdown.js.map +1 -1
  205. package/dist/tools/nl.d.ts +1 -11
  206. package/dist/tools/nl.d.ts.map +1 -1
  207. package/dist/tools/profile.d.ts +1 -1
  208. package/dist/tools/profile.d.ts.map +1 -1
  209. package/dist/tools/profile.js +20 -1
  210. package/dist/tools/profile.js.map +1 -1
  211. package/dist/tools/query-module.d.ts +59 -71
  212. package/dist/tools/query-module.d.ts.map +1 -1
  213. package/dist/tools/query-module.js +28 -7
  214. package/dist/tools/query-module.js.map +1 -1
  215. package/dist/tools/record-write-shared.d.ts.map +1 -1
  216. package/dist/tools/record-write-shared.js +20 -2
  217. package/dist/tools/record-write-shared.js.map +1 -1
  218. package/dist/tools/relationships.d.ts +6 -22
  219. package/dist/tools/relationships.d.ts.map +1 -1
  220. package/dist/tools/result-envelope.d.ts +2255 -1357
  221. package/dist/tools/result-envelope.d.ts.map +1 -1
  222. package/dist/tools/result-envelope.js +24 -2
  223. package/dist/tools/result-envelope.js.map +1 -1
  224. package/dist/tools/schema-module.d.ts +36 -21
  225. package/dist/tools/schema-module.d.ts.map +1 -1
  226. package/dist/tools/schema-module.js +106 -65
  227. package/dist/tools/schema-module.js.map +1 -1
  228. package/dist/tools/script.d.ts +1 -11
  229. package/dist/tools/script.d.ts.map +1 -1
  230. package/dist/tools/syslog.d.ts +11 -18
  231. package/dist/tools/syslog.d.ts.map +1 -1
  232. package/dist/tools/syslog.js +2 -3
  233. package/dist/tools/syslog.js.map +1 -1
  234. package/dist/tools/table-hierarchy.d.ts +35 -0
  235. package/dist/tools/table-hierarchy.d.ts.map +1 -0
  236. package/dist/tools/table-hierarchy.js +74 -0
  237. package/dist/tools/table-hierarchy.js.map +1 -0
  238. package/dist/tools/tool-module.d.ts +40 -15
  239. package/dist/tools/tool-module.d.ts.map +1 -1
  240. package/dist/tools/tool-module.js +755 -205
  241. package/dist/tools/tool-module.js.map +1 -1
  242. package/dist/tools/update-module.d.ts +11 -17
  243. package/dist/tools/update-module.d.ts.map +1 -1
  244. package/dist/tools/update-module.js +10 -12
  245. package/dist/tools/update-module.js.map +1 -1
  246. package/dist/unknown-filter-fields.d.ts +52 -0
  247. package/dist/unknown-filter-fields.d.ts.map +1 -0
  248. package/dist/unknown-filter-fields.js +87 -0
  249. package/dist/unknown-filter-fields.js.map +1 -0
  250. package/dist/version.d.ts +1 -1
  251. package/dist/version.d.ts.map +1 -1
  252. package/dist/version.js +1 -1
  253. package/dist/version.js.map +1 -1
  254. package/dist/write-value-policy.d.ts +20 -12
  255. package/dist/write-value-policy.d.ts.map +1 -1
  256. package/dist/write-value-policy.js +179 -67
  257. package/dist/write-value-policy.js.map +1 -1
  258. package/docs/ADDING-TOOLS.md +22 -13
  259. package/docs/CLIENT-SETUP.md +110 -52
  260. package/docs/CROSS-CLIENT-RELEASE-MATRIX.md +2 -2
  261. package/docs/FLOW-VIEW.md +214 -0
  262. package/docs/PRODUCTION-SECURITY.md +218 -25
  263. package/docs/RELEASE-VALIDATION.md +2 -2
  264. package/docs/TESTING-OAUTH.md +1 -1
  265. package/docs/V2-MIGRATION.md +404 -30
  266. package/package.json +20 -6
  267. package/scripts/release-validate.mjs +56 -0
  268. package/server.json +22 -0
  269. 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,17 +22,28 @@ 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;
26
29
  exports.filterSchemaEntries = filterSchemaEntries;
27
30
  exports.filterAggregateResult = filterAggregateResult;
28
31
  exports.runWithFieldPolicyConfiguration = runWithFieldPolicyConfiguration;
32
+ exports.currentFieldPolicyConfiguration = currentFieldPolicyConfiguration;
29
33
  exports.isAllFieldSelection = isAllFieldSelection;
30
34
  exports.fieldSelectionToSysparmFields = fieldSelectionToSysparmFields;
31
35
  exports.isSensitiveFieldName = isSensitiveFieldName;
36
+ exports.typeHiddenFieldNames = typeHiddenFieldNames;
37
+ exports.queryDeniedFields = queryDeniedFields;
38
+ exports.queryDeniedForSelection = queryDeniedForSelection;
39
+ exports.readableSelectionForTable = readableSelectionForTable;
40
+ exports.describeFieldPolicy = describeFieldPolicy;
41
+ exports.validateFieldPolicyConfiguration = validateFieldPolicyConfiguration;
42
+ exports.fieldPolicyInputFromEnvironment = fieldPolicyInputFromEnvironment;
32
43
  const node_async_hooks_1 = require("node:async_hooks");
33
44
  const node_util_1 = require("node:util");
45
+ const hidden_values_js_1 = require("./hidden-values.js");
46
+ const table_policy_js_1 = require("./table-policy.js");
34
47
  const FIELD_NAME = /^[a-z][a-z0-9_]{0,79}$/u;
35
48
  /** @deprecated Field authorization no longer caps the number of selected fields. */
36
49
  exports.MAX_FIELDS_PER_OPERATION = 10_000;
@@ -49,6 +62,42 @@ const ALL_FIELDS_SELECTION = Object.freeze([FIELD_POLICY_WILDCARD]);
49
62
  * defaults the operator did not state. An unstated default must stay finite:
50
63
  * "may read any field" is not "return every field on every query". */
51
64
  const GENERIC_DEFAULT_FIELDS = Object.freeze(["sys_id"]);
65
+ /** Write-response projection for a write-only table (`readable: []`). The
66
+ * record's own handle is all a write returns there; denying the write instead
67
+ * would make a write-only policy unable to write anything. */
68
+ const WRITE_ONLY_RESPONSE_FIELDS = Object.freeze(["sys_id"]);
69
+ /** Configuration keys a scoped field policy may carry. */
70
+ const FIELD_POLICY_CONFIGURATION_KEYS = Object.freeze([
71
+ "fieldPolicy",
72
+ "readableTableFields",
73
+ "writableTableFields",
74
+ ]);
75
+ /** The two table-list keys; neither may be combined with `fieldPolicy`. */
76
+ const TABLE_FIELD_LIST_KEYS = Object.freeze([
77
+ "readableTableFields",
78
+ "writableTableFields",
79
+ ]);
80
+ /** Keys a `fieldPolicy` table entry may state. */
81
+ const TABLE_ENTRY_KEYS = Object.freeze(["defaults", "readable", "writable"]);
82
+ /** Keys a `{ table, fields }` list entry may state. */
83
+ const LIST_ENTRY_KEYS = Object.freeze(["table", "fields"]);
84
+ const FIELD_NAME_RULE = "letters, digits, and underscores, starting with a letter, at most 80 characters";
85
+ /**
86
+ * Fields that change what a record is rather than what it says:
87
+ * sys_class_name moves it to another class (table), and sys_domain moves it
88
+ * to another domain. sys_class_path and sys_domain_path encode the same
89
+ * class and domain (domain visibility matches on sys_domain_path), so a
90
+ * direct write to either could move the record without touching the other
91
+ * two. A writable wildcard, including the open built-in default, never
92
+ * covers any of them. They are writable only where a profile lists them in
93
+ * `writable`.
94
+ */
95
+ const EXPLICIT_WRITE_FIELDS = new Set([
96
+ "sys_class_name",
97
+ "sys_class_path",
98
+ "sys_domain",
99
+ "sys_domain_path",
100
+ ]);
52
101
  const INCIDENT_DEFAULTS = [
53
102
  "sys_id",
54
103
  "number",
@@ -62,6 +111,13 @@ const INCIDENT_DEFAULTS = [
62
111
  "sys_updated_on",
63
112
  "active",
64
113
  ];
114
+ /**
115
+ * Built-in table entries. Only `defaults`, the bounded projection a read gets
116
+ * when it names no fields, is applied (see FIELD_POLICY_BASE). The `readable`
117
+ * and `writable` lists below are not read by any code path: a `writable: []`
118
+ * here denies nothing. What a profile may read or write is decided by its
119
+ * own field policy, its tableAccess grant, and ServiceNow's ACLs.
120
+ */
65
121
  const POLICY_DEFINITIONS = {
66
122
  incident: {
67
123
  defaults: INCIDENT_DEFAULTS,
@@ -295,11 +351,12 @@ const POLICY_DEFINITIONS = {
295
351
  ],
296
352
  writable: [],
297
353
  },
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.
354
+ // Group membership grants every role the group holds, so a write here can
355
+ // escalate the integration account as surely as a sys_script write. Nothing
356
+ // in this module denies it: like sys_user_role, sys_user_has_role, and
357
+ // sys_group_has_role (which have no entry here and no table-level block in
358
+ // table-policy.ts), it is writable exactly when the profile's tableAccess
359
+ // grants it and its field policy does not narrow it. Grant it deliberately.
303
360
  sys_user_grmember: {
304
361
  defaults: ["sys_id", "user", "group"],
305
362
  readable: ["sys_id", "user", "group", "sys_created_on", "sys_updated_on"],
@@ -575,6 +632,58 @@ const POLICY_DEFINITIONS = {
575
632
  readable: ["sys_id", "name", "status", "browser_name", "browser_version", "os_name", "os_version", "sys_updated_on"],
576
633
  writable: [],
577
634
  },
635
+ // The named-only tables (NAMED_ONLY_TABLES in table-policy.ts). A "*" table
636
+ // grant never covers them: a profile reaches them only by naming them in
637
+ // tableAccess. For field policy they belong to the profile, like the ITSM
638
+ // tables, so a profile's "*" field entry narrows them. Each default
639
+ // projection names the record and field a row is about and leaves the value
640
+ // columns to be asked for by name.
641
+ //
642
+ // The audit and journal tables hold the old and new values of other tables'
643
+ // fields, and their comments and work notes (oldvalue, newvalue, value).
644
+ sys_audit: {
645
+ defaults: ["sys_id", "tablename", "documentkey", "fieldname", "user", "sys_created_on"],
646
+ readable: ["sys_id", "tablename", "documentkey", "fieldname", "oldvalue", "newvalue", "user", "reason", "sys_created_on"],
647
+ writable: [],
648
+ },
649
+ sys_journal_field: {
650
+ defaults: ["sys_id", "name", "element_id", "element", "sys_created_by", "sys_created_on"],
651
+ readable: ["sys_id", "name", "element_id", "element", "value", "sys_created_by", "sys_created_on"],
652
+ writable: [],
653
+ },
654
+ // The history built from audit for a record's history view. Value columns:
655
+ // old, new, old_value, new_value. user_id and email name the actor and stay
656
+ // out of the default projection.
657
+ sys_history_line: {
658
+ defaults: ["sys_id", "set", "field", "label", "update", "update_time", "type"],
659
+ readable: ["sys_id", "set", "field", "label", "update", "update_time", "type", "user_name", "old", "new", "old_value", "new_value", "sys_created_on"],
660
+ writable: [],
661
+ },
662
+ // A deleted record, kept whole. Value column: payload (the record's XML).
663
+ sys_audit_delete: {
664
+ defaults: ["sys_id", "tablename", "documentkey", "display_value", "sys_created_on", "sys_created_by"],
665
+ readable: ["sys_id", "tablename", "documentkey", "display_value", "payload", "sys_created_on", "sys_created_by"],
666
+ writable: [],
667
+ },
668
+ // Attachment content, in chunks. Value column: data. sn_attach does not read
669
+ // this table: it uses the Attachment API, under the grants of sys_attachment
670
+ // and the parent table.
671
+ sys_attachment_doc: {
672
+ defaults: ["sys_id", "sys_attachment", "position", "length", "sys_created_on"],
673
+ readable: ["sys_id", "sys_attachment", "position", "length", "data", "sys_created_on"],
674
+ writable: [],
675
+ },
676
+ // Notification copies. Content columns: body, body_text, subject,
677
+ // recipients, copied, blind_copied, reply_to, headers, error_string.
678
+ sys_email: {
679
+ defaults: ["sys_id", "type", "state", "target_table", "instance", "sys_created_on"],
680
+ readable: [
681
+ "sys_id", "type", "state", "notification_type", "target_table", "instance", "mailbox",
682
+ "subject", "body", "body_text", "recipients", "copied", "blind_copied", "reply_to",
683
+ "headers", "error_string", "sys_created_on",
684
+ ],
685
+ writable: [],
686
+ },
578
687
  };
579
688
  /**
580
689
  * The policy base.
@@ -589,6 +698,11 @@ const POLICY_DEFINITIONS = {
589
698
  *
590
699
  * The "*" entry makes every other table resolvable with the same posture, so
591
700
  * a granted custom table needs no field-policy entry to be usable.
701
+ *
702
+ * A profile's own "*" entry reaches further: it also covers the ITSM tables
703
+ * (ITSM_TABLES), the named-only tables (NAMED_ONLY_BUILT_INS) and every table
704
+ * the profile names, key by key, wherever the table's own entry is silent.
705
+ * Only the system tables (SYSTEM_TABLES) are never covered by a "*" entry.
592
706
  */
593
707
  const FIELD_POLICY_BASE = Object.freeze({
594
708
  ...Object.fromEntries(Object.entries(POLICY_DEFINITIONS).map(([table, definition]) => [
@@ -606,6 +720,83 @@ const FIELD_POLICY_BASE = Object.freeze({
606
720
  }),
607
721
  });
608
722
  const BUILT_IN_TABLE_FIELD_POLICIES = buildFieldPolicyMap(FIELD_POLICY_BASE);
723
+ /**
724
+ * Built-in tables whose field policy belongs to the profile, like every
725
+ * custom table. For these, `readable` and `writable` resolve from the
726
+ * profile's own table entry, then the profile's "*" entry, then the built-in
727
+ * "*" (open). Their built-in `defaults` stay as a read-projection
728
+ * convenience, clamped to the effective readable set.
729
+ */
730
+ const ITSM_TABLES = new Set([
731
+ "incident",
732
+ "change_request",
733
+ "problem",
734
+ "sc_request",
735
+ "sc_req_item",
736
+ "sc_task",
737
+ "task",
738
+ "cmdb_ci",
739
+ "cmdb_ci_server",
740
+ "cmdb_ci_computer",
741
+ "kb_knowledge",
742
+ ]);
743
+ /**
744
+ * Every other built-in table is a system table (scripts, users and groups,
745
+ * ATF, application and dictionary metadata, syslog). It keeps its own
746
+ * built-in entry, a "*" entry never covers it, and it is narrowed only by
747
+ * naming it.
748
+ *
749
+ * This list is written out rather than derived as "built-in minus ITSM", so
750
+ * a new built-in entry never escapes every profile's "*" entry by default.
751
+ * Each built-in entry must be in exactly one of ITSM_TABLES, SYSTEM_TABLES
752
+ * and NAMED_ONLY_BUILT_INS; a test enforces this through
753
+ * BUILT_IN_TABLE_CLASSES.
754
+ */
755
+ const SYSTEM_TABLES = new Set([
756
+ "sys_user",
757
+ "sys_user_group",
758
+ "sys_user_grmember",
759
+ "syslog",
760
+ "sys_script",
761
+ "sys_script_include",
762
+ "sys_ui_script",
763
+ "sys_script_client",
764
+ "sys_ws_operation",
765
+ "sys_db_object",
766
+ "sys_app",
767
+ "sys_store_app",
768
+ "v_plugin",
769
+ "sys_atf_test",
770
+ "sys_atf_test_suite",
771
+ "sys_atf_test_suite_test",
772
+ "sys_atf_test_result",
773
+ "sys_atf_step",
774
+ "sys_element_mapping",
775
+ "sys_variable_value",
776
+ "sys_atf_test_suite_result",
777
+ "sys_atf_test_result_step",
778
+ "sys_atf_agent",
779
+ ]);
780
+ /**
781
+ * Built-in tables that a "*" table grant never covers (NAMED_ONLY_TABLES, in
782
+ * table-policy.ts, the one list). For field policy they are profile-owned like
783
+ * the ITSM tables: `readable` and `writable` resolve from the profile's own
784
+ * entry for the table, then its "*" entry, then the built-in "*" (open), so a
785
+ * profile that narrows reads with "*" narrows these too. Their built-in
786
+ * `defaults` leave out the value columns and are clamped to the effective
787
+ * readable set. A table's own entry still narrows or widens it.
788
+ */
789
+ const NAMED_ONLY_BUILT_INS = new Set(table_policy_js_1.NAMED_ONLY_TABLES);
790
+ /**
791
+ * The built-in tables and how each is classified for a profile's "*" entry.
792
+ * Frozen copies for tests; the policy reads the sets above.
793
+ */
794
+ exports.BUILT_IN_TABLE_CLASSES = Object.freeze({
795
+ builtIn: Object.freeze(Object.keys(POLICY_DEFINITIONS)),
796
+ itsm: Object.freeze([...ITSM_TABLES]),
797
+ system: Object.freeze([...SYSTEM_TABLES]),
798
+ namedOnly: Object.freeze([...NAMED_ONLY_BUILT_INS]),
799
+ });
609
800
  const GENERIC_RECORD_TABLES = new Set([
610
801
  "incident",
611
802
  "change_request",
@@ -686,7 +877,25 @@ function fieldPolicyDenialMessage(error) {
686
877
  `fieldPolicy.${table}, or a fieldPolicy."*" fallback, to allow it.`
687
878
  : "Access denied by policy: the requested table has no field policy entry.";
688
879
  case "sensitive_field":
880
+ // The same text for a name and a type denial: saying which would tell
881
+ // the caller a field's type, which is what the type rule keeps back.
689
882
  return "Access denied by policy: a requested field is denied by name as sensitive and cannot be granted by configuration.";
883
+ case "field_types_unavailable":
884
+ return hidden_values_js_1.FIELD_TYPES_UNAVAILABLE_MESSAGE;
885
+ case "explicit_field_required":
886
+ // Only the EXPLICIT_WRITE_FIELDS names reach this case; each is a fixed
887
+ // name that passed FIELD_NAME.
888
+ return table && field
889
+ ? `Write denied by policy: field "${field}" on "${table}" changes the record's ` +
890
+ "class or domain, so a writable wildcard never covers it. List it explicitly " +
891
+ `in fieldPolicy.${table}.writable to allow this write.`
892
+ : "Write denied by policy: a class or domain field must be listed explicitly in the writable set.";
893
+ case "unsupported_field_path":
894
+ // The key itself is not echoed: as a whole it did not pass FIELD_NAME.
895
+ return (`Write denied by policy: write keys${table ? ` on "${table}"` : ""} must be plain field names. ` +
896
+ "Dot-walked names (such as caller_id.email) and catalog variables (variables.*) " +
897
+ "cannot be written through this tool. To change a dot-walked value, update the " +
898
+ "referenced record itself.");
690
899
  default:
691
900
  return `Access denied by policy (${error.reason}).`;
692
901
  }
@@ -731,15 +940,17 @@ function resolveReadableFields(tableCandidate, input = {}) {
731
940
  const canonicalInput = snapshotPlainDataArguments(input);
732
941
  const responseFormat = normalizeResponseFormat(canonicalInput.responseFormat);
733
942
  const requested = canonicalInput.fields;
943
+ const hidden = typeHiddenFields(policy.table);
944
+ const queryDenied = canonicalInput.purpose === "query" ? (0, hidden_values_js_1.rowValueRule)(policy.table)?.queryDenied : undefined;
734
945
  if (requested === undefined) {
735
- return requireNonEmptySelection(responseFormat === "detailed" ? readableSelection(policy) : policy.defaults);
946
+ return visibleSelection(policy.table, requireNonEmptySelection(responseFormat === "detailed" ? readableSelection(policy) : policy.defaults));
736
947
  }
737
948
  if (typeof requested !== "string") {
738
949
  throw new FieldPolicyError("invalid_field_selection");
739
950
  }
740
951
  const trimmed = requested.trim();
741
952
  if (trimmed.toLowerCase() === "all") {
742
- return requireNonEmptySelection(readableSelection(policy));
953
+ return visibleSelection(policy.table, requireNonEmptySelection(readableSelection(policy)));
743
954
  }
744
955
  if (!trimmed)
745
956
  throw new FieldPolicyError("invalid_field_selection");
@@ -749,7 +960,10 @@ function resolveReadableFields(tableCandidate, input = {}) {
749
960
  const field = normalizeFieldName(candidate);
750
961
  if (seen.has(field))
751
962
  throw new FieldPolicyError("invalid_field_selection");
752
- if (isSensitiveFieldName(field)) {
963
+ // A hidden-typed field is refused exactly like a sensitive name, with the
964
+ // same message, before the readable check, so the refusal says nothing
965
+ // about the field's type or whether a configuration could grant it.
966
+ if (isSensitiveFieldName(field) || hidden.has(field) || queryDenied?.has(field)) {
753
967
  throw new FieldPolicyError("sensitive_field", { table: policy.table });
754
968
  }
755
969
  if (!fieldSetAllows(policy.readable, policy.allowAnyReadable, field)) {
@@ -758,7 +972,7 @@ function resolveReadableFields(tableCandidate, input = {}) {
758
972
  seen.add(field);
759
973
  selected.push(field);
760
974
  }
761
- return Object.freeze(selected);
975
+ return boundSelection(policy.table, selected);
762
976
  }
763
977
  /** Validate and clone one Table API write map using the separate write set. */
764
978
  function validateWritableFields(tableCandidate, payloadCandidate) {
@@ -782,13 +996,18 @@ function validateWritableFields(tableCandidate, payloadCandidate) {
782
996
  if (!("value" in descriptor)) {
783
997
  throw new FieldPolicyError("invalid_write_payload");
784
998
  }
785
- const field = normalizeFieldName(candidate);
999
+ const field = normalizeWriteFieldName(candidate, policy.table);
786
1000
  if (Object.hasOwn(output, field)) {
787
1001
  throw new FieldPolicyError("invalid_write_payload");
788
1002
  }
789
- if (isSensitiveFieldName(field)) {
1003
+ if (isSensitiveFieldName(field) || typeHiddenFields(policy.table).has(field)) {
790
1004
  throw new FieldPolicyError("sensitive_field", { table: policy.table });
791
1005
  }
1006
+ // policy.writable holds only explicitly listed names; it is empty when
1007
+ // the writable set is a wildcard.
1008
+ if (EXPLICIT_WRITE_FIELDS.has(field) && !policy.writable.includes(field)) {
1009
+ throw new FieldPolicyError("explicit_field_required", { table: policy.table, field });
1010
+ }
792
1011
  if (!fieldSetAllows(policy.writable, policy.allowAnyWritable, field)) {
793
1012
  throw new FieldPolicyError("non_writable_field", { table: policy.table, field });
794
1013
  }
@@ -823,14 +1042,21 @@ function prepareAdditionalReadFieldArguments(args, table, fields) {
823
1042
  safeDefineArgument(prepared, PREPARED_FIELD_ACCESS, issuePreparedAccess(canonicalArgs, table, readableFields));
824
1043
  return prepared;
825
1044
  }
1045
+ /**
1046
+ * The projection a write returns for one table: the table's readable set, or
1047
+ * `sys_id` alone when an operator made the table write-only (`readable: []`).
1048
+ * A write is authorized by the writable set; an empty readable set narrows
1049
+ * what comes back, it does not turn the write into a denial.
1050
+ */
1051
+ function resolveWriteResponseFields(tableCandidate) {
1052
+ const selection = readableSelection(requirePolicy(tableCandidate));
1053
+ return selection.length === 0 ? WRITE_ONLY_RESPONSE_FIELDS : selection;
1054
+ }
826
1055
  /** Validate write keys and prepare the corresponding safe response projection. */
827
1056
  function prepareWriteFieldArguments(args, table) {
828
1057
  const canonicalArgs = withFieldPolicyArgumentValues(args);
829
1058
  const fields = validateWritableFields(table, canonicalArgs.fields);
830
- const readableFields = resolveReadableFields(table, {
831
- fields: "all",
832
- responseFormat: "detailed",
833
- });
1059
+ const readableFields = resolveWriteResponseFields(table);
834
1060
  const prepared = withFieldPolicyArgumentValues(canonicalArgs, { table, fields });
835
1061
  safeDefineArgument(prepared, PREPARED_FIELD_ACCESS, issuePreparedAccess(canonicalArgs, table, readableFields));
836
1062
  return prepared;
@@ -866,7 +1092,8 @@ function preparedReadableFields(args, tableCandidate) {
866
1092
  if (!Array.isArray(fields) || !Object.isFrozen(fields))
867
1093
  return undefined;
868
1094
  if (isAllFieldSelection(fields)) {
869
- return policy.allowAnyReadable ? ALL_FIELDS_SELECTION : undefined;
1095
+ // The entry's own wildcard, which carries its table's hidden fields.
1096
+ return policy.allowAnyReadable ? fields : undefined;
870
1097
  }
871
1098
  if (fields.some((field) => typeof field !== "string" ||
872
1099
  !fieldSetAllows(policy.readable, policy.allowAnyReadable, field))) {
@@ -882,12 +1109,12 @@ function preparedReadableFields(args, tableCandidate) {
882
1109
  function filterReadableRecord(candidate, readableFields) {
883
1110
  if (node_util_1.types.isProxy(readableFields))
884
1111
  return null;
1112
+ const context = selectionContext(readableFields);
885
1113
  const state = responseTraversalState();
886
- if (isAllFieldSelection(readableFields)) {
887
- return sanitizeNestedValue(candidate, state, 0);
888
- }
889
- const approved = new Set(readableFields.map(normalizeFieldName));
890
- return filterRecordNode(candidate, approved, state, 0);
1114
+ const filtered = isAllFieldSelection(readableFields)
1115
+ ? sanitizeNestedValue(candidate, state, 0)
1116
+ : filterRecordNode(candidate, new Set(readableFields.map(normalizeFieldName)), state, 0);
1117
+ return context === undefined ? filtered : applyHiddenRules(filtered, context);
891
1118
  }
892
1119
  /** Remove metadata entries for fields the caller is not permitted to discover. */
893
1120
  function filterSchemaEntries(candidate, readableFields) {
@@ -948,15 +1175,26 @@ function filterSchemaEntries(candidate, readableFields) {
948
1175
  function filterAggregateResult(candidate, readableFields) {
949
1176
  if (node_util_1.types.isProxy(readableFields))
950
1177
  return null;
1178
+ const hidden = selectionContext(readableFields)?.hidden ?? EMPTY_FIELDS;
951
1179
  const state = responseTraversalState();
952
1180
  if (isAllFieldSelection(readableFields)) {
953
- return sanitizeNestedValue(candidate, state, 0);
1181
+ const sanitized = sanitizeNestedValue(candidate, state, 0);
1182
+ return hidden.size === 0 ? sanitized : withoutAggregateFields(sanitized, hidden, 0);
954
1183
  }
955
- const approved = new Set(readableFields.map(normalizeFieldName));
1184
+ const approved = new Set(readableFields.map(normalizeFieldName).filter((field) => !hidden.has(field)));
956
1185
  return filterAggregateNode(candidate, approved, state, 0);
957
1186
  }
958
1187
  function runWithFieldPolicyConfiguration(configuration, callback) {
959
- return FIELD_POLICY_CONFIGURATION_SCOPE.run(configuration ?? Object.freeze({}), callback);
1188
+ return FIELD_POLICY_CONFIGURATION_SCOPE.run(configuration ?? NO_FIELD_POLICY_CONFIGURATION, callback);
1189
+ }
1190
+ const NO_FIELD_POLICY_CONFIGURATION = Object.freeze({});
1191
+ /**
1192
+ * The field-policy configuration in force, as an identity: two preparations
1193
+ * that see the same object were checked against the same policy. Undefined
1194
+ * outside a configuration scope.
1195
+ */
1196
+ function currentFieldPolicyConfiguration() {
1197
+ return FIELD_POLICY_CONFIGURATION_SCOPE.getStore();
960
1198
  }
961
1199
  /** True when a field selection means ServiceNow should return all fields. */
962
1200
  function isAllFieldSelection(selection) {
@@ -976,6 +1214,206 @@ function isSensitiveFieldName(candidate) {
976
1214
  return (/(?:^|_)(?:password|passwd|credential|credentials|secret|token|api_key|private_key|encryption_key|ssn)(?:_|$)/u.test(normalized) ||
977
1215
  normalized === "social_security_number");
978
1216
  }
1217
+ const EMPTY_FIELDS = Object.freeze(new Set());
1218
+ /**
1219
+ * Type hiding. The dispatcher resolves each table's hidden-typed fields
1220
+ * (`hidden-values.ts`) before a call's plan is prepared and runs the plan and
1221
+ * the handler inside that scope. Every check above then treats a hidden-typed
1222
+ * field like a sensitive name: refused when named (with the same message),
1223
+ * dropped from a wildcard or configured projection, never written, and never
1224
+ * used to filter, order or group. Outside a dispatched call there is no scope
1225
+ * and only names are checked.
1226
+ */
1227
+ function typeHiddenFields(table) {
1228
+ const scope = (0, hidden_values_js_1.currentHiddenFieldScope)();
1229
+ if (scope === undefined)
1230
+ return EMPTY_FIELDS;
1231
+ const hidden = scope.tables.get(table);
1232
+ if (hidden !== undefined)
1233
+ return hidden;
1234
+ if (scope.unresolved === "names_only")
1235
+ return EMPTY_FIELDS;
1236
+ // A table outside the call's resolved plan has unknown types: refuse.
1237
+ throw new FieldPolicyError("field_types_unavailable", { table });
1238
+ }
1239
+ /** The hidden-typed fields of `table` in the running call; empty outside one. */
1240
+ function typeHiddenFieldNames(tableCandidate) {
1241
+ return typeHiddenFields(normalizeTableName(tableCandidate));
1242
+ }
1243
+ /**
1244
+ * Fields of `table` that may never filter, order, group or aggregate a read:
1245
+ * its hidden-typed fields and its row rule's value field. The sensitive-name
1246
+ * check applies on top, wherever a caller checks names.
1247
+ */
1248
+ function queryDeniedFields(tableCandidate) {
1249
+ const table = normalizeTableName(tableCandidate);
1250
+ const hidden = typeHiddenFields(table);
1251
+ const rule = (0, hidden_values_js_1.rowValueRule)(table);
1252
+ return rule === undefined ? hidden : new Set([...hidden, ...rule.queryDenied]);
1253
+ }
1254
+ /** {@link queryDeniedFields} for the table a selection was resolved on. */
1255
+ function queryDeniedForSelection(selection) {
1256
+ const context = selectionContext(selection);
1257
+ if (context === undefined)
1258
+ return EMPTY_FIELDS;
1259
+ return context.rule === undefined
1260
+ ? context.hidden
1261
+ : new Set([...context.hidden, ...context.rule.queryDenied]);
1262
+ }
1263
+ /**
1264
+ * Bind a projection the caller built itself (the bounded all-fields list) to
1265
+ * its table, without its hidden-typed fields, so the response filter applies
1266
+ * the table's rules to it.
1267
+ */
1268
+ function readableSelectionForTable(tableCandidate, fields,
1269
+ /** A selection this one extends; fields it added to fetch a type stay removed. */
1270
+ extending) {
1271
+ const table = normalizeTableName(tableCandidate);
1272
+ const inherited = extending === undefined ? undefined : SELECTION_CONTEXTS.get(extending)?.companions;
1273
+ return preparedSelection(table, fields, typeHiddenFields(table), inherited);
1274
+ }
1275
+ const SELECTION_CONTEXTS = new WeakMap();
1276
+ /** A frozen selection that remembers its table's hidden fields and row rule. */
1277
+ function boundSelection(table, fields, hidden = typeHiddenFields(table), companions = EMPTY_FIELDS) {
1278
+ const selection = Object.freeze([...fields]);
1279
+ const rule = (0, hidden_values_js_1.rowValueRule)(table);
1280
+ SELECTION_CONTEXTS.set(selection, Object.freeze({ hidden, ...(rule === undefined ? {} : { rule }), companions }));
1281
+ return selection;
1282
+ }
1283
+ /**
1284
+ * Bound copies of policy-chosen projections, per source list, table and
1285
+ * hidden set, so repeated resolutions in one scope return the same frozen
1286
+ * object (as they did before selections were bound).
1287
+ */
1288
+ const VISIBLE_SELECTIONS = new WeakMap();
1289
+ /** A policy-chosen projection (defaults, or "all") without hidden-typed fields. */
1290
+ function visibleSelection(table, selection) {
1291
+ const hidden = typeHiddenFields(table);
1292
+ let byTable = VISIBLE_SELECTIONS.get(selection);
1293
+ if (!byTable)
1294
+ VISIBLE_SELECTIONS.set(selection, (byTable = new Map()));
1295
+ let byHidden = byTable.get(table);
1296
+ if (!byHidden)
1297
+ byTable.set(table, (byHidden = new WeakMap()));
1298
+ const cached = byHidden.get(hidden);
1299
+ if (cached)
1300
+ return cached;
1301
+ const bound = isAllFieldSelection(selection)
1302
+ ? boundSelection(table, ALL_FIELDS_SELECTION, hidden)
1303
+ : boundSelection(table, requireNonEmptySelection(selection.filter((field) => !hidden.has(field))), hidden);
1304
+ byHidden.set(hidden, bound);
1305
+ return bound;
1306
+ }
1307
+ /**
1308
+ * The projection a prepared marker carries: hidden-typed fields removed, and
1309
+ * a row rule's type field added when its value field is selected, so each
1310
+ * row's type comes back to decide the value (the type is dropped from the
1311
+ * output again).
1312
+ */
1313
+ function preparedSelection(table, readableFields, hidden, inheritedCompanions = EMPTY_FIELDS) {
1314
+ if (isAllFieldSelection(readableFields)) {
1315
+ return boundSelection(table, ALL_FIELDS_SELECTION, hidden);
1316
+ }
1317
+ let fields = readableFields.filter((field) => !hidden.has(field));
1318
+ if (fields.length === 0)
1319
+ fields = [...WRITE_ONLY_RESPONSE_FIELDS];
1320
+ const rule = (0, hidden_values_js_1.rowValueRule)(table);
1321
+ if (rule !== undefined &&
1322
+ fields.includes(rule.valueField) &&
1323
+ !fields.includes(rule.typeField) &&
1324
+ !hidden.has(rule.typeField) &&
1325
+ typeFieldReadable(table, rule.typeField)) {
1326
+ return boundSelection(table, [...fields, rule.typeField], hidden, new Set([...inheritedCompanions, rule.typeField]));
1327
+ }
1328
+ return boundSelection(table, fields, hidden, inheritedCompanions);
1329
+ }
1330
+ function typeFieldReadable(table, field) {
1331
+ try {
1332
+ const policy = requirePolicy(table);
1333
+ return (!isSensitiveFieldName(field) &&
1334
+ fieldSetAllows(policy.readable, policy.allowAnyReadable, field));
1335
+ }
1336
+ catch {
1337
+ return false;
1338
+ }
1339
+ }
1340
+ /**
1341
+ * The rules for a selection: its own table's when it was resolved here, else,
1342
+ * inside a dispatched call, the union over the call's tables (a projection
1343
+ * built elsewhere is held to what any table of the call hides).
1344
+ */
1345
+ function selectionContext(selection) {
1346
+ if (typeof selection === "object" && selection !== null) {
1347
+ const bound = SELECTION_CONTEXTS.get(selection);
1348
+ if (bound !== undefined)
1349
+ return bound;
1350
+ }
1351
+ const scope = (0, hidden_values_js_1.currentHiddenFieldScope)();
1352
+ if (scope === undefined)
1353
+ return undefined;
1354
+ const hidden = new Set();
1355
+ let rule;
1356
+ for (const [table, fields] of scope.tables) {
1357
+ for (const field of fields)
1358
+ hidden.add(field);
1359
+ rule ??= (0, hidden_values_js_1.rowValueRule)(table);
1360
+ }
1361
+ return { hidden, ...(rule === undefined ? {} : { rule }), companions: EMPTY_FIELDS };
1362
+ }
1363
+ /** Drop hidden-typed fields, apply the row rule, drop companions: per record. */
1364
+ function applyHiddenRules(filtered, context) {
1365
+ if (context.hidden.size === 0 && context.rule === undefined && context.companions.size === 0) {
1366
+ return filtered;
1367
+ }
1368
+ return Array.isArray(filtered)
1369
+ ? filtered.map((record) => hideInRecord(record, context))
1370
+ : hideInRecord(filtered, context);
1371
+ }
1372
+ function hideInRecord(record, context) {
1373
+ if (typeof record !== "object" || record === null || Array.isArray(record))
1374
+ return record;
1375
+ const output = (0, hidden_values_js_1.withoutFields)(record, context.hidden);
1376
+ const rule = context.rule;
1377
+ if (rule !== undefined && Object.hasOwn(output, rule.valueField) && (0, hidden_values_js_1.rowValueHidden)(rule, output)) {
1378
+ Reflect.deleteProperty(output, rule.valueField);
1379
+ }
1380
+ for (const companion of context.companions)
1381
+ Reflect.deleteProperty(output, companion);
1382
+ return output;
1383
+ }
1384
+ /** Remove hidden fields from already-sanitized aggregate data, at any depth. */
1385
+ function withoutAggregateFields(candidate, hidden, depth) {
1386
+ if (typeof candidate !== "object" || candidate === null || depth > exports.MAX_FIELD_VALUE_DEPTH) {
1387
+ return candidate;
1388
+ }
1389
+ if (Array.isArray(candidate)) {
1390
+ return candidate
1391
+ .filter((entry) => {
1392
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry))
1393
+ return true;
1394
+ const field = entry.field;
1395
+ return typeof field !== "string" || !hidden.has(field.trim().toLowerCase());
1396
+ })
1397
+ .map((entry) => withoutAggregateFields(entry, hidden, depth + 1));
1398
+ }
1399
+ const output = {};
1400
+ for (const [key, value] of Object.entries((0, hidden_values_js_1.withoutFields)(candidate, hidden))) {
1401
+ safeDefine(output, key, withoutAggregateFields(value, hidden, depth + 1));
1402
+ }
1403
+ return output;
1404
+ }
1405
+ /** Names the writable wildcard never covers; a profile must list each one. */
1406
+ exports.EXPLICIT_WRITE_FIELD_NAMES = Object.freeze([
1407
+ ...EXPLICIT_WRITE_FIELDS,
1408
+ ]);
1409
+ function describeFieldPolicy(tableCandidate) {
1410
+ const policy = requirePolicy(tableCandidate);
1411
+ return Object.freeze({
1412
+ readable: policy.allowAnyReadable ? "*" : Object.freeze([...policy.readable]),
1413
+ writable: policy.allowAnyWritable ? "*" : Object.freeze([...policy.writable]),
1414
+ explicitWritable: Object.freeze(exports.EXPLICIT_WRITE_FIELD_NAMES.filter((field) => policy.writable.includes(field))),
1415
+ });
1416
+ }
979
1417
  function requirePolicy(tableCandidate) {
980
1418
  const table = normalizeTableName(tableCandidate);
981
1419
  const policies = currentTableFieldPolicies();
@@ -990,30 +1428,143 @@ function requirePolicy(tableCandidate) {
990
1428
  function fieldSetAllows(fields, allowAny, field) {
991
1429
  return allowAny || fields.includes(field);
992
1430
  }
1431
+ /**
1432
+ * Policy maps for configurations that validateFieldPolicyConfiguration
1433
+ * accepted, keyed by the identity of their three parts (fieldPolicy,
1434
+ * readableTableFields, writableTableFields; ABSENT_CONFIGURATION_PART for an
1435
+ * unstated one). Only deep-frozen parts are recorded, so an entry can never
1436
+ * describe content that changed after validation. The keys are the profile
1437
+ * snapshots ProfileManager hands out, so entries go when the snapshots go.
1438
+ */
1439
+ const VALIDATED_POLICY_MAPS = new WeakMap();
1440
+ const ABSENT_CONFIGURATION_PART = Object.freeze({});
1441
+ /** Deeper than any valid field policy: fieldPolicy.table.kind[entry]. */
1442
+ const MAX_CACHED_CONFIGURATION_DEPTH = 8;
993
1443
  function currentTableFieldPolicies() {
994
- const configured = readConfiguredFieldPolicyDefinitions();
1444
+ // Only the profile scope configures field policy. SN_FIELD_POLICY_DEFINITIONS
1445
+ // reaches this point solely as the SN_PROFILE_NAME environment profile's
1446
+ // own keys (profile-manager.ts), never as a process-wide fallback.
1447
+ const scoped = FIELD_POLICY_CONFIGURATION_SCOPE.getStore();
1448
+ if (!scoped ||
1449
+ (scoped.fieldPolicy === undefined &&
1450
+ scoped.readableTableFields === undefined &&
1451
+ scoped.writableTableFields === undefined)) {
1452
+ return BUILT_IN_TABLE_FIELD_POLICIES;
1453
+ }
1454
+ // A configuration that passed profile load was built once, there.
1455
+ const validated = validatedPolicyMap(scoped);
1456
+ if (validated)
1457
+ return validated;
1458
+ // Anything else takes the full fail-closed path on every call.
1459
+ const configured = normalizeConfiguredFieldPolicy(scoped);
995
1460
  if (!configured)
996
1461
  return BUILT_IN_TABLE_FIELD_POLICIES;
997
1462
  // Configuration narrows the base; it is the only thing that denies a field.
998
1463
  return buildFieldPolicyMap(mergeFieldPolicyDefinitions(FIELD_POLICY_BASE, configured.definitions));
999
1464
  }
1465
+ function configurationParts(input) {
1466
+ const parts = [input.fieldPolicy, input.readableTableFields, input.writableTableFields].map((part) => (part === undefined ? ABSENT_CONFIGURATION_PART : part));
1467
+ return parts.every((part) => typeof part === "object" && part !== null)
1468
+ ? parts
1469
+ : undefined;
1470
+ }
1471
+ function validatedPolicyMap(input) {
1472
+ const parts = configurationParts(input);
1473
+ if (!parts)
1474
+ return undefined;
1475
+ return VALIDATED_POLICY_MAPS.get(parts[0])?.get(parts[1])?.get(parts[2]);
1476
+ }
1477
+ /** Record a validated map, but only for parts that can no longer change. */
1478
+ function rememberValidatedPolicyMap(input, map) {
1479
+ const parts = configurationParts(input);
1480
+ if (!parts || !parts.every((part) => isDeepFrozen(part, 0)))
1481
+ return;
1482
+ let second = VALIDATED_POLICY_MAPS.get(parts[0]);
1483
+ if (!second) {
1484
+ second = new WeakMap();
1485
+ VALIDATED_POLICY_MAPS.set(parts[0], second);
1486
+ }
1487
+ let third = second.get(parts[1]);
1488
+ if (!third) {
1489
+ third = new WeakMap();
1490
+ second.set(parts[1], third);
1491
+ }
1492
+ third.set(parts[2], map);
1493
+ }
1494
+ function isDeepFrozen(candidate, depth) {
1495
+ if (typeof candidate !== "object" || candidate === null)
1496
+ return true;
1497
+ if (depth > MAX_CACHED_CONFIGURATION_DEPTH ||
1498
+ node_util_1.types.isProxy(candidate) ||
1499
+ !Object.isFrozen(candidate)) {
1500
+ return false;
1501
+ }
1502
+ return Object.values(candidate).every((value) => isDeepFrozen(value, depth + 1));
1503
+ }
1000
1504
  function mergeFieldPolicyDefinitions(base, configured) {
1001
1505
  const merged = { ...base };
1002
- for (const [table, definition] of Object.entries(configured)) {
1506
+ // A profile's "*" entry also covers the ITSM tables and the named-only
1507
+ // tables it does not name, so they are merged even without an entry of their
1508
+ // own.
1509
+ const profileWildcard = Object.hasOwn(configured, FIELD_POLICY_WILDCARD)
1510
+ ? configured[FIELD_POLICY_WILDCARD]
1511
+ : undefined;
1512
+ const tables = new Set(Object.keys(configured));
1513
+ if (profileWildcard !== undefined) {
1514
+ for (const table of ITSM_TABLES)
1515
+ tables.add(table);
1516
+ for (const table of NAMED_ONLY_BUILT_INS)
1517
+ tables.add(table);
1518
+ }
1519
+ for (const table of tables) {
1520
+ const definition = Object.hasOwn(configured, table)
1521
+ ? configured[table]
1522
+ : {};
1003
1523
  const existing = merged[table];
1524
+ // Every table but the system tables (ITSM, named-only and custom alike) resolves each
1525
+ // set from its own entry, then the profile's "*" entry, then the base. A
1526
+ // named custom table therefore cannot escape a narrowing "*" by stating
1527
+ // only the other key. System tables never take the "*" entry.
1528
+ const fallback = table === FIELD_POLICY_WILDCARD || SYSTEM_TABLES.has(table)
1529
+ ? undefined
1530
+ : profileWildcard;
1531
+ const readable = definition.readable ?? fallback?.readable;
1004
1532
  merged[table] = {
1005
1533
  defaults: definition.defaults ??
1006
- inheritedDefaults(existing?.defaults, definition.readable),
1534
+ (existing === undefined && definition.readable === undefined
1535
+ ? // A named custom table that leaves readable to the "*" entry
1536
+ // projects what an unnamed table does: the "*" entry's defaults,
1537
+ // else sys_id, clamped. Inheriting the whole "*" readable list
1538
+ // made a concise read ask for every readable column.
1539
+ clampedDefaults(fallback?.defaults ?? GENERIC_DEFAULT_FIELDS, readable)
1540
+ : // Built-in defaults are clamped to the effective readable set, so
1541
+ // a narrowed "*" never leaves a default the table may not read.
1542
+ // sys_id leads every built-in list and stays whenever readable.
1543
+ inheritedDefaults(existing?.defaults, readable)),
1007
1544
  // An entry that states only `defaults` reads exactly those fields.
1008
- readable: definition.readable ?? existing?.readable ?? definition.defaults,
1545
+ readable: readable ?? existing?.readable ?? definition.defaults,
1009
1546
  // Omission no longer denies. An operator who states nothing about
1010
1547
  // writes has not asked for a restriction, and tableAccess already
1011
1548
  // decided whether this table is reachable at all.
1012
- writable: definition.writable ?? existing?.writable,
1549
+ writable: definition.writable ?? fallback?.writable ?? existing?.writable,
1013
1550
  };
1014
1551
  }
1015
1552
  return merged;
1016
1553
  }
1554
+ /**
1555
+ * Clamp a default projection to a readable set, the way the "*" entry's own
1556
+ * defaults are clamped for an unnamed table: keep the defaults the set
1557
+ * allows, and fall back to the set itself only when none survive.
1558
+ */
1559
+ function clampedDefaults(defaults, readable) {
1560
+ if (readable === undefined || readable === FIELD_POLICY_WILDCARD)
1561
+ return defaults;
1562
+ if (defaults === FIELD_POLICY_WILDCARD)
1563
+ return readable;
1564
+ const allowed = new Set(readable);
1565
+ const permitted = defaults.filter((field) => allowed.has(field));
1566
+ return permitted.length > 0 ? permitted : readable;
1567
+ }
1017
1568
  /**
1018
1569
  * Carry inherited defaults across a configured `readable` replacement.
1019
1570
  *
@@ -1036,7 +1587,11 @@ function inheritedDefaults(existingDefaults, configuredReadable) {
1036
1587
  const permitted = existingDefaults.filter((field) => configuredReadable.includes(field));
1037
1588
  return permitted.length > 0 ? permitted : configuredReadable;
1038
1589
  }
1039
- function buildFieldPolicyMap(definitions) {
1590
+ /**
1591
+ * @param root Configuration key the definitions came from. Given only while a
1592
+ * configuration is validated at load, so a contradiction names its table.
1593
+ */
1594
+ function buildFieldPolicyMap(definitions, root) {
1040
1595
  return new Map(Object.entries(definitions).map(([tableCandidate, definition]) => {
1041
1596
  const table = normalizePolicyTableName(tableCandidate);
1042
1597
  // An unstated set is open. Only an explicit operator list narrows.
@@ -1047,13 +1602,21 @@ function buildFieldPolicyMap(definitions) {
1047
1602
  const defaults = defaultsCandidate === FIELD_POLICY_WILDCARD ? ALL_FIELDS_SELECTION : defaultsCandidate;
1048
1603
  const readableFields = readable === FIELD_POLICY_WILDCARD ? [] : readable;
1049
1604
  const writableFields = writable === FIELD_POLICY_WILDCARD ? [] : writable;
1050
- if (!isAllFieldSelection(defaults)) {
1605
+ if (isAllFieldSelection(defaults)) {
1606
+ // "Return every column by default" contradicts a narrowed readable
1607
+ // set: a concise read would ask ServiceNow for every field.
1608
+ if (readable !== FIELD_POLICY_WILDCARD) {
1609
+ rejectConfiguration(root === undefined ? undefined : { key: `${root}.${table}.defaults` }, `is "*" (every field), which ${root}.${table}.readable does not allow. ` +
1610
+ 'List the default fields, or make readable "*".');
1611
+ }
1612
+ }
1613
+ else {
1051
1614
  for (const field of defaults) {
1052
1615
  if (!fieldSetAllows(readableFields, readable === FIELD_POLICY_WILDCARD, field)) {
1053
1616
  // Branded so a contradictory operator policy is classified as a
1054
1617
  // policy denial instead of escaping the request path as a raw
1055
1618
  // TypeError.
1056
- throw new FieldPolicyError("invalid_argument_shape");
1619
+ rejectConfiguration(root === undefined ? undefined : { key: `${root}.${table}.defaults` }, `lists "${field}", which ${root}.${table}.readable does not allow.`);
1057
1620
  }
1058
1621
  }
1059
1622
  }
@@ -1070,68 +1633,240 @@ function buildFieldPolicyMap(definitions) {
1070
1633
  ];
1071
1634
  }));
1072
1635
  }
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];
1636
+ /**
1637
+ * A malformed field-policy configuration, raised when a profile is loaded.
1638
+ *
1639
+ * The message names the key path to fix, and with it the table. It never
1640
+ * repeats a configured value that failed validation; a table or field name
1641
+ * appears only once it has passed FIELD_NAME.
1642
+ */
1643
+ class FieldPolicyConfigurationError extends Error {
1644
+ name = "FieldPolicyConfigurationError";
1645
+ }
1646
+ exports.FieldPolicyConfigurationError = FieldPolicyConfigurationError;
1647
+ const PROFILE_CONFIGURATION_LABELS = Object.freeze({
1648
+ fieldPolicy: "fieldPolicy",
1649
+ readableTableFields: "readableTableFields",
1650
+ writableTableFields: "writableTableFields",
1651
+ });
1652
+ /**
1653
+ * Reject a malformed profile field policy at load instead of on every request.
1654
+ *
1655
+ * The request path normalizes the same configuration on each call and fails
1656
+ * closed, so a malformed entry used to deny every call on the profile, reads
1657
+ * included, with an opaque reason. This runs the same normalizers with a key
1658
+ * path attached and throws FieldPolicyConfigurationError naming the table and
1659
+ * key. A configuration that passes cannot fail normalization on a request.
1660
+ *
1661
+ * Beyond malformed names and shapes, it rejects what used to load and then
1662
+ * silently fail open: `fieldPolicy` stated beside a table list (the request
1663
+ * path applied only the lists), unknown keys in a table or list entry (a
1664
+ * `writeable` typo narrowed nothing), table keys that differ only in case,
1665
+ * and a table repeated within one list (the last entry won).
1666
+ *
1667
+ * The map built here is kept for the request path when every part is deep
1668
+ * frozen, as ProfileManager's snapshots are: requests on a loaded profile
1669
+ * then reuse it instead of rebuilding it on each lookup.
1670
+ */
1671
+ function validateFieldPolicyConfiguration(input) {
1672
+ const map = validateConfiguration(input, PROFILE_CONFIGURATION_LABELS);
1673
+ if (map !== undefined)
1674
+ rememberValidatedPolicyMap(input, map);
1675
+ }
1676
+ /**
1677
+ * Map SN_FIELD_POLICY_DEFINITIONS onto the field-policy keys of the
1678
+ * SN_PROFILE_NAME environment profile. The caller passes the environment:
1679
+ * this module never reads process.env, so the variable cannot reach a
1680
+ * file-backed profile.
1681
+ *
1682
+ * The value is either a table map (`{"incident":{...}}`) or an object holding
1683
+ * the profile keys themselves (`fieldPolicy`, `readableTableFields`,
1684
+ * `writableTableFields`); both keep their previous meaning. A value that
1685
+ * mixes the two is rejected: the table keys used to be dropped silently.
1686
+ */
1687
+ function fieldPolicyInputFromEnvironment(environment) {
1688
+ const text = environment.SN_FIELD_POLICY_DEFINITIONS;
1079
1689
  if (text === undefined || text.trim() === "")
1080
- return undefined;
1690
+ return Object.freeze({});
1081
1691
  if (text.length > MAX_FIELD_POLICY_DEFINITIONS_TEXT_LENGTH) {
1082
- throw new FieldPolicyError("invalid_argument_shape");
1692
+ throw new FieldPolicyConfigurationError(`${FIELD_POLICY_DEFINITIONS_ENV} exceeds ${MAX_FIELD_POLICY_DEFINITIONS_TEXT_LENGTH} characters.`);
1083
1693
  }
1084
1694
  let parsed;
1085
1695
  try {
1086
1696
  parsed = JSON.parse(text);
1087
1697
  }
1088
1698
  catch {
1089
- throw new FieldPolicyError("invalid_argument_shape");
1699
+ throw new FieldPolicyConfigurationError(`${FIELD_POLICY_DEFINITIONS_ENV} is not valid JSON.`);
1700
+ }
1701
+ if (!isPlainRecordCandidate(parsed)) {
1702
+ throw new FieldPolicyConfigurationError(`${FIELD_POLICY_DEFINITIONS_ENV} must be a JSON object.`);
1703
+ }
1704
+ const record = definedOwnProperties(parsed);
1705
+ const stated = FIELD_POLICY_CONFIGURATION_KEYS.filter((key) => Object.hasOwn(record, key));
1706
+ if (stated.length > 0 && Object.keys(record).length > stated.length) {
1707
+ // The other keys are table names; they are not repeated here.
1708
+ throw new FieldPolicyConfigurationError(`${FIELD_POLICY_DEFINITIONS_ENV} mixes table keys with the profile keys ` +
1709
+ `${stated.join(", ")}. Use either a table map or the profile keys ` +
1710
+ `(${FIELD_POLICY_CONFIGURATION_KEYS.join(", ")}), not both.`);
1711
+ }
1712
+ const input = stated.length > 0
1713
+ ? Object.freeze(Object.fromEntries(stated.map((key) => [key, record[key]])))
1714
+ : Object.freeze({ fieldPolicy: record });
1715
+ validateConfiguration(input, stated.length > 0
1716
+ ? {
1717
+ fieldPolicy: `${FIELD_POLICY_DEFINITIONS_ENV}.fieldPolicy`,
1718
+ readableTableFields: `${FIELD_POLICY_DEFINITIONS_ENV}.readableTableFields`,
1719
+ writableTableFields: `${FIELD_POLICY_DEFINITIONS_ENV}.writableTableFields`,
1720
+ }
1721
+ : {
1722
+ ...PROFILE_CONFIGURATION_LABELS,
1723
+ fieldPolicy: FIELD_POLICY_DEFINITIONS_ENV,
1724
+ });
1725
+ return input;
1726
+ }
1727
+ /**
1728
+ * @returns The policy map the request path would build for this input, or
1729
+ * undefined when the input states no field policy at all (the request path
1730
+ * then uses the built-in map).
1731
+ */
1732
+ function validateConfiguration(input, labels) {
1733
+ if (!isPlainRecordCandidate(input)) {
1734
+ throw new FieldPolicyConfigurationError("Field policy configuration must be an object.");
1090
1735
  }
1091
- return normalizeConfiguredFieldPolicy(parsed);
1736
+ const record = definedOwnProperties(input);
1737
+ if (!FIELD_POLICY_CONFIGURATION_KEYS.some((key) => Object.hasOwn(record, key))) {
1738
+ return undefined;
1739
+ }
1740
+ const statedLists = TABLE_FIELD_LIST_KEYS.filter((key) => Object.hasOwn(record, key));
1741
+ if (Object.hasOwn(record, "fieldPolicy") && statedLists.length > 0) {
1742
+ // The request path applied only the lists and dropped every narrowing in
1743
+ // fieldPolicy. There is no unambiguous merge, so the two forms exclude
1744
+ // each other.
1745
+ throw new FieldPolicyConfigurationError(`${labels.fieldPolicy} cannot be combined with ` +
1746
+ `${statedLists.map((key) => labels[key]).join(" and ")}. State the field ` +
1747
+ "policy in one form: fieldPolicy alone, or readableTableFields and " +
1748
+ "writableTableFields without fieldPolicy.");
1749
+ }
1750
+ try {
1751
+ // The same normalizers the request path runs, with key paths attached.
1752
+ // The labels only shape error messages, so the map is the one a request
1753
+ // would build.
1754
+ if (Object.hasOwn(record, "fieldPolicy")) {
1755
+ return buildFieldPolicyMap(mergeFieldPolicyDefinitions(FIELD_POLICY_BASE, fieldPolicyDefinitions(record.fieldPolicy, labels.fieldPolicy)), labels.fieldPolicy);
1756
+ }
1757
+ return buildFieldPolicyMap(mergeFieldPolicyDefinitions(FIELD_POLICY_BASE, tableFieldListDefinitions(record, labels)));
1758
+ }
1759
+ catch (error) {
1760
+ if (error instanceof FieldPolicyConfigurationError)
1761
+ throw error;
1762
+ if (isFieldPolicyError(error)) {
1763
+ throw new FieldPolicyConfigurationError(`Field policy configuration is invalid (${error.reason}).`);
1764
+ }
1765
+ throw error;
1766
+ }
1767
+ }
1768
+ function configurationLocation(key, table) {
1769
+ if (key === undefined)
1770
+ return undefined;
1771
+ return table === undefined ? { key } : { key, table };
1772
+ }
1773
+ function rejectConfiguration(location, problem, entry = "") {
1774
+ if (location === undefined)
1775
+ throw new FieldPolicyError("invalid_argument_shape");
1776
+ const table = location.table === undefined ? "" : ` (table "${location.table}")`;
1777
+ throw new FieldPolicyConfigurationError(`${location.key}${entry}${table} ${problem}`);
1092
1778
  }
1093
1779
  function normalizeConfiguredFieldPolicy(parsed) {
1094
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed) || node_util_1.types.isProxy(parsed)) {
1780
+ if (!isPlainRecordCandidate(parsed)) {
1095
1781
  throw new FieldPolicyError("invalid_argument_shape");
1096
1782
  }
1097
1783
  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)
1784
+ if (TABLE_FIELD_LIST_KEYS.some((key) => Object.hasOwn(outerRecord, key))) {
1785
+ // Profile load rejects this combination. A scope that skipped the load
1786
+ // fails closed rather than applying one form and dropping the other.
1787
+ if (Object.hasOwn(outerRecord, "fieldPolicy")) {
1788
+ throw new FieldPolicyError("invalid_argument_shape");
1789
+ }
1790
+ return Object.freeze({ definitions: tableFieldListDefinitions(outerRecord) });
1791
+ }
1792
+ if (outerRecord.fieldPolicy === undefined)
1109
1793
  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");
1794
+ return Object.freeze({
1795
+ definitions: fieldPolicyDefinitions(outerRecord.fieldPolicy),
1796
+ });
1797
+ }
1798
+ /**
1799
+ * Normalize a `fieldPolicy` table map.
1800
+ *
1801
+ * @param root Configuration key the map came from; given only at load.
1802
+ */
1803
+ function fieldPolicyDefinitions(source, root) {
1804
+ if (!isPlainRecordCandidate(source)) {
1805
+ rejectConfiguration(configurationLocation(root), "must be an object that maps table names to { defaults, readable, writable }.");
1112
1806
  }
1113
- const record = policySource;
1807
+ const record = source;
1114
1808
  const definitions = {};
1115
- for (const key of Object.keys(record)) {
1116
- const table = normalizePolicyTableName(key);
1809
+ const firstPosition = new Map();
1810
+ const keys = Object.keys(record);
1811
+ for (let position = 0; position < keys.length; position += 1) {
1812
+ const key = keys[position];
1813
+ const keyLocation = configurationLocation(root === undefined ? undefined : `${root} key ${position + 1}`);
1814
+ const table = normalizePolicyTableName(key, keyLocation);
1815
+ // Table names are case-insensitive, so "INCIDENT" and "incident" are one
1816
+ // table, and the later entry used to replace the earlier one silently.
1817
+ const earlier = firstPosition.get(table);
1818
+ if (earlier !== undefined) {
1819
+ rejectConfiguration(keyLocation, `names table "${table}" again (table names are case-insensitive); ` +
1820
+ `it repeats key ${earlier + 1}. State each table once.`);
1821
+ }
1822
+ firstPosition.set(table, position);
1823
+ const path = root === undefined ? undefined : `${root}.${table}`;
1117
1824
  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");
1825
+ if (!isPlainRecordCandidate(value)) {
1826
+ rejectConfiguration(configurationLocation(path), "must be an object with defaults, readable, or writable.");
1120
1827
  }
1121
1828
  const candidate = definedOwnProperties(value);
1829
+ rejectUnknownKeys(candidate, TABLE_ENTRY_KEYS, configurationLocation(path), "A table entry accepts only defaults, readable, and writable.");
1122
1830
  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);
1831
+ for (const kind of TABLE_ENTRY_KEYS) {
1832
+ if (Object.hasOwn(candidate, kind)) {
1833
+ definition[kind] = normalizePolicyFieldSet(candidate[kind], configurationLocation(path === undefined ? undefined : `${path}.${kind}`));
1834
+ }
1131
1835
  }
1132
1836
  definitions[table] = Object.freeze(definition);
1133
1837
  }
1134
- return Object.freeze({ definitions });
1838
+ return definitions;
1839
+ }
1840
+ /**
1841
+ * Reject a key outside `allowed`. An unknown key used to be ignored, so a
1842
+ * typo such as `writeable` loaded and narrowed nothing. The key is named only
1843
+ * when it is a valid identifier; anything else is identified by position.
1844
+ */
1845
+ function rejectUnknownKeys(record, allowed, location, accepted) {
1846
+ const keys = Object.keys(record);
1847
+ for (let position = 0; position < keys.length; position += 1) {
1848
+ const key = keys[position];
1849
+ if (allowed.includes(key))
1850
+ continue;
1851
+ rejectConfiguration(location, `has an unknown key ${FIELD_NAME.test(key) ? `"${key}"` : `at position ${position + 1}`}. ${accepted}`);
1852
+ }
1853
+ }
1854
+ /**
1855
+ * Normalize the `readableTableFields` / `writableTableFields` form.
1856
+ *
1857
+ * @param labels Configuration keys the lists came from; given only at load.
1858
+ */
1859
+ function tableFieldListDefinitions(record, labels) {
1860
+ const definitions = {};
1861
+ applyTableFieldList(definitions, record.readableTableFields, "readable", labels?.readableTableFields);
1862
+ applyTableFieldList(definitions, record.writableTableFields, "writable", labels?.writableTableFields);
1863
+ return definitions;
1864
+ }
1865
+ function isPlainRecordCandidate(candidate) {
1866
+ return (typeof candidate === "object" &&
1867
+ candidate !== null &&
1868
+ !Array.isArray(candidate) &&
1869
+ !node_util_1.types.isProxy(candidate));
1135
1870
  }
1136
1871
  /**
1137
1872
  * Drop own keys whose value is `undefined`.
@@ -1141,23 +1876,40 @@ function normalizeConfiguredFieldPolicy(parsed) {
1141
1876
  * Normalizing here keeps an object built with optional keys spread in
1142
1877
  * identical to one that never carried the key at all, so the same policy
1143
1878
  * cannot mean different things depending on how the caller constructed it.
1879
+ *
1880
+ * The copy has no prototype. On a plain `{}`, assigning a JSON own key
1881
+ * `__proto__` would replace the copy's prototype instead of defining a key,
1882
+ * so the unknown-key and mixed-key checks would never see it, and stated keys
1883
+ * could then be read through that prototype.
1144
1884
  */
1145
1885
  function definedOwnProperties(record) {
1146
- const defined = {};
1886
+ const defined = Object.create(null);
1147
1887
  for (const [key, value] of Object.entries(record)) {
1148
1888
  if (value !== undefined)
1149
1889
  defined[key] = value;
1150
1890
  }
1151
1891
  return defined;
1152
1892
  }
1153
- function applyTableFieldList(definitions, candidate, kind) {
1893
+ /**
1894
+ * @param root Configuration key the list came from; given only at load.
1895
+ */
1896
+ function applyTableFieldList(definitions, candidate, kind, root) {
1154
1897
  if (candidate === undefined)
1155
1898
  return;
1156
1899
  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);
1900
+ rejectConfiguration(configurationLocation(root), "must be a list of { table, fields } entries.");
1901
+ }
1902
+ // A table may appear in both lists, but only once in each: a repeated
1903
+ // entry used to replace the earlier one, so the last entry won.
1904
+ const firstIndex = new Map();
1905
+ for (let index = 0; index < candidate.length; index += 1) {
1906
+ const path = root === undefined ? undefined : `${root}[${index}]`;
1907
+ const normalized = normalizeTableFieldListDefinition(candidate[index], path);
1908
+ const earlier = firstIndex.get(normalized.table);
1909
+ if (earlier !== undefined) {
1910
+ rejectConfiguration(configurationLocation(path, normalized.table), `repeats a table already listed at ${root}[${earlier}]. List each table once.`);
1911
+ }
1912
+ firstIndex.set(normalized.table, index);
1161
1913
  const previous = definitions[normalized.table] ?? {};
1162
1914
  definitions[normalized.table] = Object.freeze({
1163
1915
  ...previous,
@@ -1165,13 +1917,14 @@ function applyTableFieldList(definitions, candidate, kind) {
1165
1917
  });
1166
1918
  }
1167
1919
  }
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");
1920
+ function normalizeTableFieldListDefinition(candidate, path) {
1921
+ if (!isPlainRecordCandidate(candidate)) {
1922
+ rejectConfiguration(configurationLocation(path), "must be an object with table and fields.");
1171
1923
  }
1172
1924
  const record = candidate;
1173
- const table = normalizePolicyTableName(record.table);
1174
- const fields = normalizePolicyFieldSet(record.fields);
1925
+ const table = normalizePolicyTableName(record.table, configurationLocation(path === undefined ? undefined : `${path}.table`));
1926
+ rejectUnknownKeys(definedOwnProperties(record), LIST_ENTRY_KEYS, configurationLocation(path, table), "A list entry accepts only table and fields.");
1927
+ const fields = normalizePolicyFieldSet(record.fields, configurationLocation(path === undefined ? undefined : `${path}.fields`, table));
1175
1928
  return Object.freeze({ table, fields });
1176
1929
  }
1177
1930
  function readableSelection(policy) {
@@ -1187,10 +1940,17 @@ function requireNonEmptySelection(selection) {
1187
1940
  throw new FieldPolicyError("unreadable_field");
1188
1941
  return selection;
1189
1942
  }
1190
- function normalizePolicyTableName(candidate) {
1943
+ function normalizePolicyTableName(candidate, location) {
1191
1944
  if (candidate === FIELD_POLICY_WILDCARD)
1192
1945
  return FIELD_POLICY_WILDCARD;
1193
- return normalizeTableName(candidate);
1946
+ try {
1947
+ return normalizeTableName(candidate);
1948
+ }
1949
+ catch (error) {
1950
+ if (location === undefined)
1951
+ throw error;
1952
+ rejectConfiguration(location, `is not a valid table name. Use a table name (${FIELD_NAME_RULE}) or "*".`);
1953
+ }
1194
1954
  }
1195
1955
  function normalizeTableName(candidate) {
1196
1956
  if (typeof candidate !== "string") {
@@ -1212,6 +1972,32 @@ function normalizeFieldName(candidate) {
1212
1972
  }
1213
1973
  return normalized;
1214
1974
  }
1975
+ /** Longest dotted write key inspected for a specific denial message. */
1976
+ const MAX_FIELD_PATH_LENGTH = 1_024;
1977
+ /**
1978
+ * Normalize one write key. A dotted key whose every segment is a field name,
1979
+ * such as the dot-walk caller_id.email or variables.requested_for, is still
1980
+ * denied: Table API write support for those names is unverified. It gets its
1981
+ * own reason so the denial says why instead of reading as a malformed name.
1982
+ */
1983
+ function normalizeWriteFieldName(candidate, table) {
1984
+ try {
1985
+ return normalizeFieldName(candidate);
1986
+ }
1987
+ catch (error) {
1988
+ if (isFieldPath(candidate)) {
1989
+ throw new FieldPolicyError("unsupported_field_path", { table });
1990
+ }
1991
+ throw error;
1992
+ }
1993
+ }
1994
+ function isFieldPath(candidate) {
1995
+ if (typeof candidate !== "string" || candidate.length > MAX_FIELD_PATH_LENGTH) {
1996
+ return false;
1997
+ }
1998
+ const segments = candidate.trim().toLowerCase().split(".");
1999
+ return segments.length > 1 && segments.every((segment) => FIELD_NAME.test(segment));
2000
+ }
1215
2001
  function normalizeResponseFormat(candidate) {
1216
2002
  if (candidate === undefined || candidate === "concise")
1217
2003
  return "concise";
@@ -1219,31 +2005,57 @@ function normalizeResponseFormat(candidate) {
1219
2005
  return "detailed";
1220
2006
  throw new FieldPolicyError("invalid_field_selection");
1221
2007
  }
1222
- function normalizePolicyFieldSet(candidates) {
1223
- if (candidates === FIELD_POLICY_WILDCARD)
2008
+ function normalizePolicyFieldSet(candidates, location) {
2009
+ if (candidates === FIELD_POLICY_WILDCARD || isWildcardFieldList(candidates)) {
1224
2010
  return FIELD_POLICY_WILDCARD;
1225
- return normalizePolicyFields(candidates);
2011
+ }
2012
+ return normalizePolicyFields(candidates, location);
1226
2013
  }
1227
- function normalizePolicyFields(candidates) {
2014
+ /**
2015
+ * `["*"]` is how `tableAccess.writeTables` spells "everything", so an operator
2016
+ * writes it here too. It means exactly what the string `"*"` means.
2017
+ */
2018
+ function isWildcardFieldList(candidate) {
2019
+ return (Array.isArray(candidate) &&
2020
+ !node_util_1.types.isProxy(candidate) &&
2021
+ candidate.length === 1 &&
2022
+ candidate[0] === FIELD_POLICY_WILDCARD);
2023
+ }
2024
+ function normalizePolicyFields(candidates, location) {
1228
2025
  // Operator policy is normalized on the request path, so a malformed set
1229
2026
  // must surface as a branded policy denial rather than a raw TypeError.
1230
2027
  if (!Array.isArray(candidates) || node_util_1.types.isProxy(candidates)) {
1231
- throw new FieldPolicyError("invalid_argument_shape");
2028
+ rejectConfiguration(location, 'must be "*" or a list of field names.');
1232
2029
  }
1233
- const fields = candidates.map((field) => normalizeFieldName(field));
1234
- if (new Set(fields).size !== fields.length) {
1235
- throw new FieldPolicyError("invalid_argument_shape");
2030
+ const fields = [];
2031
+ const seen = new Set();
2032
+ for (let index = 0; index < candidates.length; index += 1) {
2033
+ let field;
2034
+ try {
2035
+ field = normalizeFieldName(candidates[index]);
2036
+ }
2037
+ catch (error) {
2038
+ if (location === undefined)
2039
+ throw error;
2040
+ rejectConfiguration(location, `is not a field name. List exact field names (${FIELD_NAME_RULE}), or use "*" ` +
2041
+ 'on its own for every field; patterns such as "u_*" are not supported.', `[${index}]`);
2042
+ }
2043
+ if (seen.has(field)) {
2044
+ rejectConfiguration(location, `repeats the field "${field}".`, `[${index}]`);
2045
+ }
2046
+ seen.add(field);
2047
+ fields.push(field);
1236
2048
  }
1237
2049
  return Object.freeze(fields);
1238
2050
  }
1239
2051
  function issuePreparedAccess(args, table, readableFields) {
1240
2052
  const normalizedTable = normalizeTableName(table);
1241
2053
  const previous = issuedPreparedEntries(args).filter((entry) => entry.table !== normalizedTable);
2054
+ const hidden = typeHiddenFields(normalizedTable);
1242
2055
  const entry = Object.freeze({
1243
2056
  table: normalizedTable,
1244
- readableFields: isAllFieldSelection(readableFields)
1245
- ? ALL_FIELDS_SELECTION
1246
- : Object.freeze([...readableFields]),
2057
+ readableFields: preparedSelection(normalizedTable, readableFields, hidden),
2058
+ hiddenFields: Object.freeze([...hidden].sort()),
1247
2059
  });
1248
2060
  const marker = Object.freeze({
1249
2061
  entries: Object.freeze([...previous, entry]),