@milaboratories/pl-middle-layer 1.64.41 → 1.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/index.cjs +17 -0
  2. package/dist/index.d.ts +3 -1
  3. package/dist/index.js +3 -1
  4. package/dist/middle_layer/frontend_path.cjs +1 -0
  5. package/dist/middle_layer/frontend_path.cjs.map +1 -1
  6. package/dist/middle_layer/frontend_path.js +1 -0
  7. package/dist/middle_layer/frontend_path.js.map +1 -1
  8. package/dist/middle_layer/index.d.ts +2 -1
  9. package/dist/middle_layer/middle_layer.cjs +482 -16
  10. package/dist/middle_layer/middle_layer.cjs.map +1 -1
  11. package/dist/middle_layer/middle_layer.d.ts +172 -12
  12. package/dist/middle_layer/middle_layer.d.ts.map +1 -1
  13. package/dist/middle_layer/middle_layer.js +485 -19
  14. package/dist/middle_layer/middle_layer.js.map +1 -1
  15. package/dist/middle_layer/ops.cjs +2 -1
  16. package/dist/middle_layer/ops.cjs.map +1 -1
  17. package/dist/middle_layer/ops.d.ts +5 -1
  18. package/dist/middle_layer/ops.d.ts.map +1 -1
  19. package/dist/middle_layer/ops.js +2 -1
  20. package/dist/middle_layer/ops.js.map +1 -1
  21. package/dist/middle_layer/project.d.ts +4 -4
  22. package/dist/middle_layer/project.d.ts.map +1 -1
  23. package/dist/middle_layer/project_list.cjs +19 -0
  24. package/dist/middle_layer/project_list.cjs.map +1 -1
  25. package/dist/middle_layer/project_list.d.ts +1 -1
  26. package/dist/middle_layer/project_list.d.ts.map +1 -1
  27. package/dist/middle_layer/project_list.js +20 -2
  28. package/dist/middle_layer/project_list.js.map +1 -1
  29. package/dist/middle_layer/sharing_list.cjs +203 -0
  30. package/dist/middle_layer/sharing_list.cjs.map +1 -0
  31. package/dist/middle_layer/sharing_list.d.ts +41 -0
  32. package/dist/middle_layer/sharing_list.d.ts.map +1 -0
  33. package/dist/middle_layer/sharing_list.js +198 -0
  34. package/dist/middle_layer/sharing_list.js.map +1 -0
  35. package/dist/model/index.cjs +30 -0
  36. package/dist/model/index.d.ts +2 -1
  37. package/dist/model/index.js +4 -0
  38. package/dist/model/project_model.d.ts +3 -3
  39. package/dist/model/project_model.d.ts.map +1 -1
  40. package/dist/model/sharing_model.cjs +98 -0
  41. package/dist/model/sharing_model.cjs.map +1 -0
  42. package/dist/model/sharing_model.d.ts +122 -0
  43. package/dist/model/sharing_model.d.ts.map +1 -0
  44. package/dist/model/sharing_model.js +84 -0
  45. package/dist/model/sharing_model.js.map +1 -0
  46. package/dist/mutator/block-pack/frontend.cjs +1 -0
  47. package/dist/mutator/block-pack/frontend.cjs.map +1 -1
  48. package/dist/mutator/block-pack/frontend.js +1 -0
  49. package/dist/mutator/block-pack/frontend.js.map +1 -1
  50. package/dist/mutator/sharing.cjs +138 -0
  51. package/dist/mutator/sharing.cjs.map +1 -0
  52. package/dist/mutator/sharing.js +130 -0
  53. package/dist/mutator/sharing.js.map +1 -0
  54. package/package.json +15 -15
  55. package/src/middle_layer/index.ts +1 -0
  56. package/src/middle_layer/middle_layer.ts +715 -23
  57. package/src/middle_layer/ops.ts +7 -0
  58. package/src/middle_layer/project_list.ts +33 -2
  59. package/src/middle_layer/sharing_list.ts +343 -0
  60. package/src/model/index.ts +2 -0
  61. package/src/model/sharing_model.test.ts +22 -0
  62. package/src/model/sharing_model.ts +169 -0
  63. package/src/mutator/sharing.ts +216 -0
@@ -1,21 +1,69 @@
1
- import type { PlClient, SignedResourceId, ResourceRef } from "@milaboratories/pl-client";
1
+ import type {
2
+ PlClient,
3
+ PlTransaction,
4
+ SignedResourceId,
5
+ ResourceRef,
6
+ Role,
7
+ } from "@milaboratories/pl-client";
2
8
  import {
9
+ isEveryoneUserLogin,
3
10
  field,
11
+ GrantType,
4
12
  isNotNullSignedResourceId,
5
13
  isNullSignedResourceId,
6
14
  resourceIdToString,
7
15
  } from "@milaboratories/pl-client";
8
16
  import { LRUCache } from "lru-cache";
9
- import { createProjectList, ProjectsField, ProjectsResourceType } from "./project_list";
17
+ import {
18
+ createProjectList,
19
+ ensureProjectListRid,
20
+ ProjectsField,
21
+ ProjectsResourceType,
22
+ } from "./project_list";
10
23
  import { createProject, duplicateProject, withProjectAuthored } from "../mutator/project";
11
24
  import { ProjectMetaKey } from "../model/project_model";
12
25
  import type { ProjectId } from "../model/project_model";
13
26
  import type { SynchronizedTreeState } from "@milaboratories/pl-tree";
