@tearleads/client-sdk 0.1.253 → 0.1.255

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 (108) hide show
  1. package/client/containerContents/documentDiscovery.js +0 -2
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +7 -10
  4. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  5. package/data/persistence/container-contents/containerDeletionPersistence.js +5 -1
  6. package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
  7. package/data/persistence/container-contents/containerHydrationPersistence.js +1 -1
  8. package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
  9. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +11 -4
  10. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  11. package/data/persistence/container-contents/containerRemovalMetadata.js +47 -0
  12. package/data/persistence/container-contents/containerRemovalMetadata.js.map +1 -0
  13. package/data/persistence/container-contents/containerRemovalPlacements.js +22 -0
  14. package/data/persistence/container-contents/containerRemovalPlacements.js.map +1 -0
  15. package/data/persistence/container-contents/containerSyncWatermarkPersistence.d.ts +2 -1
  16. package/data/persistence/container-contents/containerSyncWatermarkPersistence.js +10 -2
  17. package/data/persistence/container-contents/containerSyncWatermarkPersistence.js.map +1 -1
  18. package/data/persistence/documents/documentDiscoveryCandidate.d.ts +1 -0
  19. package/data/persistence/documents/documentDiscoveryCandidate.js +3 -1
  20. package/data/persistence/documents/documentDiscoveryCandidate.js.map +1 -1
  21. package/data/persistence/documents/documentDiscoveryEvidencePersistence.d.ts +1 -1
  22. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +16 -4
  23. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  24. package/data/sqlite/migrations/localSchemaMigrations.js +11 -0
  25. package/data/sqlite/migrations/localSchemaMigrations.js.map +1 -1
  26. package/data/sqlite/schema/containerSyncWatermarkSchema.js +6 -3
  27. package/data/sqlite/schema/containerSyncWatermarkSchema.js.map +1 -1
  28. package/data/sqlite/schema/index.d.ts +17 -0
  29. package/index.d.ts +1 -1
  30. package/index.js +1 -1
  31. package/index.js.map +1 -1
  32. package/internal/api-client/ApiClient.d.ts +1 -0
  33. package/internal/api-client/client/apiClientContext.d.ts +1 -0
  34. package/internal/api-client/client/containerReads.d.ts +1 -0
  35. package/internal/api-client/requestInternals.js +14 -6
  36. package/internal/api-client/requestInternals.js.map +1 -1
  37. package/internal/validators/containerSystemSlot.d.ts +6 -0
  38. package/internal/validators/containerSystemSlot.js +14 -6
  39. package/internal/validators/containerSystemSlot.js.map +1 -1
  40. package/internal/validators/operation/containerReads.d.ts +29 -2
  41. package/internal/validators/operation/containerReads.js +2 -1
  42. package/internal/validators/operation/containerReads.js.map +1 -1
  43. package/internal/validators/request/containerDocumentLanes.d.ts +7 -0
  44. package/internal/validators/request/containerDocumentLanes.js +6 -0
  45. package/internal/validators/request/containerDocumentLanes.js.map +1 -1
  46. package/internal/validators/response/container.d.ts +8 -0
  47. package/internal/validators/response/container.js +1 -0
  48. package/internal/validators/response/container.js.map +1 -1
  49. package/internal/validators/response/containerParentLanes.d.ts +2 -0
  50. package/package.json +1 -1
  51. package/stores/container-contents/operations/index.js +4 -0
  52. package/stores/container-contents/operations/index.js.map +1 -1
  53. package/workflows/container-contents/container-state/create/createChild.d.ts +30 -0
  54. package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -0
  55. package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
  56. package/workflows/container-contents/container-state/remote.js +1 -1
  57. package/workflows/container-contents/container-state/remote.js.map +1 -1
  58. package/workflows/container-contents/container-state/types.d.ts +141 -0
  59. package/workflows/container-contents/documentDiscovery/containerDocumentListing.js +52 -4
  60. package/workflows/container-contents/documentDiscovery/containerDocumentListing.js.map +1 -1
  61. package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js +4 -2
  62. package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js.map +1 -1
  63. package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js +17 -12
  64. package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js.map +1 -1
  65. package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.js.map +1 -1
  66. package/workflows/container-contents/documentDiscovery/publicationWatermark.js +15 -0
  67. package/workflows/container-contents/documentDiscovery/publicationWatermark.js.map +1 -0
  68. package/workflows/container-contents/index.d.ts +1 -0
  69. package/workflows/container-contents/index.js +1 -0
  70. package/workflows/container-contents/index.js.map +1 -1
  71. package/workflows/container-contents/remoteHydration/destination/destinationSystemTopology.js +16 -0
  72. package/workflows/container-contents/remoteHydration/destination/destinationSystemTopology.js.map +1 -0
  73. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +8 -9
  74. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  75. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js +4 -4
  76. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js.map +1 -1
  77. package/workflows/container-contents/remoteHydration/lanes/restorationReceipt.js +25 -0
  78. package/workflows/container-contents/remoteHydration/lanes/restorationReceipt.js.map +1 -0
  79. package/workflows/container-contents/remoteHydration/lanes/tombstoneAccess.js +107 -0
  80. package/workflows/container-contents/remoteHydration/lanes/tombstoneAccess.js.map +1 -0
  81. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +29 -27
  82. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  83. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +17 -5
  84. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  85. package/workflows/container-contents/remoteHydration/tombstoneApplication.js +67 -24
  86. package/workflows/container-contents/remoteHydration/tombstoneApplication.js.map +1 -1
  87. package/workflows/container-contents/remoteHydration/types.d.ts +3 -1
  88. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  89. package/workflows/container-contents/remoteReset/remoteResetCursorScope.js +3 -3
  90. package/workflows/container-contents/remoteReset/remoteResetCursorScope.js.map +1 -1
  91. package/workflows/container-contents/syncPause/discoveryGuard.js +6 -2
  92. package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -1
  93. package/workflows/container-contents/tombstones/documentTombstoneGate.js +6 -3
  94. package/workflows/container-contents/tombstones/documentTombstoneGate.js.map +1 -1
  95. package/workflows/registration/bootstrapRootContainer.d.ts +1 -0
  96. package/workflows/registration/bootstrapRootContainer.js +9 -0
  97. package/workflows/registration/bootstrapRootContainer.js.map +1 -1
  98. package/workflows/registration/index.d.ts +1 -1
  99. package/workflows/registration/index.js +1 -1
  100. package/workflows/registration/index.js.map +1 -1
  101. package/workflows/registration/organizationProvisioning.d.ts +3 -2
  102. package/workflows/registration/organizationProvisioning.js +1 -2
  103. package/workflows/registration/organizationProvisioning.js.map +1 -1
  104. package/workflows/registration/provisioningBootstrapBuilders.d.ts +3 -5
  105. package/workflows/registration/provisioningBootstrapBuilders.js +11 -5
  106. package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
  107. package/workflows/registration/registerIdentity.js +2 -0
  108. package/workflows/registration/registerIdentity.js.map +1 -1
@@ -0,0 +1,15 @@
1
+ /** Select the server's publication-based recovery contract during rollout.
2
+ * Continuation positions inside the token remain opaque to the device. */
3
+ export function isPublicationWatermark(watermark) {
4
+ return watermark?.id.startsWith("d1/") === true;
5
+ }
6
+ /** An initial legacy cursor can replay on the upgraded API. Once a page has
7
+ * been read, both sides of the continuation must use the same ordering. */
8
+ export function changesDiscoveryOrder(previous, next, isContinuation) {
9
+ if (!previous || !next)
10
+ return false;
11
+ return isPublicationWatermark(previous)
12
+ ? !isPublicationWatermark(next)
13
+ : isContinuation && isPublicationWatermark(next);
14
+ }
15
+ //# sourceMappingURL=publicationWatermark.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publicationWatermark.js","sourceRoot":"","sources":["publicationWatermark.ts"],"names":[],"mappings":"AAEA;0EAC0E;AAC1E,MAAM,UAAU,sBAAsB,CACpC,SAA2C;IAE3C,OAAO,SAAS,EAAE,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC;AAClD,CAAC;AAED;2EAC2E;AAC3E,MAAM,UAAU,qBAAqB,CACnC,QAA0C,EAC1C,IAA0B,EAC1B,cAAuB;IAEvB,IAAI,CAAC,QAAQ,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAC;IACrC,OAAO,sBAAsB,CAAC,QAAQ,CAAC;QACrC,CAAC,CAAC,CAAC,sBAAsB,CAAC,IAAI,CAAC;QAC/B,CAAC,CAAC,cAAc,IAAI,sBAAsB,CAAC,IAAI,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import type { SyncWatermark } from \"@tearleads/validators/response\";\n\n/** Select the server's publication-based recovery contract during rollout.\n * Continuation positions inside the token remain opaque to the device. */\nexport function isPublicationWatermark(\n watermark: SyncWatermark | null | undefined,\n): boolean {\n return watermark?.id.startsWith(\"d1/\") === true;\n}\n\n/** An initial legacy cursor can replay on the upgraded API. Once a page has\n * been read, both sides of the continuation must use the same ordering. */\nexport function changesDiscoveryOrder(\n previous: SyncWatermark | null | undefined,\n next: SyncWatermark | null,\n isContinuation: boolean,\n): boolean {\n if (!previous || !next) return false;\n return isPublicationWatermark(previous)\n ? !isPublicationWatermark(next)\n : isContinuation && isPublicationWatermark(next);\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  export { DocumentContainerProjectionRepository } from "../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
2
2
  export { didRegainSyncPrerequisites, isDatabaseUnavailableError, } from "../../data/sync/syncCoordinator.js";
3
3
  export { type DocumentAttributionRangesInput, type DocumentAttributionRangesPage, loadDocumentAttributionRanges, } from "./attribution/documentAttributionRanges.js";
4
+ export { deriveSystemContainerId } from "./container-state/create/createChild.js";
4
5
  export type { ContainerContentsOrganizationHost } from "./container-state/organizationHost.js";
5
6
  export { type ContainerSyncWatermarkLane, ContainerSyncWatermarkRepository, createContainerContentsSyncLane, createContainerParentSyncLane, defaultContainerContentsPersistence, } from "./containerPersistence.js";
6
7
  export { type ContainerDocumentLinkInput, type ContainerDocumentQueries, type ContainerDocumentSidebarRow, type ContainerDocumentTombstone, type ContainerItemRow, type ContainerItemSort, type ContainerItemSortDirection, type ContainerItemSortKey, createContainerDocumentQueriesFromRuntime, } from "./documentQueries/index.js";
@@ -1,6 +1,7 @@
1
1
  export { DocumentContainerProjectionRepository } from "../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
2
2
  export { didRegainSyncPrerequisites, isDatabaseUnavailableError, } from "../../data/sync/syncCoordinator.js";
3
3
  export { loadDocumentAttributionRanges, } from "./attribution/documentAttributionRanges.js";
