@memberjunction/core-entities 6.3.0-edge.0 → 6.3.0-edge.2
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.
- package/dist/.tsbuildinfo +1 -1
- package/dist/custom/AnchoredConversationSecurity.d.ts +10 -1
- package/dist/custom/AnchoredConversationSecurity.d.ts.map +1 -1
- package/dist/custom/AnchoredConversationSecurity.js +15 -0
- package/dist/custom/AnchoredConversationSecurity.js.map +1 -1
- package/dist/custom/ArtifactLockValidation.d.ts +28 -0
- package/dist/custom/ArtifactLockValidation.d.ts.map +1 -0
- package/dist/custom/ArtifactLockValidation.js +867 -0
- package/dist/custom/ArtifactLockValidation.js.map +1 -0
- package/dist/custom/ArtifactPermissionDelegate.d.ts +288 -0
- package/dist/custom/ArtifactPermissionDelegate.d.ts.map +1 -0
- package/dist/custom/ArtifactPermissionDelegate.js +1779 -0
- package/dist/custom/ArtifactPermissionDelegate.js.map +1 -0
- package/dist/custom/ArtifactPreviewSnapshot.d.ts +199 -0
- package/dist/custom/ArtifactPreviewSnapshot.d.ts.map +1 -0
- package/dist/custom/ArtifactPreviewSnapshot.js +772 -0
- package/dist/custom/ArtifactPreviewSnapshot.js.map +1 -0
- package/dist/custom/ArtifactSynthesisEngine.d.ts +151 -0
- package/dist/custom/ArtifactSynthesisEngine.d.ts.map +1 -0
- package/dist/custom/ArtifactSynthesisEngine.js +1124 -0
- package/dist/custom/ArtifactSynthesisEngine.js.map +1 -0
- package/dist/custom/ConversationWriteAccess.d.ts +36 -0
- package/dist/custom/ConversationWriteAccess.d.ts.map +1 -1
- package/dist/custom/ConversationWriteAccess.js +109 -1
- package/dist/custom/ConversationWriteAccess.js.map +1 -1
- package/dist/custom/DocumentLiveBlockEngine.d.ts +612 -0
- package/dist/custom/DocumentLiveBlockEngine.d.ts.map +1 -0
- package/dist/custom/DocumentLiveBlockEngine.js +2352 -0
- package/dist/custom/DocumentLiveBlockEngine.js.map +1 -0
- package/dist/custom/MJQueryEntityExtended.d.ts.map +1 -1
- package/dist/custom/MJQueryEntityExtended.js +27 -11
- package/dist/custom/MJQueryEntityExtended.js.map +1 -1
- package/dist/custom/PermissionProviders/ArtifactPermissionProvider.d.ts.map +1 -1
- package/dist/custom/PermissionProviders/ArtifactPermissionProvider.js +31 -7
- package/dist/custom/PermissionProviders/ArtifactPermissionProvider.js.map +1 -1
- package/dist/custom/PermissionProviders/CollectionPermissionProvider.d.ts +3 -4
- package/dist/custom/PermissionProviders/CollectionPermissionProvider.d.ts.map +1 -1
- package/dist/custom/PermissionProviders/CollectionPermissionProvider.js +334 -47
- package/dist/custom/PermissionProviders/CollectionPermissionProvider.js.map +1 -1
- package/dist/custom/Permissions/BaseShareEntityExtended.d.ts +28 -3
- package/dist/custom/Permissions/BaseShareEntityExtended.d.ts.map +1 -1
- package/dist/custom/Permissions/BaseShareEntityExtended.js +150 -13
- package/dist/custom/Permissions/BaseShareEntityExtended.js.map +1 -1
- package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.d.ts +8 -6
- package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.d.ts.map +1 -1
- package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js +107 -43
- package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js.map +1 -1
- package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts +13 -5
- package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts.map +1 -1
- package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js +284 -49
- package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js.map +1 -1
- package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.d.ts +3 -1
- package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.d.ts.map +1 -1
- package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.js +83 -19
- package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.js.map +1 -1
- package/dist/custom/Permissions/shareNotification.d.ts +14 -1
- package/dist/custom/Permissions/shareNotification.d.ts.map +1 -1
- package/dist/custom/Permissions/shareNotification.js +62 -8
- package/dist/custom/Permissions/shareNotification.js.map +1 -1
- package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.d.ts.map +1 -1
- package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.js +120 -38
- package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.js.map +1 -1
- package/dist/custom/SlideDeckEngine.d.ts +469 -0
- package/dist/custom/SlideDeckEngine.d.ts.map +1 -0
- package/dist/custom/SlideDeckEngine.js +2168 -0
- package/dist/custom/SlideDeckEngine.js.map +1 -0
- package/dist/custom/SlideDeckPptxEngine.d.ts +25 -0
- package/dist/custom/SlideDeckPptxEngine.d.ts.map +1 -0
- package/dist/custom/SlideDeckPptxEngine.js +1311 -0
- package/dist/custom/SlideDeckPptxEngine.js.map +1 -0
- package/dist/custom/SpreadsheetEngine.d.ts +1377 -0
- package/dist/custom/SpreadsheetEngine.d.ts.map +1 -0
- package/dist/custom/SpreadsheetEngine.js +17652 -0
- package/dist/custom/SpreadsheetEngine.js.map +1 -0
- package/dist/custom/approvals.d.ts +31 -1
- package/dist/custom/approvals.d.ts.map +1 -1
- package/dist/custom/approvals.js +42 -2
- package/dist/custom/approvals.js.map +1 -1
- package/dist/custom/operations/ArtifactComplianceAuditOperation.d.ts +7 -0
- package/dist/custom/operations/ArtifactComplianceAuditOperation.d.ts.map +1 -0
- package/dist/custom/operations/ArtifactComplianceAuditOperation.js +7 -0
- package/dist/custom/operations/ArtifactComplianceAuditOperation.js.map +1 -0
- package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.d.ts +7 -0
- package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.d.ts.map +1 -0
- package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.js +7 -0
- package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.js.map +1 -0
- package/dist/custom/operations/ArtifactGuestShareOperations.d.ts +60 -0
- package/dist/custom/operations/ArtifactGuestShareOperations.d.ts.map +1 -0
- package/dist/custom/operations/ArtifactGuestShareOperations.js +6 -0
- package/dist/custom/operations/ArtifactGuestShareOperations.js.map +1 -0
- package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.d.ts +7 -0
- package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.d.ts.map +1 -0
- package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.js +7 -0
- package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.js.map +1 -0
- package/dist/custom/typedQuery.d.ts +162 -0
- package/dist/custom/typedQuery.d.ts.map +1 -0
- package/dist/custom/typedQuery.js +296 -0
- package/dist/custom/typedQuery.js.map +1 -0
- package/dist/engines/CanonGraphEngine.d.ts +115 -2
- package/dist/engines/CanonGraphEngine.d.ts.map +1 -1
- package/dist/engines/CanonGraphEngine.js +259 -34
- package/dist/engines/CanonGraphEngine.js.map +1 -1
- package/dist/engines/EncryptionEngineBase.js +2 -2
- package/dist/engines/EncryptionEngineBase.js.map +1 -1
- package/dist/engines/QueryEngine.js +2 -2
- package/dist/engines/QueryEngine.js.map +1 -1
- package/dist/engines/SearchEngineBase.d.ts +17 -3
- package/dist/engines/SearchEngineBase.d.ts.map +1 -1
- package/dist/engines/SearchEngineBase.js +100 -28
- package/dist/engines/SearchEngineBase.js.map +1 -1
- package/dist/engines/UserInfoEngine.d.ts +8 -0
- package/dist/engines/UserInfoEngine.d.ts.map +1 -1
- package/dist/engines/UserInfoEngine.js +50 -3
- package/dist/engines/UserInfoEngine.js.map +1 -1
- package/dist/engines/conversations.d.ts +74 -6
- package/dist/engines/conversations.d.ts.map +1 -1
- package/dist/engines/conversations.js +205 -24
- package/dist/engines/conversations.js.map +1 -1
- package/dist/generated/entities/__mj.d.ts +25652 -43408
- package/dist/generated/entities/__mj.d.ts.map +1 -1
- package/dist/generated/entities/__mj.js +50800 -83602
- package/dist/generated/entities/__mj.js.map +1 -1
- package/dist/generated/queries/__mj.d.ts +12 -12
- package/dist/generated/queries/__mj.d.ts.map +1 -1
- package/dist/generated/queries/__mj.js +1 -1
- package/dist/generated/queries/__mj.js.map +1 -1
- package/dist/generated/remote_operations.d.ts +970 -65
- package/dist/generated/remote_operations.d.ts.map +1 -1
- package/dist/generated/remote_operations.js +343 -8
- package/dist/generated/remote_operations.js.map +1 -1
- package/dist/generated/schemas/__mj.d.ts +27415 -0
- package/dist/generated/schemas/__mj.d.ts.map +1 -0
- package/dist/generated/schemas/__mj.js +45127 -0
- package/dist/generated/schemas/__mj.js.map +1 -0
- package/dist/generated/schemas.d.ts +2 -0
- package/dist/generated/schemas.d.ts.map +1 -0
- package/dist/generated/schemas.js +2 -0
- package/dist/generated/schemas.js.map +1 -0
- package/dist/graph/BaseGraphEdgeProvider.d.ts +33 -1
- package/dist/graph/BaseGraphEdgeProvider.d.ts.map +1 -1
- package/dist/graph/BaseGraphEdgeProvider.js +18 -3
- package/dist/graph/BaseGraphEdgeProvider.js.map +1 -1
- package/dist/graph/CanonDocumentRenderer.d.ts +43 -0
- package/dist/graph/CanonDocumentRenderer.d.ts.map +1 -0
- package/dist/graph/CanonDocumentRenderer.js +627 -0
- package/dist/graph/CanonDocumentRenderer.js.map +1 -0
- package/dist/graph/DomainClustering.d.ts +88 -0
- package/dist/graph/DomainClustering.d.ts.map +1 -0
- package/dist/graph/DomainClustering.js +327 -0
- package/dist/graph/DomainClustering.js.map +1 -0
- package/dist/graph/DomainProposalWriter.d.ts +25 -0
- package/dist/graph/DomainProposalWriter.d.ts.map +1 -0
- package/dist/graph/DomainProposalWriter.js +107 -0
- package/dist/graph/DomainProposalWriter.js.map +1 -0
- package/dist/graph/GraphAccessPolicy.d.ts +111 -0
- package/dist/graph/GraphAccessPolicy.d.ts.map +1 -0
- package/dist/graph/GraphAccessPolicy.js +123 -0
- package/dist/graph/GraphAccessPolicy.js.map +1 -0
- package/dist/graph/GraphEngine.d.ts +115 -7
- package/dist/graph/GraphEngine.d.ts.map +1 -1
- package/dist/graph/GraphEngine.js +432 -36
- package/dist/graph/GraphEngine.js.map +1 -1
- package/dist/graph/RecordRelations.d.ts +52 -0
- package/dist/graph/RecordRelations.d.ts.map +1 -0
- package/dist/graph/RecordRelations.js +90 -0
- package/dist/graph/RecordRelations.js.map +1 -0
- package/dist/graph/index.d.ts +9 -1
- package/dist/graph/index.d.ts.map +1 -1
- package/dist/graph/index.js +13 -1
- package/dist/graph/index.js.map +1 -1
- package/dist/graph/policies/ProvenanceAccessPolicies.d.ts +56 -0
- package/dist/graph/policies/ProvenanceAccessPolicies.d.ts.map +1 -0
- package/dist/graph/policies/ProvenanceAccessPolicies.js +228 -0
- package/dist/graph/policies/ProvenanceAccessPolicies.js.map +1 -0
- package/dist/graph/providers/QueryEdgeProvider.d.ts.map +1 -1
- package/dist/graph/providers/QueryEdgeProvider.js +2 -2
- package/dist/graph/providers/QueryEdgeProvider.js.map +1 -1
- package/dist/graph/providers/RecordLinkEdgeProvider.d.ts.map +1 -1
- package/dist/graph/providers/RecordLinkEdgeProvider.js +2 -2
- package/dist/graph/providers/RecordLinkEdgeProvider.js.map +1 -1
- package/dist/graph/providers/SharedConceptEdgeProvider.d.ts +54 -0
- package/dist/graph/providers/SharedConceptEdgeProvider.d.ts.map +1 -0
- package/dist/graph/providers/SharedConceptEdgeProvider.js +282 -0
- package/dist/graph/providers/SharedConceptEdgeProvider.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +18 -0
- package/dist/index.js.map +1 -1
- package/dist/schemas.d.ts +6 -0
- package/dist/schemas.d.ts.map +1 -0
- package/dist/schemas.js +6 -0
- package/dist/schemas.js.map +1 -0
- package/package.json +17 -6
|
@@ -0,0 +1,1779 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
import { LogError, Metadata, RunView, WellKnownUserSource } from '@memberjunction/core';
|
|
8
|
+
import { BaseSingleton, EscapeSQLString, GetGlobalObjectStore, IndexByUUID, IsValidUUID, MJGlobal, NormalizeUUID, RegisterClass, UUIDsEqual } from '@memberjunction/global';
|
|
9
|
+
/**
|
|
10
|
+
* Base class for `@RegisterClass(BaseArtifactPermissionDelegate, '<EntityName>')` registrations.
|
|
11
|
+
* Subclasses override {@link CanRead}, {@link CanEdit}, {@link CanDelete}, and/or {@link CanShare}.
|
|
12
|
+
*/
|
|
13
|
+
export class BaseArtifactPermissionDelegate {
|
|
14
|
+
async CanDelete(_context, _user) {
|
|
15
|
+
return 'Defer';
|
|
16
|
+
}
|
|
17
|
+
async CanShare(_context, _user) {
|
|
18
|
+
return 'Defer';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const MAX_DELEGATE_DEPTH = 8;
|
|
22
|
+
const MAX_COLLECTION_ANCESTRY_DEPTH = 16;
|
|
23
|
+
const IN_CLAUSE_CHUNK_SIZE = 200;
|
|
24
|
+
function chunkArray(items, size) {
|
|
25
|
+
if (items.length <= size) {
|
|
26
|
+
return items.length === 0 ? [] : [items];
|
|
27
|
+
}
|
|
28
|
+
const chunks = [];
|
|
29
|
+
for (let i = 0; i < items.length; i += size) {
|
|
30
|
+
chunks.push(items.slice(i, i + size));
|
|
31
|
+
}
|
|
32
|
+
return chunks;
|
|
33
|
+
}
|
|
34
|
+
function buildQuotedInList(ids) {
|
|
35
|
+
return ids.map((id) => `'${EscapeSQLString(id)}'`).join(',');
|
|
36
|
+
}
|
|
37
|
+
function buildEqOrInFilter(column, ids) {
|
|
38
|
+
return ids.length === 1
|
|
39
|
+
? `${column}='${EscapeSQLString(ids[0])}'`
|
|
40
|
+
: `${column} IN (${buildQuotedInList(ids)})`;
|
|
41
|
+
}
|
|
42
|
+
function canUseRunViews(provider, rv) {
|
|
43
|
+
if (typeof rv.RunViews !== 'function') {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
const providerHasRunViews = typeof provider.RunViews === 'function';
|
|
47
|
+
const rvHasOwnRunViews = Object.prototype.hasOwnProperty.call(rv, 'RunViews');
|
|
48
|
+
return providerHasRunViews || rvHasOwnRunViews;
|
|
49
|
+
}
|
|
50
|
+
const INTERNAL_PERMISSION_QUERY_PARAMS_STORE_KEY = '___MJ_INTERNAL_ARTIFACT_PERMISSION_QUERY_PARAMS___';
|
|
51
|
+
const INTERNAL_PERMISSION_QUERY_SYMBOL_STORE_KEY = '___MJ_INTERNAL_ARTIFACT_PERMISSION_QUERY_SYMBOL___';
|
|
52
|
+
const FALLBACK_INTERNAL_PERMISSION_QUERY_WEAK_SET = new WeakSet();
|
|
53
|
+
const FALLBACK_INTERNAL_PERMISSION_QUERY_SYMBOL = Symbol('MJInternalArtifactPermissionQuery');
|
|
54
|
+
function getInternalPermissionQueryWeakSet() {
|
|
55
|
+
const store = GetGlobalObjectStore();
|
|
56
|
+
if (store) {
|
|
57
|
+
const existing = store[INTERNAL_PERMISSION_QUERY_PARAMS_STORE_KEY];
|
|
58
|
+
if (existing instanceof WeakSet) {
|
|
59
|
+
return existing;
|
|
60
|
+
}
|
|
61
|
+
const created = new WeakSet();
|
|
62
|
+
store[INTERNAL_PERMISSION_QUERY_PARAMS_STORE_KEY] = created;
|
|
63
|
+
return created;
|
|
64
|
+
}
|
|
65
|
+
return FALLBACK_INTERNAL_PERMISSION_QUERY_WEAK_SET;
|
|
66
|
+
}
|
|
67
|
+
function getInternalPermissionQueryMarkerSymbol() {
|
|
68
|
+
const store = GetGlobalObjectStore();
|
|
69
|
+
if (store) {
|
|
70
|
+
const existing = store[INTERNAL_PERMISSION_QUERY_SYMBOL_STORE_KEY];
|
|
71
|
+
if (typeof existing === 'symbol') {
|
|
72
|
+
return existing;
|
|
73
|
+
}
|
|
74
|
+
const created = Symbol('MJInternalArtifactPermissionQuery');
|
|
75
|
+
store[INTERNAL_PERMISSION_QUERY_SYMBOL_STORE_KEY] = created;
|
|
76
|
+
return created;
|
|
77
|
+
}
|
|
78
|
+
return FALLBACK_INTERNAL_PERMISSION_QUERY_SYMBOL;
|
|
79
|
+
}
|
|
80
|
+
function normalizeDecision(decision) {
|
|
81
|
+
if (decision === true || decision === 'Allow') {
|
|
82
|
+
return 'Allow';
|
|
83
|
+
}
|
|
84
|
+
if (decision === false || decision === 'Deny') {
|
|
85
|
+
return 'Deny';
|
|
86
|
+
}
|
|
87
|
+
return 'Defer';
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Built-in permission delegate for child artifacts whose `DelegateEntityID` points to
|
|
91
|
+
* `'MJ: Artifacts'` (for example, an inline OLE Whiteboard or embedded Artifact block
|
|
92
|
+
* created inside a host Document, Slide Deck, or Spreadsheet).
|
|
93
|
+
*
|
|
94
|
+
* Recursively resolves `CanRead`, `CanEdit`, `CanDelete`, and `CanShare` against the parent
|
|
95
|
+
* host artifact while guarding against cyclic delegation chains.
|
|
96
|
+
*/
|
|
97
|
+
let ParentArtifactPermissionDelegate = class ParentArtifactPermissionDelegate extends BaseArtifactPermissionDelegate {
|
|
98
|
+
async CanRead(context, user) {
|
|
99
|
+
const parentPerms = await ArtifactPermissionEngine.Instance.ResolvePermissions(context.Provider, context.DelegateRecordID, user, (context.Depth ?? 0) + 1, context.VisitedArtifactIDs, context.Memo);
|
|
100
|
+
return parentPerms.CanRead ? 'Allow' : 'Deny';
|
|
101
|
+
}
|
|
102
|
+
async CanEdit(context, user) {
|
|
103
|
+
const parentPerms = await ArtifactPermissionEngine.Instance.ResolvePermissions(context.Provider, context.DelegateRecordID, user, (context.Depth ?? 0) + 1, context.VisitedArtifactIDs, context.Memo);
|
|
104
|
+
return parentPerms.CanEdit ? 'Allow' : 'Deny';
|
|
105
|
+
}
|
|
106
|
+
async CanDelete(context, user) {
|
|
107
|
+
const parentPerms = await ArtifactPermissionEngine.Instance.ResolvePermissions(context.Provider, context.DelegateRecordID, user, (context.Depth ?? 0) + 1, context.VisitedArtifactIDs, context.Memo);
|
|
108
|
+
return parentPerms.CanDelete ? 'Allow' : 'Deny';
|
|
109
|
+
}
|
|
110
|
+
async CanShare(context, user) {
|
|
111
|
+
const parentPerms = await ArtifactPermissionEngine.Instance.ResolvePermissions(context.Provider, context.DelegateRecordID, user, (context.Depth ?? 0) + 1, context.VisitedArtifactIDs, context.Memo);
|
|
112
|
+
return parentPerms.CanShare ? 'Allow' : 'Deny';
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
ParentArtifactPermissionDelegate = __decorate([
|
|
116
|
+
RegisterClass(BaseArtifactPermissionDelegate, 'MJ: Artifacts')
|
|
117
|
+
], ParentArtifactPermissionDelegate);
|
|
118
|
+
export { ParentArtifactPermissionDelegate };
|
|
119
|
+
/**
|
|
120
|
+
* Central engine that resolves viewer-scoped permissions (`CanRead`, `CanEdit`, `CanDelete`, `CanShare`)
|
|
121
|
+
* for `MJ: Artifacts` across:
|
|
122
|
+
* 1. Direct ownership (`Artifact.UserID === user.ID`),
|
|
123
|
+
* 2. Delegated host-entity permissions (`DelegateEntityID` + `DelegateRecordID` via {@link IArtifactPermissionDelegate}),
|
|
124
|
+
* 3. Direct user grants in `MJ: Artifact Permissions`, and
|
|
125
|
+
* 4. Cascaded collection grants in `MJ: Collection Artifacts` + `MJ: Collection Permissions`.
|
|
126
|
+
*
|
|
127
|
+
* Also dispatches real-time permission change notifications so active Yjs WebSocket rooms
|
|
128
|
+
* immediately disconnect or downgrade sockets when access is revoked mid-session.
|
|
129
|
+
*/
|
|
130
|
+
export class ArtifactPermissionEngine extends BaseSingleton {
|
|
131
|
+
constructor() {
|
|
132
|
+
super();
|
|
133
|
+
this._delegatesByEntityKey = new Map();
|
|
134
|
+
this._changeListeners = new Set();
|
|
135
|
+
}
|
|
136
|
+
/** Returns the process-wide singleton instance of {@link ArtifactPermissionEngine}. */
|
|
137
|
+
static get Instance() {
|
|
138
|
+
return super.getInstance();
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* @internal
|
|
142
|
+
* Framework-internal recursion guard for trusted in-process permission `RunView` lookups.
|
|
143
|
+
* Must never be called on untrusted caller `RunViewParams`.
|
|
144
|
+
*
|
|
145
|
+
* Marks a {@link RunViewParams} object as an internal permission-resolution lookup so
|
|
146
|
+
* server-side `MJ: Artifact Versions` / `MJ: Artifact Working States` `RunView` hooks skip
|
|
147
|
+
* recursive permission evaluation even when `ProviderBase.RunView` shallow-clones `params`
|
|
148
|
+
* (`{ ...params }`) or a custom `WellKnownUserSource` returns a user not matched by
|
|
149
|
+
* `isServerSystemUser`.
|
|
150
|
+
*/
|
|
151
|
+
static MarkPermissionResolutionRecursionGuard(params) {
|
|
152
|
+
if (!params || typeof params !== 'object') {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
const weakSet = getInternalPermissionQueryWeakSet();
|
|
156
|
+
weakSet.add(params);
|
|
157
|
+
const token = Object.freeze({});
|
|
158
|
+
weakSet.add(token);
|
|
159
|
+
Object.defineProperty(params, getInternalPermissionQueryMarkerSymbol(), {
|
|
160
|
+
value: token,
|
|
161
|
+
enumerable: true,
|
|
162
|
+
configurable: true,
|
|
163
|
+
writable: false
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* @internal
|
|
168
|
+
* Framework-internal recursion guard for trusted in-process permission `RunView` lookups.
|
|
169
|
+
* Must never be called on untrusted caller `RunViewParams`.
|
|
170
|
+
*
|
|
171
|
+
* Returns `true` when `params` (or a shallow `{ ...params }` clone produced by `ProviderBase.RunView`)
|
|
172
|
+
* was marked by {@link MarkPermissionResolutionRecursionGuard}.
|
|
173
|
+
*/
|
|
174
|
+
static IsPermissionResolutionRecursionGuard(params) {
|
|
175
|
+
if (!params || typeof params !== 'object') {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
const weakSet = getInternalPermissionQueryWeakSet();
|
|
179
|
+
if (weakSet.has(params)) {
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
const descriptor = Object.getOwnPropertyDescriptor(params, getInternalPermissionQueryMarkerSymbol());
|
|
183
|
+
return Boolean(descriptor &&
|
|
184
|
+
typeof descriptor.value === 'object' &&
|
|
185
|
+
descriptor.value !== null &&
|
|
186
|
+
weakSet.has(descriptor.value));
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Programmatically registers an {@link IArtifactPermissionDelegate} for an entity name or entity ID.
|
|
190
|
+
*
|
|
191
|
+
* @param entityNameOrId - Canonical entity name (e.g., `'MJ: Projects'`) or `Entity.ID` UUID.
|
|
192
|
+
* @param delegate - Delegate implementation to invoke for artifacts bound to that entity.
|
|
193
|
+
*/
|
|
194
|
+
RegisterDelegate(entityNameOrId, delegate) {
|
|
195
|
+
const key = (entityNameOrId ?? '').trim().toLowerCase();
|
|
196
|
+
if (!key) {
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
this._delegatesByEntityKey.set(key, delegate);
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Removes a previously registered programmatic delegate for `entityNameOrId`.
|
|
203
|
+
*/
|
|
204
|
+
UnregisterDelegate(entityNameOrId) {
|
|
205
|
+
const key = (entityNameOrId ?? '').trim().toLowerCase();
|
|
206
|
+
if (!key) {
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
this._delegatesByEntityKey.delete(key);
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Returns all programmatically registered delegate entity keys (lowercased entity names or IDs).
|
|
213
|
+
*/
|
|
214
|
+
GetRegisteredDelegateEntityKeys() {
|
|
215
|
+
return Array.from(this._delegatesByEntityKey.keys());
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Whether any real-time permission change listeners are currently subscribed.
|
|
219
|
+
*/
|
|
220
|
+
get HasChangeListeners() {
|
|
221
|
+
return this._changeListeners.size > 0;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Subscribes to artifact permission change events (e.g., share revocation or edit downgrade).
|
|
225
|
+
*
|
|
226
|
+
* @returns An unsubscribe function that removes the listener.
|
|
227
|
+
*/
|
|
228
|
+
OnPermissionsChanged(listener) {
|
|
229
|
+
this._changeListeners.add(listener);
|
|
230
|
+
return () => {
|
|
231
|
+
this._changeListeners.delete(listener);
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Broadcasts a permission change event to all registered listeners (such as `ArtifactCollaborationServer`).
|
|
236
|
+
*/
|
|
237
|
+
async NotifyPermissionsChanged(event) {
|
|
238
|
+
for (const listener of this._changeListeners) {
|
|
239
|
+
try {
|
|
240
|
+
await listener(event);
|
|
241
|
+
}
|
|
242
|
+
catch (err) {
|
|
243
|
+
LogError(`ArtifactPermissionEngine.NotifyPermissionsChanged listener error: ${err instanceof Error ? err.message : String(err)}`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Convenience helper that checks a single {@link ArtifactPermissionAction} (`'Read' | 'Edit' | 'Delete' | 'Share'`)
|
|
249
|
+
* for `(artifactId, user)`.
|
|
250
|
+
*/
|
|
251
|
+
async CheckPermission(provider, artifactId, user, action) {
|
|
252
|
+
const resolved = await this.ResolvePermissions(provider, artifactId, user);
|
|
253
|
+
switch (action) {
|
|
254
|
+
case 'Read':
|
|
255
|
+
return resolved.CanRead;
|
|
256
|
+
case 'Edit':
|
|
257
|
+
return resolved.CanEdit;
|
|
258
|
+
case 'Delete':
|
|
259
|
+
return resolved.CanDelete;
|
|
260
|
+
case 'Share':
|
|
261
|
+
return resolved.CanShare;
|
|
262
|
+
default:
|
|
263
|
+
return false;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Resolves the full permission set (`CanRead`, `CanEdit`, `CanDelete`, `CanShare`) for `(artifactId, user)`.
|
|
268
|
+
* Delegates to {@link ResolvePermissionsBatch} so single-artifact and batched resolution share
|
|
269
|
+
* one implementation and cannot drift apart.
|
|
270
|
+
*/
|
|
271
|
+
async ResolvePermissions(provider, artifactId, user, depth = 0, visitedArtifactIds, memo, strictThrowOnQueryError = false) {
|
|
272
|
+
const normalizedArtifactId = (artifactId ?? '').trim();
|
|
273
|
+
const batch = await this.ResolvePermissionsBatch(provider, [normalizedArtifactId], user, depth, visitedArtifactIds, memo, strictThrowOnQueryError);
|
|
274
|
+
return (batch.get(normalizedArtifactId) ??
|
|
275
|
+
this.buildDenied(normalizedArtifactId, 'Artifact permission resolution failed.'));
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Resolves permissions for many artifacts in a staged batched pass instead of per-artifact queries:
|
|
279
|
+
* - Loads only `MJ: Artifacts` headers first (`ID IN (...)`, `BypassCache: true`) so owned, missing,
|
|
280
|
+
* unregistered-delegate, and parent-delegated artifacts settle without extra permission/version queries.
|
|
281
|
+
* - Loads `MJ: Artifact Permissions` (`ArtifactID IN (...)`) and `MJ: Artifact Versions` (`ArtifactID IN (...)`)
|
|
282
|
+
* only for non-owned artifacts that still require fallback evaluation (in 1 `RunViews` call on Network
|
|
283
|
+
* providers, or `user` + `systemUser` in parallel on Database providers).
|
|
284
|
+
* - Walks `MJ: Collection Artifacts` -> `MJ: Collections` ancestry level-by-level (one batched query per
|
|
285
|
+
* depth level across all artifacts) and loads `MJ: Collection Permissions` once.
|
|
286
|
+
* - Evaluates custom delegates (deferring fallback loading to a single batch only for non-owner defers)
|
|
287
|
+
* and `ParentArtifactPermissionDelegate` chains with exact accumulated `Depth` and `VisitedArtifactIDs`.
|
|
288
|
+
*
|
|
289
|
+
* Returns a `Map` keyed by each input ID in `artifactIds`.
|
|
290
|
+
*/
|
|
291
|
+
async ResolvePermissionsBatch(provider, artifactIds, user, depth = 0, visitedArtifactIds, memo, strictThrowOnQueryError = false) {
|
|
292
|
+
const results = new Map();
|
|
293
|
+
if (!artifactIds || artifactIds.length === 0) {
|
|
294
|
+
return results;
|
|
295
|
+
}
|
|
296
|
+
const fillAllDenied = (reason) => {
|
|
297
|
+
for (const rawId of artifactIds) {
|
|
298
|
+
results.set(rawId, this.buildDenied((rawId ?? '').trim(), reason));
|
|
299
|
+
}
|
|
300
|
+
return results;
|
|
301
|
+
};
|
|
302
|
+
if (!user) {
|
|
303
|
+
return fillAllDenied('Artifact ID and authenticated user context are required.');
|
|
304
|
+
}
|
|
305
|
+
if (user.IsMagicLinkAnonymous || user.MagicLinkScope) {
|
|
306
|
+
return fillAllDenied('Scope-limited or anonymous magic-link principals cannot access governed artifact permissions.');
|
|
307
|
+
}
|
|
308
|
+
if (!IsValidUUID(user.ID)) {
|
|
309
|
+
return fillAllDenied('Artifact ID and user ID must be valid UUIDs.');
|
|
310
|
+
}
|
|
311
|
+
if (depth > MAX_DELEGATE_DEPTH) {
|
|
312
|
+
return fillAllDenied('Maximum artifact permission delegation depth exceeded.');
|
|
313
|
+
}
|
|
314
|
+
const activeProvider = provider ?? Metadata.Provider;
|
|
315
|
+
if (!activeProvider) {
|
|
316
|
+
return fillAllDenied('Metadata provider is not available.');
|
|
317
|
+
}
|
|
318
|
+
const visited = new Set(visitedArtifactIds ?? []);
|
|
319
|
+
const normUserId = NormalizeUUID(user.ID ?? '');
|
|
320
|
+
const activeMemo = memo ?? new Map();
|
|
321
|
+
const memoHits = [];
|
|
322
|
+
const toFetchByNorm = new Map();
|
|
323
|
+
for (const rawId of artifactIds) {
|
|
324
|
+
const trimmed = (rawId ?? '').trim();
|
|
325
|
+
if (!trimmed) {
|
|
326
|
+
results.set(rawId, this.buildDenied(trimmed, 'Artifact ID and authenticated user context are required.'));
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (!IsValidUUID(trimmed)) {
|
|
330
|
+
results.set(rawId, this.buildDenied(trimmed, 'Artifact ID and user ID must be valid UUIDs.'));
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
const normId = NormalizeUUID(trimmed);
|
|
334
|
+
if (visited.has(normId)) {
|
|
335
|
+
results.set(rawId, this.buildDenied(trimmed, 'Circular artifact permission delegation detected.'));
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
const memoKey = `${normId}::${normUserId}`;
|
|
339
|
+
if (!strictThrowOnQueryError) {
|
|
340
|
+
const cachedPromise = activeMemo.get(memoKey);
|
|
341
|
+
if (cachedPromise) {
|
|
342
|
+
memoHits.push({ rawId, promise: cachedPromise });
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
let entry = toFetchByNorm.get(normId);
|
|
347
|
+
if (!entry) {
|
|
348
|
+
entry = { normId, id: trimmed, rawKeys: [] };
|
|
349
|
+
toFetchByNorm.set(normId, entry);
|
|
350
|
+
}
|
|
351
|
+
entry.rawKeys.push(rawId);
|
|
352
|
+
}
|
|
353
|
+
const toFetch = Array.from(toFetchByNorm.values());
|
|
354
|
+
if (toFetch.length > 0) {
|
|
355
|
+
const resolvedByNorm = await this.resolveBatchInternal(activeProvider, toFetch, user, depth, visited, activeMemo, strictThrowOnQueryError);
|
|
356
|
+
for (const item of toFetch) {
|
|
357
|
+
const resolved = resolvedByNorm.get(item.normId) ??
|
|
358
|
+
this.buildDenied(item.id, `Artifact '${item.id}' was not found.`);
|
|
359
|
+
for (const rawKey of item.rawKeys) {
|
|
360
|
+
results.set(rawKey, resolved);
|
|
361
|
+
}
|
|
362
|
+
if (!strictThrowOnQueryError) {
|
|
363
|
+
activeMemo.set(`${item.normId}::${normUserId}`, Promise.resolve(resolved));
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
if (memoHits.length > 0) {
|
|
368
|
+
const settled = await Promise.all(memoHits.map((h) => h.promise));
|
|
369
|
+
for (let i = 0; i < memoHits.length; i++) {
|
|
370
|
+
results.set(memoHits[i].rawId, settled[i]);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return results;
|
|
374
|
+
}
|
|
375
|
+
lookupEntityInfo(provider, entityId, entitiesById) {
|
|
376
|
+
if (typeof provider.EntityByID === 'function') {
|
|
377
|
+
return provider.EntityByID(entityId);
|
|
378
|
+
}
|
|
379
|
+
return entitiesById?.Get(entityId);
|
|
380
|
+
}
|
|
381
|
+
async resolveBatchInternal(provider, initialItems, user, depth, visited, memo, strictThrowOnQueryError) {
|
|
382
|
+
const entitiesById = typeof provider.EntityByID !== 'function' && Array.isArray(provider.Entities)
|
|
383
|
+
? IndexByUUID(provider.Entities, (e) => e.ID)
|
|
384
|
+
: null;
|
|
385
|
+
const normUserId = NormalizeUUID(user.ID ?? '');
|
|
386
|
+
const resolvedByNorm = new Map();
|
|
387
|
+
const loadedNormIds = new Set();
|
|
388
|
+
const parentDelegateMetaByNormId = new Map();
|
|
389
|
+
const customDelegatedByNormId = new Map();
|
|
390
|
+
// Iterative wave loading: each wave loads ONLY MJ: Artifacts first so owned, missing, unregistered-delegate,
|
|
391
|
+
// and parent-delegated artifacts settle without querying MJ: Artifact Permissions or MJ: Artifact Versions.
|
|
392
|
+
let waveItems = initialItems.map((i) => ({ normId: i.normId, id: i.id }));
|
|
393
|
+
const maxExtraWaves = Math.max(0, MAX_DELEGATE_DEPTH - depth);
|
|
394
|
+
for (let wave = 0; wave <= maxExtraWaves && waveItems.length > 0; wave++) {
|
|
395
|
+
for (const w of waveItems) {
|
|
396
|
+
loadedNormIds.add(w.normId);
|
|
397
|
+
}
|
|
398
|
+
const artifactsInWave = await this.loadArtifactRowsBatch(provider, waveItems, user, strictThrowOnQueryError);
|
|
399
|
+
const nonDelegatedNonOwners = [];
|
|
400
|
+
const nextWaveParentsByNorm = new Map();
|
|
401
|
+
for (const w of waveItems) {
|
|
402
|
+
const artifact = artifactsInWave.get(w.normId);
|
|
403
|
+
if (!artifact) {
|
|
404
|
+
resolvedByNorm.set(w.normId, this.buildDenied(w.id, `Artifact '${w.id}' was not found.`));
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
407
|
+
const isOwner = Boolean(artifact.UserID && UUIDsEqual(artifact.UserID, user.ID));
|
|
408
|
+
if (artifact.DelegateEntityID && artifact.DelegateRecordID) {
|
|
409
|
+
const entityInfo = this.lookupEntityInfo(provider, artifact.DelegateEntityID, entitiesById);
|
|
410
|
+
const delegateEntityName = entityInfo?.Name ?? '';
|
|
411
|
+
const delegate = this.resolveDelegateInstance(artifact.DelegateEntityID, delegateEntityName);
|
|
412
|
+
if (!delegate) {
|
|
413
|
+
const entityLabel = delegateEntityName || artifact.DelegateEntityID;
|
|
414
|
+
LogError(`No permission delegate is registered for delegating entity '${entityLabel}' (${artifact.DelegateRecordID}) on artifact '${artifact.ID}'.`);
|
|
415
|
+
resolvedByNorm.set(w.normId, this.buildDenied(artifact.ID, `No permission delegate is registered for delegating entity '${entityLabel}' (${artifact.DelegateRecordID}).`));
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
if (delegate instanceof ParentArtifactPermissionDelegate) {
|
|
419
|
+
parentDelegateMetaByNormId.set(w.normId, {
|
|
420
|
+
Artifact: artifact,
|
|
421
|
+
DelegateEntityName: delegateEntityName,
|
|
422
|
+
DelegateEntityId: artifact.DelegateEntityID,
|
|
423
|
+
DelegateRecordId: artifact.DelegateRecordID
|
|
424
|
+
});
|
|
425
|
+
const parentTrimmed = artifact.DelegateRecordID.trim();
|
|
426
|
+
if (wave < maxExtraWaves && IsValidUUID(parentTrimmed)) {
|
|
427
|
+
const parentNorm = NormalizeUUID(parentTrimmed);
|
|
428
|
+
const parentMemoKey = `${parentNorm}::${normUserId}`;
|
|
429
|
+
const hasMemoHit = !strictThrowOnQueryError && memo.has(parentMemoKey);
|
|
430
|
+
if (!loadedNormIds.has(parentNorm) && !visited.has(parentNorm) && !hasMemoHit) {
|
|
431
|
+
nextWaveParentsByNorm.set(parentNorm, { normId: parentNorm, id: parentTrimmed });
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
else {
|
|
436
|
+
customDelegatedByNormId.set(w.normId, {
|
|
437
|
+
normId: w.normId,
|
|
438
|
+
id: w.id,
|
|
439
|
+
Artifact: artifact,
|
|
440
|
+
Delegate: delegate,
|
|
441
|
+
DelegateEntityName: delegateEntityName,
|
|
442
|
+
DelegateEntityId: artifact.DelegateEntityID,
|
|
443
|
+
DelegateRecordId: artifact.DelegateRecordID
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
else if (isOwner) {
|
|
448
|
+
resolvedByNorm.set(w.normId, this.evaluateNonDelegatedArtifact(artifact, user, [], []));
|
|
449
|
+
}
|
|
450
|
+
else {
|
|
451
|
+
nonDelegatedNonOwners.push({ normId: w.normId, id: w.id, Artifact: artifact });
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
if (nonDelegatedNonOwners.length > 0) {
|
|
455
|
+
const { DirectPermsByNormArtifactId, CollectionPermsByNormArtifactId } = await this.loadDirectAndCollectionBatch(provider, nonDelegatedNonOwners, user, strictThrowOnQueryError);
|
|
456
|
+
for (const item of nonDelegatedNonOwners) {
|
|
457
|
+
resolvedByNorm.set(item.normId, this.evaluateNonDelegatedArtifact(item.Artifact, user, DirectPermsByNormArtifactId.get(item.normId) ?? [], CollectionPermsByNormArtifactId.get(item.normId) ?? []));
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
waveItems = Array.from(nextWaveParentsByNorm.values());
|
|
461
|
+
}
|
|
462
|
+
// Seed a child memo with already-settled entries (never unresolved promises) so custom delegates cannot deadlock
|
|
463
|
+
const settledMemo = new Map(memo);
|
|
464
|
+
if (!strictThrowOnQueryError) {
|
|
465
|
+
for (const [normId, resolved] of resolvedByNorm.entries()) {
|
|
466
|
+
settledMemo.set(`${normId}::${normUserId}`, Promise.resolve(resolved));
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
const parentResolvedByNorm = new Map();
|
|
470
|
+
const pendingCustomInvocations = [];
|
|
471
|
+
const pendingMemoParentChains = [];
|
|
472
|
+
// Walk parent-delegate chains for initialItems, capturing exact accumulated Depth & VisitedArtifactIDs
|
|
473
|
+
// whenever a chain terminates at a custom-delegated artifact.
|
|
474
|
+
for (const item of initialItems) {
|
|
475
|
+
if (customDelegatedByNormId.has(item.normId)) {
|
|
476
|
+
const directVisited = new Set(visited);
|
|
477
|
+
directVisited.add(item.normId);
|
|
478
|
+
pendingCustomInvocations.push({
|
|
479
|
+
Kind: 'direct',
|
|
480
|
+
StartNormId: item.normId,
|
|
481
|
+
TargetNormId: item.normId,
|
|
482
|
+
Depth: depth,
|
|
483
|
+
Visited: directVisited
|
|
484
|
+
});
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
const startMeta = parentDelegateMetaByNormId.get(item.normId);
|
|
488
|
+
if (!startMeta) {
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
const walk = this.walkParentDelegateChain(item.normId, startMeta, depth, visited, normUserId, strictThrowOnQueryError, parentDelegateMetaByNormId, customDelegatedByNormId, resolvedByNorm, memo);
|
|
492
|
+
if (walk.Kind === 'resolved') {
|
|
493
|
+
parentResolvedByNorm.set(item.normId, walk.Result);
|
|
494
|
+
}
|
|
495
|
+
else if (walk.Kind === 'memo') {
|
|
496
|
+
pendingMemoParentChains.push({
|
|
497
|
+
StartNormId: item.normId,
|
|
498
|
+
StartMeta: startMeta,
|
|
499
|
+
Promise: walk.Promise
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
else {
|
|
503
|
+
pendingCustomInvocations.push({
|
|
504
|
+
Kind: 'parent-chain',
|
|
505
|
+
StartNormId: item.normId,
|
|
506
|
+
StartMeta: startMeta,
|
|
507
|
+
TargetNormId: walk.CustomNormId,
|
|
508
|
+
Depth: walk.Depth,
|
|
509
|
+
Visited: walk.Visited
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
if (pendingMemoParentChains.length > 0) {
|
|
514
|
+
const memoParents = await Promise.all(pendingMemoParentChains.map((p) => p.Promise));
|
|
515
|
+
for (let i = 0; i < pendingMemoParentChains.length; i++) {
|
|
516
|
+
const entry = pendingMemoParentChains[i];
|
|
517
|
+
parentResolvedByNorm.set(entry.StartNormId, this.formatParentDelegateResult(entry.StartMeta, memoParents[i]));
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
// Evaluate custom delegates in parallel with exact accumulated Depth & VisitedArtifactIDs;
|
|
521
|
+
// batch-load direct + collection fallback rows ONCE only for non-owner invocations that returned 'Defer'.
|
|
522
|
+
if (pendingCustomInvocations.length > 0) {
|
|
523
|
+
const evaluated = await Promise.all(pendingCustomInvocations.map(async (inv) => {
|
|
524
|
+
const target = customDelegatedByNormId.get(inv.TargetNormId);
|
|
525
|
+
const decisions = await this.evaluateCustomDelegateDecisions(provider, target.Delegate, target.Artifact, target.DelegateEntityId, target.DelegateEntityName, target.DelegateRecordId, user, inv.Depth, inv.Visited, settledMemo);
|
|
526
|
+
return { inv, target, decisions };
|
|
527
|
+
}));
|
|
528
|
+
const customNeedingFallback = new Map();
|
|
529
|
+
for (const { target, decisions } of evaluated) {
|
|
530
|
+
const isOwner = Boolean(target.Artifact.UserID && UUIDsEqual(target.Artifact.UserID, user.ID));
|
|
531
|
+
if (decisions.NeedsFallback && !isOwner) {
|
|
532
|
+
customNeedingFallback.set(target.normId, { normId: target.normId, id: target.id });
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
let fallbackDirect = new Map();
|
|
536
|
+
let fallbackCollections = new Map();
|
|
537
|
+
if (customNeedingFallback.size > 0) {
|
|
538
|
+
const loadedFallback = await this.loadDirectAndCollectionBatch(provider, Array.from(customNeedingFallback.values()), user, strictThrowOnQueryError);
|
|
539
|
+
fallbackDirect = loadedFallback.DirectPermsByNormArtifactId;
|
|
540
|
+
fallbackCollections = loadedFallback.CollectionPermsByNormArtifactId;
|
|
541
|
+
}
|
|
542
|
+
for (const { inv, target, decisions } of evaluated) {
|
|
543
|
+
const finalized = this.finalizeCustomDelegateDecisions(target.Artifact, target.DelegateEntityId, target.DelegateEntityName, target.DelegateRecordId, decisions, user, fallbackDirect.get(target.normId) ?? [], fallbackCollections.get(target.normId) ?? []);
|
|
544
|
+
if (inv.Kind === 'direct') {
|
|
545
|
+
resolvedByNorm.set(inv.StartNormId, finalized);
|
|
546
|
+
}
|
|
547
|
+
else {
|
|
548
|
+
parentResolvedByNorm.set(inv.StartNormId, this.formatParentDelegateResult(inv.StartMeta, finalized));
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
for (const [normId, result] of parentResolvedByNorm.entries()) {
|
|
553
|
+
resolvedByNorm.set(normId, result);
|
|
554
|
+
}
|
|
555
|
+
return resolvedByNorm;
|
|
556
|
+
}
|
|
557
|
+
formatParentDelegateResult(startMeta, parentPerms) {
|
|
558
|
+
if (!parentPerms.CanRead) {
|
|
559
|
+
return this.buildDenied(startMeta.Artifact.ID, `Access denied by delegate entity '${startMeta.DelegateEntityName || startMeta.DelegateEntityId}' (${startMeta.DelegateRecordId}).`);
|
|
560
|
+
}
|
|
561
|
+
return {
|
|
562
|
+
ArtifactID: startMeta.Artifact.ID,
|
|
563
|
+
CanRead: parentPerms.CanRead,
|
|
564
|
+
CanEdit: parentPerms.CanEdit,
|
|
565
|
+
CanDelete: parentPerms.CanDelete,
|
|
566
|
+
CanShare: parentPerms.CanShare,
|
|
567
|
+
Source: 'Delegate',
|
|
568
|
+
Reason: `Permissions resolved via delegate '${startMeta.DelegateEntityName || startMeta.DelegateEntityId}' (${startMeta.DelegateRecordId}).`
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
walkParentDelegateChain(startNormId, startMeta, baseDepth, baseVisited, normUserId, strictThrowOnQueryError, parentDelegateMetaByNormId, customDelegatedByNormId, resolvedByNorm, memo) {
|
|
572
|
+
const localVisited = new Set(baseVisited);
|
|
573
|
+
localVisited.add(startNormId);
|
|
574
|
+
let currentMeta = startMeta;
|
|
575
|
+
let currentDepth = baseDepth;
|
|
576
|
+
while (true) {
|
|
577
|
+
const nextDepth = currentDepth + 1;
|
|
578
|
+
const parentTrimmed = currentMeta.DelegateRecordId.trim();
|
|
579
|
+
if (!parentTrimmed || !IsValidUUID(parentTrimmed)) {
|
|
580
|
+
return {
|
|
581
|
+
Kind: 'resolved',
|
|
582
|
+
Result: this.formatParentDelegateResult(startMeta, this.buildDenied(parentTrimmed, 'Artifact ID and user ID must be valid UUIDs.'))
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
if (nextDepth > MAX_DELEGATE_DEPTH) {
|
|
586
|
+
return {
|
|
587
|
+
Kind: 'resolved',
|
|
588
|
+
Result: this.formatParentDelegateResult(startMeta, this.buildDenied(parentTrimmed, 'Maximum artifact permission delegation depth exceeded.'))
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
const parentNorm = NormalizeUUID(parentTrimmed);
|
|
592
|
+
if (localVisited.has(parentNorm)) {
|
|
593
|
+
return {
|
|
594
|
+
Kind: 'resolved',
|
|
595
|
+
Result: this.formatParentDelegateResult(startMeta, this.buildDenied(parentTrimmed, 'Circular artifact permission delegation detected.'))
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
const settledParent = resolvedByNorm.get(parentNorm);
|
|
599
|
+
if (settledParent) {
|
|
600
|
+
return { Kind: 'resolved', Result: this.formatParentDelegateResult(startMeta, settledParent) };
|
|
601
|
+
}
|
|
602
|
+
if (customDelegatedByNormId.has(parentNorm)) {
|
|
603
|
+
localVisited.add(parentNorm);
|
|
604
|
+
return { Kind: 'custom', CustomNormId: parentNorm, Depth: nextDepth, Visited: localVisited };
|
|
605
|
+
}
|
|
606
|
+
const nextParentMeta = parentDelegateMetaByNormId.get(parentNorm);
|
|
607
|
+
if (nextParentMeta) {
|
|
608
|
+
localVisited.add(parentNorm);
|
|
609
|
+
currentMeta = nextParentMeta;
|
|
610
|
+
currentDepth = nextDepth;
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
613
|
+
if (!strictThrowOnQueryError) {
|
|
614
|
+
const memoPromise = memo.get(`${parentNorm}::${normUserId}`);
|
|
615
|
+
if (memoPromise) {
|
|
616
|
+
return { Kind: 'memo', Promise: memoPromise };
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
return {
|
|
620
|
+
Kind: 'resolved',
|
|
621
|
+
Result: this.formatParentDelegateResult(startMeta, this.buildDenied(parentTrimmed, `Artifact '${parentTrimmed}' was not found.`))
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
evaluateNonDelegatedArtifact(artifact, user, directRows, collectionPerms) {
|
|
626
|
+
const isOwner = Boolean(artifact.UserID && UUIDsEqual(artifact.UserID, user.ID));
|
|
627
|
+
if (isOwner) {
|
|
628
|
+
return {
|
|
629
|
+
ArtifactID: artifact.ID,
|
|
630
|
+
CanRead: true,
|
|
631
|
+
CanEdit: true,
|
|
632
|
+
CanDelete: true,
|
|
633
|
+
CanShare: true,
|
|
634
|
+
Source: 'Owner',
|
|
635
|
+
Reason: 'User is the owner of the artifact.'
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
const directCanEdit = directRows.some((r) => Boolean(r.CanEdit));
|
|
639
|
+
const directCanDelete = directRows.some((r) => Boolean(r.CanDelete));
|
|
640
|
+
const directCanShare = directRows.some((r) => Boolean(r.CanShare));
|
|
641
|
+
const directCanRead = directRows.some((r) => Boolean(r.CanRead)) || directCanEdit || directCanDelete || directCanShare;
|
|
642
|
+
const colCanEdit = collectionPerms.some((r) => Boolean(r.CanEdit));
|
|
643
|
+
const colCanDelete = collectionPerms.some((r) => Boolean(r.CanDelete));
|
|
644
|
+
const colCanShare = collectionPerms.some((r) => Boolean(r.CanShare));
|
|
645
|
+
const colCanRead = collectionPerms.some((r) => Boolean(r.CanRead)) || colCanEdit || colCanDelete || colCanShare;
|
|
646
|
+
const canEdit = directCanEdit || colCanEdit;
|
|
647
|
+
const canDelete = directCanDelete || colCanDelete;
|
|
648
|
+
const canShare = directCanShare || colCanShare;
|
|
649
|
+
const canRead = directCanRead || colCanRead || canEdit || canDelete || canShare;
|
|
650
|
+
if (canRead) {
|
|
651
|
+
const collectionElevated = (colCanRead && !directCanRead) ||
|
|
652
|
+
(colCanEdit && !directCanEdit) ||
|
|
653
|
+
(colCanDelete && !directCanDelete) ||
|
|
654
|
+
(colCanShare && !directCanShare);
|
|
655
|
+
return {
|
|
656
|
+
ArtifactID: artifact.ID,
|
|
657
|
+
CanRead: canRead,
|
|
658
|
+
CanEdit: canEdit,
|
|
659
|
+
CanDelete: canDelete,
|
|
660
|
+
CanShare: canShare,
|
|
661
|
+
Source: !directCanRead || collectionElevated ? 'CollectionPermission' : 'ArtifactPermission',
|
|
662
|
+
Reason: directCanRead && colCanRead
|
|
663
|
+
? 'Permissions resolved from MJ: Artifact Permissions and parent Collection membership.'
|
|
664
|
+
: directCanRead
|
|
665
|
+
? 'Permissions granted via MJ: Artifact Permissions.'
|
|
666
|
+
: 'Permissions granted via parent Collection membership.'
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
return this.buildDenied(artifact.ID, `User '${user.ID}' has no permission grant on artifact '${artifact.ID}'.`);
|
|
670
|
+
}
|
|
671
|
+
async loadArtifactRowsBatch(provider, items, user, strictThrowOnQueryError) {
|
|
672
|
+
const artifactsByNormId = new Map();
|
|
673
|
+
if (items.length === 0) {
|
|
674
|
+
return artifactsByNormId;
|
|
675
|
+
}
|
|
676
|
+
const ids = items.map((i) => i.id);
|
|
677
|
+
const contextLabel = ids.length === 1 ? `artifact '${ids[0]}'` : `batch of ${ids.length} artifacts`;
|
|
678
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
679
|
+
const artifactQueries = chunkArray(ids, IN_CLAUSE_CHUNK_SIZE).map((chunk) => {
|
|
680
|
+
const artParams = {
|
|
681
|
+
EntityName: 'MJ: Artifacts',
|
|
682
|
+
ExtraFilter: buildEqOrInFilter('ID', chunk),
|
|
683
|
+
Fields: ['ID', 'UserID', 'DelegateEntityID', 'DelegateRecordID'],
|
|
684
|
+
...(chunk.length === 1 ? { MaxRows: 1 } : { IgnoreMaxRows: true }),
|
|
685
|
+
SkipTotalRowCount: true,
|
|
686
|
+
BypassCache: true,
|
|
687
|
+
ResultType: 'simple'
|
|
688
|
+
};
|
|
689
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(artParams);
|
|
690
|
+
return artParams;
|
|
691
|
+
});
|
|
692
|
+
const ingest = (res) => {
|
|
693
|
+
if (!res?.Success) {
|
|
694
|
+
if (strictThrowOnQueryError) {
|
|
695
|
+
throw new Error(res?.ErrorMessage || `Failed loading artifact rows for ${contextLabel}.`);
|
|
696
|
+
}
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
for (const row of (res.Results ?? [])) {
|
|
700
|
+
if (row?.ID) {
|
|
701
|
+
artifactsByNormId.set(NormalizeUUID(row.ID), row);
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
try {
|
|
706
|
+
const results = canUseRunViews(provider, rv)
|
|
707
|
+
? await rv.RunViews(artifactQueries, user)
|
|
708
|
+
: await Promise.all(artifactQueries.map((q) => rv.RunView(q, user)));
|
|
709
|
+
for (const res of results) {
|
|
710
|
+
ingest(res);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
catch (err) {
|
|
714
|
+
LogError(`ArtifactPermissionEngine.loadArtifactRowsBatch error for ${contextLabel} (user '${user.ID}'): ${err instanceof Error ? err.message : String(err)}`);
|
|
715
|
+
if (strictThrowOnQueryError) {
|
|
716
|
+
throw err;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
return artifactsByNormId;
|
|
720
|
+
}
|
|
721
|
+
async loadDirectAndCollectionBatch(provider, items, user, strictThrowOnQueryError) {
|
|
722
|
+
const directPermsByNormArtifactId = new Map();
|
|
723
|
+
const versionIdsByNormArtifactId = new Map();
|
|
724
|
+
if (items.length === 0) {
|
|
725
|
+
return {
|
|
726
|
+
DirectPermsByNormArtifactId: directPermsByNormArtifactId,
|
|
727
|
+
CollectionPermsByNormArtifactId: new Map()
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
let directQueryError = null;
|
|
731
|
+
let versionQueryError = null;
|
|
732
|
+
const ids = items.map((i) => i.id);
|
|
733
|
+
const contextLabel = ids.length === 1 ? `artifact '${ids[0]}'` : `batch of ${ids.length} artifacts`;
|
|
734
|
+
const queryActor = await this.resolvePermissionQueryActor(provider, user, contextLabel);
|
|
735
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
736
|
+
const safeUserId = EscapeSQLString(user.ID);
|
|
737
|
+
const chunks = chunkArray(ids, IN_CLAUSE_CHUNK_SIZE);
|
|
738
|
+
const directQueries = [];
|
|
739
|
+
const versionQueries = [];
|
|
740
|
+
for (const chunk of chunks) {
|
|
741
|
+
const directParams = {
|
|
742
|
+
EntityName: 'MJ: Artifact Permissions',
|
|
743
|
+
ExtraFilter: `${buildEqOrInFilter('ArtifactID', chunk)} AND UserID='${safeUserId}'`,
|
|
744
|
+
Fields: ['ID', 'ArtifactID', 'UserID', 'CanRead', 'CanEdit', 'CanDelete', 'CanShare'],
|
|
745
|
+
IgnoreMaxRows: true,
|
|
746
|
+
SkipTotalRowCount: true,
|
|
747
|
+
BypassCache: true,
|
|
748
|
+
ResultType: 'simple'
|
|
749
|
+
};
|
|
750
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(directParams);
|
|
751
|
+
directQueries.push(directParams);
|
|
752
|
+
if (queryActor) {
|
|
753
|
+
const verParams = {
|
|
754
|
+
EntityName: 'MJ: Artifact Versions',
|
|
755
|
+
ExtraFilter: buildEqOrInFilter('ArtifactID', chunk),
|
|
756
|
+
Fields: ['ID', 'ArtifactID'],
|
|
757
|
+
IgnoreMaxRows: true,
|
|
758
|
+
SkipTotalRowCount: true,
|
|
759
|
+
BypassCache: true,
|
|
760
|
+
ResultType: 'simple'
|
|
761
|
+
};
|
|
762
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(verParams);
|
|
763
|
+
versionQueries.push(verParams);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
const singleNormFallback = items.length === 1 ? items[0].normId : null;
|
|
767
|
+
const ingestDirectResult = (res) => {
|
|
768
|
+
if (!res?.Success) {
|
|
769
|
+
if (!directQueryError) {
|
|
770
|
+
directQueryError = new Error(res?.ErrorMessage || `Failed loading direct permissions for ${contextLabel}.`);
|
|
771
|
+
}
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
for (const row of (res.Results ?? [])) {
|
|
775
|
+
const artId = row?.ArtifactID;
|
|
776
|
+
const normArtId = artId ? NormalizeUUID(artId) : singleNormFallback;
|
|
777
|
+
if (!normArtId) {
|
|
778
|
+
continue;
|
|
779
|
+
}
|
|
780
|
+
let list = directPermsByNormArtifactId.get(normArtId);
|
|
781
|
+
if (!list) {
|
|
782
|
+
list = [];
|
|
783
|
+
directPermsByNormArtifactId.set(normArtId, list);
|
|
784
|
+
}
|
|
785
|
+
list.push(row);
|
|
786
|
+
}
|
|
787
|
+
};
|
|
788
|
+
const ingestVersionResult = (res) => {
|
|
789
|
+
if (!res?.Success) {
|
|
790
|
+
if (!versionQueryError) {
|
|
791
|
+
versionQueryError = new Error(res?.ErrorMessage || `Failed loading versions for ${contextLabel}.`);
|
|
792
|
+
}
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
for (const row of (res.Results ?? [])) {
|
|
796
|
+
if (!row?.ID) {
|
|
797
|
+
continue;
|
|
798
|
+
}
|
|
799
|
+
const normArtId = row.ArtifactID ? NormalizeUUID(row.ArtifactID) : singleNormFallback;
|
|
800
|
+
if (!normArtId) {
|
|
801
|
+
continue;
|
|
802
|
+
}
|
|
803
|
+
let list = versionIdsByNormArtifactId.get(normArtId);
|
|
804
|
+
if (!list) {
|
|
805
|
+
list = [];
|
|
806
|
+
versionIdsByNormArtifactId.set(normArtId, list);
|
|
807
|
+
}
|
|
808
|
+
list.push(row.ID);
|
|
809
|
+
}
|
|
810
|
+
};
|
|
811
|
+
if (canUseRunViews(provider, rv)) {
|
|
812
|
+
if (provider.ProviderType !== 'Database') {
|
|
813
|
+
// On Network/GraphQL providers, queryActor === user: send Direct Perms + Versions in ONE RunViews call.
|
|
814
|
+
const combined = [...directQueries, ...versionQueries];
|
|
815
|
+
try {
|
|
816
|
+
const batchRes = await rv.RunViews(combined, user);
|
|
817
|
+
const directCount = directQueries.length;
|
|
818
|
+
for (let i = 0; i < directCount; i++) {
|
|
819
|
+
ingestDirectResult(batchRes[i]);
|
|
820
|
+
}
|
|
821
|
+
for (let i = 0; i < versionQueries.length; i++) {
|
|
822
|
+
ingestVersionResult(batchRes[directCount + i]);
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
catch (err) {
|
|
826
|
+
LogError(`ArtifactPermissionEngine.loadDirectAndCollectionBatch error for ${contextLabel} (user '${user.ID}'): ${err instanceof Error ? err.message : String(err)}`);
|
|
827
|
+
if (strictThrowOnQueryError) {
|
|
828
|
+
throw err;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
else {
|
|
833
|
+
// On Database providers, run MJ: Artifact Permissions as `user` (preserving entity CanRead and RLS)
|
|
834
|
+
// and MJ: Artifact Versions as `queryActor` (systemUser, avoiding ArtifactVersionPostRunViewHook recursion) in parallel.
|
|
835
|
+
const runDirectBatch = async () => {
|
|
836
|
+
try {
|
|
837
|
+
const resList = directQueries.length === 1
|
|
838
|
+
? [await rv.RunView(directQueries[0], user)]
|
|
839
|
+
: await rv.RunViews(directQueries, user);
|
|
840
|
+
for (const res of resList) {
|
|
841
|
+
ingestDirectResult(res);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
catch (err) {
|
|
845
|
+
LogError(`ArtifactPermissionEngine.loadDirectPermissionRows error for ${contextLabel} (user '${user.ID}'): ${err instanceof Error ? err.message : String(err)}`);
|
|
846
|
+
if (!directQueryError) {
|
|
847
|
+
directQueryError = err instanceof Error ? err : new Error(String(err));
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
const runVersionBatch = async () => {
|
|
852
|
+
if (versionQueries.length === 0 || !queryActor) {
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
try {
|
|
856
|
+
const verRes = versionQueries.length === 1
|
|
857
|
+
? [await rv.RunView(versionQueries[0], queryActor)]
|
|
858
|
+
: await rv.RunViews(versionQueries, queryActor);
|
|
859
|
+
for (const res of verRes) {
|
|
860
|
+
ingestVersionResult(res);
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
catch (err) {
|
|
864
|
+
LogError(`ArtifactPermissionEngine.loadCollectionPermissionRows error for ${contextLabel} (user '${user.ID}'): ${err instanceof Error ? err.message : String(err)}`);
|
|
865
|
+
if (!versionQueryError) {
|
|
866
|
+
versionQueryError = err instanceof Error ? err : new Error(String(err));
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
};
|
|
870
|
+
await Promise.all([runDirectBatch(), runVersionBatch()]);
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
else {
|
|
874
|
+
// Fallback for test doubles that stub only RunView without RunViews
|
|
875
|
+
await Promise.all([
|
|
876
|
+
...directQueries.map(async (q) => {
|
|
877
|
+
try {
|
|
878
|
+
ingestDirectResult(await rv.RunView(q, user));
|
|
879
|
+
}
|
|
880
|
+
catch (err) {
|
|
881
|
+
LogError(`ArtifactPermissionEngine.loadDirectPermissionRows error: ${err instanceof Error ? err.message : String(err)}`);
|
|
882
|
+
if (!directQueryError) {
|
|
883
|
+
directQueryError = err instanceof Error ? err : new Error(String(err));
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
}),
|
|
887
|
+
...versionQueries.map(async (q) => {
|
|
888
|
+
try {
|
|
889
|
+
ingestVersionResult(await rv.RunView(q, queryActor));
|
|
890
|
+
}
|
|
891
|
+
catch (err) {
|
|
892
|
+
LogError(`ArtifactPermissionEngine.loadCollectionPermissionRows error for ${contextLabel} (user '${user.ID}'): ${err instanceof Error ? err.message : String(err)}`);
|
|
893
|
+
if (!versionQueryError) {
|
|
894
|
+
versionQueryError = err instanceof Error ? err : new Error(String(err));
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
})
|
|
898
|
+
]);
|
|
899
|
+
}
|
|
900
|
+
if (strictThrowOnQueryError) {
|
|
901
|
+
if (directQueryError) {
|
|
902
|
+
throw directQueryError;
|
|
903
|
+
}
|
|
904
|
+
if (versionQueryError) {
|
|
905
|
+
throw versionQueryError;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
const artifactsNeedingCollections = new Set(items.map((i) => i.normId));
|
|
909
|
+
const collectionPermsByNormArtifactId = await this.loadBatchedCollectionPermissions(provider, items, artifactsNeedingCollections, versionIdsByNormArtifactId, queryActor, user, strictThrowOnQueryError);
|
|
910
|
+
return {
|
|
911
|
+
DirectPermsByNormArtifactId: directPermsByNormArtifactId,
|
|
912
|
+
CollectionPermsByNormArtifactId: collectionPermsByNormArtifactId
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
async loadBatchedCollectionPermissions(provider, items, artifactsNeedingCollections, versionIdsByNormArtifactId, queryActor, user, strictThrowOnQueryError) {
|
|
916
|
+
const resultByNormArtifactId = new Map();
|
|
917
|
+
if (artifactsNeedingCollections.size === 0) {
|
|
918
|
+
return resultByNormArtifactId;
|
|
919
|
+
}
|
|
920
|
+
const contextLabel = items.length === 1 ? `artifact '${items[0].id}'` : `batch of ${items.length} artifacts`;
|
|
921
|
+
if (!queryActor) {
|
|
922
|
+
if (strictThrowOnQueryError) {
|
|
923
|
+
throw new Error(`System user is unavailable for collection lookup on ${contextLabel}.`);
|
|
924
|
+
}
|
|
925
|
+
return resultByNormArtifactId;
|
|
926
|
+
}
|
|
927
|
+
// Collect all unique version IDs across artifacts needing collection resolution
|
|
928
|
+
const versionNormToArtifactNorms = new Map();
|
|
929
|
+
const uniqueVersionIds = [];
|
|
930
|
+
for (const normArtId of artifactsNeedingCollections) {
|
|
931
|
+
const verIds = versionIdsByNormArtifactId.get(normArtId) ?? [];
|
|
932
|
+
for (const verId of verIds) {
|
|
933
|
+
const normVerId = NormalizeUUID(verId);
|
|
934
|
+
let owners = versionNormToArtifactNorms.get(normVerId);
|
|
935
|
+
if (!owners) {
|
|
936
|
+
owners = new Set();
|
|
937
|
+
versionNormToArtifactNorms.set(normVerId, owners);
|
|
938
|
+
uniqueVersionIds.push(verId);
|
|
939
|
+
}
|
|
940
|
+
owners.add(normArtId);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
if (uniqueVersionIds.length === 0) {
|
|
944
|
+
return resultByNormArtifactId;
|
|
945
|
+
}
|
|
946
|
+
try {
|
|
947
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
948
|
+
const runBatch = async (paramsList) => {
|
|
949
|
+
for (const p of paramsList) {
|
|
950
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(p);
|
|
951
|
+
}
|
|
952
|
+
if (paramsList.length === 0) {
|
|
953
|
+
return [];
|
|
954
|
+
}
|
|
955
|
+
if (paramsList.length === 1) {
|
|
956
|
+
return [await rv.RunView(paramsList[0], queryActor)];
|
|
957
|
+
}
|
|
958
|
+
if (canUseRunViews(provider, rv)) {
|
|
959
|
+
return await rv.RunViews(paramsList, queryActor);
|
|
960
|
+
}
|
|
961
|
+
return await Promise.all(paramsList.map((p) => rv.RunView(p, queryActor)));
|
|
962
|
+
};
|
|
963
|
+
// 1. Batched MJ: Collection Artifacts lookup
|
|
964
|
+
const colArtQueries = chunkArray(uniqueVersionIds, IN_CLAUSE_CHUNK_SIZE).map((verChunk) => ({
|
|
965
|
+
EntityName: 'MJ: Collection Artifacts',
|
|
966
|
+
ExtraFilter: `ArtifactVersionID IN (${buildQuotedInList(verChunk)})`,
|
|
967
|
+
Fields: ['ArtifactVersionID', 'CollectionID'],
|
|
968
|
+
IgnoreMaxRows: true,
|
|
969
|
+
SkipTotalRowCount: true,
|
|
970
|
+
BypassCache: true,
|
|
971
|
+
ResultType: 'simple'
|
|
972
|
+
}));
|
|
973
|
+
const colArtResults = await runBatch(colArtQueries);
|
|
974
|
+
const directColsByNormArtifactId = new Map();
|
|
975
|
+
const seenColNormIds = new Set();
|
|
976
|
+
const directCollectionIds = [];
|
|
977
|
+
const singleFallbackArtNorm = artifactsNeedingCollections.size === 1 ? Array.from(artifactsNeedingCollections)[0] : null;
|
|
978
|
+
for (const res of colArtResults) {
|
|
979
|
+
if (!res?.Success) {
|
|
980
|
+
if (strictThrowOnQueryError) {
|
|
981
|
+
throw new Error(res?.ErrorMessage || `Failed loading collection links for ${contextLabel}.`);
|
|
982
|
+
}
|
|
983
|
+
continue;
|
|
984
|
+
}
|
|
985
|
+
for (const row of (res.Results ?? [])) {
|
|
986
|
+
if (!row?.CollectionID) {
|
|
987
|
+
continue;
|
|
988
|
+
}
|
|
989
|
+
const normColId = NormalizeUUID(row.CollectionID);
|
|
990
|
+
const targetArts = row.ArtifactVersionID
|
|
991
|
+
? versionNormToArtifactNorms.get(NormalizeUUID(row.ArtifactVersionID))
|
|
992
|
+
: singleFallbackArtNorm
|
|
993
|
+
? new Set([singleFallbackArtNorm])
|
|
994
|
+
: undefined;
|
|
995
|
+
if (!targetArts) {
|
|
996
|
+
continue;
|
|
997
|
+
}
|
|
998
|
+
if (!seenColNormIds.has(normColId)) {
|
|
999
|
+
seenColNormIds.add(normColId);
|
|
1000
|
+
directCollectionIds.push(row.CollectionID);
|
|
1001
|
+
}
|
|
1002
|
+
for (const normArtId of targetArts) {
|
|
1003
|
+
let colSet = directColsByNormArtifactId.get(normArtId);
|
|
1004
|
+
if (!colSet) {
|
|
1005
|
+
colSet = new Set();
|
|
1006
|
+
directColsByNormArtifactId.set(normArtId, colSet);
|
|
1007
|
+
}
|
|
1008
|
+
colSet.add(normColId);
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
if (directCollectionIds.length === 0) {
|
|
1013
|
+
return resultByNormArtifactId;
|
|
1014
|
+
}
|
|
1015
|
+
// 2. Walk collection ancestry level-by-level across ALL collections (1 batched query per depth level)
|
|
1016
|
+
const collectionMetaByNormId = new Map();
|
|
1017
|
+
const allCollectionIds = [...directCollectionIds];
|
|
1018
|
+
let frontier = [...directCollectionIds];
|
|
1019
|
+
for (let level = 0; level < MAX_COLLECTION_ANCESTRY_DEPTH && frontier.length > 0; level++) {
|
|
1020
|
+
const colMetaQueries = chunkArray(frontier, IN_CLAUSE_CHUNK_SIZE).map((colChunk) => ({
|
|
1021
|
+
EntityName: 'MJ: Collections',
|
|
1022
|
+
ExtraFilter: `ID IN (${buildQuotedInList(colChunk)})`,
|
|
1023
|
+
Fields: ['ID', 'OwnerID', 'ParentID'],
|
|
1024
|
+
IgnoreMaxRows: true,
|
|
1025
|
+
SkipTotalRowCount: true,
|
|
1026
|
+
BypassCache: true,
|
|
1027
|
+
ResultType: 'simple'
|
|
1028
|
+
}));
|
|
1029
|
+
const colMetaResults = await runBatch(colMetaQueries);
|
|
1030
|
+
const nextFrontier = [];
|
|
1031
|
+
for (const res of colMetaResults) {
|
|
1032
|
+
if (!res?.Success && strictThrowOnQueryError) {
|
|
1033
|
+
throw new Error(res?.ErrorMessage || `Failed loading collections for ${contextLabel}.`);
|
|
1034
|
+
}
|
|
1035
|
+
if (!res?.Success || !res.Results) {
|
|
1036
|
+
continue;
|
|
1037
|
+
}
|
|
1038
|
+
for (const col of res.Results) {
|
|
1039
|
+
if (!col?.ID) {
|
|
1040
|
+
continue;
|
|
1041
|
+
}
|
|
1042
|
+
collectionMetaByNormId.set(NormalizeUUID(col.ID), col);
|
|
1043
|
+
if (level + 1 >= MAX_COLLECTION_ANCESTRY_DEPTH) {
|
|
1044
|
+
continue;
|
|
1045
|
+
}
|
|
1046
|
+
const parentId = col.ParentID?.trim();
|
|
1047
|
+
if (parentId && IsValidUUID(parentId)) {
|
|
1048
|
+
const normParent = NormalizeUUID(parentId);
|
|
1049
|
+
if (!seenColNormIds.has(normParent)) {
|
|
1050
|
+
seenColNormIds.add(normParent);
|
|
1051
|
+
allCollectionIds.push(parentId);
|
|
1052
|
+
nextFrontier.push(parentId);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
frontier = nextFrontier;
|
|
1058
|
+
}
|
|
1059
|
+
// 3. Load MJ: Collection Permissions once for ALL discovered collections across the batch
|
|
1060
|
+
const safeUserId = EscapeSQLString(user.ID);
|
|
1061
|
+
const permQueries = chunkArray(allCollectionIds, IN_CLAUSE_CHUNK_SIZE).map((colChunk) => ({
|
|
1062
|
+
EntityName: 'MJ: Collection Permissions',
|
|
1063
|
+
ExtraFilter: `CollectionID IN (${buildQuotedInList(colChunk)}) AND UserID='${safeUserId}'`,
|
|
1064
|
+
Fields: ['CollectionID', 'CanRead', 'CanEdit', 'CanDelete', 'CanShare'],
|
|
1065
|
+
IgnoreMaxRows: true,
|
|
1066
|
+
SkipTotalRowCount: true,
|
|
1067
|
+
BypassCache: true,
|
|
1068
|
+
ResultType: 'simple'
|
|
1069
|
+
}));
|
|
1070
|
+
const permResults = await runBatch(permQueries);
|
|
1071
|
+
const permsByNormColId = new Map();
|
|
1072
|
+
const unkeyedPermRows = [];
|
|
1073
|
+
for (const res of permResults) {
|
|
1074
|
+
if (!res?.Success && strictThrowOnQueryError) {
|
|
1075
|
+
throw new Error(res?.ErrorMessage || `Failed loading collection permissions for ${contextLabel}.`);
|
|
1076
|
+
}
|
|
1077
|
+
if (!res?.Success || !res.Results) {
|
|
1078
|
+
continue;
|
|
1079
|
+
}
|
|
1080
|
+
for (const row of res.Results) {
|
|
1081
|
+
if (row.CollectionID) {
|
|
1082
|
+
const normColId = NormalizeUUID(row.CollectionID);
|
|
1083
|
+
let list = permsByNormColId.get(normColId);
|
|
1084
|
+
if (!list) {
|
|
1085
|
+
list = [];
|
|
1086
|
+
permsByNormColId.set(normColId, list);
|
|
1087
|
+
}
|
|
1088
|
+
list.push(row);
|
|
1089
|
+
}
|
|
1090
|
+
else if (artifactsNeedingCollections.size === 1) {
|
|
1091
|
+
unkeyedPermRows.push(row);
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
// 4. Assemble each artifact's effective collection permission rows in memory (cycle-guarded, depth-bounded)
|
|
1096
|
+
for (const [normArtId, directColNorms] of directColsByNormArtifactId.entries()) {
|
|
1097
|
+
const artRows = [...unkeyedPermRows];
|
|
1098
|
+
const visitedForArt = new Set();
|
|
1099
|
+
let artFrontier = Array.from(directColNorms);
|
|
1100
|
+
for (let level = 0; level < MAX_COLLECTION_ANCESTRY_DEPTH && artFrontier.length > 0; level++) {
|
|
1101
|
+
const nextArtFrontier = [];
|
|
1102
|
+
for (const normColId of artFrontier) {
|
|
1103
|
+
if (visitedForArt.has(normColId)) {
|
|
1104
|
+
continue;
|
|
1105
|
+
}
|
|
1106
|
+
visitedForArt.add(normColId);
|
|
1107
|
+
const col = collectionMetaByNormId.get(normColId);
|
|
1108
|
+
if (col?.OwnerID && UUIDsEqual(col.OwnerID, user.ID)) {
|
|
1109
|
+
artRows.push({
|
|
1110
|
+
CollectionID: col.ID,
|
|
1111
|
+
CanRead: true,
|
|
1112
|
+
CanEdit: true,
|
|
1113
|
+
CanDelete: true,
|
|
1114
|
+
CanShare: true
|
|
1115
|
+
});
|
|
1116
|
+
}
|
|
1117
|
+
const colPermRows = permsByNormColId.get(normColId);
|
|
1118
|
+
if (colPermRows) {
|
|
1119
|
+
artRows.push(...colPermRows);
|
|
1120
|
+
}
|
|
1121
|
+
if (level + 1 < MAX_COLLECTION_ANCESTRY_DEPTH && col?.ParentID?.trim()) {
|
|
1122
|
+
const normParent = NormalizeUUID(col.ParentID.trim());
|
|
1123
|
+
if (!visitedForArt.has(normParent)) {
|
|
1124
|
+
nextArtFrontier.push(normParent);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
artFrontier = nextArtFrontier;
|
|
1129
|
+
}
|
|
1130
|
+
resultByNormArtifactId.set(normArtId, artRows);
|
|
1131
|
+
}
|
|
1132
|
+
return resultByNormArtifactId;
|
|
1133
|
+
}
|
|
1134
|
+
catch (err) {
|
|
1135
|
+
LogError(`ArtifactPermissionEngine.loadCollectionPermissionRows error for ${contextLabel} (user '${user.ID}'): ${err instanceof Error ? err.message : String(err)}`);
|
|
1136
|
+
if (strictThrowOnQueryError) {
|
|
1137
|
+
throw err;
|
|
1138
|
+
}
|
|
1139
|
+
return resultByNormArtifactId;
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
async evaluateCustomDelegateDecisions(provider, delegate, artifact, delegateEntityId, delegateEntityName, delegateRecordId, user, depth, visited, memo) {
|
|
1143
|
+
const context = {
|
|
1144
|
+
ArtifactID: artifact.ID,
|
|
1145
|
+
ArtifactOwnerUserID: artifact.UserID,
|
|
1146
|
+
DelegateEntityID: delegateEntityId,
|
|
1147
|
+
DelegateEntityName: delegateEntityName,
|
|
1148
|
+
DelegateRecordID: delegateRecordId,
|
|
1149
|
+
Provider: provider,
|
|
1150
|
+
Depth: depth,
|
|
1151
|
+
VisitedArtifactIDs: visited,
|
|
1152
|
+
Memo: memo
|
|
1153
|
+
};
|
|
1154
|
+
const [readDec, editDec, deleteDec, shareDec] = await Promise.all([
|
|
1155
|
+
delegate.CanRead(context, user),
|
|
1156
|
+
delegate.CanEdit(context, user),
|
|
1157
|
+
delegate.CanDelete ? delegate.CanDelete(context, user) : Promise.resolve('Defer'),
|
|
1158
|
+
delegate.CanShare ? delegate.CanShare(context, user) : Promise.resolve('Defer')
|
|
1159
|
+
]);
|
|
1160
|
+
const normRead = normalizeDecision(readDec);
|
|
1161
|
+
const normEdit = normalizeDecision(editDec);
|
|
1162
|
+
const normDelete = normalizeDecision(deleteDec);
|
|
1163
|
+
const normShare = normalizeDecision(shareDec);
|
|
1164
|
+
const needsFallback = normRead !== 'Deny' &&
|
|
1165
|
+
(normRead === 'Defer' || normEdit === 'Defer' || normDelete === 'Defer' || normShare === 'Defer');
|
|
1166
|
+
return {
|
|
1167
|
+
NormRead: normRead,
|
|
1168
|
+
NormEdit: normEdit,
|
|
1169
|
+
NormDelete: normDelete,
|
|
1170
|
+
NormShare: normShare,
|
|
1171
|
+
NeedsFallback: needsFallback
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
finalizeCustomDelegateDecisions(artifact, delegateEntityId, delegateEntityName, delegateRecordId, decisions, user, directRows, collectionRows) {
|
|
1175
|
+
const { NormRead: normRead, NormEdit: normEdit, NormDelete: normDelete, NormShare: normShare } = decisions;
|
|
1176
|
+
// If every action deferred, fall through to owner / MJ: Artifact Permissions / Collection Permissions.
|
|
1177
|
+
if (normRead === 'Defer' && normEdit === 'Defer' && normDelete === 'Defer' && normShare === 'Defer') {
|
|
1178
|
+
return this.evaluateNonDelegatedArtifact(artifact, user, directRows, collectionRows);
|
|
1179
|
+
}
|
|
1180
|
+
// If the delegate explicitly denied Read, deny all actions immediately.
|
|
1181
|
+
if (normRead === 'Deny') {
|
|
1182
|
+
return this.buildDenied(artifact.ID, `Access denied by delegate entity '${delegateEntityName || delegateEntityId}' (${delegateRecordId}).`);
|
|
1183
|
+
}
|
|
1184
|
+
// For any individual action that returned 'Defer', combine with fallback (owner + direct + collection grants).
|
|
1185
|
+
const isOwner = Boolean(artifact.UserID && UUIDsEqual(artifact.UserID, user.ID));
|
|
1186
|
+
let fallbackEdit = isOwner;
|
|
1187
|
+
let fallbackDelete = isOwner;
|
|
1188
|
+
let fallbackShare = isOwner;
|
|
1189
|
+
let fallbackRead = isOwner;
|
|
1190
|
+
if (!isOwner && (normRead === 'Defer' || normEdit === 'Defer' || normDelete === 'Defer' || normShare === 'Defer')) {
|
|
1191
|
+
const fallbackRows = [...directRows, ...collectionRows];
|
|
1192
|
+
fallbackEdit = fallbackRows.some((r) => Boolean(r.CanEdit));
|
|
1193
|
+
fallbackDelete = fallbackRows.some((r) => Boolean(r.CanDelete));
|
|
1194
|
+
fallbackShare = fallbackRows.some((r) => Boolean(r.CanShare));
|
|
1195
|
+
fallbackRead = fallbackRows.some((r) => Boolean(r.CanRead)) || fallbackEdit || fallbackDelete || fallbackShare;
|
|
1196
|
+
}
|
|
1197
|
+
const canEdit = normEdit === 'Allow' ? true : normEdit === 'Deny' ? false : fallbackEdit;
|
|
1198
|
+
const canDelete = normDelete === 'Allow' ? true : normDelete === 'Deny' ? false : fallbackDelete;
|
|
1199
|
+
const canShare = normShare === 'Allow' ? true : normShare === 'Deny' ? false : fallbackShare;
|
|
1200
|
+
const canRead = normRead === 'Allow' ? true : fallbackRead || canEdit || canDelete || canShare;
|
|
1201
|
+
return {
|
|
1202
|
+
ArtifactID: artifact.ID,
|
|
1203
|
+
CanRead: canRead,
|
|
1204
|
+
CanEdit: canEdit,
|
|
1205
|
+
CanDelete: canDelete,
|
|
1206
|
+
CanShare: canShare,
|
|
1207
|
+
Source: canRead ? 'Delegate' : 'Denied',
|
|
1208
|
+
Reason: canRead
|
|
1209
|
+
? `Permissions resolved via delegate '${delegateEntityName || delegateEntityId}' (${delegateRecordId}).`
|
|
1210
|
+
: `Access denied by delegate '${delegateEntityName || delegateEntityId}' (${delegateRecordId}).`
|
|
1211
|
+
};
|
|
1212
|
+
}
|
|
1213
|
+
resolveDelegateInstance(entityId, entityName) {
|
|
1214
|
+
const byId = this._delegatesByEntityKey.get(entityId.trim().toLowerCase());
|
|
1215
|
+
if (byId) {
|
|
1216
|
+
return byId;
|
|
1217
|
+
}
|
|
1218
|
+
if (entityName) {
|
|
1219
|
+
const byName = this._delegatesByEntityKey.get(entityName.trim().toLowerCase());
|
|
1220
|
+
if (byName) {
|
|
1221
|
+
return byName;
|
|
1222
|
+
}
|
|
1223
|
+
if (entityName.trim().toLowerCase() === 'mj: artifacts') {
|
|
1224
|
+
return new ParentArtifactPermissionDelegate();
|
|
1225
|
+
}
|
|
1226
|
+
const registered = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactPermissionDelegate, entityName);
|
|
1227
|
+
if (registered && registered.constructor !== BaseArtifactPermissionDelegate) {
|
|
1228
|
+
return registered;
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
return null;
|
|
1232
|
+
}
|
|
1233
|
+
/**
|
|
1234
|
+
* Resolves effective collection permissions for `(collectionId, user)` by walking `ParentID`
|
|
1235
|
+
* ancestry up to depth 16 (cycle-guarded) and unioning `OwnerID` ownership with direct and
|
|
1236
|
+
* ancestor `MJ: Collection Permissions` rows.
|
|
1237
|
+
*/
|
|
1238
|
+
async ResolveCollectionAncestryPermissions(provider, collectionId, user) {
|
|
1239
|
+
const targetId = (collectionId ?? '').trim();
|
|
1240
|
+
if (!provider || !targetId || !user?.ID) {
|
|
1241
|
+
return this.buildDeniedCollection(targetId, 'Missing provider, collectionId, or user context.');
|
|
1242
|
+
}
|
|
1243
|
+
if (user.IsMagicLinkAnonymous || user.MagicLinkScope) {
|
|
1244
|
+
return this.buildDeniedCollection(targetId, 'Scope-limited or anonymous magic-link principals cannot access governed collection permissions.');
|
|
1245
|
+
}
|
|
1246
|
+
if (!IsValidUUID(targetId) || !IsValidUUID(user.ID)) {
|
|
1247
|
+
return this.buildDeniedCollection(targetId, 'Collection ID and user ID must be valid UUIDs.');
|
|
1248
|
+
}
|
|
1249
|
+
try {
|
|
1250
|
+
const queryActor = await this.resolvePermissionQueryActor(provider, user, `collection '${targetId}'`);
|
|
1251
|
+
if (!queryActor) {
|
|
1252
|
+
return this.buildDeniedCollection(targetId, 'System user is unavailable for collection permission resolution.');
|
|
1253
|
+
}
|
|
1254
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
1255
|
+
const visited = new Set();
|
|
1256
|
+
const chainIds = [targetId];
|
|
1257
|
+
const directNormalized = NormalizeUUID(targetId);
|
|
1258
|
+
visited.add(directNormalized);
|
|
1259
|
+
let ownerMatchedDepth = null;
|
|
1260
|
+
let rootMissing = false;
|
|
1261
|
+
let currentId = targetId;
|
|
1262
|
+
for (let depth = 0; depth < MAX_COLLECTION_ANCESTRY_DEPTH && currentId; depth++) {
|
|
1263
|
+
if (!IsValidUUID(currentId)) {
|
|
1264
|
+
break;
|
|
1265
|
+
}
|
|
1266
|
+
const colParams = {
|
|
1267
|
+
EntityName: 'MJ: Collections',
|
|
1268
|
+
ExtraFilter: `ID='${EscapeSQLString(currentId)}'`,
|
|
1269
|
+
Fields: ['ID', 'OwnerID', 'ParentID'],
|
|
1270
|
+
IgnoreMaxRows: true,
|
|
1271
|
+
SkipTotalRowCount: true,
|
|
1272
|
+
ResultType: 'simple'
|
|
1273
|
+
};
|
|
1274
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(colParams);
|
|
1275
|
+
const colRes = await rv.RunView(colParams, queryActor);
|
|
1276
|
+
const row = colRes.Success && colRes.Results && colRes.Results.length > 0 ? colRes.Results[0] : null;
|
|
1277
|
+
if (!row) {
|
|
1278
|
+
if (depth === 0) {
|
|
1279
|
+
rootMissing = true;
|
|
1280
|
+
}
|
|
1281
|
+
break;
|
|
1282
|
+
}
|
|
1283
|
+
if (row.OwnerID && UUIDsEqual(row.OwnerID, user.ID)) {
|
|
1284
|
+
ownerMatchedDepth = depth;
|
|
1285
|
+
break;
|
|
1286
|
+
}
|
|
1287
|
+
if (depth + 1 >= MAX_COLLECTION_ANCESTRY_DEPTH) {
|
|
1288
|
+
break;
|
|
1289
|
+
}
|
|
1290
|
+
const nextParent = row.ParentID?.trim() || null;
|
|
1291
|
+
if (!nextParent || !IsValidUUID(nextParent)) {
|
|
1292
|
+
break;
|
|
1293
|
+
}
|
|
1294
|
+
const normParent = NormalizeUUID(nextParent);
|
|
1295
|
+
if (visited.has(normParent)) {
|
|
1296
|
+
break;
|
|
1297
|
+
}
|
|
1298
|
+
visited.add(normParent);
|
|
1299
|
+
chainIds.push(nextParent);
|
|
1300
|
+
currentId = nextParent;
|
|
1301
|
+
}
|
|
1302
|
+
if (rootMissing) {
|
|
1303
|
+
return this.buildDeniedCollection(targetId, `Collection '${targetId}' was not found.`);
|
|
1304
|
+
}
|
|
1305
|
+
if (ownerMatchedDepth !== null) {
|
|
1306
|
+
return {
|
|
1307
|
+
CollectionID: targetId,
|
|
1308
|
+
CanRead: true,
|
|
1309
|
+
CanEdit: true,
|
|
1310
|
+
CanDelete: true,
|
|
1311
|
+
CanShare: true,
|
|
1312
|
+
Source: ownerMatchedDepth === 0 ? 'Owner' : 'AncestorCollection',
|
|
1313
|
+
Reason: ownerMatchedDepth === 0
|
|
1314
|
+
? 'User is the owner of the collection.'
|
|
1315
|
+
: 'User is the owner of an ancestor collection.'
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
const safeUserId = EscapeSQLString(user.ID);
|
|
1319
|
+
const matchingRows = [];
|
|
1320
|
+
for (const idChunk of chunkArray(chainIds, IN_CLAUSE_CHUNK_SIZE)) {
|
|
1321
|
+
const permParams = {
|
|
1322
|
+
EntityName: 'MJ: Collection Permissions',
|
|
1323
|
+
ExtraFilter: `CollectionID IN (${buildQuotedInList(idChunk)}) AND UserID='${safeUserId}'`,
|
|
1324
|
+
Fields: ['CollectionID', 'CanRead', 'CanEdit', 'CanDelete', 'CanShare'],
|
|
1325
|
+
IgnoreMaxRows: true,
|
|
1326
|
+
SkipTotalRowCount: true,
|
|
1327
|
+
ResultType: 'simple'
|
|
1328
|
+
};
|
|
1329
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(permParams);
|
|
1330
|
+
const permResult = await rv.RunView(permParams, queryActor);
|
|
1331
|
+
if (permResult.Success && permResult.Results) {
|
|
1332
|
+
matchingRows.push(...permResult.Results);
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
const canEdit = matchingRows.some((r) => Boolean(r.CanEdit));
|
|
1336
|
+
const canDelete = matchingRows.some((r) => Boolean(r.CanDelete));
|
|
1337
|
+
const canShare = matchingRows.some((r) => Boolean(r.CanShare));
|
|
1338
|
+
const canRead = matchingRows.some((r) => Boolean(r.CanRead)) || canEdit || canDelete || canShare;
|
|
1339
|
+
if (!canRead) {
|
|
1340
|
+
return this.buildDeniedCollection(targetId, `User '${user.ID}' has no permission grant on collection '${targetId}'.`);
|
|
1341
|
+
}
|
|
1342
|
+
const hasDirectGrant = matchingRows.some((r) => (!r.CollectionID || NormalizeUUID(r.CollectionID) === directNormalized) &&
|
|
1343
|
+
(Boolean(r.CanRead) || Boolean(r.CanEdit) || Boolean(r.CanDelete) || Boolean(r.CanShare)));
|
|
1344
|
+
return {
|
|
1345
|
+
CollectionID: targetId,
|
|
1346
|
+
CanRead: canRead,
|
|
1347
|
+
CanEdit: canEdit,
|
|
1348
|
+
CanDelete: canDelete,
|
|
1349
|
+
CanShare: canShare,
|
|
1350
|
+
Source: hasDirectGrant ? 'CollectionPermission' : 'AncestorCollection',
|
|
1351
|
+
Reason: hasDirectGrant
|
|
1352
|
+
? 'Permissions granted via MJ: Collection Permissions.'
|
|
1353
|
+
: 'Permissions inherited from ancestor MJ: Collection Permissions.'
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
catch (err) {
|
|
1357
|
+
LogError(`ArtifactPermissionEngine.ResolveCollectionAncestryPermissions error for collection '${targetId}': ${err instanceof Error ? err.message : String(err)}`);
|
|
1358
|
+
return this.buildDeniedCollection(targetId, 'Collection permission resolution failed.');
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
/**
|
|
1362
|
+
* Builds the normalized (`NormalizeUUID`) set of all `CollectionID`s readable by `user`,
|
|
1363
|
+
* combining collection ownership, direct shares, and descendant collections (depth 16, cycle-guarded).
|
|
1364
|
+
*/
|
|
1365
|
+
async BuildReadableCollectionIdSet(provider, user) {
|
|
1366
|
+
const readable = new Set();
|
|
1367
|
+
if (!provider || !user?.ID || !IsValidUUID(user.ID)) {
|
|
1368
|
+
return readable;
|
|
1369
|
+
}
|
|
1370
|
+
if (user.IsMagicLinkAnonymous || user.MagicLinkScope) {
|
|
1371
|
+
return readable;
|
|
1372
|
+
}
|
|
1373
|
+
try {
|
|
1374
|
+
const queryActor = await this.resolvePermissionQueryActor(provider, user, 'BuildReadableCollectionIdSet');
|
|
1375
|
+
if (!queryActor) {
|
|
1376
|
+
return readable;
|
|
1377
|
+
}
|
|
1378
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
1379
|
+
const collectionIds = await this.collectReadableCollectionIds(rv, queryActor, user.ID);
|
|
1380
|
+
for (const cid of collectionIds) {
|
|
1381
|
+
const norm = NormalizeUUID(cid);
|
|
1382
|
+
if (norm) {
|
|
1383
|
+
readable.add(norm);
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
return readable;
|
|
1387
|
+
}
|
|
1388
|
+
catch (err) {
|
|
1389
|
+
LogError(`ArtifactPermissionEngine.BuildReadableCollectionIdSet error for user '${user.ID}': ${err instanceof Error ? err.message : String(err)}`);
|
|
1390
|
+
return readable;
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
/**
|
|
1394
|
+
* Same as {@link BuildReadableCollectionIdSet}, except returns `null` when underlying metadata/database
|
|
1395
|
+
* queries fail (`!res.Success` or missing actor) so SQL pre-filtering can fall back cleanly rather than
|
|
1396
|
+
* treating an unmocked failure as zero readable collections. Supports `requireShareOrDelete` (`B5`).
|
|
1397
|
+
*/
|
|
1398
|
+
async TryBuildReadableCollectionIdSet(provider, user, options) {
|
|
1399
|
+
const readable = new Set();
|
|
1400
|
+
if (!provider || !user?.ID || !IsValidUUID(user.ID)) {
|
|
1401
|
+
return readable;
|
|
1402
|
+
}
|
|
1403
|
+
if (user.IsMagicLinkAnonymous || user.MagicLinkScope) {
|
|
1404
|
+
return readable;
|
|
1405
|
+
}
|
|
1406
|
+
try {
|
|
1407
|
+
const queryActor = await this.resolvePermissionQueryActor(provider, user, 'TryBuildReadableCollectionIdSet');
|
|
1408
|
+
if (!queryActor) {
|
|
1409
|
+
return null;
|
|
1410
|
+
}
|
|
1411
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
1412
|
+
const collectionIds = await this.collectReadableCollectionIds(rv, queryActor, user.ID, true, options?.requireShareOrDelete === true);
|
|
1413
|
+
for (const cid of collectionIds) {
|
|
1414
|
+
const norm = NormalizeUUID(cid);
|
|
1415
|
+
if (norm) {
|
|
1416
|
+
readable.add(norm);
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
return readable;
|
|
1420
|
+
}
|
|
1421
|
+
catch {
|
|
1422
|
+
return null;
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
async collectReadableCollectionIds(rv, queryActor, userId, throwOnQueryFailure = false, requireShareOrDelete = false) {
|
|
1426
|
+
const safeUserId = EscapeSQLString(userId);
|
|
1427
|
+
const seedCollectionIds = [];
|
|
1428
|
+
const seenCollections = new Set();
|
|
1429
|
+
const addCollectionSeed = (id) => {
|
|
1430
|
+
if (!id || !IsValidUUID(id))
|
|
1431
|
+
return;
|
|
1432
|
+
const norm = NormalizeUUID(id);
|
|
1433
|
+
if (norm && !seenCollections.has(norm)) {
|
|
1434
|
+
seenCollections.add(norm);
|
|
1435
|
+
seedCollectionIds.push(id);
|
|
1436
|
+
}
|
|
1437
|
+
};
|
|
1438
|
+
const ownedColsParams = {
|
|
1439
|
+
EntityName: 'MJ: Collections',
|
|
1440
|
+
ExtraFilter: `OwnerID='${safeUserId}'`,
|
|
1441
|
+
Fields: ['ID'],
|
|
1442
|
+
IgnoreMaxRows: true,
|
|
1443
|
+
SkipTotalRowCount: true,
|
|
1444
|
+
ResultType: 'simple'
|
|
1445
|
+
};
|
|
1446
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(ownedColsParams);
|
|
1447
|
+
const sharedColsParams = {
|
|
1448
|
+
EntityName: 'MJ: Collection Permissions',
|
|
1449
|
+
ExtraFilter: requireShareOrDelete
|
|
1450
|
+
? `UserID='${safeUserId}' AND (CanShare=1 OR CanDelete=1)`
|
|
1451
|
+
: `UserID='${safeUserId}' AND (CanRead=1 OR CanEdit=1 OR CanDelete=1 OR CanShare=1)`,
|
|
1452
|
+
Fields: ['CollectionID'],
|
|
1453
|
+
IgnoreMaxRows: true,
|
|
1454
|
+
SkipTotalRowCount: true,
|
|
1455
|
+
ResultType: 'simple'
|
|
1456
|
+
};
|
|
1457
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(sharedColsParams);
|
|
1458
|
+
const [ownedColsRes, sharedColsRes] = await Promise.all([
|
|
1459
|
+
rv.RunView(ownedColsParams, queryActor),
|
|
1460
|
+
rv.RunView(sharedColsParams, queryActor)
|
|
1461
|
+
]);
|
|
1462
|
+
if (!ownedColsRes.Success && throwOnQueryFailure) {
|
|
1463
|
+
throw new Error(ownedColsRes.ErrorMessage || 'Failed querying owned collections.');
|
|
1464
|
+
}
|
|
1465
|
+
if (ownedColsRes.Success && ownedColsRes.Results) {
|
|
1466
|
+
for (const row of ownedColsRes.Results) {
|
|
1467
|
+
addCollectionSeed(row.ID);
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
if (!sharedColsRes.Success && throwOnQueryFailure) {
|
|
1471
|
+
throw new Error(sharedColsRes.ErrorMessage || 'Failed querying collection permissions.');
|
|
1472
|
+
}
|
|
1473
|
+
if (sharedColsRes.Success && sharedColsRes.Results) {
|
|
1474
|
+
for (const row of sharedColsRes.Results) {
|
|
1475
|
+
addCollectionSeed(row.CollectionID);
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
let frontier = [...seedCollectionIds];
|
|
1479
|
+
// Depth 0 is the seed collection; traverse at most MAX_COLLECTION_ANCESTRY_DEPTH - 1 child hops (16 levels 0..15, L1).
|
|
1480
|
+
for (let depth = 0; depth < MAX_COLLECTION_ANCESTRY_DEPTH - 1 && frontier.length > 0; depth++) {
|
|
1481
|
+
const nextFrontier = [];
|
|
1482
|
+
for (const chunk of chunkArray(frontier, IN_CLAUSE_CHUNK_SIZE)) {
|
|
1483
|
+
const childParams = {
|
|
1484
|
+
EntityName: 'MJ: Collections',
|
|
1485
|
+
ExtraFilter: `ParentID IN (${buildQuotedInList(chunk)})`,
|
|
1486
|
+
Fields: ['ID'],
|
|
1487
|
+
IgnoreMaxRows: true,
|
|
1488
|
+
SkipTotalRowCount: true,
|
|
1489
|
+
ResultType: 'simple'
|
|
1490
|
+
};
|
|
1491
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(childParams);
|
|
1492
|
+
const childRes = await rv.RunView(childParams, queryActor);
|
|
1493
|
+
if (!childRes.Success && throwOnQueryFailure) {
|
|
1494
|
+
throw new Error(childRes.ErrorMessage || 'Failed querying child collections.');
|
|
1495
|
+
}
|
|
1496
|
+
if (childRes.Success && childRes.Results) {
|
|
1497
|
+
for (const child of childRes.Results) {
|
|
1498
|
+
if (!child.ID || !IsValidUUID(child.ID))
|
|
1499
|
+
continue;
|
|
1500
|
+
const norm = NormalizeUUID(child.ID);
|
|
1501
|
+
if (norm && !seenCollections.has(norm)) {
|
|
1502
|
+
seenCollections.add(norm);
|
|
1503
|
+
seedCollectionIds.push(child.ID);
|
|
1504
|
+
nextFrontier.push(child.ID);
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
frontier = nextFrontier;
|
|
1510
|
+
}
|
|
1511
|
+
return seedCollectionIds;
|
|
1512
|
+
}
|
|
1513
|
+
/**
|
|
1514
|
+
* Builds the normalized (`NormalizeUUID`) set of all `ArtifactID`s readable by `user`,
|
|
1515
|
+
* combining artifact ownership, direct shares, and collection hierarchy grants (with full
|
|
1516
|
+
* delegate `'Deny'` enforcement via {@link ResolvePermissions}).
|
|
1517
|
+
*/
|
|
1518
|
+
async BuildReadableArtifactIdSet(provider, user, predicate) {
|
|
1519
|
+
const result = await this.buildReadableArtifactIdSetInternal(provider, user, predicate, false);
|
|
1520
|
+
return result ?? new Set();
|
|
1521
|
+
}
|
|
1522
|
+
/**
|
|
1523
|
+
* Same as {@link BuildReadableArtifactIdSet}, except returns `null` if ANY underlying query or
|
|
1524
|
+
* permission resolution fails so fail-closed SQL callers throw instead of treating partial errors
|
|
1525
|
+
* as an empty/truncated workspace (`R7-4`).
|
|
1526
|
+
*/
|
|
1527
|
+
async TryBuildReadableArtifactIdSet(provider, user, predicate) {
|
|
1528
|
+
return this.buildReadableArtifactIdSetInternal(provider, user, predicate, true);
|
|
1529
|
+
}
|
|
1530
|
+
async buildReadableArtifactIdSetInternal(provider, user, predicate, throwOnQueryFailure) {
|
|
1531
|
+
const readable = new Set();
|
|
1532
|
+
if (!provider || !user?.ID || !IsValidUUID(user.ID)) {
|
|
1533
|
+
return readable;
|
|
1534
|
+
}
|
|
1535
|
+
if (user.IsMagicLinkAnonymous || user.MagicLinkScope) {
|
|
1536
|
+
return readable;
|
|
1537
|
+
}
|
|
1538
|
+
try {
|
|
1539
|
+
const queryActor = await this.resolvePermissionQueryActor(provider, user, 'BuildReadableArtifactIdSet');
|
|
1540
|
+
if (!queryActor) {
|
|
1541
|
+
return throwOnQueryFailure ? null : readable;
|
|
1542
|
+
}
|
|
1543
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
1544
|
+
const safeUserId = EscapeSQLString(user.ID);
|
|
1545
|
+
const candidates = new Map();
|
|
1546
|
+
const addCandidate = (id) => {
|
|
1547
|
+
if (!id || !IsValidUUID(id))
|
|
1548
|
+
return;
|
|
1549
|
+
const norm = NormalizeUUID(id);
|
|
1550
|
+
if (norm && !candidates.has(norm)) {
|
|
1551
|
+
candidates.set(norm, id);
|
|
1552
|
+
}
|
|
1553
|
+
};
|
|
1554
|
+
// 1. Owned artifacts
|
|
1555
|
+
const ownedParams = {
|
|
1556
|
+
EntityName: 'MJ: Artifacts',
|
|
1557
|
+
ExtraFilter: `UserID='${safeUserId}'`,
|
|
1558
|
+
Fields: ['ID'],
|
|
1559
|
+
IgnoreMaxRows: true,
|
|
1560
|
+
SkipTotalRowCount: true,
|
|
1561
|
+
ResultType: 'simple'
|
|
1562
|
+
};
|
|
1563
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(ownedParams);
|
|
1564
|
+
const ownedRes = await rv.RunView(ownedParams, queryActor);
|
|
1565
|
+
if (!ownedRes.Success && throwOnQueryFailure) {
|
|
1566
|
+
throw new Error(ownedRes.ErrorMessage || 'Failed querying owned artifacts.');
|
|
1567
|
+
}
|
|
1568
|
+
if (ownedRes.Success && ownedRes.Results) {
|
|
1569
|
+
for (const row of ownedRes.Results) {
|
|
1570
|
+
addCandidate(row.ID);
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
// 2. Directly shared artifacts
|
|
1574
|
+
const directParams = {
|
|
1575
|
+
EntityName: 'MJ: Artifact Permissions',
|
|
1576
|
+
ExtraFilter: `UserID='${safeUserId}' AND (CanRead=1 OR CanEdit=1 OR CanDelete=1 OR CanShare=1)`,
|
|
1577
|
+
Fields: ['ArtifactID'],
|
|
1578
|
+
IgnoreMaxRows: true,
|
|
1579
|
+
SkipTotalRowCount: true,
|
|
1580
|
+
ResultType: 'simple'
|
|
1581
|
+
};
|
|
1582
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(directParams);
|
|
1583
|
+
const directRes = await rv.RunView(directParams, queryActor);
|
|
1584
|
+
if (!directRes.Success && throwOnQueryFailure) {
|
|
1585
|
+
throw new Error(directRes.ErrorMessage || 'Failed querying direct artifact permissions.');
|
|
1586
|
+
}
|
|
1587
|
+
if (directRes.Success && directRes.Results) {
|
|
1588
|
+
for (const row of directRes.Results) {
|
|
1589
|
+
addCandidate(row.ArtifactID);
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
// 3. Owned collections + shared collections + descendant collections (depth 16, cycle-guarded)
|
|
1593
|
+
const seedCollectionIds = await this.collectReadableCollectionIds(rv, queryActor, user.ID, throwOnQueryFailure);
|
|
1594
|
+
if (seedCollectionIds.length > 0) {
|
|
1595
|
+
const versionIdSet = new Set();
|
|
1596
|
+
const versionIds = [];
|
|
1597
|
+
for (const colChunk of chunkArray(seedCollectionIds, IN_CLAUSE_CHUNK_SIZE)) {
|
|
1598
|
+
const colArtParams = {
|
|
1599
|
+
EntityName: 'MJ: Collection Artifacts',
|
|
1600
|
+
ExtraFilter: `CollectionID IN (${buildQuotedInList(colChunk)})`,
|
|
1601
|
+
Fields: ['ArtifactVersionID'],
|
|
1602
|
+
IgnoreMaxRows: true,
|
|
1603
|
+
SkipTotalRowCount: true,
|
|
1604
|
+
ResultType: 'simple'
|
|
1605
|
+
};
|
|
1606
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(colArtParams);
|
|
1607
|
+
const colArtRes = await rv.RunView(colArtParams, queryActor);
|
|
1608
|
+
if (!colArtRes.Success && throwOnQueryFailure) {
|
|
1609
|
+
throw new Error(colArtRes.ErrorMessage || 'Failed querying collection artifact memberships.');
|
|
1610
|
+
}
|
|
1611
|
+
if (colArtRes.Success && colArtRes.Results) {
|
|
1612
|
+
for (const row of colArtRes.Results) {
|
|
1613
|
+
const vid = row.ArtifactVersionID;
|
|
1614
|
+
if (vid) {
|
|
1615
|
+
const norm = NormalizeUUID(vid);
|
|
1616
|
+
if (!versionIdSet.has(norm)) {
|
|
1617
|
+
versionIdSet.add(norm);
|
|
1618
|
+
versionIds.push(vid);
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
for (const verChunk of chunkArray(versionIds, IN_CLAUSE_CHUNK_SIZE)) {
|
|
1625
|
+
const verParams = {
|
|
1626
|
+
EntityName: 'MJ: Artifact Versions',
|
|
1627
|
+
ExtraFilter: `ID IN (${buildQuotedInList(verChunk)})`,
|
|
1628
|
+
Fields: ['ID', 'ArtifactID'],
|
|
1629
|
+
IgnoreMaxRows: true,
|
|
1630
|
+
SkipTotalRowCount: true,
|
|
1631
|
+
ResultType: 'simple'
|
|
1632
|
+
};
|
|
1633
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(verParams);
|
|
1634
|
+
const verRes = await rv.RunView(verParams, queryActor);
|
|
1635
|
+
if (!verRes.Success && throwOnQueryFailure) {
|
|
1636
|
+
throw new Error(verRes.ErrorMessage || 'Failed querying collection artifact versions.');
|
|
1637
|
+
}
|
|
1638
|
+
if (verRes.Success && verRes.Results) {
|
|
1639
|
+
for (const row of verRes.Results) {
|
|
1640
|
+
addCandidate(row.ArtifactID);
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
// 3b. Expand child artifacts delegated to any candidate artifact via DelegateEntityID -> 'MJ: Artifacts'
|
|
1646
|
+
const artifactsEntityId = provider.EntityByName?.('MJ: Artifacts')?.ID;
|
|
1647
|
+
if (artifactsEntityId && IsValidUUID(artifactsEntityId) && candidates.size > 0) {
|
|
1648
|
+
const safeArtifactsEntityId = EscapeSQLString(artifactsEntityId);
|
|
1649
|
+
let delegateFrontier = Array.from(candidates.values());
|
|
1650
|
+
for (let hop = 0; hop < MAX_DELEGATE_DEPTH && delegateFrontier.length > 0; hop++) {
|
|
1651
|
+
const nextDelegateFrontier = [];
|
|
1652
|
+
for (const parentChunk of chunkArray(delegateFrontier, IN_CLAUSE_CHUNK_SIZE)) {
|
|
1653
|
+
const childArtParams = {
|
|
1654
|
+
EntityName: 'MJ: Artifacts',
|
|
1655
|
+
ExtraFilter: `DelegateEntityID='${safeArtifactsEntityId}' AND DelegateRecordID IN (${buildQuotedInList(parentChunk)})`,
|
|
1656
|
+
Fields: ['ID'],
|
|
1657
|
+
IgnoreMaxRows: true,
|
|
1658
|
+
SkipTotalRowCount: true,
|
|
1659
|
+
ResultType: 'simple'
|
|
1660
|
+
};
|
|
1661
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(childArtParams);
|
|
1662
|
+
const childArtRes = await rv.RunView(childArtParams, queryActor);
|
|
1663
|
+
if (!childArtRes.Success && throwOnQueryFailure) {
|
|
1664
|
+
throw new Error(childArtRes.ErrorMessage || 'Failed querying parent-delegated artifacts.');
|
|
1665
|
+
}
|
|
1666
|
+
if (childArtRes.Success && childArtRes.Results) {
|
|
1667
|
+
for (const row of childArtRes.Results) {
|
|
1668
|
+
if (row.ID && IsValidUUID(row.ID)) {
|
|
1669
|
+
const norm = NormalizeUUID(row.ID);
|
|
1670
|
+
if (!candidates.has(norm)) {
|
|
1671
|
+
candidates.set(norm, row.ID);
|
|
1672
|
+
nextDelegateFrontier.push(row.ID);
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
delegateFrontier = nextDelegateFrontier;
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
// 3c. Only scan non-'MJ: Artifacts' delegated artifacts for entities that actually have a custom delegate registered (`S-g`).
|
|
1682
|
+
const customDelegateKeys = Array.from(this._delegatesByEntityKey.keys()).filter((k) => k !== 'mj: artifacts');
|
|
1683
|
+
if (customDelegateKeys.length > 0) {
|
|
1684
|
+
const customEntityIds = [];
|
|
1685
|
+
for (const key of customDelegateKeys) {
|
|
1686
|
+
if (IsValidUUID(key)) {
|
|
1687
|
+
customEntityIds.push(key);
|
|
1688
|
+
}
|
|
1689
|
+
else {
|
|
1690
|
+
const entInfo = provider.EntityByName?.(key) ??
|
|
1691
|
+
provider.Entities?.find((e) => e.Name.trim().toLowerCase() === key);
|
|
1692
|
+
if (entInfo?.ID && IsValidUUID(entInfo.ID)) {
|
|
1693
|
+
customEntityIds.push(entInfo.ID);
|
|
1694
|
+
}
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
for (const idChunk of chunkArray(customEntityIds, IN_CLAUSE_CHUNK_SIZE)) {
|
|
1698
|
+
const customDelegParams = {
|
|
1699
|
+
EntityName: 'MJ: Artifacts',
|
|
1700
|
+
ExtraFilter: `DelegateEntityID IN (${buildQuotedInList(idChunk)})`,
|
|
1701
|
+
Fields: ['ID'],
|
|
1702
|
+
IgnoreMaxRows: true,
|
|
1703
|
+
SkipTotalRowCount: true,
|
|
1704
|
+
ResultType: 'simple'
|
|
1705
|
+
};
|
|
1706
|
+
ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(customDelegParams);
|
|
1707
|
+
const customDelegRes = await rv.RunView(customDelegParams, queryActor);
|
|
1708
|
+
if (!customDelegRes.Success && throwOnQueryFailure) {
|
|
1709
|
+
throw new Error(customDelegRes.ErrorMessage || 'Failed querying custom-delegated artifacts.');
|
|
1710
|
+
}
|
|
1711
|
+
if (customDelegRes.Success && customDelegRes.Results) {
|
|
1712
|
+
for (const row of customDelegRes.Results) {
|
|
1713
|
+
addCandidate(row.ID);
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
// 4. Verify all candidates in one batched ResolvePermissionsBatch call (chunked internally at
|
|
1719
|
+
// IN_CLAUSE_CHUNK_SIZE) so delegate 'Deny' overrides are honored in O(1) round trips.
|
|
1720
|
+
const candidateValues = Array.from(candidates.entries());
|
|
1721
|
+
if (candidateValues.length > 0) {
|
|
1722
|
+
const resolveMemo = new Map();
|
|
1723
|
+
const resolvedBatch = await this.ResolvePermissionsBatch(provider, candidateValues.map(([, rawId]) => rawId), user, 0, undefined, resolveMemo, throwOnQueryFailure);
|
|
1724
|
+
for (const [normId, rawId] of candidateValues) {
|
|
1725
|
+
const perms = resolvedBatch.get(rawId);
|
|
1726
|
+
if (perms && perms.CanRead) {
|
|
1727
|
+
const matches = predicate ? predicate(perms) : perms.CanRead;
|
|
1728
|
+
if (matches) {
|
|
1729
|
+
readable.add(normId);
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
return readable;
|
|
1735
|
+
}
|
|
1736
|
+
catch (err) {
|
|
1737
|
+
LogError(`ArtifactPermissionEngine.BuildReadableArtifactIdSet error for user '${user.ID}': ${err instanceof Error ? err.message : String(err)}`);
|
|
1738
|
+
return throwOnQueryFailure ? null : readable;
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
async resolvePermissionQueryActor(provider, user, contextLabel) {
|
|
1742
|
+
if (provider.ProviderType === 'Database') {
|
|
1743
|
+
const systemUser = await WellKnownUserSource.Instance.GetSystemUser(provider);
|
|
1744
|
+
if (!systemUser) {
|
|
1745
|
+
LogError(`ArtifactPermissionEngine skipped lookup for ${contextLabel}: system user is unavailable on Database provider.`);
|
|
1746
|
+
return null;
|
|
1747
|
+
}
|
|
1748
|
+
return systemUser;
|
|
1749
|
+
}
|
|
1750
|
+
return user;
|
|
1751
|
+
}
|
|
1752
|
+
buildDeniedCollection(collectionId, reason) {
|
|
1753
|
+
return {
|
|
1754
|
+
CollectionID: collectionId,
|
|
1755
|
+
CanRead: false,
|
|
1756
|
+
CanEdit: false,
|
|
1757
|
+
CanDelete: false,
|
|
1758
|
+
CanShare: false,
|
|
1759
|
+
Source: 'Denied',
|
|
1760
|
+
Reason: reason
|
|
1761
|
+
};
|
|
1762
|
+
}
|
|
1763
|
+
buildDenied(artifactId, reason) {
|
|
1764
|
+
return {
|
|
1765
|
+
ArtifactID: artifactId,
|
|
1766
|
+
CanRead: false,
|
|
1767
|
+
CanEdit: false,
|
|
1768
|
+
CanDelete: false,
|
|
1769
|
+
CanShare: false,
|
|
1770
|
+
Source: 'Denied',
|
|
1771
|
+
Reason: reason
|
|
1772
|
+
};
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
/** Tree-shaking prevention loader for {@link ParentArtifactPermissionDelegate}. */
|
|
1776
|
+
export function LoadArtifactPermissionDelegates() {
|
|
1777
|
+
// Intentionally empty — ensures @RegisterClass decorators in this module execute.
|
|
1778
|
+
}
|
|
1779
|
+
//# sourceMappingURL=ArtifactPermissionDelegate.js.map
|