27
+ import {
28
+ acceptanceFieldLogin,
29
+ canGrantToEveryone,
30
+ canImpersonate,
31
+ decodeEnvelopeData,
32
+ isAcceptanceField,
33
+ SharingOutboxField,
34
+ SharingOutboxResourceType,
35
+ SharingStateField,
36
+ SharingStateResourceType,
37
+ type EnvelopeAcceptance,
38
+ type EnvelopeData,
39
+ type ProjectChangeAction,
40
+ type ProjectFieldUuid,
41
+ type ShareId,
42
+ type ShareProjectsOptions,
43
+ } from "../model/sharing_model";
44
+ import {
45
+ buildShareEnvelope,
46
+ copyEnvelopeProjectsIntoList,
47
+ envelopeProjectFieldUuid,
48
+ isEnvelopeProjectField,
49
+ resourceIdsToStrings,
50
+ writeEnvelopeAcceptance,
51
+ writeSharingDecision,
52
+ type EnvelopeProjectSource,
53
+ } from "../mutator/sharing";
54
+ import type { LiveEnvelope, OutgoingShare, PendingShare } from "./sharing_list";
55
+ import {
56
+ createLiveEnvelopesComputable,
57
+ createOutgoingShares,
58
+ createPendingSharesComputable,
59
+ createPendingSharesTree,
60
+ createSharingStateTree,
61
+ } from "./sharing_list";
14
62
  import { BlockPackPreparer } from "../mutator/block-pack/block_pack";
15
63
  import type { MiLogger, Signer } from "@milaboratories/ts-helpers";
16
- import { BlockEventDispatcher } from "@milaboratories/ts-helpers";
64
+ import { BlockEventDispatcher, cachedDeserialize } from "@milaboratories/ts-helpers";
17
65
  import { HmacSha256Signer } from "@milaboratories/ts-helpers";
18
- import type { ComputableStableDefined } from "@milaboratories/computable";
66
+ import type { Computable, ComputableStableDefined } from "@milaboratories/computable";
19
67
  import { WatchableValue } from "@milaboratories/computable";
20
68
  import { Project } from "./project";
21
69
  import type { MiddleLayerOps, MiddleLayerOpsConstructor } from "./ops";