4
+ export { deriveSystemContainerId } from "./container-state/create/createChild.js";
4
5
  export { ContainerSyncWatermarkRepository, createContainerContentsSyncLane, createContainerParentSyncLane, defaultContainerContentsPersistence, } from "./containerPersistence.js";
5
6
  export { createContainerDocumentQueriesFromRuntime, } from "./documentQueries/index.js";
6
7
  export { activateDocumentLink, addDocumentLink, canMutateDocumentLink, canMutateLocalDocumentLink, moveDocumentLink, moveLocalDocumentLink, removeDocumentLink, } from "./documentQueries/documentStructure.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qCAAqC,EAAE,MAAM,kFAAkF,CAAC;AACzI,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAGL,6BAA6B,GAC9B,MAAM,yCAAyC,CAAC;AAEjD,OAAO,EAEL,gCAAgC,EAChC,+BAA+B,EAC/B,6BAA6B,EAC7B,mCAAmC,GACpC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EASL,yCAAyC,GAC1C,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,qBAAqB,EACrB,0BAA0B,EAG1B,gBAAgB,EAChB,qBAAqB,EACrB,kBAAkB,GAEnB,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EASL,YAAY,GACb,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAQL,iBAAiB,GAClB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAQL,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,uCAAuC,EACvC,wCAAwC,EACxC,uCAAuC,EACvC,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AACpB,OAAO,EAEL,0CAA0C,EAC1C,uBAAuB,EACvB,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,iBAAiB,GAOlB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,wDAAwD,EACxD,gDAAgD,EAChD,8CAA8C,GAC/C,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAcL,uCAAuC,EACvC,2CAA2C,EAC3C,uDAAuD,EACvD,sCAAsC,EACtC,kDAAkD,GACnD,MAAM,WAAW,CAAC;AAKnB,OAAO,EACL,sCAAsC,EACtC,sCAAsC,GACvC,MAAM,aAAa,CAAC;AACrB,OAAO,EAEL,yBAAyB,GAC1B,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,4BAA4B,CAAC","sourcesContent":["export { DocumentContainerProjectionRepository } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n type DocumentAttributionRangesInput,\n type DocumentAttributionRangesPage,\n loadDocumentAttributionRanges,\n} from \"./attribution/documentAttributionRanges\";\nexport type { ContainerContentsOrganizationHost } from \"./container-state/organizationHost\";\nexport {\n type ContainerSyncWatermarkLane,\n ContainerSyncWatermarkRepository,\n createContainerContentsSyncLane,\n createContainerParentSyncLane,\n defaultContainerContentsPersistence,\n} from \"./containerPersistence\";\nexport {\n type ContainerDocumentLinkInput,\n type ContainerDocumentQueries,\n type ContainerDocumentSidebarRow,\n type ContainerDocumentTombstone,\n type ContainerItemRow,\n type ContainerItemSort,\n type ContainerItemSortDirection,\n type ContainerItemSortKey,\n createContainerDocumentQueriesFromRuntime,\n} from \"./documentQueries\";\nexport {\n activateDocumentLink,\n addDocumentLink,\n canMutateDocumentLink,\n canMutateLocalDocumentLink,\n type DocumentStructuralMutationHost,\n type MergeDocumentSummary,\n moveDocumentLink,\n moveLocalDocumentLink,\n removeDocumentLink,\n type SetLinkedContainerIdsForDocument,\n} from \"./documentQueries/documentStructure\";\nexport type { PendingDownloadQueueItem } from \"./documentQueries/pendingDownloads\";\nexport {\n type BlobInfo,\n type BlobInfoAttachmentKind,\n type BlobInfoDocumentReference,\n type BlobInfoInput,\n type BlobInfoList,\n type BlobInfoSort,\n type BlobInfoSortDirection,\n type BlobInfoSortKey,\n listBlobInfo,\n} from \"./info/blobInfo\";\nexport {\n type ContainerInfo,\n type ContainerInfoGrant,\n type ContainerInfoGrantRow,\n type ContainerInfoPathEntry,\n type ContainerInfoRemoteMode,\n type ContainerInfoSecurityDetails,\n type ContainerShareAccessLevel,\n loadContainerInfo,\n} from \"./info/containerInfo\";\nexport {\n type DocumentInfo,\n type DocumentInfoAttachment,\n type DocumentInfoAuthorizingContainerPath,\n type DocumentInfoLocalDetails,\n type DocumentInfoRemoteAttachmentBinding,\n type DocumentInfoRemoteDetails,\n type DocumentInfoRemoteMode,\n loadDocumentInfo,\n} from \"./info/documentInfo\";\nexport {\n type ContainerMetadataPatch,\n hasContainerMetadataDocumentUpdateEvent,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n syncContainerMetadataState,\n} from \"./metadata\";\nexport {\n type ContainerMetadataDocument,\n createInitializedContainerMetadataDocument,\n getDefaultContainerName,\n readContainerMetadataValue,\n writeContainerMetadataValue,\n} from \"./metadata/containerMetadataDocument\";\nexport {\n listPendingWrites,\n type PendingWriteQueueItem,\n type PendingWriteQueueItemStatus,\n type PendingWriteQueueObjectKind,\n type PendingWriteQueueOperation,\n type PendingWriteQueueOperationKind,\n type PendingWriteQueueOperationStatus,\n} from \"./pendingWrites\";\nexport {\n type ContainerContentsProjectionUserKeyResolver,\n createContainerContentsDocumentProjectionUserKeyResolver,\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport type { RecoveryFolder } from \"./recovery/folderRecovery\";\nexport {\n type ContainerContentsRootAdopter,\n type ContainerContentsRootAdoptionInput,\n type ContainerContentsStoreWorkflowRuntime,\n type ContainerContentsWorkflowRuntime,\n type ContainerContentsWorkflowRuntimeAuth,\n type ContainerContentsWorkflowRuntimeCrypto,\n type ContainerContentsWorkflowRuntimeGroups,\n type ContainerContentsWorkflowRuntimeInfra,\n type ContainerContentsWorkflowRuntimeInput,\n type ContainerContentsWorkflowRuntimeInputGroups,\n type ContainerContentsWorkflowRuntimeSnapshot,\n type ContainerContentsWorkflowRuntimeState,\n type ContainerContentsWorkflowRuntimeUtil,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsStoreWorkflowRuntimeFromSnapshot,\n createContainerContentsWorkflowRuntime,\n createContainerContentsWorkflowRuntimeFromSnapshot,\n} from \"./runtime\";\nexport type {\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n} from \"./syncState\";\nexport {\n createContainerDocumentObjectSyncState,\n syncedContainerDocumentObjectSyncState,\n} from \"./syncState\";\nexport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"./systemSlot\";\nexport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"./tombstones/documentPurge\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EA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O,EACL,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,4BAA4B,CAAC","sourcesContent":["export { DocumentContainerProjectionRepository } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n type DocumentAttributionRangesInput,\n type DocumentAttributionRangesPage,\n loadDocumentAttributionRanges,\n} from \"./attribution/documentAttributionRanges\";\nexport { deriveSystemContainerId } from \"./container-state/create/createChild\";\nexport type { ContainerContentsOrganizationHost } from \"./container-state/organizationHost\";\nexport {\n type ContainerSyncWatermarkLane,\n ContainerSyncWatermarkRepository,\n createContainerContentsSyncLane,\n createContainerParentSyncLane,\n defaultContainerContentsPersistence,\n} from \"./containerPersistence\";\nexport {\n type ContainerDocumentLinkInput,\n type ContainerDocumentQueries,\n type ContainerDocumentSidebarRow,\n type ContainerDocumentTombstone,\n type ContainerItemRow,\n type ContainerItemSort,\n type ContainerItemSortDirection,\n type ContainerItemSortKey,\n createContainerDocumentQueriesFromRuntime,\n} from \"./documentQueries\";\nexport {\n activateDocumentLink,\n addDocumentLink,\n canMutateDocumentLink,\n canMutateLocalDocumentLink,\n type DocumentStructuralMutationHost,\n type MergeDocumentSummary,\n moveDocumentLink,\n moveLocalDocumentLink,\n removeDocumentLink,\n type SetLinkedContainerIdsForDocument,\n} from \"./documentQueries/documentStructure\";\nexport type { PendingDownloadQueueItem } from \"./documentQueries/pendingDownloads\";\nexport {\n type BlobInfo,\n type BlobInfoAttachmentKind,\n type BlobInfoDocumentReference,\n type BlobInfoInput,\n type BlobInfoList,\n type BlobInfoSort,\n type BlobInfoSortDirection,\n type BlobInfoSortKey,\n listBlobInfo,\n} from \"./info/blobInfo\";\nexport {\n type ContainerInfo,\n type ContainerInfoGrant,\n type ContainerInfoGrantRow,\n type ContainerInfoPathEntry,\n type ContainerInfoRemoteMode,\n type ContainerInfoSecurityDetails,\n type ContainerShareAccessLevel,\n loadContainerInfo,\n} from \"./info/containerInfo\";\nexport {\n type DocumentInfo,\n type DocumentInfoAttachment,\n type DocumentInfoAuthorizingContainerPath,\n type DocumentInfoLocalDetails,\n type DocumentInfoRemoteAttachmentBinding,\n type DocumentInfoRemoteDetails,\n type DocumentInfoRemoteMode,\n loadDocumentInfo,\n} from \"./info/documentInfo\";\nexport {\n type ContainerMetadataPatch,\n hasContainerMetadataDocumentUpdateEvent,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n syncContainerMetadataState,\n} from \"./metadata\";\nexport {\n type ContainerMetadataDocument,\n createInitializedContainerMetadataDocument,\n getDefaultContainerName,\n readContainerMetadataValue,\n writeContainerMetadataValue,\n} from \"./metadata/containerMetadataDocument\";\nexport {\n listPendingWrites,\n type PendingWriteQueueItem,\n type PendingWriteQueueItemStatus,\n type PendingWriteQueueObjectKind,\n type PendingWriteQueueOperation,\n type PendingWriteQueueOperationKind,\n type PendingWriteQueueOperationStatus,\n} from \"./pendingWrites\";\nexport {\n type ContainerContentsProjectionUserKeyResolver,\n createContainerContentsDocumentProjectionUserKeyResolver,\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport type { RecoveryFolder } from \"./recovery/folderRecovery\";\nexport {\n type ContainerContentsRootAdopter,\n type ContainerContentsRootAdoptionInput,\n type ContainerContentsStoreWorkflowRuntime,\n type ContainerContentsWorkflowRuntime,\n type ContainerContentsWorkflowRuntimeAuth,\n type ContainerContentsWorkflowRuntimeCrypto,\n type ContainerContentsWorkflowRuntimeGroups,\n type ContainerContentsWorkflowRuntimeInfra,\n type ContainerContentsWorkflowRuntimeInput,\n type ContainerContentsWorkflowRuntimeInputGroups,\n type ContainerContentsWorkflowRuntimeSnapshot,\n type ContainerContentsWorkflowRuntimeState,\n type ContainerContentsWorkflowRuntimeUtil,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsStoreWorkflowRuntimeFromSnapshot,\n createContainerContentsWorkflowRuntime,\n createContainerContentsWorkflowRuntimeFromSnapshot,\n} from \"./runtime\";\nexport type {\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n} from \"./syncState\";\nexport {\n createContainerDocumentObjectSyncState,\n syncedContainerDocumentObjectSyncState,\n} from \"./syncState\";\nexport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"./systemSlot\";\nexport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"./tombstones/documentPurge\";\n"]}
