@memberjunction/core-entities-server 6.3.0-edge.2 → 6.3.0-edge.3

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 (171) hide show
  1. package/README.md +13 -0
  2. package/dist/custom/ArtifactSecurityHookHelpers.d.ts.map +1 -1
  3. package/dist/custom/ArtifactSecurityHookHelpers.js +50 -0
  4. package/dist/custom/ArtifactSecurityHookHelpers.js.map +1 -1
  5. package/dist/custom/GraphConceptReadSecurityHook.d.ts +75 -0
  6. package/dist/custom/GraphConceptReadSecurityHook.d.ts.map +1 -0
  7. package/dist/custom/GraphConceptReadSecurityHook.js +574 -0
  8. package/dist/custom/GraphConceptReadSecurityHook.js.map +1 -0
  9. package/dist/custom/GraphRecordChangesReadSecurityHook.d.ts +45 -0
  10. package/dist/custom/GraphRecordChangesReadSecurityHook.d.ts.map +1 -0
  11. package/dist/custom/GraphRecordChangesReadSecurityHook.js +744 -0
  12. package/dist/custom/GraphRecordChangesReadSecurityHook.js.map +1 -0
  13. package/dist/custom/MJAIAgentActionEntityServer.server.d.ts +13 -0
  14. package/dist/custom/MJAIAgentActionEntityServer.server.d.ts.map +1 -0
  15. package/dist/custom/MJAIAgentActionEntityServer.server.js +52 -0
  16. package/dist/custom/MJAIAgentActionEntityServer.server.js.map +1 -0
  17. package/dist/custom/MJAIAgentCategoryEntityServer.server.d.ts +30 -0
  18. package/dist/custom/MJAIAgentCategoryEntityServer.server.d.ts.map +1 -0
  19. package/dist/custom/MJAIAgentCategoryEntityServer.server.js +127 -0
  20. package/dist/custom/MJAIAgentCategoryEntityServer.server.js.map +1 -0
  21. package/dist/custom/MJAIAgentClientToolEntityServer.server.d.ts +12 -0
  22. package/dist/custom/MJAIAgentClientToolEntityServer.server.d.ts.map +1 -0
  23. package/dist/custom/MJAIAgentClientToolEntityServer.server.js +46 -0
  24. package/dist/custom/MJAIAgentClientToolEntityServer.server.js.map +1 -0
  25. package/dist/custom/MJAIAgentEntityServer.server.d.ts +113 -7
  26. package/dist/custom/MJAIAgentEntityServer.server.d.ts.map +1 -1
  27. package/dist/custom/MJAIAgentEntityServer.server.js +1946 -96
  28. package/dist/custom/MJAIAgentEntityServer.server.js.map +1 -1
  29. package/dist/custom/MJAIAgentModalityEntityServer.server.d.ts +13 -0
  30. package/dist/custom/MJAIAgentModalityEntityServer.server.d.ts.map +1 -0
  31. package/dist/custom/MJAIAgentModalityEntityServer.server.js +52 -0
  32. package/dist/custom/MJAIAgentModalityEntityServer.server.js.map +1 -0
  33. package/dist/custom/MJAIAgentNoteEntityServer.server.d.ts +64 -8
  34. package/dist/custom/MJAIAgentNoteEntityServer.server.d.ts.map +1 -1
  35. package/dist/custom/MJAIAgentNoteEntityServer.server.js +263 -9
  36. package/dist/custom/MJAIAgentNoteEntityServer.server.js.map +1 -1
  37. package/dist/custom/MJAIAgentPersonaEntityServer.server.d.ts +2 -2
  38. package/dist/custom/MJAIAgentPersonaEntityServer.server.d.ts.map +1 -1
  39. package/dist/custom/MJAIAgentPersonaEntityServer.server.js +10 -8
  40. package/dist/custom/MJAIAgentPersonaEntityServer.server.js.map +1 -1
  41. package/dist/custom/MJAIAgentRelationshipEntityServer.server.d.ts +5 -2
  42. package/dist/custom/MJAIAgentRelationshipEntityServer.server.d.ts.map +1 -1
  43. package/dist/custom/MJAIAgentRelationshipEntityServer.server.js +25 -2
  44. package/dist/custom/MJAIAgentRelationshipEntityServer.server.js.map +1 -1
  45. package/dist/custom/MJAIAgentSkillEntityServer.server.d.ts +12 -0
  46. package/dist/custom/MJAIAgentSkillEntityServer.server.d.ts.map +1 -0
  47. package/dist/custom/MJAIAgentSkillEntityServer.server.js +46 -0
  48. package/dist/custom/MJAIAgentSkillEntityServer.server.js.map +1 -0
  49. package/dist/custom/MJAIAgentStepTypeEntityServer.server.d.ts +28 -0
  50. package/dist/custom/MJAIAgentStepTypeEntityServer.server.d.ts.map +1 -0
  51. package/dist/custom/MJAIAgentStepTypeEntityServer.server.js +117 -0
  52. package/dist/custom/MJAIAgentStepTypeEntityServer.server.js.map +1 -0
  53. package/dist/custom/MJAIAgentTypeEntityServer.server.d.ts +34 -0
  54. package/dist/custom/MJAIAgentTypeEntityServer.server.d.ts.map +1 -0
  55. package/dist/custom/MJAIAgentTypeEntityServer.server.js +231 -0
  56. package/dist/custom/MJAIAgentTypeEntityServer.server.js.map +1 -0
  57. package/dist/custom/MJActionEntityServer.server.d.ts +37 -0
  58. package/dist/custom/MJActionEntityServer.server.d.ts.map +1 -1
  59. package/dist/custom/MJActionEntityServer.server.js +208 -3
  60. package/dist/custom/MJActionEntityServer.server.js.map +1 -1
  61. package/dist/custom/MJComponentEntityServer.server.d.ts +6 -0
  62. package/dist/custom/MJComponentEntityServer.server.d.ts.map +1 -1
  63. package/dist/custom/MJComponentEntityServer.server.js +20 -2
  64. package/dist/custom/MJComponentEntityServer.server.js.map +1 -1
  65. package/dist/custom/MJContentSourceEntityServer.server.d.ts +28 -0
  66. package/dist/custom/MJContentSourceEntityServer.server.d.ts.map +1 -0
  67. package/dist/custom/MJContentSourceEntityServer.server.js +73 -0
  68. package/dist/custom/MJContentSourceEntityServer.server.js.map +1 -0
  69. package/dist/custom/MJContentSourceTypeEntityServer.server.d.ts +25 -0
  70. package/dist/custom/MJContentSourceTypeEntityServer.server.d.ts.map +1 -0
  71. package/dist/custom/MJContentSourceTypeEntityServer.server.js +73 -0
  72. package/dist/custom/MJContentSourceTypeEntityServer.server.js.map +1 -0
  73. package/dist/custom/MJDashboardEntityServer.server.d.ts +6 -0
  74. package/dist/custom/MJDashboardEntityServer.server.d.ts.map +1 -1
  75. package/dist/custom/MJDashboardEntityServer.server.js +24 -2
  76. package/dist/custom/MJDashboardEntityServer.server.js.map +1 -1
  77. package/dist/custom/MJGraphConceptEntityServer.server.d.ts +175 -23
  78. package/dist/custom/MJGraphConceptEntityServer.server.d.ts.map +1 -1
  79. package/dist/custom/MJGraphConceptEntityServer.server.js +584 -41
  80. package/dist/custom/MJGraphConceptEntityServer.server.js.map +1 -1
  81. package/dist/custom/MJGraphEdgeEntityServer.server.d.ts +38 -11
  82. package/dist/custom/MJGraphEdgeEntityServer.server.d.ts.map +1 -1
  83. package/dist/custom/MJGraphEdgeEntityServer.server.js +249 -39
  84. package/dist/custom/MJGraphEdgeEntityServer.server.js.map +1 -1
  85. package/dist/custom/MJGraphEntityServer.server.d.ts +58 -0
  86. package/dist/custom/MJGraphEntityServer.server.d.ts.map +1 -0
  87. package/dist/custom/MJGraphEntityServer.server.js +357 -0
  88. package/dist/custom/MJGraphEntityServer.server.js.map +1 -0
  89. package/dist/custom/MJGraphLinkEntityServer.server.d.ts +98 -0
  90. package/dist/custom/MJGraphLinkEntityServer.server.d.ts.map +1 -0
  91. package/dist/custom/MJGraphLinkEntityServer.server.js +375 -0
  92. package/dist/custom/MJGraphLinkEntityServer.server.js.map +1 -0
  93. package/dist/custom/MJGraphPermissionEntityServer.server.d.ts +29 -0
  94. package/dist/custom/MJGraphPermissionEntityServer.server.d.ts.map +1 -0
  95. package/dist/custom/MJGraphPermissionEntityServer.server.js +141 -0
  96. package/dist/custom/MJGraphPermissionEntityServer.server.js.map +1 -0
  97. package/dist/custom/MJListDetailEntityServer.server.d.ts +4 -4
  98. package/dist/custom/MJListDetailEntityServer.server.js +4 -4
  99. package/dist/custom/MJListEntityServer.server.d.ts +2 -1
  100. package/dist/custom/MJListEntityServer.server.d.ts.map +1 -1
  101. package/dist/custom/MJListEntityServer.server.js +5 -2
  102. package/dist/custom/MJListEntityServer.server.js.map +1 -1
  103. package/dist/custom/MJQueryEntityServer.server.d.ts +51 -3
  104. package/dist/custom/MJQueryEntityServer.server.d.ts.map +1 -1
  105. package/dist/custom/MJQueryEntityServer.server.js +142 -28
  106. package/dist/custom/MJQueryEntityServer.server.js.map +1 -1
  107. package/dist/custom/MJQueryParameterEntityServer.server.d.ts +37 -0
  108. package/dist/custom/MJQueryParameterEntityServer.server.d.ts.map +1 -0
  109. package/dist/custom/MJQueryParameterEntityServer.server.js +160 -0
  110. package/dist/custom/MJQueryParameterEntityServer.server.js.map +1 -0
  111. package/dist/custom/MJQuerySQLEntityServer.server.d.ts +23 -0
  112. package/dist/custom/MJQuerySQLEntityServer.server.d.ts.map +1 -1
  113. package/dist/custom/MJQuerySQLEntityServer.server.js +106 -9
  114. package/dist/custom/MJQuerySQLEntityServer.server.js.map +1 -1
  115. package/dist/custom/MJRowLevelSecurityFilterEntityServer.server.d.ts +1 -1
  116. package/dist/custom/MJRowLevelSecurityFilterEntityServer.server.d.ts.map +1 -1
  117. package/dist/custom/MJRowLevelSecurityFilterEntityServer.server.js +8 -5
  118. package/dist/custom/MJRowLevelSecurityFilterEntityServer.server.js.map +1 -1
  119. package/dist/custom/MJUserRoleEntityServer.server.d.ts.map +1 -1
  120. package/dist/custom/MJUserRoleEntityServer.server.js +9 -0
  121. package/dist/custom/MJUserRoleEntityServer.server.js.map +1 -1
  122. package/dist/custom/MJUserViewEntityServer.server.d.ts +9 -0
  123. package/dist/custom/MJUserViewEntityServer.server.d.ts.map +1 -1
  124. package/dist/custom/MJUserViewEntityServer.server.js +59 -3
  125. package/dist/custom/MJUserViewEntityServer.server.js.map +1 -1
  126. package/dist/custom/agentRelationalGrantGuard.d.ts +73 -0
  127. package/dist/custom/agentRelationalGrantGuard.d.ts.map +1 -0
  128. package/dist/custom/agentRelationalGrantGuard.js +375 -0
  129. package/dist/custom/agentRelationalGrantGuard.js.map +1 -0
  130. package/dist/custom/approvalStamp.d.ts +68 -4
  131. package/dist/custom/approvalStamp.d.ts.map +1 -1
  132. package/dist/custom/approvalStamp.js +107 -13
  133. package/dist/custom/approvalStamp.js.map +1 -1
  134. package/dist/custom/canon/CanonFingerprintRecorderServer.d.ts +20 -0
  135. package/dist/custom/canon/CanonFingerprintRecorderServer.d.ts.map +1 -0
  136. package/dist/custom/canon/CanonFingerprintRecorderServer.js +148 -0
  137. package/dist/custom/canon/CanonFingerprintRecorderServer.js.map +1 -0
  138. package/dist/custom/canon/index.d.ts +2 -0
  139. package/dist/custom/canon/index.d.ts.map +1 -0
  140. package/dist/custom/canon/index.js +2 -0
  141. package/dist/custom/canon/index.js.map +1 -0
  142. package/dist/custom/graph/GraphFindPathServerOperation.d.ts +7 -5
  143. package/dist/custom/graph/GraphFindPathServerOperation.d.ts.map +1 -1
  144. package/dist/custom/graph/GraphFindPathServerOperation.js +41 -12
  145. package/dist/custom/graph/GraphFindPathServerOperation.js.map +1 -1
  146. package/dist/custom/graphPermissionGuard.d.ts +69 -0
  147. package/dist/custom/graphPermissionGuard.d.ts.map +1 -0
  148. package/dist/custom/graphPermissionGuard.js +229 -0
  149. package/dist/custom/graphPermissionGuard.js.map +1 -0
  150. package/dist/custom/graphRlsCacheInvalidation.d.ts +38 -0
  151. package/dist/custom/graphRlsCacheInvalidation.d.ts.map +1 -0
  152. package/dist/custom/graphRlsCacheInvalidation.js +111 -0
  153. package/dist/custom/graphRlsCacheInvalidation.js.map +1 -0
  154. package/dist/custom/queryParentFingerprint.d.ts +36 -0
  155. package/dist/custom/queryParentFingerprint.d.ts.map +1 -0
  156. package/dist/custom/queryParentFingerprint.js +159 -0
  157. package/dist/custom/queryParentFingerprint.js.map +1 -0
  158. package/dist/custom/queryParentSaveChain.d.ts +5 -0
  159. package/dist/custom/queryParentSaveChain.d.ts.map +1 -0
  160. package/dist/custom/queryParentSaveChain.js +25 -0
  161. package/dist/custom/queryParentSaveChain.js.map +1 -0
  162. package/dist/custom/seededMetadataPush.d.ts +7 -0
  163. package/dist/custom/seededMetadataPush.d.ts.map +1 -0
  164. package/dist/custom/seededMetadataPush.js +23 -0
  165. package/dist/custom/seededMetadataPush.js.map +1 -0
  166. package/dist/index.d.ts +19 -0
  167. package/dist/index.d.ts.map +1 -1
  168. package/dist/index.js +19 -0
  169. package/dist/index.js.map +1 -1
  170. package/dist/tsconfig.tsbuildinfo +1 -1
  171. package/package.json +31 -31
