@tearleads/client-sdk 0.1.76 → 0.1.78
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/{documents/blob/shared → blobs/attachments}/blobEnvelopeStream.js +1 -1
- package/data/{documents/blob/shared → blobs/attachments}/blobEnvelopeStream.js.map +1 -1
- package/data/blobs/attachments/blobRecordCrypto.d.ts +26 -0
- package/data/{documents/blob/shared → blobs/attachments}/blobRecordCrypto.js +2 -2
- package/data/{documents/blob/shared → blobs/attachments}/blobSourceSnapshot.d.ts +1 -1
- package/data/{documents/blob/shared → blobs/attachments}/blobSourceSnapshot.js +2 -2
- package/data/blobs/attachments/blobSourceSnapshot.js.map +1 -0
- package/data/blobs/attachments/chunkedBlobCrypto.d.ts +17 -0
- package/data/{documents/blob/shared → blobs/attachments}/chunkedBlobCrypto.js +3 -3
- package/data/blobs/attachments/chunkedBlobCrypto.js.map +1 -0
- package/data/blobs/attachments/crypto.d.ts +3 -0
- package/data/blobs/attachments/encryptedUploadParts.js.map +1 -0
- package/data/{documents/blob/shared → blobs/attachments}/events.js +3 -3
- package/data/blobs/attachments/events.js.map +1 -0
- package/data/{documents/blob/shared → blobs/attachments}/projection.js +8 -8
- package/data/blobs/attachments/projection.js.map +1 -0
- package/data/{documents/blob/shared → blobs/attachments}/readers.js +3 -3
- package/data/blobs/attachments/readers.js.map +1 -0
- package/data/{documents/blob/shared → blobs/attachments}/responses.js +2 -2
- package/data/blobs/attachments/responses.js.map +1 -0
- package/data/{documents/blob/shared → blobs/attachments}/types.d.ts +8 -8
- package/data/blobs/attachments/types.js.map +1 -0
- package/data/{containers → persistence/container-contents}/containerBinding.js +1 -1
- package/data/persistence/container-contents/containerContentsPersistence.js +2 -2
- package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -2
- package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
- package/data/persistence/container-contents/containerDeletionPersistence.js +2 -2
- package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerHydrationPersistence.js +2 -2
- package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js +2 -2
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataRows.js +1 -1
- package/data/persistence/container-contents/containerMetadataRows.js.map +1 -1
- package/data/persistence/container-contents/containerRebindPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerReconcilePersistence.js +2 -2
- package/data/persistence/container-contents/containerReconcilePersistence.js.map +1 -1
- package/data/persistence/container-contents/containerStructuralRepair.js +1 -1
- package/data/persistence/container-contents/containerStructuralRepair.js.map +1 -1
- package/data/persistence/container-contents/dormantMetadataSweep.js +1 -1
- package/data/persistence/container-contents/dormantMetadataSweep.js.map +1 -1
- package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +1 -1
- package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js.map +1 -1
- package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
- package/data/persistence/documents/internal/containerDocumentTombstones.js.map +1 -1
- package/data/persistence/documents/internal/discoveredDocumentPlacement.js +1 -1
- package/data/persistence/documents/internal/discoveredDocumentPlacement.js.map +1 -1
- package/package.json +1 -1
- package/stores/container-contents/systemContainers/systemContainerIcon.js +1 -1
- package/stores/container-contents/systemContainers/systemContainerIcon.js.map +1 -1
- package/stores/documents/documentStore/attachmentUpload/attachmentSourceUpload.js +1 -2
- package/stores/documents/documentStore/attachmentUpload/attachmentSourceUpload.js.map +1 -1
- package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
- package/workflows/blobs/detach.js +2 -2
- package/workflows/blobs/detach.js.map +1 -1
- package/workflows/blobs/hydration/blobChunkDecryption.js +1 -1
- package/workflows/blobs/hydration/blobChunkDecryption.js.map +1 -1
- package/workflows/blobs/hydration/decrypt.d.ts +1 -1
- package/workflows/blobs/hydration/decrypt.js +4 -4
- package/workflows/blobs/hydration/decrypt.js.map +1 -1
- package/workflows/blobs/index.d.ts +3 -1
- package/workflows/blobs/index.js +3 -0
- package/workflows/blobs/index.js.map +1 -1
- package/workflows/blobs/upload/automaticMultipartUpload.js +1 -1
- package/workflows/blobs/upload/automaticMultipartUpload.js.map +1 -1
- package/workflows/blobs/upload/index.d.ts +2 -2
- package/workflows/blobs/upload/index.js +4 -4
- package/workflows/blobs/upload/index.js.map +1 -1
- package/workflows/blobs/upload/multipartFirstParts.js.map +1 -1
- package/workflows/blobs/upload/multipartStageFailures.js.map +1 -1
- package/workflows/blobs/upload/multipartStageResolution.js.map +1 -1
- package/workflows/blobs/upload/multipartUpload.js.map +1 -1
- package/workflows/blobs/verification/attachmentBindingVerification.js.map +1 -1
- package/workflows/blobs/verification/attachmentKeyAuthenticator.js +1 -1
- package/workflows/blobs/verification/attachmentKeyAuthenticator.js.map +1 -1
- package/workflows/blobs/verification/retainedAttachmentVerification.js +1 -1
- package/workflows/blobs/verification/retainedAttachmentVerification.js.map +1 -1
- package/workflows/blobs/verification/writerProjection.js +1 -1
- package/workflows/blobs/verification/writerProjection.js.map +1 -1
- package/workflows/container-contents/container-state/create/createChild.js +1 -1
- package/workflows/container-contents/container-state/create/createChild.js.map +1 -1
- package/workflows/container-contents/container-state/purge/purgeTree.js +1 -1
- package/workflows/container-contents/container-state/purge/purgeTree.js.map +1 -1
- package/workflows/container-contents/container-state/types.js.map +1 -1
- package/workflows/container-contents/containerPersistence.d.ts +3 -3
- package/workflows/container-contents/containerPersistence.js +1 -1
- package/workflows/container-contents/containerPersistence.js.map +1 -1
- package/workflows/container-contents/documentLinks/documentLinkIntent.js +1 -1
- package/workflows/container-contents/documentLinks/documentLinkIntent.js.map +1 -1
- package/workflows/container-contents/documentLinks/index.js +1 -1
- package/workflows/container-contents/documentLinks/index.js.map +1 -1
- package/workflows/container-contents/documentMove/documentMoveIntent.js +1 -1
- package/workflows/container-contents/documentMove/documentMoveIntent.js.map +1 -1
- package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js +2 -2
- package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js.map +1 -1
- package/workflows/container-contents/documentQueries/documentSubtreeQueries.js +1 -1
- package/workflows/container-contents/documentQueries/documentSubtreeQueries.js.map +1 -1
- package/workflows/container-contents/documentQueries/index.js +3 -3
- package/workflows/container-contents/documentQueries/index.js.map +1 -1
- package/workflows/container-contents/documentQueries/pendingDownloads.js +1 -1
- package/workflows/container-contents/documentQueries/pendingDownloads.js.map +1 -1
- package/workflows/container-contents/index.d.ts +1 -1
- package/workflows/container-contents/index.js +1 -1
- package/workflows/container-contents/index.js.map +1 -1
- package/workflows/container-contents/info/blobInfo.js +1 -1
- package/workflows/container-contents/info/blobInfo.js.map +1 -1
- package/workflows/container-contents/info/containerInfo.js +2 -2
- package/workflows/container-contents/info/containerInfo.js.map +1 -1
- package/{data/containers → workflows/container-contents/metadata}/containerMetadataDocument.d.ts +1 -1
- package/{data/containers → workflows/container-contents/metadata}/containerMetadataDocument.js +2 -2
- package/workflows/container-contents/metadata/containerMetadataDocument.js.map +1 -0
- package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
- package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
- package/workflows/container-contents/metadata/metadataPersistence.js +1 -1
- package/workflows/container-contents/metadata/metadataPersistence.js.map +1 -1
- package/workflows/container-contents/metadata/metadataRecord.js.map +1 -1
- package/workflows/container-contents/metadata/metadataStateIsolation.js +1 -1
- package/workflows/container-contents/metadata/metadataStateIsolation.js.map +1 -1
- package/workflows/container-contents/metadata/metadataSyncSettlement.js +1 -1
- package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
- package/workflows/container-contents/metadata/metadataTypes.d.ts +2 -2
- package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
- package/workflows/container-contents/recovery/folderRecovery.js +1 -1
- package/workflows/container-contents/recovery/folderRecovery.js.map +1 -1
- package/workflows/container-contents/remoteHydration/destination/replacementBinding.js +1 -1
- package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -1
- package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +1 -1
- package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
- package/workflows/container-contents/remoteHydration/heldContainerRebind.js +1 -1
- package/workflows/container-contents/remoteHydration/heldContainerRebind.js.map +1 -1
- package/workflows/container-contents/remoteHydration/reattachMetadata.js +1 -1
- package/workflows/container-contents/remoteHydration/reattachMetadata.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/insertRemoteContainer.js +2 -2
- package/workflows/container-contents/remoteHydration/remoteContainers/insertRemoteContainer.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/container-contents/storedContainerState.js +1 -1
- package/workflows/container-contents/storedContainerState.js.map +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
- package/workflows/organizations/readModel/localReadModelDetails.js +1 -1
- package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
- package/workflows/registration/bootstrapRootContainer.js +1 -1
- package/workflows/registration/bootstrapRootContainer.js.map +1 -1
- package/workflows/registration/provisioningBootstrapBuilders.js +1 -1
- package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
- package/workflows/registration/rootMetadataBootstrap.js +1 -1
- package/workflows/registration/rootMetadataBootstrap.js.map +1 -1
- package/workflows/sync/remoteReset.js +1 -1
- package/workflows/sync/remoteReset.js.map +1 -1
- package/data/containers/containerMetadataDocument.js.map +0 -1
- package/data/documents/blob/shared/blobSourceSnapshot.js.map +0 -1
- package/data/documents/blob/shared/chunkedBlobCrypto.js.map +0 -1
- package/data/documents/blob/shared/encryptedUploadParts.js.map +0 -1
- package/data/documents/blob/shared/events.js.map +0 -1
- package/data/documents/blob/shared/projection.js.map +0 -1
- package/data/documents/blob/shared/readers.js.map +0 -1
- package/data/documents/blob/shared/responses.js.map +0 -1
- package/data/documents/blob/shared/types.js.map +0 -1
- /package/data/{documents/blob/shared → blobs/attachments}/blobRecordCrypto.js.map +0 -0
- /package/data/{documents/blob/shared → blobs/attachments}/crypto.js +0 -0
- /package/data/{documents/blob/shared → blobs/attachments}/crypto.js.map +0 -0
- /package/data/{documents/blob/shared → blobs/attachments}/encryptedUploadParts.js +0 -0
- /package/data/{documents/blob/shared → blobs/attachments}/types.js +0 -0
- /package/data/{containers → persistence/container-contents}/containerBinding.d.ts +0 -0
- /package/data/{containers → persistence/container-contents}/containerBinding.js.map +0 -0
- /package/data/persistence/{containers → container-contents}/containerPersistence.d.ts +0 -0
- /package/data/persistence/{containers → container-contents}/containerPersistence.js +0 -0
- /package/data/persistence/{containers → container-contents}/containerPersistence.js.map +0 -0
- /package/data/persistence/{containers → container-contents}/containerSyncWatermarkPersistence.d.ts +0 -0
- /package/data/persistence/{containers → container-contents}/containerSyncWatermarkPersistence.js +0 -0
- /package/data/persistence/{containers → container-contents}/containerSyncWatermarkPersistence.js.map +0 -0
- /package/data/persistence/{containers → container-contents}/documentContainerProjectionPersistence.js +0 -0
- /package/data/persistence/{containers → container-contents}/documentContainerProjectionPersistence.js.map +0 -0
- /package/data/persistence/{containers → container-contents}/documentPlacement.js +0 -0
- /package/data/persistence/{containers → container-contents}/documentPlacement.js.map +0 -0
package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remoteContainerState.js","sourceRoot":"","sources":["remoteContainerState.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oBAAoB,EACpB,iCAAiC,GAClC,MAAM,8CAA8C,CAAC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KAAK,CAAC,0BAA0B,IAAI,IAAI;YACpE,2BAA2B;YAC3B,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,KAAK,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC,CAAC;AACT,CAAC","sourcesContent":["import type { AccessManifestCheckpoint } from \"@tearleads/crypto\";\nimport {\n heldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../../data/containers/containerBinding\";\nimport {\n isKeyingVerificationError,\n runWithSecurityIncidentReporting,\n} from \"../../../../data/keyingProjectionVerification/error\";\nimport { isProjectionVerificationCancelledError } from \"../../../../data/keyingProjectionVerification/types\";\nimport type { ContainerHydrationTombstone } from \"../../containerPersistence\";\nimport { installContainerMetadataRecord } from \"../../metadata/metadataPersistence\";\nimport { projectionGeneration } from \"../../projectionGeneration\";\nimport type { PrefetchedDestinationProjection } from \"../destination/destinationPrefetch\";\nimport { verifyRemoteContainerDestination } from \"../destination/verifiedDestination\";\nimport { rebindReHomedContainer } from \"../heldContainerRebind\";\nimport {\n moveIndexedContainerChild,\n removeIndexedContainerChild,\n} from \"../lanes/childIndex\";\nimport {\n reconcileLocalOnlyRootContainers,\n reconcileLocalOnlySystemContainers,\n} from \"../reconciliation\";\nimport type {\n ContainerChildIndex,\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n} from \"../types\";\nimport { insertRemoteContainerState } from \"./insertRemoteContainer\";\nimport {\n applyRemoteContainerTimestamps,\n remoteContainerHydrationSaveOptions,\n resolveRemoteContainerHydrationLocalUpdatedAt,\n} from \"./remoteContainerTimestamps\";\n\n// Container ids (restricted to the inbound page) that carry an unsynced local\n// create or move intent. Such a container's parent and local-edit timestamp are\n// owned by its structural-intent lane until that lane reconciles, so inbound\n// hydration must not revert parentId to the server value nor collapse\n// localUpdatedAt — doing so silently undoes a queued move and falsely reads\n// \"synced\". Move intents are read via listUnsyncedMoveIntents so a blocked\n// move — one whose destination parent has not synced yet, the common boot-time\n// case — is protected too. Pending *metadata*\n// updates are handled separately (listRemoteContainerIdsWithPendingMetadataUpdates);\n// structural intents live in the local outbox's container lanes, which that\n// query does not cover.\nexport async function listRemoteContainerIdsWithPendingStructuralIntents(input: {\n remoteContainers: ReadonlyArray<RemoteContainer>;\n state: RemoteContainerHydrationState;\n}): Promise<Set<string>> {\n if (input.remoteContainers.length === 0) {\n return new Set();\n }\n const remoteContainerIds = new Set(\n input.remoteContainers.map((remoteContainer) => remoteContainer.id),\n );\n\n const execSql = input.state.runtime.infra.execSql;\n const [pendingCreateIntents, unsyncedMoveIntents] = await Promise.all([\n input.state.persistence.listPendingCreateIntents(execSql),\n input.state.persistence.listUnsyncedMoveIntents(execSql),\n ]);\n const containerIdsWithPendingStructuralIntents = new Set<string>();\n for (const intent of pendingCreateIntents) {\n if (remoteContainerIds.has(intent.containerId)) {\n containerIdsWithPendingStructuralIntents.add(intent.containerId);\n }\n }\n for (const intent of unsyncedMoveIntents) {\n if (remoteContainerIds.has(intent.containerId)) {\n containerIdsWithPendingStructuralIntents.add(intent.containerId);\n }\n }\n return containerIdsWithPendingStructuralIntents;\n}\n\nexport async function listRemoteContainerIdsWithPendingMetadataUpdates(input: {\n remoteContainers: ReadonlyArray<RemoteContainer>;\n state: RemoteContainerHydrationState;\n}): Promise<Set<string>> {\n const containerIds = input.remoteContainers.flatMap((remoteContainer) => {\n const previousLocalUpdatedAt = input.state.containersById.get(\n remoteContainer.id,\n )?.container.localUpdatedAt;\n\n return previousLocalUpdatedAt &&\n previousLocalUpdatedAt.localeCompare(remoteContainer.updatedAt) > 0\n ? [remoteContainer.id]\n : [];\n });\n if (containerIds.length === 0) {\n return new Set();\n }\n\n const execSql = input.state.runtime.infra.execSql;\n return new Set(\n await input.state.persistence.listContainerIdsWithPendingUpdates(\n execSql,\n containerIds,\n ),\n );\n}\n\nfunction removeMissingHydratedContainer(input: {\n childIdsByParentId?: ContainerChildIndex | undefined;\n existingState: ContainerState;\n host: RemoteContainerHydrationHost;\n previousParentId: string | null;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): void {\n const { existingState, remoteContainer, state } = input;\n if (state.containersById.get(remoteContainer.id) !== existingState) {\n return;\n }\n\n state.containersById.delete(remoteContainer.id);\n if (input.childIdsByParentId) {\n removeIndexedContainerChild(\n input.childIdsByParentId,\n remoteContainer.id,\n input.previousParentId,\n );\n input.childIdsByParentId.delete(remoteContainer.id);\n }\n input.host.updateSnapshot();\n}\n\nfunction createUpdatedRemoteContainerState(\n existingState: ContainerState,\n remoteContainer: RemoteContainer,\n): ContainerState {\n return {\n ...existingState,\n container: applyRemoteContainerTimestamps(\n existingState.container,\n remoteContainer,\n ),\n containerWriterProjection: null,\n metadataReferencedPrincipals: remoteContainer.metadataReferencedPrincipals,\n };\n}\n\nfunction installUpdatedRemoteContainerState(\n existingState: ContainerState,\n nextState: ContainerState,\n host: RemoteContainerHydrationHost,\n): void {\n const wasLocalOnly = existingState.container.serverCreatedAt == null;\n existingState.container = nextState.container;\n existingState.containerWriterProjection = nextState.containerWriterProjection;\n existingState.metadataReferencedPrincipals =\n nextState.metadataReferencedPrincipals;\n // The snapshot copied the live generation when it was taken; a hint that\n // landed during the persist leaves the live metadata projection dropped.\n if (projectionGeneration(existingState) === projectionGeneration(nextState))\n existingState.metadataWriterProjection = nextState.metadataWriterProjection;\n installContainerMetadataRecord(existingState, nextState.record);\n // A document pass may have deferred while this root was awaiting proof.\n // The first durable remote acknowledgement makes its pending creates runnable.\n if (wasLocalOnly && existingState.container.serverCreatedAt != null)\n host.requestDocumentPriming?.();\n}\n\nasync function updateExistingRemoteContainerState(input: {\n childIdsByParentId?: ContainerChildIndex | undefined;\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n existingState: ContainerState;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): Promise<ContainerState | null> {\n const { childIdsByParentId, existingState, host, remoteContainer, state } =\n input;\n const previousParentId = existingState.container.parentId;\n const previousLocalUpdatedAt = existingState.container.localUpdatedAt;\n // A queued, not-yet-synced local move/create owns this container's parent\n // until its intent lane reconciles. Omit the remote parent when the page scan\n // saw one; persistence also rechecks the intent transactionally so a move\n // created after that scan wins. Both paths preserve the durable local clock.\n const hasPendingStructuralIntent =\n input.containerIdsWithPendingStructuralIntents.has(remoteContainer.id);\n const nextParentId = hasPendingStructuralIntent\n ? undefined\n : remoteContainer.parentId;\n const localUpdatedAt = resolveRemoteContainerHydrationLocalUpdatedAt({\n containerIdsWithPendingMetadataUpdates:\n input.containerIdsWithPendingMetadataUpdates,\n hasPendingStructuralIntent,\n previousLocalUpdatedAt,\n remoteContainer,\n });\n const nextState = createUpdatedRemoteContainerState(\n existingState,\n remoteContainer,\n );\n const persistenceResult = await host.persistContainerState(\n nextState,\n {\n accessEpoch: remoteContainer.metadataAccessEpoch,\n accessStateHash: remoteContainer.metadataAccessStateHash,\n documentId: remoteContainer.metadataDocumentId,\n effectiveAccessLevel: remoteContainer.effectiveAccessLevel,\n metadataDocumentId: remoteContainer.metadataDocumentId,\n systemSlot: remoteContainer.systemSlot ?? null,\n organizationId: remoteContainer.organizationId,\n ...(nextParentId !== undefined ? { parentId: nextParentId } : {}),\n },\n false,\n remoteContainerHydrationSaveOptions({\n localUpdatedAt,\n remoteContainer,\n }),\n {\n preserveDurableStructureWhenPending: true,\n },\n );\n if (persistenceResult.status === \"missing\") {\n // Hydration persists a detached candidate so an in-flight response cannot\n // mutate mapped state before its guards settle. Retire the exact state this\n // hydration read because store-level reference cleanup cannot see the clone.\n removeMissingHydratedContainer({\n childIdsByParentId,\n existingState,\n host,\n previousParentId,\n remoteContainer,\n state,\n });\n return null;\n }\n if (persistenceResult.status !== \"persisted\") return null;\n const { record: nextRecord } = persistenceResult;\n installContainerMetadataRecord(nextState, nextRecord);\n if (input.isCurrent?.() === false) {\n return existingState;\n }\n nextState.container = {\n ...nextState.container,\n metadataDocumentId: remoteContainer.metadataDocumentId,\n organizationId: remoteContainer.organizationId,\n parentId: nextState.container.parentId,\n };\n\n installUpdatedRemoteContainerState(existingState, nextState, host);\n moveIndexedContainerChild(\n childIdsByParentId,\n remoteContainer.id,\n previousParentId,\n existingState.container.parentId,\n );\n await reconcileLocalOnlyRootContainers({\n childIdsByParentId,\n isCurrent: input.isCurrent,\n remoteRootState: existingState,\n requestDocumentPriming: host.requestDocumentPriming,\n state,\n });\n return existingState;\n}\n\ninterface UpsertRemoteContainerStateInput {\n childIdsByParentId?: ContainerChildIndex | undefined;\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n host: RemoteContainerHydrationHost;\n expectedHydrationTombstone?: ContainerHydrationTombstone | null | undefined;\n isCurrent?: (() => boolean) | undefined;\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}\n\nexport async function upsertRemoteContainerState(\n input: UpsertRemoteContainerStateInput,\n): Promise<ContainerState | null> {\n let expectedPlacementCheckpoint: AccessManifestCheckpoint | undefined;\n const heldState = input.state.containersById.get(input.remoteContainer.id);\n const heldBinding = heldState\n ? heldContainerBinding(heldState)\n : await input.state.persistence.loadHeldContainerBinding(\n input.state.runtime.infra.execSql,\n input.remoteContainer.id,\n );\n const listed = input.remoteContainer;\n // A folder re-homed away from the listed organization never returns there,\n // whatever binding (possibly none, after a reset) the device holds now.\n const supersededListing =\n !listingRepeatsHeldOrdinaryBinding(heldBinding, listed) &&\n (await input.state.persistence.isSupersededContainerBinding(\n input.state.runtime.infra.execSql,\n { containerId: listed.id, organizationId: listed.organizationId },\n ));\n if (input.isCurrent?.() === false) return null;\n const verified = await verifyRemoteContainerDestination({\n ...input,\n heldBinding,\n supersededListing,\n refresh: !!input.expectedHydrationTombstone,\n onVerifiedCheckpoint: (checkpoint) => {\n expectedPlacementCheckpoint = checkpoint;\n },\n });\n if (!verified || input.isCurrent?.() === false) return null;\n input = { ...input, remoteContainer: verified };\n const existingState = input.state.containersById.get(\n input.remoteContainer.id,\n );\n const remoteState = await runWithSecurityIncidentReporting(\n input.state.runtime.util.reportSecurityIncident,\n {\n objectId: verified.id,\n objectKind: \"container\",\n operation: \"container.binding.persist\",\n organizationId: verified.organizationId,\n },\n async () =>\n (await rebindReHomedContainer({\n existingState,\n heldBinding,\n isCurrent: input.isCurrent,\n state: input.state,\n verified,\n }))\n ? persistVerifiedRemoteContainer({\n ...input,\n existingState,\n expectedPlacementCheckpoint,\n })\n : null,\n );\n if (!remoteState) {\n return null;\n }\n await reconcileLocalOnlySystemContainers({\n childIdsByParentId: input.childIdsByParentId,\n isCurrent: input.isCurrent,\n requestDocumentPriming: input.host.requestDocumentPriming,\n remoteSystemState: remoteState,\n state: input.state,\n });\n return remoteState;\n}\n\n/**\n * Upsert one listed folder, isolating a rejected proof or binding. The refusal\n * was already reported; returning no state leaves the item unapplied without\n * blocking independent folders.\n */\nexport async function upsertIsolatedRemoteContainerState(\n input: UpsertRemoteContainerStateInput,\n): Promise<ContainerState | null> {\n try {\n return await upsertRemoteContainerState(input);\n } catch (error) {\n if (\n !isKeyingVerificationError(error) &&\n !isProjectionVerificationCancelledError(error)\n )\n throw error;\n return null;\n }\n}\n\nfunction persistVerifiedRemoteContainer(\n input: UpsertRemoteContainerStateInput & {\n existingState: ContainerState | undefined;\n expectedPlacementCheckpoint: AccessManifestCheckpoint | undefined;\n },\n): Promise<ContainerState | null> {\n const { existingState, expectedPlacementCheckpoint } = input;\n return existingState\n ? updateExistingRemoteContainerState({\n childIdsByParentId: input.childIdsByParentId,\n containerIdsWithPendingMetadataUpdates:\n input.containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents:\n input.containerIdsWithPendingStructuralIntents,\n existingState,\n host: input.host,\n isCurrent: input.isCurrent,\n remoteContainer: input.remoteContainer,\n state: input.state,\n })\n : insertRemoteContainerState({\n childIdsByParentId: input.childIdsByParentId,\n host: input.host,\n expectedHydrationTombstone: input.expectedHydrationTombstone ?? null,\n expectedPlacementCheckpoint,\n isCurrent: input.isCurrent,\n remoteContainer: input.remoteContainer,\n state: input.state,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"remoteContainerState.js","sourceRoot":"","sources":["remoteContainerState.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,EACzB,gCAAgC,GACjC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,sCAAsC,EAAE,MAAM,qDAAqD,CAAC;AAC7G,OAAO,EACL,oBAAoB,EACpB,iCAAiC,GAClC,MAAM,kEAAkE,CAAC;AAE1E,OAAO,EAAE,8BAA8B,EAAE,MAAM,oCAAoC,CAAC;AACpF,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAElE,OAAO,EAAE,gCAAgC,EAAE,MAAM,oCAAoC,CAAC;AACtF,OAAO,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAChE,OAAO,EACL,yBAAyB,EACzB,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,gCAAgC,EAChC,kCAAkC,GACnC,MAAM,mBAAmB,CAAC;AAQ3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AACrE,OAAO,EACL,8BAA8B,EAC9B,mCAAmC,EACnC,6CAA6C,GAC9C,MAAM,6BAA6B,CAAC;AAErC,8EAA8E;AAC9E,gFAAgF;AAChF,6EAA6E;AAC7E,sEAAsE;AACtE,4EAA4E;AAC5E,2EAA2E;AAC3E,+EAA+E;AAC/E,8CAA8C;AAC9C,qFAAqF;AACrF,4EAA4E;AAC5E,wBAAwB;AACxB,MAAM,CAAC,KAAK,UAAU,kDAAkD,CAAC,KAGxE;IACC,IAAI,KAAK,CAAC,gBAAgB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACx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wCAAwC,EACtC,KAAK,CAAC,wCAAwC;YAChD,aAAa;YACb,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,KAAK,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC;QACJ,CAAC,CAAC,0BAA0B,CAAC;YACzB,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,0BAA0B,EAAE,KAAK,CAAC,0BAA0B,IAAI,IAAI;YACpE,2BAA2B;YAC3B,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,KAAK,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC,CAAC;AACT,CAAC","sourcesContent":["import type { AccessManifestCheckpoint } from \"@tearleads/crypto\";\nimport {\n isKeyingVerificationError,\n runWithSecurityIncidentReporting,\n} from \"../../../../data/keyingProjectionVerification/error\";\nimport { isProjectionVerificationCancelledError } from \"../../../../data/keyingProjectionVerification/types\";\nimport {\n heldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../../data/persistence/container-contents/containerBinding\";\nimport type { ContainerHydrationTombstone } from \"../../containerPersistence\";\nimport { installContainerMetadataRecord } from \"../../metadata/metadataPersistence\";\nimport { projectionGeneration } from \"../../projectionGeneration\";\nimport type { PrefetchedDestinationProjection } from \"../destination/destinationPrefetch\";\nimport { verifyRemoteContainerDestination } from \"../destination/verifiedDestination\";\nimport { rebindReHomedContainer } from \"../heldContainerRebind\";\nimport {\n moveIndexedContainerChild,\n removeIndexedContainerChild,\n} from \"../lanes/childIndex\";\nimport {\n reconcileLocalOnlyRootContainers,\n reconcileLocalOnlySystemContainers,\n} from \"../reconciliation\";\nimport type {\n ContainerChildIndex,\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n} from \"../types\";\nimport { insertRemoteContainerState } from \"./insertRemoteContainer\";\nimport {\n applyRemoteContainerTimestamps,\n remoteContainerHydrationSaveOptions,\n resolveRemoteContainerHydrationLocalUpdatedAt,\n} from \"./remoteContainerTimestamps\";\n\n// Container ids (restricted to the inbound page) that carry an unsynced local\n// create or move intent. Such a container's parent and local-edit timestamp are\n// owned by its structural-intent lane until that lane reconciles, so inbound\n// hydration must not revert parentId to the server value nor collapse\n// localUpdatedAt — doing so silently undoes a queued move and falsely reads\n// \"synced\". Move intents are read via listUnsyncedMoveIntents so a blocked\n// move — one whose destination parent has not synced yet, the common boot-time\n// case — is protected too. Pending *metadata*\n// updates are handled separately (listRemoteContainerIdsWithPendingMetadataUpdates);\n// structural intents live in the local outbox's container lanes, which that\n// query does not cover.\nexport async function listRemoteContainerIdsWithPendingStructuralIntents(input: {\n remoteContainers: ReadonlyArray<RemoteContainer>;\n state: RemoteContainerHydrationState;\n}): Promise<Set<string>> {\n if (input.remoteContainers.length === 0) {\n return new Set();\n }\n const remoteContainerIds = new Set(\n input.remoteContainers.map((remoteContainer) => remoteContainer.id),\n );\n\n const execSql = input.state.runtime.infra.execSql;\n const [pendingCreateIntents, unsyncedMoveIntents] = await Promise.all([\n input.state.persistence.listPendingCreateIntents(execSql),\n input.state.persistence.listUnsyncedMoveIntents(execSql),\n ]);\n const containerIdsWithPendingStructuralIntents = new Set<string>();\n for (const intent of pendingCreateIntents) {\n if (remoteContainerIds.has(intent.containerId)) {\n containerIdsWithPendingStructuralIntents.add(intent.containerId);\n }\n }\n for (const intent of unsyncedMoveIntents) {\n if (remoteContainerIds.has(intent.containerId)) {\n containerIdsWithPendingStructuralIntents.add(intent.containerId);\n }\n }\n return containerIdsWithPendingStructuralIntents;\n}\n\nexport async function listRemoteContainerIdsWithPendingMetadataUpdates(input: {\n remoteContainers: ReadonlyArray<RemoteContainer>;\n state: RemoteContainerHydrationState;\n}): Promise<Set<string>> {\n const containerIds = input.remoteContainers.flatMap((remoteContainer) => {\n const previousLocalUpdatedAt = input.state.containersById.get(\n remoteContainer.id,\n )?.container.localUpdatedAt;\n\n return previousLocalUpdatedAt &&\n previousLocalUpdatedAt.localeCompare(remoteContainer.updatedAt) > 0\n ? [remoteContainer.id]\n : [];\n });\n if (containerIds.length === 0) {\n return new Set();\n }\n\n const execSql = input.state.runtime.infra.execSql;\n return new Set(\n await input.state.persistence.listContainerIdsWithPendingUpdates(\n execSql,\n containerIds,\n ),\n );\n}\n\nfunction removeMissingHydratedContainer(input: {\n childIdsByParentId?: ContainerChildIndex | undefined;\n existingState: ContainerState;\n host: RemoteContainerHydrationHost;\n previousParentId: string | null;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): void {\n const { existingState, remoteContainer, state } = input;\n if (state.containersById.get(remoteContainer.id) !== existingState) {\n return;\n }\n\n state.containersById.delete(remoteContainer.id);\n if (input.childIdsByParentId) {\n removeIndexedContainerChild(\n input.childIdsByParentId,\n remoteContainer.id,\n input.previousParentId,\n );\n input.childIdsByParentId.delete(remoteContainer.id);\n }\n input.host.updateSnapshot();\n}\n\nfunction createUpdatedRemoteContainerState(\n existingState: ContainerState,\n remoteContainer: RemoteContainer,\n): ContainerState {\n return {\n ...existingState,\n container: applyRemoteContainerTimestamps(\n existingState.container,\n remoteContainer,\n ),\n containerWriterProjection: null,\n metadataReferencedPrincipals: remoteContainer.metadataReferencedPrincipals,\n };\n}\n\nfunction installUpdatedRemoteContainerState(\n existingState: ContainerState,\n nextState: ContainerState,\n host: RemoteContainerHydrationHost,\n): void {\n const wasLocalOnly = existingState.container.serverCreatedAt == null;\n existingState.container = nextState.container;\n existingState.containerWriterProjection = nextState.containerWriterProjection;\n existingState.metadataReferencedPrincipals =\n nextState.metadataReferencedPrincipals;\n // The snapshot copied the live generation when it was taken; a hint that\n // landed during the persist leaves the live metadata projection dropped.\n if (projectionGeneration(existingState) === projectionGeneration(nextState))\n existingState.metadataWriterProjection = nextState.metadataWriterProjection;\n installContainerMetadataRecord(existingState, nextState.record);\n // A document pass may have deferred while this root was awaiting proof.\n // The first durable remote acknowledgement makes its pending creates runnable.\n if (wasLocalOnly && existingState.container.serverCreatedAt != null)\n host.requestDocumentPriming?.();\n}\n\nasync function updateExistingRemoteContainerState(input: {\n childIdsByParentId?: ContainerChildIndex | undefined;\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n existingState: ContainerState;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): Promise<ContainerState | null> {\n const { childIdsByParentId, existingState, host, remoteContainer, state } =\n input;\n const previousParentId = existingState.container.parentId;\n const previousLocalUpdatedAt = existingState.container.localUpdatedAt;\n // A queued, not-yet-synced local move/create owns this container's parent\n // until its intent lane reconciles. Omit the remote parent when the page scan\n // saw one; persistence also rechecks the intent transactionally so a move\n // created after that scan wins. Both paths preserve the durable local clock.\n const hasPendingStructuralIntent =\n input.containerIdsWithPendingStructuralIntents.has(remoteContainer.id);\n const nextParentId = hasPendingStructuralIntent\n ? undefined\n : remoteContainer.parentId;\n const localUpdatedAt = resolveRemoteContainerHydrationLocalUpdatedAt({\n containerIdsWithPendingMetadataUpdates:\n input.containerIdsWithPendingMetadataUpdates,\n hasPendingStructuralIntent,\n previousLocalUpdatedAt,\n remoteContainer,\n });\n const nextState = createUpdatedRemoteContainerState(\n existingState,\n remoteContainer,\n );\n const persistenceResult = await host.persistContainerState(\n nextState,\n {\n accessEpoch: remoteContainer.metadataAccessEpoch,\n accessStateHash: remoteContainer.metadataAccessStateHash,\n documentId: remoteContainer.metadataDocumentId,\n effectiveAccessLevel: remoteContainer.effectiveAccessLevel,\n metadataDocumentId: remoteContainer.metadataDocumentId,\n systemSlot: remoteContainer.systemSlot ?? null,\n organizationId: remoteContainer.organizationId,\n ...(nextParentId !== undefined ? { parentId: nextParentId } : {}),\n },\n false,\n remoteContainerHydrationSaveOptions({\n localUpdatedAt,\n remoteContainer,\n }),\n {\n preserveDurableStructureWhenPending: true,\n },\n );\n if (persistenceResult.status === \"missing\") {\n // Hydration persists a detached candidate so an in-flight response cannot\n // mutate mapped state before its guards settle. Retire the exact state this\n // hydration read because store-level reference cleanup cannot see the clone.\n removeMissingHydratedContainer({\n childIdsByParentId,\n existingState,\n host,\n previousParentId,\n remoteContainer,\n state,\n });\n return null;\n }\n if (persistenceResult.status !== \"persisted\") return null;\n const { record: nextRecord } = persistenceResult;\n installContainerMetadataRecord(nextState, nextRecord);\n if (input.isCurrent?.() === false) {\n return existingState;\n }\n nextState.container = {\n ...nextState.container,\n metadataDocumentId: remoteContainer.metadataDocumentId,\n organizationId: remoteContainer.organizationId,\n parentId: nextState.container.parentId,\n };\n\n installUpdatedRemoteContainerState(existingState, nextState, host);\n moveIndexedContainerChild(\n childIdsByParentId,\n remoteContainer.id,\n previousParentId,\n existingState.container.parentId,\n );\n await reconcileLocalOnlyRootContainers({\n childIdsByParentId,\n isCurrent: input.isCurrent,\n remoteRootState: existingState,\n requestDocumentPriming: host.requestDocumentPriming,\n state,\n });\n return existingState;\n}\n\ninterface UpsertRemoteContainerStateInput {\n childIdsByParentId?: ContainerChildIndex | undefined;\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n host: RemoteContainerHydrationHost;\n expectedHydrationTombstone?: ContainerHydrationTombstone | null | undefined;\n isCurrent?: (() => boolean) | undefined;\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}\n\nexport async function upsertRemoteContainerState(\n input: UpsertRemoteContainerStateInput,\n): Promise<ContainerState | null> {\n let expectedPlacementCheckpoint: AccessManifestCheckpoint | undefined;\n const heldState = input.state.containersById.get(input.remoteContainer.id);\n const heldBinding = heldState\n ? heldContainerBinding(heldState)\n : await input.state.persistence.loadHeldContainerBinding(\n input.state.runtime.infra.execSql,\n input.remoteContainer.id,\n );\n const listed = input.remoteContainer;\n // A folder re-homed away from the listed organization never returns there,\n // whatever binding (possibly none, after a reset) the device holds now.\n const supersededListing =\n !listingRepeatsHeldOrdinaryBinding(heldBinding, listed) &&\n (await input.state.persistence.isSupersededContainerBinding(\n input.state.runtime.infra.execSql,\n { containerId: listed.id, organizationId: listed.organizationId },\n ));\n if (input.isCurrent?.() === false) return null;\n const verified = await verifyRemoteContainerDestination({\n ...input,\n heldBinding,\n supersededListing,\n refresh: !!input.expectedHydrationTombstone,\n onVerifiedCheckpoint: (checkpoint) => {\n expectedPlacementCheckpoint = checkpoint;\n },\n });\n if (!verified || input.isCurrent?.() === false) return null;\n input = { ...input, remoteContainer: verified };\n const existingState = input.state.containersById.get(\n input.remoteContainer.id,\n );\n const remoteState = await runWithSecurityIncidentReporting(\n input.state.runtime.util.reportSecurityIncident,\n {\n objectId: verified.id,\n objectKind: \"container\",\n operation: \"container.binding.persist\",\n organizationId: verified.organizationId,\n },\n async () =>\n (await rebindReHomedContainer({\n existingState,\n heldBinding,\n isCurrent: input.isCurrent,\n state: input.state,\n verified,\n }))\n ? persistVerifiedRemoteContainer({\n ...input,\n existingState,\n expectedPlacementCheckpoint,\n })\n : null,\n );\n if (!remoteState) {\n return null;\n }\n await reconcileLocalOnlySystemContainers({\n childIdsByParentId: input.childIdsByParentId,\n isCurrent: input.isCurrent,\n requestDocumentPriming: input.host.requestDocumentPriming,\n remoteSystemState: remoteState,\n state: input.state,\n });\n return remoteState;\n}\n\n/**\n * Upsert one listed folder, isolating a rejected proof or binding. The refusal\n * was already reported; returning no state leaves the item unapplied without\n * blocking independent folders.\n */\nexport async function upsertIsolatedRemoteContainerState(\n input: UpsertRemoteContainerStateInput,\n): Promise<ContainerState | null> {\n try {\n return await upsertRemoteContainerState(input);\n } catch (error) {\n if (\n !isKeyingVerificationError(error) &&\n !isProjectionVerificationCancelledError(error)\n )\n throw error;\n return null;\n }\n}\n\nfunction persistVerifiedRemoteContainer(\n input: UpsertRemoteContainerStateInput & {\n existingState: ContainerState | undefined;\n expectedPlacementCheckpoint: AccessManifestCheckpoint | undefined;\n },\n): Promise<ContainerState | null> {\n const { existingState, expectedPlacementCheckpoint } = input;\n return existingState\n ? updateExistingRemoteContainerState({\n childIdsByParentId: input.childIdsByParentId,\n containerIdsWithPendingMetadataUpdates:\n input.containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents:\n input.containerIdsWithPendingStructuralIntents,\n existingState,\n host: input.host,\n isCurrent: input.isCurrent,\n remoteContainer: input.remoteContainer,\n state: input.state,\n })\n : insertRemoteContainerState({\n childIdsByParentId: input.childIdsByParentId,\n host: input.host,\n expectedHydrationTombstone: input.expectedHydrationTombstone ?? null,\n expectedPlacementCheckpoint,\n isCurrent: input.isCurrent,\n remoteContainer: input.remoteContainer,\n state: input.state,\n });\n}\n"]}
|
|
@@ -2,11 +2,11 @@ import type { RequestResult } from "../../../internal/api-client/index.js";
|
|
|
2
2
|
import type { ContainerReplacementAuthorizationsResponse } from "../../../internal/validators/operation/index.js";
|
|
3
3
|
import type { ListContainerParentLanesRequest } from "../../../internal/validators/request/index.js";
|
|
4
4
|
import type { ContainerSummary, ContainerWriterProjectionResponse, DocumentWriterProjectionResponse, ListContainerParentLanesResponse, ListContainersResponse, ReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
|
|
5
|
-
import type { createContainerMetadataDocument } from "../../../data/containers/containerMetadataDocument.js";
|
|
6
5
|
import type { CurrentPrincipalPolicyReader } from "../../principals/currentPrincipalPolicyReader.js";
|
|
7
6
|
import type { PrincipalPolicyHistoryReader } from "../../principals/principalPolicyHistoryReader.js";
|
|
8
7
|
import type { ContainerContentsPersistence, ContainerDocumentRecord, ContainerHydrationTombstone, ContainerRecord, createContainerParentSyncLane } from "../containerPersistence.js";
|
|
9
8
|
import type { ContainerMetadataPatch } from "../metadata/index.js";
|
|
9
|
+
import type { createContainerMetadataDocument } from "../metadata/containerMetadataDocument.js";
|
|
10
10
|
import type { ContainerContentsWorkflowRuntime } from "../runtime.js";
|
|
11
11
|
export type ListedRemoteContainerPageItem = ListContainersResponse["items"][number];
|
|
12
12
|
export type ContainerChildIndex = Map<string, Set<string>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { RequestResult } from \"@tearleads/api-client\";\nimport type { ContainerReplacementAuthorizationsResponse } from \"@tearleads/validators/operation\";\nimport type { ListContainerParentLanesRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n ListContainerParentLanesResponse,\n ListContainersResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type {
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { RequestResult } from \"@tearleads/api-client\";\nimport type { ContainerReplacementAuthorizationsResponse } from \"@tearleads/validators/operation\";\nimport type { ListContainerParentLanesRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n ListContainerParentLanesResponse,\n ListContainersResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerDocumentRecord,\n ContainerHydrationTombstone,\n ContainerRecord,\n createContainerParentSyncLane,\n} from \"../containerPersistence\";\nimport type { ContainerMetadataPatch } from \"../metadata\";\nimport type { createContainerMetadataDocument } from \"../metadata/containerMetadataDocument\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ListedRemoteContainerPageItem =\n ListContainersResponse[\"items\"][number];\nexport type ContainerChildIndex = Map<string, Set<string>>;\nexport type QueueContainerParentLane = (parentId: string | null) => void;\nexport type RemoteContainerIngestQueue = Map<string, RemoteContainer>;\nexport type SaveContainerOptions = Parameters<\n ContainerContentsPersistence[\"saveContainer\"]\n>[3];\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createContainerMetadataDocument>\n>;\nexport type RemoteContainer = Pick<\n ContainerSummary,\n | \"createdAt\"\n | \"effectiveAccessLevel\"\n | \"systemSlot\"\n | \"id\"\n | \"metadataAccessEpoch\"\n | \"metadataAccessStateHash\"\n | \"metadataDocumentId\"\n | \"metadataReferencedPrincipals\"\n | \"organizationId\"\n | \"parentId\"\n | \"updatedAt\"\n>;\n\nexport interface ContainerState {\n containerWriterProjection?:\n | ContainerWriterProjectionResponse\n | null\n | undefined;\n /**\n * Bumped whenever a realtime hint drops this container's cached writer\n * projections (container and metadata document alike); an operation that\n * fetched or carried a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration?: number | undefined;\n metadataReferencedPrincipals?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n container: ContainerRecord;\n doc: ContainerMetadataDocumentState;\n metadataWriterProjection?:\n | DocumentWriterProjectionResponse\n | null\n | undefined;\n /** Durable pull progress mirrored from the metadata document record. */\n pullContinuation?: ContainerDocumentRecord[\"pullContinuation\"] | undefined;\n record: ContainerDocumentRecord;\n}\n\ninterface RemoteContainerHydrationApi\n extends Partial<PrincipalPolicyHistoryReader>,\n CurrentPrincipalPolicyReader {\n getContainerReplacementAuthorizationsResult(\n containerId: string,\n replacesOrganizationId: string,\n ): Promise<RequestResult<ContainerReplacementAuthorizationsResponse>>;\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n listContainerParentLanes(\n input: ListContainerParentLanesRequest,\n ): Promise<ListContainerParentLanesResponse | null>;\n}\n\ninterface RemoteContainerHydrationRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"adoptRootContainer\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: RemoteContainerHydrationApi;\n}\n\nexport interface RemoteContainerHydrationState {\n containersById: Map<string, ContainerState>;\n lifecycleGeneration?: number | undefined;\n persistence: ContainerContentsPersistence;\n rootLaneHydrated?: boolean | undefined;\n runtime: RemoteContainerHydrationRuntime;\n structuralGeneration?: number | undefined;\n}\n\nexport type PersistContainerStateResult =\n | { status: \"identity-superseded\"; record: ContainerDocumentRecord }\n | { status: \"missing\" }\n | {\n status: \"persisted\";\n record: ContainerDocumentRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | { status: \"stale-generation\" };\n\nexport interface RemoteContainerHydrationHost {\n persistContainerState: (\n containerState: ContainerState,\n patch?: Partial<ContainerMetadataPatch>,\n updateView?: boolean,\n saveOptions?: SaveContainerOptions,\n mutationOptions?: {\n /** Queued metadata rows the server committed, settled in this write. */\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedStateWhenMissing?: ContainerState | undefined;\n isCurrent?: (() => boolean) | undefined;\n createIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"createIntentSettlement\"];\n moveIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"moveIntentSettlement\"];\n preserveDurableStructureWhenPending?: boolean | undefined;\n },\n ) => Promise<PersistContainerStateResult>;\n requestDocumentPriming?: (() => void) | undefined;\n updateSnapshot: () => void;\n}\n\nexport interface ContainerParentHydrationLane {\n parentId: string | null;\n watermark?: ListContainersResponse[\"nextWatermark\"];\n}\n\nexport interface ExpectedContainerState {\n container: ContainerRecord;\n fingerprint: string;\n}\n\nexport interface FetchedContainerParentLanePage {\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n expectedHydrationTombstones: ReadonlyMap<string, ContainerHydrationTombstone>;\n lane: ContainerParentHydrationLane;\n response: ListContainersResponse;\n syncLane: ReturnType<typeof createContainerParentSyncLane>;\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { base64ToBytes, bytesToBase64 } from "../../internal/encoding/index.js";
|
|
2
2
|
import { exportAllUpdates, importUpdates } from "../../internal/loro/index.js";
|
|
3
|
-
import { createContainerMetadataDocument, getDefaultContainerName, readContainerMetadataValue, writeContainerMetadataValue, } from "../../data/containers/containerMetadataDocument.js";
|
|
4
3
|
import { enqueuePendingContainerUpdate, } from "./containerPersistence.js";
|
|
4
|
+
import { createContainerMetadataDocument, getDefaultContainerName, readContainerMetadataValue, writeContainerMetadataValue, } from "./metadata/containerMetadataDocument.js";
|
|
5
5
|
function createInitialContainerRecord(input) {
|
|
6
6
|
return {
|
|
7
7
|
accessEpoch: 1,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storedContainerState.js","sourceRoot":"","sources":["storedContainerState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"storedContainerState.js","sourceRoot":"","sources":["storedContainerState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAElE,OAAO,EAGL,6BAA6B,GAE9B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,+BAA+B,EAC/B,uBAAuB,EACvB,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,sCAAsC,CAAC;AAO9C,SAAS,4BAA4B,CAAC,KAGrC;IACC,OAAO;QACL,WAAW,EAAE,CAAC;QACd,eAAe,EAAE,IAAI;QACrB,gBA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AC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,MAAM,GAAG,GAAG,MAAM,+BAA+B,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;IAChE,IAAI,aAAa,GAAG,SAAS,CAAC;IAC9B,IAAI,MAAM,CAAC,eAAe,EAAE,CAAC;QAC3B,aAAa,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;QAC5D,MAAM,QAAQ,GAAG,0BAA0B,CACzC,GAAG,EACH,uBAAuB,CAAC,SAAS,CAAC,QAAQ,CAAC,CAC5C,CAAC;QACF,aAAa,GAAG,EAAE,GAAG,SAAS,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC;IAC7E,CAAC;SAAM,CAAC;QACN,2BAA2B,CAAC,GAAG,EAAE;YAC/B,IAAI,EAAE,SAAS,CAAC,IAAI;YACpB,IAAI,EAAE,SAAS,CAAC,IAAI;SACrB,CAAC,CAAC;IACL,CAAC;IACD,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC;AACnD,CAAC","sourcesContent":["import { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { exportAllUpdates, importUpdates } from \"@tearleads/loro\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type ContainerContentsPersistence,\n type ContainerMetadataRecord,\n enqueuePendingContainerUpdate,\n type StoredContainerState,\n} from \"./containerPersistence\";\nimport {\n createContainerMetadataDocument,\n getDefaultContainerName,\n readContainerMetadataValue,\n writeContainerMetadataValue,\n} from \"./metadata/containerMetadataDocument\";\nimport type { ContainerState } from \"./remoteHydration/types\";\n\ntype SaveContainerOptions = Parameters<\n ContainerContentsPersistence[\"saveContainer\"]\n>[3];\n\nfunction createInitialContainerRecord(input: {\n container: StoredContainerState[\"container\"];\n metadataUpdates: string;\n}): ContainerMetadataRecord {\n return {\n accessEpoch: 1,\n accessStateHash: null,\n contentKeyBundle: null,\n documentId: input.container.metadataDocumentId,\n documentKekTargets: null,\n documentManifestBundle: null,\n id: input.container.id,\n lastCommitLsn: null,\n metadataUpdates: input.metadataUpdates,\n snapshotEndVersion: \"\",\n };\n}\n\nfunction metadataProjectionChanged(\n left: StoredContainerState[\"container\"],\n right: StoredContainerState[\"container\"],\n): boolean {\n return left.icon !== right.icon || left.name !== right.name;\n}\n\nfunction replaySaveOptions(\n container: StoredContainerState[\"container\"],\n): SaveContainerOptions {\n const localUpdatedAt =\n container.localUpdatedAt ?? container.updatedAt ?? null;\n return localUpdatedAt ? { localUpdatedAt } : undefined;\n}\n\nexport async function hydrateStoredContainerState(input: {\n execSql: ExecSql;\n persistence: ContainerContentsPersistence;\n storedContainer: StoredContainerState;\n}): Promise<ContainerState> {\n const { execSql, persistence, storedContainer } = input;\n const { container } = storedContainer;\n const doc = await createContainerMetadataDocument(container.id);\n let nextContainer = container;\n let nextRecord = storedContainer.record;\n\n if (nextRecord?.metadataUpdates) {\n importUpdates(doc, [base64ToBytes(nextRecord.metadataUpdates)]);\n const metadata = readContainerMetadataValue(\n doc,\n getDefaultContainerName(container.parentId),\n );\n nextContainer = {\n ...container,\n icon: metadata.icon,\n name: metadata.name,\n };\n if (metadataProjectionChanged(container, nextContainer)) {\n await persistence.saveContainer(\n execSql,\n nextContainer,\n nextRecord,\n replaySaveOptions(container),\n );\n }\n } else {\n writeContainerMetadataValue(doc, {\n icon: container.icon,\n name: container.name,\n });\n const initialUpdate = exportAllUpdates(doc);\n nextRecord = createInitialContainerRecord({\n container,\n metadataUpdates: bytesToBase64(initialUpdate),\n });\n await persistence.saveContainer(execSql, nextContainer, nextRecord);\n\n // A device-first child's first metadata waits for its create. A root's\n // never does: only registration creates a root remotely, and provisioning\n // commits the root's metadata itself, so a queued copy would only be\n // replayed after login as duplicate ops.\n if (!container.metadataDocumentId && container.parentId !== null) {\n await enqueuePendingContainerUpdate(execSql, persistence, {\n containerId: container.id,\n update: initialUpdate,\n });\n }\n }\n\n return { container: nextContainer, doc, record: nextRecord };\n}\n\n/** Materialize a CAS winner without writing repair rows from a stale caller. */\nexport async function materializeStoredContainerStateReadOnly(input: {\n storedContainer: StoredContainerState;\n}): Promise<ContainerState | null> {\n const { container, record } = input.storedContainer;\n if (!record) return null;\n const doc = await createContainerMetadataDocument(container.id);\n let nextContainer = container;\n if (record.metadataUpdates) {\n importUpdates(doc, [base64ToBytes(record.metadataUpdates)]);\n const metadata = readContainerMetadataValue(\n doc,\n getDefaultContainerName(container.parentId),\n );\n nextContainer = { ...container, icon: metadata.icon, name: metadata.name };\n } else {\n writeContainerMetadataValue(doc, {\n icon: container.icon,\n name: container.name,\n });\n }\n return { container: nextContainer, doc, record };\n}\n"]}
|
|
@@ -3,7 +3,7 @@ import { deriveOrganizationMetadataContainerSystemSlot } from "../../../internal
|
|
|
3
3
|
import { getTargetContainerContext, readContainerState, } from "../../../data/containers/shared/projection.js";
|
|
4
4
|
import { unwrapContainerKekPath } from "../../../data/documents/shared/containerKek/containerKekPath.js";
|
|
5
5
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
|
|
6
|
-
import { loadContainers } from "../../../data/persistence/
|
|
6
|
+
import { loadContainers } from "../../../data/persistence/container-contents/containerPersistence.js";
|
|
7
7
|
import { withMetadataRootReload } from "./groupMetadataErrors.js";
|
|
8
8
|
/**
|
|
9
9
|
* A group's signed name does not open under the metadata key it cites, or opens
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"groupMetadataAccess.js","sourceRoot":"","sources":["groupMetadataAccess.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oBAAoB,EAGpB,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6CAA6C,EAAE,MAAM,2CAA2C,CAAC;AAE1G,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,4CAA4C,CAAC;AACp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,IAAI,GAAG,MAAM,6CAA6C,CAAC;gBAC/D,cAAc,EAAE,KAAK,CAAC,cAAc;aACrC,CAAC,CAAC;YACH,MAAM,UAAU,GAAG,MAAM,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACvD,MAAM,SAAS,GAAG,UAAU,CAAC,IAAI,CAC/B,CAAC,GAAG,EAAE,EAAE,CACN,GAAG,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;gBAC3C,GAAG,CAAC,UAAU,KAAK,IAAI,CAC1B,CAAC;YACF,IAAI,CAAC,SAAS;gBACZ,MAAM,IAAI,KAAK,CACb,yDAAyD,CAC1D,CAAC;YACJ,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;YAC3C,IAAI,CAAC,OAAO;gBAAE,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;YACzE,OAAO,OAAO,CAAC,OAAO,CAAC;QACzB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerAccessManifestState,\n decryptGroupMetadata,\n type GroupMetadataKey,\n type ReferencedPrincipalHead,\n readGroupMetadata,\n} from \"@tearleads/crypto\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../data/containers/shared/projection\";\nimport { unwrapContainerKekPath } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { loadContainers } from \"../../../data/persistence/containers/containerPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { GroupPolicyNameReader } from \"../principalPolicy/principalPolicyRequest\";\nimport { withMetadataRootReload } from \"./groupMetadataErrors\";\n\nexport interface GroupMetadataAccessInput {\n readonly apiClient: {\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n };\n readonly verifyMetadataContainer: (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead | undefined,\n ) => Promise<void>;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly targetSecretKey: Uint8Array;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\n/**\n * A group's signed name does not open under the metadata key it cites, or opens\n * to an invalid name. Every reader holding that key gets the same result. The\n * API checks the citation but can never check the ciphertext, so a dishonest\n * admin can sign such a name; directory walks isolate the group instead of\n * failing every name in the organization.\n */\nexport class GroupMetadataUnreadableError extends Error {\n constructor(groupId: string, cause: unknown) {\n super(`Group ${groupId} metadata cannot be decrypted`, { cause });\n this.name = \"GroupMetadataUnreadableError\";\n }\n}\n\nfunction loadMetadataKeyring(\n input: GroupMetadataAccessInput,\n containerId: string,\n) {\n return withMetadataRootReload(\n () => loadMetadataKeyringOnce(input, containerId),\n () => input.apiClient.evictContainerWriterProjection(containerId),\n );\n}\n\nasync function loadMetadataKeyringOnce(\n input: GroupMetadataAccessInput,\n containerId: string,\n) {\n const projection =\n await input.apiClient.getContainerWriterProjection(containerId);\n if (!projection) return null;\n if (\n projection.containerId !== containerId ||\n projection.organizationId !== input.organizationId\n )\n throw new Error(\"Group metadata container is unavailable\");\n const target = getTargetContainerContext(projection);\n const state = readContainerState(target.manifest);\n const slot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.organizationId,\n });\n if (\n state.organizationId !== input.organizationId ||\n state.systemSlot !== slot ||\n state.parentContainerId !== null\n )\n throw new Error(\n \"Group metadata requires the signed organization metadata container\",\n );\n await input.verifyMetadataContainer(\n state,\n projection.policyEvidence.organization?.head,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n const keys = await unwrapContainerKekPath({\n ...input,\n projection,\n secretKey: input.targetSecretKey,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const keyMaterial = keys.get(target.kek.containerKeyEpochId);\n if (!keyMaterial)\n throw new Error(\"Group metadata container key is unavailable\");\n return {\n current: {\n organizationId: input.organizationId,\n containerId,\n containerKeyEpochId: target.kek.containerKeyEpochId,\n keyMaterial,\n },\n keys,\n };\n}\n\n/** Uses the shared metadata container's authenticated keyring, including old epochs. */\nexport function createGroupMetadataAccess(input: GroupMetadataAccessInput) {\n const loads = new Map<\n string,\n Promise<{\n current: GroupMetadataKey;\n keys: ReadonlyMap<string, Uint8Array>;\n } | null>\n >();\n function loaded(containerId: string) {\n let pending = loads.get(containerId);\n if (!pending) {\n pending = loadMetadataKeyring(input, containerId);\n loads.set(containerId, pending);\n }\n return pending;\n }\n const readName: GroupPolicyNameReader = async (bundle) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const metadata = readGroupMetadata(bundle.currentPayload.ciphertext);\n if (\"role\" in metadata)\n return metadata.role === \"admins\" ? \"Admins\" : \"Members\";\n if (\n metadata.organizationId !== input.organizationId ||\n metadata.groupId !== bundle.currentState.principalId ||\n bundle.currentState.principalType !== \"group\"\n )\n throw new Error(\"Group metadata scope does not match its signed group\");\n const keyring = await loaded(metadata.containerId);\n const keyMaterial = keyring?.keys.get(metadata.containerKeyEpochId);\n if (!keyMaterial)\n throw new Error(\"Group metadata historical key is unavailable\");\n try {\n return await decryptGroupMetadata({\n key: { ...metadata, keyMaterial },\n groupId: bundle.currentState.principalId,\n payload: bundle.currentPayload.ciphertext,\n });\n } catch (cause) {\n throw new GroupMetadataUnreadableError(\n bundle.currentState.principalId,\n cause,\n );\n }\n };\n return {\n readName,\n async loadEncryptionKey(): Promise<GroupMetadataKey> {\n const slot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.organizationId,\n });\n const containers = await loadContainers(input.execSql);\n const container = containers.find(\n (row) =>\n row.organizationId === input.organizationId &&\n row.systemSlot === slot,\n );\n if (!container)\n throw new Error(\n \"Organization metadata container has not been discovered\",\n );\n const keyring = await loaded(container.id);\n if (!keyring) throw new Error(\"Group metadata container is unavailable\");\n return keyring.current;\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"groupMetadataAccess.js","sourceRoot":"","sources":["groupMetadataAccess.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oBAAoB,EAGpB,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6CAA6C,EAAE,MAAM,2CAA2C,CAAC;AAE1G,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,sBAAsB,EAAE,MAAM,8DAA8D,CAAC;AAKtG,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,cAAc,EAAE,MAAM,mEAAmE,CAAC;AAGnG,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAuB/D;;;;;;GAMG;AACH,MAAM,OAAO,4BAA6B,SAAQ,KAAK;IACrD,YAAY,OAAe,EAAE,KAAc;QACzC,KAAK,CAAC,SAAS,OAAO,+BAA+B,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAClE,IAAI,CAAC,IAAI,GAAG,8BAA8B,CAAC;IAC7C,CAAC;CACF;AAED,SAAS,mBAAmB,CAC1B,KAA+B,EAC/B,WAAmB;IAEnB,OAAO,sBAAsB,CAC3B,GAAG,EAAE,CAAC,uBAAuB,CAAC,KAAK,EAAE,WAAW,CAAC,EACjD,GAAG,EAAE,CAAC,KAAK,CAAC,SAAS,CAAC,8BAA8B,CAAC,WAAW,CAAC,CAClE,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,uBAAuB,CACpC,KAA+B,EAC/B,WAAmB;IAEnB,MAAM,UAAU,G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AAW;YACd,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;QAClE,IAAI,CAAC;YACH,OAAO,MAAM,oBAAoB,CAAC;gBAChC,GAAG,EAAE,EAAE,GAAG,QAAQ,EAAE,WAAW,EAAE;gBACjC,OAAO,EAAE,MAAM,CAAC,YAAY,CAAC,WAAW;gBACxC,OAAO,EAAE,MAAM,CAAC,cAAc,CAAC,UAAU;aAC1C,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,4BAA4B,CACpC,MAAM,CAAC,YAAY,CAAC,WAAW,EAC/B,KAAK,CACN,CAAC;QACJ,CAAC;IACH,CAAC,CAAC;IACF,OAAO;QACL,QAAQ;QACR,KAAK,CAAC,iBAAiB;YACrB,MAAM,IAAI,GAAG,MAAM,6CAA6C,CAAC;gBAC/D,cAAc,EAAE,KAAK,CAAC,cAAc;aACrC,CAAC,CAAC;YACH,MAAM,UAAU,GAAG,MAAM,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACvD,MAAM,SAAS,GAAG,UAAU,CAAC,IAAI,CAC/B,CAAC,GAAG,EAAE,EAAE,CACN,GAAG,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;gBAC3C,GAAG,CAAC,UAAU,KAAK,IAAI,CAC1B,CAAC;YACF,IAAI,CAAC,SAAS;gBACZ,MAAM,IAAI,KAAK,CACb,yDAAyD,CAC1D,CAAC;YACJ,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;YAC3C,IAAI,CAAC,OAAO;gBAAE,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;YACzE,OAAO,OAAO,CAAC,OAAO,CAAC;QACzB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerAccessManifestState,\n decryptGroupMetadata,\n type GroupMetadataKey,\n type ReferencedPrincipalHead,\n readGroupMetadata,\n} from \"@tearleads/crypto\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../data/containers/shared/projection\";\nimport { unwrapContainerKekPath } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { loadContainers } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { GroupPolicyNameReader } from \"../principalPolicy/principalPolicyRequest\";\nimport { withMetadataRootReload } from \"./groupMetadataErrors\";\n\nexport interface GroupMetadataAccessInput {\n readonly apiClient: {\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n };\n readonly verifyMetadataContainer: (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead | undefined,\n ) => Promise<void>;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly targetSecretKey: Uint8Array;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\n/**\n * A group's signed name does not open under the metadata key it cites, or opens\n * to an invalid name. Every reader holding that key gets the same result. The\n * API checks the citation but can never check the ciphertext, so a dishonest\n * admin can sign such a name; directory walks isolate the group instead of\n * failing every name in the organization.\n */\nexport class GroupMetadataUnreadableError extends Error {\n constructor(groupId: string, cause: unknown) {\n super(`Group ${groupId} metadata cannot be decrypted`, { cause });\n this.name = \"GroupMetadataUnreadableError\";\n }\n}\n\nfunction loadMetadataKeyring(\n input: GroupMetadataAccessInput,\n containerId: string,\n) {\n return withMetadataRootReload(\n () => loadMetadataKeyringOnce(input, containerId),\n () => input.apiClient.evictContainerWriterProjection(containerId),\n );\n}\n\nasync function loadMetadataKeyringOnce(\n input: GroupMetadataAccessInput,\n containerId: string,\n) {\n const projection =\n await input.apiClient.getContainerWriterProjection(containerId);\n if (!projection) return null;\n if (\n projection.containerId !== containerId ||\n projection.organizationId !== input.organizationId\n )\n throw new Error(\"Group metadata container is unavailable\");\n const target = getTargetContainerContext(projection);\n const state = readContainerState(target.manifest);\n const slot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.organizationId,\n });\n if (\n state.organizationId !== input.organizationId ||\n state.systemSlot !== slot ||\n state.parentContainerId !== null\n )\n throw new Error(\n \"Group metadata requires the signed organization metadata container\",\n );\n await input.verifyMetadataContainer(\n state,\n projection.policyEvidence.organization?.head,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n const keys = await unwrapContainerKekPath({\n ...input,\n projection,\n secretKey: input.targetSecretKey,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const keyMaterial = keys.get(target.kek.containerKeyEpochId);\n if (!keyMaterial)\n throw new Error(\"Group metadata container key is unavailable\");\n return {\n current: {\n organizationId: input.organizationId,\n containerId,\n containerKeyEpochId: target.kek.containerKeyEpochId,\n keyMaterial,\n },\n keys,\n };\n}\n\n/** Uses the shared metadata container's authenticated keyring, including old epochs. */\nexport function createGroupMetadataAccess(input: GroupMetadataAccessInput) {\n const loads = new Map<\n string,\n Promise<{\n current: GroupMetadataKey;\n keys: ReadonlyMap<string, Uint8Array>;\n } | null>\n >();\n function loaded(containerId: string) {\n let pending = loads.get(containerId);\n if (!pending) {\n pending = loadMetadataKeyring(input, containerId);\n loads.set(containerId, pending);\n }\n return pending;\n }\n const readName: GroupPolicyNameReader = async (bundle) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const metadata = readGroupMetadata(bundle.currentPayload.ciphertext);\n if (\"role\" in metadata)\n return metadata.role === \"admins\" ? \"Admins\" : \"Members\";\n if (\n metadata.organizationId !== input.organizationId ||\n metadata.groupId !== bundle.currentState.principalId ||\n bundle.currentState.principalType !== \"group\"\n )\n throw new Error(\"Group metadata scope does not match its signed group\");\n const keyring = await loaded(metadata.containerId);\n const keyMaterial = keyring?.keys.get(metadata.containerKeyEpochId);\n if (!keyMaterial)\n throw new Error(\"Group metadata historical key is unavailable\");\n try {\n return await decryptGroupMetadata({\n key: { ...metadata, keyMaterial },\n groupId: bundle.currentState.principalId,\n payload: bundle.currentPayload.ciphertext,\n });\n } catch (cause) {\n throw new GroupMetadataUnreadableError(\n bundle.currentState.principalId,\n cause,\n );\n }\n };\n return {\n readName,\n async loadEncryptionKey(): Promise<GroupMetadataKey> {\n const slot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.organizationId,\n });\n const containers = await loadContainers(input.execSql);\n const container = containers.find(\n (row) =>\n row.organizationId === input.organizationId &&\n row.systemSlot === slot,\n );\n if (!container)\n throw new Error(\n \"Organization metadata container has not been discovered\",\n );\n const keyring = await loaded(container.id);\n if (!keyring) throw new Error(\"Group metadata container is unavailable\");\n return keyring.current;\n },\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { loadContainerDisplayNamesByIds } from "../../../data/persistence/
|
|
1
|
+
import { loadContainerDisplayNamesByIds } from "../../../data/persistence/container-contents/containerPersistence.js";
|
|
2
2
|
import { loadOrganizationGroupDisplayNames } from "../../../data/persistence/organizations/organizationGroupNamePersistence.js";
|
|
3
3
|
import { loadOrganizationReadModelProjection } from "../../../data/persistence/organizations/organizationReadModelPersistence.js";
|
|
4
4
|
import { loadPrincipalPolicyBundle } from "../../../data/persistence/principalPolicy/principalPolicyPersistence.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localReadModelDetails.js","sourceRoot":"","sources":["localReadModelDetails.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,8BAA8B,EAAE,MAAM,2DAA2D,CAAC;AAC3G,OAAO,EA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AC,CACpE,CAAC;QACF,MAAM,MAAM,GAAG,MAAM,YAAY,CAC/B,KAAK,CAAC,OAAO,EACb,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;QACF,OAAO;YACL,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,IAAI;YACJ,MAAM;YACN,MAAM,EAAE;gBACN,YAAY,EAAE,MAAM,CAAC,MAAM,CACzB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,MAAM,IAAI,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,MAAM,CACnE;gBACD,WAAW,EAAE,MAAM,CAAC,MAAM,CACxB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAClE;aACF;SACF,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n OrganizationContainerGrantResponse,\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { loadContainerDisplayNamesByIds } from \"../../../data/persistence/containers/containerPersistence\";\nimport { loadOrganizationGroupDisplayNames } from \"../../../data/persistence/organizations/organizationGroupNamePersistence\";\nimport { loadOrganizationReadModelProjection } from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { loadPrincipalPolicyBundle } from \"../../../data/persistence/principalPolicy/principalPolicyPersistence\";\nimport { loadVerifiedOrganizationGroupRoles } from \"../../../data/principals/organizationGroupRoles\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationGroupPolicyHistory,\n buildOrganizationPolicyHistory,\n} from \"../policyHistory/policyHistoryReadModel\";\nimport type {\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupPolicyHistory,\n OrganizationPolicyHistory,\n OrganizationUserDetail,\n} from \"./index\";\nimport { runOrganizationPresentationRead } from \"./organizationPresentationAccessState\";\n\ninterface LocalReadModelInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\ntype PolicyPrincipalType = ReferencedPrincipalStateResponse[\"principalType\"];\n\nconst DISPLAY_NAME_BATCH_SIZE = 400;\n\nfunction uniqueContainerIds(\n grants: readonly OrganizationContainerGrantResponse[],\n): string[] {\n return [...new Set(grants.map((grant) => grant.containerId))];\n}\n\nasync function enrichGrants(\n execSql: ExecSql,\n grants: readonly OrganizationContainerGrantResponse[],\n organizationId: string,\n): Promise<OrganizationContainerGrant[]> {\n const containerIds = uniqueContainerIds(grants);\n const groupNames = await loadOrganizationGroupDisplayNames(\n execSql,\n organizationId,\n );\n const groupRoles = await loadVerifiedOrganizationGroupRoles(\n execSql,\n organizationId,\n );\n const displayNames = new Map<string, string>();\n for (\n let index = 0;\n index < containerIds.length;\n index += DISPLAY_NAME_BATCH_SIZE\n ) {\n const batch = await loadContainerDisplayNamesByIds(\n execSql,\n containerIds.slice(index, index + DISPLAY_NAME_BATCH_SIZE),\n );\n for (const [containerId, displayName] of batch) {\n displayNames.set(containerId, displayName);\n }\n }\n return grants.map((grant) => ({\n ...grant,\n containerDisplayName: displayNames.get(grant.containerId) ?? null,\n groupName:\n grant.subjectType === \"group\"\n ? (groupRoles.get(grant.subjectId) ??\n groupNames.get(grant.subjectId) ??\n null)\n : null,\n }));\n}\n\nfunction toGroupContainer(\n grant: OrganizationContainerGrant,\n): OrganizationGroupContainer {\n return {\n accessLevel: grant.accessLevel,\n containerId: grant.containerId,\n containerDisplayName: grant.containerDisplayName,\n createdAt: grant.createdAt,\n depth: grant.depth,\n isBuiltin: grant.isBuiltin,\n metadataAccessEpoch: grant.metadataAccessEpoch,\n metadataAccessStateHash: grant.metadataAccessStateHash,\n metadataDocumentId: grant.metadataDocumentId,\n parentId: grant.parentId,\n updatedAt: grant.updatedAt,\n };\n}\n\n/**\n * The groups a user belongs to is exactly the set naming them as a member.\n *\n * This used to be a breadth-first walk over group-in-group edges. Groups\n * contain only users now, so the walk had no second level to visit.\n */\nfunction reachableGroupIds(input: {\n readonly edges: ReadonlyArray<{\n readonly groupId: string;\n readonly userId: string;\n }>;\n readonly userId: string;\n}): Set<string> {\n return new Set(\n input.edges\n .filter((edge) => edge.userId === input.userId)\n .map((edge) => edge.groupId),\n );\n}\n\nexport async function loadLocalOrganizationContainerGrants(\n input: LocalReadModelInput,\n): Promise<OrganizationContainerGrants | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n return {\n organizationId: input.organizationId,\n grants: await enrichGrants(\n input.execSql,\n projection.grants.grants,\n input.organizationId,\n ),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupContainers(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupContainers | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const groupIsInOrganization =\n input.groupId === projection.groups.memberGroupId ||\n projection.groups.groups.some(\n (group) => group.groupId === input.groupId,\n );\n if (!groupIsInOrganization) {\n return null;\n }\n const grants = projection.grants.grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && grant.subjectId === input.groupId,\n );\n return {\n organizationId: input.organizationId,\n groupId: input.groupId,\n containers: (\n await enrichGrants(input.execSql, grants, input.organizationId)\n ).map(toGroupContainer),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupPolicyHistory(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.groupId,\n );\n if (!projectedHead) {\n return null;\n }\n\n const bundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.groupId,\n );\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationGroupPolicyHistory(bundle, input.organizationId)\n : null;\n },\n );\n}\n\nfunction policyBundleMatchesProjectedHead(\n bundle: PrincipalPolicyBundleResponse | null,\n projectedHead: {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n readonly stateHash: string;\n readonly version: number;\n },\n): bundle is PrincipalPolicyBundleResponse {\n const storedHead = bundle?.currentState;\n return Boolean(\n storedHead &&\n storedHead.principalType === projectedHead.principalType &&\n storedHead.principalId === projectedHead.principalId &&\n storedHead.stateHash === projectedHead.stateHash &&\n storedHead.version === projectedHead.version &&\n storedHead.keyEpoch === projectedHead.keyEpoch &&\n storedHead.keyFingerprint === projectedHead.keyFingerprint &&\n storedHead.memberCount === projectedHead.memberCount,\n );\n}\n\nexport async function loadLocalOrganizationPolicyHistory(\n input: LocalReadModelInput,\n): Promise<OrganizationPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"organization\" &&\n head.principalId === input.organizationId,\n );\n if (!projectedHead) {\n return null;\n }\n const bundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"organization\",\n input.organizationId,\n );\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationPolicyHistory(bundle)\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationPolicyReference(\n input: LocalReadModelInput & {\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n },\n): Promise<ReferencedPrincipalStateResponse | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const head = projection.policyHeads.find(\n (candidate) =>\n candidate.principalType === input.principalType &&\n candidate.principalId === input.principalId,\n );\n return head\n ? {\n principalType: head.principalType,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n }\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationUserDetail(\n input: LocalReadModelInput & { readonly userId: string },\n): Promise<OrganizationUserDetail | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n const user = projection?.directory.users.find(\n (candidate) => candidate.userId === input.userId,\n );\n if (!projection?.requester || !user) {\n return null;\n }\n\n const reachable = reachableGroupIds({\n edges: projection.membershipEdges,\n userId: input.userId,\n });\n const groups = projection.groups.groups\n .filter((group) => reachable.has(group.groupId))\n .map((group) => ({ ...group, nameUnreadable: false }));\n const relevantGrants = projection.grants.grants.filter(\n (grant) =>\n (grant.subjectType === \"user\" && grant.subjectId === input.userId) ||\n (grant.subjectType === \"group\" && reachable.has(grant.subjectId)),\n );\n const grants = await enrichGrants(\n input.execSql,\n relevantGrants,\n input.organizationId,\n );\n return {\n organizationId: input.organizationId,\n user,\n groups,\n grants: {\n directGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"user\" && grant.subjectId === input.userId,\n ),\n groupGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && reachable.has(grant.subjectId),\n ),\n },\n };\n },\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"localReadModelDetails.js","sourceRoot":"","sources":["localReadModelDetails.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,8BAA8B,EAAE,MAAM,mEAAmE,CAAC;AACnH,OAAO,EAAE,iCAAiC,EAAE,MAAM,0EAA0E,CAAC;AAC7H,OAAO,EAAE,mCAAmC,EAAE,MAAM,0EAA0E,CAAC;AAC/H,OAAO,EAAE,yBAAyB,EAAE,MAAM,sEAAsE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AAErG,OAAO,EACL,mCAAmC,EACnC,8BAA8B,GAC/B,MAAM,yCAAyC,CAAC;AAUjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAUxF,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC,SAAS,kBAAkB,CACzB,MAAqD;IAErD,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC;AAED,KAAK,UAAU,YAAY,CACzB,OAAgB,EAChB,MAAqD,EACrD,cAAsB;IAEtB,MAAM,YAAY,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;IAChD,MAAM,UAAU,GAAG,MAAM,iCAAiC,CACxD,OAAO,EACP,cAAc,CACf,CAAC;IACF,MAAM,UAAU,GAAG,MAAM,kCAAkC,CACzD,OAAO,EACP,cAAc,CACf,CAAC;IACF,MAAM,YAAY,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC/C,KACE,IAAI,KAAK,GAAG,CAAC,EACb,KAAK,GAAG,YAAY,CAAC,MAAM,EAC3B,KAAK,IAAI,uBAAuB,EAChC,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,8BAA8B,CAChD,OAAO,EACP,YAAY,CAA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EAAE,CACR,CAAC,KAAK,CAAC,WAAW,KAAK,MAAM,IAAI,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,MAAM,CAAC;YAClE,CAAC,KAAK,CAAC,WAAW,KAAK,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CACpE,CAAC;QACF,MAAM,MAAM,GAAG,MAAM,YAAY,CAC/B,KAAK,CAAC,OAAO,EACb,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;QACF,OAAO;YACL,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,IAAI;YACJ,MAAM;YACN,MAAM,EAAE;gBACN,YAAY,EAAE,MAAM,CAAC,MAAM,CACzB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,MAAM,IAAI,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,MAAM,CACnE;gBACD,WAAW,EAAE,MAAM,CAAC,MAAM,CACxB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAClE;aACF;SACF,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n OrganizationContainerGrantResponse,\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { loadContainerDisplayNamesByIds } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport { loadOrganizationGroupDisplayNames } from \"../../../data/persistence/organizations/organizationGroupNamePersistence\";\nimport { loadOrganizationReadModelProjection } from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { loadPrincipalPolicyBundle } from \"../../../data/persistence/principalPolicy/principalPolicyPersistence\";\nimport { loadVerifiedOrganizationGroupRoles } from \"../../../data/principals/organizationGroupRoles\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationGroupPolicyHistory,\n buildOrganizationPolicyHistory,\n} from \"../policyHistory/policyHistoryReadModel\";\nimport type {\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupPolicyHistory,\n OrganizationPolicyHistory,\n OrganizationUserDetail,\n} from \"./index\";\nimport { runOrganizationPresentationRead } from \"./organizationPresentationAccessState\";\n\ninterface LocalReadModelInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\ntype PolicyPrincipalType = ReferencedPrincipalStateResponse[\"principalType\"];\n\nconst DISPLAY_NAME_BATCH_SIZE = 400;\n\nfunction uniqueContainerIds(\n grants: readonly OrganizationContainerGrantResponse[],\n): string[] {\n return [...new Set(grants.map((grant) => grant.containerId))];\n}\n\nasync function enrichGrants(\n execSql: ExecSql,\n grants: readonly OrganizationContainerGrantResponse[],\n organizationId: string,\n): Promise<OrganizationContainerGrant[]> {\n const containerIds = uniqueContainerIds(grants);\n const groupNames = await loadOrganizationGroupDisplayNames(\n execSql,\n organizationId,\n );\n const groupRoles = await loadVerifiedOrganizationGroupRoles(\n execSql,\n organizationId,\n );\n const displayNames = new Map<string, string>();\n for (\n let index = 0;\n index < containerIds.length;\n index += DISPLAY_NAME_BATCH_SIZE\n ) {\n const batch = await loadContainerDisplayNamesByIds(\n execSql,\n containerIds.slice(index, index + DISPLAY_NAME_BATCH_SIZE),\n );\n for (const [containerId, displayName] of batch) {\n displayNames.set(containerId, displayName);\n }\n }\n return grants.map((grant) => ({\n ...grant,\n containerDisplayName: displayNames.get(grant.containerId) ?? null,\n groupName:\n grant.subjectType === \"group\"\n ? (groupRoles.get(grant.subjectId) ??\n groupNames.get(grant.subjectId) ??\n null)\n : null,\n }));\n}\n\nfunction toGroupContainer(\n grant: OrganizationContainerGrant,\n): OrganizationGroupContainer {\n return {\n accessLevel: grant.accessLevel,\n containerId: grant.containerId,\n containerDisplayName: grant.containerDisplayName,\n createdAt: grant.createdAt,\n depth: grant.depth,\n isBuiltin: grant.isBuiltin,\n metadataAccessEpoch: grant.metadataAccessEpoch,\n metadataAccessStateHash: grant.metadataAccessStateHash,\n metadataDocumentId: grant.metadataDocumentId,\n parentId: grant.parentId,\n updatedAt: grant.updatedAt,\n };\n}\n\n/**\n * The groups a user belongs to is exactly the set naming them as a member.\n *\n * This used to be a breadth-first walk over group-in-group edges. Groups\n * contain only users now, so the walk had no second level to visit.\n */\nfunction reachableGroupIds(input: {\n readonly edges: ReadonlyArray<{\n readonly groupId: string;\n readonly userId: string;\n }>;\n readonly userId: string;\n}): Set<string> {\n return new Set(\n input.edges\n .filter((edge) => edge.userId === input.userId)\n .map((edge) => edge.groupId),\n );\n}\n\nexport async function loadLocalOrganizationContainerGrants(\n input: LocalReadModelInput,\n): Promise<OrganizationContainerGrants | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n return {\n organizationId: input.organizationId,\n grants: await enrichGrants(\n input.execSql,\n projection.grants.grants,\n input.organizationId,\n ),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupContainers(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupContainers | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const groupIsInOrganization =\n input.groupId === projection.groups.memberGroupId ||\n projection.groups.groups.some(\n (group) => group.groupId === input.groupId,\n );\n if (!groupIsInOrganization) {\n return null;\n }\n const grants = projection.grants.grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && grant.subjectId === input.groupId,\n );\n return {\n organizationId: input.organizationId,\n groupId: input.groupId,\n containers: (\n await enrichGrants(input.execSql, grants, input.organizationId)\n ).map(toGroupContainer),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupPolicyHistory(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.groupId,\n );\n if (!projectedHead) {\n return null;\n }\n\n const bundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.groupId,\n );\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationGroupPolicyHistory(bundle, input.organizationId)\n : null;\n },\n );\n}\n\nfunction policyBundleMatchesProjectedHead(\n bundle: PrincipalPolicyBundleResponse | null,\n projectedHead: {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n readonly stateHash: string;\n readonly version: number;\n },\n): bundle is PrincipalPolicyBundleResponse {\n const storedHead = bundle?.currentState;\n return Boolean(\n storedHead &&\n storedHead.principalType === projectedHead.principalType &&\n storedHead.principalId === projectedHead.principalId &&\n storedHead.stateHash === projectedHead.stateHash &&\n storedHead.version === projectedHead.version &&\n storedHead.keyEpoch === projectedHead.keyEpoch &&\n storedHead.keyFingerprint === projectedHead.keyFingerprint &&\n storedHead.memberCount === projectedHead.memberCount,\n );\n}\n\nexport async function loadLocalOrganizationPolicyHistory(\n input: LocalReadModelInput,\n): Promise<OrganizationPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"organization\" &&\n head.principalId === input.organizationId,\n );\n if (!projectedHead) {\n return null;\n }\n const bundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"organization\",\n input.organizationId,\n );\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationPolicyHistory(bundle)\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationPolicyReference(\n input: LocalReadModelInput & {\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n },\n): Promise<ReferencedPrincipalStateResponse | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const head = projection.policyHeads.find(\n (candidate) =>\n candidate.principalType === input.principalType &&\n candidate.principalId === input.principalId,\n );\n return head\n ? {\n principalType: head.principalType,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n }\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationUserDetail(\n input: LocalReadModelInput & { readonly userId: string },\n): Promise<OrganizationUserDetail | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n const user = projection?.directory.users.find(\n (candidate) => candidate.userId === input.userId,\n );\n if (!projection?.requester || !user) {\n return null;\n }\n\n const reachable = reachableGroupIds({\n edges: projection.membershipEdges,\n userId: input.userId,\n });\n const groups = projection.groups.groups\n .filter((group) => reachable.has(group.groupId))\n .map((group) => ({ ...group, nameUnreadable: false }));\n const relevantGrants = projection.grants.grants.filter(\n (grant) =>\n (grant.subjectType === \"user\" && grant.subjectId === input.userId) ||\n (grant.subjectType === \"group\" && reachable.has(grant.subjectId)),\n );\n const grants = await enrichGrants(\n input.execSql,\n relevantGrants,\n input.organizationId,\n );\n return {\n organizationId: input.organizationId,\n user,\n groups,\n grants: {\n directGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"user\" && grant.subjectId === input.userId,\n ),\n groupGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && reachable.has(grant.subjectId),\n ),\n },\n };\n },\n );\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ensureContainerTables, loadContainers, saveContainer, } from "../../data/persistence/
|
|
1
|
+
import { ensureContainerTables, loadContainers, saveContainer, } from "../../data/persistence/container-contents/containerPersistence.js";
|
|
2
2
|
import { createExecSql, runSerializedSqlMutation, } from "../../data/sqlite/sqlSchema.js";
|
|
3
3
|
async function bootstrapRootContainerFromExecSql(execSql) {
|
|
4
4
|
return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bootstrapRootContainer.js","sourceRoot":"","sources":["bootstrapRootContainer.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,aAAa,GACd,MAAM,
|
|
1
|
+
{"version":3,"file":"bootstrapRootContainer.js","sourceRoot":"","sources":["bootstrapRootContainer.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,aAAa,GACd,MAAM,gEAAgE,CAAC;AACxE,OAAO,EACL,aAAa,EAGb,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AAOrC,KAAK,UAAU,iCAAiC,CAC9C,OAAgB;IAEhB,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QAC/D,MAAM,qBAAqB,CAAC,aAAa,CAAC,CAAC;QAC3C,MAAM,UAAU,GAAG,MAAM,cAAc,CAAC,aAAa,CAAC,CAAC;QACvD,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAC1B,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,QAAQ,KAAK,IAAI,IAAI,CAAC,SAAS,CAAC,UAAU,CACpE,CAAC;QAEF,IAAI,IAAI,EAAE,CAAC;YACT,OAAO;gBACL,WAAW,EAAE,IAAI,CAAC,EAAE;gBACpB,OAAO,EAAE,KAAK;aACf,CAAC;QACJ,CAAC;QAED,MAAM,WAAW,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;QACxC,MAAM,aAAa,CAAC,aAAa,EAAE;YACjC,EAAE,EAAE,WAAW;YACf,oBAAoB,EAAE,OAAO;YAC7B,cAAc,EAAE,EAAE;YAClB,QAAQ,EAAE,IAAI;YACd,kBAAkB,EAAE,IAAI;YACxB,IAAI,EAAE,GAAG;YACT,IAAI,EAAE,IAAI;SACX,CAAC,CAAC;QAEH,OAAO;YACL,WAAW;YACX,OAAO,EAAE,IAAI;SACd,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAAkC;IAElC,OAAO,iCAAiC,CACtC,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,aAAa,CAAC,KAAK,CAAC,CAC3D,CAAC;AACJ,CAAC","sourcesContent":["import {\n ensureContainerTables,\n loadContainers,\n saveContainer,\n} from \"../../data/persistence/container-contents/containerPersistence\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\n\ninterface RootContainerBootstrapResult {\n containerId: string;\n created: boolean;\n}\n\nasync function bootstrapRootContainerFromExecSql(\n execSql: ExecSql,\n): Promise<RootContainerBootstrapResult> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureContainerTables(lockedExecSql);\n const containers = await loadContainers(lockedExecSql);\n const root = containers.find(\n (container) => container.parentId === null && !container.systemSlot,\n );\n\n if (root) {\n return {\n containerId: root.id,\n created: false,\n };\n }\n\n const containerId = crypto.randomUUID();\n await saveContainer(lockedExecSql, {\n id: containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: \"\",\n parentId: null,\n metadataDocumentId: null,\n name: \"/\",\n icon: null,\n });\n\n return {\n containerId,\n created: true,\n };\n });\n}\n\nexport async function bootstrapRootContainer(\n input: ExecSql | ExecSqlClientLike,\n): Promise<RootContainerBootstrapResult> {\n return bootstrapRootContainerFromExecSql(\n typeof input === \"function\" ? input : createExecSql(input),\n );\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { base64ToBytes } from "../../internal/encoding/index.js";
|
|
2
|
-
import { createInitializedContainerMetadataDocument } from "../../data/containers/containerMetadataDocument.js";
|
|
3
2
|
import { deriveStableDocumentId } from "../../data/documents/shared/stableDocumentId.js";
|
|
3
|
+
import { createInitializedContainerMetadataDocument } from "../container-contents/metadata/containerMetadataDocument.js";
|
|
4
4
|
import { deriveContainerSystemSlot, } from "../container-contents/systemSlot.js";
|
|
5
5
|
import { buildContainerCreatePlan, childContainerWriterProjectionFromCreatePlan, } from "../containers/child/create/index.js";
|
|
6
6
|
import { buildRootContainerCreatePlan, rootContainerWriterProjectionFromCreatePlan, } from "../containers/root/create.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provisioningBootstrapBuilders.js","sourceRoot":"","sources":["provisioningBootstrapBuilders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,0CAA0C,EAAE,MAAM,iDAAiD,CAAC;AAC7G,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EAEL,yBAAyB,GAC1B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,wBAAwB,EACxB,4CAA4C,GAC7C,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,4BAA4B,EAC5B,2CAA2C,GAC5C,MAAM,2BAA2B,CAAC;AAEnC,OAA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E,MAAM,+BAA+B,CAAC;gBACjD,MAAM,EAAE,KAAK,CAAC,MAAM;gBACpB,mBAAmB,EAAE,uBAAuB;gBAC5C,aAAa,EAAE,KAAK,CAAC,SAAS,CAAC,aAAa;gBAC5C,oBAAoB,EAAE,oBAAoB;aAC3C,CAAC;SACH;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { CreateOrganizationGroupRequest } from \"@tearleads/validators/request\";\nimport { createInitializedContainerMetadataDocument } from \"../../data/containers/containerMetadataDocument\";\nimport { deriveStableDocumentId } from \"../../data/documents/shared/stableDocumentId\";\nimport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"../container-contents/systemSlot\";\nimport {\n buildContainerCreatePlan,\n childContainerWriterProjectionFromCreatePlan,\n} from \"../containers/child/create\";\nimport {\n buildRootContainerCreatePlan,\n rootContainerWriterProjectionFromCreatePlan,\n} from \"../containers/root/create\";\nimport type { resolveDocumentCreateAuthor } from \"../documents/author\";\nimport { buildMaterializedDocumentCreatePlan } from \"../documents/create\";\nimport { buildInitialDocumentSyncRequest } from \"../documents/sync/initialSync\";\nimport { getOrganizationProfileDocumentLocalId } from \"../organizations/organizationProfile\";\nimport {\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n getRosterProfileDocumentLocalId,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n} from \"../organizations/rosterProfileContainer\";\nimport type {\n InitialOrganizationMetadataBootstrap,\n InitialRootContainerCreatePlan,\n InitialRosterProfileBootstrap,\n InitialSystemContainerBootstrap,\n InitialSystemContainerCreatePlan,\n} from \"./organizationProvisioningArtifacts\";\nimport {\n buildProvisionedOrganizationProfile,\n buildProvisionedRosterProfile,\n} from \"./provisionedProfileDocument\";\nimport { verifiedPrincipalPolicyFromInitialGroupRequest } from \"./registrationPrincipalPolicyPersistence\";\nimport type { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\ntype InitialRootContainerProjection = ReturnType<\n typeof rootContainerWriterProjectionFromCreatePlan\n>;\n\n/**\n * An app-owned system container to provision atomically with a new organization\n * (e.g. a trash bin). The client-sdk is agnostic to what these are:\n * the caller (the app, which owns the mini-app slot namespaces) declares each\n * one, and the provisioning path derives its per-user system slot, builds a\n * signed Admins-scoped child of root, and links it into the same transaction as\n * the rest of the organization bootstrap. The behavioral rules that govern a\n * system container are resolved client-side by slot, so provisioning needs only\n * the slot definition, display name, and icon — no rules travel to the server.\n */\nexport interface ProvisionedSystemContainerSpec {\n readonly slotDefinition: ContainerSystemSlotDefinition;\n readonly name: string;\n readonly icon: string | null;\n}\n\ninterface InitialOrganizationMetadataBootstrapInput {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n containerId: string;\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n organizationProfileName?: string | undefined;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n targetSecretKey: Uint8Array;\n}\n\ninterface InitialRosterProfileInput {\n author: InitialOrganizationMetadataBootstrapInput[\"author\"];\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n encapsulationPublicKey: Uint8Array;\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n rosterProfileNickname?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\ninterface ProvisionedChildContainerCore {\n containerId: string;\n containerMetadataDocument: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >;\n containerMetadataInitialUpdate: Uint8Array;\n containerPlan: InitialSystemContainerCreatePlan;\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n containerRequest: {\n systemSlot: ContainerSystemSlot;\n container: InitialSystemContainerCreatePlan[\"plan\"][\"request\"];\n initialMetadataSync: Awaited<\n ReturnType<typeof buildInitialDocumentSyncRequest>\n >;\n metadataDocument: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >[\"plan\"][\"request\"];\n };\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n systemSlot: ContainerSystemSlot;\n}\n\n/**\n * The shared spine of every provisioned system child container: mint the\n * container and its metadata document under root, project the writer view,\n * and assemble the create request. Callers differ only in slot derivation,\n * display metadata, authorizing policies, an optional managed read grant, and\n * what they attach afterwards (roster/org profile documents).\n */\nasync function buildProvisionedChildContainerCore(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n containerId?: string | undefined;\n icon: string | null;\n managedPrincipalGrant?: Parameters<\n typeof buildContainerCreatePlan\n >[0][\"managedPrincipalGrant\"];\n name: string;\n principalPolicies: Parameters<\n typeof buildContainerCreatePlan\n >[0][\"principalPolicies\"];\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n systemSlot: ContainerSystemSlot;\n targetSecretKey: Uint8Array;\n independentMetadataGroups?: {\n adminGroup: CreateOrganizationGroupRequest;\n memberGroup: CreateOrganizationGroupRequest;\n };\n}): Promise<ProvisionedChildContainerCore> {\n const containerId = input.containerId ?? crypto.randomUUID();\n const { initialUpdate } = await createInitializedContainerMetadataDocument(\n containerId,\n {\n icon: input.icon,\n name: input.name,\n },\n );\n const containerKey = crypto.getRandomValues(new Uint8Array(32));\n const containerPlan: InitialSystemContainerCreatePlan = {\n containerKey,\n plan: input.independentMetadataGroups\n ? (\n await buildRootContainerCreatePlan({\n ...input.independentMetadataGroups,\n author: input.author,\n containerId,\n containerKey,\n metadataDocumentId: containerId,\n systemSlot: input.systemSlot,\n recipientEncapsulationPublicKey: base64ToBytes(\n input.independentMetadataGroups.adminGroup.initialGroupPolicy\n .state.encapsulationPublicKey,\n ),\n })\n ).plan\n : await buildContainerCreatePlan({\n author: input.author,\n containerId,\n containerKey,\n ...(input.managedPrincipalGrant\n ? { managedPrincipalGrant: input.managedPrincipalGrant }\n : {}),\n metadataDocumentId: containerId,\n systemSlot: input.systemSlot,\n parentProjection: input.rootContainerProjection,\n principalPolicies: input.principalPolicies,\n }),\n };\n const containerProjection = input.independentMetadataGroups\n ? rootContainerWriterProjectionFromCreatePlan(containerPlan.plan)\n : childContainerWriterProjectionFromCreatePlan({\n materializedPlan: containerPlan,\n parentProjection: input.rootContainerProjection,\n });\n const knownContainerKeks = new Map([\n [containerPlan.plan.containerKeyEpochId, containerPlan.containerKey],\n ]);\n const containerMetadataDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection,\n documentId: containerPlan.plan.metadataDocumentId,\n knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n const initialMetadataSync = await buildInitialDocumentSyncRequest({\n author: input.author,\n containerProjection,\n initialUpdate,\n materializedDocument: containerMetadataDocument,\n });\n return {\n containerId,\n containerMetadataDocument,\n containerMetadataInitialUpdate: initialUpdate,\n containerPlan,\n containerProjection,\n containerRequest: {\n systemSlot: input.systemSlot,\n container: containerPlan.plan.request,\n initialMetadataSync,\n metadataDocument: containerMetadataDocument.plan.request,\n },\n knownContainerKeks,\n systemSlot: input.systemSlot,\n };\n}\n\nexport async function buildInitialRosterProfileBootstrap(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n encapsulationPublicKey: Uint8Array;\n initialAdminGroup: CreateOrganizationGroupRequest;\n rosterProfileNickname?: string | undefined;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n targetSecretKey: Uint8Array;\n}): Promise<InitialRosterProfileBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n icon: null,\n name: ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n principalPolicies: [\n await verifiedPrincipalPolicyFromInitialGroupRequest(\n input.initialAdminGroup,\n ),\n ],\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveOrganizationRosterProfileContainerSystemSlot({\n organizationId: input.author.organizationId,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n const { profile, rosterProfileDocument } = await buildInitialRosterProfile({\n author: input.author,\n containerProjection: core.containerProjection,\n encapsulationPublicKey: input.encapsulationPublicKey,\n knownContainerKeks: core.knownContainerKeks,\n rosterProfileNickname: input.rosterProfileNickname,\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n profileDocument: rosterProfileDocument,\n profileDocumentInitialUpdate: profile.initialUpdate,\n profileDocumentRequest: profile.request,\n systemSlot: core.systemSlot,\n };\n}\n\nasync function buildInitialRosterProfile(input: InitialRosterProfileInput) {\n const rosterProfileDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: input.containerProjection,\n documentId: await deriveStableDocumentId(\n getRosterProfileDocumentLocalId({\n organizationId: input.author.organizationId,\n userId: input.author.signerUserId,\n }),\n ),\n knownContainerKeks: input.knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n const profile = await buildProvisionedRosterProfile({\n author: input.author,\n containerProjection: input.containerProjection,\n encapsulationPublicKey: input.encapsulationPublicKey,\n materializedDocument: rosterProfileDocument,\n nickname: input.rosterProfileNickname,\n });\n return { profile, rosterProfileDocument };\n}\n\nexport async function buildInitialSystemContainerBootstrap(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n initialAdminGroup: CreateOrganizationGroupRequest;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n signingPrivateKey: Uint8Array;\n spec: ProvisionedSystemContainerSpec;\n targetSecretKey: Uint8Array;\n}): Promise<InitialSystemContainerBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n icon: input.spec.icon,\n name: input.spec.name,\n principalPolicies: [\n await verifiedPrincipalPolicyFromInitialGroupRequest(\n input.initialAdminGroup,\n ),\n ],\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveContainerSystemSlot({\n definition: input.spec.slotDefinition,\n secretKey: input.signingPrivateKey,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n icon: input.spec.icon,\n name: input.spec.name,\n systemSlot: core.systemSlot,\n };\n}\n\nfunction stableOrganizationProfileId(organizationId: string): Promise<string> {\n return deriveStableDocumentId(\n getOrganizationProfileDocumentLocalId({ organizationId }),\n );\n}\n\nasync function buildInitialOrganizationProfile(input: {\n author: InitialOrganizationMetadataBootstrapInput[\"author\"];\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n organizationProfileName?: string | undefined;\n targetSecretKey: Uint8Array;\n}) {\n const organizationProfileDocument = await buildMaterializedDocumentCreatePlan(\n {\n author: input.author,\n containerProjection: input.containerProjection,\n documentId: await stableOrganizationProfileId(\n input.author.organizationId,\n ),\n knownContainerKeks: input.knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n },\n );\n const profile = await buildProvisionedOrganizationProfile({\n author: input.author,\n containerProjection: input.containerProjection,\n materializedDocument: organizationProfileDocument,\n name: input.organizationProfileName,\n });\n return { organizationProfileDocument, profile };\n}\n\n/**\n * Organization labels use an independent system root with Admins/admin and\n * Members/read grants. Personal root shares and rotations cannot expose or\n * strand organization metadata; Members changes still rotate its own KEK.\n */\nexport async function buildInitialOrganizationMetadataBootstrap(\n input: InitialOrganizationMetadataBootstrapInput,\n): Promise<InitialOrganizationMetadataBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n containerId: input.containerId,\n icon: null,\n independentMetadataGroups: {\n adminGroup: input.initialAdminGroup,\n memberGroup: input.initialMemberGroup,\n },\n name: ORGANIZATION_METADATA_CONTAINER_NAME,\n // Both reserved groups receive explicit grants on the independent root.\n principalPolicies: await Promise.all([\n verifiedPrincipalPolicyFromInitialGroupRequest(input.initialAdminGroup),\n verifiedPrincipalPolicyFromInitialGroupRequest(input.initialMemberGroup),\n ]),\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.author.organizationId,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n const { organizationProfileDocument, profile } =\n await buildInitialOrganizationProfile({\n author: input.author,\n containerProjection: core.containerProjection,\n knownContainerKeks: core.knownContainerKeks,\n organizationProfileName: input.organizationProfileName,\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n organizationProfileDocument,\n organizationProfileDocumentRequest: profile.request,\n organizationProfileSnapshot: profile.snapshot,\n systemSlot: core.systemSlot,\n };\n}\n\nexport async function buildInitialRootProvisioning(input: {\n adminGroup: CreateOrganizationGroupRequest;\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n bootstrap: Awaited<ReturnType<typeof createInitialRootMetadataBootstrap>>;\n recipientEncapsulationPublicKey: Uint8Array;\n rootContainerId: string;\n targetSecretKey: Uint8Array;\n}) {\n const rootContainer = await buildRootContainerCreatePlan({\n adminGroup: input.adminGroup,\n author: input.author,\n containerId: input.rootContainerId,\n metadataDocumentId: input.bootstrap.metadataDocumentId,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n });\n const rootContainerProjection = rootContainerWriterProjectionFromCreatePlan(\n rootContainer.plan,\n );\n const rootMetadataDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: rootContainerProjection,\n documentId: input.bootstrap.metadataDocumentId,\n knownContainerKeks: new Map([\n [rootContainer.plan.containerKeyEpochId, rootContainer.containerKey],\n ]),\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n return {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest: {\n ...rootMetadataDocument.plan.request,\n initialSync: await buildInitialDocumentSyncRequest({\n author: input.author,\n containerProjection: rootContainerProjection,\n initialUpdate: input.bootstrap.initialUpdate,\n materializedDocument: rootMetadataDocument,\n }),\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provisioningBootstrapBuilders.js","sourceRoot":"","sources":["provisioningBootstrapBuilders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EAAE,0CAA0C,EAAE,MAAM,0DAA0D,CAAC;AACtH,OAAO,EAEL,yBAAyB,GAC1B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,wBAAwB,EACxB,4CAA4C,GAC7C,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,4BAA4B,EAC5B,2CAA2C,GAC5C,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,mCAAmC,EAAE,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,EAAE,qCAAqC,EAAE,MAAM,sCAAsC,CAAC;AAC7F,OAAO,EACL,6CAA6C,EAC7C,kDAAkD,EAClD,+BAA+B,EAC/B,oCAAoC,EACpC,0CAA0C,GAC3C,MAAM,yCAAyC,CAAC;AAQjD,OAAO,EACL,mCAAmC,EACnC,6BAA6B,GAC9B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,8CA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,CAAC,KAAK,UAAU,4BAA4B,CAAC,KAOlD;IACC,MAAM,aAAa,GAAG,MAAM,4BAA4B,CAAC;QACvD,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,WAAW,EAAE,KAAK,CAAC,eAAe;QAClC,kBAAkB,EAAE,KAAK,CAAC,SAAS,CAAC,kBAAkB;QACtD,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACH,MAAM,uBAAuB,GAAG,2CAA2C,CACzE,aAAa,CAAC,IAAI,CACnB,CAAC;IACF,MAAM,oBAAoB,GAAG,MAAM,mCAAmC,CAAC;QACrE,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,mBAAmB,EAAE,uBAAuB;QAC5C,UAAU,EAAE,KAAK,CAAC,SAAS,CAAC,kBAAkB;QAC9C,kBAAkB,EAAE,IAAI,GAAG,CAAC;YAC1B,CAAC,aAAa,CAAC,IAAI,CAAC,mBAAmB,EAAE,aAAa,CAAC,YAAY,CAAC;SACrE,CAAC;QACF,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,sBAAsB,EAAE,IAAI;KAC7B,CAAC,CAAC;IACH,OAAO;QACL,aAAa;QACb,uBAAuB;QACvB,oBAAoB;QACpB,2BAA2B,EAAE;YAC3B,GAAG,oBAAoB,CAAC,IAAI,CAAC,OAAO;YACpC,WAAW,EAAE,MAAM,+BAA+B,CAAC;gBACjD,MAAM,EAAE,KAAK,CAAC,MAAM;gBACpB,mBAAmB,EAAE,uBAAuB;gBAC5C,aAAa,EAAE,KAAK,CAAC,SAAS,CAAC,aAAa;gBAC5C,oBAAoB,EAAE,oBAAoB;aAC3C,CAAC;SACH;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { CreateOrganizationGroupRequest } from \"@tearleads/validators/request\";\nimport { deriveStableDocumentId } from \"../../data/documents/shared/stableDocumentId\";\nimport { createInitializedContainerMetadataDocument } from \"../container-contents/metadata/containerMetadataDocument\";\nimport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"../container-contents/systemSlot\";\nimport {\n buildContainerCreatePlan,\n childContainerWriterProjectionFromCreatePlan,\n} from \"../containers/child/create\";\nimport {\n buildRootContainerCreatePlan,\n rootContainerWriterProjectionFromCreatePlan,\n} from \"../containers/root/create\";\nimport type { resolveDocumentCreateAuthor } from \"../documents/author\";\nimport { buildMaterializedDocumentCreatePlan } from \"../documents/create\";\nimport { buildInitialDocumentSyncRequest } from \"../documents/sync/initialSync\";\nimport { getOrganizationProfileDocumentLocalId } from \"../organizations/organizationProfile\";\nimport {\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n getRosterProfileDocumentLocalId,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n} from \"../organizations/rosterProfileContainer\";\nimport type {\n InitialOrganizationMetadataBootstrap,\n InitialRootContainerCreatePlan,\n InitialRosterProfileBootstrap,\n InitialSystemContainerBootstrap,\n InitialSystemContainerCreatePlan,\n} from \"./organizationProvisioningArtifacts\";\nimport {\n buildProvisionedOrganizationProfile,\n buildProvisionedRosterProfile,\n} from \"./provisionedProfileDocument\";\nimport { verifiedPrincipalPolicyFromInitialGroupRequest } from \"./registrationPrincipalPolicyPersistence\";\nimport type { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\ntype InitialRootContainerProjection = ReturnType<\n typeof rootContainerWriterProjectionFromCreatePlan\n>;\n\n/**\n * An app-owned system container to provision atomically with a new organization\n * (e.g. a trash bin). The client-sdk is agnostic to what these are:\n * the caller (the app, which owns the mini-app slot namespaces) declares each\n * one, and the provisioning path derives its per-user system slot, builds a\n * signed Admins-scoped child of root, and links it into the same transaction as\n * the rest of the organization bootstrap. The behavioral rules that govern a\n * system container are resolved client-side by slot, so provisioning needs only\n * the slot definition, display name, and icon — no rules travel to the server.\n */\nexport interface ProvisionedSystemContainerSpec {\n readonly slotDefinition: ContainerSystemSlotDefinition;\n readonly name: string;\n readonly icon: string | null;\n}\n\ninterface InitialOrganizationMetadataBootstrapInput {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n containerId: string;\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n organizationProfileName?: string | undefined;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n targetSecretKey: Uint8Array;\n}\n\ninterface InitialRosterProfileInput {\n author: InitialOrganizationMetadataBootstrapInput[\"author\"];\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n encapsulationPublicKey: Uint8Array;\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n rosterProfileNickname?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\ninterface ProvisionedChildContainerCore {\n containerId: string;\n containerMetadataDocument: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >;\n containerMetadataInitialUpdate: Uint8Array;\n containerPlan: InitialSystemContainerCreatePlan;\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n containerRequest: {\n systemSlot: ContainerSystemSlot;\n container: InitialSystemContainerCreatePlan[\"plan\"][\"request\"];\n initialMetadataSync: Awaited<\n ReturnType<typeof buildInitialDocumentSyncRequest>\n >;\n metadataDocument: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >[\"plan\"][\"request\"];\n };\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n systemSlot: ContainerSystemSlot;\n}\n\n/**\n * The shared spine of every provisioned system child container: mint the\n * container and its metadata document under root, project the writer view,\n * and assemble the create request. Callers differ only in slot derivation,\n * display metadata, authorizing policies, an optional managed read grant, and\n * what they attach afterwards (roster/org profile documents).\n */\nasync function buildProvisionedChildContainerCore(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n containerId?: string | undefined;\n icon: string | null;\n managedPrincipalGrant?: Parameters<\n typeof buildContainerCreatePlan\n >[0][\"managedPrincipalGrant\"];\n name: string;\n principalPolicies: Parameters<\n typeof buildContainerCreatePlan\n >[0][\"principalPolicies\"];\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n systemSlot: ContainerSystemSlot;\n targetSecretKey: Uint8Array;\n independentMetadataGroups?: {\n adminGroup: CreateOrganizationGroupRequest;\n memberGroup: CreateOrganizationGroupRequest;\n };\n}): Promise<ProvisionedChildContainerCore> {\n const containerId = input.containerId ?? crypto.randomUUID();\n const { initialUpdate } = await createInitializedContainerMetadataDocument(\n containerId,\n {\n icon: input.icon,\n name: input.name,\n },\n );\n const containerKey = crypto.getRandomValues(new Uint8Array(32));\n const containerPlan: InitialSystemContainerCreatePlan = {\n containerKey,\n plan: input.independentMetadataGroups\n ? (\n await buildRootContainerCreatePlan({\n ...input.independentMetadataGroups,\n author: input.author,\n containerId,\n containerKey,\n metadataDocumentId: containerId,\n systemSlot: input.systemSlot,\n recipientEncapsulationPublicKey: base64ToBytes(\n input.independentMetadataGroups.adminGroup.initialGroupPolicy\n .state.encapsulationPublicKey,\n ),\n })\n ).plan\n : await buildContainerCreatePlan({\n author: input.author,\n containerId,\n containerKey,\n ...(input.managedPrincipalGrant\n ? { managedPrincipalGrant: input.managedPrincipalGrant }\n : {}),\n metadataDocumentId: containerId,\n systemSlot: input.systemSlot,\n parentProjection: input.rootContainerProjection,\n principalPolicies: input.principalPolicies,\n }),\n };\n const containerProjection = input.independentMetadataGroups\n ? rootContainerWriterProjectionFromCreatePlan(containerPlan.plan)\n : childContainerWriterProjectionFromCreatePlan({\n materializedPlan: containerPlan,\n parentProjection: input.rootContainerProjection,\n });\n const knownContainerKeks = new Map([\n [containerPlan.plan.containerKeyEpochId, containerPlan.containerKey],\n ]);\n const containerMetadataDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection,\n documentId: containerPlan.plan.metadataDocumentId,\n knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n const initialMetadataSync = await buildInitialDocumentSyncRequest({\n author: input.author,\n containerProjection,\n initialUpdate,\n materializedDocument: containerMetadataDocument,\n });\n return {\n containerId,\n containerMetadataDocument,\n containerMetadataInitialUpdate: initialUpdate,\n containerPlan,\n containerProjection,\n containerRequest: {\n systemSlot: input.systemSlot,\n container: containerPlan.plan.request,\n initialMetadataSync,\n metadataDocument: containerMetadataDocument.plan.request,\n },\n knownContainerKeks,\n systemSlot: input.systemSlot,\n };\n}\n\nexport async function buildInitialRosterProfileBootstrap(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n encapsulationPublicKey: Uint8Array;\n initialAdminGroup: CreateOrganizationGroupRequest;\n rosterProfileNickname?: string | undefined;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n targetSecretKey: Uint8Array;\n}): Promise<InitialRosterProfileBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n icon: null,\n name: ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n principalPolicies: [\n await verifiedPrincipalPolicyFromInitialGroupRequest(\n input.initialAdminGroup,\n ),\n ],\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveOrganizationRosterProfileContainerSystemSlot({\n organizationId: input.author.organizationId,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n const { profile, rosterProfileDocument } = await buildInitialRosterProfile({\n author: input.author,\n containerProjection: core.containerProjection,\n encapsulationPublicKey: input.encapsulationPublicKey,\n knownContainerKeks: core.knownContainerKeks,\n rosterProfileNickname: input.rosterProfileNickname,\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n profileDocument: rosterProfileDocument,\n profileDocumentInitialUpdate: profile.initialUpdate,\n profileDocumentRequest: profile.request,\n systemSlot: core.systemSlot,\n };\n}\n\nasync function buildInitialRosterProfile(input: InitialRosterProfileInput) {\n const rosterProfileDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: input.containerProjection,\n documentId: await deriveStableDocumentId(\n getRosterProfileDocumentLocalId({\n organizationId: input.author.organizationId,\n userId: input.author.signerUserId,\n }),\n ),\n knownContainerKeks: input.knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n const profile = await buildProvisionedRosterProfile({\n author: input.author,\n containerProjection: input.containerProjection,\n encapsulationPublicKey: input.encapsulationPublicKey,\n materializedDocument: rosterProfileDocument,\n nickname: input.rosterProfileNickname,\n });\n return { profile, rosterProfileDocument };\n}\n\nexport async function buildInitialSystemContainerBootstrap(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n initialAdminGroup: CreateOrganizationGroupRequest;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n signingPrivateKey: Uint8Array;\n spec: ProvisionedSystemContainerSpec;\n targetSecretKey: Uint8Array;\n}): Promise<InitialSystemContainerBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n icon: input.spec.icon,\n name: input.spec.name,\n principalPolicies: [\n await verifiedPrincipalPolicyFromInitialGroupRequest(\n input.initialAdminGroup,\n ),\n ],\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveContainerSystemSlot({\n definition: input.spec.slotDefinition,\n secretKey: input.signingPrivateKey,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n icon: input.spec.icon,\n name: input.spec.name,\n systemSlot: core.systemSlot,\n };\n}\n\nfunction stableOrganizationProfileId(organizationId: string): Promise<string> {\n return deriveStableDocumentId(\n getOrganizationProfileDocumentLocalId({ organizationId }),\n );\n}\n\nasync function buildInitialOrganizationProfile(input: {\n author: InitialOrganizationMetadataBootstrapInput[\"author\"];\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n organizationProfileName?: string | undefined;\n targetSecretKey: Uint8Array;\n}) {\n const organizationProfileDocument = await buildMaterializedDocumentCreatePlan(\n {\n author: input.author,\n containerProjection: input.containerProjection,\n documentId: await stableOrganizationProfileId(\n input.author.organizationId,\n ),\n knownContainerKeks: input.knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n },\n );\n const profile = await buildProvisionedOrganizationProfile({\n author: input.author,\n containerProjection: input.containerProjection,\n materializedDocument: organizationProfileDocument,\n name: input.organizationProfileName,\n });\n return { organizationProfileDocument, profile };\n}\n\n/**\n * Organization labels use an independent system root with Admins/admin and\n * Members/read grants. Personal root shares and rotations cannot expose or\n * strand organization metadata; Members changes still rotate its own KEK.\n */\nexport async function buildInitialOrganizationMetadataBootstrap(\n input: InitialOrganizationMetadataBootstrapInput,\n): Promise<InitialOrganizationMetadataBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n containerId: input.containerId,\n icon: null,\n independentMetadataGroups: {\n adminGroup: input.initialAdminGroup,\n memberGroup: input.initialMemberGroup,\n },\n name: ORGANIZATION_METADATA_CONTAINER_NAME,\n // Both reserved groups receive explicit grants on the independent root.\n principalPolicies: await Promise.all([\n verifiedPrincipalPolicyFromInitialGroupRequest(input.initialAdminGroup),\n verifiedPrincipalPolicyFromInitialGroupRequest(input.initialMemberGroup),\n ]),\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.author.organizationId,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n const { organizationProfileDocument, profile } =\n await buildInitialOrganizationProfile({\n author: input.author,\n containerProjection: core.containerProjection,\n knownContainerKeks: core.knownContainerKeks,\n organizationProfileName: input.organizationProfileName,\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n organizationProfileDocument,\n organizationProfileDocumentRequest: profile.request,\n organizationProfileSnapshot: profile.snapshot,\n systemSlot: core.systemSlot,\n };\n}\n\nexport async function buildInitialRootProvisioning(input: {\n adminGroup: CreateOrganizationGroupRequest;\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n bootstrap: Awaited<ReturnType<typeof createInitialRootMetadataBootstrap>>;\n recipientEncapsulationPublicKey: Uint8Array;\n rootContainerId: string;\n targetSecretKey: Uint8Array;\n}) {\n const rootContainer = await buildRootContainerCreatePlan({\n adminGroup: input.adminGroup,\n author: input.author,\n containerId: input.rootContainerId,\n metadataDocumentId: input.bootstrap.metadataDocumentId,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n });\n const rootContainerProjection = rootContainerWriterProjectionFromCreatePlan(\n rootContainer.plan,\n );\n const rootMetadataDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: rootContainerProjection,\n documentId: input.bootstrap.metadataDocumentId,\n knownContainerKeks: new Map([\n [rootContainer.plan.containerKeyEpochId, rootContainer.containerKey],\n ]),\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n return {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest: {\n ...rootMetadataDocument.plan.request,\n initialSync: await buildInitialDocumentSyncRequest({\n author: input.author,\n containerProjection: rootContainerProjection,\n initialUpdate: input.bootstrap.initialUpdate,\n materializedDocument: rootMetadataDocument,\n }),\n },\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createInitializedContainerMetadataDocument } from "
|
|
1
|
+
import { createInitializedContainerMetadataDocument } from "../container-contents/metadata/containerMetadataDocument.js";
|
|
2
2
|
export async function createInitialRootMetadataBootstrap(containerId) {
|
|
3
3
|
const metadataDocumentId = crypto.randomUUID();
|
|
4
4
|
const { initialUpdate } = await createInitializedContainerMetadataDocument(containerId, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rootMetadataBootstrap.js","sourceRoot":"","sources":["rootMetadataBootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0CAA0C,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"rootMetadataBootstrap.js","sourceRoot":"","sources":["rootMetadataBootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0CAA0C,EAAE,MAAM,0DAA0D,CAAC;AAOtH,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,WAAmB;IAEnB,MAAM,kBAAkB,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;IAC/C,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,0CAA0C,CACxE,WAAW,EACX;QACE,IAAI,EAAE,IAAI;QACV,IAAI,EAAE,GAAG;KACV,CACF,CAAC;IAEF,OAAO;QACL,aAAa;QACb,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import { createInitializedContainerMetadataDocument } from \"../container-contents/metadata/containerMetadataDocument\";\n\nexport interface InitialRootMetadataBootstrap {\n initialUpdate: Uint8Array;\n metadataDocumentId: string;\n}\n\nexport async function createInitialRootMetadataBootstrap(\n containerId: string,\n): Promise<InitialRootMetadataBootstrap> {\n const metadataDocumentId = crypto.randomUUID();\n const { initialUpdate } = await createInitializedContainerMetadataDocument(\n containerId,\n {\n icon: null,\n name: \"/\",\n },\n );\n\n return {\n initialUpdate,\n metadataDocumentId,\n };\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { and, eq, inArray, or } from "drizzle-orm";
|
|
2
|
+
import { deleteDocumentPlacementRowsByContainerIds, deleteDocumentPlacementRowsByDocumentIds, } from "../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
|
|
2
3
|
import { recordSupersededContainerBindingsInTransaction } from "../../data/persistence/container-contents/supersededContainerBindings.js";
|
|
3
|
-
import { deleteDocumentPlacementRowsByContainerIds, deleteDocumentPlacementRowsByDocumentIds, } from "../../data/persistence/containers/documentContainerProjectionPersistence.js";
|
|
4
4
|
import { clearDocumentDiscoveryEvidenceOnRemoteReset } from "../../data/persistence/documents/documentDiscoveryReset.js";
|
|
5
5
|
import { queuedUpdateRow, unqueueDocumentScopesInTransaction, } from "../../data/sqlite/documentPersistence/documentPendingUpdatePersistence.js";
|
|
6
6
|
import { CLEARED_DOCUMENT_SYNC_FAILURE } from "../../data/sqlite/documentPersistence/documentSyncFailurePersistence.js";
|