@@ -0,0 +1,16 @@
1
+ import { KeyingVerificationError } from "../../../../internal/crypto/index.js";
2
+ import { deriveOrganizationMetadataContainerSystemSlot, deriveOrganizationTrashSystemSlot, } from "../../../../internal/validators/containerSystemSlot.js";
3
+ /** All fields come from the verified path, including parents absent from the local tree. */
4
+ export async function assertSystemDestinationTopology(input) {
5
+ if (input.systemSlot === null)
6
+ return;
7
+ const metadataSlot = await deriveOrganizationMetadataContainerSystemSlot(input);
8
+ if (input.rootSystemSlot !== null &&
9
+ input.systemSlot === deriveOrganizationTrashSystemSlot(input.organizationId)) {
10
+ throw new KeyingVerificationError("invalid_shape", "Trash must be a child of the organization's data root");
11
+ }
12
+ if (input.pathLength !== (input.systemSlot === metadataSlot ? 1 : 2)) {
13
+ throw new KeyingVerificationError("invalid_shape", "system destination has the wrong signed topology");
14
+ }
15
+ }
16
+ //# sourceMappingURL=destinationSystemTopology.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"destinationSystemTopology.js","sourceRoot":"","sources":["destinationSystemTopology.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,6CAA6C,EAC7C,iCAAiC,GAClC,MAAM,2CAA2C,CAAC;AAEnD,4FAA4F;AAC5F,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAKrD;IACC,IAAI,KAAK,CAAC,UAAU,KAAK,IAAI;QAAE,OAAO;IACtC,MAAM,YAAY,GAChB,MAAM,6CAA6C,CAAC,KAAK,CAAC,CAAC;IAC7D,IACE,KAAK,CAAC,cAAc,KAAK,IAAI;QAC7B,KAAK,CAAC,UAAU,KAAK,iCAAiC,CAAC,KAAK,CAAC,cAAc,CAAC,EAC5E,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,uDAAuD,CACxD,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,UAAU,KAAK,CAAC,KAAK,CAAC,UAAU,KAAK,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACrE,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,kDAAkD,CACnD,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationTrashSystemSlot,\n} from \"@tearleads/validators/containerSystemSlot\";\n\n/** All fields come from the verified path, including parents absent from the local tree. */\nexport async function assertSystemDestinationTopology(input: {\n organizationId: string;\n pathLength: number;\n rootSystemSlot: string | null;\n systemSlot: string | null;\n}) {\n if (input.systemSlot === null) return;\n const metadataSlot =\n await deriveOrganizationMetadataContainerSystemSlot(input);\n if (\n input.rootSystemSlot !== null &&\n input.systemSlot === deriveOrganizationTrashSystemSlot(input.organizationId)\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Trash must be a child of the organization's data root\",\n );\n }\n if (input.pathLength !== (input.systemSlot === metadataSlot ? 1 : 2)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"system destination has the wrong signed topology\",\n );\n }\n}\n"]}
@@ -1,11 +1,11 @@
1
1
  import { KeyingVerificationError, } from "../../../../internal/crypto/index.js";
2
- import { deriveOrganizationMetadataContainerSystemSlot } from "../../../../internal/validators/containerSystemSlot.js";
3
2
  import { verifiedContainerCreateManifest, verifyContainerDestinationProjection, verifyContainerWriterProjection, } from "../../../../data/keyingProjectionVerification/index.js";
4
3
  import { listingRepeatsHeldOrdinaryBinding, } from "../../../../data/persistence/container-contents/containerBinding.js";
5
4
  import { openPrincipalPolicyBundleReader } from "../../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
6
5
  import { isKeyingVerificationError, reportKeyingVerificationErrorInCauseChain, runWithSecurityIncidentReporting, } from "../../../../data/shared/securityIncidents.js";
7
6
  import { cachedDestinationRole, rememberDestinationRole, } from "./destinationRoleCache.js";
8
7
  import { resolveWithMetadataRootReload } from "./destinationRootReload.js";
8
+ import { assertSystemDestinationTopology } from "./destinationSystemTopology.js";
9
9
  import { assertPermittedDestinationBinding } from "./replacementBinding.js";
