@milaboratories/pl-middle-layer 1.64.42 → 1.65.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/middle_layer/middle_layer.cjs +41 -2
- package/dist/middle_layer/middle_layer.cjs.map +1 -1
- package/dist/middle_layer/middle_layer.d.ts +19 -0
- package/dist/middle_layer/middle_layer.d.ts.map +1 -1
- package/dist/middle_layer/middle_layer.js +43 -4
- package/dist/middle_layer/middle_layer.js.map +1 -1
- package/dist/middle_layer/project_list.cjs +19 -0
- package/dist/middle_layer/project_list.cjs.map +1 -1
- package/dist/middle_layer/project_list.d.ts +1 -1
- package/dist/middle_layer/project_list.d.ts.map +1 -1
- package/dist/middle_layer/project_list.js +20 -2
- package/dist/middle_layer/project_list.js.map +1 -1
- package/dist/model/index.cjs +1 -0
- package/dist/model/index.d.ts +2 -2
- package/dist/model/index.js +2 -2
- package/dist/model/sharing_model.cjs +17 -0
- package/dist/model/sharing_model.cjs.map +1 -1
- package/dist/model/sharing_model.d.ts +11 -1
- package/dist/model/sharing_model.d.ts.map +1 -1
- package/dist/model/sharing_model.js +17 -1
- package/dist/model/sharing_model.js.map +1 -1
- package/package.json +10 -10
- package/src/middle_layer/middle_layer.ts +72 -2
- package/src/middle_layer/project_list.ts +33 -2
- package/src/model/sharing_model.test.ts +22 -0
- package/src/model/sharing_model.ts +19 -0
package/dist/index.cjs
CHANGED
|
@@ -69,6 +69,7 @@ exports.acceptanceFieldLogin = require_sharing_model.acceptanceFieldLogin;
|
|
|
69
69
|
exports.asShareId = require_sharing_model.asShareId;
|
|
70
70
|
exports.cacheBlockPackTemplate = require_template_cache.cacheBlockPackTemplate;
|
|
71
71
|
exports.canGrantToEveryone = require_sharing_model.canGrantToEveryone;
|
|
72
|
+
exports.canImpersonate = require_sharing_model.canImpersonate;
|
|
72
73
|
exports.checkNetwork = require_network_check.checkNetwork;
|
|
73
74
|
exports.createRenderTemplate = require_render_template.createRenderTemplate;
|
|
74
75
|
exports.decisionField = require_sharing_model.decisionField;
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { V2RegistryProvider } from "./block_registry/registry-v2-provider.js";
|
|
|
2
2
|
import { BlockPackRegistry, getDevV1PacketMtime, getDevV2PacketMtime, getFromPackV2Mtime } from "./block_registry/registry.js";
|
|
3
3
|
import { CentralBlockRegistry, V1CentralDevSnapshotRegistry, V1CentralRegistry } from "./block_registry/well_known_registries.js";
|
|
4
4
|
import { BlockArgsAuthorKeyPrefix, ProjectCreatedTimestamp, ProjectField, ProjectId, ProjectLastModifiedTimestamp, ProjectListEntry, ProjectMetaKey, ProjectResourceType, ProjectStructureAuthorKey, ProjectStructureKey, SchemaVersionCurrent, SchemaVersionKey } from "./model/project_model.js";
|
|
5
|
-
import { AcceptanceFieldPrefix, EnvelopeAcceptance, EnvelopeData, EnvelopeMode, EnvelopeProject, ProjectChangeAction, ProjectFieldUuid, ShareId, ShareProjectsOptions, SharedEnvelopeResourceType, SharingDecision, SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, acceptanceField, acceptanceFieldLogin, asShareId, canGrantToEveryone, decisionField, decodeEnvelopeData, isAcceptanceField, newShareId } from "./model/sharing_model.js";
|
|
5
|
+
import { AcceptanceFieldPrefix, EnvelopeAcceptance, EnvelopeData, EnvelopeMode, EnvelopeProject, ProjectChangeAction, ProjectFieldUuid, ShareId, ShareProjectsOptions, SharedEnvelopeResourceType, SharingDecision, SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, acceptanceField, acceptanceFieldLogin, asShareId, canGrantToEveryone, canImpersonate, decisionField, decodeEnvelopeData, isAcceptanceField, newShareId } from "./model/sharing_model.js";
|
|
6
6
|
import { OutgoingShare, PendingShare } from "./middle_layer/sharing_list.js";
|
|
7
7
|
import { CachedTemplate, ExplicitTemplate, PreparedTemplate, TemplateFromFile, TemplateFromRegistry, TemplateSpecAny, TemplateSpecPrepared } from "./model/template_spec.js";
|
|
8
8
|
import { BlockPackExplicit, BlockPackSpecAny, BlockPackSpecPrepared, FrontendFromFolder, FrontendFromFolderData, FrontendFromFolderResourceType, FrontendFromLocalTgz, FrontendFromLocalTgzData, FrontendFromLocalTgzResourceType, FrontendFromUrl, FrontendFromUrlData, FrontendFromUrlResourceType, FrontendSpec } from "./model/block_pack_spec.js";
|
|
@@ -24,4 +24,4 @@ export * from "@platforma-sdk/model";
|
|
|
24
24
|
export * from "@milaboratories/pl-model-middle-layer";
|
|
25
25
|
export * from "@milaboratories/pl-deployments";
|
|
26
26
|
export * from "@milaboratories/pl-client";
|
|
27
|
-
export { ACCESS_COUNT_KEY, ACCESS_KEY_PREFIX, AcceptanceFieldPrefix, BlockArgsAuthorKeyPrefix, BlockPackExplicit, BlockPackRegistry, BlockPackSpecAny, BlockPackSpecPrepared, CachedTemplate, CentralBlockRegistry, CheckNetworkOpts, DefaultDriverKitOpsPaths, DefaultDriverKitOpsSettings, DefaultMiddleLayerOpsPaths, DefaultMiddleLayerOpsSettings, DriverKitOps, DriverKitOpsConstructor, DriverKitOpsPaths, DriverKitOpsSettings, EnvelopeAcceptance, EnvelopeData, EnvelopeMode, EnvelopeProject, ExplicitTemplate, type FieldType, FrontendFromFolder, FrontendFromFolderData, FrontendFromFolderResourceType, FrontendFromLocalTgz, FrontendFromLocalTgzData, FrontendFromLocalTgzResourceType, FrontendFromUrl, FrontendFromUrlData, FrontendFromUrlResourceType, FrontendSpec, GC_ACCESS_THRESHOLD, GC_MAX_ENTRIES, type InternalLsDriver, MiddleLayer, MiddleLayerDebugOptions, MiddleLayerDriverKit, MiddleLayerOps, MiddleLayerOpsConstructor, MiddleLayerOpsPaths, MiddleLayerOpsSettings, type OutgoingShare, type PendingShare, PreparedTemplate, Project, ProjectChangeAction, ProjectCreatedTimestamp, type ProjectField, ProjectFieldUuid, type ProjectId, ProjectLastModifiedTimestamp, type ProjectListEntry, ProjectMetaKey, ProjectResourceType, ProjectStructureAuthorKey, ProjectStructureKey, ProjectsField, type ResourceType, SchemaVersionCurrent, SchemaVersionKey, ShareId, ShareProjectsOptions, SharedEnvelopeResourceType, SharingDecision, SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, TemplateCacheFieldName, TemplateCacheStat, TemplateCacheType, TemplateFromFile, TemplateFromRegistry, TemplateSpecAny, TemplateSpecPrepared, TengoTemplateGet, TengoTemplateGetRegistry, TengoTemplateGetTemplate, TengoTemplateGetTemplateURI, TengoTemplatePack, TengoTemplatePackConvert, TengoTemplatePackConvertTemplate, TengoTemplatePackConvertTemplatePack, V1CentralDevSnapshotRegistry, V1CentralRegistry, V2RegistryProvider, acceptanceField, acceptanceFieldLogin, asShareId, cacheBlockPackTemplate, canGrantToEveryone, checkNetwork, createRenderTemplate, decisionField, decodeEnvelopeData, deriveGlobalPObjectId, deriveLocalPObjectId, dropTemplateCache, duplicateProject, flattenTemplateTree, getDevV1PacketMtime, getDevV2PacketMtime, getFromPackV2Mtime, getOrCreateTemplateCache, initDriverKit, initNetworkCheck, invalidateTemplateCacheId, isAcceptanceField, loadTemplate, loadTemplateCached, newShareId, parseFinalPObjectCollection, prepareTemplateSpec, runGc };
|
|
27
|
+
export { ACCESS_COUNT_KEY, ACCESS_KEY_PREFIX, AcceptanceFieldPrefix, BlockArgsAuthorKeyPrefix, BlockPackExplicit, BlockPackRegistry, BlockPackSpecAny, BlockPackSpecPrepared, CachedTemplate, CentralBlockRegistry, CheckNetworkOpts, DefaultDriverKitOpsPaths, DefaultDriverKitOpsSettings, DefaultMiddleLayerOpsPaths, DefaultMiddleLayerOpsSettings, DriverKitOps, DriverKitOpsConstructor, DriverKitOpsPaths, DriverKitOpsSettings, EnvelopeAcceptance, EnvelopeData, EnvelopeMode, EnvelopeProject, ExplicitTemplate, type FieldType, FrontendFromFolder, FrontendFromFolderData, FrontendFromFolderResourceType, FrontendFromLocalTgz, FrontendFromLocalTgzData, FrontendFromLocalTgzResourceType, FrontendFromUrl, FrontendFromUrlData, FrontendFromUrlResourceType, FrontendSpec, GC_ACCESS_THRESHOLD, GC_MAX_ENTRIES, type InternalLsDriver, MiddleLayer, MiddleLayerDebugOptions, MiddleLayerDriverKit, MiddleLayerOps, MiddleLayerOpsConstructor, MiddleLayerOpsPaths, MiddleLayerOpsSettings, type OutgoingShare, type PendingShare, PreparedTemplate, Project, ProjectChangeAction, ProjectCreatedTimestamp, type ProjectField, ProjectFieldUuid, type ProjectId, ProjectLastModifiedTimestamp, type ProjectListEntry, ProjectMetaKey, ProjectResourceType, ProjectStructureAuthorKey, ProjectStructureKey, ProjectsField, type ResourceType, SchemaVersionCurrent, SchemaVersionKey, ShareId, ShareProjectsOptions, SharedEnvelopeResourceType, SharingDecision, SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, TemplateCacheFieldName, TemplateCacheStat, TemplateCacheType, TemplateFromFile, TemplateFromRegistry, TemplateSpecAny, TemplateSpecPrepared, TengoTemplateGet, TengoTemplateGetRegistry, TengoTemplateGetTemplate, TengoTemplateGetTemplateURI, TengoTemplatePack, TengoTemplatePackConvert, TengoTemplatePackConvertTemplate, TengoTemplatePackConvertTemplatePack, V1CentralDevSnapshotRegistry, V1CentralRegistry, V2RegistryProvider, acceptanceField, acceptanceFieldLogin, asShareId, cacheBlockPackTemplate, canGrantToEveryone, canImpersonate, checkNetwork, createRenderTemplate, decisionField, decodeEnvelopeData, deriveGlobalPObjectId, deriveLocalPObjectId, dropTemplateCache, duplicateProject, flattenTemplateTree, getDevV1PacketMtime, getDevV2PacketMtime, getFromPackV2Mtime, getOrCreateTemplateCache, initDriverKit, initNetworkCheck, invalidateTemplateCacheId, isAcceptanceField, loadTemplate, loadTemplateCached, newShareId, parseFinalPObjectCollection, prepareTemplateSpec, runGc };
|
package/dist/index.js
CHANGED
|
@@ -7,7 +7,7 @@ import { ProjectsField } from "./middle_layer/project_list.js";
|
|
|
7
7
|
import { createRenderTemplate } from "./mutator/template/render_template.js";
|
|
8
8
|
import { TengoTemplateGet, TengoTemplateGetRegistry, TengoTemplateGetTemplate, TengoTemplateGetTemplateURI, TengoTemplatePack, TengoTemplatePackConvert, TengoTemplatePackConvertTemplate, TengoTemplatePackConvertTemplatePack, loadTemplate, prepareTemplateSpec } from "./mutator/template/template_loading.js";
|
|
9
9
|
import { FrontendFromFolderResourceType, FrontendFromLocalTgzResourceType, FrontendFromUrlResourceType } from "./model/block_pack_spec.js";
|
|
10
|
-
import { AcceptanceFieldPrefix, SharedEnvelopeResourceType, SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, acceptanceField, acceptanceFieldLogin, asShareId, canGrantToEveryone, decisionField, decodeEnvelopeData, isAcceptanceField, newShareId } from "./model/sharing_model.js";
|
|
10
|
+
import { AcceptanceFieldPrefix, SharedEnvelopeResourceType, SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, acceptanceField, acceptanceFieldLogin, asShareId, canGrantToEveryone, canImpersonate, decisionField, decodeEnvelopeData, isAcceptanceField, newShareId } from "./model/sharing_model.js";
|
|
11
11
|
import "./model/index.js";
|
|
12
12
|
import { duplicateProject } from "./mutator/project.js";
|
|
13
13
|
import { deriveGlobalPObjectId, deriveLocalPObjectId } from "./pool/data.js";
|
|
@@ -23,4 +23,4 @@ export * from "@platforma-sdk/model";
|
|
|
23
23
|
export * from "@milaboratories/pl-model-middle-layer";
|
|
24
24
|
export * from "@milaboratories/pl-deployments";
|
|
25
25
|
export * from "@milaboratories/pl-client";
|
|
26
|
-
export { ACCESS_COUNT_KEY, ACCESS_KEY_PREFIX, AcceptanceFieldPrefix, BlockArgsAuthorKeyPrefix, BlockPackRegistry, CentralBlockRegistry, DefaultDriverKitOpsPaths, DefaultDriverKitOpsSettings, DefaultMiddleLayerOpsPaths, DefaultMiddleLayerOpsSettings, FrontendFromFolderResourceType, FrontendFromLocalTgzResourceType, FrontendFromUrlResourceType, GC_ACCESS_THRESHOLD, GC_MAX_ENTRIES, MiddleLayer, Project, ProjectCreatedTimestamp, ProjectLastModifiedTimestamp, ProjectMetaKey, ProjectResourceType, ProjectStructureAuthorKey, ProjectStructureKey, ProjectsField, SchemaVersionCurrent, SchemaVersionKey, SharedEnvelopeResourceType, SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, TemplateCacheFieldName, TemplateCacheType, TengoTemplateGet, TengoTemplateGetRegistry, TengoTemplateGetTemplate, TengoTemplateGetTemplateURI, TengoTemplatePack, TengoTemplatePackConvert, TengoTemplatePackConvertTemplate, TengoTemplatePackConvertTemplatePack, V1CentralDevSnapshotRegistry, V1CentralRegistry, V2RegistryProvider, acceptanceField, acceptanceFieldLogin, asShareId, cacheBlockPackTemplate, canGrantToEveryone, checkNetwork, createRenderTemplate, decisionField, decodeEnvelopeData, deriveGlobalPObjectId, deriveLocalPObjectId, dropTemplateCache, duplicateProject, flattenTemplateTree, getDevV1PacketMtime, getDevV2PacketMtime, getFromPackV2Mtime, getOrCreateTemplateCache, initDriverKit, initNetworkCheck, invalidateTemplateCacheId, isAcceptanceField, loadTemplate, loadTemplateCached, newShareId, parseFinalPObjectCollection, prepareTemplateSpec, runGc };
|
|
26
|
+
export { ACCESS_COUNT_KEY, ACCESS_KEY_PREFIX, AcceptanceFieldPrefix, BlockArgsAuthorKeyPrefix, BlockPackRegistry, CentralBlockRegistry, DefaultDriverKitOpsPaths, DefaultDriverKitOpsSettings, DefaultMiddleLayerOpsPaths, DefaultMiddleLayerOpsSettings, FrontendFromFolderResourceType, FrontendFromLocalTgzResourceType, FrontendFromUrlResourceType, GC_ACCESS_THRESHOLD, GC_MAX_ENTRIES, MiddleLayer, Project, ProjectCreatedTimestamp, ProjectLastModifiedTimestamp, ProjectMetaKey, ProjectResourceType, ProjectStructureAuthorKey, ProjectStructureKey, ProjectsField, SchemaVersionCurrent, SchemaVersionKey, SharedEnvelopeResourceType, SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, TemplateCacheFieldName, TemplateCacheType, TengoTemplateGet, TengoTemplateGetRegistry, TengoTemplateGetTemplate, TengoTemplateGetTemplateURI, TengoTemplatePack, TengoTemplatePackConvert, TengoTemplatePackConvertTemplate, TengoTemplatePackConvertTemplatePack, V1CentralDevSnapshotRegistry, V1CentralRegistry, V2RegistryProvider, acceptanceField, acceptanceFieldLogin, asShareId, cacheBlockPackTemplate, canGrantToEveryone, canImpersonate, checkNetwork, createRenderTemplate, decisionField, decodeEnvelopeData, deriveGlobalPObjectId, deriveLocalPObjectId, dropTemplateCache, duplicateProject, flattenTemplateTree, getDevV1PacketMtime, getDevV2PacketMtime, getFromPackV2Mtime, getOrCreateTemplateCache, initDriverKit, initNetworkCheck, invalidateTemplateCacheId, isAcceptanceField, loadTemplate, loadTemplateCached, newShareId, parseFinalPObjectCollection, prepareTemplateSpec, runGc };
|
|
@@ -104,7 +104,11 @@ var MiddleLayer = class MiddleLayer {
|
|
|
104
104
|
* additional required capabilities later without a UI change.
|
|
105
105
|
*/
|
|
106
106
|
get sharingSupported() {
|
|
107
|
-
return this.serverCapabilities.includes("crossTreeRefs:v1");
|
|
107
|
+
return this.serverCapabilities.includes("crossTreeRefs:v1") && !this.impersonating;
|
|
108
|
+
}
|
|
109
|
+
/** True when this session is impersonating another user (an admin opened another user's root). */
|
|
110
|
+
get impersonating() {
|
|
111
|
+
return this.pl.conf.asUser !== void 0;
|
|
108
112
|
}
|
|
109
113
|
/**
|
|
110
114
|
* Role of the authenticated user, from the `GetSessionInfo` RPC surfaced through the
|
|
@@ -120,7 +124,17 @@ var MiddleLayer = class MiddleLayer {
|
|
|
120
124
|
* permission-ceiling gate.
|
|
121
125
|
*/
|
|
122
126
|
get canShareWithEveryone() {
|
|
123
|
-
return this.serverCapabilities.includes("publicGrants:v1") && require_sharing_model.canGrantToEveryone(this.currentUserRole);
|
|
127
|
+
return !this.impersonating && this.serverCapabilities.includes("publicGrants:v1") && require_sharing_model.canGrantToEveryone(this.currentUserRole);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Whether the authenticated user may impersonate others (open another user's root). Mirrors
|
|
131
|
+
* the backend's `CanImpersonate` role gate — admin/controller only, never a regular user.
|
|
132
|
+
* Derived from the session role, which stays the authenticated admin's even while
|
|
133
|
+
* impersonating, so this stays true across a switch: the "return to my root" affordance must
|
|
134
|
+
* not vanish mid-impersonation. Not a security boundary; the backend re-checks on every call.
|
|
135
|
+
*/
|
|
136
|
+
get currentUserCanImpersonate() {
|
|
137
|
+
return require_sharing_model.canImpersonate(this.currentUserRole);
|
|
124
138
|
}
|
|
125
139
|
/** Adds a runtime capability to the middle layer. */
|
|
126
140
|
addRuntimeCapability(requirement, value = true) {
|
|
@@ -222,6 +236,31 @@ var MiddleLayer = class MiddleLayer {
|
|
|
222
236
|
return newProjectId;
|
|
223
237
|
}
|
|
224
238
|
/**
|
|
239
|
+
* Duplicates a project into another user's root, minted in the TARGET user's color so the target
|
|
240
|
+
* owns it. Sibling of {@link duplicateProject}, but writes into a different root. The source
|
|
241
|
+
* project (on the current client root) is referenced cross-color for its block data, kept alive
|
|
242
|
+
* by refcounting, exactly like accepting a shared project. Works both ways: pull (while
|
|
243
|
+
* impersonating a user, copy their project to yourself) and push (from your own root, copy a
|
|
244
|
+
* project to a user). Admin cross-root op; requires the crossTreeRefs:v1 backend capability.
|
|
245
|
+
*/
|
|
246
|
+
async duplicateProjectToUser(srcProjectId, targetLogin, rename) {
|
|
247
|
+
if (!this.serverCapabilities.includes("crossTreeRefs:v1")) throw new Error("duplicateProjectToUser requires the crossTreeRefs:v1 backend capability.");
|
|
248
|
+
const sourceRid = await this.resolveProjectId(srcProjectId);
|
|
249
|
+
const targetRoot = await this.pl.getUserRoot({
|
|
250
|
+
login: targetLogin,
|
|
251
|
+
createIfNotExists: true
|
|
252
|
+
});
|
|
253
|
+
await this.pl.withWriteTxOnRoot(targetRoot, "MLDuplicateProjectToUser", async (tx) => {
|
|
254
|
+
const targetProjectListRid = await require_project_list.ensureProjectListRid(tx);
|
|
255
|
+
const sourceMeta = await tx.getKValueJson(sourceRid, require_project_model.ProjectMetaKey);
|
|
256
|
+
const targetListData = await tx.getResourceData(targetProjectListRid, true);
|
|
257
|
+
const existingLabels = (await Promise.all(targetListData.fields.map((f) => f.value).filter(_milaboratories_pl_client.isNotNullSignedResourceId).map((rid) => tx.getKValueJson(rid, require_project_model.ProjectMetaKey)))).map((m) => m.label);
|
|
258
|
+
const newPrj = await require_project.duplicateProject(tx, sourceRid, { label: rename ? rename(sourceMeta.label, existingLabels) : sourceMeta.label });
|
|
259
|
+
tx.createField((0, _milaboratories_pl_client.field)(targetProjectListRid, (0, node_crypto.randomUUID)()), "Dynamic", newPrj);
|
|
260
|
+
await tx.commit();
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
225
264
|
* Shares the given projects (Copy & Share). Snapshots the projects, creates one envelope, and
|
|
226
265
|
* grants it — all in one atomic write transaction, so a failed grant rolls the whole thing back
|
|
227
266
|
* and the outbox is left as it was.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middle_layer.cjs","names":["canGrantToEveryone","LRUCache","createProject","withProjectAuthored","ProjectMetaKey","isNotNullSignedResourceId","duplicateProject","buildShareEnvelope","GrantType","isEnvelopeProjectField","envelopeProjectFieldUuid","isAcceptanceField","acceptanceFieldLogin","decodeEnvelopeData","copyEnvelopeProjectsIntoList","resourceIdsToStrings","Project","HmacSha256Signer","DefaultMiddleLayerOpsSettings","DefaultMiddleLayerOpsPaths","getDebugFlags","ProjectsField","ProjectsResourceType","SharingOutboxField","SharingOutboxResourceType","SharingStateField","SharingStateResourceType","initDriverKit","RetryAgent","V2RegistryProvider","BlockPackPreparer","RuntimeCapabilities","REQUIRES_PFRAMES_VERSION","createModelServiceRegistry","BlockEventDispatcher","BlockUpdateWatcher","ProjectHelper","WatchableValue","createProjectList","createOutgoingShares","createSharingStateTree","createPendingSharesTree","createPendingSharesComputable","createLiveEnvelopesComputable"],"sources":["../../src/middle_layer/middle_layer.ts"],"sourcesContent":["import type {\n PlClient,\n PlTransaction,\n SignedResourceId,\n ResourceRef,\n Role,\n} from \"@milaboratories/pl-client\";\nimport {\n isEveryoneUserLogin,\n field,\n GrantType,\n isNotNullSignedResourceId,\n isNullSignedResourceId,\n resourceIdToString,\n} from \"@milaboratories/pl-client\";\nimport { LRUCache } from \"lru-cache\";\nimport { createProjectList, ProjectsField, ProjectsResourceType } from \"./project_list\";\nimport { createProject, duplicateProject, withProjectAuthored } from \"../mutator/project\";\nimport { ProjectMetaKey } from \"../model/project_model\";\nimport type { ProjectId } from \"../model/project_model\";\nimport type { SynchronizedTreeState } from \"@milaboratories/pl-tree\";\nimport {\n acceptanceFieldLogin,\n canGrantToEveryone,\n decodeEnvelopeData,\n isAcceptanceField,\n SharingOutboxField,\n SharingOutboxResourceType,\n SharingStateField,\n SharingStateResourceType,\n type EnvelopeAcceptance,\n type EnvelopeData,\n type ProjectChangeAction,\n type ProjectFieldUuid,\n type ShareId,\n type ShareProjectsOptions,\n} from \"../model/sharing_model\";\nimport {\n buildShareEnvelope,\n copyEnvelopeProjectsIntoList,\n envelopeProjectFieldUuid,\n isEnvelopeProjectField,\n resourceIdsToStrings,\n writeEnvelopeAcceptance,\n writeSharingDecision,\n type EnvelopeProjectSource,\n} from \"../mutator/sharing\";\nimport type { LiveEnvelope, OutgoingShare, PendingShare } from \"./sharing_list\";\nimport {\n createLiveEnvelopesComputable,\n createOutgoingShares,\n createPendingSharesComputable,\n createPendingSharesTree,\n createSharingStateTree,\n} from \"./sharing_list\";\nimport { BlockPackPreparer } from \"../mutator/block-pack/block_pack\";\nimport type { MiLogger, Signer } from \"@milaboratories/ts-helpers\";\nimport { BlockEventDispatcher, cachedDeserialize } from \"@milaboratories/ts-helpers\";\nimport { HmacSha256Signer } from \"@milaboratories/ts-helpers\";\nimport type { Computable, ComputableStableDefined } from \"@milaboratories/computable\";\nimport { WatchableValue } from \"@milaboratories/computable\";\nimport { Project } from \"./project\";\nimport type { MiddleLayerOps, MiddleLayerOpsConstructor } from \"./ops\";\nimport { DefaultMiddleLayerOpsPaths, DefaultMiddleLayerOpsSettings } from \"./ops\";\nimport { randomUUID } from \"node:crypto\";\nimport type { ProjectListEntry } from \"../model\";\nimport type {\n AuthorMarker,\n ProjectMeta,\n BlockPlatform,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport { BlockUpdateWatcher } from \"../block_registry/watcher\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { getQuickJS } from \"quickjs-emscripten\";\nimport type { MiddleLayerDriverKit } from \"./driver_kit\";\nimport { initDriverKit } from \"./driver_kit\";\nimport type { BlockCodeFeatureFlags, DriverKit, SupportedRequirement } from \"@platforma-sdk/model\";\nimport { RuntimeCapabilities } from \"@platforma-sdk/model\";\nimport {\n type ModelServiceRegistry,\n registerServiceCapabilities,\n REQUIRES_PFRAMES_VERSION,\n} from \"@milaboratories/pl-model-common\";\nimport { createModelServiceRegistry } from \"../service_factories\";\nimport type { DownloadUrlDriver } from \"@milaboratories/pl-drivers\";\nimport { V2RegistryProvider } from \"../block_registry\";\nimport type { Dispatcher } from \"undici\";\nimport { RetryAgent } from \"undici\";\nimport { getDebugFlags } from \"../debug\";\nimport { ProjectHelper } from \"../model/project_helper\";\n\nexport interface MiddleLayerEnvironment {\n dispose(): Promise<void>;\n readonly pl: PlClient;\n readonly runtimeCapabilities: RuntimeCapabilities;\n readonly logger: MiLogger;\n readonly blockEventDispatcher: BlockEventDispatcher;\n readonly httpDispatcher: Dispatcher;\n readonly retryHttpDispatcher: Dispatcher;\n readonly signer: Signer;\n readonly ops: MiddleLayerOps;\n readonly bpPreparer: BlockPackPreparer;\n readonly frontendDownloadDriver: DownloadUrlDriver;\n readonly blockUpdateWatcher: BlockUpdateWatcher;\n readonly quickJs: QuickJSWASMModule;\n readonly driverKit: MiddleLayerDriverKit;\n readonly serviceRegistry: ModelServiceRegistry;\n readonly projectHelper: ProjectHelper;\n}\n\n/**\n * Main access object to work with pl from UI.\n *\n * It implements an abstraction layer of projects and blocks.\n *\n * As a main entry point inside the pl, this object uses a resource attached\n * via the {@link ProjectsField} to the pl client's root, this resource\n * contains project list.\n *\n * Read about alternative roots, if isolated project lists (working environments)\n * are required.\n * */\nexport class MiddleLayer {\n public readonly pl: PlClient;\n\n private constructor(\n private readonly env: MiddleLayerEnvironment,\n public readonly driverKit: DriverKit,\n public readonly signer: Signer,\n private readonly projectListResourceId: SignedResourceId,\n private readonly sharingOutboxResourceId: SignedResourceId,\n private readonly sharingStateResourceId: SignedResourceId,\n private readonly openedProjectsList: WatchableValue<ProjectId[]>,\n private readonly projectListTree: SynchronizedTreeState,\n private readonly sharingOutboxTree: SynchronizedTreeState,\n private readonly sharingStateTree: SynchronizedTreeState,\n private readonly pendingSharesTree: SynchronizedTreeState,\n public readonly blockRegistryProvider: V2RegistryProvider,\n /** Contains a reactive list of projects along with their meta information. */\n public readonly projectList: ComputableStableDefined<ProjectListEntry[]>,\n /** Reactive view of the donor's outbox — the shares this user has created.\n * v1: API only, no UI. */\n public outgoingShares: Computable<OutgoingShare[] | undefined>,\n /** Envelopes granted to this user, not yet accepted or rejected. Fed by the\n * shared-resource discovery tree. */\n public pendingShares: Computable<PendingShare[] | undefined>,\n /** Internal: the acceptor's currently-live envelopes, read from the same shared-resource\n * discovery tree as {@link pendingShares}. The single source the accept/reject flow resolves\n * live envelopes from — no second discovery path. */\n private readonly liveEnvelopes: Computable<LiveEnvelope[] | undefined>,\n ) {\n this.pl = this.env.pl;\n this.startEnvelopeCleanup();\n }\n\n /**\n * Get the OS where backend is running.\n * For old backend versions returns undefined.\n */\n public get serverPlatform(): BlockPlatform | undefined {\n return this.pl.serverInfo.platform as BlockPlatform | undefined;\n }\n\n /**\n * Runtime capabilities advertised by the connected backend (tokens of\n * the form `<feature>:<version>`, e.g. \"wasm:v1\"). Empty list if the\n * backend predates the capability mechanism — that's the desired\n * fail-closed behaviour for blocks declaring any `requiredCapabilities`.\n */\n public get serverCapabilities(): string[] {\n return this.pl.serverInfo.capabilities ?? [];\n }\n\n /**\n * Login of the authenticated user, for the \"Signed in as\" UI. `null` when the\n * backend has no auth (local/dev mode) — the UI hides the element.\n */\n public get currentUserLogin(): string | null {\n return this.pl.userResources.authUser;\n }\n\n /**\n * Whether the connected backend supports project sharing. Synthetic — computed\n * in the middle layer from the backend capabilities the share flow needs (the\n * cross-color field-reference relaxation the accept flow rests on). It can absorb\n * additional required capabilities later without a UI change.\n */\n public get sharingSupported(): boolean {\n return this.serverCapabilities.includes(\"crossTreeRefs:v1\");\n }\n\n /**\n * Role of the authenticated user, from the `GetSessionInfo` RPC surfaced through the\n * pl-client. `null` in no-auth mode (when {@link currentUserLogin} is null).\n */\n public get currentUserRole(): Role | null {\n return this.pl.currentUserRole;\n }\n\n /**\n * Whether the UI offers share-with-everybody — no role policy lives in the UI:\n * serverCapabilities.has(\"publicGrants:v1\") && canGrantToEveryone(currentUserRole)\n * Not a security boundary: a crafted call still hits the backend's role +\n * permission-ceiling gate.\n */\n public get canShareWithEveryone(): boolean {\n return (\n this.serverCapabilities.includes(\"publicGrants:v1\") &&\n canGrantToEveryone(this.currentUserRole)\n );\n }\n\n /** Adds a runtime capability to the middle layer. */\n public addRuntimeCapability(\n requirement: SupportedRequirement,\n value: number | boolean = true,\n ): void {\n this.env.runtimeCapabilities.addSupportedRequirement(requirement, value);\n }\n\n /** Checks if the given block feature flags are compatible with the runtime capabilities. */\n public checkBlockCompatibility(featureFlags: BlockCodeFeatureFlags | undefined): boolean {\n return this.env.runtimeCapabilities.checkCompatibility(featureFlags);\n }\n\n /** Returns extended API driver kit used internally by middle layer. */\n public get internalDriverKit(): MiddleLayerDriverKit {\n return this.env.driverKit;\n }\n\n /** Returns the service registry for service introspection. */\n public get serviceRegistry(): ModelServiceRegistry {\n return this.env.serviceRegistry;\n }\n\n //\n // ProjectId ↔ SignedResourceId resolution\n //\n\n private readonly projectIdCache = new LRUCache<ProjectId, SignedResourceId>({ max: 1024 });\n\n /** Resolves a ProjectId to a signed SignedResourceId.\n * Uses LRU cache with TX-scan fallback. */\n private async resolveProjectId(projectId: ProjectId): Promise<SignedResourceId> {\n const cached = this.projectIdCache.get(projectId);\n if (cached !== undefined) return cached;\n\n // Cache miss — scan project list fields to find the matching resource\n const rid = await this.pl.withReadTx(\"ResolveProjectId\", async (tx) => {\n const data = await tx.getResourceData(this.projectListResourceId, true);\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n if (resourceIdToString(f.value) === (projectId as string)) return f.value;\n }\n throw new Error(`Project ${projectId} not found in project list.`);\n });\n\n this.projectIdCache.set(projectId, rid);\n return rid;\n }\n\n //\n // Project List Manipulation\n //\n\n /** Creates a project with initial state and adds it to project list. */\n public async createProject(meta: ProjectMeta): Promise<ProjectId> {\n let prj: ResourceRef;\n await this.pl.withWriteTx(\"MLCreateProject\", async (tx) => {\n prj = await createProject(tx, meta);\n tx.createField(field(this.projectListResourceId, randomUUID()), \"Dynamic\", prj);\n await tx.commit();\n });\n await this.projectListTree.refreshState();\n\n const signedRid = await prj!.globalId;\n const projectId = resourceIdToString(signedRid) as ProjectId;\n this.projectIdCache.set(projectId, signedRid);\n return projectId;\n }\n\n /** Updates project metadata */\n public async setProjectMeta(\n id: ProjectId,\n meta: ProjectMeta,\n author?: AuthorMarker,\n ): Promise<void> {\n const rid = await this.resolveProjectId(id);\n await withProjectAuthored(\n this.env.projectHelper,\n this.pl,\n rid,\n author,\n (prj) => {\n prj.setMeta(meta);\n },\n { name: \"setProjectMeta\" },\n );\n await this.projectListTree.refreshState();\n }\n\n /** Permanently deletes project from the project list, this will result in\n * destruction of all attached objects, like files, analysis results etc. */\n public async deleteProject(id: ProjectId): Promise<void> {\n await this.pl.withWriteTx(\"MLRemoveProject\", async (tx) => {\n const data = await tx.getResourceData(this.projectListResourceId, true);\n let fieldName: string | undefined;\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n if (resourceIdToString(f.value) === (id as string)) {\n fieldName = f.name;\n break;\n }\n }\n if (fieldName === undefined) throw new Error(`Project ${id} not found in project list.`);\n tx.removeField(field(this.projectListResourceId, fieldName));\n await tx.commit();\n });\n this.projectIdCache.delete(id);\n await this.projectListTree.refreshState();\n }\n\n /**\n * Duplicates an existing project and adds the copy to this user's project list.\n *\n * @param srcProjectId - project id of the project to duplicate\n * @param rename - optional function that receives the source label and all existing\n * project labels (read within the same transaction), and returns the label for the copy\n */\n public async duplicateProject(\n srcProjectId: ProjectId,\n rename?: (previousLabel: string, existingLabels: string[]) => string,\n ): Promise<ProjectId> {\n const sourceRid = await this.resolveProjectId(srcProjectId);\n\n const newPrj: ResourceRef = await this.pl.withWriteTx(\"MLDuplicateProject\", async (tx) => {\n // Read source project meta\n const sourceMeta = await tx.getKValueJson<ProjectMeta>(sourceRid, ProjectMetaKey);\n\n // Read all existing project labels from the project list (parallel reads)\n const projectListData = await tx.getResourceData(this.projectListResourceId, true);\n const projectRids = projectListData.fields\n .map((f) => f.value)\n .filter(isNotNullSignedResourceId);\n const existingLabels = (\n await Promise.all(\n projectRids.map((rid) => tx.getKValueJson<ProjectMeta>(rid, ProjectMetaKey)),\n )\n ).map((m) => m.label);\n\n // Compute new label\n const newLabel = rename ? rename(sourceMeta.label, existingLabels) : sourceMeta.label;\n\n // Create the duplicate\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n\n // Attach to project list with a random UUID field name\n tx.createField(field(this.projectListResourceId, randomUUID()), \"Dynamic\", newPrj);\n await tx.commit();\n\n return newPrj;\n });\n\n await this.projectListTree.refreshState();\n\n const signedRid = await newPrj.globalId;\n const newProjectId = resourceIdToString(signedRid) as ProjectId;\n this.projectIdCache.set(newProjectId, signedRid);\n return newProjectId;\n }\n\n //\n // Project Sharing (Copy & Share)\n //\n\n /**\n * Shares the given projects (Copy & Share). Snapshots the projects, creates one envelope, and\n * grants it — all in one atomic write transaction, so a failed grant rolls the whole thing back\n * and the outbox is left as it was.\n *\n * Two variants (see {@link ShareProjectsOptions}):\n * - `{ recipients }` — one writable grant per named recipient; the envelope expires after the\n * default TTL (`sharedAt + envelopeTtlMs`).\n * - `{ everyone: true }` — one make-public grant (backend rewrites the target to the\n * everyone-user); the envelope's `expiresAt` is `null`, so it never expires.\n *\n * v1 always passes `mode: \"copy\"`.\n */\n public async shareProjects(\n projectIds: ProjectId[],\n options: ShareProjectsOptions,\n ): Promise<void> {\n if (projectIds.length === 0) throw new Error(\"shareProjects: no projects given\");\n\n // Everyone + replace: refresh the existing everyone-share of this project under its stable\n // shareId (so recipients who already decided aren't re-prompted), if one exists. Found\n // automatically by project overlap; falls through to a fresh share when none exists.\n if (\"everyone\" in options && options.replace) {\n const priorEveryone = (await this.findSupersedableEnvelopes(projectIds)).find(\n (p) => p.everyone,\n );\n if (priorEveryone !== undefined) {\n await this.changeShare(priorEveryone.shareId, { title: options.title });\n return;\n }\n }\n\n await this.createNewShare(projectIds, options);\n }\n\n /**\n * Mints a fresh share: snapshots the projects into one new envelope (a fresh shareId),\n * supersedes prior shares of the same project, and grants it — all in one atomic write\n * transaction, so a failed grant rolls the whole thing back and the outbox is left as it was.\n * The everyone-refresh path is the {@link changeShare} branch of {@link shareProjects}; this is\n * the mint-a-new-envelope branch.\n */\n private async createNewShare(\n projectIds: ProjectId[],\n options: ShareProjectsOptions,\n ): Promise<void> {\n const everyone = \"everyone\" in options;\n const sources: EnvelopeProjectSource[] = await Promise.all(\n projectIds.map(\n async (id): Promise<EnvelopeProjectSource> => ({\n kind: \"fresh\",\n projectId: id,\n sourceRid: await this.resolveProjectId(id),\n }),\n ),\n );\n const sender = this.currentUserLogin ?? \"\";\n // Targeted share: sharedAt + ttl. Share-with-everybody: never expires (null).\n const expiresAt = everyone ? null : Date.now() + this.env.ops.envelopeTtlMs;\n\n // Supersede prior shares of the same project(s) so they never pile up. Resolved before\n // the write tx (ListGrants is a separate RPC). Everyone-share supersedes a prior\n // everyone-share of the same project; a targeted share pulls each named recipient out of\n // any prior share of that project, deleting that share if it ends up with no recipients.\n const priors = await this.findSupersedableEnvelopes(projectIds);\n\n await this.pl.withWriteTx(\"MLShareProjects\", async (tx) => {\n if (everyone) {\n for (const prior of priors) {\n if (prior.everyone) tx.removeField(field(this.sharingOutboxResourceId, prior.fieldName));\n }\n } else {\n const newRecipients = new Set(options.recipients);\n for (const prior of priors) {\n if (prior.everyone) continue; // a single user can't be pulled from an everyone-grant\n const toRemove = prior.recipients.filter((u) => newRecipients.has(u));\n if (toRemove.length === 0) continue;\n const remaining = prior.recipients.filter((u) => !newRecipients.has(u));\n if (remaining.length === 0) {\n // Nobody left on the old share — drop the whole envelope.\n tx.removeField(field(this.sharingOutboxResourceId, prior.fieldName));\n } else {\n for (const u of toRemove) tx.revokeAccess(prior.rid, u);\n }\n }\n }\n\n const { envelope } = await buildShareEnvelope(tx, this.sharingOutboxResourceId, sources, {\n mode: options.mode,\n sender,\n title: options.title,\n expiresAt,\n });\n\n // Grant in the same transaction (writable: the cross-color accept rule demands a writable\n // grant on the envelope). Atomic with the create.\n const envelopeGid = await envelope.globalId;\n if (everyone) {\n // One everyone-grant: empty/ignored target, ANY_AUTHORISED. The backend rewrites\n // the target to the everyone-user; gated by role + permission ceiling.\n tx.grantAccess(envelopeGid, \"\", { writable: true }, GrantType.ANY_AUTHORISED);\n } else {\n for (const recipient of options.recipients) {\n tx.grantAccess(envelopeGid, recipient, { writable: true });\n }\n }\n\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n }\n\n /**\n * Changes a share in place (same {@link ShareId}), in one write transaction: re-snapshots live\n * source projects and carries deleted ones' snapshots forward; applies edited recipients/title;\n * transfers already-decided recipients' accept/reject records (they keep their copy and aren't\n * re-prompted); re-grants; drops the old envelope.\n *\n * `opts.recipients` is the full targeted set (decided users are always kept). `opts.title`\n * replaces the title — omit keeps the current one. `opts.everyone` upgrades targeted ->\n * everyone; the reverse is impossible and ignored.\n *\n * `opts.projectActions` is a per-source-project decision, keyed by projectId: `update`\n * re-snapshots the live source (falls back to carry if the source is gone), `keep` carries the\n * existing snapshot (and its timestamp), `remove` drops the project from the pack. A project not\n * in the map defaults to `keep`. Omit the whole map for the legacy auto behavior (live sources\n * updated, gone ones kept) — the everyone-refresh path relies on that.\n */\n public async changeShare(\n shareId: ShareId,\n opts: {\n recipients?: string[];\n everyone?: boolean;\n title?: string;\n projectActions?: Record<ProjectId, ProjectChangeAction>;\n } = {},\n ): Promise<void> {\n await this.pl.withWriteTx(\"MLChangeShare\", async (tx) => {\n const old = await this.resolveOutboxEnvelope(tx, shareId);\n if (old === undefined)\n throw new Error(`changeShare: no live share with id ${shareId} in the outbox.`);\n\n const self = this.currentUserLogin ?? \"\";\n const grants = await tx.listGrants(old.rid);\n // A targeted share may be upgraded to everyone; an everyone-share can't be narrowed back.\n const everyone = grants.some((g) => isEveryoneUserLogin(g.user)) || opts.everyone === true;\n\n // Read the old envelope's project snapshots (uuid -> rid) and accept/reject records.\n const oldRd = await tx.getResourceData(old.rid, true);\n const snapshotByUuid = new Map<string, SignedResourceId>();\n const acceptances: { login: string; acc: EnvelopeAcceptance }[] = [];\n for (const f of oldRd.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n if (isEnvelopeProjectField(f.name)) {\n snapshotByUuid.set(envelopeProjectFieldUuid(f.name), f.value);\n } else if (isAcceptanceField(f.name)) {\n const raw = (await tx.getResourceData(f.value, false)).data;\n if (raw === undefined) continue;\n acceptances.push({\n login: acceptanceFieldLogin(f.name),\n acc: cachedDeserialize(raw) as EnvelopeAcceptance,\n });\n }\n }\n const decidedLogins = acceptances.map((a) => a.login);\n\n // Everyone-shares ignore recipients; targeted shares keep decided users plus the edited set.\n const priorRecipients = grants\n .filter((g) => !isEveryoneUserLogin(g.user) && g.user !== self)\n .map((g) => g.user);\n const recipients = everyone\n ? []\n : Array.from(new Set([...(opts.recipients ?? priorRecipients), ...decidedLogins]));\n\n // Live source projects by persistable id — these get a fresh snapshot.\n const liveProjects = new Map<string, SignedResourceId>();\n const projList = await tx.getResourceData(this.projectListResourceId, true);\n for (const f of projList.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n liveProjects.set(resourceIdToString(f.value), f.value);\n }\n\n // Per project (keyed by field uuid), apply the caller's decision (default `keep`); with no\n // projectActions map, fall back to the legacy auto behavior: update a live source, keep a gone one.\n const actions = opts.projectActions;\n const sources: EnvelopeProjectSource[] = [];\n for (const uuid of Object.keys(old.data.projects) as ProjectFieldUuid[]) {\n const { label, source, updatedAt } = old.data.projects[uuid];\n const liveRid = liveProjects.get(source);\n\n const action = actions\n ? (actions[source] ?? \"keep\")\n : liveRid !== undefined\n ? \"update\"\n : \"keep\";\n if (action === \"remove\") continue;\n\n if (action === \"update\" && liveRid !== undefined) {\n sources.push({ kind: \"fresh\", projectId: source, sourceRid: liveRid });\n } else {\n // keep, or an \"update\" whose source vanished before commit (deleted meanwhile, e.g. from\n // another client): carry the prior snapshot. Liveness is read inside this write tx — race-safe.\n const snapshotRid = snapshotByUuid.get(uuid);\n if (snapshotRid !== undefined)\n sources.push({ kind: \"carry\", projectId: source, label, snapshotRid, updatedAt });\n }\n }\n\n // Omit (undefined) keeps the current title; a provided value replaces it.\n const title = opts.title === undefined ? old.data.title : opts.title.trim();\n const expiresAt = everyone ? null : Date.now() + this.env.ops.envelopeTtlMs;\n\n // Same shareId, same outbox field name — detach the old field before rebuilding, or they collide.\n tx.removeField(field(this.sharingOutboxResourceId, old.fieldName));\n\n const { envelope } = await buildShareEnvelope(tx, this.sharingOutboxResourceId, sources, {\n mode: old.data.mode,\n sender: self,\n title,\n expiresAt,\n shareId, // SAME shareId — the essence of change\n });\n\n // Transfer the decided users' records onto the new envelope (donor-written copies).\n for (const { login, acc } of acceptances) {\n if (!everyone && !recipients.includes(login)) continue;\n writeEnvelopeAcceptance(tx, envelope, login, acc.action, acc.timestamp);\n }\n\n const gid = await envelope.globalId;\n if (everyone) tx.grantAccess(gid, \"\", { writable: true }, GrantType.ANY_AUTHORISED);\n else for (const r of recipients) tx.grantAccess(gid, r, { writable: true });\n\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n }\n\n /**\n * Finds the donor's own outgoing envelopes built from any of the given source projects —\n * the supersede candidates for a fresh share of the same project(s). Reads each envelope's\n * recipient set via `ListGrants` so the caller can pull individual recipients or detect an\n * everyone-share.\n */\n private async findSupersedableEnvelopes(projectIds: ProjectId[]): Promise<\n {\n fieldName: string;\n rid: SignedResourceId;\n shareId: ShareId;\n everyone: boolean;\n recipients: string[];\n }[]\n > {\n const wanted = new Set(projectIds);\n\n const matched = await this.pl.withReadTx(\"MLFindSupersede\", async (tx) => {\n const outbox = await tx.getResourceData(this.sharingOutboxResourceId, true);\n const out: { fieldName: string; rid: SignedResourceId; shareId: ShareId }[] = [];\n for (const f of outbox.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const rd = await tx.getResourceData(f.value, false);\n if (rd.data === undefined) continue;\n const data = decodeEnvelopeData(rd.data);\n if (Object.values(data.projects).some((p) => wanted.has(p.source)))\n out.push({ fieldName: f.name, rid: f.value, shareId: data.shareId });\n }\n return out;\n });\n\n return await Promise.all(\n matched.map(async ({ fieldName, rid, shareId }) => {\n const grants = await this.pl.userResources.listGrants(rid);\n return {\n fieldName,\n rid,\n shareId,\n everyone: grants.some((g) => isEveryoneUserLogin(g.user)),\n recipients: grants.filter((g) => !isEveryoneUserLogin(g.user)).map((g) => g.user),\n };\n }),\n );\n }\n\n /**\n * Revokes and deletes an outgoing share for all recipients: detaches and deletes the envelope, and\n * its grants are revoked along with it. Already-accepted copies are unaffected (ref-counting keeps\n * the adopted resources alive). Idempotent — revoking a share that is already gone is a no-op.\n */\n public async revokeShare(shareId: ShareId): Promise<void> {\n await this.pl.withWriteTx(\"MLRevokeShare\", async (tx) => {\n const target = await this.resolveOutboxEnvelope(tx, shareId);\n if (target === undefined) return;\n tx.removeField(field(this.sharingOutboxResourceId, target.fieldName));\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n }\n\n /**\n * Resolves a live envelope from the donor's own outbox by its logical `shareId`, returning the\n * outbox field name (for detach), the signed envelope id, and its decoded {@link EnvelopeData}.\n * The outbox is keyed by `{shareId}` directly, but a replaced/legacy share may have drifted, so\n * we match on the decoded `shareId` rather than the field name alone.\n */\n private async resolveOutboxEnvelope(\n tx: PlTransaction,\n shareId: ShareId,\n ): Promise<{ fieldName: string; rid: SignedResourceId; data: EnvelopeData } | undefined> {\n const outboxData = await tx.getResourceData(this.sharingOutboxResourceId, true);\n for (const f of outboxData.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const rd = await tx.getResourceData(f.value, false);\n if (rd.data === undefined) continue;\n const data = decodeEnvelopeData(rd.data);\n if (data.shareId === shareId) return { fieldName: f.name, rid: f.value, data };\n }\n return undefined;\n }\n\n /**\n * Resolves currently-shared envelopes (granted to this user) to their resource ids, keyed by\n * the envelope's logical `shareId`.\n *\n * Reads the {@link liveEnvelopes} Computable — the same shared-resource discovery tree that\n * feeds {@link pendingShares}. This is the single discovery mechanism: there is no separate\n * `ListUserResources` re-stream on every accept/reject. `refreshState()` is awaited first so a\n * just-granted envelope is observed (the tree's discovery poll may otherwise lag a freshly\n * landed grant). The tree is gRPC-only, so this is empty on a REST-connected client.\n */\n private async resolveLiveEnvelopes(): Promise<Map<ShareId, LiveEnvelope>> {\n await this.pendingSharesTree.refreshState();\n const live = (await this.liveEnvelopes.getValue()) ?? [];\n // Dedup by logical shareId (last writer wins — at most one live envelope per shareId).\n const map = new Map<ShareId, LiveEnvelope>();\n for (const e of live) map.set(e.data.shareId, e);\n return map;\n }\n\n /**\n * Accepts one or more pending shares: duplicates each share's projects into this user's\n * project list, records the decision per share, and (read-write share) writes the donor-visible\n * acceptance onto the envelope. Per-share failures (e.g. an expiry race) are collected, not\n * short-circuited — the rest still get accepted. Accept-all = pass every current pending shareId.\n *\n * `rename` resolves label collisions (same callback contract as {@link duplicateProject}), but\n * the source lives in the envelope tree, so accept calls the low-level mutator directly.\n */\n public async acceptShare(\n shareIds: ShareId[],\n rename?: (previousLabel: string, existingLabels: string[]) => string,\n ): Promise<{ accepted: ProjectId[]; failed: { shareId: ShareId; error: string }[] }> {\n const live = await this.resolveLiveEnvelopes();\n const login = this.currentUserLogin;\n\n const accepted: ProjectId[] = [];\n const failed: { shareId: ShareId; error: string }[] = [];\n\n for (const shareId of shareIds) {\n const envelope = live.get(shareId);\n if (envelope === undefined) {\n failed.push({ shareId, error: \"Share is no longer available.\" });\n continue;\n }\n try {\n const now = Date.now();\n const createdRids = await this.pl.withWriteTx(\"MLAcceptShare\", async (tx) => {\n const created = await copyEnvelopeProjectsIntoList(\n tx,\n envelope.rid,\n this.projectListResourceId,\n rename,\n );\n\n // Record the decision on the acceptor's own SharingState, keyed on shareId.\n writeSharingDecision(tx, this.sharingStateResourceId, shareId, {\n decision: \"accepted\",\n timestamp: now,\n envelopeSharedAt: envelope.data.sharedAt,\n acceptedProjects: resourceIdsToStrings(created),\n });\n\n // Read-write share: write the donor-visible acceptance onto the envelope.\n if (login !== null && envelope.data.mode !== \"read-only\")\n writeEnvelopeAcceptance(tx, envelope.rid, login, \"accepted\", now);\n\n await tx.commit();\n return created;\n });\n for (const rid of createdRids) {\n const projectId = resourceIdToString(rid) as ProjectId;\n this.projectIdCache.set(projectId, rid);\n accepted.push(projectId);\n }\n } catch (e) {\n failed.push({ shareId, error: e instanceof Error ? e.message : String(e) });\n }\n }\n\n await Promise.all([this.projectListTree.refreshState(), this.sharingStateTree.refreshState()]);\n return { accepted, failed };\n }\n\n /** Records rejection of a pending share; it never surfaces again. */\n public async rejectShare(shareId: ShareId): Promise<void> {\n const live = await this.resolveLiveEnvelopes();\n const envelope = live.get(shareId);\n const login = this.currentUserLogin;\n const now = Date.now();\n\n await this.pl.withWriteTx(\"MLRejectShare\", async (tx) => {\n writeSharingDecision(tx, this.sharingStateResourceId, shareId, {\n decision: \"rejected\",\n timestamp: now,\n envelopeSharedAt: envelope?.data.sharedAt ?? now,\n acceptedProjects: [],\n });\n\n // Read-write share: write the donor-visible rejection onto the envelope (if still live).\n if (envelope !== undefined && login !== null && envelope.data.mode !== \"read-only\")\n writeEnvelopeAcceptance(tx, envelope.rid, login, \"rejected\", now);\n\n await tx.commit();\n });\n\n await this.sharingStateTree.refreshState();\n }\n\n //\n // Outbox cleanup (donor side)\n //\n\n private static readonly EnvelopeCleanupIntervalMs = 6 * 3600 * 1000; // every 6h\n private envelopeCleanupTimer: ReturnType<typeof setInterval> | undefined;\n\n /** On ML start and every 6h, delete envelopes whose immutable `expiresAt` has passed. */\n private startEnvelopeCleanup(): void {\n void this.runEnvelopeCleanup();\n this.envelopeCleanupTimer = setInterval(() => {\n void this.runEnvelopeCleanup();\n }, MiddleLayer.EnvelopeCleanupIntervalMs);\n // Don't keep the process alive solely for cleanup.\n this.envelopeCleanupTimer.unref?.();\n }\n\n /** Scans the donor's outbox and deletes expired envelopes (backend auto-revokes their grants).\n * Envelopes with `expiresAt: null` (share-with-everybody) are skipped. */\n private async runEnvelopeCleanup(): Promise<void> {\n try {\n const now = Date.now();\n const expired = await this.pl.withReadTx(\"MLEnvelopeCleanupScan\", async (tx) => {\n const data = await tx.getResourceData(this.sharingOutboxResourceId, true);\n const toDelete: { fieldName: string }[] = [];\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const rd = await tx.getResourceData(f.value, false);\n if (rd.data === undefined) continue;\n const envData = decodeEnvelopeData(rd.data);\n if (envData.expiresAt === null) continue; // never expires\n if (envData.expiresAt <= now) toDelete.push({ fieldName: f.name });\n }\n return toDelete;\n });\n\n if (expired.length === 0) return;\n\n await this.pl.withWriteTx(\"MLEnvelopeCleanup\", async (tx) => {\n for (const { fieldName } of expired)\n tx.removeField(field(this.sharingOutboxResourceId, fieldName));\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n } catch (e) {\n this.env.logger.warn(\n `envelope cleanup failed: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n }\n\n //\n // Projects\n //\n\n private readonly openedProjects = new Map<ProjectId, Project>();\n\n /** Opens a project, and starts corresponding project maintenance loop. */\n public async openProject(id: ProjectId): Promise<void> {\n if (this.openedProjects.has(id)) throw new Error(`Project ${id} already opened`);\n const rid = await this.resolveProjectId(id);\n this.openedProjects.set(id, await Project.init(this.env, id, rid));\n this.openedProjectsList.setValue([...this.openedProjects.keys()]);\n }\n\n /** Closes the project, and deallocate all corresponding resources. */\n public async closeProject(id: ProjectId): Promise<void> {\n const prj = this.openedProjects.get(id);\n if (prj === undefined) throw new Error(`Project ${id} not found among opened projects`);\n this.openedProjects.delete(id);\n await prj.destroy();\n this.openedProjectsList.setValue([...this.openedProjects.keys()]);\n }\n\n /** Returns a project access object for an opened project. */\n public getOpenedProject(id: ProjectId): Project {\n const prj = this.openedProjects.get(id);\n if (prj === undefined) throw new Error(`Project ${id} not found among opened projects`);\n return prj;\n }\n\n /** Returns true if project with given id is currently opened. */\n public isProjectOpened(id: ProjectId): boolean {\n return this.openedProjects.has(id);\n }\n\n /**\n * Deallocates all runtime resources consumed by this object and awaits\n * actual termination of event loops and other processes associated with\n * them.\n */\n public async close() {\n if (this.envelopeCleanupTimer !== undefined) clearInterval(this.envelopeCleanupTimer);\n await Promise.all([...this.openedProjects.values()].map((prj) => prj.destroy()));\n // this.env.quickJs;\n await Promise.all([\n this.projectListTree.terminate(),\n this.sharingOutboxTree.terminate(),\n this.sharingStateTree.terminate(),\n this.pendingSharesTree.terminate(),\n ]);\n await this.env.dispose();\n await this.pl.close();\n }\n\n /** @deprecated */\n public async closeAndAwaitTermination() {\n await this.close();\n }\n\n /** Generates sufficiently random string to be used as local secret for the\n * middle layer */\n public static generateLocalSecret(): string {\n return HmacSha256Signer.generateSecret();\n }\n\n /** Returns a block event dispatcher, which can be used to listen to block events. */\n public get blockEventDispatcher(): BlockEventDispatcher {\n return this.env.blockEventDispatcher;\n }\n\n /** Initialize middle layer */\n public static async init(\n pl: PlClient,\n workdir: string,\n _ops: MiddleLayerOpsConstructor,\n ): Promise<MiddleLayer> {\n const ops: MiddleLayerOps = {\n ...DefaultMiddleLayerOpsSettings,\n ...DefaultMiddleLayerOpsPaths(workdir),\n ..._ops,\n };\n\n // overriding debug options from environment variables\n ops.defaultTreeOptions.logStat = getDebugFlags().logTreeStats;\n ops.debugOps.dumpInitialTreeState = getDebugFlags().dumpInitialTreeState;\n // apply MI_TREE_TRAVERSAL only when the embedder hasn't set an explicit mode\n if (\n ops.defaultTreeOptions.traversalMode === undefined &&\n getDebugFlags().treeTraversalMode !== undefined\n )\n ops.defaultTreeOptions.traversalMode = getDebugFlags().treeTraversalMode;\n\n const { projects, sharingOutbox, sharingState } = await pl.withWriteTx(\n \"MLInitialization\",\n async (tx) => {\n // Lazily create each clientRoot-attached singleton resource. Returns the existing\n // resource id if the field is already populated, otherwise creates + locks + sets it.\n const lazyInit = async (\n fieldName: string,\n type: { name: string; version: string },\n ): Promise<{ ref?: ResourceRef; existing?: SignedResourceId }> => {\n const f = field(tx.clientRoot, fieldName);\n tx.createField(f, \"Dynamic\");\n const fData = await tx.getField(f);\n if (isNullSignedResourceId(fData.value)) {\n const ref = tx.createEphemeral(type);\n tx.lock(ref);\n tx.setField(f, ref);\n return { ref };\n }\n return { existing: fData.value };\n };\n\n const projectsR = await lazyInit(ProjectsField, ProjectsResourceType);\n const outboxR = await lazyInit(SharingOutboxField, SharingOutboxResourceType);\n const stateR = await lazyInit(SharingStateField, SharingStateResourceType);\n\n await tx.commit();\n\n return {\n projects: projectsR.existing ?? (await projectsR.ref!.globalId),\n sharingState: stateR.existing ?? (await stateR.ref!.globalId),\n sharingOutbox: outboxR.existing ?? (await outboxR.ref!.globalId),\n };\n },\n );\n\n const logger = ops.logger;\n\n const driverKit = await initDriverKit(pl, workdir, ops.frontendDownloadPath, ops);\n\n // passed to components having no own retry logic\n const retryHttpDispatcher = new RetryAgent(pl.httpDispatcher);\n\n const v2RegistryProvider = new V2RegistryProvider(retryHttpDispatcher);\n\n const bpPreparer = new BlockPackPreparer(\n v2RegistryProvider,\n driverKit.signer,\n retryHttpDispatcher,\n );\n\n const quickJs = await getQuickJS();\n\n const runtimeCapabilities = new RuntimeCapabilities();\n // add runtime capabilities of model here\n runtimeCapabilities.addSupportedRequirement(\"requiresModelAPIVersion\", 1);\n runtimeCapabilities.addSupportedRequirement(\"requiresModelAPIVersion\", 2);\n runtimeCapabilities.addSupportedRequirement(\"requiresCreatePTable\", 2);\n runtimeCapabilities.addSupportedRequirement(\"requiresPFramesVersion\", REQUIRES_PFRAMES_VERSION);\n registerServiceCapabilities((flag, value) =>\n runtimeCapabilities.addSupportedRequirement(flag, value),\n );\n // runtime capabilities of the desktop are to be added by the desktop app / test framework\n\n const serviceRegistry = createModelServiceRegistry({ logger });\n\n const env: MiddleLayerEnvironment = {\n pl,\n blockEventDispatcher: new BlockEventDispatcher(),\n signer: driverKit.signer,\n logger,\n httpDispatcher: pl.httpDispatcher,\n retryHttpDispatcher,\n ops,\n bpPreparer,\n frontendDownloadDriver: driverKit.frontendDriver,\n driverKit,\n blockUpdateWatcher: new BlockUpdateWatcher(v2RegistryProvider, logger, {\n minDelay: ops.devBlockUpdateRecheckInterval,\n http: retryHttpDispatcher,\n preferredUpdateChannel: ops.preferredUpdateChannel,\n }),\n runtimeCapabilities,\n serviceRegistry,\n quickJs,\n projectHelper: new ProjectHelper(quickJs, logger),\n dispose: async () => {\n await serviceRegistry.dispose();\n await retryHttpDispatcher.destroy();\n await driverKit.dispose();\n },\n };\n\n const openedProjects = new WatchableValue<ProjectId[]>([]);\n const projectListTC = await createProjectList(pl, projects, openedProjects, env);\n\n // Project sharing trees and reactive views.\n const outgoingTC = await createOutgoingShares(pl, sharingOutbox, env);\n const sharingStateTree = await createSharingStateTree(pl, sharingState, env);\n const pendingSharesTree = await createPendingSharesTree(pl, env);\n const pendingShares = createPendingSharesComputable(\n pendingSharesTree,\n sharingStateTree,\n pl.userResources.authUser,\n );\n const liveEnvelopes = createLiveEnvelopesComputable(pendingSharesTree);\n\n return new MiddleLayer(\n env,\n driverKit,\n driverKit.signer,\n projects,\n sharingOutbox,\n sharingState,\n openedProjects,\n projectListTC.tree,\n outgoingTC.tree,\n sharingStateTree,\n pendingSharesTree,\n v2RegistryProvider,\n projectListTC.computable,\n outgoingTC.computable,\n pendingShares,\n liveEnvelopes,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0HA,IAAa,cAAb,MAAa,YAAY;CAIJ;CACD;CACA;CACC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;CAEA;CAGT;CAGA;CAIU;CA1BnB;CAEA,YACE,KACA,WACA,QACA,uBACA,yBACA,wBACA,oBACA,iBACA,mBACA,kBACA,mBACA,uBAEA,aAGA,gBAGA,eAIA,eACA;EAxBiB,KAAA,MAAA;EACD,KAAA,YAAA;EACA,KAAA,SAAA;EACC,KAAA,wBAAA;EACA,KAAA,0BAAA;EACA,KAAA,yBAAA;EACA,KAAA,qBAAA;EACA,KAAA,kBAAA;EACA,KAAA,oBAAA;EACA,KAAA,mBAAA;EACA,KAAA,oBAAA;EACD,KAAA,wBAAA;EAEA,KAAA,cAAA;EAGT,KAAA,iBAAA;EAGA,KAAA,gBAAA;EAIU,KAAA,gBAAA;EAEjB,KAAK,KAAK,KAAK,IAAI;EACnB,KAAK,qBAAqB;CAC5B;;;;;CAMA,IAAW,iBAA4C;EACrD,OAAO,KAAK,GAAG,WAAW;CAC5B;;;;;;;CAQA,IAAW,qBAA+B;EACxC,OAAO,KAAK,GAAG,WAAW,gBAAgB,CAAC;CAC7C;;;;;CAMA,IAAW,mBAAkC;EAC3C,OAAO,KAAK,GAAG,cAAc;CAC/B;;;;;;;CAQA,IAAW,mBAA4B;EACrC,OAAO,KAAK,mBAAmB,SAAS,kBAAkB;CAC5D;;;;;CAMA,IAAW,kBAA+B;EACxC,OAAO,KAAK,GAAG;CACjB;;;;;;;CAQA,IAAW,uBAAgC;EACzC,OACE,KAAK,mBAAmB,SAAS,iBAAiB,KAClDA,sBAAAA,mBAAmB,KAA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AIC,2BAAAA,qBAAqB;GAC/C,QAAQ,UAAU;GAClB;GACA,gBAAgB,GAAG;GACnB;GACA;GACA;GACA,wBAAwB,UAAU;GAClC;GACA,oBAAoB,IAAIC,gBAAAA,mBAAmB,oBAAoB,QAAQ;IACrE,UAAU,IAAI;IACd,MAAM;IACN,wBAAwB,IAAI;GAC9B,CAAC;GACD;GACA;GACA;GACA,eAAe,IAAIC,uBAAAA,cAAc,SAAS,MAAM;GAChD,SAAS,YAAY;IACnB,MAAM,gBAAgB,QAAQ;IAC9B,MAAM,oBAAoB,QAAQ;IAClC,MAAM,UAAU,QAAQ;GAC1B;EACF;EAEA,MAAM,iBAAiB,IAAIC,2BAAAA,eAA4B,CAAC,CAAC;EACzD,MAAM,gBAAgB,MAAMC,qBAAAA,kBAAkB,IAAI,UAAU,gBAAgB,GAAG;EAG/E,MAAM,aAAa,MAAMC,qBAAAA,qBAAqB,IAAI,eAAe,GAAG;EACpE,MAAM,mBAAmB,MAAMC,qBAAAA,uBAAuB,IAAI,cAAc,GAAG;EAC3E,MAAM,oBAAoB,MAAMC,qBAAAA,wBAAwB,IAAI,GAAG;EAC/D,MAAM,gBAAgBC,qBAAAA,8BACpB,mBACA,kBACA,GAAG,cAAc,QACnB;EACA,MAAM,gBAAgBC,qBAAAA,8BAA8B,iBAAiB;EAErE,OAAO,IAAI,YACT,KACA,WACA,UAAU,QACV,UACA,eACA,cACA,gBACA,cAAc,MACd,WAAW,MACX,kBACA,mBACA,oBACA,cAAc,YACd,WAAW,YACX,eACA,aACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"middle_layer.cjs","names":["canGrantToEveryone","canImpersonate","LRUCache","createProject","withProjectAuthored","ProjectMetaKey","isNotNullSignedResourceId","duplicateProject","ensureProjectListRid","buildShareEnvelope","GrantType","isEnvelopeProjectField","envelopeProjectFieldUuid","isAcceptanceField","acceptanceFieldLogin","decodeEnvelopeData","copyEnvelopeProjectsIntoList","resourceIdsToStrings","Project","HmacSha256Signer","DefaultMiddleLayerOpsSettings","DefaultMiddleLayerOpsPaths","getDebugFlags","ProjectsField","ProjectsResourceType","SharingOutboxField","SharingOutboxResourceType","SharingStateField","SharingStateResourceType","initDriverKit","RetryAgent","V2RegistryProvider","BlockPackPreparer","RuntimeCapabilities","REQUIRES_PFRAMES_VERSION","createModelServiceRegistry","BlockEventDispatcher","BlockUpdateWatcher","ProjectHelper","WatchableValue","createProjectList","createOutgoingShares","createSharingStateTree","createPendingSharesTree","createPendingSharesComputable","createLiveEnvelopesComputable"],"sources":["../../src/middle_layer/middle_layer.ts"],"sourcesContent":["import type {\n PlClient,\n PlTransaction,\n SignedResourceId,\n ResourceRef,\n Role,\n} from \"@milaboratories/pl-client\";\nimport {\n isEveryoneUserLogin,\n field,\n GrantType,\n isNotNullSignedResourceId,\n isNullSignedResourceId,\n resourceIdToString,\n} from \"@milaboratories/pl-client\";\nimport { LRUCache } from \"lru-cache\";\nimport {\n createProjectList,\n ensureProjectListRid,\n ProjectsField,\n ProjectsResourceType,\n} from \"./project_list\";\nimport { createProject, duplicateProject, withProjectAuthored } from \"../mutator/project\";\nimport { ProjectMetaKey } from \"../model/project_model\";\nimport type { ProjectId } from \"../model/project_model\";\nimport type { SynchronizedTreeState } from \"@milaboratories/pl-tree\";\nimport {\n acceptanceFieldLogin,\n canGrantToEveryone,\n canImpersonate,\n decodeEnvelopeData,\n isAcceptanceField,\n SharingOutboxField,\n SharingOutboxResourceType,\n SharingStateField,\n SharingStateResourceType,\n type EnvelopeAcceptance,\n type EnvelopeData,\n type ProjectChangeAction,\n type ProjectFieldUuid,\n type ShareId,\n type ShareProjectsOptions,\n} from \"../model/sharing_model\";\nimport {\n buildShareEnvelope,\n copyEnvelopeProjectsIntoList,\n envelopeProjectFieldUuid,\n isEnvelopeProjectField,\n resourceIdsToStrings,\n writeEnvelopeAcceptance,\n writeSharingDecision,\n type EnvelopeProjectSource,\n} from \"../mutator/sharing\";\nimport type { LiveEnvelope, OutgoingShare, PendingShare } from \"./sharing_list\";\nimport {\n createLiveEnvelopesComputable,\n createOutgoingShares,\n createPendingSharesComputable,\n createPendingSharesTree,\n createSharingStateTree,\n} from \"./sharing_list\";\nimport { BlockPackPreparer } from \"../mutator/block-pack/block_pack\";\nimport type { MiLogger, Signer } from \"@milaboratories/ts-helpers\";\nimport { BlockEventDispatcher, cachedDeserialize } from \"@milaboratories/ts-helpers\";\nimport { HmacSha256Signer } from \"@milaboratories/ts-helpers\";\nimport type { Computable, ComputableStableDefined } from \"@milaboratories/computable\";\nimport { WatchableValue } from \"@milaboratories/computable\";\nimport { Project } from \"./project\";\nimport type { MiddleLayerOps, MiddleLayerOpsConstructor } from \"./ops\";\nimport { DefaultMiddleLayerOpsPaths, DefaultMiddleLayerOpsSettings } from \"./ops\";\nimport { randomUUID } from \"node:crypto\";\nimport type { ProjectListEntry } from \"../model\";\nimport type {\n AuthorMarker,\n ProjectMeta,\n BlockPlatform,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport { BlockUpdateWatcher } from \"../block_registry/watcher\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { getQuickJS } from \"quickjs-emscripten\";\nimport type { MiddleLayerDriverKit } from \"./driver_kit\";\nimport { initDriverKit } from \"./driver_kit\";\nimport type { BlockCodeFeatureFlags, DriverKit, SupportedRequirement } from \"@platforma-sdk/model\";\nimport { RuntimeCapabilities } from \"@platforma-sdk/model\";\nimport {\n type ModelServiceRegistry,\n registerServiceCapabilities,\n REQUIRES_PFRAMES_VERSION,\n} from \"@milaboratories/pl-model-common\";\nimport { createModelServiceRegistry } from \"../service_factories\";\nimport type { DownloadUrlDriver } from \"@milaboratories/pl-drivers\";\nimport { V2RegistryProvider } from \"../block_registry\";\nimport type { Dispatcher } from \"undici\";\nimport { RetryAgent } from \"undici\";\nimport { getDebugFlags } from \"../debug\";\nimport { ProjectHelper } from \"../model/project_helper\";\n\nexport interface MiddleLayerEnvironment {\n dispose(): Promise<void>;\n readonly pl: PlClient;\n readonly runtimeCapabilities: RuntimeCapabilities;\n readonly logger: MiLogger;\n readonly blockEventDispatcher: BlockEventDispatcher;\n readonly httpDispatcher: Dispatcher;\n readonly retryHttpDispatcher: Dispatcher;\n readonly signer: Signer;\n readonly ops: MiddleLayerOps;\n readonly bpPreparer: BlockPackPreparer;\n readonly frontendDownloadDriver: DownloadUrlDriver;\n readonly blockUpdateWatcher: BlockUpdateWatcher;\n readonly quickJs: QuickJSWASMModule;\n readonly driverKit: MiddleLayerDriverKit;\n readonly serviceRegistry: ModelServiceRegistry;\n readonly projectHelper: ProjectHelper;\n}\n\n/**\n * Main access object to work with pl from UI.\n *\n * It implements an abstraction layer of projects and blocks.\n *\n * As a main entry point inside the pl, this object uses a resource attached\n * via the {@link ProjectsField} to the pl client's root, this resource\n * contains project list.\n *\n * Read about alternative roots, if isolated project lists (working environments)\n * are required.\n * */\nexport class MiddleLayer {\n public readonly pl: PlClient;\n\n private constructor(\n private readonly env: MiddleLayerEnvironment,\n public readonly driverKit: DriverKit,\n public readonly signer: Signer,\n private readonly projectListResourceId: SignedResourceId,\n private readonly sharingOutboxResourceId: SignedResourceId,\n private readonly sharingStateResourceId: SignedResourceId,\n private readonly openedProjectsList: WatchableValue<ProjectId[]>,\n private readonly projectListTree: SynchronizedTreeState,\n private readonly sharingOutboxTree: SynchronizedTreeState,\n private readonly sharingStateTree: SynchronizedTreeState,\n private readonly pendingSharesTree: SynchronizedTreeState,\n public readonly blockRegistryProvider: V2RegistryProvider,\n /** Contains a reactive list of projects along with their meta information. */\n public readonly projectList: ComputableStableDefined<ProjectListEntry[]>,\n /** Reactive view of the donor's outbox — the shares this user has created.\n * v1: API only, no UI. */\n public outgoingShares: Computable<OutgoingShare[] | undefined>,\n /** Envelopes granted to this user, not yet accepted or rejected. Fed by the\n * shared-resource discovery tree. */\n public pendingShares: Computable<PendingShare[] | undefined>,\n /** Internal: the acceptor's currently-live envelopes, read from the same shared-resource\n * discovery tree as {@link pendingShares}. The single source the accept/reject flow resolves\n * live envelopes from — no second discovery path. */\n private readonly liveEnvelopes: Computable<LiveEnvelope[] | undefined>,\n ) {\n this.pl = this.env.pl;\n this.startEnvelopeCleanup();\n }\n\n /**\n * Get the OS where backend is running.\n * For old backend versions returns undefined.\n */\n public get serverPlatform(): BlockPlatform | undefined {\n return this.pl.serverInfo.platform as BlockPlatform | undefined;\n }\n\n /**\n * Runtime capabilities advertised by the connected backend (tokens of\n * the form `<feature>:<version>`, e.g. \"wasm:v1\"). Empty list if the\n * backend predates the capability mechanism — that's the desired\n * fail-closed behaviour for blocks declaring any `requiredCapabilities`.\n */\n public get serverCapabilities(): string[] {\n return this.pl.serverInfo.capabilities ?? [];\n }\n\n /**\n * Login of the authenticated user, for the \"Signed in as\" UI. `null` when the\n * backend has no auth (local/dev mode) — the UI hides the element.\n */\n public get currentUserLogin(): string | null {\n return this.pl.userResources.authUser;\n }\n\n /**\n * Whether the connected backend supports project sharing. Synthetic — computed\n * in the middle layer from the backend capabilities the share flow needs (the\n * cross-color field-reference relaxation the accept flow rests on). It can absorb\n * additional required capabilities later without a UI change.\n */\n public get sharingSupported(): boolean {\n // Sharing does not compose with impersonation (discovery is scoped to the admin's session,\n // decisions attribute to the admin), so it is disabled while impersonating. Admins move\n // projects across roots with duplicateProjectToUser instead.\n return this.serverCapabilities.includes(\"crossTreeRefs:v1\") && !this.impersonating;\n }\n\n /** True when this session is impersonating another user (an admin opened another user's root). */\n public get impersonating(): boolean {\n return this.pl.conf.asUser !== undefined;\n }\n\n /**\n * Role of the authenticated user, from the `GetSessionInfo` RPC surfaced through the\n * pl-client. `null` in no-auth mode (when {@link currentUserLogin} is null).\n */\n public get currentUserRole(): Role | null {\n return this.pl.currentUserRole;\n }\n\n /**\n * Whether the UI offers share-with-everybody — no role policy lives in the UI:\n * serverCapabilities.has(\"publicGrants:v1\") && canGrantToEveryone(currentUserRole)\n * Not a security boundary: a crafted call still hits the backend's role +\n * permission-ceiling gate.\n */\n public get canShareWithEveryone(): boolean {\n return (\n !this.impersonating &&\n this.serverCapabilities.includes(\"publicGrants:v1\") &&\n canGrantToEveryone(this.currentUserRole)\n );\n }\n\n /**\n * Whether the authenticated user may impersonate others (open another user's root). Mirrors\n * the backend's `CanImpersonate` role gate — admin/controller only, never a regular user.\n * Derived from the session role, which stays the authenticated admin's even while\n * impersonating, so this stays true across a switch: the \"return to my root\" affordance must\n * not vanish mid-impersonation. Not a security boundary; the backend re-checks on every call.\n */\n public get currentUserCanImpersonate(): boolean {\n return canImpersonate(this.currentUserRole);\n }\n\n /** Adds a runtime capability to the middle layer. */\n public addRuntimeCapability(\n requirement: SupportedRequirement,\n value: number | boolean = true,\n ): void {\n this.env.runtimeCapabilities.addSupportedRequirement(requirement, value);\n }\n\n /** Checks if the given block feature flags are compatible with the runtime capabilities. */\n public checkBlockCompatibility(featureFlags: BlockCodeFeatureFlags | undefined): boolean {\n return this.env.runtimeCapabilities.checkCompatibility(featureFlags);\n }\n\n /** Returns extended API driver kit used internally by middle layer. */\n public get internalDriverKit(): MiddleLayerDriverKit {\n return this.env.driverKit;\n }\n\n /** Returns the service registry for service introspection. */\n public get serviceRegistry(): ModelServiceRegistry {\n return this.env.serviceRegistry;\n }\n\n //\n // ProjectId ↔ SignedResourceId resolution\n //\n\n private readonly projectIdCache = new LRUCache<ProjectId, SignedResourceId>({ max: 1024 });\n\n /** Resolves a ProjectId to a signed SignedResourceId.\n * Uses LRU cache with TX-scan fallback. */\n private async resolveProjectId(projectId: ProjectId): Promise<SignedResourceId> {\n const cached = this.projectIdCache.get(projectId);\n if (cached !== undefined) return cached;\n\n // Cache miss — scan project list fields to find the matching resource\n const rid = await this.pl.withReadTx(\"ResolveProjectId\", async (tx) => {\n const data = await tx.getResourceData(this.projectListResourceId, true);\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n if (resourceIdToString(f.value) === (projectId as string)) return f.value;\n }\n throw new Error(`Project ${projectId} not found in project list.`);\n });\n\n this.projectIdCache.set(projectId, rid);\n return rid;\n }\n\n //\n // Project List Manipulation\n //\n\n /** Creates a project with initial state and adds it to project list. */\n public async createProject(meta: ProjectMeta): Promise<ProjectId> {\n let prj: ResourceRef;\n await this.pl.withWriteTx(\"MLCreateProject\", async (tx) => {\n prj = await createProject(tx, meta);\n tx.createField(field(this.projectListResourceId, randomUUID()), \"Dynamic\", prj);\n await tx.commit();\n });\n await this.projectListTree.refreshState();\n\n const signedRid = await prj!.globalId;\n const projectId = resourceIdToString(signedRid) as ProjectId;\n this.projectIdCache.set(projectId, signedRid);\n return projectId;\n }\n\n /** Updates project metadata */\n public async setProjectMeta(\n id: ProjectId,\n meta: ProjectMeta,\n author?: AuthorMarker,\n ): Promise<void> {\n const rid = await this.resolveProjectId(id);\n await withProjectAuthored(\n this.env.projectHelper,\n this.pl,\n rid,\n author,\n (prj) => {\n prj.setMeta(meta);\n },\n { name: \"setProjectMeta\" },\n );\n await this.projectListTree.refreshState();\n }\n\n /** Permanently deletes project from the project list, this will result in\n * destruction of all attached objects, like files, analysis results etc. */\n public async deleteProject(id: ProjectId): Promise<void> {\n await this.pl.withWriteTx(\"MLRemoveProject\", async (tx) => {\n const data = await tx.getResourceData(this.projectListResourceId, true);\n let fieldName: string | undefined;\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n if (resourceIdToString(f.value) === (id as string)) {\n fieldName = f.name;\n break;\n }\n }\n if (fieldName === undefined) throw new Error(`Project ${id} not found in project list.`);\n tx.removeField(field(this.projectListResourceId, fieldName));\n await tx.commit();\n });\n this.projectIdCache.delete(id);\n await this.projectListTree.refreshState();\n }\n\n /**\n * Duplicates an existing project and adds the copy to this user's project list.\n *\n * @param srcProjectId - project id of the project to duplicate\n * @param rename - optional function that receives the source label and all existing\n * project labels (read within the same transaction), and returns the label for the copy\n */\n public async duplicateProject(\n srcProjectId: ProjectId,\n rename?: (previousLabel: string, existingLabels: string[]) => string,\n ): Promise<ProjectId> {\n const sourceRid = await this.resolveProjectId(srcProjectId);\n\n const newPrj: ResourceRef = await this.pl.withWriteTx(\"MLDuplicateProject\", async (tx) => {\n // Read source project meta\n const sourceMeta = await tx.getKValueJson<ProjectMeta>(sourceRid, ProjectMetaKey);\n\n // Read all existing project labels from the project list (parallel reads)\n const projectListData = await tx.getResourceData(this.projectListResourceId, true);\n const projectRids = projectListData.fields\n .map((f) => f.value)\n .filter(isNotNullSignedResourceId);\n const existingLabels = (\n await Promise.all(\n projectRids.map((rid) => tx.getKValueJson<ProjectMeta>(rid, ProjectMetaKey)),\n )\n ).map((m) => m.label);\n\n // Compute new label\n const newLabel = rename ? rename(sourceMeta.label, existingLabels) : sourceMeta.label;\n\n // Create the duplicate\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n\n // Attach to project list with a random UUID field name\n tx.createField(field(this.projectListResourceId, randomUUID()), \"Dynamic\", newPrj);\n await tx.commit();\n\n return newPrj;\n });\n\n await this.projectListTree.refreshState();\n\n const signedRid = await newPrj.globalId;\n const newProjectId = resourceIdToString(signedRid) as ProjectId;\n this.projectIdCache.set(newProjectId, signedRid);\n return newProjectId;\n }\n\n /**\n * Duplicates a project into another user's root, minted in the TARGET user's color so the target\n * owns it. Sibling of {@link duplicateProject}, but writes into a different root. The source\n * project (on the current client root) is referenced cross-color for its block data, kept alive\n * by refcounting, exactly like accepting a shared project. Works both ways: pull (while\n * impersonating a user, copy their project to yourself) and push (from your own root, copy a\n * project to a user). Admin cross-root op; requires the crossTreeRefs:v1 backend capability.\n */\n public async duplicateProjectToUser(\n srcProjectId: ProjectId,\n targetLogin: string,\n rename?: (previousLabel: string, existingLabels: string[]) => string,\n ): Promise<void> {\n if (!this.serverCapabilities.includes(\"crossTreeRefs:v1\"))\n throw new Error(\"duplicateProjectToUser requires the crossTreeRefs:v1 backend capability.\");\n\n const sourceRid = await this.resolveProjectId(srcProjectId);\n const targetRoot = await this.pl.getUserRoot({ login: targetLogin, createIfNotExists: true });\n\n // Run on the target root: the tx default color is the target's, so the new project (and the\n // target's project list, if created here) are minted in the target's color.\n await this.pl.withWriteTxOnRoot(targetRoot, \"MLDuplicateProjectToUser\", async (tx) => {\n // Resolve or lazily create the target root's project list (tx.clientRoot === targetRoot).\n const targetProjectListRid = await ensureProjectListRid(tx);\n\n // Source label + the target's existing labels, for collision-aware renaming.\n const sourceMeta = await tx.getKValueJson<ProjectMeta>(sourceRid, ProjectMetaKey);\n const targetListData = await tx.getResourceData(targetProjectListRid, true);\n const existingLabels = (\n await Promise.all(\n targetListData.fields\n .map((f) => f.value)\n .filter(isNotNullSignedResourceId)\n .map((rid) => tx.getKValueJson<ProjectMeta>(rid, ProjectMetaKey)),\n )\n ).map((m) => m.label);\n const newLabel = rename ? rename(sourceMeta.label, existingLabels) : sourceMeta.label;\n\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n tx.createField(field(targetProjectListRid, randomUUID()), \"Dynamic\", newPrj);\n await tx.commit();\n });\n }\n\n //\n // Project Sharing (Copy & Share)\n //\n\n /**\n * Shares the given projects (Copy & Share). Snapshots the projects, creates one envelope, and\n * grants it — all in one atomic write transaction, so a failed grant rolls the whole thing back\n * and the outbox is left as it was.\n *\n * Two variants (see {@link ShareProjectsOptions}):\n * - `{ recipients }` — one writable grant per named recipient; the envelope expires after the\n * default TTL (`sharedAt + envelopeTtlMs`).\n * - `{ everyone: true }` — one make-public grant (backend rewrites the target to the\n * everyone-user); the envelope's `expiresAt` is `null`, so it never expires.\n *\n * v1 always passes `mode: \"copy\"`.\n */\n public async shareProjects(\n projectIds: ProjectId[],\n options: ShareProjectsOptions,\n ): Promise<void> {\n if (projectIds.length === 0) throw new Error(\"shareProjects: no projects given\");\n\n // Everyone + replace: refresh the existing everyone-share of this project under its stable\n // shareId (so recipients who already decided aren't re-prompted), if one exists. Found\n // automatically by project overlap; falls through to a fresh share when none exists.\n if (\"everyone\" in options && options.replace) {\n const priorEveryone = (await this.findSupersedableEnvelopes(projectIds)).find(\n (p) => p.everyone,\n );\n if (priorEveryone !== undefined) {\n await this.changeShare(priorEveryone.shareId, { title: options.title });\n return;\n }\n }\n\n await this.createNewShare(projectIds, options);\n }\n\n /**\n * Mints a fresh share: snapshots the projects into one new envelope (a fresh shareId),\n * supersedes prior shares of the same project, and grants it — all in one atomic write\n * transaction, so a failed grant rolls the whole thing back and the outbox is left as it was.\n * The everyone-refresh path is the {@link changeShare} branch of {@link shareProjects}; this is\n * the mint-a-new-envelope branch.\n */\n private async createNewShare(\n projectIds: ProjectId[],\n options: ShareProjectsOptions,\n ): Promise<void> {\n const everyone = \"everyone\" in options;\n const sources: EnvelopeProjectSource[] = await Promise.all(\n projectIds.map(\n async (id): Promise<EnvelopeProjectSource> => ({\n kind: \"fresh\",\n projectId: id,\n sourceRid: await this.resolveProjectId(id),\n }),\n ),\n );\n const sender = this.currentUserLogin ?? \"\";\n // Targeted share: sharedAt + ttl. Share-with-everybody: never expires (null).\n const expiresAt = everyone ? null : Date.now() + this.env.ops.envelopeTtlMs;\n\n // Supersede prior shares of the same project(s) so they never pile up. Resolved before\n // the write tx (ListGrants is a separate RPC). Everyone-share supersedes a prior\n // everyone-share of the same project; a targeted share pulls each named recipient out of\n // any prior share of that project, deleting that share if it ends up with no recipients.\n const priors = await this.findSupersedableEnvelopes(projectIds);\n\n await this.pl.withWriteTx(\"MLShareProjects\", async (tx) => {\n if (everyone) {\n for (const prior of priors) {\n if (prior.everyone) tx.removeField(field(this.sharingOutboxResourceId, prior.fieldName));\n }\n } else {\n const newRecipients = new Set(options.recipients);\n for (const prior of priors) {\n if (prior.everyone) continue; // a single user can't be pulled from an everyone-grant\n const toRemove = prior.recipients.filter((u) => newRecipients.has(u));\n if (toRemove.length === 0) continue;\n const remaining = prior.recipients.filter((u) => !newRecipients.has(u));\n if (remaining.length === 0) {\n // Nobody left on the old share — drop the whole envelope.\n tx.removeField(field(this.sharingOutboxResourceId, prior.fieldName));\n } else {\n for (const u of toRemove) tx.revokeAccess(prior.rid, u);\n }\n }\n }\n\n const { envelope } = await buildShareEnvelope(tx, this.sharingOutboxResourceId, sources, {\n mode: options.mode,\n sender,\n title: options.title,\n expiresAt,\n });\n\n // Grant in the same transaction (writable: the cross-color accept rule demands a writable\n // grant on the envelope). Atomic with the create.\n const envelopeGid = await envelope.globalId;\n if (everyone) {\n // One everyone-grant: empty/ignored target, ANY_AUTHORISED. The backend rewrites\n // the target to the everyone-user; gated by role + permission ceiling.\n tx.grantAccess(envelopeGid, \"\", { writable: true }, GrantType.ANY_AUTHORISED);\n } else {\n for (const recipient of options.recipients) {\n tx.grantAccess(envelopeGid, recipient, { writable: true });\n }\n }\n\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n }\n\n /**\n * Changes a share in place (same {@link ShareId}), in one write transaction: re-snapshots live\n * source projects and carries deleted ones' snapshots forward; applies edited recipients/title;\n * transfers already-decided recipients' accept/reject records (they keep their copy and aren't\n * re-prompted); re-grants; drops the old envelope.\n *\n * `opts.recipients` is the full targeted set (decided users are always kept). `opts.title`\n * replaces the title — omit keeps the current one. `opts.everyone` upgrades targeted ->\n * everyone; the reverse is impossible and ignored.\n *\n * `opts.projectActions` is a per-source-project decision, keyed by projectId: `update`\n * re-snapshots the live source (falls back to carry if the source is gone), `keep` carries the\n * existing snapshot (and its timestamp), `remove` drops the project from the pack. A project not\n * in the map defaults to `keep`. Omit the whole map for the legacy auto behavior (live sources\n * updated, gone ones kept) — the everyone-refresh path relies on that.\n */\n public async changeShare(\n shareId: ShareId,\n opts: {\n recipients?: string[];\n everyone?: boolean;\n title?: string;\n projectActions?: Record<ProjectId, ProjectChangeAction>;\n } = {},\n ): Promise<void> {\n await this.pl.withWriteTx(\"MLChangeShare\", async (tx) => {\n const old = await this.resolveOutboxEnvelope(tx, shareId);\n if (old === undefined)\n throw new Error(`changeShare: no live share with id ${shareId} in the outbox.`);\n\n const self = this.currentUserLogin ?? \"\";\n const grants = await tx.listGrants(old.rid);\n // A targeted share may be upgraded to everyone; an everyone-share can't be narrowed back.\n const everyone = grants.some((g) => isEveryoneUserLogin(g.user)) || opts.everyone === true;\n\n // Read the old envelope's project snapshots (uuid -> rid) and accept/reject records.\n const oldRd = await tx.getResourceData(old.rid, true);\n const snapshotByUuid = new Map<string, SignedResourceId>();\n const acceptances: { login: string; acc: EnvelopeAcceptance }[] = [];\n for (const f of oldRd.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n if (isEnvelopeProjectField(f.name)) {\n snapshotByUuid.set(envelopeProjectFieldUuid(f.name), f.value);\n } else if (isAcceptanceField(f.name)) {\n const raw = (await tx.getResourceData(f.value, false)).data;\n if (raw === undefined) continue;\n acceptances.push({\n login: acceptanceFieldLogin(f.name),\n acc: cachedDeserialize(raw) as EnvelopeAcceptance,\n });\n }\n }\n const decidedLogins = acceptances.map((a) => a.login);\n\n // Everyone-shares ignore recipients; targeted shares keep decided users plus the edited set.\n const priorRecipients = grants\n .filter((g) => !isEveryoneUserLogin(g.user) && g.user !== self)\n .map((g) => g.user);\n const recipients = everyone\n ? []\n : Array.from(new Set([...(opts.recipients ?? priorRecipients), ...decidedLogins]));\n\n // Live source projects by persistable id — these get a fresh snapshot.\n const liveProjects = new Map<string, SignedResourceId>();\n const projList = await tx.getResourceData(this.projectListResourceId, true);\n for (const f of projList.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n liveProjects.set(resourceIdToString(f.value), f.value);\n }\n\n // Per project (keyed by field uuid), apply the caller's decision (default `keep`); with no\n // projectActions map, fall back to the legacy auto behavior: update a live source, keep a gone one.\n const actions = opts.projectActions;\n const sources: EnvelopeProjectSource[] = [];\n for (const uuid of Object.keys(old.data.projects) as ProjectFieldUuid[]) {\n const { label, source, updatedAt } = old.data.projects[uuid];\n const liveRid = liveProjects.get(source);\n\n const action = actions\n ? (actions[source] ?? \"keep\")\n : liveRid !== undefined\n ? \"update\"\n : \"keep\";\n if (action === \"remove\") continue;\n\n if (action === \"update\" && liveRid !== undefined) {\n sources.push({ kind: \"fresh\", projectId: source, sourceRid: liveRid });\n } else {\n // keep, or an \"update\" whose source vanished before commit (deleted meanwhile, e.g. from\n // another client): carry the prior snapshot. Liveness is read inside this write tx — race-safe.\n const snapshotRid = snapshotByUuid.get(uuid);\n if (snapshotRid !== undefined)\n sources.push({ kind: \"carry\", projectId: source, label, snapshotRid, updatedAt });\n }\n }\n\n // Omit (undefined) keeps the current title; a provided value replaces it.\n const title = opts.title === undefined ? old.data.title : opts.title.trim();\n const expiresAt = everyone ? null : Date.now() + this.env.ops.envelopeTtlMs;\n\n // Same shareId, same outbox field name — detach the old field before rebuilding, or they collide.\n tx.removeField(field(this.sharingOutboxResourceId, old.fieldName));\n\n const { envelope } = await buildShareEnvelope(tx, this.sharingOutboxResourceId, sources, {\n mode: old.data.mode,\n sender: self,\n title,\n expiresAt,\n shareId, // SAME shareId — the essence of change\n });\n\n // Transfer the decided users' records onto the new envelope (donor-written copies).\n for (const { login, acc } of acceptances) {\n if (!everyone && !recipients.includes(login)) continue;\n writeEnvelopeAcceptance(tx, envelope, login, acc.action, acc.timestamp);\n }\n\n const gid = await envelope.globalId;\n if (everyone) tx.grantAccess(gid, \"\", { writable: true }, GrantType.ANY_AUTHORISED);\n else for (const r of recipients) tx.grantAccess(gid, r, { writable: true });\n\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n }\n\n /**\n * Finds the donor's own outgoing envelopes built from any of the given source projects —\n * the supersede candidates for a fresh share of the same project(s). Reads each envelope's\n * recipient set via `ListGrants` so the caller can pull individual recipients or detect an\n * everyone-share.\n */\n private async findSupersedableEnvelopes(projectIds: ProjectId[]): Promise<\n {\n fieldName: string;\n rid: SignedResourceId;\n shareId: ShareId;\n everyone: boolean;\n recipients: string[];\n }[]\n > {\n const wanted = new Set(projectIds);\n\n const matched = await this.pl.withReadTx(\"MLFindSupersede\", async (tx) => {\n const outbox = await tx.getResourceData(this.sharingOutboxResourceId, true);\n const out: { fieldName: string; rid: SignedResourceId; shareId: ShareId }[] = [];\n for (const f of outbox.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const rd = await tx.getResourceData(f.value, false);\n if (rd.data === undefined) continue;\n const data = decodeEnvelopeData(rd.data);\n if (Object.values(data.projects).some((p) => wanted.has(p.source)))\n out.push({ fieldName: f.name, rid: f.value, shareId: data.shareId });\n }\n return out;\n });\n\n return await Promise.all(\n matched.map(async ({ fieldName, rid, shareId }) => {\n const grants = await this.pl.userResources.listGrants(rid);\n return {\n fieldName,\n rid,\n shareId,\n everyone: grants.some((g) => isEveryoneUserLogin(g.user)),\n recipients: grants.filter((g) => !isEveryoneUserLogin(g.user)).map((g) => g.user),\n };\n }),\n );\n }\n\n /**\n * Revokes and deletes an outgoing share for all recipients: detaches and deletes the envelope, and\n * its grants are revoked along with it. Already-accepted copies are unaffected (ref-counting keeps\n * the adopted resources alive). Idempotent — revoking a share that is already gone is a no-op.\n */\n public async revokeShare(shareId: ShareId): Promise<void> {\n await this.pl.withWriteTx(\"MLRevokeShare\", async (tx) => {\n const target = await this.resolveOutboxEnvelope(tx, shareId);\n if (target === undefined) return;\n tx.removeField(field(this.sharingOutboxResourceId, target.fieldName));\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n }\n\n /**\n * Resolves a live envelope from the donor's own outbox by its logical `shareId`, returning the\n * outbox field name (for detach), the signed envelope id, and its decoded {@link EnvelopeData}.\n * The outbox is keyed by `{shareId}` directly, but a replaced/legacy share may have drifted, so\n * we match on the decoded `shareId` rather than the field name alone.\n */\n private async resolveOutboxEnvelope(\n tx: PlTransaction,\n shareId: ShareId,\n ): Promise<{ fieldName: string; rid: SignedResourceId; data: EnvelopeData } | undefined> {\n const outboxData = await tx.getResourceData(this.sharingOutboxResourceId, true);\n for (const f of outboxData.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const rd = await tx.getResourceData(f.value, false);\n if (rd.data === undefined) continue;\n const data = decodeEnvelopeData(rd.data);\n if (data.shareId === shareId) return { fieldName: f.name, rid: f.value, data };\n }\n return undefined;\n }\n\n /**\n * Resolves currently-shared envelopes (granted to this user) to their resource ids, keyed by\n * the envelope's logical `shareId`.\n *\n * Reads the {@link liveEnvelopes} Computable — the same shared-resource discovery tree that\n * feeds {@link pendingShares}. This is the single discovery mechanism: there is no separate\n * `ListUserResources` re-stream on every accept/reject. `refreshState()` is awaited first so a\n * just-granted envelope is observed (the tree's discovery poll may otherwise lag a freshly\n * landed grant). The tree is gRPC-only, so this is empty on a REST-connected client.\n */\n private async resolveLiveEnvelopes(): Promise<Map<ShareId, LiveEnvelope>> {\n await this.pendingSharesTree.refreshState();\n const live = (await this.liveEnvelopes.getValue()) ?? [];\n // Dedup by logical shareId (last writer wins — at most one live envelope per shareId).\n const map = new Map<ShareId, LiveEnvelope>();\n for (const e of live) map.set(e.data.shareId, e);\n return map;\n }\n\n /**\n * Accepts one or more pending shares: duplicates each share's projects into this user's\n * project list, records the decision per share, and (read-write share) writes the donor-visible\n * acceptance onto the envelope. Per-share failures (e.g. an expiry race) are collected, not\n * short-circuited — the rest still get accepted. Accept-all = pass every current pending shareId.\n *\n * `rename` resolves label collisions (same callback contract as {@link duplicateProject}), but\n * the source lives in the envelope tree, so accept calls the low-level mutator directly.\n */\n public async acceptShare(\n shareIds: ShareId[],\n rename?: (previousLabel: string, existingLabels: string[]) => string,\n ): Promise<{ accepted: ProjectId[]; failed: { shareId: ShareId; error: string }[] }> {\n const live = await this.resolveLiveEnvelopes();\n const login = this.currentUserLogin;\n\n const accepted: ProjectId[] = [];\n const failed: { shareId: ShareId; error: string }[] = [];\n\n for (const shareId of shareIds) {\n const envelope = live.get(shareId);\n if (envelope === undefined) {\n failed.push({ shareId, error: \"Share is no longer available.\" });\n continue;\n }\n try {\n const now = Date.now();\n const createdRids = await this.pl.withWriteTx(\"MLAcceptShare\", async (tx) => {\n const created = await copyEnvelopeProjectsIntoList(\n tx,\n envelope.rid,\n this.projectListResourceId,\n rename,\n );\n\n // Record the decision on the acceptor's own SharingState, keyed on shareId.\n writeSharingDecision(tx, this.sharingStateResourceId, shareId, {\n decision: \"accepted\",\n timestamp: now,\n envelopeSharedAt: envelope.data.sharedAt,\n acceptedProjects: resourceIdsToStrings(created),\n });\n\n // Read-write share: write the donor-visible acceptance onto the envelope.\n if (login !== null && envelope.data.mode !== \"read-only\")\n writeEnvelopeAcceptance(tx, envelope.rid, login, \"accepted\", now);\n\n await tx.commit();\n return created;\n });\n for (const rid of createdRids) {\n const projectId = resourceIdToString(rid) as ProjectId;\n this.projectIdCache.set(projectId, rid);\n accepted.push(projectId);\n }\n } catch (e) {\n failed.push({ shareId, error: e instanceof Error ? e.message : String(e) });\n }\n }\n\n await Promise.all([this.projectListTree.refreshState(), this.sharingStateTree.refreshState()]);\n return { accepted, failed };\n }\n\n /** Records rejection of a pending share; it never surfaces again. */\n public async rejectShare(shareId: ShareId): Promise<void> {\n const live = await this.resolveLiveEnvelopes();\n const envelope = live.get(shareId);\n const login = this.currentUserLogin;\n const now = Date.now();\n\n await this.pl.withWriteTx(\"MLRejectShare\", async (tx) => {\n writeSharingDecision(tx, this.sharingStateResourceId, shareId, {\n decision: \"rejected\",\n timestamp: now,\n envelopeSharedAt: envelope?.data.sharedAt ?? now,\n acceptedProjects: [],\n });\n\n // Read-write share: write the donor-visible rejection onto the envelope (if still live).\n if (envelope !== undefined && login !== null && envelope.data.mode !== \"read-only\")\n writeEnvelopeAcceptance(tx, envelope.rid, login, \"rejected\", now);\n\n await tx.commit();\n });\n\n await this.sharingStateTree.refreshState();\n }\n\n //\n // Outbox cleanup (donor side)\n //\n\n private static readonly EnvelopeCleanupIntervalMs = 6 * 3600 * 1000; // every 6h\n private envelopeCleanupTimer: ReturnType<typeof setInterval> | undefined;\n\n /** On ML start and every 6h, delete envelopes whose immutable `expiresAt` has passed. */\n private startEnvelopeCleanup(): void {\n void this.runEnvelopeCleanup();\n this.envelopeCleanupTimer = setInterval(() => {\n void this.runEnvelopeCleanup();\n }, MiddleLayer.EnvelopeCleanupIntervalMs);\n // Don't keep the process alive solely for cleanup.\n this.envelopeCleanupTimer.unref?.();\n }\n\n /** Scans the donor's outbox and deletes expired envelopes (backend auto-revokes their grants).\n * Envelopes with `expiresAt: null` (share-with-everybody) are skipped. */\n private async runEnvelopeCleanup(): Promise<void> {\n try {\n const now = Date.now();\n const expired = await this.pl.withReadTx(\"MLEnvelopeCleanupScan\", async (tx) => {\n const data = await tx.getResourceData(this.sharingOutboxResourceId, true);\n const toDelete: { fieldName: string }[] = [];\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const rd = await tx.getResourceData(f.value, false);\n if (rd.data === undefined) continue;\n const envData = decodeEnvelopeData(rd.data);\n if (envData.expiresAt === null) continue; // never expires\n if (envData.expiresAt <= now) toDelete.push({ fieldName: f.name });\n }\n return toDelete;\n });\n\n if (expired.length === 0) return;\n\n await this.pl.withWriteTx(\"MLEnvelopeCleanup\", async (tx) => {\n for (const { fieldName } of expired)\n tx.removeField(field(this.sharingOutboxResourceId, fieldName));\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n } catch (e) {\n this.env.logger.warn(\n `envelope cleanup failed: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n }\n\n //\n // Projects\n //\n\n private readonly openedProjects = new Map<ProjectId, Project>();\n\n /** Opens a project, and starts corresponding project maintenance loop. */\n public async openProject(id: ProjectId): Promise<void> {\n if (this.openedProjects.has(id)) throw new Error(`Project ${id} already opened`);\n const rid = await this.resolveProjectId(id);\n this.openedProjects.set(id, await Project.init(this.env, id, rid));\n this.openedProjectsList.setValue([...this.openedProjects.keys()]);\n }\n\n /** Closes the project, and deallocate all corresponding resources. */\n public async closeProject(id: ProjectId): Promise<void> {\n const prj = this.openedProjects.get(id);\n if (prj === undefined) throw new Error(`Project ${id} not found among opened projects`);\n this.openedProjects.delete(id);\n await prj.destroy();\n this.openedProjectsList.setValue([...this.openedProjects.keys()]);\n }\n\n /** Returns a project access object for an opened project. */\n public getOpenedProject(id: ProjectId): Project {\n const prj = this.openedProjects.get(id);\n if (prj === undefined) throw new Error(`Project ${id} not found among opened projects`);\n return prj;\n }\n\n /** Returns true if project with given id is currently opened. */\n public isProjectOpened(id: ProjectId): boolean {\n return this.openedProjects.has(id);\n }\n\n /**\n * Deallocates all runtime resources consumed by this object and awaits\n * actual termination of event loops and other processes associated with\n * them.\n */\n public async close() {\n if (this.envelopeCleanupTimer !== undefined) clearInterval(this.envelopeCleanupTimer);\n await Promise.all([...this.openedProjects.values()].map((prj) => prj.destroy()));\n // this.env.quickJs;\n await Promise.all([\n this.projectListTree.terminate(),\n this.sharingOutboxTree.terminate(),\n this.sharingStateTree.terminate(),\n this.pendingSharesTree.terminate(),\n ]);\n await this.env.dispose();\n await this.pl.close();\n }\n\n /** @deprecated */\n public async closeAndAwaitTermination() {\n await this.close();\n }\n\n /** Generates sufficiently random string to be used as local secret for the\n * middle layer */\n public static generateLocalSecret(): string {\n return HmacSha256Signer.generateSecret();\n }\n\n /** Returns a block event dispatcher, which can be used to listen to block events. */\n public get blockEventDispatcher(): BlockEventDispatcher {\n return this.env.blockEventDispatcher;\n }\n\n /** Initialize middle layer */\n public static async init(\n pl: PlClient,\n workdir: string,\n _ops: MiddleLayerOpsConstructor,\n ): Promise<MiddleLayer> {\n const ops: MiddleLayerOps = {\n ...DefaultMiddleLayerOpsSettings,\n ...DefaultMiddleLayerOpsPaths(workdir),\n ..._ops,\n };\n\n // overriding debug options from environment variables\n ops.defaultTreeOptions.logStat = getDebugFlags().logTreeStats;\n ops.debugOps.dumpInitialTreeState = getDebugFlags().dumpInitialTreeState;\n // apply MI_TREE_TRAVERSAL only when the embedder hasn't set an explicit mode\n if (\n ops.defaultTreeOptions.traversalMode === undefined &&\n getDebugFlags().treeTraversalMode !== undefined\n )\n ops.defaultTreeOptions.traversalMode = getDebugFlags().treeTraversalMode;\n\n const { projects, sharingOutbox, sharingState } = await pl.withWriteTx(\n \"MLInitialization\",\n async (tx) => {\n // Lazily create each clientRoot-attached singleton resource. Returns the existing\n // resource id if the field is already populated, otherwise creates + locks + sets it.\n const lazyInit = async (\n fieldName: string,\n type: { name: string; version: string },\n ): Promise<{ ref?: ResourceRef; existing?: SignedResourceId }> => {\n const f = field(tx.clientRoot, fieldName);\n tx.createField(f, \"Dynamic\");\n const fData = await tx.getField(f);\n if (isNullSignedResourceId(fData.value)) {\n const ref = tx.createEphemeral(type);\n tx.lock(ref);\n tx.setField(f, ref);\n return { ref };\n }\n return { existing: fData.value };\n };\n\n const projectsR = await lazyInit(ProjectsField, ProjectsResourceType);\n const outboxR = await lazyInit(SharingOutboxField, SharingOutboxResourceType);\n const stateR = await lazyInit(SharingStateField, SharingStateResourceType);\n\n await tx.commit();\n\n return {\n projects: projectsR.existing ?? (await projectsR.ref!.globalId),\n sharingState: stateR.existing ?? (await stateR.ref!.globalId),\n sharingOutbox: outboxR.existing ?? (await outboxR.ref!.globalId),\n };\n },\n );\n\n const logger = ops.logger;\n\n const driverKit = await initDriverKit(pl, workdir, ops.frontendDownloadPath, ops);\n\n // passed to components having no own retry logic\n const retryHttpDispatcher = new RetryAgent(pl.httpDispatcher);\n\n const v2RegistryProvider = new V2RegistryProvider(retryHttpDispatcher);\n\n const bpPreparer = new BlockPackPreparer(\n v2RegistryProvider,\n driverKit.signer,\n retryHttpDispatcher,\n );\n\n const quickJs = await getQuickJS();\n\n const runtimeCapabilities = new RuntimeCapabilities();\n // add runtime capabilities of model here\n runtimeCapabilities.addSupportedRequirement(\"requiresModelAPIVersion\", 1);\n runtimeCapabilities.addSupportedRequirement(\"requiresModelAPIVersion\", 2);\n runtimeCapabilities.addSupportedRequirement(\"requiresCreatePTable\", 2);\n runtimeCapabilities.addSupportedRequirement(\"requiresPFramesVersion\", REQUIRES_PFRAMES_VERSION);\n registerServiceCapabilities((flag, value) =>\n runtimeCapabilities.addSupportedRequirement(flag, value),\n );\n // runtime capabilities of the desktop are to be added by the desktop app / test framework\n\n const serviceRegistry = createModelServiceRegistry({ logger });\n\n const env: MiddleLayerEnvironment = {\n pl,\n blockEventDispatcher: new BlockEventDispatcher(),\n signer: driverKit.signer,\n logger,\n httpDispatcher: pl.httpDispatcher,\n retryHttpDispatcher,\n ops,\n bpPreparer,\n frontendDownloadDriver: driverKit.frontendDriver,\n driverKit,\n blockUpdateWatcher: new BlockUpdateWatcher(v2RegistryProvider, logger, {\n minDelay: ops.devBlockUpdateRecheckInterval,\n http: retryHttpDispatcher,\n preferredUpdateChannel: ops.preferredUpdateChannel,\n }),\n runtimeCapabilities,\n serviceRegistry,\n quickJs,\n projectHelper: new ProjectHelper(quickJs, logger),\n dispose: async () => {\n await serviceRegistry.dispose();\n await retryHttpDispatcher.destroy();\n await driverKit.dispose();\n },\n };\n\n const openedProjects = new WatchableValue<ProjectId[]>([]);\n const projectListTC = await createProjectList(pl, projects, openedProjects, env);\n\n // Project sharing trees and reactive views.\n const outgoingTC = await createOutgoingShares(pl, sharingOutbox, env);\n const sharingStateTree = await createSharingStateTree(pl, sharingState, env);\n const pendingSharesTree = await createPendingSharesTree(pl, env);\n const pendingShares = createPendingSharesComputable(\n pendingSharesTree,\n sharingStateTree,\n pl.userResources.authUser,\n );\n const liveEnvelopes = createLiveEnvelopesComputable(pendingSharesTree);\n\n return new MiddleLayer(\n env,\n driverKit,\n driverKit.signer,\n projects,\n sharingOutbox,\n sharingState,\n openedProjects,\n projectListTC.tree,\n outgoingTC.tree,\n sharingStateTree,\n pendingSharesTree,\n v2RegistryProvider,\n projectListTC.computable,\n outgoingTC.computable,\n pendingShares,\n liveEnvelopes,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgIA,IAAa,cAAb,MAAa,YAAY;CAIJ;CACD;CACA;CACC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;CAEA;CAGT;CAGA;CAIU;CA1BnB;CAEA,YACE,KACA,WACA,QACA,uBACA,yBACA,wBACA,oBACA,iBACA,mBACA,kBACA,mBACA,uBAEA,aAGA,gBAGA,eAIA,eACA;EAxBiB,KAAA,MAAA;EACD,KAAA,YAAA;EACA,KAAA,SAAA;EACC,KAAA,wBAAA;EACA,KAAA,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IAAI,cAAc,GAAG;EAC3E,MAAM,oBAAoB,MAAMC,qBAAAA,wBAAwB,IAAI,GAAG;EAC/D,MAAM,gBAAgBC,qBAAAA,8BACpB,mBACA,kBACA,GAAG,cAAc,QACnB;EACA,MAAM,gBAAgBC,qBAAAA,8BAA8B,iBAAiB;EAErE,OAAO,IAAI,YACT,KACA,WACA,UAAU,QACV,UACA,eACA,cACA,gBACA,cAAc,MACd,WAAW,MACX,kBACA,mBACA,oBACA,cAAc,YACd,WAAW,YACX,eACA,aACF;CACF;AACF"}
|
|
@@ -100,6 +100,8 @@ declare class MiddleLayer {
|
|
|
100
100
|
* additional required capabilities later without a UI change.
|
|
101
101
|
*/
|
|
102
102
|
get sharingSupported(): boolean;
|
|
103
|
+
/** True when this session is impersonating another user (an admin opened another user's root). */
|
|
104
|
+
get impersonating(): boolean;
|
|
103
105
|
/**
|
|
104
106
|
* Role of the authenticated user, from the `GetSessionInfo` RPC surfaced through the
|
|
105
107
|
* pl-client. `null` in no-auth mode (when {@link currentUserLogin} is null).
|
|
@@ -112,6 +114,14 @@ declare class MiddleLayer {
|
|
|
112
114
|
* permission-ceiling gate.
|
|
113
115
|
*/
|
|
114
116
|
get canShareWithEveryone(): boolean;
|
|
117
|
+
/**
|
|
118
|
+
* Whether the authenticated user may impersonate others (open another user's root). Mirrors
|
|
119
|
+
* the backend's `CanImpersonate` role gate — admin/controller only, never a regular user.
|
|
120
|
+
* Derived from the session role, which stays the authenticated admin's even while
|
|
121
|
+
* impersonating, so this stays true across a switch: the "return to my root" affordance must
|
|
122
|
+
* not vanish mid-impersonation. Not a security boundary; the backend re-checks on every call.
|
|
123
|
+
*/
|
|
124
|
+
get currentUserCanImpersonate(): boolean;
|
|
115
125
|
/** Adds a runtime capability to the middle layer. */
|
|
116
126
|
addRuntimeCapability(requirement: SupportedRequirement, value?: number | boolean): void;
|
|
117
127
|
/** Checks if the given block feature flags are compatible with the runtime capabilities. */
|
|
@@ -139,6 +149,15 @@ declare class MiddleLayer {
|
|
|
139
149
|
* project labels (read within the same transaction), and returns the label for the copy
|
|
140
150
|
*/
|
|
141
151
|
duplicateProject(srcProjectId: ProjectId$1, rename?: (previousLabel: string, existingLabels: string[]) => string): Promise<ProjectId$1>;
|
|
152
|
+
/**
|
|
153
|
+
* Duplicates a project into another user's root, minted in the TARGET user's color so the target
|
|
154
|
+
* owns it. Sibling of {@link duplicateProject}, but writes into a different root. The source
|
|
155
|
+
* project (on the current client root) is referenced cross-color for its block data, kept alive
|
|
156
|
+
* by refcounting, exactly like accepting a shared project. Works both ways: pull (while
|
|
157
|
+
* impersonating a user, copy their project to yourself) and push (from your own root, copy a
|
|
158
|
+
* project to a user). Admin cross-root op; requires the crossTreeRefs:v1 backend capability.
|
|
159
|
+
*/
|
|
160
|
+
duplicateProjectToUser(srcProjectId: ProjectId$1, targetLogin: string, rename?: (previousLabel: string, existingLabels: string[]) => string): Promise<void>;
|
|
142
161
|
/**
|
|
143
162
|
* Shares the given projects (Copy & Share). Snapshots the projects, creates one envelope, and
|
|
144
163
|
* grants it — all in one atomic write transaction, so a failed grant rolls the whole thing back
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middle_layer.d.ts","names":[],"sources":["../../src/middle_layer/middle_layer.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"middle_layer.d.ts","names":[],"sources":["../../src/middle_layer/middle_layer.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;UAiGiB,sBAAA;EACf,OAAA,IAAW,OAAA;EAAA,SACF,EAAA,EAAI,QAAA;EAAA,SACJ,mBAAA,EAAqB,mBAAA;EAAA,SACrB,MAAA,EAAQ,QAAA;EAAA,SACR,oBAAA,EAAsB,oBAAA;EAAA,SACtB,cAAA,EAAgB,UAAA;EAAA,SAChB,mBAAA,EAAqB,UAAA;EAAA,SACrB,MAAA,EAAQ,MAAA;EAAA,SACR,GAAA,EAAK,cAAA;EAAA,SACL,UAAA,EAAY,iBAAA;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AA,QAChB,oBAAA;EAnFI;EAAA,QAsFJ,oBAAA;EAtFN;;EAAA,QAiGY,kBAAA;EAAA,iBAqCG,cAAA;EArImB;EAwIvB,WAAA,CAAY,EAAA,EAAI,WAAA,GAAY,OAAA;EAxIc;EAgJ1C,YAAA,CAAa,EAAA,EAAI,WAAA,GAAY,OAAA;EA3F7B;EAoGN,gBAAA,CAAiB,EAAA,EAAI,WAAA,GAAY,OAAA;EApGf;EA2GlB,eAAA,CAAgB,EAAA,EAAI,WAAA;EA/EH;;;;;EAwFX,KAAA,IAAK,OAAA;EAjCW;EAgDhB,wBAAA,IAAwB,OAAA;EAhDI;;EAAA,OAsD3B,mBAAA;EA9CY;EAAA,IAmDf,oBAAA,IAAwB,oBAAA;EA1C5B;EAAA,OA+Ca,IAAA,CAClB,EAAA,EAAI,QAAA,EACJ,OAAA,UACA,IAAA,EAAM,yBAAA,GACL,OAAA,CAAQ,WAAA;AAAA"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { V2RegistryProvider } from "../block_registry/registry-v2-provider.js";
|
|
2
2
|
import "../block_registry/index.js";
|
|
3
3
|
import { ProjectMetaKey } from "../model/project_model.js";
|
|
4
|
-
import { ProjectsField, ProjectsResourceType, createProjectList } from "./project_list.js";
|
|
5
|
-
import { SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, acceptanceFieldLogin, canGrantToEveryone, decodeEnvelopeData, isAcceptanceField } from "../model/sharing_model.js";
|
|
4
|
+
import { ProjectsField, ProjectsResourceType, createProjectList, ensureProjectListRid } from "./project_list.js";
|
|
5
|
+
import { SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, acceptanceFieldLogin, canGrantToEveryone, canImpersonate, decodeEnvelopeData, isAcceptanceField } from "../model/sharing_model.js";
|
|
6
6
|
import { BlockPackPreparer } from "../mutator/block-pack/block_pack.js";
|
|
7
7
|
import { getDebugFlags } from "../debug/index.js";
|
|
8
8
|
import { createProject, duplicateProject, withProjectAuthored } from "../mutator/project.js";
|
|
@@ -104,7 +104,11 @@ var MiddleLayer = class MiddleLayer {
|
|
|
104
104
|
* additional required capabilities later without a UI change.
|
|
105
105
|
*/
|
|
106
106
|
get sharingSupported() {
|
|
107
|
-
return this.serverCapabilities.includes("crossTreeRefs:v1");
|
|
107
|
+
return this.serverCapabilities.includes("crossTreeRefs:v1") && !this.impersonating;
|
|
108
|
+
}
|
|
109
|
+
/** True when this session is impersonating another user (an admin opened another user's root). */
|
|
110
|
+
get impersonating() {
|
|
111
|
+
return this.pl.conf.asUser !== void 0;
|
|
108
112
|
}
|
|
109
113
|
/**
|
|
110
114
|
* Role of the authenticated user, from the `GetSessionInfo` RPC surfaced through the
|
|
@@ -120,7 +124,17 @@ var MiddleLayer = class MiddleLayer {
|
|
|
120
124
|
* permission-ceiling gate.
|
|
121
125
|
*/
|
|
122
126
|
get canShareWithEveryone() {
|
|
123
|
-
return this.serverCapabilities.includes("publicGrants:v1") && canGrantToEveryone(this.currentUserRole);
|
|
127
|
+
return !this.impersonating && this.serverCapabilities.includes("publicGrants:v1") && canGrantToEveryone(this.currentUserRole);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Whether the authenticated user may impersonate others (open another user's root). Mirrors
|
|
131
|
+
* the backend's `CanImpersonate` role gate — admin/controller only, never a regular user.
|
|
132
|
+
* Derived from the session role, which stays the authenticated admin's even while
|
|
133
|
+
* impersonating, so this stays true across a switch: the "return to my root" affordance must
|
|
134
|
+
* not vanish mid-impersonation. Not a security boundary; the backend re-checks on every call.
|
|
135
|
+
*/
|
|
136
|
+
get currentUserCanImpersonate() {
|
|
137
|
+
return canImpersonate(this.currentUserRole);
|
|
124
138
|
}
|
|
125
139
|
/** Adds a runtime capability to the middle layer. */
|
|
126
140
|
addRuntimeCapability(requirement, value = true) {
|
|
@@ -222,6 +236,31 @@ var MiddleLayer = class MiddleLayer {
|
|
|
222
236
|
return newProjectId;
|
|
223
237
|
}
|
|
224
238
|
/**
|
|
239
|
+
* Duplicates a project into another user's root, minted in the TARGET user's color so the target
|
|
240
|
+
* owns it. Sibling of {@link duplicateProject}, but writes into a different root. The source
|
|
241
|
+
* project (on the current client root) is referenced cross-color for its block data, kept alive
|
|
242
|
+
* by refcounting, exactly like accepting a shared project. Works both ways: pull (while
|
|
243
|
+
* impersonating a user, copy their project to yourself) and push (from your own root, copy a
|
|
244
|
+
* project to a user). Admin cross-root op; requires the crossTreeRefs:v1 backend capability.
|
|
245
|
+
*/
|
|
246
|
+
async duplicateProjectToUser(srcProjectId, targetLogin, rename) {
|
|
247
|
+
if (!this.serverCapabilities.includes("crossTreeRefs:v1")) throw new Error("duplicateProjectToUser requires the crossTreeRefs:v1 backend capability.");
|
|
248
|
+
const sourceRid = await this.resolveProjectId(srcProjectId);
|
|
249
|
+
const targetRoot = await this.pl.getUserRoot({
|
|
250
|
+
login: targetLogin,
|
|
251
|
+
createIfNotExists: true
|
|
252
|
+
});
|
|
253
|
+
await this.pl.withWriteTxOnRoot(targetRoot, "MLDuplicateProjectToUser", async (tx) => {
|
|
254
|
+
const targetProjectListRid = await ensureProjectListRid(tx);
|
|
255
|
+
const sourceMeta = await tx.getKValueJson(sourceRid, ProjectMetaKey);
|
|
256
|
+
const targetListData = await tx.getResourceData(targetProjectListRid, true);
|
|
257
|
+
const existingLabels = (await Promise.all(targetListData.fields.map((f) => f.value).filter(isNotNullSignedResourceId).map((rid) => tx.getKValueJson(rid, ProjectMetaKey)))).map((m) => m.label);
|
|
258
|
+
const newPrj = await duplicateProject(tx, sourceRid, { label: rename ? rename(sourceMeta.label, existingLabels) : sourceMeta.label });
|
|
259
|
+
tx.createField(field(targetProjectListRid, randomUUID()), "Dynamic", newPrj);
|
|
260
|
+
await tx.commit();
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
225
264
|
* Shares the given projects (Copy & Share). Snapshots the projects, creates one envelope, and
|
|
226
265
|
* grants it — all in one atomic write transaction, so a failed grant rolls the whole thing back
|
|
227
266
|
* and the outbox is left as it was.
|