@@ -0,0 +1,744 @@
1
+ import { BaseEntity, CompositeKey, FormatVisibilityNodeKey, GetDataHooks, LogError, Metadata, RegisterDataHook, RegisterPostRunViewProtectedEntity, ResolveVisibility, RunView, WellKnownUserSource, } from '@memberjunction/core';
2
+ import { EscapeSQLString, GetGlobalObjectStore, UUIDMap, UUIDSet, UUIDsEqual } from '@memberjunction/global';
3
+ import { GraphEngine, GraphPermissionProvider, LoadCoreVisibilityRules, MJRecordChangeEntity, } from '@memberjunction/core-entities';
4
+ import { EntityNamesMatch, ExtractSingleUuidFieldFromFilter, ResolveTargetEntityNameAsync, StripSyntheticFieldsFromRow, } from './ArtifactSecurityHookHelpers.js';
5
+ import { IsGraphOwnerUser } from './graphPermissionGuard.js';
6
+ const RECORD_CHANGES_ENTITY_NAME = 'MJ: Record Changes';
7
+ /**
8
+ * Entities whose `MJ: Record Changes` audit rows contain graph-scoped state (link targets,
9
+ * concept text, edge descriptions, graph metadata) and therefore require `Read` permission
10
+ * on the owning graph before a non-admin caller can read those change rows (Finding 298 / D70).
11
+ */
12
+ export const GRAPH_SCOPED_RECORD_CHANGE_ENTITIES = [
13
+ 'MJ: Graphs',
14
+ 'MJ: Graph Concepts',
15
+ 'MJ: Graph Edges',
16
+ 'MJ: Graph Links',
17
+ ];
18
+ const REQUIRED_SECURITY_FIELDS = ['ID', 'EntityID', 'RecordID', 'FullRecordJSON', 'ChangesJSON'];
19
+ const GLOBAL_KEY_INTERNAL_PARAMS = '__MJ_INTERNAL_GRAPH_RC_SECURITY_PARAMS__';
20
+ const GLOBAL_KEY_ORIGINAL_FIELDS = '__MJ_ORIGINAL_GRAPH_RC_FIELDS_BY_PARAMS__';
21
+ function getInternalParamsSet() {
22
+ const store = GetGlobalObjectStore();
23
+ if (store) {
24
+ const existing = store[GLOBAL_KEY_INTERNAL_PARAMS];
25
+ if (existing instanceof WeakSet) {
26
+ return existing;
27
+ }
28
+ const created = new WeakSet();
29
+ store[GLOBAL_KEY_INTERNAL_PARAMS] = created;
30
+ return created;
31
+ }
32
+ return new WeakSet();
33
+ }
34
+ function getOriginalFieldsMap() {
35
+ const store = GetGlobalObjectStore();
36
+ if (store) {
37
+ const existing = store[GLOBAL_KEY_ORIGINAL_FIELDS];
38
+ if (existing instanceof WeakMap) {
39
+ return existing;
40
+ }
41
+ const created = new WeakMap();
42
+ store[GLOBAL_KEY_ORIGINAL_FIELDS] = created;
43
+ return created;
44
+ }
45
+ return new WeakMap();
46
+ }
47
+ function resolveProvider(hookProvider, contextUser) {
48
+ return (hookProvider ??
49
+ contextUser?.OwningProvider ??
50
+ Metadata.Provider ?? // global-provider-ok: fallback when provider is not attached to user
51
+ null);
52
+ }
53
+ function isExemptUser(user) {
54
+ if (!user) {
55
+ return false;
56
+ }
57
+ return WellKnownUserSource.Instance.IsSystemUser(user) || IsGraphOwnerUser(user);
58
+ }
59
+ function readRowField(row, fieldName) {
60
+ if (!row || typeof row !== 'object') {
61
+ return undefined;
62
+ }
63
+ if (row instanceof MJRecordChangeEntity) {
64
+ switch (fieldName) {
65
+ case 'ID':
66
+ return row.ID;
67
+ case 'EntityID':
68
+ return row.EntityID;
69
+ case 'RecordID':
70
+ return row.RecordID;
71
+ case 'FullRecordJSON':
72
+ return row.FullRecordJSON;
73
+ case 'ChangesJSON':
74
+ return row.ChangesJSON;
75
+ }
76
+ }
77
+ if (row instanceof BaseEntity) {
78
+ return row.GetFieldByName(fieldName)?.Value;
79
+ }
80
+ return row[fieldName];
81
+ }
82
+ function readJsonFieldCaseInsensitive(obj, targetLower) {
83
+ for (const [k, v] of Object.entries(obj)) {
84
+ if (k.trim().toLowerCase() === targetLower) {
85
+ return v;
86
+ }
87
+ }
88
+ return undefined;
89
+ }
90
+ /**
91
+ * Extracts all `GraphID` UUIDs referenced by a `MJ: Record Changes` row's `FullRecordJSON` and/or
92
+ * `ChangesJSON` payloads (including both `OldValue` and `NewValue` on a graph reparent).
93
+ */
94
+ export function ExtractGraphIdsFromRecordChangePayloads(fullRecordJson, changesJson) {
95
+ const seen = new UUIDSet();
96
+ const ids = [];
97
+ const add = (candidate) => {
98
+ if (typeof candidate !== 'string') {
99
+ return;
100
+ }
101
+ const trimmed = candidate.trim();
102
+ if (trimmed.length > 0 && !seen.Has(trimmed)) {
103
+ seen.Add(trimmed);
104
+ ids.push(trimmed);
105
+ }
106
+ };
107
+ if (typeof fullRecordJson === 'string' && fullRecordJson.trim().length > 0) {
108
+ try {
109
+ const parsed = JSON.parse(fullRecordJson);
110
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
111
+ add(readJsonFieldCaseInsensitive(parsed, 'graphid'));
112
+ }
113
+ }
114
+ catch {
115
+ // Malformed JSON — fail closed via empty extraction unless live lookup resolves it.
116
+ }
117
+ }
118
+ if (typeof changesJson === 'string' && changesJson.trim().length > 0) {
119
+ try {
120
+ const parsed = JSON.parse(changesJson);
121
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
122
+ const entry = readJsonFieldCaseInsensitive(parsed, 'graphid');
123
+ if (typeof entry === 'string') {
124
+ add(entry);
125
+ }
126
+ else if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
127
+ const changeObj = entry;
128
+ add(readJsonFieldCaseInsensitive(changeObj, 'oldvalue'));
129
+ add(readJsonFieldCaseInsensitive(changeObj, 'newvalue'));
130
+ }
131
+ }
132
+ }
133
+ catch {
134
+ // Malformed JSON — handled fail-closed downstream.
135
+ }
136
+ }
137
+ return ids;
138
+ }
139
+ /**
140
+ * Extracts the bare primary-key UUID from a `MJ: Record Changes.RecordID` value (handling both
141
+ * `'ID|<uuid>'` concatenated keys and bare `'<uuid>'` strings).
142
+ */
143
+ export function ExtractSingleRecordIdFromChange(entity, rawRecordId) {
144
+ const trimmed = typeof rawRecordId === 'string' ? rawRecordId.trim() : '';
145
+ if (trimmed.length === 0) {
146
+ return null;
147
+ }
148
+ try {
149
+ const key = CompositeKey.FromRecordID(entity, trimmed);
150
+ const firstVal = key.KeyValuePairs[0]?.Value;
151
+ const normalized = firstVal != null ? String(firstVal).trim() : '';
152
+ return normalized.length > 0 ? normalized : null;
153
+ }
154
+ catch {
155
+ const pipeIdx = trimmed.indexOf('|');
156
+ const fallback = pipeIdx >= 0 ? trimmed.slice(pipeIdx + 1).trim() : trimmed;
157
+ return fallback.length > 0 ? fallback : null;
158
+ }
159
+ }
160
+ function buildGraphScopedEntityIndex(provider) {
161
+ const byId = new UUIDMap();
162
+ let graphsEntityId = null;
163
+ let conceptsEntityId = null;
164
+ for (const name of GRAPH_SCOPED_RECORD_CHANGE_ENTITIES) {
165
+ const ent = provider.EntityByName(name);
166
+ if (ent) {
167
+ byId.Set(ent.ID, ent);
168
+ if (name === 'MJ: Graphs') {
169
+ graphsEntityId = ent.ID;
170
+ }
171
+ else if (name === 'MJ: Graph Concepts') {
172
+ conceptsEntityId = ent.ID;
173
+ }
174
+ }
175
+ }
176
+ return { GraphsEntityID: graphsEntityId, ConceptsEntityID: conceptsEntityId, ByEntityId: byId };
177
+ }
178
+ async function loadReadableGraphIdsForUser(user, provider) {
179
+ if (!provider.EntityByName('MJ: Graph Permissions')) {
180
+ return new UUIDSet();
181
+ }
182
+ try {
183
+ const permProvider = new GraphPermissionProvider();
184
+ const resources = await permProvider.GetUserResources(user, 'Graphs', provider);
185
+ return new UUIDSet(resources
186
+ .filter((r) => r.Actions.includes('Read'))
187
+ .map((r) => r.ResourceID));
188
+ }
189
+ catch (err) {
190
+ const msg = err instanceof Error ? err.message : String(err);
191
+ LogError(`GraphRecordChangesReadSecurityHook: failed loading readable graphs for user '${user.ID}': ${msg}`);
192
+ return new UUIDSet();
193
+ }
194
+ }
195
+ async function lookupLiveGraphIdsByRecordIds(entity, recordIds, provider, contextUser) {
196
+ const out = new UUIDMap();
197
+ const unique = Array.from(new Set(recordIds.filter((id) => id.trim().length > 0)));
198
+ if (unique.length === 0) {
199
+ return out;
200
+ }
201
+ const pkName = entity.FirstPrimaryKey?.Name; // first-pk-ok: Graph entities all use single GUID PK 'ID'
202
+ if (!pkName) {
203
+ return out;
204
+ }
205
+ const systemUser = (await WellKnownUserSource.Instance.GetSystemUser(provider)) ?? contextUser;
206
+ const params = {
207
+ EntityName: entity.Name,
208
+ ExtraFilter: `[${pkName}] IN (${unique.map((id) => `'${EscapeSQLString(id)}'`).join(',')})`,
209
+ Fields: [pkName, 'GraphID'],
210
+ ResultType: 'simple',
211
+ };
212
+ getInternalParamsSet().add(params);
213
+ try {
214
+ const res = await RunView.FromMetadataProvider(provider).RunView(params, systemUser);
215
+ if (res.Success && Array.isArray(res.Results)) {
216
+ for (const row of res.Results) {
217
+ const recId = row[pkName];
218
+ const graphId = row['GraphID'];
219
+ if (typeof recId === 'string' && typeof graphId === 'string' && graphId.trim().length > 0) {
220
+ out.Set(recId, graphId.trim());
221
+ }
222
+ }
223
+ }
224
+ }
225
+ catch (err) {
226
+ const msg = err instanceof Error ? err.message : String(err);
227
+ LogError(`GraphRecordChangesReadSecurityHook: live GraphID lookup failed for '${entity.Name}': ${msg}`);
228
+ }
229
+ return out;
230
+ }
231
+ /**
232
+ * Explicit allow-list of non-sensitive structural columns preserved on a Redacted concept's
233
+ * `MJ: Record Changes` row (Finding 394). Every other column (including `FullRecordJSON`,
234
+ * `ChangesJSON`, `ChangesDescription`, `ErrorLog`, `Comments`, `RestoreReason`, `ChangeContext`,
235
+ * and any future text column) is nulled so hidden concept text cannot leak.
236
+ */
237
+ export const REDACTED_RECORD_CHANGE_ALLOWED_FIELDS = new Set([
238
+ 'id',
239
+ 'entityid',
240
+ 'recordid',
241
+ 'userid',
242
+ 'type',
243
+ 'source',
244
+ 'changedat',
245
+ 'status',
246
+ '__mj_createdat',
247
+ '__mj_updatedat',
248
+ ]);
249
+ function redactRecordChangeRowByAllowList(row) {
250
+ if (!row || typeof row !== 'object') {
251
+ return row;
252
+ }
253
+ if (row instanceof BaseEntity) {
254
+ for (const field of row.Fields) {
255
+ if (!REDACTED_RECORD_CHANGE_ALLOWED_FIELDS.has(field.Name.trim().toLowerCase()) && field.Value != null) {
256
+ field.Value = null;
257
+ field.ResetOldValue();
258
+ }
259
+ }
260
+ return row;
261
+ }
262
+ const copy = { ...row };
263
+ for (const key of Object.keys(copy)) {
264
+ if (!REDACTED_RECORD_CHANGE_ALLOWED_FIELDS.has(key.trim().toLowerCase())) {
265
+ copy[key] = null;
266
+ }
267
+ }
268
+ return copy;
269
+ }
270
+ /**
271
+ * Extracts `ParentID` values referenced inside `FullRecordJSON` (`ParentID`) and `ChangesJSON`
272
+ * (`ParentID.OldValue` / `ParentID.NewValue`) for an `MJ: Graph Concepts` change row (Finding 394).
273
+ */
274
+ function extractParentIdsFromConceptChangePayloads(fullRecordJson, changesJson) {
275
+ const ids = [];
276
+ const seen = new Set();
277
+ let parseError = false;
278
+ const add = (val) => {
279
+ if (typeof val === 'string' && val.trim().length > 0) {
280
+ const trimmed = val.trim();
281
+ const lower = trimmed.toLowerCase();
282
+ if (!seen.has(lower)) {
283
+ seen.add(lower);
284
+ ids.push(trimmed);
285
+ }
286
+ }
287
+ };
288
+ if (typeof fullRecordJson === 'string' && fullRecordJson.trim().length > 0) {
289
+ try {
290
+ const parsed = JSON.parse(fullRecordJson);
291
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
292
+ add(parsed['ParentID'] ?? parsed['parentId'] ?? parsed['parentid']);
293
+ }
294
+ }
295
+ catch {
296
+ parseError = true;
297
+ }
298
+ }
299
+ if (typeof changesJson === 'string' && changesJson.trim().length > 0) {
300
+ try {
301
+ const parsed = JSON.parse(changesJson);
302
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
303
+ const entry = parsed['ParentID'] ?? parsed['parentId'] ?? parsed['parentid'];
304
+ if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
305
+ const delta = entry;
306
+ add(delta['OldValue'] ?? delta['oldValue']);
307
+ add(delta['NewValue'] ?? delta['newValue']);
308
+ }
309
+ }
310
+ }
311
+ catch {
312
+ parseError = true;
313
+ }
314
+ }
315
+ return { ParentIds: ids, ParseError: parseError };
316
+ }
317
+ function stripParentKeyFromJsonString(raw) {
318
+ if (typeof raw !== 'string' || raw.trim().length === 0) {
319
+ return { Value: typeof raw === 'string' ? raw : null, HadParentKey: false, Failed: false };
320
+ }
321
+ try {
322
+ const parsed = JSON.parse(raw);
323
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
324
+ return { Value: null, HadParentKey: false, Failed: true };
325
+ }
326
+ const obj = { ...parsed };
327
+ let hadParentKey = false;
328
+ for (const key of Object.keys(obj)) {
329
+ if (key.trim().toLowerCase() === 'parent') {
330
+ delete obj[key];
331
+ hadParentKey = true;
332
+ }
333
+ }
334
+ return { Value: hadParentKey ? JSON.stringify(obj) : raw, HadParentKey: hadParentKey, Failed: false };
335
+ }
336
+ catch {
337
+ return { Value: null, HadParentKey: false, Failed: true };
338
+ }
339
+ }
340
+ /**
341
+ * Strips the virtual `Parent` key from `FullRecordJSON` and `ChangesJSON` on an Allowed concept
342
+ * change row whose parent concept did not resolve `'Allowed'` (Finding 394). If either JSON blob
343
+ * cannot be safely parsed, nulls both columns (fail closed). Never mutates frozen cache rows.
344
+ */
345
+ function stripParentNameFromRecordChangePayload(row) {
346
+ if (!row || typeof row !== 'object') {
347
+ return row;
348
+ }
349
+ const fullRes = stripParentKeyFromJsonString(readRowField(row, 'FullRecordJSON'));
350
+ const changesRes = stripParentKeyFromJsonString(readRowField(row, 'ChangesJSON'));
351
+ const nullBoth = fullRes.Failed || changesRes.Failed;
352
+ const nextFull = nullBoth ? null : fullRes.Value;
353
+ const nextChanges = nullBoth ? null : changesRes.Value;
354
+ const clearDesc = nullBoth || changesRes.HadParentKey;
355
+ if (row instanceof BaseEntity) {
356
+ const fullField = row.GetFieldByName('FullRecordJSON');
357
+ if (fullField && fullField.Value !== nextFull) {
358
+ fullField.Value = nextFull;
359
+ fullField.ResetOldValue();
360
+ }
361
+ const changesField = row.GetFieldByName('ChangesJSON');
362
+ if (changesField && changesField.Value !== nextChanges) {
363
+ changesField.Value = nextChanges;
364
+ changesField.ResetOldValue();
365
+ }
366
+ if (clearDesc) {
367
+ const descField = row.GetFieldByName('ChangesDescription');
368
+ if (descField && descField.Value != null) {
369
+ descField.Value = null;
370
+ descField.ResetOldValue();
371
+ }
372
+ }
373
+ return row;
374
+ }
375
+ const copy = { ...row };
376
+ for (const key of Object.keys(copy)) {
377
+ const lower = key.trim().toLowerCase();
378
+ if (lower === 'fullrecordjson') {
379
+ copy[key] = nextFull;
380
+ }
381
+ else if (lower === 'changesjson') {
382
+ copy[key] = nextChanges;
383
+ }
384
+ else if (clearDesc && lower === 'changesdescription') {
385
+ copy[key] = null;
386
+ }
387
+ }
388
+ return copy;
389
+ }
390
+ /**
391
+ * Evaluates which rows in `rows` (`MJ: Record Changes` rows) belong to a graph-scoped entity
392
+ * and fail either the caller's per-graph `Read` check (Finding 298) OR — for `MJ: Graph Concepts`
393
+ * rows — core `ResolveVisibility` (Finding 375: drop when `Hidden`, strip `FullRecordJSON` /
394
+ * `ChangesJSON` / `ChangesDescription` when `Redacted`).
395
+ */
396
+ async function evaluateGraphRecordChangeRows(rows, index, user, provider) {
397
+ const graphRows = [];
398
+ for (let i = 0; i < rows.length; i++) {
399
+ const row = rows[i];
400
+ const entityId = String(readRowField(row, 'EntityID') ?? '').trim();
401
+ if (!entityId) {
402
+ continue;
403
+ }
404
+ const entity = index.ByEntityId.Get(entityId);
405
+ if (!entity) {
406
+ continue;
407
+ }
408
+ const rawRecordId = readRowField(row, 'RecordID');
409
+ const recordId = ExtractSingleRecordIdFromChange(entity, typeof rawRecordId === 'string' ? rawRecordId : null);
410
+ let graphIds = [];
411
+ if (index.GraphsEntityID && UUIDsEqual(entity.ID, index.GraphsEntityID)) {
412
+ if (recordId) {
413
+ graphIds = [recordId];
414
+ }
415
+ }
416
+ else {
417
+ const fullJson = readRowField(row, 'FullRecordJSON');
418
+ const changesJson = readRowField(row, 'ChangesJSON');
419
+ graphIds = ExtractGraphIdsFromRecordChangePayloads(typeof fullJson === 'string' ? fullJson : null, typeof changesJson === 'string' ? changesJson : null);
420
+ }
421
+ graphRows.push({ RowIndex: i, Entity: entity, RecordId: recordId, GraphIds: graphIds });
422
+ }
423
+ if (graphRows.length === 0) {
424
+ return { Denied: new Set(), Redacted: new Set(), StripParentFromPayload: new Set() };
425
+ }
426
+ // Batch live lookups for any non-Graph rows whose JSON payloads omitted GraphID
427
+ const missingByEntity = new UUIDMap();
428
+ for (const item of graphRows) {
429
+ if (item.GraphIds.length === 0 &&
430
+ item.RecordId &&
431
+ (!index.GraphsEntityID || !UUIDsEqual(item.Entity.ID, index.GraphsEntityID))) {
432
+ const bucket = missingByEntity.Get(item.Entity.ID) ?? { Entity: item.Entity, RecordIds: [] };
433
+ bucket.RecordIds.push(item.RecordId);
434
+ missingByEntity.Set(item.Entity.ID, bucket);
435
+ }
436
+ }
437
+ const liveGraphByEntityAndRecord = new UUIDMap();
438
+ for (const [entityId, bucket] of missingByEntity) {
439
+ liveGraphByEntityAndRecord.Set(entityId, await lookupLiveGraphIdsByRecordIds(bucket.Entity, bucket.RecordIds, provider, user));
440
+ }
441
+ // Check graph read permission via GraphEngine.CanUserReadGraph for non-Owner admin roles
442
+ // (respecting explicit user-direct 'None' denies per A26 / Finding 362), or batch via
443
+ // GraphPermissionProvider.GetUserResources for standard users.
444
+ const isAdminRole = GraphEngine.Instance.IsGraphAdminUser(user);
445
+ const readableGraphIds = isAdminRole ? null : await loadReadableGraphIdsForUser(user, provider);
446
+ const adminReadCache = new UUIDMap();
447
+ const canReadGraph = async (graphId) => {
448
+ if (readableGraphIds !== null) {
449
+ return readableGraphIds.Has(graphId);
450
+ }
451
+ const cached = adminReadCache.Get(graphId);
452
+ if (cached !== undefined) {
453
+ return cached;
454
+ }
455
+ const allowed = await GraphEngine.Instance.CanUserReadGraph(user, graphId, provider);
456
+ adminReadCache.Set(graphId, allowed);
457
+ return allowed;
458
+ };
459
+ const denied = new Set();
460
+ const redacted = new Set();
461
+ const survivingConceptRows = [];
462
+ for (const item of graphRows) {
463
+ let effectiveGraphIds = item.GraphIds;
464
+ if (effectiveGraphIds.length === 0 && item.RecordId) {
465
+ const liveGraphId = liveGraphByEntityAndRecord.Get(item.Entity.ID)?.Get(item.RecordId);
466
+ if (liveGraphId) {
467
+ effectiveGraphIds = [liveGraphId];
468
+ }
469
+ }
470
+ // Fail closed: if GraphID cannot be established OR any referenced graph is unreadable, drop row.
471
+ if (effectiveGraphIds.length === 0) {
472
+ denied.add(item.RowIndex);
473
+ continue;
474
+ }
475
+ let allReadable = true;
476
+ for (const gid of effectiveGraphIds) {
477
+ if (!(await canReadGraph(gid))) {
478
+ allReadable = false;
479
+ break;
480
+ }
481
+ }
482
+ if (!allReadable) {
483
+ denied.add(item.RowIndex);
484
+ continue;
485
+ }
486
+ if (index.ConceptsEntityID && UUIDsEqual(item.Entity.ID, index.ConceptsEntityID)) {
487
+ if (!item.RecordId) {
488
+ denied.add(item.RowIndex);
489
+ }
490
+ else {
491
+ survivingConceptRows.push({ RowIndex: item.RowIndex, RecordId: item.RecordId });
492
+ }
493
+ }
494
+ }
495
+ // Finding 375 & 394: resolve provenance/source visibility for surviving MJ: Graph Concepts change rows
496
+ // AND any ParentID referenced in Allowed concept change payloads in ONE batched ResolveVisibility call.
497
+ // Hidden concepts drop their Record Changes rows; Redacted concepts redact via allow-list; Allowed
498
+ // concepts whose parent is not Allowed strip the virtual `Parent` key from FullRecordJSON/ChangesJSON.
499
+ const stripParentFromPayload = new Set();
500
+ if (survivingConceptRows.length > 0 && index.ConceptsEntityID) {
501
+ LoadCoreVisibilityRules();
502
+ const refs = [];
503
+ const seenConceptIds = new Set();
504
+ const addRef = (id) => {
505
+ const norm = id.toLowerCase();
506
+ if (!seenConceptIds.has(norm)) {
507
+ seenConceptIds.add(norm);
508
+ refs.push({
509
+ EntityName: 'MJ: Graph Concepts',
510
+ EntityID: index.ConceptsEntityID,
511
+ RecordID: id,
512
+ });
513
+ }
514
+ };
515
+ const parentInfoByRowIndex = new Map();
516
+ for (const entry of survivingConceptRows) {
517
+ addRef(entry.RecordId);
518
+ const rawRow = rows[entry.RowIndex];
519
+ const fullJson = readRowField(rawRow, 'FullRecordJSON');
520
+ const changesJson = readRowField(rawRow, 'ChangesJSON');
521
+ const pInfo = extractParentIdsFromConceptChangePayloads(typeof fullJson === 'string' ? fullJson : null, typeof changesJson === 'string' ? changesJson : null);
522
+ parentInfoByRowIndex.set(entry.RowIndex, pInfo);
523
+ for (const pid of pInfo.ParentIds) {
524
+ addRef(pid);
525
+ }
526
+ }
527
+ const decisions = await ResolveVisibility(refs, user, {
528
+ Provider: provider,
529
+ Caller: 'GraphRecordChangesReadSecurityHook',
530
+ });
531
+ for (const entry of survivingConceptRows) {
532
+ const key = FormatVisibilityNodeKey({
533
+ EntityName: 'MJ: Graph Concepts',
534
+ EntityID: index.ConceptsEntityID,
535
+ RecordID: entry.RecordId,
536
+ }, provider);
537
+ const decision = decisions.get(key);
538
+ if (!decision || decision.Outcome === 'Hidden') {
539
+ denied.add(entry.RowIndex);
540
+ }
541
+ else if (decision.Outcome === 'Redacted') {
542
+ redacted.add(entry.RowIndex);
543
+ }
544
+ else {
545
+ const pInfo = parentInfoByRowIndex.get(entry.RowIndex);
546
+ if (pInfo) {
547
+ if (pInfo.ParseError) {
548
+ stripParentFromPayload.add(entry.RowIndex);
549
+ }
550
+ else if (pInfo.ParentIds.length > 0) {
551
+ const anyParentNotAllowed = pInfo.ParentIds.some((pid) => {
552
+ const pKey = FormatVisibilityNodeKey({ EntityName: 'MJ: Graph Concepts', EntityID: index.ConceptsEntityID, RecordID: pid }, provider);
553
+ return decisions.get(pKey)?.Outcome !== 'Allowed';
554
+ });
555
+ if (anyParentNotAllowed) {
556
+ stripParentFromPayload.add(entry.RowIndex);
557
+ }
558
+ }
559
+ }
560
+ }
561
+ }
562
+ }
563
+ return { Denied: denied, Redacted: redacted, StripParentFromPayload: stripParentFromPayload };
564
+ }
565
+ /**
566
+ * Server-side `PreRunView` hook for `MJ: Record Changes` (Finding 298).
567
+ * Ensures `EntityID`, `RecordID`, `FullRecordJSON`, and `ChangesJSON` are projected when a
568
+ * non-admin caller specifies a narrow `Fields` list, so `PostRunView` can filter graph-scoped
569
+ * change history without mutating the caller's requested shape afterward.
570
+ */
571
+ export const GraphRecordChangesPreRunViewHook = async (params, contextUser, hookProvider) => {
572
+ if (!params || !contextUser || getInternalParamsSet().has(params) || isExemptUser(contextUser)) {
573
+ return params;
574
+ }
575
+ const provider = resolveProvider(hookProvider, contextUser);
576
+ if (!provider || provider.ProviderType !== 'Database') {
577
+ return params;
578
+ }
579
+ const entityName = await ResolveTargetEntityNameAsync(params, provider, contextUser);
580
+ if (!entityName || !EntityNamesMatch(entityName, RECORD_CHANGES_ENTITY_NAME, provider)) {
581
+ return params;
582
+ }
583
+ if (!Array.isArray(params.Fields) || params.Fields.length === 0 || params.ResultType === 'count_only') {
584
+ return params;
585
+ }
586
+ // Finding 367: skip projecting large JSON columns when ExtraFilter explicitly targets a single
587
+ // non-graph EntityID (zero overhead for ordinary entity Record Changes queries).
588
+ const filteredEntityId = ExtractSingleUuidFieldFromFilter(params.ExtraFilter, 'EntityID');
589
+ if (filteredEntityId) {
590
+ const index = buildGraphScopedEntityIndex(provider);
591
+ if (!index.ByEntityId.Has(filteredEntityId)) {
592
+ return params;
593
+ }
594
+ }
595
+ const existingLower = new Set(params.Fields.map((f) => f.trim().toLowerCase()));
596
+ const missing = REQUIRED_SECURITY_FIELDS.filter((f) => !existingLower.has(f.toLowerCase()));
597
+ if (missing.length === 0) {
598
+ return params;
599
+ }
600
+ getOriginalFieldsMap().set(params, [...params.Fields]);
601
+ params.Fields = [...params.Fields, ...missing];
602
+ return params;
603
+ };
604
+ /**
605
+ * Server-side `PostRunView` hook for `MJ: Record Changes` (Finding 298).
606
+ * Filters out change-history rows for `MJ: Graphs`, `MJ: Graph Concepts`, `MJ: Graph Edges`, and
607
+ * `MJ: Graph Links` whenever the caller lacks `Read` permission on the owning graph (including
608
+ * `count_only` queries). Never mutates `results.Results` in place.
609
+ */
610
+ export const GraphRecordChangesPostRunViewHook = async (params, results, contextUser, hookProvider) => {
611
+ const originalFieldsMap = getOriginalFieldsMap();
612
+ const originalFields = originalFieldsMap.get(params);
613
+ originalFieldsMap.delete(params);
614
+ if (!results?.Success || getInternalParamsSet().has(params)) {
615
+ return results;
616
+ }
617
+ const provider = resolveProvider(hookProvider, contextUser);
618
+ if (!provider || provider.ProviderType !== 'Database') {
619
+ return results;
620
+ }
621
+ const entityName = await ResolveTargetEntityNameAsync(params, provider, contextUser);
622
+ if (!entityName || !EntityNamesMatch(entityName, RECORD_CHANGES_ENTITY_NAME, provider)) {
623
+ return results;
624
+ }
625
+ if (!contextUser) {
626
+ return { ...results, Results: [], RowCount: 0, TotalRowCount: 0 };
627
+ }
628
+ if (isExemptUser(contextUser)) {
629
+ return stripSyntheticFieldsIfNeeded(results, originalFields);
630
+ }
631
+ const index = buildGraphScopedEntityIndex(provider);
632
+ if (index.ByEntityId.Size === 0) {
633
+ return stripSyntheticFieldsIfNeeded(results, originalFields);
634
+ }
635
+ try {
636
+ if (params.ResultType === 'count_only') {
637
+ return await adjustCountOnlyResult(params, results, index, contextUser, provider);
638
+ }
639
+ const rows = Array.isArray(results.Results) ? results.Results : [];
640
+ if (rows.length === 0) {
641
+ return results;
642
+ }
643
+ const { Denied: denied, Redacted: redacted, StripParentFromPayload: stripParent, } = await evaluateGraphRecordChangeRows(rows, index, contextUser, provider);
644
+ if (denied.size === 0 && redacted.size === 0 && stripParent.size === 0) {
645
+ return stripSyntheticFieldsIfNeeded(results, originalFields);
646
+ }
647
+ const filteredRows = [];
648
+ for (let idx = 0; idx < rows.length; idx++) {
649
+ if (denied.has(idx)) {
650
+ continue;
651
+ }
652
+ let row = rows[idx];
653
+ if (redacted.has(idx)) {
654
+ row = redactRecordChangeRowByAllowList(row);
655
+ }
656
+ else if (stripParent.has(idx)) {
657
+ row = stripParentNameFromRecordChangePayload(row);
658
+ }
659
+ filteredRows.push(originalFields ? stripRowSyntheticFields(row, originalFields) : row);
660
+ }
661
+ const removedCount = rows.length - filteredRows.length;
662
+ return {
663
+ ...results,
664
+ Results: filteredRows,
665
+ RowCount: filteredRows.length,
666
+ TotalRowCount: Math.max(filteredRows.length, (results.TotalRowCount ?? results.RowCount ?? rows.length) - removedCount),
667
+ };
668
+ }
669
+ catch (err) {
670
+ const msg = err instanceof Error ? err.message : String(err);
671
+ LogError(`GraphRecordChangesPostRunViewHook failed; failing closed: ${msg}`);
672
+ return { ...results, Results: [], RowCount: 0, TotalRowCount: 0 };
673
+ }
674
+ };
675
+ function stripRowSyntheticFields(row, originalFields) {
676
+ return row != null && typeof row === 'object' ? StripSyntheticFieldsFromRow(row, originalFields) : row;
677
+ }
678
+ function stripSyntheticFieldsIfNeeded(results, originalFields) {
679
+ if (!originalFields || !Array.isArray(results.Results)) {
680
+ return results;
681
+ }
682
+ return {
683
+ ...results,
684
+ Results: results.Results.map((row) => stripRowSyntheticFields(row, originalFields)),
685
+ };
686
+ }
687
+ async function adjustCountOnlyResult(params, results, index, user, provider) {
688
+ const rawCount = results.TotalRowCount ?? 0;
689
+ if (rawCount <= 0) {
690
+ return results;
691
+ }
692
+ const entityIdList = Array.from(index.ByEntityId.Keys())
693
+ .map((id) => `'${EscapeSQLString(id)}'`)
694
+ .join(',');
695
+ const graphEntityFilter = `[EntityID] IN (${entityIdList})`;
696
+ const callerFilter = typeof params.ExtraFilter === 'string' && params.ExtraFilter.trim().length > 0
697
+ ? `(${params.ExtraFilter}) AND (${graphEntityFilter})`
698
+ : graphEntityFilter;
699
+ const systemUser = (await WellKnownUserSource.Instance.GetSystemUser(provider)) ?? user;
700
+ const probeParams = {
701
+ EntityName: RECORD_CHANGES_ENTITY_NAME,
702
+ ExtraFilter: callerFilter,
703
+ Fields: [...REQUIRED_SECURITY_FIELDS],
704
+ ResultType: 'simple',
705
+ IgnoreMaxRows: true,
706
+ };
707
+ getInternalParamsSet().add(probeParams);
708
+ const probeRes = await RunView.FromMetadataProvider(provider).RunView(probeParams, systemUser);
709
+ if (!probeRes.Success) {
710
+ LogError(`GraphRecordChangesPostRunViewHook count_only probe failed; failing closed: ${probeRes.ErrorMessage}`);
711
+ return { ...results, Results: [], RowCount: 0, TotalRowCount: 0 };
712
+ }
713
+ const graphRows = Array.isArray(probeRes.Results) ? probeRes.Results : [];
714
+ if (graphRows.length === 0) {
715
+ return results;
716
+ }
717
+ const { Denied: denied } = await evaluateGraphRecordChangeRows(graphRows, index, user, provider);
718
+ if (denied.size === 0) {
719
+ return results;
720
+ }
721
+ return {
722
+ ...results,
723
+ TotalRowCount: Math.max(0, rawCount - denied.size),
724
+ };
725
+ }
726
+ /**
727
+ * Ensures {@link GraphRecordChangesPreRunViewHook} and {@link GraphRecordChangesPostRunViewHook}
728
+ * are registered and `MJ: Record Changes` is protected from differential-cache / raw-view bypasses.
729
+ * Idempotent.
730
+ */
731
+ export function EnsureGraphRecordChangesReadHookRegistered() {
732
+ const existingPre = GetDataHooks('PreRunView');
733
+ if (!existingPre.includes(GraphRecordChangesPreRunViewHook)) {
734
+ RegisterDataHook('PreRunView', GraphRecordChangesPreRunViewHook);
735
+ }
736
+ const existingPost = GetDataHooks('PostRunView');
737
+ if (!existingPost.includes(GraphRecordChangesPostRunViewHook)) {
738
+ RegisterDataHook('PostRunView', GraphRecordChangesPostRunViewHook);
739
+ }
740
+ RegisterPostRunViewProtectedEntity(RECORD_CHANGES_ENTITY_NAME);
741
+ }
742
+ // Auto-register when @memberjunction/core-entities-server is loaded
743
+ EnsureGraphRecordChangesReadHookRegistered();
744
+ //# sourceMappingURL=GraphRecordChangesReadSecurityHook.js.map