10
10
  async function destinationRoleFromPath(input) {
11
11
  const { listed, path } = input;
@@ -15,13 +15,15 @@ async function destinationRoleFromPath(input) {
15
15
  head.state.organizationId !== listed.organizationId) {
16
16
  throw new KeyingVerificationError("object_mismatch", "container destination manifest has the wrong identity");
17
17
  }
18
- const metadataSlot = await deriveOrganizationMetadataContainerSystemSlot({
18
+ const root = path[0];
19
+ if (!root)
20
+ throw new Error("Destination root is unavailable");
21
+ await assertSystemDestinationTopology({
19
22
  organizationId: listed.organizationId,
23
+ systemSlot: head.state.systemSlot,
24
+ pathLength: path.length,
25
+ rootSystemSlot: root.state.systemSlot,
20
26
  });
21
- if (head.state.systemSlot !== null &&
22
- path.length !== (head.state.systemSlot === metadataSlot ? 1 : 2)) {
23
- throw new KeyingVerificationError("invalid_shape", "system destination has the wrong signed topology");
24
- }
25
27
  // The head may be a later grant signed by any admin; only the epoch-1
26
28
  // create names the creator, and roots are always created by the org owner.
27
29
  const created = verifiedContainerCreateManifest({
@@ -29,9 +31,6 @@ async function destinationRoleFromPath(input) {
29
31
  label: "Container destination",
30
32
  verifiedByHash: input.verifiedByHash,
31
33
  });
32
- const root = path[0];
33
- if (!root)
34
- throw new Error("Destination root is unavailable");
35
34
  const rootCreated = verifiedContainerCreateManifest({
36
35
  head: root,
37
36
  label: "Destination root",
@@ -1 +1 @@
1
- {"version":3,"file":"verifiedDestination.js","sourceRoot":"","sources":["verifiedDestination.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6CAA6C,EAAE,MAAM,2CAA2C,CAAC;AAC1G,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,EACpC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAEL,iCAAiC,GAClC,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,+BAA+B,EAAE,MAAM,8EAA8E,CAAC;AAC/H,OAAO,EACL,yBAAyB,EACzB,yCAAyC,EACzC,gCAAgC,GACjC,MAAM,2CAA2C,CAAC;AAOnD,OAAO,EACL,qBAAqB,EAErB,uBAAuB,GACxB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,6BAA6B,EAAE,MAAM,yBAAyB,CAAC;AACxE,OAAO,EAAE,iCAAiC,EAAE,MAAM,sBAAsB,CAAC;AAKzE,KAAK,UAAU,uBAAuB,CAAC,KAItC;IACC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC;IAC/B,MAAM,IAAI,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IACzB,IACE,CAAC,IAAI;QACL,IAAI,CAAC,KAAK,CAAC,WAAW,KAAK,MAAM,CAAC,EAAE;QACpC,IAAI,CAAC,KAAK,CAAC,cAAc,KAAK,MAAM,CAAC,cAAc,EACnD,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,uDAAuD,CACxD,CAAC;IACJ,CAAC;IACD,MAAM,YAAY,GAAG,MAAM,6CAA6C,CAAC;QACvE,cAAc,EAAE,MAAM,CAAC,cAAc;KACtC,CAAC,CAAC;IACH,IACE,IAAI,CAAC,KAAK,CAAC,UAAU,KAAK,IAAI;QA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M,EAAE,SAAS,EAAE,GAAG,eAAe,CAAC;IACtC,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IAC9B,IAAI,CAAC,kBAAkB,CAAC,eAAe,EAAE,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,IAAI,GAAG,qBAAqB,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IACrE,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAC;IACxB,IAAI,CAAC;QACH,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI,EAAE,CAAC;YAC3B,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,2DAA2D,CAC5D,CAAC;QACJ,CAAC;QACD,8BAA8B,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC9C,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,QAAQ,GAAG,MAAM,yCAAyC,CAC9D,KAAK,EACL,OAAO,CAAC,IAAI,CAAC,sBAAsB,EACnC;YACE,QAAQ,EAAE,SAAS,CAAC,EAAE;YACtB,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,0BAA0B;YACrC,cAAc,EAAE,SAAS,CAAC,cAAc;SACzC,CACF,CAAC;QACF,IAAI,CAAC,QAAQ;YAAE,MAAM,KAAK,CAAC;QAC3B,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport {\n verifiedContainerCreateManifest,\n verifyContainerDestinationProjection,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport {\n type HeldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../../data/persistence/container-contents/containerBinding\";\nimport { openPrincipalPolicyBundleReader } from \"../../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n runWithSecurityIncidentReporting,\n} from \"../../../../data/shared/securityIncidents\";\nimport type {\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationState,\n} from \"../types\";\nimport type { PrefetchedDestinationProjection } from \"./destinationPrefetch\";\nimport {\n cachedDestinationRole,\n type DestinationRole,\n rememberDestinationRole,\n} from \"./destinationRoleCache\";\nimport { resolveWithMetadataRootReload } from \"./destinationRootReload\";\nimport { assertPermittedDestinationBinding } from \"./replacementBinding\";\n\n/** The identity a role is verified and cached under. */\ntype DestinationIdentity = Pick<RemoteContainer, \"id\" | \"organizationId\">;\n\nasync function destinationRoleFromPath(input: {\n listed: DestinationIdentity;\n path: readonly VerifiedContainerAccessManifest[];\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): Promise<{ role: DestinationRole; parentId: string | null }> {\n const { listed, path } = input;\n const head = path.at(-1);\n if (\n !head ||\n head.state.containerId !== listed.id ||\n head.state.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination manifest has the wrong identity\",\n );\n }\n const metadataSlot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: listed.organizationId,\n });\n if (\n head.state.systemSlot !== null &&\n path.length !== (head.state.systemSlot === metadataSlot ? 1 : 2)\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"system destination has the wrong signed topology\",\n );\n }\n // The head may be a later grant signed by any admin; only the epoch-1\n // create names the creator, and roots are always created by the org owner.\n const created = verifiedContainerCreateManifest({\n head,\n label: \"Container destination\",\n verifiedByHash: input.verifiedByHash,\n });\n const root = path[0];\n if (!root) throw new Error(\"Destination root is unavailable\");\n const rootCreated = verifiedContainerCreateManifest({\n head: root,\n label: \"Destination root\",\n verifiedByHash: input.verifiedByHash,\n });\n return {\n parentId: head.state.parentContainerId,\n role: {\n createSignerUserId: created.event.event.signerUserId,\n rootContainerId: rootCreated.state.containerId,\n rootCreateManifestHash: rootCreated.manifestHash,\n rootMetadataDocumentId: rootCreated.state.metadataDocumentId,\n metadataDocumentId: head.state.metadataDocumentId,\n ...(head.state.parentContainerId === null ||\n head.state.systemSlot !== null\n ? { parentId: head.state.parentContainerId }\n : {}),\n systemSlot: head.state.systemSlot,\n },\n };\n}\n\n/**\n * The session's root id arrives in an unsigned login response, so the root it\n * names must prove it belongs to this user: every acknowledged organization was\n * created by the session user, whose device signed the root's `container.create`.\n * A verified root created by anyone else is a substitution, never the merge\n * target for pre-login local content, whatever grants it carries. The check\n * runs on cache reuse too, since the cache is not scoped to the session user.\n */\nfunction assertRootCreatedBySessionUser(\n role: DestinationRole,\n runtime: RemoteContainerHydrationState[\"runtime\"],\n): void {\n if (role.systemSlot !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"acknowledged session root cannot be a system container\",\n );\n }\n if (role.createSignerUserId !== runtime.auth.userId) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"acknowledged session root was not created by the session user\",\n );\n }\n}\n\nfunction assertAcknowledgedRootSigner(input: {\n listed: DestinationIdentity;\n role: DestinationRole;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): void {\n const { listed, role, runtime } = input;\n if (role.parentId !== null || listed.id !== runtime.auth.rootContainerId) {\n return;\n }\n assertRootCreatedBySessionUser(role, runtime);\n}\n\n/**\n * Authenticate destination roles before admitting a binding or advancing any\n * placement pin. Shared rehomes additionally require signed replacement evidence.\n */\nfunction assertDestinationProjectionIdentity(\n projection: { readonly containerId: string; readonly organizationId: string },\n listed: DestinationIdentity,\n): void {\n if (\n projection.containerId !== listed.id ||\n projection.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination projection has the wrong identity\",\n );\n }\n}\n\nasync function verifyDestinationRole(input: {\n heldBinding: HeldContainerBinding | null;\n prefetched: PrefetchedDestinationProjection | undefined;\n verifyCurrentPlacement: boolean;\n onVerifiedCheckpoint:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n isCurrent?: (() => boolean) | undefined;\n listed: DestinationIdentity;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): Promise<{ role: DestinationRole; parentId: string | null } | null> {\n const { isCurrent, listed, runtime } = input;\n const projection = input.prefetched\n ? input.prefetched.projection\n : await runtime.apiClient.getContainerWriterProjection(listed.id);\n if (!projection || isCurrent?.() === false) return null;\n assertDestinationProjectionIdentity(projection, listed);\n const verificationInput = {\n execSql: runtime.infra.execSql,\n openPrincipalPolicyBundleReader,\n projection,\n resolveUserKey: runtime.resolveTrustedUserIdentity,\n stillCurrent: isCurrent,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer(),\n };\n const { path, verifiedByHash } =\n await verifyContainerDestinationProjection(verificationInput);\n if (isCurrent?.() === false) return null;\n const destination = await destinationRoleFromPath({\n listed,\n path,\n verifiedByHash,\n });\n const { role } = destination;\n // Refuse a rebinding before group checks or placement pins run for it.\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (role.parentId === null && role.systemSlot !== null) {\n const head = path.at(-1);\n if (!head) throw new Error(\"Metadata root manifest is unavailable\");\n await runtime.organizations.verifyGroupMetadataAuthority({\n runtime,\n organizationId: listed.organizationId,\n organizationReference: projection.policyEvidence.organization?.head,\n state: head.state,\n stillCurrent: isCurrent ?? (() => true),\n });\n }\n if (isCurrent?.() === false) return null;\n if (input.verifyCurrentPlacement) {\n // Check the immutable role before allowing current placement to advance pins.\n assertAcknowledgedRootSigner({ listed, role, runtime });\n const currentPath = await verifyContainerWriterProjection({\n ...verificationInput,\n stillCurrent: isCurrent,\n });\n const currentHead = currentPath.at(-1);\n if (!currentHead)\n throw new Error(\"Recovery placement manifest is unavailable\");\n input.onVerifiedCheckpoint?.(currentHead.checkpoint);\n }\n if (isCurrent?.() === false) return null;\n return destination;\n}\n\ntype VerifyRemoteContainerDestinationInput = {\n heldBinding: HeldContainerBinding | null;\n /** The held folder was re-homed away from the listed organization. */\n supersededListing?: boolean | undefined;\n /** Fetched ahead by page hydration; ignored when placement is refreshed. */\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n refresh?: boolean;\n onVerifiedCheckpoint?:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n isCurrent?: (() => boolean) | undefined;\n};\n\n/** A cached immutable role, or a freshly verified one with its signed parent. */\nasync function resolveDestinationRole(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<{\n freshlyVerified: boolean;\n parentId: string | null | undefined;\n role: DestinationRole;\n} | null> {\n const { remoteContainer: listed, isCurrent } = input;\n const runtime = input.state.runtime;\n const cached = input.refresh\n ? undefined\n : cachedDestinationRole(runtime.infra.execSql, listed);\n // Ordinary parent edges are not immutable. A refresh authenticates current\n // placement; a forged root hint must also be corrected from a signed path.\n if (cached && !(cached.parentId === undefined && listed.parentId === null)) {\n return { freshlyVerified: false, parentId: cached.parentId, role: cached };\n }\n const verified = await verifyDestinationRole({\n heldBinding: input.heldBinding,\n prefetched: input.refresh ? undefined : input.prefetchedProjection,\n isCurrent,\n listed,\n runtime,\n verifyCurrentPlacement: input.refresh === true,\n onVerifiedCheckpoint: input.onVerifiedCheckpoint,\n });\n if (!verified) return null;\n return {\n freshlyVerified: true,\n parentId:\n input.refresh || listed.parentId === null\n ? verified.parentId\n : verified.role.parentId,\n role: verified.role,\n };\n}\n\n/**\n * A held ordinary binding was verified (or signed by this device) when it was\n * stored; a listing that repeats it needs no second proof. A listing the\n * caller already found superseded is refused.\n */\nfunction heldOrdinaryBindingStands(\n input: VerifyRemoteContainerDestinationInput,\n): boolean {\n if (input.supersededListing) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container was re-homed away from the listed organization\",\n );\n }\n return (\n !input.refresh &&\n listingRepeatsHeldOrdinaryBinding(input.heldBinding, input.remoteContainer)\n );\n}\n\n/**\n * Listing hints never establish a metadata target or a system/root role, and a\n * held folder keeps its organization and metadata target unless its own user\n * re-created it or its pinned founder authorized a verified replacement.\n * A conflicting proof is refused before placement pins\n * advance or its role is cached.\n */\nexport async function verifyRemoteContainerDestination(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<RemoteContainer | null> {\n const { remoteContainer: listed, state, isCurrent } = input;\n const runtime = state.runtime;\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: listed.id,\n objectKind: \"container\",\n operation: \"container.destination.verify\",\n organizationId: listed.organizationId,\n },\n async () => {\n if (heldOrdinaryBindingStands(input)) {\n return { ...listed, systemSlot: null };\n }\n if (input.refresh)\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n // A metadata root read before a reserved-group commit is reloaded once.\n const resolved = await resolveWithMetadataRootReload(\n input,\n resolveDestinationRole,\n () => runtime.apiClient.evictContainerWriterProjection(listed.id),\n runtime.organizations.withMetadataRootReload,\n ).catch((error: unknown) => {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error))\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n throw error;\n });\n if (!resolved || isCurrent?.() === false) return null;\n const { role, parentId } = resolved;\n // Fresh verification checked this binding before any placement pins.\n // A cached role still needs the held binding and replacement proof checked.\n if (!resolved.freshlyVerified)\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (resolved.freshlyVerified)\n rememberDestinationRole(runtime.infra.execSql, listed, role);\n assertAcknowledgedRootSigner({ listed, role, runtime });\n return {\n ...listed,\n metadataDocumentId: role.metadataDocumentId,\n parentId: parentId === undefined ? listed.parentId : parentId,\n systemSlot: role.systemSlot,\n };\n },\n );\n}\n\n/** The root the unsigned login answer named, in the expected organization. */\nexport function isSessionRootState(\n remoteRootState: ContainerState,\n state: RemoteContainerHydrationState,\n): boolean {\n const { container } = remoteRootState;\n const { auth } = state.runtime;\n return (\n container.parentId === null &&\n !container.systemSlot &&\n container.id === auth.rootContainerId &&\n container.organizationId === auth.organizationId\n );\n}\n\n/**\n * Whether the session root may absorb the pre-login local roots. The unsigned\n * login answer only names the root; the merge target must also be the verified\n * root whose epoch-1 `container.create` the session user signed. A row persisted\n * earlier as an ordinary shared container (another user's root this device once\n * hydrated) never passed that check for this session, so the creator is checked\n * here, at the reconciliation boundary itself, before any local content is\n * re-parented. The role comes only from the cache remote hydration fills when\n * it verifies the destination: this gate never fetches, so a local refresh stays\n * independent of the network. Without a cached role the merge is left pending\n * (no incident) until hydration verifies the root and reconciles from the\n * cache. A different creator is a `signer_mismatch` incident and never a merge;\n * the refusal is the \"no merge\" outcome, so the refresh that carried it\n * completes with the local content left in place.\n */\nexport async function isVerifiedLocalRootReconciliationTarget(input: {\n remoteRootState: ContainerState;\n state: RemoteContainerHydrationState;\n}): Promise<boolean> {\n const { remoteRootState, state } = input;\n const { container } = remoteRootState;\n const runtime = state.runtime;\n if (!isSessionRootState(remoteRootState, state)) return false;\n const role = cachedDestinationRole(runtime.infra.execSql, container);\n if (!role) return false;\n try {\n if (role.parentId !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"session root reconciliation target is not a verified root\",\n );\n }\n assertRootCreatedBySessionUser(role, runtime);\n return true;\n } catch (error) {\n const reported = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: container.id,\n objectKind: \"container\",\n operation: \"container.root.reconcile\",\n organizationId: container.organizationId,\n },\n );\n if (!reported) throw error;\n return false;\n }\n}\n"]}
1
+ {"version":3,"file":"verifiedDestination.js","sourceRoot":"","sources":["verifiedDestination.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,+B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Q,KAAK,IAAI,EAAE,CAAC;YAC3B,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,2DAA2D,CAC5D,CAAC;QACJ,CAAC;QACD,8BAA8B,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC9C,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,QAAQ,GAAG,MAAM,yCAAyC,CAC9D,KAAK,EACL,OAAO,CAAC,IAAI,CAAC,sBAAsB,EACnC;YACE,QAAQ,EAAE,SAAS,CAAC,EAAE;YACtB,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,0BAA0B;YACrC,cAAc,EAAE,SAAS,CAAC,cAAc;SACzC,CACF,CAAC;QACF,IAAI,CAAC,QAAQ;YAAE,MAAM,KAAK,CAAC;QAC3B,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport {\n verifiedContainerCreateManifest,\n verifyContainerDestinationProjection,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport {\n type HeldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../../data/persistence/container-contents/containerBinding\";\nimport { openPrincipalPolicyBundleReader } from \"../../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n runWithSecurityIncidentReporting,\n} from \"../../../../data/shared/securityIncidents\";\nimport type {\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationState,\n} from \"../types\";\nimport type { PrefetchedDestinationProjection } from \"./destinationPrefetch\";\nimport {\n cachedDestinationRole,\n type DestinationRole,\n rememberDestinationRole,\n} from \"./destinationRoleCache\";\nimport { resolveWithMetadataRootReload } from \"./destinationRootReload\";\nimport { assertSystemDestinationTopology } from \"./destinationSystemTopology\";\nimport { assertPermittedDestinationBinding } from \"./replacementBinding\";\n\n/** The identity a role is verified and cached under. */\ntype DestinationIdentity = Pick<RemoteContainer, \"id\" | \"organizationId\">;\n\nasync function destinationRoleFromPath(input: {\n listed: DestinationIdentity;\n path: readonly VerifiedContainerAccessManifest[];\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): Promise<{ role: DestinationRole; parentId: string | null }> {\n const { listed, path } = input;\n const head = path.at(-1);\n if (\n !head ||\n head.state.containerId !== listed.id ||\n head.state.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination manifest has the wrong identity\",\n );\n }\n const root = path[0];\n if (!root) throw new Error(\"Destination root is unavailable\");\n await assertSystemDestinationTopology({\n organizationId: listed.organizationId,\n systemSlot: head.state.systemSlot,\n pathLength: path.length,\n rootSystemSlot: root.state.systemSlot,\n });\n // The head may be a later grant signed by any admin; only the epoch-1\n // create names the creator, and roots are always created by the org owner.\n const created = verifiedContainerCreateManifest({\n head,\n label: \"Container destination\",\n verifiedByHash: input.verifiedByHash,\n });\n const rootCreated = verifiedContainerCreateManifest({\n head: root,\n label: \"Destination root\",\n verifiedByHash: input.verifiedByHash,\n });\n return {\n parentId: head.state.parentContainerId,\n role: {\n createSignerUserId: created.event.event.signerUserId,\n rootContainerId: rootCreated.state.containerId,\n rootCreateManifestHash: rootCreated.manifestHash,\n rootMetadataDocumentId: rootCreated.state.metadataDocumentId,\n metadataDocumentId: head.state.metadataDocumentId,\n ...(head.state.parentContainerId === null ||\n head.state.systemSlot !== null\n ? { parentId: head.state.parentContainerId }\n : {}),\n systemSlot: head.state.systemSlot,\n },\n };\n}\n\n/**\n * The session's root id arrives in an unsigned login response, so the root it\n * names must prove it belongs to this user: every acknowledged organization was\n * created by the session user, whose device signed the root's `container.create`.\n * A verified root created by anyone else is a substitution, never the merge\n * target for pre-login local content, whatever grants it carries. The check\n * runs on cache reuse too, since the cache is not scoped to the session user.\n */\nfunction assertRootCreatedBySessionUser(\n role: DestinationRole,\n runtime: RemoteContainerHydrationState[\"runtime\"],\n): void {\n if (role.systemSlot !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"acknowledged session root cannot be a system container\",\n );\n }\n if (role.createSignerUserId !== runtime.auth.userId) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"acknowledged session root was not created by the session user\",\n );\n }\n}\n\nfunction assertAcknowledgedRootSigner(input: {\n listed: DestinationIdentity;\n role: DestinationRole;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): void {\n const { listed, role, runtime } = input;\n if (role.parentId !== null || listed.id !== runtime.auth.rootContainerId) {\n return;\n }\n assertRootCreatedBySessionUser(role, runtime);\n}\n\n/**\n * Authenticate destination roles before admitting a binding or advancing any\n * placement pin. Shared rehomes additionally require signed replacement evidence.\n */\nfunction assertDestinationProjectionIdentity(\n projection: { readonly containerId: string; readonly organizationId: string },\n listed: DestinationIdentity,\n): void {\n if (\n projection.containerId !== listed.id ||\n projection.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination projection has the wrong identity\",\n );\n }\n}\n\nasync function verifyDestinationRole(input: {\n heldBinding: HeldContainerBinding | null;\n prefetched: PrefetchedDestinationProjection | undefined;\n verifyCurrentPlacement: boolean;\n onVerifiedCheckpoint:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n isCurrent?: (() => boolean) | undefined;\n listed: DestinationIdentity;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): Promise<{ role: DestinationRole; parentId: string | null } | null> {\n const { isCurrent, listed, runtime } = input;\n const projection = input.prefetched\n ? input.prefetched.projection\n : await runtime.apiClient.getContainerWriterProjection(listed.id);\n if (!projection || isCurrent?.() === false) return null;\n assertDestinationProjectionIdentity(projection, listed);\n const verificationInput = {\n execSql: runtime.infra.execSql,\n openPrincipalPolicyBundleReader,\n projection,\n resolveUserKey: runtime.resolveTrustedUserIdentity,\n stillCurrent: isCurrent,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer(),\n };\n const { path, verifiedByHash } =\n await verifyContainerDestinationProjection(verificationInput);\n if (isCurrent?.() === false) return null;\n const destination = await destinationRoleFromPath({\n listed,\n path,\n verifiedByHash,\n });\n const { role } = destination;\n // Refuse a rebinding before group checks or placement pins run for it.\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (role.parentId === null && role.systemSlot !== null) {\n const head = path.at(-1);\n if (!head) throw new Error(\"Metadata root manifest is unavailable\");\n await runtime.organizations.verifyGroupMetadataAuthority({\n runtime,\n organizationId: listed.organizationId,\n organizationReference: projection.policyEvidence.organization?.head,\n state: head.state,\n stillCurrent: isCurrent ?? (() => true),\n });\n }\n if (isCurrent?.() === false) return null;\n if (input.verifyCurrentPlacement) {\n // Check the immutable role before allowing current placement to advance pins.\n assertAcknowledgedRootSigner({ listed, role, runtime });\n const currentPath = await verifyContainerWriterProjection({\n ...verificationInput,\n stillCurrent: isCurrent,\n });\n const currentHead = currentPath.at(-1);\n if (!currentHead)\n throw new Error(\"Recovery placement manifest is unavailable\");\n input.onVerifiedCheckpoint?.(currentHead.checkpoint);\n }\n if (isCurrent?.() === false) return null;\n return destination;\n}\n\ntype VerifyRemoteContainerDestinationInput = {\n heldBinding: HeldContainerBinding | null;\n /** The held folder was re-homed away from the listed organization. */\n supersededListing?: boolean | undefined;\n /** Fetched ahead by page hydration; ignored when placement is refreshed. */\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n refresh?: boolean;\n onVerifiedCheckpoint?:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n isCurrent?: (() => boolean) | undefined;\n};\n\n/** A cached immutable role, or a freshly verified one with its signed parent. */\nasync function resolveDestinationRole(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<{\n freshlyVerified: boolean;\n parentId: string | null | undefined;\n role: DestinationRole;\n} | null> {\n const { remoteContainer: listed, isCurrent } = input;\n const runtime = input.state.runtime;\n const cached = input.refresh\n ? undefined\n : cachedDestinationRole(runtime.infra.execSql, listed);\n // Ordinary parent edges are not immutable. A refresh authenticates current\n // placement; a forged root hint must also be corrected from a signed path.\n if (cached && !(cached.parentId === undefined && listed.parentId === null)) {\n return { freshlyVerified: false, parentId: cached.parentId, role: cached };\n }\n const verified = await verifyDestinationRole({\n heldBinding: input.heldBinding,\n prefetched: input.refresh ? undefined : input.prefetchedProjection,\n isCurrent,\n listed,\n runtime,\n verifyCurrentPlacement: input.refresh === true,\n onVerifiedCheckpoint: input.onVerifiedCheckpoint,\n });\n if (!verified) return null;\n return {\n freshlyVerified: true,\n parentId:\n input.refresh || listed.parentId === null\n ? verified.parentId\n : verified.role.parentId,\n role: verified.role,\n };\n}\n\n/**\n * A held ordinary binding was verified (or signed by this device) when it was\n * stored; a listing that repeats it needs no second proof. A listing the\n * caller already found superseded is refused.\n */\nfunction heldOrdinaryBindingStands(\n input: VerifyRemoteContainerDestinationInput,\n): boolean {\n if (input.supersededListing) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container was re-homed away from the listed organization\",\n );\n }\n return (\n !input.refresh &&\n listingRepeatsHeldOrdinaryBinding(input.heldBinding, input.remoteContainer)\n );\n}\n\n/**\n * Listing hints never establish a metadata target or a system/root role, and a\n * held folder keeps its organization and metadata target unless its own user\n * re-created it or its pinned founder authorized a verified replacement.\n * A conflicting proof is refused before placement pins\n * advance or its role is cached.\n */\nexport async function verifyRemoteContainerDestination(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<RemoteContainer | null> {\n const { remoteContainer: listed, state, isCurrent } = input;\n const runtime = state.runtime;\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: listed.id,\n objectKind: \"container\",\n operation: \"container.destination.verify\",\n organizationId: listed.organizationId,\n },\n async () => {\n if (heldOrdinaryBindingStands(input)) {\n return { ...listed, systemSlot: null };\n }\n if (input.refresh)\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n // A metadata root read before a reserved-group commit is reloaded once.\n const resolved = await resolveWithMetadataRootReload(\n input,\n resolveDestinationRole,\n () => runtime.apiClient.evictContainerWriterProjection(listed.id),\n runtime.organizations.withMetadataRootReload,\n ).catch((error: unknown) => {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error))\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n throw error;\n });\n if (!resolved || isCurrent?.() === false) return null;\n const { role, parentId } = resolved;\n // Fresh verification checked this binding before any placement pins.\n // A cached role still needs the held binding and replacement proof checked.\n if (!resolved.freshlyVerified)\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (resolved.freshlyVerified)\n rememberDestinationRole(runtime.infra.execSql, listed, role);\n assertAcknowledgedRootSigner({ listed, role, runtime });\n return {\n ...listed,\n metadataDocumentId: role.metadataDocumentId,\n parentId: parentId === undefined ? listed.parentId : parentId,\n systemSlot: role.systemSlot,\n };\n },\n );\n}\n\n/** The root the unsigned login answer named, in the expected organization. */\nexport function isSessionRootState(\n remoteRootState: ContainerState,\n state: RemoteContainerHydrationState,\n): boolean {\n const { container } = remoteRootState;\n const { auth } = state.runtime;\n return (\n container.parentId === null &&\n !container.systemSlot &&\n container.id === auth.rootContainerId &&\n container.organizationId === auth.organizationId\n );\n}\n\n/**\n * Whether the session root may absorb the pre-login local roots. The unsigned\n * login answer only names the root; the merge target must also be the verified\n * root whose epoch-1 `container.create` the session user signed. A row persisted\n * earlier as an ordinary shared container (another user's root this device once\n * hydrated) never passed that check for this session, so the creator is checked\n * here, at the reconciliation boundary itself, before any local content is\n * re-parented. The role comes only from the cache remote hydration fills when\n * it verifies the destination: this gate never fetches, so a local refresh stays\n * independent of the network. Without a cached role the merge is left pending\n * (no incident) until hydration verifies the root and reconciles from the\n * cache. A different creator is a `signer_mismatch` incident and never a merge;\n * the refusal is the \"no merge\" outcome, so the refresh that carried it\n * completes with the local content left in place.\n */\nexport async function isVerifiedLocalRootReconciliationTarget(input: {\n remoteRootState: ContainerState;\n state: RemoteContainerHydrationState;\n}): Promise<boolean> {\n const { remoteRootState, state } = input;\n const { container } = remoteRootState;\n const runtime = state.runtime;\n if (!isSessionRootState(remoteRootState, state)) return false;\n const role = cachedDestinationRole(runtime.infra.execSql, container);\n if (!role) return false;\n try {\n if (role.parentId !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"session root reconciliation target is not a verified root\",\n );\n }\n assertRootCreatedBySessionUser(role, runtime);\n return true;\n } catch (error) {\n const reported = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: container.id,\n objectKind: \"container\",\n operation: \"container.root.reconcile\",\n organizationId: container.organizationId,\n },\n );\n if (!reported) throw error;\n return false;\n }\n}\n"]}
@@ -9,7 +9,7 @@ async function finishRemoteHydration(input) {
9
9
  if (input.changedCount > 0) {
10
10
  input.host.updateSnapshot();
11
11
  let insertedCount = 0;
12
- for (const containerId of input.seenContainerIds) {
12
+ for (const containerId of input.seenContainerObservations.keys()) {
13
13
  if (!input.containerIdsBeforeHydration.has(containerId)) {
14
14
  insertedCount++;
15
15
  }
@@ -32,7 +32,7 @@ export async function hydrateRemoteContainers(input) {
32
32
  if (!canHydrateRemoteContainers(state) || input.isCurrent?.() === false) {
33
33
  return 0;
34
34
  }
35
- const seenContainerIds = new Set();
35
+ const seenContainerObservations = new Map();
36
36
  const containerIdsBeforeHydration = new Set(state.containersById.keys());
37
37
  const childIdsByParentId = createContainerChildIndex(state.containersById);
38
38
  const { lanes, queueParentLane } = createContainerParentHydrationQueue({
@@ -63,7 +63,7 @@ export async function hydrateRemoteContainers(input) {
63
63
  isCurrent: input.isCurrent,
64
64
  lanes,
65
65
  queueParentLane: queueDiscoveredParentLane,
66
- seenContainerIds,
66
+ seenContainerObservations,
67
67
  state,
68
68
  });
69
69
  const { changedCount } = result;
@@ -76,7 +76,7 @@ export async function hydrateRemoteContainers(input) {
76
76
  host,
77
77
  isCurrent: input.isCurrent,
78
78
  onFullyHydrated: input.onFullyHydrated,
79
- seenContainerIds,
79
+ seenContainerObservations,
80
80
  state,
81
81
  });
82
82
  if (input.reconnect?.isCurrent() && canHydrateRemoteContainers(state)) {
@@ -1 +1 @@
1
- {"version":3,"file":"hydrateRemoteContainers.js","sourceRoot":"","sources":["hydrateRemoteContainers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,mCAAmC,EAAE,MAAM,yBAAyB,CAAC;AAC9E,OAAO,EACL,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAQxE,KAAK,UAAU,qBAAqB,CAAC,KASpC;IACC,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QAClC,OAAO;IACT,CAAC;IACD,IAAI,KAAK,CAAC,YAAY,GAAG,CAAC,EAAE,CAAC;QAC3B,KAAK,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;QAC5B,IAAI,aAAa,GAAG,CAAC,CAAC;QACtB,KAAK,MAAM,WAAW,IAAI,KAAK,CAAC,gBAAgB,EAAE,CAAC;YACjD,IAAI,CAAC,KAAK,CAAC,2BAA2B,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;gBACxD,aAAa,EAAE,CAAC;YAClB,CAAC;QACH,CAAC;QACD,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAC1B,gCAAgC,CAAC;YAC/B,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,aAAa;SACd,CAAC,CACH,CAAC;IACJ,CAAC;IACD,IACE,KAAK,C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I,WAA8B,CAAC;IACnC,MAAM,MAAM,GAAG,MAAM,2BAA2B,CAAC;QAC/C,SAAS,EAAE,KAAK,CAAC,SAAS,IAAI;YAC5B,YAAY,EAAE,IAAI,EAAE,iBAAiB,EAAE;YACvC,iBAAiB,EAAE,CAAC,KAAK,EAAE,EAAE;gBAC3B,WAAW,KAAK,KAAK,CAAC;YACxB,CAAC;SACF;QACD,kBAAkB;QAClB,IAAI;QACJ,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,KAAK;QACL,eAAe,EAAE,yBAAyB;QAC1C,gBAAgB;QAChB,KAAK;KACN,CAAC,CAAC;IACH,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,CAAC;IAChC,MAAM,qBAAqB,CAAC;QAC1B,YAAY;QACZ,QAAQ,EACN,MAAM,CAAC,OAAO,KAAK,UAAU;YAC7B,0BAA0B,CAAC,KAAK,CAAC;YACjC,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;QAC/B,2BAA2B;QAC3B,IAAI;QACJ,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB;QAChB,KAAK;KACN,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,IAAI,0BAA0B,CAAC,KAAK,CAAC,EAAE,CAAC;QACtE,MAAM,eAAe,GAAG,KAAK,CAAC,sBAAsB;YAClD,CAAC,CAAC,WAAW;YACb,CAAC,CAAC,SAAS,CAAC;QACd,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QACxD,sFAAsF;QACtF,IAAI,eAAe;YAAE,MAAM,eAAe,CAAC;IAC7C,CAAC;IACD,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import { createContainerChildIndex } from \"./lanes/childIndex\";\nimport { createContainerParentHydrationQueue } from \"./lanes/parentLaneQueue\";\nimport {\n canHydrateRemoteContainers,\n hydrateContainerParentLanes,\n} from \"./remoteContainers/remoteContainerPageHydration\";\nimport { describeRemoteContainerHydration } from \"./remoteHydrationLog\";\nimport type {\n QueueContainerParentLane,\n ReconnectCrawl,\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n} from \"./types\";\n\nasync function finishRemoteHydration(input: {\n changedCount: number;\n complete: boolean;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n onFullyHydrated?: (() => Promise<void> | void) | undefined;\n seenContainerIds: ReadonlySet<string>;\n containerIdsBeforeHydration: ReadonlySet<string>;\n state: RemoteContainerHydrationState;\n}): Promise<void> {\n if (input.isCurrent?.() === false) {\n return;\n }\n if (input.changedCount > 0) {\n input.host.updateSnapshot();\n let insertedCount = 0;\n for (const containerId of input.seenContainerIds) {\n if (!input.containerIdsBeforeHydration.has(containerId)) {\n insertedCount++;\n }\n }\n input.state.runtime.util.log(\n describeRemoteContainerHydration({\n changedCount: input.changedCount,\n insertedCount,\n }),\n );\n }\n if (\n input.complete &&\n input.isCurrent?.() !== false &&\n input.onFullyHydrated\n ) {\n await input.onFullyHydrated();\n }\n}\n\n// Distinct correlation IDs prevent an acknowledged crawl joining an older in-flight HTTP listing.\nlet reconnectSequence = 0;\n\nexport async function hydrateRemoteContainers(input: {\n followDiscoveredParentLanes?: boolean | undefined;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n reconnect?: ReconnectCrawl | undefined;\n onFullyHydrated?: (() => Promise<void> | void) | undefined;\n parentIds?: ReadonlyArray<string | null> | undefined;\n resetAllLaneWatermarks?: boolean | undefined;\n resetRootLaneWatermark?: boolean | undefined;\n state: RemoteContainerHydrationState;\n}): Promise<number> {\n const { host, state } = input;\n if (!canHydrateRemoteContainers(state) || input.isCurrent?.() === false) {\n return 0;\n }\n\n const seenContainerIds = new Set<string>();\n const containerIdsBeforeHydration = new Set(state.containersById.keys());\n const childIdsByParentId = createContainerChildIndex(state.containersById);\n const { lanes, queueParentLane } = createContainerParentHydrationQueue({\n containerIds: state.containersById.keys(),\n parentIds: input.parentIds,\n resetAllLaneWatermarks: input.resetAllLaneWatermarks,\n resetRootLaneWatermark: input.resetRootLaneWatermark,\n });\n // Follow child lanes during an explicit recursive crawl or for containers first\n // discovered in this pass. The latter lets a newly authorized root populate its\n // descendants immediately, while routine ticks keep known subtrees cache-first.\n const queueDiscoveredParentLane: QueueContainerParentLane = (containerId) => {\n if (\n input.followDiscoveredParentLanes ||\n (containerId !== null && !containerIdsBeforeHydration.has(containerId))\n ) {\n queueParentLane(containerId);\n }\n };\n let manualError: Error | undefined;\n const result = await hydrateContainerParentLanes({\n reconnect: input.reconnect && {\n laneIdPrefix: `r${++reconnectSequence}`,\n recordManualError: (error) => {\n manualError ??= error;\n },\n },\n childIdsByParentId,\n host,\n isCurrent: input.isCurrent,\n lanes,\n queueParentLane: queueDiscoveredParentLane,\n seenContainerIds,\n state,\n });\n const { changedCount } = result;\n await finishRemoteHydration({\n changedCount,\n complete:\n result.outcome === \"complete\" &&\n canHydrateRemoteContainers(state) &&\n input.isCurrent?.() !== false,\n containerIdsBeforeHydration,\n host,\n isCurrent: input.isCurrent,\n onFullyHydrated: input.onFullyHydrated,\n seenContainerIds,\n state,\n });\n if (input.reconnect?.isCurrent() && canHydrateRemoteContainers(state)) {\n const manualRejection = input.resetAllLaneWatermarks\n ? manualError\n : undefined;\n input.reconnect.record(result.outcome, manualRejection);\n // A manual refresh sharing this crawl observes the error it would receive on its own.\n if (manualRejection) throw manualRejection;\n }\n return changedCount;\n}\n"]}
1
+ {"version":3,"file":"hydrateRemoteContainers.js","sourceRoot":"","sources":["hydrateRemoteContainers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,mCAAmC,EAAE,MAAM,yBAAyB,CAAC;AAC9E,OAAO,EACL,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,iDAAiD,CAAC;AACzD,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B,0BAA0B,CAAC,KAAK,CAAC;YACjC,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;QAC/B,2BAA2B;QAC3B,IAAI;QACJ,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,yBAAyB;QACzB,KAAK;KACN,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,IAAI,0BAA0B,CAAC,KAAK,CAAC,EAAE,CAAC;QACtE,MAAM,eAAe,GAAG,KAAK,CAAC,sBAAsB;YAClD,CAAC,CAAC,WAAW;YACb,CAAC,CAAC,SAAS,CAAC;QACd,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QACxD,sFAAsF;QACtF,IAAI,eAAe;YAAE,MAAM,eAAe,CAAC;IAC7C,CAAC;IACD,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import { createContainerChildIndex } from \"./lanes/childIndex\";\nimport { createContainerParentHydrationQueue } from \"./lanes/parentLaneQueue\";\nimport {\n canHydrateRemoteContainers,\n hydrateContainerParentLanes,\n} from \"./remoteContainers/remoteContainerPageHydration\";\nimport { describeRemoteContainerHydration } from \"./remoteHydrationLog\";\nimport type {\n QueueContainerParentLane,\n ReconnectCrawl,\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n} from \"./types\";\n\nasync function finishRemoteHydration(input: {\n changedCount: number;\n complete: boolean;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n onFullyHydrated?: (() => Promise<void> | void) | undefined;\n seenContainerObservations: ReadonlyMap<string, string>;\n containerIdsBeforeHydration: ReadonlySet<string>;\n state: RemoteContainerHydrationState;\n}): Promise<void> {\n if (input.isCurrent?.() === false) {\n return;\n }\n if (input.changedCount > 0) {\n input.host.updateSnapshot();\n let insertedCount = 0;\n for (const containerId of input.seenContainerObservations.keys()) {\n if (!input.containerIdsBeforeHydration.has(containerId)) {\n insertedCount++;\n }\n }\n input.state.runtime.util.log(\n describeRemoteContainerHydration({\n changedCount: input.changedCount,\n insertedCount,\n }),\n );\n }\n if (\n input.complete &&\n input.isCurrent?.() !== false &&\n input.onFullyHydrated\n ) {\n await input.onFullyHydrated();\n }\n}\n\n// Distinct correlation IDs prevent an acknowledged crawl joining an older in-flight HTTP listing.\nlet reconnectSequence = 0;\n\nexport async function hydrateRemoteContainers(input: {\n followDiscoveredParentLanes?: boolean | undefined;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n reconnect?: ReconnectCrawl | undefined;\n onFullyHydrated?: (() => Promise<void> | void) | undefined;\n parentIds?: ReadonlyArray<string | null> | undefined;\n resetAllLaneWatermarks?: boolean | undefined;\n resetRootLaneWatermark?: boolean | undefined;\n state: RemoteContainerHydrationState;\n}): Promise<number> {\n const { host, state } = input;\n if (!canHydrateRemoteContainers(state) || input.isCurrent?.() === false) {\n return 0;\n }\n\n const seenContainerObservations = new Map<string, string>();\n const containerIdsBeforeHydration = new Set(state.containersById.keys());\n const childIdsByParentId = createContainerChildIndex(state.containersById);\n const { lanes, queueParentLane } = createContainerParentHydrationQueue({\n containerIds: state.containersById.keys(),\n parentIds: input.parentIds,\n resetAllLaneWatermarks: input.resetAllLaneWatermarks,\n resetRootLaneWatermark: input.resetRootLaneWatermark,\n });\n // Follow child lanes during an explicit recursive crawl or for containers first\n // discovered in this pass. The latter lets a newly authorized root populate its\n // descendants immediately, while routine ticks keep known subtrees cache-first.\n const queueDiscoveredParentLane: QueueContainerParentLane = (containerId) => {\n if (\n input.followDiscoveredParentLanes ||\n (containerId !== null && !containerIdsBeforeHydration.has(containerId))\n ) {\n queueParentLane(containerId);\n }\n };\n let manualError: Error | undefined;\n const result = await hydrateContainerParentLanes({\n reconnect: input.reconnect && {\n laneIdPrefix: `r${++reconnectSequence}`,\n recordManualError: (error) => {\n manualError ??= error;\n },\n },\n childIdsByParentId,\n host,\n isCurrent: input.isCurrent,\n lanes,\n queueParentLane: queueDiscoveredParentLane,\n seenContainerObservations,\n state,\n });\n const { changedCount } = result;\n await finishRemoteHydration({\n changedCount,\n complete:\n result.outcome === \"complete\" &&\n canHydrateRemoteContainers(state) &&\n input.isCurrent?.() !== false,\n containerIdsBeforeHydration,\n host,\n isCurrent: input.isCurrent,\n onFullyHydrated: input.onFullyHydrated,\n seenContainerObservations,\n state,\n });\n if (input.reconnect?.isCurrent() && canHydrateRemoteContainers(state)) {\n const manualRejection = input.resetAllLaneWatermarks\n ? manualError\n : undefined;\n input.reconnect.record(result.outcome, manualRejection);\n // A manual refresh sharing this crawl observes the error it would receive on its own.\n if (manualRejection) throw manualRejection;\n }\n return changedCount;\n}\n"]}
@@ -0,0 +1,25 @@
1
+ import { ContainerSyncWatermarkRepository, } from "../../../../data/persistence/container-contents/containerSyncWatermarkPersistence.js";
2
+ const lane = (containerId) => ({
3
+ kind: "container_restoration",
4
+ containerId,
5
+ });
6
+ /** The same access loss can appear on later folder publications. Read all
7
+ * receipts for this page together; ordinary pages need no SQLite lookup. */
8
+ export async function pendingFolderRestorations(input) {
9
+ const candidates = input.items.filter((item) => !!item.restorationId &&
10
+ !input.isPaused?.(item) &&
11
+ !!input.childIdsByParentId.get(item.id)?.size);
12
+ if (!candidates.length)
13
+ return [];
14
+ const receipts = await new ContainerSyncWatermarkRepository(input.execSql).loadWatermarkRecords(candidates.map((item) => lane(item.id)));
15
+ return candidates.filter((item, index) => receipts[index]?.watermark.id !== item.restorationId);
16
+ }
17
+ export async function recordFolderRestoration(execSql, item, settled, stillCurrent) {
18
+ if (!item || !settled)
19
+ return settled;
20
+ return new ContainerSyncWatermarkRepository(execSql).saveWatermark(lane(item.id), {
21
+ id: item.restorationId,
22
+ updatedAt: item.updatedAt,
23
+ }, { stillCurrent });
24
+ }
25
+ //# sourceMappingURL=restorationReceipt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"restorationReceipt.js","sourceRoot":"","sources":["restorationReceip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CAAC,EACb;QACE,EAAE,EAAE,IAAI,CAAC,aAAa;QACtB,SAAS,EAAE,IAAI,CAAC,SAAS;KAC1B,EACD,EAAE,YAAY,EAAE,CACjB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerSyncWatermarkLane,\n ContainerSyncWatermarkRepository,\n} from \"../../../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport type { ExecSql } from \"../../../../data/sqlite/sqlSchema\";\nimport type {\n ContainerChildIndex,\n ListedRemoteContainerPageItem,\n} from \"../types\";\n\ntype RestoredContainer = ListedRemoteContainerPageItem & {\n restorationId: string;\n};\n\nconst lane = (containerId: string): ContainerSyncWatermarkLane => ({\n kind: \"container_restoration\",\n containerId,\n});\n\n/** The same access loss can appear on later folder publications. Read all\n * receipts for this page together; ordinary pages need no SQLite lookup. */\nexport async function pendingFolderRestorations(input: {\n childIdsByParentId: ContainerChildIndex;\n execSql: ExecSql;\n isPaused?: ((item: ListedRemoteContainerPageItem) => boolean) | undefined;\n items: ReadonlyArray<ListedRemoteContainerPageItem>;\n}): Promise<RestoredContainer[]> {\n const candidates = input.items.filter(\n (item): item is RestoredContainer =>\n !!item.restorationId &&\n !input.isPaused?.(item) &&\n !!input.childIdsByParentId.get(item.id)?.size,\n );\n if (!candidates.length) return [];\n const receipts = await new ContainerSyncWatermarkRepository(\n input.execSql,\n ).loadWatermarkRecords(candidates.map((item) => lane(item.id)));\n return candidates.filter(\n (item, index) => receipts[index]?.watermark.id !== item.restorationId,\n );\n}\n\nexport async function recordFolderRestoration(\n execSql: ExecSql,\n item: RestoredContainer | undefined,\n settled: boolean,\n stillCurrent: () => boolean,\n) {\n if (!item || !settled) return settled;\n return new ContainerSyncWatermarkRepository(execSql).saveWatermark(\n lane(item.id),\n {\n id: item.restorationId,\n updatedAt: item.updatedAt,\n },\n { stillCurrent },\n );\n}\n"]}
@@ -0,0 +1,107 @@
1
+ import { MAX_CONTAINER_DOCUMENT_LANES, } from "../../../../internal/validators/request/index.js";
2
+ import { isContainerNotFoundFailure } from "../../../../data/containers/shared/mutationFailures.js";
3
+ import { captureRemovalPlacementHeads } from "../../../../data/persistence/container-contents/containerRemovalPlacements.js";
4
+ import { isPublicationWatermark } from "../../documentDiscovery/publicationWatermark.js";
5
+ import { collectRemovedContainers } from "../tombstoneReasons.js";
6
+ function classifyLane(result) {
7
+ if (!result)
8
+ return "unknown";
9
+ if ("page" in result)
10
+ return "readable";
11
+ return result.failure.status === 403 ||
12
+ isContainerNotFoundFailure(result.failure)
13
+ ? "denied"
14
+ : "unknown";
15
+ }
16
+ /** A successful lane read proves the device should retain its existing row.
17
+ * A lane-local access denial or coded absence confirms a discovery removal.
18
+ * Any other outcome leaves the page retryable. */
19
+ async function readTombstoneCascadeAccess(api, containerIds, afterParentPage, isCurrent) {
20
+ const denied = new Set();
21
+ for (let index = 0; index < containerIds.length; index += MAX_CONTAINER_DOCUMENT_LANES) {
22
+ if (isCurrent?.() === false)
23
+ return null;
24
+ const ids = containerIds.slice(index, index + MAX_CONTAINER_DOCUMENT_LANES);
25
+ const response = await api.listContainerDocumentLanes({
26
+ afterParentPage,
27
+ lanes: ids.map((containerId, i) => ({
28
+ containerId,
29
+ laneId: String(i),
30
+ watermark: null,
31
+ limit: 1,
32
+ })),
33
+ }, { reportErrors: false });
34
+ if (!response || response.results.length !== ids.length)
35
+ return null;
36
+ for (const [i, containerId] of ids.entries()) {
37
+ const result = response.results.find((row) => row.laneId === String(i));
38
+ const outcome = classifyLane(result);
39
+ if (outcome === "unknown")
40
+ return null;
41
+ if (outcome === "denied")
42
+ denied.add(containerId);
43
+ }
44
+ }
45
+ return { denied };
46
+ }
47
+ export async function resolveTombstoneCascade(input) {
48
+ const cascade = (preservedContainerIds) => collectRemovedContainers({
49
+ childIdsByParentId: input.childIdsByParentId,
50
+ containersById: input.state.containersById,
51
+ preservedContainerIds,
52
+ tombstones: [input.tombstone],
53
+ });
54
+ const candidates = cascade(input.preservedContainerIds);
55
+ const clockConflict = candidates.removedContainerIds.some((id) => {
56
+ const held = input.expectedContainerStates.get(id)?.container.serverUpdatedAt;
57
+ return held != null && held > input.tombstone.updatedAt;
58
+ });
59
+ // A directly shared or moved child may be behind the saved parent cursor
60
+ // regardless of its entity clock. Check every cached child before an
61
+ // ancestor removal from a server that can fence that permission read.
62
+ const hasCachedDescendants = isPublicationWatermark(input.afterParentPage?.watermark) &&
63
+ candidates.removedContainerIds.some((id) => id !== input.tombstone.containerId);
64
+ if (!input.reconcileDescendants && !clockConflict && !hasCachedDescendants)
65
+ return { cascade: candidates, denied: null };
66
+ if (!input.afterParentPage)
67
+ return null;
68
+ const ids = [
69
+ ...new Set([
70
+ input.tombstone.containerId,
71
+ ...candidates.removedContainerIds,
72
+ ]),
73
+ ];
74
+ const placements = await captureRemovalPlacementHeads(input.state.runtime.infra.execSql, ids.flatMap((id) => {
75
+ const held = input.expectedContainerStates.get(id);
76
+ return held ? [held.container] : [];
77
+ }));
78
+ const access = await readTombstoneCascadeAccess(input.state.runtime.apiClient, ids, input.afterParentPage, input.isCurrent);
79
+ // A move before the server upgrade may have left a superseded removal in
80
+ // its old lane. Preserve a currently readable root and advance past it.
81
+ if (!access) {
82
+ if (input.isCurrent?.() !== false) {
83
+ // The request boundary reports a lagging replica as an unavailable
84
+ // response. Resume this exact lane on the next scheduled refresh.
85
+ input.state.containerListingFailures =
86
+ (input.state.containerListingFailures ?? 0) + 1;
87
+ input.state.containerParentIdsNeedingHydration?.add(input.afterParentPage.parentId);
88
+ }
89
+ return null;
90
+ }
91
+ // A restored row only asks to reconcile its descendants. A newer loss of
92
+ // the root itself has its own publication.
93
+ if (input.reconcileDescendants)
94
+ access.denied.delete(input.tombstone.containerId);
95
+ return {
96
+ // A cached descendant may have moved away from a still-readable ancestor.
97
+ // The batch checked every candidate independently.
98
+ cascade: {
99
+ ...candidates,
100
+ removedContainerIds: candidates.removedContainerIds.filter((id) => access.denied.has(id)),
101
+ fenceOnlyContainerIds: candidates.fenceOnlyContainerIds.filter((id) => access.denied.has(id)),
102
+ absentDeletedContainerIds: candidates.absentDeletedContainerIds.filter((id) => access.denied.has(id)),
103
+ },
104
+ denied: new Map([...access.denied].map((id) => [id, placements.get(id) ?? null])),
105
+ };
106
+ }
107
+ //# sourceMappingURL=tombstoneAccess.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tombstoneAccess.js","sourceRoot":"","sources":["tombstoneAccess.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,4BAA4B,GAC7B,MAAM,+BAA+B,CAAC;AAKvC,OAAO,EAAE,0BAA0B,EAAE,MAAM,qDAAqD,CAAC;AACjG,OAAO,EAAE,4BAA4B,EAAE,MAAM,4EAA4E,CAAC;AAC1H,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAO/D,SAAS,YAAY,CACnB,MAAyE;IAEzE,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;IAC9B,IAAI,MAAM,IAAI,MAAM;QAAE,OAAO,UAAU,CAAC;IACxC,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,KAAK,GAAG;QAClC,0BAA0B,CAAC,MAAM,CAAC,OAAO,CAAC;QAC1C,CAAC,CAAC,QAAQ;QACV,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC;AAED;;kDAEkD;AAClD,KAAK,UAAU,0BAA0B,CACvC,GAA0D,EAC1D,YAA+B,EAC/B,eAEC,EACD,SAAuC;IAEvC,MAAM,MAAM,GAAG,IAAI,GAAG,EAAU,CAAC;IACjC,KACE,IAAI,KAAK,GAAG,CAAC,EACb,KAAK,GAAG,YAAY,CAAC,MAAM,EAC3B,KAAK,IAAI,4BAA4B,EACrC,CAAC;QACD,IAAI,SAAS,EAAE,EAAE,KAAK,KAAK;YAAE,OAAO,IAAI,CAAC;QACzC,MAAM,GAAG,GAAG,YAAY,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,4BAA4B,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AU,CAAC,yBAAyB,CAAC,MAAM,CACpE,CAAC,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAC9B;SACF;QACD,MAAM,EAAE,IAAI,GAAG,CACb,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC,CACjE;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ListContainerDocumentLanesRequest,\n MAX_CONTAINER_DOCUMENT_LANES,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerSyncTombstone,\n ListContainerDocumentLanesResponse,\n} from \"@tearleads/validators/response\";\nimport { isContainerNotFoundFailure } from \"../../../../data/containers/shared/mutationFailures\";\nimport { captureRemovalPlacementHeads } from \"../../../../data/persistence/container-contents/containerRemovalPlacements\";\nimport { isPublicationWatermark } from \"../../documentDiscovery/publicationWatermark\";\nimport { collectRemovedContainers } from \"../tombstoneReasons\";\nimport type {\n ContainerChildIndex,\n ExpectedContainerState,\n RemoteContainerHydrationState,\n} from \"../types\";\n\nfunction classifyLane(\n result: ListContainerDocumentLanesResponse[\"results\"][number] | undefined,\n) {\n if (!result) return \"unknown\";\n if (\"page\" in result) return \"readable\";\n return result.failure.status === 403 ||\n isContainerNotFoundFailure(result.failure)\n ? \"denied\"\n : \"unknown\";\n}\n\n/** A successful lane read proves the device should retain its existing row.\n * A lane-local access denial or coded absence confirms a discovery removal.\n * Any other outcome leaves the page retryable. */\nasync function readTombstoneCascadeAccess(\n api: RemoteContainerHydrationState[\"runtime\"][\"apiClient\"],\n containerIds: readonly string[],\n afterParentPage: NonNullable<\n ListContainerDocumentLanesRequest[\"afterParentPage\"]\n >,\n isCurrent?: (() => boolean) | undefined,\n) {\n const denied = new Set<string>();\n for (\n let index = 0;\n index < containerIds.length;\n index += MAX_CONTAINER_DOCUMENT_LANES\n ) {\n if (isCurrent?.() === false) return null;\n const ids = containerIds.slice(index, index + MAX_CONTAINER_DOCUMENT_LANES);\n const response = await api.listContainerDocumentLanes(\n {\n afterParentPage,\n lanes: ids.map((containerId, i) => ({\n containerId,\n laneId: String(i),\n watermark: null,\n limit: 1,\n })),\n },\n { reportErrors: false },\n );\n if (!response || response.results.length !== ids.length) return null;\n for (const [i, containerId] of ids.entries()) {\n const result = response.results.find((row) => row.laneId === String(i));\n const outcome = classifyLane(result);\n if (outcome === \"unknown\") return null;\n if (outcome === \"denied\") denied.add(containerId);\n }\n }\n return { denied };\n}\n\nexport async function resolveTombstoneCascade(input: {\n reconcileDescendants: boolean;\n afterParentPage: ListContainerDocumentLanesRequest[\"afterParentPage\"];\n childIdsByParentId: ContainerChildIndex;\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n isCurrent?: (() => boolean) | undefined;\n preservedContainerIds: ReadonlySet<string>;\n state: RemoteContainerHydrationState;\n tombstone: ContainerSyncTombstone;\n}): Promise<{\n cascade: ReturnType<typeof collectRemovedContainers>;\n denied: ReadonlyMap<string, string | null> | null;\n} | null> {\n const cascade = (preservedContainerIds: ReadonlySet<string>) =>\n collectRemovedContainers({\n childIdsByParentId: input.childIdsByParentId,\n containersById: input.state.containersById,\n preservedContainerIds,\n tombstones: [input.tombstone],\n });\n const candidates = cascade(input.preservedContainerIds);\n const clockConflict = candidates.removedContainerIds.some((id) => {\n const held =\n input.expectedContainerStates.get(id)?.container.serverUpdatedAt;\n return held != null && held > input.tombstone.updatedAt;\n });\n // A directly shared or moved child may be behind the saved parent cursor\n // regardless of its entity clock. Check every cached child before an\n // ancestor removal from a server that can fence that permission read.\n const hasCachedDescendants =\n isPublicationWatermark(input.afterParentPage?.watermark) &&\n candidates.removedContainerIds.some(\n (id) => id !== input.tombstone.containerId,\n );\n if (!input.reconcileDescendants && !clockConflict && !hasCachedDescendants)\n return { cascade: candidates, denied: null };\n\n if (!input.afterParentPage) return null;\n const ids = [\n ...new Set([\n input.tombstone.containerId,\n ...candidates.removedContainerIds,\n ]),\n ];\n const placements = await captureRemovalPlacementHeads(\n input.state.runtime.infra.execSql,\n ids.flatMap((id) => {\n const held = input.expectedContainerStates.get(id);\n return held ? [held.container] : [];\n }),\n );\n const access = await readTombstoneCascadeAccess(\n input.state.runtime.apiClient,\n ids,\n input.afterParentPage,\n input.isCurrent,\n );\n // A move before the server upgrade may have left a superseded removal in\n // its old lane. Preserve a currently readable root and advance past it.\n if (!access) {\n if (input.isCurrent?.() !== false) {\n // The request boundary reports a lagging replica as an unavailable\n // response. Resume this exact lane on the next scheduled refresh.\n input.state.containerListingFailures =\n (input.state.containerListingFailures ?? 0) + 1;\n input.state.containerParentIdsNeedingHydration?.add(\n input.afterParentPage.parentId,\n );\n }\n return null;\n }\n // A restored row only asks to reconcile its descendants. A newer loss of\n // the root itself has its own publication.\n if (input.reconcileDescendants)\n access.denied.delete(input.tombstone.containerId);\n return {\n // A cached descendant may have moved away from a still-readable ancestor.\n // The batch checked every candidate independently.\n cascade: {\n ...candidates,\n removedContainerIds: candidates.removedContainerIds.filter((id) =>\n access.denied.has(id),\n ),\n fenceOnlyContainerIds: candidates.fenceOnlyContainerIds.filter((id) =>\n access.denied.has(id),\n ),\n absentDeletedContainerIds: candidates.absentDeletedContainerIds.filter(\n (id) => access.denied.has(id),\n ),\n },\n denied: new Map(\n [...access.denied].map((id) => [id, placements.get(id) ?? null]),\n ),\n };\n}\n"]}