@tearleads/client-sdk 0.1.243 → 0.1.246
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/client/organizations/principalMutations.d.ts +5 -0
- package/data/containers/shared/mutationAcknowledgement.d.ts +1 -1
- package/data/containers/shared/mutationAcknowledgement.js +3 -8
- package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
- package/data/documents/shared/sync/mutationAcknowledgement.js +11 -2
- package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.d.ts +26 -0
- package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js +46 -0
- package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js.map +1 -0
- package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +7 -4
- package/data/keyingProjectionVerification/container/containerDestinationVerification.js +5 -1
- package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -1
- package/data/keyingProjectionVerification/container/containerProjectionVerification.js +9 -2
- package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/document/documentContainerProjections.js +2 -1
- package/data/keyingProjectionVerification/document/documentContainerProjections.js.map +1 -1
- package/data/keyingProjectionVerification/document/documentProjectionVerification.js +9 -2
- package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/index.d.ts +1 -0
- package/data/keyingProjectionVerification/index.js +1 -0
- package/data/keyingProjectionVerification/index.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistence.js +2 -0
- package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -1
- package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataRevalidations.d.ts +22 -0
- package/data/persistence/container-contents/containerMetadataRevalidations.js +52 -0
- package/data/persistence/container-contents/containerMetadataRevalidations.js.map +1 -0
- package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js +16 -4
- package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js.map +1 -1
- package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts +13 -0
- package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +11 -0
- package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
- package/data/persistence/verifiedCitations/authoredBundleCitation.d.ts +20 -0
- package/data/persistence/verifiedCitations/authoredBundleCitation.js +32 -0
- package/data/persistence/verifiedCitations/authoredBundleCitation.js.map +1 -0
- package/data/persistence/verifiedManifestBundlePersistence.d.ts +10 -0
- package/data/persistence/verifiedManifestBundlePersistence.js +95 -9
- package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
- package/data/sqlite/schema/containerSchema.d.ts +173 -0
- package/data/sqlite/schema/containerSchema.js +18 -0
- package/data/sqlite/schema/containerSchema.js.map +1 -1
- package/data/sqlite/schema/index.d.ts +84 -1
- package/data/sqlite/schema/index.js +1 -1
- package/data/sqlite/schema/index.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +56 -8
- package/internal/api-client/client/apiClientContext.d.ts +1 -0
- package/internal/api-client/client/containerMutations.d.ts +11 -0
- package/internal/api-client/client/containerReads.d.ts +1 -0
- package/internal/api-client/client/documents.d.ts +5 -0
- package/internal/api-client/client/organizations.d.ts +20 -0
- package/internal/api-client/client/principalPolicies.d.ts +9 -0
- package/internal/api-client/client/session.d.ts +10 -0
- package/internal/api-client/principalPolicyRequests.d.ts +7 -0
- package/internal/api-client/writerProjectionCitations.d.ts +3 -0
- package/internal/api-client/writerProjectionCitations.js +12 -0
- package/internal/api-client/writerProjectionCitations.js.map +1 -1
- package/internal/crypto/index.d.ts +1 -1
- package/internal/crypto/index.js +1 -1
- package/internal/crypto/index.js.map +1 -1
- package/internal/crypto/keying/accessManifestVerificationTypes.d.ts +8 -2
- package/internal/crypto/keying/accessManifestVerificationTypes.js.map +1 -1
- package/internal/crypto/keying/canonicalJsonGuard.d.ts +13 -0
- package/internal/crypto/keying/canonicalJsonGuard.js +23 -0
- package/internal/crypto/keying/canonicalJsonGuard.js.map +1 -1
- package/internal/crypto/keying/containerAccess.js +1 -1
- package/internal/crypto/keying/containerAccess.js.map +1 -1
- package/internal/crypto/keying/documentAccess.js +1 -1
- package/internal/crypto/keying/documentAccess.js.map +1 -1
- package/internal/crypto/keying/index.d.ts +1 -1
- package/internal/crypto/keying/index.js +1 -1
- package/internal/crypto/keying/index.js.map +1 -1
- package/internal/crypto/keying/keyingHashDomains.d.ts +1 -1
- package/internal/crypto/keying/keyingHashDomains.js.map +1 -1
- package/internal/crypto/organizationReplacement.js +5 -6
- package/internal/crypto/organizationReplacement.js.map +1 -1
- package/internal/loro/document.d.ts +5 -0
- package/internal/loro/document.js +17 -0
- package/internal/loro/document.js.map +1 -1
- package/internal/loro/index.d.ts +1 -1
- package/internal/loro/index.js +1 -1
- package/internal/loro/index.js.map +1 -1
- package/internal/validators/operation/attachments.d.ts +0 -12
- package/internal/validators/operation/auth.d.ts +40 -76
- package/internal/validators/operation/containerMutations.d.ts +45 -49
- package/internal/validators/operation/containerMutations.js +1 -1
- package/internal/validators/operation/containerMutations.js.map +1 -1
- package/internal/validators/operation/containerReads.d.ts +2 -0
- package/internal/validators/operation/documentMutations.d.ts +12 -24
- package/internal/validators/operation/documentSync.d.ts +0 -4
- package/internal/validators/operation/organizations.d.ts +48 -88
- package/internal/validators/operation/principals.d.ts +16 -16
- package/internal/validators/request/blob.d.ts +0 -12
- package/internal/validators/request/container.d.ts +0 -16
- package/internal/validators/request/container.js +0 -2
- package/internal/validators/request/container.js.map +1 -1
- package/internal/validators/request/containerMetadata.d.ts +0 -20
- package/internal/validators/request/document.d.ts +0 -22
- package/internal/validators/request/document.js +0 -1
- package/internal/validators/request/document.js.map +1 -1
- package/internal/validators/request/documentSyncSchema.d.ts +0 -4
- package/internal/validators/request/documentSyncSchema.js +0 -1
- package/internal/validators/request/documentSyncSchema.js.map +1 -1
- package/internal/validators/request/organization.d.ts +0 -16
- package/internal/validators/request/organizationProvisioning.d.ts +0 -242
- package/internal/validators/request/principal.d.ts +0 -20
- package/internal/validators/request/registration.d.ts +0 -76
- package/internal/validators/response/areas/containers.d.ts +1 -1
- package/internal/validators/response/areas/containers.js +1 -1
- package/internal/validators/response/areas/containers.js.map +1 -1
- package/internal/validators/response/container.d.ts +24 -0
- package/internal/validators/response/container.js +4 -0
- package/internal/validators/response/container.js.map +1 -1
- package/internal/validators/response/containerMetadata.d.ts +8 -0
- package/internal/validators/response/containerParentLanes.d.ts +2 -0
- package/internal/validators/response/documentMutation.d.ts +8 -0
- package/internal/validators/response/documentMutation.js +2 -1
- package/internal/validators/response/documentMutation.js.map +1 -1
- package/internal/validators/response/organization.d.ts +8 -0
- package/internal/validators/response/organizationProvisioning.d.ts +113 -0
- package/internal/validators/response/organizationProvisioning.js +2 -1
- package/internal/validators/response/organizationProvisioning.js.map +1 -1
- package/internal/validators/response/principal.d.ts +16 -0
- package/internal/validators/response/registration.d.ts +40 -0
- package/internal/validators/response/writerProjectionWire.d.ts +25 -0
- package/internal/validators/response/writerProjectionWire.js +109 -3
- package/internal/validators/response/writerProjectionWire.js.map +1 -1
- package/package.json +1 -1
- package/stores/container-contents/containerContentsStore.js +2 -0
- package/stores/container-contents/containerContentsStore.js.map +1 -1
- package/stores/container-contents/hydration/startupHydration.js +6 -2
- package/stores/container-contents/hydration/startupHydration.js.map +1 -1
- package/stores/container-contents/state.js +5 -1
- package/stores/container-contents/state.js.map +1 -1
- package/stores/container-contents/syncAgent/metadataRevalidation.js +79 -0
- package/stores/container-contents/syncAgent/metadataRevalidation.js.map +1 -0
- package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +6 -0
- package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
- package/stores/container-contents/syncAgent/syncLaneIteration.js +110 -23
- package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
- package/stores/documents/documentStore/rotation/index.js +3 -1
- package/stores/documents/documentStore/rotation/index.js.map +1 -1
- package/stores/documents/documentStore/sync/syncAttachments.js +4 -1
- package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
- package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -1
- package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
- package/stores/documents/documentStore/sync/syncRequest.js +3 -1
- package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
- package/workflows/container-contents/container-state/create/createAdoption.js +11 -3
- package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
- package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
- package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
- package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js +3 -0
- package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js.map +1 -1
- package/workflows/container-contents/container-state/projectionCache.js +3 -0
- package/workflows/container-contents/container-state/projectionCache.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +3 -0
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/containerPersistence.d.ts +1 -0
- package/workflows/container-contents/containerPersistence.js.map +1 -1
- package/workflows/container-contents/metadata/index.js +9 -3
- package/workflows/container-contents/metadata/index.js.map +1 -1
- package/workflows/container-contents/metadata/metadataSyncFollowup.js +9 -0
- package/workflows/container-contents/metadata/metadataSyncFollowup.js.map +1 -1
- package/workflows/container-contents/metadata/metadataTypes.d.ts +2 -0
- package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
- package/workflows/container-contents/remoteHydration/index.js +9 -0
- package/workflows/container-contents/remoteHydration/index.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +31 -0
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +9 -1
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/containers/child/mutationRequestCore.js +1 -1
- package/workflows/containers/child/mutationRequestCore.js.map +1 -1
- package/workflows/containers/child/recite.js +4 -2
- package/workflows/containers/child/recite.js.map +1 -1
- package/workflows/containers/child/recitePlan.js +0 -1
- package/workflows/containers/child/recitePlan.js.map +1 -1
- package/workflows/containers/root/create.js +0 -1
- package/workflows/containers/root/create.js.map +1 -1
- package/workflows/documents/create/createAdoption.js +11 -2
- package/workflows/documents/create/createAdoption.js.map +1 -1
- package/workflows/documents/create/createResponse.js +1 -0
- package/workflows/documents/create/createResponse.js.map +1 -1
- package/workflows/documents/linkSet/index.js +0 -1
- package/workflows/documents/linkSet/index.js.map +1 -1
- package/workflows/documents/linkSet/linkSetRemote.js +1 -0
- package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
- package/workflows/documents/sync/syncAttemptPlanning.js +8 -2
- package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
- package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +3 -2
- package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
- package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js +3 -2
- package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js.map +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +17 -10
- package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
- package/workflows/registration/organizationCreation/organizationCreationIntent.d.ts +10 -0
- package/workflows/registration/provisioningAcknowledgement.js +16 -11
- package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
- package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createResponse.js","sourceRoot":"","sources":["createResponse.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AAErG,OAAO,EACL,0BAA0B,EAC1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KAAK,YAAY,oCAAoC,CAAC;YAAE,MAAM,KAAK,CAAC;QAC1E,2EAA2E;QAC3E,6EAA6E;QAC7E,6EAA6E;QAC7E,OAAO,wCAAwC,CAAC,GAAG,EAAE,CACnD,2BAA2B,CAAC;YAC1B,GAAG,KAAK;YACR,UAAU,EAAE,QAAQ,CAAC,EAAE;YACvB,mBAAmB,EAAE,KAAK,CAAC,mBAAmB,CAAC,WAAW;YAC1D,sBAAsB,EAAE,KAAK,CAAC,mBAAmB,CAAC,cAAc;YAChE,oBAAoB,EAAE,KAAK,CAAC,MAAM,CAAC,YAAY;SAChD,CAAC,CACH,CAAC;IACJ,CAAC;IACD,KAAK,CAAC,SAAS,CAAC,6BAA6B,CAAC,QAAQ,CAAC,EAAE,EAAE,gBAAgB,CAAC,CAAC;IAC7E,OAAO;QACL,UAAU,EAAE,gBAAgB,CAAC,UAAU;QACvC,UAAU,EAAE,QAAQ,CAAC,EAAE;QACvB,cAAc;QACd,IAAI,EAAE,gBAAgB,CAAC,IAAI;QAC3B,QAAQ;QACR,gBAAgB;KACjB,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ContainerWriterProjectionResponse,\n DocumentCreateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport {\n acknowledgedDocumentCreate,\n persistedDocumentStateFromAcknowledgement,\n} from \"../../../data/documents/shared/responses\";\nimport { acknowledgeDocumentMutation } from \"../../../data/documents/shared/sync/mutationAcknowledgement\";\nimport type {\n CreateRemoteDocumentResult,\n DocumentCreateApi,\n DocumentCreateAuthor,\n MaterializedDocumentCreatePlan,\n} from \"../../../data/documents/shared/types\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { nullOnProjectionVerificationCancellation } from \"../../../data/keyingProjectionVerification/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { adoptExistingRemoteDocument } from \"./createAdoption\";\nimport { documentWriterProjectionFromCreateResponse } from \"./createProjection\";\n\n/** A matched acknowledgement remains committed if authorization evidence races. */\nexport async function acknowledgeRemoteDocumentCreate(\n input: {\n readonly apiClient: DocumentCreateApi;\n readonly author: DocumentCreateAuthor;\n readonly containerProjection: ContainerWriterProjectionResponse;\n readonly execSql: ExecSql;\n readonly materializedPlan: MaterializedDocumentCreatePlan;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly response: DocumentCreateResponse;\n readonly targetSecretKey: Uint8Array;\n } & ProjectionVerificationOptions,\n): Promise<CreateRemoteDocumentResult | null> {\n const { materializedPlan, response } = input;\n const acknowledged = acknowledgedDocumentCreate(\n materializedPlan.plan,\n response,\n );\n const persistedState =\n persistedDocumentStateFromAcknowledgement(acknowledged);\n await acknowledgeDocumentMutation({\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n const writerProjection = documentWriterProjectionFromCreateResponse({\n containerProjection: input.containerProjection,\n response: acknowledged,\n });\n try {\n const targets = await nullOnProjectionVerificationCancellation(() =>\n assertDocumentWriterProjectionConsistent(writerProjection, input),\n );\n if (!targets || input.stillCurrent?.() === false) return null;\n } catch (error) {\n if (!(error instanceof ProjectionDependencyUnavailableError)) throw error;\n // A principal pin can advance while POST is in flight. Recover the already\n // committed document from fresh evidence, without submitting another create.\n // The adoption path still verifies its author, scope, chain and key binding.\n return nullOnProjectionVerificationCancellation(() =>\n adoptExistingRemoteDocument({\n ...input,\n documentId: response.id,\n expectedContainerId: input.containerProjection.containerId,\n expectedOrganizationId: input.containerProjection.organizationId,\n expectedSignerUserId: input.author.signerUserId,\n }),\n );\n }\n input.apiClient.primeDocumentWriterProjection(response.id, writerProjection);\n return {\n contentKey: materializedPlan.contentKey,\n documentId: response.id,\n persistedState,\n plan: materializedPlan.plan,\n response,\n writerProjection,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"createResponse.js","sourceRoot":"","sources":["createResponse.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AAErG,OAAO,EACL,0BAA0B,EAC1B,yCAAyC,GAC1C,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,2BAA2B,EAAE,MAAM,6DAA6D,CAAC;AAQ1G,OAAO,EAAE,wCAAwC,EAAE,MAAM,kDAAkD,CAAC;AAC5G,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAElG,OAAO,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,0CAA0C,EAAE,MAAM,oBAAoB,CAAC;AAEhF,mFAAmF;AACnF,MAAM,CAAC,KAAK,UAAU,+BAA+B,CACnD,KASiC;IAEjC,MAAM,EAAE,gBAAgB,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC;IAC7C,MAAM,YAAY,GAAG,0BAA0B,CAC7C,gBAAgB,CAAC,IAAI,EACrB,QAAQ,CACT,CAAC;IACF,MAAM,cAAc,GAClB,yCAAyC,CAAC,YAAY,CAAC,CAAC;IAC1D,MAAM,2BAA2B,CAAC;QAChC,YAAY,EAAE,QAAQ,CAAC,YAAY;QACnC,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,IAAI,EAAE,gBAAgB,CAAC,IAAI;QAC3B,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAClD,MAAM,gBAAgB,GAAG,0CAA0C,CAAC;QAClE,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,QAAQ,EAAE,YAAY;KACvB,CAAC,CAAC;IACH,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,MAAM,wCAAwC,CAAC,GAAG,EAAE,CAClE,wCAAwC,CAAC,gBAAgB,EAAE,KAAK,CAAC,CAClE,CAAC;QACF,IAAI,CAAC,OAAO,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;YAAE,OAAO,IAAI,CAAC;IAChE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,CAAC,KAAK,YAAY,oCAAoC,CAAC;YAAE,MAAM,KAAK,CAAC;QAC1E,2EAA2E;QAC3E,6EAA6E;QAC7E,6EAA6E;QAC7E,OAAO,wCAAwC,CAAC,GAAG,EAAE,CACnD,2BAA2B,CAAC;YAC1B,GAAG,KAAK;YACR,UAAU,EAAE,QAAQ,CAAC,EAAE;YACvB,mBAAmB,EAAE,KAAK,CAAC,mBAAmB,CAAC,WAAW;YAC1D,sBAAsB,EAAE,KAAK,CAAC,mBAAmB,CAAC,cAAc;YAChE,oBAAoB,EAAE,KAAK,CAAC,MAAM,CAAC,YAAY;SAChD,CAAC,CACH,CAAC;IACJ,CAAC;IACD,KAAK,CAAC,SAAS,CAAC,6BAA6B,CAAC,QAAQ,CAAC,EAAE,EAAE,gBAAgB,CAAC,CAAC;IAC7E,OAAO;QACL,UAAU,EAAE,gBAAgB,CAAC,UAAU;QACvC,UAAU,EAAE,QAAQ,CAAC,EAAE;QACvB,cAAc;QACd,IAAI,EAAE,gBAAgB,CAAC,IAAI;QAC3B,QAAQ;QACR,gBAAgB;KACjB,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ContainerWriterProjectionResponse,\n DocumentCreateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport {\n acknowledgedDocumentCreate,\n persistedDocumentStateFromAcknowledgement,\n} from \"../../../data/documents/shared/responses\";\nimport { acknowledgeDocumentMutation } from \"../../../data/documents/shared/sync/mutationAcknowledgement\";\nimport type {\n CreateRemoteDocumentResult,\n DocumentCreateApi,\n DocumentCreateAuthor,\n MaterializedDocumentCreatePlan,\n} from \"../../../data/documents/shared/types\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { nullOnProjectionVerificationCancellation } from \"../../../data/keyingProjectionVerification/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { adoptExistingRemoteDocument } from \"./createAdoption\";\nimport { documentWriterProjectionFromCreateResponse } from \"./createProjection\";\n\n/** A matched acknowledgement remains committed if authorization evidence races. */\nexport async function acknowledgeRemoteDocumentCreate(\n input: {\n readonly apiClient: DocumentCreateApi;\n readonly author: DocumentCreateAuthor;\n readonly containerProjection: ContainerWriterProjectionResponse;\n readonly execSql: ExecSql;\n readonly materializedPlan: MaterializedDocumentCreatePlan;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly response: DocumentCreateResponse;\n readonly targetSecretKey: Uint8Array;\n } & ProjectionVerificationOptions,\n): Promise<CreateRemoteDocumentResult | null> {\n const { materializedPlan, response } = input;\n const acknowledged = acknowledgedDocumentCreate(\n materializedPlan.plan,\n response,\n );\n const persistedState =\n persistedDocumentStateFromAcknowledgement(acknowledged);\n await acknowledgeDocumentMutation({\n bundleDigest: response.bundleDigest,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n const writerProjection = documentWriterProjectionFromCreateResponse({\n containerProjection: input.containerProjection,\n response: acknowledged,\n });\n try {\n const targets = await nullOnProjectionVerificationCancellation(() =>\n assertDocumentWriterProjectionConsistent(writerProjection, input),\n );\n if (!targets || input.stillCurrent?.() === false) return null;\n } catch (error) {\n if (!(error instanceof ProjectionDependencyUnavailableError)) throw error;\n // A principal pin can advance while POST is in flight. Recover the already\n // committed document from fresh evidence, without submitting another create.\n // The adoption path still verifies its author, scope, chain and key binding.\n return nullOnProjectionVerificationCancellation(() =>\n adoptExistingRemoteDocument({\n ...input,\n documentId: response.id,\n expectedContainerId: input.containerProjection.containerId,\n expectedOrganizationId: input.containerProjection.organizationId,\n expectedSignerUserId: input.author.signerUserId,\n }),\n );\n }\n input.apiClient.primeDocumentWriterProjection(response.id, writerProjection);\n return {\n contentKey: materializedPlan.contentKey,\n documentId: response.id,\n persistedState,\n plan: materializedPlan.plan,\n response,\n writerProjection,\n };\n}\n"]}
|
|
@@ -160,7 +160,6 @@ async function buildDocumentLinkSetMutationPlan({ author, blobRewraps, contentKe
|
|
|
160
160
|
event: readCanonicalRecord(eventPlan.event, "Document link-set event"),
|
|
161
161
|
body: readCanonicalRecord(eventPlan.body, "Document link-set body"),
|
|
162
162
|
expectedManifestHash: manifestHash,
|
|
163
|
-
manifest: readCanonicalRecord(manifest, "Document link-set manifest"),
|
|
164
163
|
targetContainerPathRefs,
|
|
165
164
|
authorizingContainerPathRefs: eventPlan.authorizingContainerPathRefs,
|
|
166
165
|
contentKeyBundle: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,mCAAmC,EACnC,+BAA+B,EAG/B,6BAA6B,EAC7B,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAMrF,OAAO,EACL,yCAAyC,EACzC,qCAAqC,GACtC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,6BAA6B,EAAE,MAAM,uCAAuC,CAAC;AACtF,OAAO,EACL,wCAAwC,EACxC,mCAAmC,EACnC,iBAAiB,EACjB,sBAAsB,E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W,CAAC,kBAAkB;YACvD,aAAa,EAAE,IAAI,CAAC,WAAW,CAAC,OAAO;YACvC,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;SACzC,CAAC;KACH,CAAC,CAAC;AACL,CAAC;AAED,SAAS,6BAA6B,CACpC,KAGC,EACD,kBAAqC;IAErC,0FAA0F;IAC1F,6BAA6B,CAC3B,KAAK,CAAC,gBAAgB,EACtB,IAAI,GAAG,CAAC,kBAAkB,CAAC,CAC5B,CAAC;IACF,IAAI,KAAK,CAAC,SAAS,KAAK,MAAM,EAAE,CAAC;QAC/B,6BAA6B,CAC3B,KAAK,CAAC,yBAAyB,CAAC,aAAa,CAC9C,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n computeAccessManifestHash,\n computeDocumentContentKeyTargetHash,\n DOCUMENT_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n type DocumentLinkSetManifestState,\n deriveDocumentLinkSetManifest,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport type { DocumentContentKeyTargetEnvelope } from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS,\n MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS,\n} from \"@tearleads/validators/util\";\nimport {\n assertContainerKekPathCurrent,\n assertDocumentKekPathsCurrent,\n} from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { buildDocumentLinkSetEventPlan } from \"../../../data/documents/shared/events\";\nimport {\n assertDocumentWriterProjectionConsistent,\n collectContainerKeksForDocumentSync,\n containerPathRefs,\n currentDocumentTargets,\n deriveDocumentTargetFromProjection,\n mergeTargetEnvelopes,\n readLinkedContainerIdsFromDocumentManifest,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyFromWriterProjection,\n verifiedDocumentWrapTargets,\n} from \"../../../data/documents/shared/projection\";\nimport {\n type ProjectionVerificationOptions,\n projectionVerificationOptions,\n} from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport {\n assertDocumentManifestBundleConsistent,\n describeDocumentTargetKek,\n sortDocumentTargets,\n targetKey,\n uniqueSortedStrings,\n} from \"../../../data/documents/shared/readers\";\nimport type {\n BuildDocumentLinkSetMutationPlanInput,\n DocumentCreateAuthor,\n DocumentLinkSetMutationOperation,\n DocumentLinkSetMutationPlan,\n DocumentLinkSetTargetState,\n MaterializedDocumentLinkSetMutationPlan,\n} from \"../../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport type { PrincipalPolicyCache } from \"../../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n assertSubtreePurgePath,\n type SubtreePurgeRoot,\n} from \"../purge/subtreePurgeScope\";\nimport {\n assertDocumentLinkAuthorAccess,\n verifyDocumentLinkSetCurrentPolicies,\n} from \"./linkSetAuthority\";\n\nfunction deriveDocumentLinkSetTargetState(input: {\n operation: DocumentLinkSetMutationOperation;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}): DocumentLinkSetTargetState {\n const currentTargets = currentDocumentTargets(input.writerProjection);\n const currentLinkedContainerIds = readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n );\n const target = deriveDocumentTargetFromProjection(\n input.targetContainerProjection,\n );\n const currentTarget = currentTargets.find(\n (candidate) => candidate.containerId === target.containerId,\n );\n\n if (input.operation === \"link\") {\n if (currentTarget) {\n throw new Error(\"Document link target is already linked\");\n }\n assertDocumentLinkTargetCapacity(currentTargets.length);\n assertDocumentLinkAuthorizationPathCapacity(\n input.writerProjection.authorizingContainerPaths.map(\n (projection) => projection.path.length,\n ),\n input.targetContainerProjection.path.length,\n );\n\n return {\n currentTargets,\n linkedContainerIds: uniqueSortedStrings([\n ...currentLinkedContainerIds,\n target.containerId,\n ]),\n target,\n targets: sortDocumentTargets([...currentTargets, target]),\n };\n }\n\n if (!currentTarget) {\n throw new Error(\"Document unlink target is not linked\");\n }\n if (targetKey(currentTarget) !== targetKey(target)) {\n throw new Error(\"Document unlink target projection is stale\");\n }\n\n const linkedContainerIds = currentLinkedContainerIds.filter(\n (containerId) => containerId !== target.containerId,\n );\n if (linkedContainerIds.length === 0) {\n throw new Error(\"Document unlink must leave a linked container\");\n }\n\n return {\n currentTargets,\n linkedContainerIds,\n target,\n targets: currentTargets.filter(\n (candidate) => candidate.containerId !== target.containerId,\n ),\n };\n}\n\nexport function assertDocumentLinkTargetCapacity(\n currentTargetCount: number,\n): void {\n if (currentTargetCount >= MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS) {\n throw new RangeError(\n `A document cannot be linked to more than ${MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS} containers`,\n );\n }\n}\n\nexport function assertDocumentLinkAuthorizationPathCapacity(\n currentPathLengths: readonly number[],\n targetPathLength: number,\n): void {\n const totalReferences = currentPathLengths.reduce(\n (total, length) => total + length,\n targetPathLength,\n );\n if (totalReferences > MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS) {\n throw new RangeError(\n `Document links cannot require more than ${MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS} authorization references`,\n );\n }\n}\n\nasync function wrapDocumentContentKeyForTargets(input: {\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n keksByEpochId: ReadonlyMap<string, Uint8Array>;\n targets: readonly DocumentContentKeyTarget[];\n}): Promise<DocumentContentKeyTargetEnvelope[]> {\n return Promise.all(\n sortDocumentTargets(input.targets).map(async (target) => {\n const targetKek = input.keksByEpochId.get(target.containerKeyEpochId);\n if (!targetKek) {\n throw new Error(\n `Document target KEK could not be unwrapped for ${describeDocumentTargetKek(target)}`,\n );\n }\n\n const wrapped = await wrapContentKey(input.contentKey, targetKek, {\n kind: \"Document\",\n objectId: input.documentId,\n contentKeyEpoch: input.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: DOCUMENT_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n }),\n );\n}\n\n// Resolve the organization a link/unlink mutation belongs to: the document's\n// own org (from its manifest), which must equal the target container's org —\n// both are owned by the same organization. The acting member's personal org is\n// intentionally not part of this check; a member may link documents within any\n// org they belong to. Returns the document org so the plan stamps it onto the\n// signed event and manifest rather than the author's org.\nasync function resolveDocumentLinkSetMutationOrganization(input: {\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<string> {\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document link-set manifest\",\n });\n if (\n manifestIdentity.organizationId !==\n input.targetContainerProjection.organizationId\n ) {\n throw new Error(\"Document target container organization mismatch\");\n }\n\n return manifestIdentity.organizationId;\n}\n\nfunction readDocumentLinkSetPreviousEpoch(\n writerProjection: DocumentWriterProjectionResponse,\n): number {\n const previousState = writerProjection.documentManifest.state;\n const previousEpoch = isPlainRecord(previousState)\n ? Reflect.get(previousState, \"epoch\")\n : undefined;\n if (\n typeof previousEpoch !== \"number\" ||\n !Number.isInteger(previousEpoch) ||\n previousEpoch <= 0\n ) {\n throw new Error(\"Document link-set previous epoch is invalid\");\n }\n\n return previousEpoch;\n}\n\nasync function buildDocumentLinkSetMutationPlan({\n author,\n blobRewraps,\n contentKeyEpoch,\n eventId = crypto.randomUUID(),\n operation,\n signedAt = new Date().toISOString(),\n targetContainerProjection,\n targetEnvelopes,\n writerProjection,\n}: BuildDocumentLinkSetMutationPlanInput): Promise<DocumentLinkSetMutationPlan> {\n const organizationId = await resolveDocumentLinkSetMutationOrganization({\n targetContainerProjection,\n writerProjection,\n });\n const targetState = deriveDocumentLinkSetTargetState({\n operation,\n targetContainerProjection,\n writerProjection,\n });\n const targetEnvelopesForRequest = mergeTargetEnvelopes(\n targetState.targets,\n targetEnvelopes,\n );\n const targetContainerPathRefs = containerPathRefs(\n targetContainerProjection.path,\n );\n const eventPlan = await buildDocumentLinkSetEventPlan({\n author,\n blobRewraps,\n eventId,\n operation,\n organizationId,\n signedAt,\n targetContainerPathRefs,\n targetState,\n writerProjection,\n });\n const previousEpoch = readDocumentLinkSetPreviousEpoch(writerProjection);\n\n const state: DocumentLinkSetManifestState = {\n version: 1,\n documentId: writerProjection.documentId,\n organizationId,\n epoch: previousEpoch + 1,\n previousManifestHash: writerProjection.documentManifest.manifestHash,\n eventHash: eventPlan.eventHash,\n linkedContainerIds: [...targetState.linkedContainerIds],\n };\n const manifest = await deriveDocumentLinkSetManifest(state);\n const manifestHash = await computeAccessManifestHash(manifest);\n const targetHash = await computeDocumentContentKeyTargetHash(\n targetState.targets,\n );\n\n return {\n body: eventPlan.body,\n contentKeyEpoch,\n documentId: writerProjection.documentId,\n event: eventPlan.event,\n eventHash: eventPlan.eventHash,\n manifest,\n manifestHash,\n operation,\n request: {\n event: readCanonicalRecord(eventPlan.event, \"Document link-set event\"),\n body: readCanonicalRecord(eventPlan.body, \"Document link-set body\"),\n expectedManifestHash: manifestHash,\n manifest: readCanonicalRecord(manifest, \"Document link-set manifest\"),\n targetContainerPathRefs,\n authorizingContainerPathRefs: eventPlan.authorizingContainerPathRefs,\n contentKeyBundle: {\n contentKeyEpoch,\n linkSetManifestHash: manifestHash,\n targetHash,\n targets: targetEnvelopesForRequest,\n },\n },\n state,\n targetHash,\n targets: sortDocumentTargets(targetState.targets),\n };\n}\n\nexport async function buildMaterializedDocumentLinkSetMutationPlan(\n input: {\n author: DocumentCreateAuthor;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n prepareBlobRewraps: (\n targets: readonly DocumentContentKeyTarget[],\n ) => Promise<BuildDocumentLinkSetMutationPlanInput[\"blobRewraps\"]>;\n contentKey?: Uint8Array | undefined;\n eventId?: string | undefined;\n execSql?: ExecSql | undefined;\n operation: DocumentLinkSetMutationOperation;\n signedAt?: string | undefined;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetSecretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<MaterializedDocumentLinkSetMutationPlan> {\n const verificationOptions = projectionVerificationOptions(input);\n const principalPolicyCache: PrincipalPolicyCache = new Map();\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n execSql: input.execSql,\n principalPolicyCache,\n ...verificationOptions,\n });\n await verifyDocumentLinkSetCurrentPolicies({\n execSql: input.execSql,\n principalPolicyCache,\n targetContainerProjection: input.targetContainerProjection,\n writerProjection: input.writerProjection,\n ...verificationOptions,\n });\n assertSubtreePurgePath(\n input.targetContainerProjection.path,\n input.expectedSubtreeRoot,\n );\n if (input.resolveProjectionUserKey)\n assertDocumentLinkAuthorAccess({\n ...input,\n principalPolicies: [...principalPolicyCache.values()],\n });\n const targetState = deriveDocumentLinkSetTargetState({\n operation: input.operation,\n targetContainerProjection: input.targetContainerProjection,\n writerProjection: input.writerProjection,\n });\n assertLinkSetWriteKeksCurrent(input, targetState.linkedContainerIds);\n const currentContentKey = await unwrapDocumentContentKeyFromWriterProjection({\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...verificationOptions,\n });\n const contentKeyRotated = input.operation === \"unlink\";\n const contentKey = contentKeyRotated\n ? (input.contentKey ?? crypto.getRandomValues(new Uint8Array(32)))\n : currentContentKey;\n if (contentKey.byteLength !== 32) {\n throw new Error(\"Document content key must be 32 bytes\");\n }\n // A link carries the existing envelopes forward at the same epoch; an\n // unlink rotates to a fresh key at the next one.\n const contentKeyEpoch =\n input.writerProjection.contentKeyBundle.contentKeyEpoch +\n (contentKeyRotated ? 1 : 0);\n const targetEnvelopes = await buildLinkSetTargetEnvelopes(input, {\n contentKey,\n contentKeyEpoch,\n targetState,\n });\n\n const plan = await buildDocumentLinkSetMutationPlan({\n author: input.author,\n blobRewraps: await input.prepareBlobRewraps(targetState.targets),\n contentKeyEpoch,\n eventId: input.eventId,\n operation: input.operation,\n signedAt: input.signedAt,\n targetContainerProjection: input.targetContainerProjection,\n targetEnvelopes,\n writerProjection: input.writerProjection,\n });\n\n return {\n contentKey,\n contentKeyRotated,\n plan,\n };\n}\n\nasync function buildLinkSetTargetEnvelopes(\n input: Parameters<typeof buildMaterializedDocumentLinkSetMutationPlan>[0],\n wrap: {\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n targetState: ReturnType<typeof deriveDocumentLinkSetTargetState>;\n },\n): Promise<DocumentContentKeyTargetEnvelope[]> {\n const verificationOptions = projectionVerificationOptions(input);\n const sealing = {\n contentKey: wrap.contentKey,\n contentKeyEpoch: wrap.contentKeyEpoch,\n documentId: input.writerProjection.documentId,\n };\n if (input.operation === \"link\") {\n return [\n ...input.writerProjection.contentKeyBundle.targets,\n ...(await wrapDocumentContentKeyForTargets({\n ...sealing,\n keksByEpochId: await unwrapContainerKekPath({\n execSql: input.execSql,\n projection: input.targetContainerProjection,\n secretKey: input.targetSecretKey,\n ...verificationOptions,\n }),\n targets: [wrap.targetState.target],\n })),\n ];\n }\n return wrapDocumentContentKeyForTargets({\n ...sealing,\n keksByEpochId: (\n await collectContainerKeksForDocumentSync({\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...verificationOptions,\n })\n ).keksByEpochId,\n // The rotated key is wrapped only to verified current heads of the\n // remaining linked containers, never to a server-listed epoch.\n targets: verifiedDocumentWrapTargets({\n linkedContainerIds: wrap.targetState.linkedContainerIds,\n serverTargets: wrap.targetState.targets,\n writerProjection: input.writerProjection,\n }),\n });\n}\n\nfunction assertLinkSetWriteKeksCurrent(\n input: Pick<\n Parameters<typeof buildMaterializedDocumentLinkSetMutationPlan>[0],\n \"writerProjection\" | \"targetContainerProjection\" | \"operation\"\n >,\n linkedContainerIds: readonly string[],\n): void {\n // Unlink can escape a stale branch; only recipients of the successor key must be current.\n assertDocumentKekPathsCurrent(\n input.writerProjection,\n new Set(linkedContainerIds),\n );\n if (input.operation === \"link\") {\n assertContainerKekPathCurrent(\n input.targetContainerProjection.containerKeks,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,mCAAmC,EACnC,+BAA+B,EAG/B,6BAA6B,EAC7B,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAMrF,OAAO,EACL,yCAAyC,EACzC,qCAAqC,GACtC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,6BAA6B,EAAE,MAAM,uCAAuC,CAAC;AACtF,OAAO,EACL,wCAAwC,EACxC,mCAAmC,EACnC,iBAAiB,EACjB,sBAAsB,EACtB,kCAAkC,EAClC,oBAAoB,EACpB,0CAA0C,EAC1C,sBAAsB,EACtB,4CAA4C,EAC5C,2BAA2B,GAC5B,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAEL,6BAA6B,GAC9B,MAAM,yEAAyE,CAAC;AACjF,OAAO,EACL,sCAAsC,EACtC,yBAAyB,EACzB,mBAAmB,EACnB,SAAS,EACT,mBAAmB,GACpB,MAAM,wCAAwC,CAAC;AAShD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAGzE,OAAO,EACL,sBAAsB,GAEvB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,8BAA8B,EAC9B,oCAAoC,GACrC,MAAM,oBAAoB,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_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n type DocumentLinkSetManifestState,\n deriveDocumentLinkSetManifest,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport type { DocumentContentKeyTargetEnvelope } from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS,\n MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS,\n} from \"@tearleads/validators/util\";\nimport {\n assertContainerKekPathCurrent,\n assertDocumentKekPathsCurrent,\n} from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { buildDocumentLinkSetEventPlan } from \"../../../data/documents/shared/events\";\nimport {\n assertDocumentWriterProjectionConsistent,\n collectContainerKeksForDocumentSync,\n containerPathRefs,\n currentDocumentTargets,\n deriveDocumentTargetFromProjection,\n mergeTargetEnvelopes,\n readLinkedContainerIdsFromDocumentManifest,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyFromWriterProjection,\n verifiedDocumentWrapTargets,\n} from \"../../../data/documents/shared/projection\";\nimport {\n type ProjectionVerificationOptions,\n projectionVerificationOptions,\n} from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport {\n assertDocumentManifestBundleConsistent,\n describeDocumentTargetKek,\n sortDocumentTargets,\n targetKey,\n uniqueSortedStrings,\n} from \"../../../data/documents/shared/readers\";\nimport type {\n BuildDocumentLinkSetMutationPlanInput,\n DocumentCreateAuthor,\n DocumentLinkSetMutationOperation,\n DocumentLinkSetMutationPlan,\n DocumentLinkSetTargetState,\n MaterializedDocumentLinkSetMutationPlan,\n} from \"../../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport type { PrincipalPolicyCache } from \"../../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n assertSubtreePurgePath,\n type SubtreePurgeRoot,\n} from \"../purge/subtreePurgeScope\";\nimport {\n assertDocumentLinkAuthorAccess,\n verifyDocumentLinkSetCurrentPolicies,\n} from \"./linkSetAuthority\";\n\nfunction deriveDocumentLinkSetTargetState(input: {\n operation: DocumentLinkSetMutationOperation;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}): DocumentLinkSetTargetState {\n const currentTargets = currentDocumentTargets(input.writerProjection);\n const currentLinkedContainerIds = readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n );\n const target = deriveDocumentTargetFromProjection(\n input.targetContainerProjection,\n );\n const currentTarget = currentTargets.find(\n (candidate) => candidate.containerId === target.containerId,\n );\n\n if (input.operation === \"link\") {\n if (currentTarget) {\n throw new Error(\"Document link target is already linked\");\n }\n assertDocumentLinkTargetCapacity(currentTargets.length);\n assertDocumentLinkAuthorizationPathCapacity(\n input.writerProjection.authorizingContainerPaths.map(\n (projection) => projection.path.length,\n ),\n input.targetContainerProjection.path.length,\n );\n\n return {\n currentTargets,\n linkedContainerIds: uniqueSortedStrings([\n ...currentLinkedContainerIds,\n target.containerId,\n ]),\n target,\n targets: sortDocumentTargets([...currentTargets, target]),\n };\n }\n\n if (!currentTarget) {\n throw new Error(\"Document unlink target is not linked\");\n }\n if (targetKey(currentTarget) !== targetKey(target)) {\n throw new Error(\"Document unlink target projection is stale\");\n }\n\n const linkedContainerIds = currentLinkedContainerIds.filter(\n (containerId) => containerId !== target.containerId,\n );\n if (linkedContainerIds.length === 0) {\n throw new Error(\"Document unlink must leave a linked container\");\n }\n\n return {\n currentTargets,\n linkedContainerIds,\n target,\n targets: currentTargets.filter(\n (candidate) => candidate.containerId !== target.containerId,\n ),\n };\n}\n\nexport function assertDocumentLinkTargetCapacity(\n currentTargetCount: number,\n): void {\n if (currentTargetCount >= MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS) {\n throw new RangeError(\n `A document cannot be linked to more than ${MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS} containers`,\n );\n }\n}\n\nexport function assertDocumentLinkAuthorizationPathCapacity(\n currentPathLengths: readonly number[],\n targetPathLength: number,\n): void {\n const totalReferences = currentPathLengths.reduce(\n (total, length) => total + length,\n targetPathLength,\n );\n if (totalReferences > MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS) {\n throw new RangeError(\n `Document links cannot require more than ${MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS} authorization references`,\n );\n }\n}\n\nasync function wrapDocumentContentKeyForTargets(input: {\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n keksByEpochId: ReadonlyMap<string, Uint8Array>;\n targets: readonly DocumentContentKeyTarget[];\n}): Promise<DocumentContentKeyTargetEnvelope[]> {\n return Promise.all(\n sortDocumentTargets(input.targets).map(async (target) => {\n const targetKek = input.keksByEpochId.get(target.containerKeyEpochId);\n if (!targetKek) {\n throw new Error(\n `Document target KEK could not be unwrapped for ${describeDocumentTargetKek(target)}`,\n );\n }\n\n const wrapped = await wrapContentKey(input.contentKey, targetKek, {\n kind: \"Document\",\n objectId: input.documentId,\n contentKeyEpoch: input.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: DOCUMENT_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n }),\n );\n}\n\n// Resolve the organization a link/unlink mutation belongs to: the document's\n// own org (from its manifest), which must equal the target container's org —\n// both are owned by the same organization. The acting member's personal org is\n// intentionally not part of this check; a member may link documents within any\n// org they belong to. Returns the document org so the plan stamps it onto the\n// signed event and manifest rather than the author's org.\nasync function resolveDocumentLinkSetMutationOrganization(input: {\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<string> {\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document link-set manifest\",\n });\n if (\n manifestIdentity.organizationId !==\n input.targetContainerProjection.organizationId\n ) {\n throw new Error(\"Document target container organization mismatch\");\n }\n\n return manifestIdentity.organizationId;\n}\n\nfunction readDocumentLinkSetPreviousEpoch(\n writerProjection: DocumentWriterProjectionResponse,\n): number {\n const previousState = writerProjection.documentManifest.state;\n const previousEpoch = isPlainRecord(previousState)\n ? Reflect.get(previousState, \"epoch\")\n : undefined;\n if (\n typeof previousEpoch !== \"number\" ||\n !Number.isInteger(previousEpoch) ||\n previousEpoch <= 0\n ) {\n throw new Error(\"Document link-set previous epoch is invalid\");\n }\n\n return previousEpoch;\n}\n\nasync function buildDocumentLinkSetMutationPlan({\n author,\n blobRewraps,\n contentKeyEpoch,\n eventId = crypto.randomUUID(),\n operation,\n signedAt = new Date().toISOString(),\n targetContainerProjection,\n targetEnvelopes,\n writerProjection,\n}: BuildDocumentLinkSetMutationPlanInput): Promise<DocumentLinkSetMutationPlan> {\n const organizationId = await resolveDocumentLinkSetMutationOrganization({\n targetContainerProjection,\n writerProjection,\n });\n const targetState = deriveDocumentLinkSetTargetState({\n operation,\n targetContainerProjection,\n writerProjection,\n });\n const targetEnvelopesForRequest = mergeTargetEnvelopes(\n targetState.targets,\n targetEnvelopes,\n );\n const targetContainerPathRefs = containerPathRefs(\n targetContainerProjection.path,\n );\n const eventPlan = await buildDocumentLinkSetEventPlan({\n author,\n blobRewraps,\n eventId,\n operation,\n organizationId,\n signedAt,\n targetContainerPathRefs,\n targetState,\n writerProjection,\n });\n const previousEpoch = readDocumentLinkSetPreviousEpoch(writerProjection);\n\n const state: DocumentLinkSetManifestState = {\n version: 1,\n documentId: writerProjection.documentId,\n organizationId,\n epoch: previousEpoch + 1,\n previousManifestHash: writerProjection.documentManifest.manifestHash,\n eventHash: eventPlan.eventHash,\n linkedContainerIds: [...targetState.linkedContainerIds],\n };\n const manifest = await deriveDocumentLinkSetManifest(state);\n const manifestHash = await computeAccessManifestHash(manifest);\n const targetHash = await computeDocumentContentKeyTargetHash(\n targetState.targets,\n );\n\n return {\n body: eventPlan.body,\n contentKeyEpoch,\n documentId: writerProjection.documentId,\n event: eventPlan.event,\n eventHash: eventPlan.eventHash,\n manifest,\n manifestHash,\n operation,\n request: {\n event: readCanonicalRecord(eventPlan.event, \"Document link-set event\"),\n body: readCanonicalRecord(eventPlan.body, \"Document link-set body\"),\n expectedManifestHash: manifestHash,\n targetContainerPathRefs,\n authorizingContainerPathRefs: eventPlan.authorizingContainerPathRefs,\n contentKeyBundle: {\n contentKeyEpoch,\n linkSetManifestHash: manifestHash,\n targetHash,\n targets: targetEnvelopesForRequest,\n },\n },\n state,\n targetHash,\n targets: sortDocumentTargets(targetState.targets),\n };\n}\n\nexport async function buildMaterializedDocumentLinkSetMutationPlan(\n input: {\n author: DocumentCreateAuthor;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n prepareBlobRewraps: (\n targets: readonly DocumentContentKeyTarget[],\n ) => Promise<BuildDocumentLinkSetMutationPlanInput[\"blobRewraps\"]>;\n contentKey?: Uint8Array | undefined;\n eventId?: string | undefined;\n execSql?: ExecSql | undefined;\n operation: DocumentLinkSetMutationOperation;\n signedAt?: string | undefined;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetSecretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<MaterializedDocumentLinkSetMutationPlan> {\n const verificationOptions = projectionVerificationOptions(input);\n const principalPolicyCache: PrincipalPolicyCache = new Map();\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n execSql: input.execSql,\n principalPolicyCache,\n ...verificationOptions,\n });\n await verifyDocumentLinkSetCurrentPolicies({\n execSql: input.execSql,\n principalPolicyCache,\n targetContainerProjection: input.targetContainerProjection,\n writerProjection: input.writerProjection,\n ...verificationOptions,\n });\n assertSubtreePurgePath(\n input.targetContainerProjection.path,\n input.expectedSubtreeRoot,\n );\n if (input.resolveProjectionUserKey)\n assertDocumentLinkAuthorAccess({\n ...input,\n principalPolicies: [...principalPolicyCache.values()],\n });\n const targetState = deriveDocumentLinkSetTargetState({\n operation: input.operation,\n targetContainerProjection: input.targetContainerProjection,\n writerProjection: input.writerProjection,\n });\n assertLinkSetWriteKeksCurrent(input, targetState.linkedContainerIds);\n const currentContentKey = await unwrapDocumentContentKeyFromWriterProjection({\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...verificationOptions,\n });\n const contentKeyRotated = input.operation === \"unlink\";\n const contentKey = contentKeyRotated\n ? (input.contentKey ?? crypto.getRandomValues(new Uint8Array(32)))\n : currentContentKey;\n if (contentKey.byteLength !== 32) {\n throw new Error(\"Document content key must be 32 bytes\");\n }\n // A link carries the existing envelopes forward at the same epoch; an\n // unlink rotates to a fresh key at the next one.\n const contentKeyEpoch =\n input.writerProjection.contentKeyBundle.contentKeyEpoch +\n (contentKeyRotated ? 1 : 0);\n const targetEnvelopes = await buildLinkSetTargetEnvelopes(input, {\n contentKey,\n contentKeyEpoch,\n targetState,\n });\n\n const plan = await buildDocumentLinkSetMutationPlan({\n author: input.author,\n blobRewraps: await input.prepareBlobRewraps(targetState.targets),\n contentKeyEpoch,\n eventId: input.eventId,\n operation: input.operation,\n signedAt: input.signedAt,\n targetContainerProjection: input.targetContainerProjection,\n targetEnvelopes,\n writerProjection: input.writerProjection,\n });\n\n return {\n contentKey,\n contentKeyRotated,\n plan,\n };\n}\n\nasync function buildLinkSetTargetEnvelopes(\n input: Parameters<typeof buildMaterializedDocumentLinkSetMutationPlan>[0],\n wrap: {\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n targetState: ReturnType<typeof deriveDocumentLinkSetTargetState>;\n },\n): Promise<DocumentContentKeyTargetEnvelope[]> {\n const verificationOptions = projectionVerificationOptions(input);\n const sealing = {\n contentKey: wrap.contentKey,\n contentKeyEpoch: wrap.contentKeyEpoch,\n documentId: input.writerProjection.documentId,\n };\n if (input.operation === \"link\") {\n return [\n ...input.writerProjection.contentKeyBundle.targets,\n ...(await wrapDocumentContentKeyForTargets({\n ...sealing,\n keksByEpochId: await unwrapContainerKekPath({\n execSql: input.execSql,\n projection: input.targetContainerProjection,\n secretKey: input.targetSecretKey,\n ...verificationOptions,\n }),\n targets: [wrap.targetState.target],\n })),\n ];\n }\n return wrapDocumentContentKeyForTargets({\n ...sealing,\n keksByEpochId: (\n await collectContainerKeksForDocumentSync({\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...verificationOptions,\n })\n ).keksByEpochId,\n // The rotated key is wrapped only to verified current heads of the\n // remaining linked containers, never to a server-listed epoch.\n targets: verifiedDocumentWrapTargets({\n linkedContainerIds: wrap.targetState.linkedContainerIds,\n serverTargets: wrap.targetState.targets,\n writerProjection: input.writerProjection,\n }),\n });\n}\n\nfunction assertLinkSetWriteKeksCurrent(\n input: Pick<\n Parameters<typeof buildMaterializedDocumentLinkSetMutationPlan>[0],\n \"writerProjection\" | \"targetContainerProjection\" | \"operation\"\n >,\n linkedContainerIds: readonly string[],\n): void {\n // Unlink can escape a stale branch; only recipients of the successor key must be current.\n assertDocumentKekPathsCurrent(\n input.writerProjection,\n new Set(linkedContainerIds),\n );\n if (input.operation === \"link\") {\n assertContainerKekPathCurrent(\n input.targetContainerProjection.containerKeks,\n );\n }\n}\n"]}
|
|
@@ -77,6 +77,7 @@ async function completeRemoteDocumentLinkSet(input) {
|
|
|
77
77
|
const acknowledged = acknowledgedDocumentLinkSetMutation(input.completedPlan, input.response);
|
|
78
78
|
const persistedState = persistedDocumentStateFromAcknowledgement(acknowledged);
|
|
79
79
|
await acknowledgeDocumentMutation({
|
|
80
|
+
bundleDigest: input.response.bundleDigest,
|
|
80
81
|
execSql: input.execSql,
|
|
81
82
|
plan: input.completedPlan,
|
|
82
83
|
stillCurrent: input.st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I,CAAC,IAAI;YACX,OAAO,EAAE,MAAM,8BAA8B,CAAC;gBAC5C,GAAG,KAAK;gBACR,cAAc,EAAE,OAAO,CAAC,OAAO,CAAC,OAAO,KAAK,OAAO;gBACnD,OAAO;gBACP,yBAAyB;gBACzB,gBAAgB;aACjB,CAAC;YACF,MAAM,EAAE,QAAQ;SACjB,CAAC;QACF,OAAO,CAAC,OAAO,GAAG,uBAAuB,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACrE,OAAO,QAAQ,CAAC,OAAO,CAAC;IAC1B,CAAC,CAAC;IACF,OAAO,iCAAiC,CACtC,GAAG,EAAE,CACH,wCAAwC,CAAC,GAAG,EAAE,CAC5C,4CAA4C,CAAC;QAC3C,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,kBAAkB;QAClB,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,yBAAyB;QACzB,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,+BAA+B,EAC7B,KAAK,CAAC,+BAA+B;QACvC,gBAAgB;KACjB,CAAC,CACH,EACH,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import type {\n DocumentContentKeyTarget,\n DocumentLinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type { DocumentLinkSetMutationRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentLinkSetMutationResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n acknowledgedDocumentLinkSetMutation,\n persistedDocumentStateFromAcknowledgement,\n} from \"../../../data/documents/shared/responses\";\nimport { acknowledgeDocumentMutation } from \"../../../data/documents/shared/sync/mutationAcknowledgement\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationApi,\n DocumentLinkSetMutationOperation,\n RelinkRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { documentMayHaveAttachments } from \"../../../data/persistence/documents/documentAttachmentPresence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { recordDocumentAuthorAccessFailure } from \"../authorAccessFailure\";\nimport type { SubtreePurgeRoot } from \"../purge/subtreePurgeScope\";\nimport type { RemoteDocumentCollaborators } from \"../remote/remoteDocumentCollaborators\";\nimport { completeLinkSetMutationRequest } from \"../rotationBaseline\";\nimport { buildMaterializedDocumentLinkSetMutationPlan } from \"./index\";\nimport {\n type LinkSetAttachmentReuse,\n prepareDocumentLinkBlobRewraps,\n reuseCommittedBlobRewraps,\n} from \"./linkSetBlobRewraps\";\nimport {\n holdsLinkSetRefusals,\n INITIAL_LINK_SET_LEG_STATE,\n type LinkSetLegAttempt,\n type LinkSetSubmitFailure,\n linkSetAttemptEvent,\n type PreparedLinkSetRewraps,\n recordLinkSetLegRewraps,\n startLinkSetLegAttempt,\n transitionLinkSetLeg,\n} from \"./linkSetLegMachine\";\nimport { seedLinkSetWriterProjection } from \"./linkSetProjectionSeed\";\n\nasync function submitLinkSetMutation(input: {\n apiClient: DocumentLinkSetMutationApi;\n documentId: string;\n expectedOrganizationId: string;\n onFailure: (failure: LinkSetSubmitFailure) => void;\n operation: DocumentLinkSetMutationOperation;\n request: DocumentLinkSetMutationRequest;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<DocumentLinkSetMutationResponse | null> {\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input;\n // Preserve the HTTP failure for the durable move-intent queue. Its host\n // report waits until the leg knows the refusal is not one it recovers from.\n const resultFn =\n input.operation === \"link\"\n ? apiClient.linkDocumentResult.bind(apiClient)\n : apiClient.unlinkDocumentResult.bind(apiClient);\n const result = await resultFn(input.documentId, input.request, {\n expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,\n reportErrors: false,\n });\n if (result.ok) {\n return result.data;\n }\n // A refusal the operation no longer waits for is neither retried nor\n // reported.\n if (input.stillCurrent?.() === false) return null;\n input.onFailure({\n code: result.code,\n message: result.message,\n report: result.report,\n status: result.status,\n });\n return null;\n}\n\n/** Hand a refusal the leg does not recover from to its host and caller. */\nfunction reportLinkSetFailure(\n input: Pick<RelinkRemoteDocumentInput, \"onFailure\">,\n failure: LinkSetSubmitFailure,\n): void {\n failure.report?.();\n input.onFailure?.({\n code: failure.code,\n message: failure.message,\n status: failure.status,\n });\n}\n\ninterface LinkSetProjectionFetch<TProjection> {\n failure: LinkSetSubmitFailure | null;\n projection: TProjection | null;\n}\n\n// Cold-cache projection fetches must keep their HTTP status: collapsing a\n// 403 to null would leave an access-denied link/unlink routinely retriable\n// instead of parking its move for the access-restored signal (row 7).\nasync function fetchLinkSetProjection<TProjection>(input: {\n fetchProjectionResult: () => Promise<\n | { readonly data: TProjection; readonly ok: true }\n | DocumentSyncSubmitFailure\n >;\n}): Promise<LinkSetProjectionFetch<TProjection>> {\n const result = await input.fetchProjectionResult();\n if (result.ok) {\n return { failure: null, projection: result.data };\n }\n return {\n failure: {\n code: result.code,\n message: result.message,\n report: result.report,\n status: result.status,\n },\n projection: null,\n };\n}\n\nfunction fetchLinkSetDocumentProjection(\n apiClient: DocumentLinkSetMutationApi,\n documentId: string,\n): Promise<LinkSetProjectionFetch<DocumentWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getDocumentWriterProjectionResult.bind(\n apiClient,\n documentId,\n { reportErrors: false },\n ),\n });\n}\n\nfunction fetchLinkSetContainerProjection(\n apiClient: DocumentLinkSetMutationApi,\n containerId: string,\n): Promise<LinkSetProjectionFetch<ContainerWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getContainerWriterProjectionResult.bind(\n apiClient,\n containerId,\n { reportErrors: false },\n ),\n });\n}\n\nasync function completeRemoteDocumentLinkSet(input: {\n completedPlan: Parameters<typeof acknowledgedDocumentLinkSetMutation>[0];\n execSql: ExecSql;\n materializedPlan: Awaited<\n ReturnType<typeof buildMaterializedDocumentLinkSetMutationPlan>\n >;\n operation: DocumentLinkSetMutationOperation;\n response: DocumentLinkSetMutationResponse;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n apiClient: DocumentLinkSetMutationApi;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const acknowledged = acknowledgedDocumentLinkSetMutation(\n input.completedPlan,\n input.response,\n );\n const persistedState =\n persistedDocumentStateFromAcknowledgement(acknowledged);\n await acknowledgeDocumentMutation({\n execSql: input.execSql,\n plan: input.completedPlan,\n stillCurrent: input.stillCurrent,\n });\n await seedLinkSetWriterProjection({\n apiClient: input.apiClient,\n execSql: input.execSql,\n operation: input.operation,\n priorProjection: input.writerProjection,\n response: acknowledged,\n targetContainerId: input.targetContainerId,\n targetContainerProjection: input.targetContainerProjection,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n return {\n contentKey: input.materializedPlan.contentKey,\n contentKeyRotated: input.materializedPlan.contentKeyRotated,\n documentId: input.response.id,\n linkedContainerIds: [\n ...input.materializedPlan.plan.state.linkedContainerIds,\n ],\n persistedState,\n plan: input.completedPlan,\n response: input.response,\n };\n}\n\n/** What varies per link or unlink leg; the collaborators bind the rest. */\nexport interface RelinkRemoteDocumentRequest {\n /** Shared by the legs of one move or trash workflow. */\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n author: DocumentCreateAuthor;\n contentKey?: Uint8Array | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n eventId?: string | undefined;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: DocumentLinkSetMutationOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RelinkRemoteDocumentInput extends RelinkRemoteDocumentRequest {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetSecretKey: Uint8Array;\n}\n\n/**\n * A leg that cited rewraps without listing and was refused because the\n * attachment set (or a re-cited key epoch) moved lists and retries once, as a\n * leg that listed would have; that first refusal is neither reported nor\n * retried once the operation is no longer current (`transitionLinkSetLeg`).\n */\nexport async function relinkRemoteDocument(\n remote: RemoteDocumentCollaborators,\n request: RelinkRemoteDocumentRequest,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (!remote.encapsulationSecretKey) {\n throw new Error(\n \"Remote document link-set mutation requires an encapsulation key\",\n );\n }\n const input: RelinkRemoteDocumentInput = {\n ...request,\n apiClient: remote.api,\n execSql: remote.execSql,\n targetSecretKey: remote.encapsulationSecretKey,\n };\n const reuse = input.attachmentReuse;\n let leg = INITIAL_LINK_SET_LEG_STATE;\n let result: RelinkRemoteDocumentResult | null = null;\n while (leg.status === \"speculative\" || leg.status === \"fresh\") {\n const attempt = { current: startLinkSetLegAttempt(leg) };\n const heldFailures: LinkSetSubmitFailure[] = [];\n result = await relinkRemoteDocumentOnce(input, attempt, (failure) => {\n if (holdsLinkSetRefusals(attempt.current)) heldFailures.push(failure);\n else reportLinkSetFailure(input, failure);\n }).catch((error: unknown) => {\n // A leg that threw may have committed before failing: list again next.\n if (reuse) reuse.committed = null;\n throw error;\n });\n const event = linkSetAttemptEvent({\n attempt: attempt.current,\n committed: result !== null,\n heldFailures,\n stillCurrent: input.stillCurrent?.() !== false,\n });\n if (reuse)\n reuse.committed =\n event.type === \"attemptCommitted\" ? event.rewraps : null;\n leg = transitionLinkSetLeg(leg, event);\n }\n if (leg.status === \"failed\") {\n for (const failure of leg.unreported) reportLinkSetFailure(input, failure);\n }\n return result;\n}\n\n/** The attempt in flight; preparation replaces it with what it signed. */\ninterface LinkSetAttemptSlot {\n current: LinkSetLegAttempt;\n}\n\nasync function relinkRemoteDocumentOnce(\n input: RelinkRemoteDocumentInput,\n attempt: LinkSetAttemptSlot,\n onSubmitFailure: (failure: LinkSetSubmitFailure) => void,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (input.operation === \"unlink\" && !input.rotationSnapshot) {\n throw new Error(\n \"Document unlink requires a proven full-history rotation snapshot\",\n );\n }\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote document link-set mutation\",\n );\n const [writerFetch, targetContainerFetch] = await Promise.all([\n fetchLinkSetDocumentProjection(input.apiClient, input.documentId),\n fetchLinkSetContainerProjection(input.apiClient, input.targetContainerId),\n ]);\n if (!writerFetch.projection || !targetContainerFetch.projection) {\n // A failure the operation no longer waits for is not reported.\n if (input.stillCurrent?.() === false) return null;\n for (const failure of orderedProjectionFailures([\n writerFetch.failure,\n targetContainerFetch.failure,\n ])) {\n reportLinkSetFailure(input, failure);\n }\n return null;\n }\n const writerProjection = writerFetch.projection;\n const targetContainerProjection = targetContainerFetch.projection;\n if (input.stillCurrent?.() === false) return null;\n\n const signedAt = input.signedAt ?? new Date().toISOString();\n const materializedPlan = await prepareRemoteLinkSetMutation(\n { ...input, resolveProjectionUserKey, signedAt },\n writerProjection,\n targetContainerProjection,\n attempt,\n );\n if (!materializedPlan) return null;\n const request = await completeLinkSetMutationRequest({\n author: input.author,\n materializedPlan,\n operation: input.operation,\n rotationSnapshot: input.rotationSnapshot,\n signedAt,\n });\n const completedPlan = { ...materializedPlan.plan, request };\n if (input.beforeSubmit && !(await input.beforeSubmit())) return null;\n const response = await submitLinkSetMutation({\n apiClient: input.apiClient,\n documentId: completedPlan.documentId,\n expectedOrganizationId: completedPlan.state.organizationId,\n onFailure: onSubmitFailure,\n operation: input.operation,\n request: completedPlan.request,\n stillCurrent: input.stillCurrent,\n });\n if (!response) {\n return null;\n }\n if (input.stillCurrent?.() === false) return null;\n return completeRemoteDocumentLinkSet({\n apiClient: input.apiClient,\n completedPlan,\n execSql: input.execSql,\n materializedPlan,\n operation: input.operation,\n response,\n stillCurrent: input.stillCurrent,\n targetContainerId: input.targetContainerId,\n targetContainerProjection,\n writerProjection,\n });\n}\n\n// Every projection failure reaches the handler: the queued-move accumulator\n// classifies a vanished container from ANY coded container 404, so a document\n// fetch failure must not hide a container one (or vice versa). A 403 is\n// delivered last, so a single-slot consumer keeps the denial that parks the\n// move (row 7) while the accumulator still sees both.\nfunction orderedProjectionFailures(\n failures: readonly (LinkSetSubmitFailure | null)[],\n): LinkSetSubmitFailure[] {\n const present = failures.filter(\n (failure): failure is LinkSetSubmitFailure => failure !== null,\n );\n return [\n ...present.filter((failure) => failure.status !== 403),\n ...present.filter((failure) => failure.status === 403),\n ];\n}\n\n/**\n * Rewraps a first attempt may sign without listing: the previous leg's\n * envelopes, or none when the local view holds no attachment for the\n * document. The server's binding check at commit refuses either if stale.\n */\nasync function speculativeBlobRewraps(\n input: RelinkRemoteDocumentInput,\n writerProjection: DocumentWriterProjectionResponse,\n targets: readonly DocumentContentKeyTarget[],\n): Promise<{\n readonly rewraps: DocumentLinkAccessEventBody[\"blobRewraps\"];\n readonly source: \"reused\" | \"skipped\";\n} | null> {\n const committed = input.attachmentReuse?.committed;\n if (committed) {\n const reused = reuseCommittedBlobRewraps({\n committed,\n documentId: writerProjection.documentId,\n targets,\n });\n if (reused) return { rewraps: reused, source: \"reused\" };\n // The previous leg cited attachments this leg cannot re-cite: list them.\n if (committed.length > 0) return null;\n }\n if (\n await documentMayHaveAttachments(input.execSql, writerProjection.documentId)\n )\n return null;\n return { rewraps: [], source: \"skipped\" };\n}\n\nfunction prepareRemoteLinkSetMutation(\n input: RelinkRemoteDocumentInput & {\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt: string;\n },\n writerProjection: DocumentWriterProjectionResponse,\n targetContainerProjection: ContainerWriterProjectionResponse,\n attempt: LinkSetAttemptSlot,\n) {\n const prepareBlobRewraps = async (\n targets: readonly DocumentContentKeyTarget[],\n ) => {\n const prepared: PreparedLinkSetRewraps = (attempt.current.listing ===\n \"speculative\"\n ? await speculativeBlobRewraps(input, writerProjection, targets)\n : null) ?? {\n rewraps: await prepareDocumentLinkBlobRewraps({\n ...input,\n refreshListing: attempt.current.listing === \"fresh\",\n targets,\n targetContainerProjection,\n writerProjection,\n }),\n source: \"listed\",\n };\n attempt.current = recordLinkSetLegRewraps(attempt.current, prepared);\n return prepared.rewraps;\n };\n return recordDocumentAuthorAccessFailure(\n () =>\n nullOnProjectionVerificationCancellation(() =>\n buildMaterializedDocumentLinkSetMutationPlan({\n author: input.author,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n prepareBlobRewraps,\n contentKey: input.contentKey,\n eventId: input.eventId,\n execSql: input.execSql,\n operation: input.operation,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetContainerProjection,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n writerProjection,\n }),\n ),\n input.onFailure,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"linkSetRemote.js","sourceRoot":"","sources":["linkSetRemote.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,mCAAmC,EACnC,yCAAyC,GAC1C,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,2B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ACP,yBAAyB;gBACzB,gBAAgB;aACjB,CAAC;YACF,MAAM,EAAE,QAAQ;SACjB,CAAC;QACF,OAAO,CAAC,OAAO,GAAG,uBAAuB,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACrE,OAAO,QAAQ,CAAC,OAAO,CAAC;IAC1B,CAAC,CAAC;IACF,OAAO,iCAAiC,CACtC,GAAG,EAAE,CACH,wCAAwC,CAAC,GAAG,EAAE,CAC5C,4CAA4C,CAAC;QAC3C,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,kBAAkB;QAClB,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,yBAAyB;QACzB,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,+BAA+B,EAC7B,KAAK,CAAC,+BAA+B;QACvC,gBAAgB;KACjB,CAAC,CACH,EACH,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import type {\n DocumentContentKeyTarget,\n DocumentLinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type { DocumentLinkSetMutationRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentLinkSetMutationResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n acknowledgedDocumentLinkSetMutation,\n persistedDocumentStateFromAcknowledgement,\n} from \"../../../data/documents/shared/responses\";\nimport { acknowledgeDocumentMutation } from \"../../../data/documents/shared/sync/mutationAcknowledgement\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationApi,\n DocumentLinkSetMutationOperation,\n RelinkRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { documentMayHaveAttachments } from \"../../../data/persistence/documents/documentAttachmentPresence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { recordDocumentAuthorAccessFailure } from \"../authorAccessFailure\";\nimport type { SubtreePurgeRoot } from \"../purge/subtreePurgeScope\";\nimport type { RemoteDocumentCollaborators } from \"../remote/remoteDocumentCollaborators\";\nimport { completeLinkSetMutationRequest } from \"../rotationBaseline\";\nimport { buildMaterializedDocumentLinkSetMutationPlan } from \"./index\";\nimport {\n type LinkSetAttachmentReuse,\n prepareDocumentLinkBlobRewraps,\n reuseCommittedBlobRewraps,\n} from \"./linkSetBlobRewraps\";\nimport {\n holdsLinkSetRefusals,\n INITIAL_LINK_SET_LEG_STATE,\n type LinkSetLegAttempt,\n type LinkSetSubmitFailure,\n linkSetAttemptEvent,\n type PreparedLinkSetRewraps,\n recordLinkSetLegRewraps,\n startLinkSetLegAttempt,\n transitionLinkSetLeg,\n} from \"./linkSetLegMachine\";\nimport { seedLinkSetWriterProjection } from \"./linkSetProjectionSeed\";\n\nasync function submitLinkSetMutation(input: {\n apiClient: DocumentLinkSetMutationApi;\n documentId: string;\n expectedOrganizationId: string;\n onFailure: (failure: LinkSetSubmitFailure) => void;\n operation: DocumentLinkSetMutationOperation;\n request: DocumentLinkSetMutationRequest;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<DocumentLinkSetMutationResponse | null> {\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input;\n // Preserve the HTTP failure for the durable move-intent queue. Its host\n // report waits until the leg knows the refusal is not one it recovers from.\n const resultFn =\n input.operation === \"link\"\n ? apiClient.linkDocumentResult.bind(apiClient)\n : apiClient.unlinkDocumentResult.bind(apiClient);\n const result = await resultFn(input.documentId, input.request, {\n expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,\n reportErrors: false,\n });\n if (result.ok) {\n return result.data;\n }\n // A refusal the operation no longer waits for is neither retried nor\n // reported.\n if (input.stillCurrent?.() === false) return null;\n input.onFailure({\n code: result.code,\n message: result.message,\n report: result.report,\n status: result.status,\n });\n return null;\n}\n\n/** Hand a refusal the leg does not recover from to its host and caller. */\nfunction reportLinkSetFailure(\n input: Pick<RelinkRemoteDocumentInput, \"onFailure\">,\n failure: LinkSetSubmitFailure,\n): void {\n failure.report?.();\n input.onFailure?.({\n code: failure.code,\n message: failure.message,\n status: failure.status,\n });\n}\n\ninterface LinkSetProjectionFetch<TProjection> {\n failure: LinkSetSubmitFailure | null;\n projection: TProjection | null;\n}\n\n// Cold-cache projection fetches must keep their HTTP status: collapsing a\n// 403 to null would leave an access-denied link/unlink routinely retriable\n// instead of parking its move for the access-restored signal (row 7).\nasync function fetchLinkSetProjection<TProjection>(input: {\n fetchProjectionResult: () => Promise<\n | { readonly data: TProjection; readonly ok: true }\n | DocumentSyncSubmitFailure\n >;\n}): Promise<LinkSetProjectionFetch<TProjection>> {\n const result = await input.fetchProjectionResult();\n if (result.ok) {\n return { failure: null, projection: result.data };\n }\n return {\n failure: {\n code: result.code,\n message: result.message,\n report: result.report,\n status: result.status,\n },\n projection: null,\n };\n}\n\nfunction fetchLinkSetDocumentProjection(\n apiClient: DocumentLinkSetMutationApi,\n documentId: string,\n): Promise<LinkSetProjectionFetch<DocumentWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getDocumentWriterProjectionResult.bind(\n apiClient,\n documentId,\n { reportErrors: false },\n ),\n });\n}\n\nfunction fetchLinkSetContainerProjection(\n apiClient: DocumentLinkSetMutationApi,\n containerId: string,\n): Promise<LinkSetProjectionFetch<ContainerWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getContainerWriterProjectionResult.bind(\n apiClient,\n containerId,\n { reportErrors: false },\n ),\n });\n}\n\nasync function completeRemoteDocumentLinkSet(input: {\n completedPlan: Parameters<typeof acknowledgedDocumentLinkSetMutation>[0];\n execSql: ExecSql;\n materializedPlan: Awaited<\n ReturnType<typeof buildMaterializedDocumentLinkSetMutationPlan>\n >;\n operation: DocumentLinkSetMutationOperation;\n response: DocumentLinkSetMutationResponse;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n apiClient: DocumentLinkSetMutationApi;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const acknowledged = acknowledgedDocumentLinkSetMutation(\n input.completedPlan,\n input.response,\n );\n const persistedState =\n persistedDocumentStateFromAcknowledgement(acknowledged);\n await acknowledgeDocumentMutation({\n bundleDigest: input.response.bundleDigest,\n execSql: input.execSql,\n plan: input.completedPlan,\n stillCurrent: input.stillCurrent,\n });\n await seedLinkSetWriterProjection({\n apiClient: input.apiClient,\n execSql: input.execSql,\n operation: input.operation,\n priorProjection: input.writerProjection,\n response: acknowledged,\n targetContainerId: input.targetContainerId,\n targetContainerProjection: input.targetContainerProjection,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n return {\n contentKey: input.materializedPlan.contentKey,\n contentKeyRotated: input.materializedPlan.contentKeyRotated,\n documentId: input.response.id,\n linkedContainerIds: [\n ...input.materializedPlan.plan.state.linkedContainerIds,\n ],\n persistedState,\n plan: input.completedPlan,\n response: input.response,\n };\n}\n\n/** What varies per link or unlink leg; the collaborators bind the rest. */\nexport interface RelinkRemoteDocumentRequest {\n /** Shared by the legs of one move or trash workflow. */\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n author: DocumentCreateAuthor;\n contentKey?: Uint8Array | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n eventId?: string | undefined;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: DocumentLinkSetMutationOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RelinkRemoteDocumentInput extends RelinkRemoteDocumentRequest {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetSecretKey: Uint8Array;\n}\n\n/**\n * A leg that cited rewraps without listing and was refused because the\n * attachment set (or a re-cited key epoch) moved lists and retries once, as a\n * leg that listed would have; that first refusal is neither reported nor\n * retried once the operation is no longer current (`transitionLinkSetLeg`).\n */\nexport async function relinkRemoteDocument(\n remote: RemoteDocumentCollaborators,\n request: RelinkRemoteDocumentRequest,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (!remote.encapsulationSecretKey) {\n throw new Error(\n \"Remote document link-set mutation requires an encapsulation key\",\n );\n }\n const input: RelinkRemoteDocumentInput = {\n ...request,\n apiClient: remote.api,\n execSql: remote.execSql,\n targetSecretKey: remote.encapsulationSecretKey,\n };\n const reuse = input.attachmentReuse;\n let leg = INITIAL_LINK_SET_LEG_STATE;\n let result: RelinkRemoteDocumentResult | null = null;\n while (leg.status === \"speculative\" || leg.status === \"fresh\") {\n const attempt = { current: startLinkSetLegAttempt(leg) };\n const heldFailures: LinkSetSubmitFailure[] = [];\n result = await relinkRemoteDocumentOnce(input, attempt, (failure) => {\n if (holdsLinkSetRefusals(attempt.current)) heldFailures.push(failure);\n else reportLinkSetFailure(input, failure);\n }).catch((error: unknown) => {\n // A leg that threw may have committed before failing: list again next.\n if (reuse) reuse.committed = null;\n throw error;\n });\n const event = linkSetAttemptEvent({\n attempt: attempt.current,\n committed: result !== null,\n heldFailures,\n stillCurrent: input.stillCurrent?.() !== false,\n });\n if (reuse)\n reuse.committed =\n event.type === \"attemptCommitted\" ? event.rewraps : null;\n leg = transitionLinkSetLeg(leg, event);\n }\n if (leg.status === \"failed\") {\n for (const failure of leg.unreported) reportLinkSetFailure(input, failure);\n }\n return result;\n}\n\n/** The attempt in flight; preparation replaces it with what it signed. */\ninterface LinkSetAttemptSlot {\n current: LinkSetLegAttempt;\n}\n\nasync function relinkRemoteDocumentOnce(\n input: RelinkRemoteDocumentInput,\n attempt: LinkSetAttemptSlot,\n onSubmitFailure: (failure: LinkSetSubmitFailure) => void,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (input.operation === \"unlink\" && !input.rotationSnapshot) {\n throw new Error(\n \"Document unlink requires a proven full-history rotation snapshot\",\n );\n }\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote document link-set mutation\",\n );\n const [writerFetch, targetContainerFetch] = await Promise.all([\n fetchLinkSetDocumentProjection(input.apiClient, input.documentId),\n fetchLinkSetContainerProjection(input.apiClient, input.targetContainerId),\n ]);\n if (!writerFetch.projection || !targetContainerFetch.projection) {\n // A failure the operation no longer waits for is not reported.\n if (input.stillCurrent?.() === false) return null;\n for (const failure of orderedProjectionFailures([\n writerFetch.failure,\n targetContainerFetch.failure,\n ])) {\n reportLinkSetFailure(input, failure);\n }\n return null;\n }\n const writerProjection = writerFetch.projection;\n const targetContainerProjection = targetContainerFetch.projection;\n if (input.stillCurrent?.() === false) return null;\n\n const signedAt = input.signedAt ?? new Date().toISOString();\n const materializedPlan = await prepareRemoteLinkSetMutation(\n { ...input, resolveProjectionUserKey, signedAt },\n writerProjection,\n targetContainerProjection,\n attempt,\n );\n if (!materializedPlan) return null;\n const request = await completeLinkSetMutationRequest({\n author: input.author,\n materializedPlan,\n operation: input.operation,\n rotationSnapshot: input.rotationSnapshot,\n signedAt,\n });\n const completedPlan = { ...materializedPlan.plan, request };\n if (input.beforeSubmit && !(await input.beforeSubmit())) return null;\n const response = await submitLinkSetMutation({\n apiClient: input.apiClient,\n documentId: completedPlan.documentId,\n expectedOrganizationId: completedPlan.state.organizationId,\n onFailure: onSubmitFailure,\n operation: input.operation,\n request: completedPlan.request,\n stillCurrent: input.stillCurrent,\n });\n if (!response) {\n return null;\n }\n if (input.stillCurrent?.() === false) return null;\n return completeRemoteDocumentLinkSet({\n apiClient: input.apiClient,\n completedPlan,\n execSql: input.execSql,\n materializedPlan,\n operation: input.operation,\n response,\n stillCurrent: input.stillCurrent,\n targetContainerId: input.targetContainerId,\n targetContainerProjection,\n writerProjection,\n });\n}\n\n// Every projection failure reaches the handler: the queued-move accumulator\n// classifies a vanished container from ANY coded container 404, so a document\n// fetch failure must not hide a container one (or vice versa). A 403 is\n// delivered last, so a single-slot consumer keeps the denial that parks the\n// move (row 7) while the accumulator still sees both.\nfunction orderedProjectionFailures(\n failures: readonly (LinkSetSubmitFailure | null)[],\n): LinkSetSubmitFailure[] {\n const present = failures.filter(\n (failure): failure is LinkSetSubmitFailure => failure !== null,\n );\n return [\n ...present.filter((failure) => failure.status !== 403),\n ...present.filter((failure) => failure.status === 403),\n ];\n}\n\n/**\n * Rewraps a first attempt may sign without listing: the previous leg's\n * envelopes, or none when the local view holds no attachment for the\n * document. The server's binding check at commit refuses either if stale.\n */\nasync function speculativeBlobRewraps(\n input: RelinkRemoteDocumentInput,\n writerProjection: DocumentWriterProjectionResponse,\n targets: readonly DocumentContentKeyTarget[],\n): Promise<{\n readonly rewraps: DocumentLinkAccessEventBody[\"blobRewraps\"];\n readonly source: \"reused\" | \"skipped\";\n} | null> {\n const committed = input.attachmentReuse?.committed;\n if (committed) {\n const reused = reuseCommittedBlobRewraps({\n committed,\n documentId: writerProjection.documentId,\n targets,\n });\n if (reused) return { rewraps: reused, source: \"reused\" };\n // The previous leg cited attachments this leg cannot re-cite: list them.\n if (committed.length > 0) return null;\n }\n if (\n await documentMayHaveAttachments(input.execSql, writerProjection.documentId)\n )\n return null;\n return { rewraps: [], source: \"skipped\" };\n}\n\nfunction prepareRemoteLinkSetMutation(\n input: RelinkRemoteDocumentInput & {\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt: string;\n },\n writerProjection: DocumentWriterProjectionResponse,\n targetContainerProjection: ContainerWriterProjectionResponse,\n attempt: LinkSetAttemptSlot,\n) {\n const prepareBlobRewraps = async (\n targets: readonly DocumentContentKeyTarget[],\n ) => {\n const prepared: PreparedLinkSetRewraps = (attempt.current.listing ===\n \"speculative\"\n ? await speculativeBlobRewraps(input, writerProjection, targets)\n : null) ?? {\n rewraps: await prepareDocumentLinkBlobRewraps({\n ...input,\n refreshListing: attempt.current.listing === \"fresh\",\n targets,\n targetContainerProjection,\n writerProjection,\n }),\n source: \"listed\",\n };\n attempt.current = recordLinkSetLegRewraps(attempt.current, prepared);\n return prepared.rewraps;\n };\n return recordDocumentAuthorAccessFailure(\n () =>\n nullOnProjectionVerificationCancellation(() =>\n buildMaterializedDocumentLinkSetMutationPlan({\n author: input.author,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n prepareBlobRewraps,\n contentKey: input.contentKey,\n eventId: input.eventId,\n execSql: input.execSql,\n operation: input.operation,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetContainerProjection,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n writerProjection,\n }),\n ),\n input.onFailure,\n );\n}\n"]}
|
|
@@ -2,6 +2,7 @@ import { ContainerKekRepairInaccessibleError } from "../../../data/documents/sha
|
|
|
2
2
|
import { assertDocumentManifestBundleConsistent } from "../../../data/documents/shared/readers.js";
|
|
3
3
|
import { isDocumentSyncRequestLimitError } from "../../../data/documents/shared/sync/documentSyncOutgoingBatch.js";
|
|
4
4
|
import { resolvePullContinuationMinLsn, } from "../../../data/documents/shared/sync/syncPagination.js";
|
|
5
|
+
import { checkWithHeldBundleRecovery } from "../../../data/keyingProjectionVerification/index.js";
|
|
5
6
|
import { retrySyncPlanOrAbandon } from "../syncFailures/index.js";
|
|
6
7
|
import { abandonAncestorRepair, abandonBlockedSync, abandonInaccessibleAncestorRepair, abandonOversizedSyncPlan, isPullUnderWay, } from "../syncFailures/syncAbandon.js";
|
|
7
8
|
import { DocumentAncestorRepairAbandonedError, DocumentSyncPreparationRequiredError, } from "../syncFailures/syncRepairAbandon.js";
|
|
@@ -34,10 +35,15 @@ async function plannedPendingUpdates(input) {
|
|
|
34
35
|
return [];
|
|
35
36
|
if (input.pendingUpdates.length === 0)
|
|
36
37
|
return input.pendingUpdates;
|
|
37
|
-
|
|
38
|
+
// A held head this check refuses is dropped, so the next sync fetches it.
|
|
39
|
+
const { organizationId } = await checkWithHeldBundleRecovery({
|
|
40
|
+
execSql: input.sync.execSql,
|
|
41
|
+
projection: input.writerProjection,
|
|
42
|
+
stillCurrent: input.sync.stillCurrent,
|
|
43
|
+
}, () => assertDocumentManifestBundleConsistent({
|
|
38
44
|
bundle: input.writerProjection.documentManifest,
|
|
39
45
|
label: "Document sync manifest",
|
|
40
|
-
});
|
|
46
|
+
}));
|
|
41
47
|
if (!input.sync.isRemoteSyncBlocked?.(organizationId)) {
|
|
42
48
|
return input.pendingUpdates;
|
|
43
49
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncAttemptPlanning.js","sourceRoot":"","sources":["syncAttemptPlanning.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kEAAkE,CAAC;AACvH,OAAO,EAAE,sCAAsC,EAAE,MAAM,wCAAwC,CAAC;AAChG,OAAO,EAAE,+BAA+B,EAAE,MAAM,+DAA+D,CAAC;AAChH,OAAO,EAEL,6BAA6B,GAC9B,MAAM,oDAAoD,CAAC;
|
|
1
|
+
{"version":3,"file":"syncAttemptPlanning.js","sourceRoot":"","sources":["syncAttemptPlanning.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,m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WriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { assertDocumentManifestBundleConsistent } from \"../../../data/documents/shared/readers\";\nimport { isDocumentSyncRequestLimitError } from \"../../../data/documents/shared/sync/documentSyncOutgoingBatch\";\nimport {\n type DocumentSyncPullContinuation,\n resolvePullContinuationMinLsn,\n} from \"../../../data/documents/shared/sync/syncPagination\";\nimport { checkWithHeldBundleRecovery } from \"../../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { retrySyncPlanOrAbandon } from \"../syncFailures\";\nimport {\n abandonAncestorRepair,\n abandonBlockedSync,\n abandonInaccessibleAncestorRepair,\n abandonOversizedSyncPlan,\n isPullUnderWay,\n} from \"../syncFailures/syncAbandon\";\nimport type { TerminalSubmitFailureHandler } from \"../syncFailures/syncFailureClassification\";\nimport {\n DocumentAncestorRepairAbandonedError,\n DocumentSyncPreparationRequiredError,\n} from \"../syncFailures/syncRepairAbandon\";\nimport { prepareSyncAttemptContainerRekeys } from \"../syncRekeys/syncContainerRekeyPreparation\";\nimport { buildRemoteDocumentSyncPlan } from \"../syncRekeys/syncContainerRekeys\";\nimport type { RemoteDocumentSyncPass } from \"./remoteDocumentSyncPass\";\n\n/**\n * A write-bearing pass records through the submit handler (its queued writes\n * are what the failure blocks). A read-only pass records through the\n * revalidation handler so the refusal still leaves a durable trail instead\n * of silently never revalidating (edge-case row 13). A cursor continuation is\n * wire-level read-only, but its failure still blocks the queued writes it\n * deliberately deferred. Update-id recovery likewise empties the in-flight\n * batch while durable rows remain. Both keep the submit classification and\n * its 403 handling.\n */\nexport function projectionFailureHandler(\n input: RemoteDocumentSyncPass,\n failureBlocksQueuedWrites: boolean,\n): TerminalSubmitFailureHandler | undefined {\n return failureBlocksQueuedWrites\n ? input.onTerminalSubmitFailure\n : input.onReadOnlyProjectionFailure;\n}\n/**\n * The queued writes this attempt sends, or null when their organization is\n * held and the attempt has to stop. A cursor continuation sends none. Nor\n * does the restart of a pull whose cursor expired while its organization is\n * held: a held organization sends nothing, but a pull that already fetched a\n * page still has to finish, so the writes stay queued behind it.\n */\nasync function plannedPendingUpdates(input: {\n pendingUpdates: readonly PendingUpdateRecord[];\n pullContinuation?: DocumentSyncPullContinuation | undefined;\n sync: RemoteDocumentSyncPass;\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<readonly PendingUpdateRecord[] | null> {\n if (input.pullContinuation !== undefined) return [];\n if (input.pendingUpdates.length === 0) return input.pendingUpdates;\n // A held head this check refuses is dropped, so the next sync fetches it.\n const { organizationId } = await checkWithHeldBundleRecovery(\n {\n execSql: input.sync.execSql,\n projection: input.writerProjection,\n stillCurrent: input.sync.stillCurrent,\n },\n () =>\n assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document sync manifest\",\n }),\n );\n if (!input.sync.isRemoteSyncBlocked?.(organizationId)) {\n return input.pendingUpdates;\n }\n return isPullUnderWay(input.sync) ? [] : null;\n}\n\nexport async function planDocumentSyncAttempt(input: {\n /** The version the request advertises; defaults to the sync's live one. */\n localVersionVector?: string | null | undefined;\n pendingUpdates: readonly PendingUpdateRecord[];\n pullContinuation?: DocumentSyncPullContinuation | undefined;\n regenerateQueuedCheckpoints: boolean;\n sync: RemoteDocumentSyncPass;\n failureBlocksQueuedWrites: boolean;\n writerProjection: DocumentWriterProjectionResponse;\n}) {\n try {\n const pendingUpdates = await plannedPendingUpdates(input);\n if (!pendingUpdates) return abandonBlockedSync(input.sync);\n // Durable repair happens once at this explicit attempt boundary. The\n // retryable builder below may only sign inline plans against its projection.\n const prepared =\n pendingUpdates.length &&\n !input.sync.buildContainerRekeys &&\n input.sync.buildRotationSnapshot\n ? await prepareSyncAttemptContainerRekeys(\n input.sync,\n input.writerProjection,\n )\n : { projection: input.writerProjection, plans: undefined };\n if (!prepared) return null;\n return await retrySyncPlanOrAbandon({\n apiClient: input.sync.apiClient,\n buildWithProjection: (projection) =>\n buildRemoteDocumentSyncPlan({\n pendingUpdates,\n localVersionVector: input.localVersionVector,\n preparedRekeys:\n projection === prepared.projection ? prepared.plans : undefined,\n minLsn: resolvePullContinuationMinLsn(\n input.pullContinuation,\n input.sync.minLsn,\n ),\n pullCursor: input.pullContinuation?.cursor,\n projection,\n regenerateQueuedCheckpoints: input.regenerateQueuedCheckpoints,\n sync: input.sync,\n }),\n documentId: input.sync.documentId,\n onRemoteDocumentDeleted: input.sync.onRemoteDocumentDeleted,\n onSyncAbandoned: input.sync.onSyncAbandoned,\n onSyncTrace: input.sync.onSyncTrace,\n onTerminalFailure: projectionFailureHandler(\n input.sync,\n input.failureBlocksQueuedWrites,\n ),\n stillCurrent: input.sync.stillCurrent,\n writerProjection: prepared.projection,\n });\n } catch (error) {\n if (error instanceof DocumentSyncPreparationRequiredError)\n return \"retry\" as const;\n if (error instanceof DocumentAncestorRepairAbandonedError) {\n return abandonAncestorRepair(input.sync, error);\n }\n if (error instanceof ContainerKekRepairInaccessibleError) {\n return abandonInaccessibleAncestorRepair(input.sync, error);\n }\n if (!isDocumentSyncRequestLimitError(error)) {\n throw error;\n }\n return abandonOversizedSyncPlan(input.sync, error);\n }\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../../internal/crypto/index.js";
|
|
2
|
+
import { deriveDecodedProjection, } from "../../../internal/validators/response/index.js";
|
|
2
3
|
import { MAX_INLINE_CONTAINER_REKEYS } from "../../../internal/validators/util/index.js";
|
|
3
4
|
import { ContainerAuthorAccessError } from "../../../data/containers/shared/authorAccess.js";
|
|
4
5
|
import { ContainerKekRepairInaccessibleError } from "../../../data/documents/shared/containerKek/containerKekCurrency.js";
|
|
@@ -21,12 +22,12 @@ function firstStaleContainer(projection) {
|
|
|
21
22
|
}
|
|
22
23
|
return {
|
|
23
24
|
isPathTarget: index === path.containerKeks.length - 1,
|
|
24
|
-
projection: {
|
|
25
|
+
projection: deriveDecodedProjection(path, {
|
|
25
26
|
...path,
|
|
26
27
|
containerId: child.containerId,
|
|
27
28
|
containerKeks: path.containerKeks.slice(0, index + 1),
|
|
28
29
|
path: path.path.slice(0, index + 1),
|
|
29
|
-
},
|
|
30
|
+
}),
|
|
30
31
|
};
|
|
31
32
|
}
|
|
32
33
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncAutomaticContainerRekeys.js","sourceRoot":"","sources":["syncAutomaticContainerRekeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAE1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kEAAkE,CAAC;AACvH,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,4BAA4B,EAAE,MAAM,kFAAkF,CAAC;AAChI,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,kBAAkB,CAAC;AAEvE,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAQzE,SAAS,mBAAmB,CAC1B,UAA4C;IAE5C,KAAK,MAAM,IAAI,IAAI,4BAA4B,CAAC,UAAU,CAAC,EAAE,CAAC;QAC5D,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;YAClE,MAAM,MAAM,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;YAC7C,MAAM,K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E,IACE,MAAM,yBAAyB,CAC7B,IAAI,EACJ,iBAAiB,EACjB,kBAAkB,CAAC,WAAW,CAC/B,EACD,CAAC;oBACD,MAAM,IAAI,mCAAmC,CAC3C,kBAAkB,CAAC,WAAW,CAC/B,CAAC;gBACJ,CAAC;gBACD,MAAM,IAAI,CAAC,uBAAuB,EAAE,CAAC;oBACnC,IAAI,EAAE,KAAK,CAAC,IAAI;oBAChB,OAAO,EAAE,KAAK,CAAC,OAAO;oBACtB,EAAE,EAAE,KAAK;oBACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;oBACvB,MAAM,EAAE,KAAK,CAAC,MAAM;iBACrB,CAAC,CAAC;gBACH,MAAM,IAAI,oCAAoC,CAAC,SAAS,CAAC,CAAC;YAC5D,CAAC;YACD,qEAAqE;YACrE,uEAAuE;YACvE,uEAAuE;YACvE,MAAM,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC;gBACtC,CAAC,CAAC,IAAI,mCAAmC,CACrC,kBAAkB,CAAC,WAAW,CAC/B;gBACH,CAAC,CAAC,KAAK,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,UAAU,CAAC,GAAG,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;QAC/C,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpB,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { MAX_INLINE_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { buildMaterializedContainerRekeyPlan } from \"../../containers\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { hasOtherLinkedWriteAccess } from \"../syncFailures/syncRepairAccess\";\nimport { applyContainerRekeyPlan } from \"./syncContainerRekeyProjection\";\n\ninterface StaleContainer {\n /** The stale container is the one the document itself is linked into. */\n readonly isPathTarget: boolean;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\nfunction firstStaleContainer(\n projection: DocumentWriterProjectionResponse,\n): StaleContainer | null {\n for (const path of documentContainerProjections(projection)) {\n for (let index = 1; index < path.containerKeks.length; index += 1) {\n const parent = path.containerKeks[index - 1];\n const child = path.containerKeks[index];\n if (!parent || !child)\n throw new Error(\"Container KEK path is incomplete\");\n if (child.parentContainerKeyEpochId === parent.containerKeyEpochId) {\n continue;\n }\n return {\n isPathTarget: index === path.containerKeks.length - 1,\n projection: {\n ...path,\n containerId: child.containerId,\n containerKeks: path.containerKeks.slice(0, index + 1),\n path: path.path.slice(0, index + 1),\n },\n };\n }\n }\n return null;\n}\n\n/**\n * The stale container is not this writer's to re-key: no wrap on the verified\n * path opens it, or the signed path grants the signer no write access there.\n * Both are judged against the path sliced at the stale container, so a grant\n * held only further down never counts — exactly the API's `container.rekey`\n * rule. Anything else (keyring damage, a forged path) stays an error.\n *\n * A target's write refusal is handled separately: another linked target may\n * still authorize the document write. Key unwrap failures on a target stay\n * errors, because this path's readable grant should open its own key.\n */\nfunction isRepairInaccessible(error: unknown, stale: StaleContainer): boolean {\n if (stale.isPathTarget) return false;\n return (\n error instanceof ContainerAuthorAccessError ||\n (error instanceof ContainerKekTargetUnreachableError &&\n error.containerId === stale.projection.containerId)\n );\n}\n\n/** Prepare parent-first repairs; the sync transaction commits them with the write. */\nexport async function buildAutomaticContainerRekeys(\n sync: RemoteDocumentSyncPass,\n initialProjection: DocumentWriterProjectionResponse,\n): Promise<{ plans: MaterializedContainerRekeyPlan[]; hasMore: boolean }> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const plannedIds = new Set<string>();\n let projection = initialProjection;\n for (;;) {\n const stale = firstStaleContainer(projection);\n if (!stale) return { plans, hasMore: false };\n const previousProjection = stale.projection;\n if (plans.length >= MAX_INLINE_CONTAINER_REKEYS) {\n return { plans, hasMore: true };\n }\n // Use the shared cancellation sentinel: syncRemoteDocument converts only\n // that to a graceful null, so a plain Error would report a routine\n // generation flip mid-repair as a real sync failure.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n if (plannedIds.has(previousProjection.containerId)) {\n // Abandon like every other routine repair failure: two linked paths\n // disagreeing about a container is a concurrent-rotation race, not a\n // defect, and a raw Error would crash the sync lane instead.\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n // Assert rather than adopt: resolveRotationContext compares the verified\n // manifest's organization against the author's, so substituting the path's\n // own organization here would make that the only cross-org check and leave\n // it comparing a server-supplied value with itself.\n if (previousProjection.organizationId !== sync.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair crosses the author's organization\",\n );\n }\n const planned = await buildMaterializedContainerRekeyPlan({\n author: sync.author,\n persistVerificationCheckpoints: false,\n previousProjection,\n signedAt: sync.signedAt,\n targetSecretKey: sync.targetSecretKey,\n resolveProjectionUserKey: sync.resolveProjectionUserKey,\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n execSql: sync.execSql,\n }).catch(async (error: unknown) => {\n if (error instanceof ContainerAuthorAccessError && stale.isPathTarget) {\n if (\n await hasOtherLinkedWriteAccess(\n sync,\n initialProjection,\n previousProjection.containerId,\n )\n ) {\n throw new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n );\n }\n await sync.onTerminalSubmitFailure?.({\n code: error.code,\n message: error.message,\n ok: false,\n report: () => undefined,\n status: error.status,\n });\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // Repairs run parent-first and access inherits downward, so only the\n // first stale container can be out of reach. Retry-classified like any\n // stale path: one refetch sees a repair a capable member already made.\n throw isRepairInaccessible(error, stale)\n ? new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n )\n : error;\n });\n plannedIds.add(previousProjection.containerId);\n plans.push(planned);\n projection = await applyContainerRekeyPlan(projection, planned);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncAutomaticContainerRekeys.js","sourceRoot":"","sources":["syncAutomaticContainerRekeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAGL,uBAAuB,GACxB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAE1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kEAAkE,CAAC;AACvH,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,4BAA4B,EAAE,MAAM,kFAAkF,CAAC;AAChI,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,kBAAkB,CAAC;AAEvE,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAQzE,SAAS,mBAAmB,CAC1B,UAA4C;IAE5C,KAAK,MAAM,IAAI,IAAI,4BAA4B,CAAC,UAAU,CAAC,EAAE,CAAC;Q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ACvD,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,+BAA+B,EAAE,IAAI,CAAC,+BAA+B;YACrE,OAAO,EAAE,IAAI,CAAC,OAAO;SACtB,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,KAAc,EAAE,EAAE;YAChC,IAAI,KAAK,YAAY,0BAA0B,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;gBACtE,IACE,MAAM,yBAAyB,CAC7B,IAAI,EACJ,iBAAiB,EACjB,kBAAkB,CAAC,WAAW,CAC/B,EACD,CAAC;oBACD,MAAM,IAAI,mCAAmC,CAC3C,kBAAkB,CAAC,WAAW,CAC/B,CAAC;gBACJ,CAAC;gBACD,MAAM,IAAI,CAAC,uBAAuB,EAAE,CAAC;oBACnC,IAAI,EAAE,KAAK,CAAC,IAAI;oBAChB,OAAO,EAAE,KAAK,CAAC,OAAO;oBACtB,EAAE,EAAE,KAAK;oBACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;oBACvB,MAAM,EAAE,KAAK,CAAC,MAAM;iBACrB,CAAC,CAAC;gBACH,MAAM,IAAI,oCAAoC,CAAC,SAAS,CAAC,CAAC;YAC5D,CAAC;YACD,qEAAqE;YACrE,uEAAuE;YACvE,uEAAuE;YACvE,MAAM,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC;gBACtC,CAAC,CAAC,IAAI,mCAAmC,CACrC,kBAAkB,CAAC,WAAW,CAC/B;gBACH,CAAC,CAAC,KAAK,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,UAAU,CAAC,GAAG,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;QAC/C,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpB,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n type ContainerWriterProjectionResponse,\n type DocumentWriterProjectionResponse,\n deriveDecodedProjection,\n} from \"@tearleads/validators/response\";\nimport { MAX_INLINE_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { buildMaterializedContainerRekeyPlan } from \"../../containers\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { hasOtherLinkedWriteAccess } from \"../syncFailures/syncRepairAccess\";\nimport { applyContainerRekeyPlan } from \"./syncContainerRekeyProjection\";\n\ninterface StaleContainer {\n /** The stale container is the one the document itself is linked into. */\n readonly isPathTarget: boolean;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\nfunction firstStaleContainer(\n projection: DocumentWriterProjectionResponse,\n): StaleContainer | null {\n for (const path of documentContainerProjections(projection)) {\n for (let index = 1; index < path.containerKeks.length; index += 1) {\n const parent = path.containerKeks[index - 1];\n const child = path.containerKeks[index];\n if (!parent || !child)\n throw new Error(\"Container KEK path is incomplete\");\n if (child.parentContainerKeyEpochId === parent.containerKeyEpochId) {\n continue;\n }\n return {\n isPathTarget: index === path.containerKeks.length - 1,\n projection: deriveDecodedProjection(path, {\n ...path,\n containerId: child.containerId,\n containerKeks: path.containerKeks.slice(0, index + 1),\n path: path.path.slice(0, index + 1),\n }),\n };\n }\n }\n return null;\n}\n\n/**\n * The stale container is not this writer's to re-key: no wrap on the verified\n * path opens it, or the signed path grants the signer no write access there.\n * Both are judged against the path sliced at the stale container, so a grant\n * held only further down never counts — exactly the API's `container.rekey`\n * rule. Anything else (keyring damage, a forged path) stays an error.\n *\n * A target's write refusal is handled separately: another linked target may\n * still authorize the document write. Key unwrap failures on a target stay\n * errors, because this path's readable grant should open its own key.\n */\nfunction isRepairInaccessible(error: unknown, stale: StaleContainer): boolean {\n if (stale.isPathTarget) return false;\n return (\n error instanceof ContainerAuthorAccessError ||\n (error instanceof ContainerKekTargetUnreachableError &&\n error.containerId === stale.projection.containerId)\n );\n}\n\n/** Prepare parent-first repairs; the sync transaction commits them with the write. */\nexport async function buildAutomaticContainerRekeys(\n sync: RemoteDocumentSyncPass,\n initialProjection: DocumentWriterProjectionResponse,\n): Promise<{ plans: MaterializedContainerRekeyPlan[]; hasMore: boolean }> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const plannedIds = new Set<string>();\n let projection = initialProjection;\n for (;;) {\n const stale = firstStaleContainer(projection);\n if (!stale) return { plans, hasMore: false };\n const previousProjection = stale.projection;\n if (plans.length >= MAX_INLINE_CONTAINER_REKEYS) {\n return { plans, hasMore: true };\n }\n // Use the shared cancellation sentinel: syncRemoteDocument converts only\n // that to a graceful null, so a plain Error would report a routine\n // generation flip mid-repair as a real sync failure.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n if (plannedIds.has(previousProjection.containerId)) {\n // Abandon like every other routine repair failure: two linked paths\n // disagreeing about a container is a concurrent-rotation race, not a\n // defect, and a raw Error would crash the sync lane instead.\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n // Assert rather than adopt: resolveRotationContext compares the verified\n // manifest's organization against the author's, so substituting the path's\n // own organization here would make that the only cross-org check and leave\n // it comparing a server-supplied value with itself.\n if (previousProjection.organizationId !== sync.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair crosses the author's organization\",\n );\n }\n const planned = await buildMaterializedContainerRekeyPlan({\n author: sync.author,\n persistVerificationCheckpoints: false,\n previousProjection,\n signedAt: sync.signedAt,\n targetSecretKey: sync.targetSecretKey,\n resolveProjectionUserKey: sync.resolveProjectionUserKey,\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n execSql: sync.execSql,\n }).catch(async (error: unknown) => {\n if (error instanceof ContainerAuthorAccessError && stale.isPathTarget) {\n if (\n await hasOtherLinkedWriteAccess(\n sync,\n initialProjection,\n previousProjection.containerId,\n )\n ) {\n throw new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n );\n }\n await sync.onTerminalSubmitFailure?.({\n code: error.code,\n message: error.message,\n ok: false,\n report: () => undefined,\n status: error.status,\n });\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // Repairs run parent-first and access inherits downward, so only the\n // first stale container can be out of reach. Retry-classified like any\n // stale path: one refetch sees a repair a capable member already made.\n throw isRepairInaccessible(error, stale)\n ? new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n )\n : error;\n });\n plannedIds.add(previousProjection.containerId);\n plans.push(planned);\n projection = await applyContainerRekeyPlan(projection, planned);\n }\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { computeDocumentContentKeyTargetHash } from "../../../internal/crypto/index.js";
|
|
2
|
+
import { deriveDecodedProjection, } from "../../../internal/validators/response/index.js";
|
|
2
3
|
import { normalizeDocumentKekTargetResponse, readManifestContainerId, } from "../../../data/documents/shared/readers.js";
|
|
3
4
|
function replaceRekeyedPathNode(input) {
|
|
4
5
|
const index = input.projection.path.findIndex((bundle) => readManifestContainerId(bundle) === input.plan.plan.containerId);
|
|
@@ -54,7 +55,7 @@ export async function applyContainerRekeyPlan(writerProjection, plan) {
|
|
|
54
55
|
throw new Error("Document inline rekey does not belong to its writer projection");
|
|
55
56
|
}
|
|
56
57
|
const documentKeyTargetHash = await computeDocumentContentKeyTargetHash(targets);
|
|
57
|
-
return {
|
|
58
|
+
return deriveDecodedProjection(writerProjection, {
|
|
58
59
|
...writerProjection,
|
|
59
60
|
authorizingContainerPaths,
|
|
60
61
|
...(documentKeyTargetHash === writerProjection.contentKeyBundle.targetHash
|
|
@@ -67,7 +68,7 @@ export async function applyContainerRekeyPlan(writerProjection, plan) {
|
|
|
67
68
|
linkedContainerManifestHashes: targets.map((target) => target.containerManifestHash),
|
|
68
69
|
targets: targets.map((target) => ({ ...target })),
|
|
69
70
|
},
|
|
70
|
-
};
|
|
71
|
+
});
|
|
71
72
|
}
|
|
72
73
|
export async function applyDocumentSyncContainerRekeys(input) {
|
|
73
74
|
let projection = input.writerProjection;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncContainerRekeyProjection.js","sourceRoot":"","sources":["syncContainerRekeyProjection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"syncContainerRekeyProjection.js","sourceRoot":"","sources":["syncContainerRekeyProjection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,EAEL,uBAAuB,GACxB,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,kCAAkC,EAClC,uBAAuB,GACxB,MAAM,wCAAwC,CAAC;AAEhD,SAAS,sBAAsB,CAAC,KAG/B;IACC,MAAM,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS,CAC3C,CAAC,MAAM,EAAE,EAAE,CAAC,uBAAuB,CAAC,MAAM,CAAC,KAAK,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAC5E,CAAC;IACF,IAAI,KAAK,GAAG,CAAC;QAAE,OAAO,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;IACxE,MAAM,gBAAgB,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACtD,MAAM,WAAW,GAAG,KAAK,CAAC,UAAU,CAAC,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E,qBAAqB,EAAE,IAAa,EAAE,CAAC;QAC7C,kBAAkB,EAAE;YAClB,GAAG,gBAAgB,CAAC,kBAAkB;YACtC,qBAAqB;YACrB,0BAA0B,EAAE,OAAO,CAAC,GAAG,CACrC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,mBAAmB,CACvC;YACD,6BAA6B,EAAE,OAAO,CAAC,GAAG,CACxC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,qBAAqB,CACzC;YACD,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;SAClD;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gCAAgC,CAAC,KAGtD;IACC,IAAI,UAAU,GAAG,KAAK,CAAC,gBAAgB,CAAC;IACxC,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;QAC/B,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { computeDocumentContentKeyTargetHash } from \"@tearleads/crypto\";\nimport {\n type DocumentWriterProjectionResponse,\n deriveDecodedProjection,\n} from \"@tearleads/validators/response\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport {\n normalizeDocumentKekTargetResponse,\n readManifestContainerId,\n} from \"../../../data/documents/shared/readers\";\n\nfunction replaceRekeyedPathNode(input: {\n plan: MaterializedContainerRekeyPlan;\n projection: DocumentWriterProjectionResponse[\"authorizingContainerPaths\"][number];\n}) {\n const index = input.projection.path.findIndex(\n (bundle) => readManifestContainerId(bundle) === input.plan.plan.containerId,\n );\n if (index < 0) return { projection: input.projection, replaced: false };\n const previousManifest = input.projection.path[index];\n const previousKek = input.projection.containerKeks[index];\n const nextManifest = input.plan.writerProjection.path.at(-1);\n const nextKek = input.plan.writerProjection.containerKeks.at(-1);\n if (\n !previousManifest ||\n !previousKek ||\n !nextManifest ||\n !nextKek ||\n previousManifest.manifestHash !==\n input.plan.plan.previousManifest.manifestHash ||\n previousKek.accessManifestHash !== previousManifest.manifestHash\n ) {\n throw new Error(\"Document inline rekey projection predecessor mismatch\");\n }\n const path = [...input.projection.path];\n const containerKeks = [...input.projection.containerKeks];\n path[index] = nextManifest;\n containerKeks[index] = nextKek;\n return {\n projection: { ...input.projection, containerKeks, path },\n replaced: true,\n };\n}\n\nexport async function applyContainerRekeyPlan(\n writerProjection: DocumentWriterProjectionResponse,\n plan: MaterializedContainerRekeyPlan,\n): Promise<DocumentWriterProjectionResponse> {\n let replacedPath = false;\n const authorizingContainerPaths =\n writerProjection.authorizingContainerPaths.map((projection) => {\n const replaced = replaceRekeyedPathNode({ plan, projection });\n replacedPath ||= replaced.replaced;\n return replaced.projection;\n });\n const nextKek = plan.writerProjection.containerKeks.at(-1);\n const nextManifest = plan.writerProjection.path.at(-1);\n if (!nextKek || !nextManifest) {\n throw new Error(\"Document inline rekey projection is empty\");\n }\n let replacedTarget = false;\n const targets = normalizeDocumentKekTargetResponse(\n writerProjection.documentKekTargets,\n ).map((target) => {\n if (target.containerId !== plan.plan.containerId) return target;\n replacedTarget = true;\n return {\n ...target,\n containerKeyEpoch: nextKek.containerKeyEpoch,\n containerKeyEpochId: nextKek.containerKeyEpochId,\n containerManifestHash: nextManifest.manifestHash,\n };\n });\n if (!replacedPath && !replacedTarget) {\n throw new Error(\n \"Document inline rekey does not belong to its writer projection\",\n );\n }\n const documentKeyTargetHash =\n await computeDocumentContentKeyTargetHash(targets);\n return deriveDecodedProjection(writerProjection, {\n ...writerProjection,\n authorizingContainerPaths,\n ...(documentKeyTargetHash === writerProjection.contentKeyBundle.targetHash\n ? {}\n : { contentKeyBundleStale: true as const }),\n documentKekTargets: {\n ...writerProjection.documentKekTargets,\n documentKeyTargetHash,\n linkedContainerKeyEpochIds: targets.map(\n (target) => target.containerKeyEpochId,\n ),\n linkedContainerManifestHashes: targets.map(\n (target) => target.containerManifestHash,\n ),\n targets: targets.map((target) => ({ ...target })),\n },\n });\n}\n\nexport async function applyDocumentSyncContainerRekeys(input: {\n plans: readonly MaterializedContainerRekeyPlan[];\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<DocumentWriterProjectionResponse> {\n let projection = input.writerProjection;\n for (const plan of input.plans) {\n projection = await applyContainerRekeyPlan(projection, plan);\n }\n return projection;\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { compareCanonicalStrings, computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, computePrincipalStateHash, } from "../../../internal/crypto/index.js";
|
|
1
|
+
import { compareCanonicalStrings, computeAccessEventHash, computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, computePrincipalStateHash, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { canonicalKeyingJsonString } from "../../../data/keying/canonicalJson.js";
|
|
3
|
-
import { readContainerKeyEpoch, readContainerKeyWrap, } from "../../../data/keyingProjectionVerification/readers.js";
|
|
3
|
+
import { readAccessEvent, readContainerKeyEpoch, readContainerKeyWrap, } from "../../../data/keyingProjectionVerification/readers.js";
|
|
4
4
|
import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
|
|
5
5
|
function sortedCanonicalValues(values, label) {
|
|
6
6
|
return [...values].sort((left, right) => compareCanonicalStrings(canonicalKeyingJsonString(left, label), canonicalKeyingJsonString(right, label)));
|
|
@@ -39,16 +39,23 @@ async function assertContainerMutationAcknowledgements(input) {
|
|
|
39
39
|
recipientKind: wrap.recipientKind,
|
|
40
40
|
};
|
|
41
41
|
}), "authored recipient target");
|
|
42
|
-
// The request carries this client's own hash of the manifest it signed
|
|
43
|
-
// and
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
//
|
|
47
|
-
//
|
|
42
|
+
// The request carries this client's own hash of the manifest it signed
|
|
43
|
+
// and the signed event, whose hashes the acknowledgement must name. The
|
|
44
|
+
// manifest hash commits the epoch, but the request no longer names it,
|
|
45
|
+
// so the receipt's epoch label is not compared here: journal recovery
|
|
46
|
+
// discards the receipt after this check, and the in-process path stores
|
|
47
|
+
// a head only through the plan-based container acknowledgement, which
|
|
48
|
+
// requires the plan's epoch. Every field compared here is one the
|
|
49
|
+
// server received in the request, so this binds the receipt to the
|
|
50
|
+
// request; it never proved a commit, with or without the epoch. A
|
|
51
|
+
// rotation's signed body commits its keyring hash, so a substituted
|
|
52
|
+
// keyring must refuse here, before journal recovery clears the saved
|
|
53
|
+
// request. A grant that keeps its epoch commits none; the container
|
|
54
|
+
// acknowledgement checks the retained keyring against the epoch's own.
|
|
48
55
|
const committedKeyringHash = Reflect.get(Object(request.body), "keyringHash");
|
|
49
56
|
if (response.manifestHead.manifestHash !== request.expectedManifestHash ||
|
|
50
|
-
response.
|
|
51
|
-
|
|
57
|
+
response.eventHash !==
|
|
58
|
+
(await computeAccessEventHash(readAccessEvent(request.event, label))) ||
|
|
52
59
|
response.containerKek.containerKeyEpochId !== keyEpoch.id ||
|
|
53
60
|
response.containerKek.containerKeyEpoch !== keyEpoch.keyEpoch ||
|
|
54
61
|
response.containerKek.keyEpochHash !==
|