@@ -81,21 +129,34 @@ export interface MiddleLayerEnvironment {
81
129
  export class MiddleLayer {
82
130
  public readonly pl: PlClient;
83
131
 
84
- /** Contains a reactive list of projects along with their meta information. */
85
- public readonly projectList: ComputableStableDefined<ProjectListEntry[]>;
86
-
87
132
  private constructor(
88
133
  private readonly env: MiddleLayerEnvironment,
89
134
  public readonly driverKit: DriverKit,
90
135
  public readonly signer: Signer,
91
136
  private readonly projectListResourceId: SignedResourceId,
137
+ private readonly sharingOutboxResourceId: SignedResourceId,
138
+ private readonly sharingStateResourceId: SignedResourceId,
92
139
  private readonly openedProjectsList: WatchableValue<ProjectId[]>,
93
140
  private readonly projectListTree: SynchronizedTreeState,
141
+ private readonly sharingOutboxTree: SynchronizedTreeState,
142
+ private readonly sharingStateTree: SynchronizedTreeState,
143
+ private readonly pendingSharesTree: SynchronizedTreeState,
94
144
  public readonly blockRegistryProvider: V2RegistryProvider,
95
- projectList: ComputableStableDefined<ProjectListEntry[]>,
145
+ /** Contains a reactive list of projects along with their meta information. */
146
+ public readonly projectList: ComputableStableDefined<ProjectListEntry[]>,
147
+ /** Reactive view of the donor's outbox — the shares this user has created.
148
+ * v1: API only, no UI. */
149
+ public outgoingShares: Computable<OutgoingShare[] | undefined>,
150
+ /** Envelopes granted to this user, not yet accepted or rejected. Fed by the
151
+ * shared-resource discovery tree. */
152
+ public pendingShares: Computable<PendingShare[] | undefined>,
153
+ /** Internal: the acceptor's currently-live envelopes, read from the same shared-resource
154
+ * discovery tree as {@link pendingShares}. The single source the accept/reject flow resolves
155
+ * live envelopes from — no second discovery path. */
156
+ private readonly liveEnvelopes: Computable<LiveEnvelope[] | undefined>,
96
157
  ) {
97
- this.projectList = projectList;
98
158
  this.pl = this.env.pl;
159
+ this.startEnvelopeCleanup();
99
160
  }
100
161
 
101
162
  /**
@@ -116,6 +177,65 @@ export class MiddleLayer {
116
177
  return this.pl.serverInfo.capabilities ?? [];
117
178
  }
118
179
 
180
+ /**
181
+ * Login of the authenticated user, for the "Signed in as" UI. `null` when the
182
+ * backend has no auth (local/dev mode) — the UI hides the element.
183
+ */
184
+ public get currentUserLogin(): string | null {
185
+ return this.pl.userResources.authUser;
186
+ }
187
+
188
+ /**
189
+ * Whether the connected backend supports project sharing. Synthetic — computed
190
+ * in the middle layer from the backend capabilities the share flow needs (the
191
+ * cross-color field-reference relaxation the accept flow rests on). It can absorb
192
+ * additional required capabilities later without a UI change.
193
+ */
194
+ public get sharingSupported(): boolean {
195
+ // Sharing does not compose with impersonation (discovery is scoped to the admin's session,
196
+ // decisions attribute to the admin), so it is disabled while impersonating. Admins move
197
+ // projects across roots with duplicateProjectToUser instead.
198
+ return this.serverCapabilities.includes("crossTreeRefs:v1") && !this.impersonating;
199
+ }
200
+
201
+ /** True when this session is impersonating another user (an admin opened another user's root). */
202
+ public get impersonating(): boolean {
203
+ return this.pl.conf.asUser !== undefined;
204
+ }
205
+
206
+ /**
207
+ * Role of the authenticated user, from the `GetSessionInfo` RPC surfaced through the
208
+ * pl-client. `null` in no-auth mode (when {@link currentUserLogin} is null).
209
+ */
210
+ public get currentUserRole(): Role | null {
211
+ return this.pl.currentUserRole;
212
+ }
213
+
214
+ /**
215
+ * Whether the UI offers share-with-everybody — no role policy lives in the UI:
216
+ * serverCapabilities.has("publicGrants:v1") && canGrantToEveryone(currentUserRole)
217
+ * Not a security boundary: a crafted call still hits the backend's role +
218
+ * permission-ceiling gate.
219
+ */
220
+ public get canShareWithEveryone(): boolean {
221
+ return (
222
+ !this.impersonating &&
223
+ this.serverCapabilities.includes("publicGrants:v1") &&
224
+ canGrantToEveryone(this.currentUserRole)
225
+ );
226
+ }
227
+
228
+ /**
229
+ * Whether the authenticated user may impersonate others (open another user's root). Mirrors
230
+ * the backend's `CanImpersonate` role gate — admin/controller only, never a regular user.
231
+ * Derived from the session role, which stays the authenticated admin's even while
232
+ * impersonating, so this stays true across a switch: the "return to my root" affordance must
233
+ * not vanish mid-impersonation. Not a security boundary; the backend re-checks on every call.
234
+ */
235
+ public get currentUserCanImpersonate(): boolean {
236
+ return canImpersonate(this.currentUserRole);
237
+ }
238
+
119
239
  /** Adds a runtime capability to the middle layer. */
120
240
  public addRuntimeCapability(
121
241
  requirement: SupportedRequirement,
@@ -275,6 +395,536 @@ export class MiddleLayer {
275
395
  return newProjectId;
276
396
  }
277
397
 
398
+ /**
399
+ * Duplicates a project into another user's root, minted in the TARGET user's color so the target
400
+ * owns it. Sibling of {@link duplicateProject}, but writes into a different root. The source
401
+ * project (on the current client root) is referenced cross-color for its block data, kept alive
402
+ * by refcounting, exactly like accepting a shared project. Works both ways: pull (while
403
+ * impersonating a user, copy their project to yourself) and push (from your own root, copy a
404
+ * project to a user). Admin cross-root op; requires the crossTreeRefs:v1 backend capability.
405
+ */
406
+ public async duplicateProjectToUser(
407
+ srcProjectId: ProjectId,
408
+ targetLogin: string,
409
+ rename?: (previousLabel: string, existingLabels: string[]) => string,
410
+ ): Promise<void> {
411
+ if (!this.serverCapabilities.includes("crossTreeRefs:v1"))
412
+ throw new Error("duplicateProjectToUser requires the crossTreeRefs:v1 backend capability.");
413
+
414
+ const sourceRid = await this.resolveProjectId(srcProjectId);
415
+ const targetRoot = await this.pl.getUserRoot({ login: targetLogin, createIfNotExists: true });
416
+
417
+ // Run on the target root: the tx default color is the target's, so the new project (and the
418
+ // target's project list, if created here) are minted in the target's color.
419
+ await this.pl.withWriteTxOnRoot(targetRoot, "MLDuplicateProjectToUser", async (tx) => {
420
+ // Resolve or lazily create the target root's project list (tx.clientRoot === targetRoot).
421
+ const targetProjectListRid = await ensureProjectListRid(tx);
422
+
423
+ // Source label + the target's existing labels, for collision-aware renaming.
424
+ const sourceMeta = await tx.getKValueJson<ProjectMeta>(sourceRid, ProjectMetaKey);
425
+ const targetListData = await tx.getResourceData(targetProjectListRid, true);
426
+ const existingLabels = (
427
+ await Promise.all(
428
+ targetListData.fields
429
+ .map((f) => f.value)
430
+ .filter(isNotNullSignedResourceId)
431
+ .map((rid) => tx.getKValueJson<ProjectMeta>(rid, ProjectMetaKey)),
432
+ )
433
+ ).map((m) => m.label);
434
+ const newLabel = rename ? rename(sourceMeta.label, existingLabels) : sourceMeta.label;
435
+
436
+ const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });
437
+ tx.createField(field(targetProjectListRid, randomUUID()), "Dynamic", newPrj);
438
+ await tx.commit();
439
+ });
440
+ }
441
+
442
+ //
443
+ // Project Sharing (Copy & Share)
444
+ //
445
+
446
+ /**
447
+ * Shares the given projects (Copy & Share). Snapshots the projects, creates one envelope, and
448
+ * grants it — all in one atomic write transaction, so a failed grant rolls the whole thing back
449
+ * and the outbox is left as it was.
450
+ *
451
+ * Two variants (see {@link ShareProjectsOptions}):
452
+ * - `{ recipients }` — one writable grant per named recipient; the envelope expires after the
453
+ * default TTL (`sharedAt + envelopeTtlMs`).
454
+ * - `{ everyone: true }` — one make-public grant (backend rewrites the target to the
455
+ * everyone-user); the envelope's `expiresAt` is `null`, so it never expires.
456
+ *
457
+ * v1 always passes `mode: "copy"`.
458
+ */
459
+ public async shareProjects(
460
+ projectIds: ProjectId[],
461
+ options: ShareProjectsOptions,
462
+ ): Promise<void> {
463
+ if (projectIds.length === 0) throw new Error("shareProjects: no projects given");
464
+
465
+ // Everyone + replace: refresh the existing everyone-share of this project under its stable
466
+ // shareId (so recipients who already decided aren't re-prompted), if one exists. Found
467
+ // automatically by project overlap; falls through to a fresh share when none exists.
468
+ if ("everyone" in options && options.replace) {
469
+ const priorEveryone = (await this.findSupersedableEnvelopes(projectIds)).find(
470
+ (p) => p.everyone,
471
+ );
472
+ if (priorEveryone !== undefined) {
473
+ await this.changeShare(priorEveryone.shareId, { title: options.title });
474
+ return;
475
+ }
476
+ }
477
+
478
+ await this.createNewShare(projectIds, options);
479
+ }
480
+
481
+ /**
482
+ * Mints a fresh share: snapshots the projects into one new envelope (a fresh shareId),
483
+ * supersedes prior shares of the same project, and grants it — all in one atomic write
484
+ * transaction, so a failed grant rolls the whole thing back and the outbox is left as it was.
485
+ * The everyone-refresh path is the {@link changeShare} branch of {@link shareProjects}; this is
486
+ * the mint-a-new-envelope branch.
487
+ */
488
+ private async createNewShare(
489
+ projectIds: ProjectId[],
490
+ options: ShareProjectsOptions,
491
+ ): Promise<void> {
492
+ const everyone = "everyone" in options;
493
+ const sources: EnvelopeProjectSource[] = await Promise.all(
494
+ projectIds.map(
495
+ async (id): Promise<EnvelopeProjectSource> => ({
496
+ kind: "fresh",
497
+ projectId: id,
498
+ sourceRid: await this.resolveProjectId(id),
499
+ }),
500
+ ),
501
+ );
502
+ const sender = this.currentUserLogin ?? "";
503
+ // Targeted share: sharedAt + ttl. Share-with-everybody: never expires (null).
504
+ const expiresAt = everyone ? null : Date.now() + this.env.ops.envelopeTtlMs;
505
+
506
+ // Supersede prior shares of the same project(s) so they never pile up. Resolved before
507
+ // the write tx (ListGrants is a separate RPC). Everyone-share supersedes a prior
508
+ // everyone-share of the same project; a targeted share pulls each named recipient out of
509
+ // any prior share of that project, deleting that share if it ends up with no recipients.
510
+ const priors = await this.findSupersedableEnvelopes(projectIds);
511
+
512
+ await this.pl.withWriteTx("MLShareProjects", async (tx) => {
513
+ if (everyone) {
514
+ for (const prior of priors) {
515
+ if (prior.everyone) tx.removeField(field(this.sharingOutboxResourceId, prior.fieldName));
516
+ }
517
+ } else {
518
+ const newRecipients = new Set(options.recipients);
519
+ for (const prior of priors) {
520
+ if (prior.everyone) continue; // a single user can't be pulled from an everyone-grant
521
+ const toRemove = prior.recipients.filter((u) => newRecipients.has(u));
522
+ if (toRemove.length === 0) continue;
523
+ const remaining = prior.recipients.filter((u) => !newRecipients.has(u));
524
+ if (remaining.length === 0) {
525
+ // Nobody left on the old share — drop the whole envelope.
526
+ tx.removeField(field(this.sharingOutboxResourceId, prior.fieldName));
527
+ } else {
528
+ for (const u of toRemove) tx.revokeAccess(prior.rid, u);
529
+ }
530
+ }
531
+ }
532
+
533
+ const { envelope } = await buildShareEnvelope(tx, this.sharingOutboxResourceId, sources, {
534
+ mode: options.mode,
535
+ sender,
536
+ title: options.title,
537
+ expiresAt,
538
+ });
539
+
540
+ // Grant in the same transaction (writable: the cross-color accept rule demands a writable
541
+ // grant on the envelope). Atomic with the create.
542
+ const envelopeGid = await envelope.globalId;
543
+ if (everyone) {
544
+ // One everyone-grant: empty/ignored target, ANY_AUTHORISED. The backend rewrites
545
+ // the target to the everyone-user; gated by role + permission ceiling.
546
+ tx.grantAccess(envelopeGid, "", { writable: true }, GrantType.ANY_AUTHORISED);
547
+ } else {
548
+ for (const recipient of options.recipients) {
549
+ tx.grantAccess(envelopeGid, recipient, { writable: true });
550
+ }
551
+ }
552
+
553
+ await tx.commit();
554
+ });
555
+
556
+ await this.sharingOutboxTree.refreshState();
557
+ }
558
+
559
+ /**
560
+ * Changes a share in place (same {@link ShareId}), in one write transaction: re-snapshots live
561
+ * source projects and carries deleted ones' snapshots forward; applies edited recipients/title;
562
+ * transfers already-decided recipients' accept/reject records (they keep their copy and aren't
563
+ * re-prompted); re-grants; drops the old envelope.
564
+ *
565
+ * `opts.recipients` is the full targeted set (decided users are always kept). `opts.title`
566
+ * replaces the title — omit keeps the current one. `opts.everyone` upgrades targeted ->
567
+ * everyone; the reverse is impossible and ignored.
568
+ *
569
+ * `opts.projectActions` is a per-source-project decision, keyed by projectId: `update`
570
+ * re-snapshots the live source (falls back to carry if the source is gone), `keep` carries the
571
+ * existing snapshot (and its timestamp), `remove` drops the project from the pack. A project not
572
+ * in the map defaults to `keep`. Omit the whole map for the legacy auto behavior (live sources
573
+ * updated, gone ones kept) — the everyone-refresh path relies on that.
574
+ */
575
+ public async changeShare(
576
+ shareId: ShareId,
577
+ opts: {
578
+ recipients?: string[];
579
+ everyone?: boolean;
580
+ title?: string;
581
+ projectActions?: Record<ProjectId, ProjectChangeAction>;
582
+ } = {},
583
+ ): Promise<void> {
584
+ await this.pl.withWriteTx("MLChangeShare", async (tx) => {
585
+ const old = await this.resolveOutboxEnvelope(tx, shareId);
586
+ if (old === undefined)
587
+ throw new Error(`changeShare: no live share with id ${shareId} in the outbox.`);
588
+
589
+ const self = this.currentUserLogin ?? "";
590
+ const grants = await tx.listGrants(old.rid);
591
+ // A targeted share may be upgraded to everyone; an everyone-share can't be narrowed back.
592
+ const everyone = grants.some((g) => isEveryoneUserLogin(g.user)) || opts.everyone === true;
593
+
594
+ // Read the old envelope's project snapshots (uuid -> rid) and accept/reject records.
595
+ const oldRd = await tx.getResourceData(old.rid, true);
596
+ const snapshotByUuid = new Map<string, SignedResourceId>();
597
+ const acceptances: { login: string; acc: EnvelopeAcceptance }[] = [];
598
+ for (const f of oldRd.fields) {
599
+ if (isNullSignedResourceId(f.value)) continue;
600
+ if (isEnvelopeProjectField(f.name)) {
601
+ snapshotByUuid.set(envelopeProjectFieldUuid(f.name), f.value);
602
+ } else if (isAcceptanceField(f.name)) {
603
+ const raw = (await tx.getResourceData(f.value, false)).data;
604
+ if (raw === undefined) continue;
605
+ acceptances.push({
606
+ login: acceptanceFieldLogin(f.name),
607
+ acc: cachedDeserialize(raw) as EnvelopeAcceptance,
608
+ });
609
+ }
610
+ }
611
+ const decidedLogins = acceptances.map((a) => a.login);
612
+
613
+ // Everyone-shares ignore recipients; targeted shares keep decided users plus the edited set.
614
+ const priorRecipients = grants
615
+ .filter((g) => !isEveryoneUserLogin(g.user) && g.user !== self)
616
+ .map((g) => g.user);
617
+ const recipients = everyone
618
+ ? []
619
+ : Array.from(new Set([...(opts.recipients ?? priorRecipients), ...decidedLogins]));
620
+
621
+ // Live source projects by persistable id — these get a fresh snapshot.
622
+ const liveProjects = new Map<string, SignedResourceId>();
623
+ const projList = await tx.getResourceData(this.projectListResourceId, true);
624
+ for (const f of projList.fields) {
625
+ if (isNullSignedResourceId(f.value)) continue;
626
+ liveProjects.set(resourceIdToString(f.value), f.value);
627
+ }
628
+
629
+ // Per project (keyed by field uuid), apply the caller's decision (default `keep`); with no
630
+ // projectActions map, fall back to the legacy auto behavior: update a live source, keep a gone one.
631
+ const actions = opts.projectActions;
632
+ const sources: EnvelopeProjectSource[] = [];
633
+ for (const uuid of Object.keys(old.data.projects) as ProjectFieldUuid[]) {
634
+ const { label, source, updatedAt } = old.data.projects[uuid];
635
+ const liveRid = liveProjects.get(source);
636
+
637
+ const action = actions
638
+ ? (actions[source] ?? "keep")
639
+ : liveRid !== undefined
640
+ ? "update"
641
+ : "keep";
642
+ if (action === "remove") continue;
643
+
644
+ if (action === "update" && liveRid !== undefined) {
645
+ sources.push({ kind: "fresh", projectId: source, sourceRid: liveRid });
646
+ } else {
647
+ // keep, or an "update" whose source vanished before commit (deleted meanwhile, e.g. from
648
+ // another client): carry the prior snapshot. Liveness is read inside this write tx — race-safe.
649
+ const snapshotRid = snapshotByUuid.get(uuid);
650
+ if (snapshotRid !== undefined)
651
+ sources.push({ kind: "carry", projectId: source, label, snapshotRid, updatedAt });
652
+ }
653
+ }
654
+
655
+ // Omit (undefined) keeps the current title; a provided value replaces it.
656
+ const title = opts.title === undefined ? old.data.title : opts.title.trim();
657
+ const expiresAt = everyone ? null : Date.now() + this.env.ops.envelopeTtlMs;
658
+
659
+ // Same shareId, same outbox field name — detach the old field before rebuilding, or they collide.
660
+ tx.removeField(field(this.sharingOutboxResourceId, old.fieldName));
661
+
662
+ const { envelope } = await buildShareEnvelope(tx, this.sharingOutboxResourceId, sources, {
663
+ mode: old.data.mode,
664
+ sender: self,
665
+ title,
666
+ expiresAt,
667
+ shareId, // SAME shareId — the essence of change
668
+ });
669
+
670
+ // Transfer the decided users' records onto the new envelope (donor-written copies).
671
+ for (const { login, acc } of acceptances) {
672
+ if (!everyone && !recipients.includes(login)) continue;
673
+ writeEnvelopeAcceptance(tx, envelope, login, acc.action, acc.timestamp);
674
+ }
675
+
676
+ const gid = await envelope.globalId;
677
+ if (everyone) tx.grantAccess(gid, "", { writable: true }, GrantType.ANY_AUTHORISED);
678
+ else for (const r of recipients) tx.grantAccess(gid, r, { writable: true });
679
+
680
+ await tx.commit();
681
+ });
682
+
683
+ await this.sharingOutboxTree.refreshState();
684
+ }
685
+
686
+ /**
687
+ * Finds the donor's own outgoing envelopes built from any of the given source projects —
688
+ * the supersede candidates for a fresh share of the same project(s). Reads each envelope's
689
+ * recipient set via `ListGrants` so the caller can pull individual recipients or detect an
690
+ * everyone-share.
691
+ */
692
+ private async findSupersedableEnvelopes(projectIds: ProjectId[]): Promise<
693
+ {
694
+ fieldName: string;
695
+ rid: SignedResourceId;
696
+ shareId: ShareId;
697
+ everyone: boolean;
698
+ recipients: string[];
699
+ }[]
700
+ > {
701
+ const wanted = new Set(projectIds);
702
+
703
+ const matched = await this.pl.withReadTx("MLFindSupersede", async (tx) => {
704
+ const outbox = await tx.getResourceData(this.sharingOutboxResourceId, true);
705
+ const out: { fieldName: string; rid: SignedResourceId; shareId: ShareId }[] = [];
706
+ for (const f of outbox.fields) {
707
+ if (isNullSignedResourceId(f.value)) continue;
708
+ const rd = await tx.getResourceData(f.value, false);
709
+ if (rd.data === undefined) continue;
710
+ const data = decodeEnvelopeData(rd.data);
711
+ if (Object.values(data.projects).some((p) => wanted.has(p.source)))
712
+ out.push({ fieldName: f.name, rid: f.value, shareId: data.shareId });
713
+ }
714
+ return out;
715
+ });
716
+
717
+ return await Promise.all(
718
+ matched.map(async ({ fieldName, rid, shareId }) => {
719
+ const grants = await this.pl.userResources.listGrants(rid);
720
+ return {
721
+ fieldName,
722
+ rid,
723
+ shareId,
724
+ everyone: grants.some((g) => isEveryoneUserLogin(g.user)),
725
+ recipients: grants.filter((g) => !isEveryoneUserLogin(g.user)).map((g) => g.user),
726
+ };
727
+ }),
728
+ );
729
+ }
730
+
731
+ /**
732
+ * Revokes and deletes an outgoing share for all recipients: detaches and deletes the envelope, and
733
+ * its grants are revoked along with it. Already-accepted copies are unaffected (ref-counting keeps
734
+ * the adopted resources alive). Idempotent — revoking a share that is already gone is a no-op.
735
+ */
736
+ public async revokeShare(shareId: ShareId): Promise<void> {
737
+ await this.pl.withWriteTx("MLRevokeShare", async (tx) => {
738
+ const target = await this.resolveOutboxEnvelope(tx, shareId);
739
+ if (target === undefined) return;
740
+ tx.removeField(field(this.sharingOutboxResourceId, target.fieldName));
741
+ await tx.commit();
742
+ });
743
+
744
+ await this.sharingOutboxTree.refreshState();
745
+ }
746
+
747
+ /**
748
+ * Resolves a live envelope from the donor's own outbox by its logical `shareId`, returning the
749
+ * outbox field name (for detach), the signed envelope id, and its decoded {@link EnvelopeData}.
750
+ * The outbox is keyed by `{shareId}` directly, but a replaced/legacy share may have drifted, so
751
+ * we match on the decoded `shareId` rather than the field name alone.
752
+ */
753
+ private async resolveOutboxEnvelope(
754
+ tx: PlTransaction,
755
+ shareId: ShareId,
756
+ ): Promise<{ fieldName: string; rid: SignedResourceId; data: EnvelopeData } | undefined> {
757
+ const outboxData = await tx.getResourceData(this.sharingOutboxResourceId, true);
758
+ for (const f of outboxData.fields) {
759
+ if (isNullSignedResourceId(f.value)) continue;
760
+ const rd = await tx.getResourceData(f.value, false);
761
+ if (rd.data === undefined) continue;
762
+ const data = decodeEnvelopeData(rd.data);
763
+ if (data.shareId === shareId) return { fieldName: f.name, rid: f.value, data };
764
+ }
765
+ return undefined;
766
+ }
767
+
768
+ /**
769
+ * Resolves currently-shared envelopes (granted to this user) to their resource ids, keyed by
770
+ * the envelope's logical `shareId`.
771
+ *
772
+ * Reads the {@link liveEnvelopes} Computable — the same shared-resource discovery tree that
773
+ * feeds {@link pendingShares}. This is the single discovery mechanism: there is no separate
774
+ * `ListUserResources` re-stream on every accept/reject. `refreshState()` is awaited first so a
775
+ * just-granted envelope is observed (the tree's discovery poll may otherwise lag a freshly
776
+ * landed grant). The tree is gRPC-only, so this is empty on a REST-connected client.
777
+ */
778
+ private async resolveLiveEnvelopes(): Promise<Map<ShareId, LiveEnvelope>> {
779
+ await this.pendingSharesTree.refreshState();
780
+ const live = (await this.liveEnvelopes.getValue()) ?? [];
781
+ // Dedup by logical shareId (last writer wins — at most one live envelope per shareId).
782
+ const map = new Map<ShareId, LiveEnvelope>();
783
+ for (const e of live) map.set(e.data.shareId, e);
784
+ return map;
785
+ }
786
+
787
+ /**
788
+ * Accepts one or more pending shares: duplicates each share's projects into this user's
789
+ * project list, records the decision per share, and (read-write share) writes the donor-visible
790
+ * acceptance onto the envelope. Per-share failures (e.g. an expiry race) are collected, not
791
+ * short-circuited — the rest still get accepted. Accept-all = pass every current pending shareId.
792
+ *
793
+ * `rename` resolves label collisions (same callback contract as {@link duplicateProject}), but
794
+ * the source lives in the envelope tree, so accept calls the low-level mutator directly.
795
+ */
796
+ public async acceptShare(
797
+ shareIds: ShareId[],
798
+ rename?: (previousLabel: string, existingLabels: string[]) => string,
799
+ ): Promise<{ accepted: ProjectId[]; failed: { shareId: ShareId; error: string }[] }> {
800
+ const live = await this.resolveLiveEnvelopes();
801
+ const login = this.currentUserLogin;
802
+
803
+ const accepted: ProjectId[] = [];
804
+ const failed: { shareId: ShareId; error: string }[] = [];
805
+
806
+ for (const shareId of shareIds) {
807
+ const envelope = live.get(shareId);
808
+ if (envelope === undefined) {
809
+ failed.push({ shareId, error: "Share is no longer available." });
810
+ continue;
811
+ }
812
+ try {
813
+ const now = Date.now();
814
+ const createdRids = await this.pl.withWriteTx("MLAcceptShare", async (tx) => {
815
+ const created = await copyEnvelopeProjectsIntoList(
816
+ tx,
817
+ envelope.rid,
818
+ this.projectListResourceId,
819
+ rename,
820
+ );
821
+
822
+ // Record the decision on the acceptor's own SharingState, keyed on shareId.
823
+ writeSharingDecision(tx, this.sharingStateResourceId, shareId, {
824
+ decision: "accepted",
825
+ timestamp: now,
826
+ envelopeSharedAt: envelope.data.sharedAt,
827
+ acceptedProjects: resourceIdsToStrings(created),
828
+ });
829
+
830
+ // Read-write share: write the donor-visible acceptance onto the envelope.
831
+ if (login !== null && envelope.data.mode !== "read-only")
832
+ writeEnvelopeAcceptance(tx, envelope.rid, login, "accepted", now);
833
+
834
+ await tx.commit();
835
+ return created;
836
+ });
837
+ for (const rid of createdRids) {
838
+ const projectId = resourceIdToString(rid) as ProjectId;
839
+ this.projectIdCache.set(projectId, rid);
840
+ accepted.push(projectId);
841
+ }
842
+ } catch (e) {
843
+ failed.push({ shareId, error: e instanceof Error ? e.message : String(e) });
844
+ }
845
+ }
846
+
847
+ await Promise.all([this.projectListTree.refreshState(), this.sharingStateTree.refreshState()]);
848
+ return { accepted, failed };
849
+ }
850
+
851
+ /** Records rejection of a pending share; it never surfaces again. */
852
+ public async rejectShare(shareId: ShareId): Promise<void> {
853
+ const live = await this.resolveLiveEnvelopes();
854
+ const envelope = live.get(shareId);
855
+ const login = this.currentUserLogin;
856
+ const now = Date.now();
857
+
858
+ await this.pl.withWriteTx("MLRejectShare", async (tx) => {
859
+ writeSharingDecision(tx, this.sharingStateResourceId, shareId, {
860
+ decision: "rejected",
861
+ timestamp: now,
862
+ envelopeSharedAt: envelope?.data.sharedAt ?? now,
863
+ acceptedProjects: [],
864
+ });
865
+
866
+ // Read-write share: write the donor-visible rejection onto the envelope (if still live).
867
+ if (envelope !== undefined && login !== null && envelope.data.mode !== "read-only")
868
+ writeEnvelopeAcceptance(tx, envelope.rid, login, "rejected", now);
869
+
870
+ await tx.commit();
871
+ });
872
+
873
+ await this.sharingStateTree.refreshState();
874
+ }
875
+
876
+ //
877
+ // Outbox cleanup (donor side)
878
+ //
879
+
880
+ private static readonly EnvelopeCleanupIntervalMs = 6 * 3600 * 1000; // every 6h
881
+ private envelopeCleanupTimer: ReturnType<typeof setInterval> | undefined;
882
+
883
+ /** On ML start and every 6h, delete envelopes whose immutable `expiresAt` has passed. */
884
+ private startEnvelopeCleanup(): void {
885
+ void this.runEnvelopeCleanup();
886
+ this.envelopeCleanupTimer = setInterval(() => {
887
+ void this.runEnvelopeCleanup();
888
+ }, MiddleLayer.EnvelopeCleanupIntervalMs);
889
+ // Don't keep the process alive solely for cleanup.
890
+ this.envelopeCleanupTimer.unref?.();
891
+ }
892
+
893
+ /** Scans the donor's outbox and deletes expired envelopes (backend auto-revokes their grants).
894
+ * Envelopes with `expiresAt: null` (share-with-everybody) are skipped. */
895
+ private async runEnvelopeCleanup(): Promise<void> {
896
+ try {
897
+ const now = Date.now();
898
+ const expired = await this.pl.withReadTx("MLEnvelopeCleanupScan", async (tx) => {
899
+ const data = await tx.getResourceData(this.sharingOutboxResourceId, true);
900
+ const toDelete: { fieldName: string }[] = [];
901
+ for (const f of data.fields) {
902
+ if (isNullSignedResourceId(f.value)) continue;
903
+ const rd = await tx.getResourceData(f.value, false);
904
+ if (rd.data === undefined) continue;
905
+ const envData = decodeEnvelopeData(rd.data);
906
+ if (envData.expiresAt === null) continue; // never expires
907
+ if (envData.expiresAt <= now) toDelete.push({ fieldName: f.name });
908
+ }
909
+ return toDelete;
910
+ });
911
+
912
+ if (expired.length === 0) return;
913
+
914
+ await this.pl.withWriteTx("MLEnvelopeCleanup", async (tx) => {
915
+ for (const { fieldName } of expired)
916
+ tx.removeField(field(this.sharingOutboxResourceId, fieldName));
917
+ await tx.commit();
918
+ });
919
+
920
+ await this.sharingOutboxTree.refreshState();
921
+ } catch (e) {
922
+ this.env.logger.warn(
923
+ `envelope cleanup failed: ${e instanceof Error ? e.message : String(e)}`,
924
+ );
925
+ }
926
+ }
927
+
278
928
  //
279
929
  // Projects
280
930
  //
@@ -316,9 +966,15 @@ export class MiddleLayer {
316
966
  * them.
317
967
  */
318
968
  public async close() {
969
+ if (this.envelopeCleanupTimer !== undefined) clearInterval(this.envelopeCleanupTimer);
319
970
  await Promise.all([...this.openedProjects.values()].map((prj) => prj.destroy()));
320
971
  // this.env.quickJs;
321
- await this.projectListTree.terminate();
972
+ await Promise.all([
973
+ this.projectListTree.terminate(),
974
+ this.sharingOutboxTree.terminate(),
975
+ this.sharingStateTree.terminate(),
976
+ this.pendingSharesTree.terminate(),
977
+ ]);
322
978
  await this.env.dispose();
323
979
  await this.pl.close();
324
980
  }
@@ -361,23 +1017,40 @@ export class MiddleLayer {
361
1017
  )
362
1018
  ops.defaultTreeOptions.traversalMode = getDebugFlags().treeTraversalMode;
363
1019
 
364
- const projects = await pl.withWriteTx("MLInitialization", async (tx) => {
365
- const projectsField = field(tx.clientRoot, ProjectsField);
366
- tx.createField(projectsField, "Dynamic");
367
- const projectsFieldData = await tx.getField(projectsField);
368
- if (isNullSignedResourceId(projectsFieldData.value)) {
369
- const projects = tx.createEphemeral(ProjectsResourceType);
370
- tx.lock(projects);
1020
+ const { projects, sharingOutbox, sharingState } = await pl.withWriteTx(
1021
+ "MLInitialization",
1022
+ async (tx) => {
1023
+ // Lazily create each clientRoot-attached singleton resource. Returns the existing
1024
+ // resource id if the field is already populated, otherwise creates + locks + sets it.
1025
+ const lazyInit = async (
1026
+ fieldName: string,
1027
+ type: { name: string; version: string },
1028
+ ): Promise<{ ref?: ResourceRef; existing?: SignedResourceId }> => {
1029
+ const f = field(tx.clientRoot, fieldName);
1030
+ tx.createField(f, "Dynamic");
1031
+ const fData = await tx.getField(f);
1032
+ if (isNullSignedResourceId(fData.value)) {
1033
+ const ref = tx.createEphemeral(type);
1034
+ tx.lock(ref);
1035
+ tx.setField(f, ref);
1036
+ return { ref };
1037
+ }
1038
+ return { existing: fData.value };
1039
+ };
371
1040
 
372
- tx.setField(projectsField, projects);
1041
+ const projectsR = await lazyInit(ProjectsField, ProjectsResourceType);
1042
+ const outboxR = await lazyInit(SharingOutboxField, SharingOutboxResourceType);
1043
+ const stateR = await lazyInit(SharingStateField, SharingStateResourceType);
373
1044
 
374
1045
  await tx.commit();
375
1046
 
376
- return await projects.globalId;
377
- } else {
378
- return projectsFieldData.value;
379
- }
380
- });
1047
+ return {
1048
+ projects: projectsR.existing ?? (await projectsR.ref!.globalId),
1049
+ sharingState: stateR.existing ?? (await stateR.ref!.globalId),
1050
+ sharingOutbox: outboxR.existing ?? (await outboxR.ref!.globalId),
1051
+ };
1052
+ },
1053
+ );
381
1054
 
382
1055
  const logger = ops.logger;
383
1056
 
@@ -439,15 +1112,34 @@ export class MiddleLayer {
439
1112
  const openedProjects = new WatchableValue<ProjectId[]>([]);
440
1113
  const projectListTC = await createProjectList(pl, projects, openedProjects, env);
441
1114
 
1115
+ // Project sharing trees and reactive views.
1116
+ const outgoingTC = await createOutgoingShares(pl, sharingOutbox, env);
1117
+ const sharingStateTree = await createSharingStateTree(pl, sharingState, env);
1118
+ const pendingSharesTree = await createPendingSharesTree(pl, env);
1119
+ const pendingShares = createPendingSharesComputable(
1120
+ pendingSharesTree,
1121
+ sharingStateTree,
1122
+ pl.userResources.authUser,
1123
+ );
1124
+ const liveEnvelopes = createLiveEnvelopesComputable(pendingSharesTree);
1125
+
442
1126
  return new MiddleLayer(
443
1127
  env,
444
1128
  driverKit,
445
1129
  driverKit.signer,
446
1130
  projects,
1131
+ sharingOutbox,
1132
+ sharingState,
447
1133
  openedProjects,
448
1134
  projectListTC.tree,
1135
+ outgoingTC.tree,
1136
+ sharingStateTree,
1137
+ pendingSharesTree,
449
1138
  v2RegistryProvider,
450
1139
  projectListTC.computable,
1140
+ outgoingTC.computable,
1141
+ pendingShares,
1142
+ liveEnvelopes,
451
1143
  );
452
1144
  }
453
1145
  }