@tearleads/client-sdk 0.1.242 → 0.1.244
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/currentPrincipalMutations.js +1 -0
- package/client/organizations/currentPrincipalMutations.js.map +1 -1
- package/client/organizations/principalMutations.d.ts +5 -0
- package/client/organizations/principalMutations.js +1 -0
- package/client/organizations/principalMutations.js.map +1 -1
- 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/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/principals/organizationDirectoryKeying.js +136 -0
- package/data/principals/organizationDirectoryKeying.js.map +1 -0
- package/data/principals/organizationGroupDirectoryRequest.js +17 -11
- package/data/principals/organizationGroupDirectoryRequest.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +55 -0
- package/internal/api-client/client/containerMutations.d.ts +11 -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/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/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/validators/operation/auth.d.ts +40 -0
- package/internal/validators/operation/containerMutations.d.ts +44 -0
- package/internal/validators/operation/documentMutations.d.ts +12 -0
- package/internal/validators/operation/organizations.d.ts +48 -0
- package/internal/validators/operation/principals.d.ts +16 -0
- 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 +16 -0
- package/internal/validators/response/container.js +3 -0
- package/internal/validators/response/container.js.map +1 -1
- package/internal/validators/response/containerMetadata.d.ts +8 -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/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/projectionCache.js +3 -0
- package/workflows/container-contents/container-state/projectionCache.js.map +1 -1
- package/workflows/container-contents/metadata/index.js +5 -2
- package/workflows/container-contents/metadata/index.js.map +1 -1
- package/workflows/containers/child/recite.js +4 -2
- package/workflows/containers/child/recite.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/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/groupPolicy/commitCurrentGroupPolicyMutation.js +1 -0
- package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -1
- package/workflows/organizations/groupShare/currentShareGrantMutation.js +3 -0
- package/workflows/organizations/groupShare/currentShareGrantMutation.js.map +1 -1
- package/workflows/organizations/groupShare/shareWithGroup.js +2 -0
- package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js +3 -0
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
- package/workflows/organizations/groups/deleteCurrentOrganizationGroup.js +1 -0
- package/workflows/organizations/groups/deleteCurrentOrganizationGroup.js.map +1 -1
- package/workflows/organizations/groups/deleteOrganizationGroup.d.ts +2 -0
- package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -0
- package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
- package/workflows/organizations/groups/organizationGroupDirectory.js +1 -0
- package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
- package/workflows/organizations/principalPolicy/index.d.ts +12 -0
- package/workflows/organizations/principalPolicy/index.js +11 -0
- package/workflows/organizations/principalPolicy/index.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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAdoption.js","sourceRoot":"","sources":["createAdoption.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,wCAAwC,EACxC,0CAA0C,EAC1C,4CAA4C,GAC7C,MAAM,2CAA2C,CAAC;AAEnD,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EAAE,gDAAgD,EAAE,MAAM,0CAA0C,CAAC;AAK5G,OAAO,EACL,eAAe,EACf,kBAAkB,GACnB,MAAM,oDAAoD,CAAC;AAc5D;;;;;;;;;;;;;GAaG;AACH,SAAS,8BAA8B,CACrC,KAAkC,EAClC,gBAAkD;IAElD,MAAM,KAAK,GAAG,0BAA0B,CAAC;IACzC,MAAM,aAAa,GAAG,IAAI,GAAG,CAC3B,gBAAgB,CAAC,uBAAuB,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;QACvD,MAAM,CAAC,YAAY;QACnB,MAAM;KACP,CAAC,CACH,CAAC;IACF,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAClC,IAAI,MAAM,GAAG,gBAAgB,CAAC,gBAAgB,CAAC;IAC/C,SAAS,CAAC;QACR,MAAM,QAAQ,GAAG,kBAAkB,CAAC,MAAM,CAAC,QAAQ,EAAE,GAAG,KAAK,WAAW,CAAC,CAAC;QAC1E,IACE,QAAQ,CAAC,UAAU,KAAK,UAAU;YAClC,QAAQ,CAAC,QAAQ,KAAK,KAAK,CA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H,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAClD,KAAK,CAAC,SAAS,CAAC,6BAA6B,CAC3C,gBAAgB,CAAC,UAAU,EAC3B,gBAAgB,CACjB,CAAC;IACF,OAAO;QACL,UAAU;QACV,UAAU,EAAE,gBAAgB,CAAC,UAAU;QACvC,cAAc,EACZ,gDAAgD,CAAC,gBAAgB,CAAC;QACpE,gBAAgB;KACjB,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n assertDocumentWriterProjectionConsistent,\n readLinkedContainerIdsFromDocumentManifest,\n unwrapDocumentContentKeyFromWriterProjection,\n} from \"../../../data/documents/shared/projection\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { persistedDocumentCreateStateFromWriterProjection } from \"../../../data/documents/shared/responses\";\nimport type {\n CreateRemoteDocumentResult,\n DocumentCreateApi,\n} from \"../../../data/documents/shared/types\";\nimport {\n readAccessEvent,\n readAccessManifest,\n} from \"../../../data/keyingProjectionVerification/readers\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\ntype RemoteDocumentAdoptionInput = {\n readonly apiClient: DocumentCreateApi;\n readonly documentId: string;\n readonly execSql: ExecSql;\n readonly expectedContainerId: string;\n readonly expectedOrganizationId: string;\n /** The local user whose pending create the retry is recovering. */\n readonly expectedSignerUserId: string;\n readonly targetSecretKey: Uint8Array;\n} & ProjectionVerificationOptions;\n\n/**\n * A retry after a lost create response can only recover the local user's own\n * create: the server serves whatever document holds the stable id we minted,\n * and an honest server only ever committed ours under it. A create event signed\n * by anyone else is a foreign document colliding on that id (a member with\n * write access on the same container, or a dishonest server), which must not be\n * adopted as if it were the pending local write.\n *\n * The create event is located by walking the served head's predecessor chain,\n * not by scanning the history for any parentless manifest: the history is\n * server-supplied, so a dishonest server could splice in a genesis this user\n * signed for a different document. Every manifest on the chain must also name\n * the requested document.\n */\nfunction assertCreateEventSignedLocally(\n input: RemoteDocumentAdoptionInput,\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n const label = \"Document create conflict\";\n const historyByHash = new Map(\n writerProjection.documentManifestHistory.map((bundle) => [\n bundle.manifestHash,\n bundle,\n ]),\n );\n const visited = new Set<string>();\n let bundle = writerProjection.documentManifest;\n for (;;) {\n const manifest = readAccessManifest(bundle.manifest, `${label} manifest`);\n if (\n manifest.objectKind !== \"document\" ||\n manifest.objectId !== input.documentId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${label} manifest chain names another document`,\n );\n }\n if (manifest.previousManifestHash === null) {\n const createEvent = readAccessEvent(\n bundle.event.event,\n `${label} create event`,\n );\n if (createEvent.signerUserId !== input.expectedSignerUserId) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n `${label} create event was signed by another user`,\n );\n }\n return;\n }\n if (visited.has(bundle.manifestHash)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `${label} manifest history is cyclic`,\n );\n }\n visited.add(bundle.manifestHash);\n const previous = historyByHash.get(manifest.previousManifestHash);\n if (!previous) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `${label} does not expose its create event`,\n );\n }\n bundle = previous;\n }\n}\n\nfunction assertExpectedAdoptionScope(\n input: RemoteDocumentAdoptionInput,\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n const linkedContainerIds =\n readLinkedContainerIdsFromDocumentManifest(writerProjection);\n const expectedPath = writerProjection.authorizingContainerPaths.find(\n (projection) =>\n projection.containerId === input.expectedContainerId &&\n projection.organizationId === input.expectedOrganizationId,\n );\n if (\n linkedContainerIds.length !== 1 ||\n linkedContainerIds[0] !== input.expectedContainerId ||\n !expectedPath\n ) {\n throw new Error(\n \"Document create conflict belongs to another container or organization\",\n );\n }\n}\n\n/** Recover a committed retry only when it belongs to the intended org scope. */\nexport async function adoptExistingRemoteDocument(\n input: RemoteDocumentAdoptionInput,\n): Promise<CreateRemoteDocumentResult | null> {\n const writerProjection = await input.apiClient.getDocumentWriterProjection(\n input.documentId,\n );\n if (!writerProjection) return null;\n\n // Reject a foreign collision before verification can pin its checkpoints.\n assertExpectedAdoptionScope(input, writerProjection);\n assertCreateEventSignedLocally(input, writerProjection);\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache = new Map<string, VerifiedPrincipalPolicy>();\n const targets = await assertDocumentWriterProjectionConsistent(\n writerProjection,\n {\n execSql: input.execSql,\n principalPolicyCache,\n verifiedByHash,\n ...projectionVerificationOptions(input),\n },\n );\n if (\n targets.length !== 1 ||\n targets[0]?.containerId !== input.expectedContainerId\n ) {\n throw new Error(\n \"Document create conflict belongs to another container or organization\",\n );\n }\n const contentKey = await unwrapDocumentContentKeyFromWriterProjection({\n execSql: input.execSql,\n principalPolicyCache,\n secretKey: input.targetSecretKey,\n verifiedByHash,\n writerProjection,\n ...projectionVerificationOptions(input),\n });\n if (input.stillCurrent?.() === false) return null;\n input.apiClient.primeDocumentWriterProjection(\n writerProjection.documentId,\n writerProjection,\n );\n return {\n contentKey,\n documentId: writerProjection.documentId,\n persistedState:\n persistedDocumentCreateStateFromWriterProjection(writerProjection),\n writerProjection,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"createAdoption.js","sourceRoot":"","sources":["createAdoption.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,wCAAwC,EACxC,0CAA0C,EAC1C,4CAA4C,GAC7C,MAAM,2CAA2C,CAAC;AAEnD,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EAAE,gDAAgD,EAAE,MAAM,0CAA0C,CAAC;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KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n assertDocumentWriterProjectionConsistent,\n readLinkedContainerIdsFromDocumentManifest,\n unwrapDocumentContentKeyFromWriterProjection,\n} from \"../../../data/documents/shared/projection\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { persistedDocumentCreateStateFromWriterProjection } from \"../../../data/documents/shared/responses\";\nimport type {\n CreateRemoteDocumentResult,\n DocumentCreateApi,\n} from \"../../../data/documents/shared/types\";\nimport { checkWithHeldBundleRecovery } from \"../../../data/keyingProjectionVerification\";\nimport {\n readAccessEvent,\n readAccessManifest,\n} from \"../../../data/keyingProjectionVerification/readers\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\ntype RemoteDocumentAdoptionInput = {\n readonly apiClient: DocumentCreateApi;\n readonly documentId: string;\n readonly execSql: ExecSql;\n readonly expectedContainerId: string;\n readonly expectedOrganizationId: string;\n /** The local user whose pending create the retry is recovering. */\n readonly expectedSignerUserId: string;\n readonly targetSecretKey: Uint8Array;\n} & ProjectionVerificationOptions;\n\n/**\n * A retry after a lost create response can only recover the local user's own\n * create: the server serves whatever document holds the stable id we minted,\n * and an honest server only ever committed ours under it. A create event signed\n * by anyone else is a foreign document colliding on that id (a member with\n * write access on the same container, or a dishonest server), which must not be\n * adopted as if it were the pending local write.\n *\n * The create event is located by walking the served head's predecessor chain,\n * not by scanning the history for any parentless manifest: the history is\n * server-supplied, so a dishonest server could splice in a genesis this user\n * signed for a different document. Every manifest on the chain must also name\n * the requested document.\n */\nfunction assertCreateEventSignedLocally(\n input: RemoteDocumentAdoptionInput,\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n const label = \"Document create conflict\";\n const historyByHash = new Map(\n writerProjection.documentManifestHistory.map((bundle) => [\n bundle.manifestHash,\n bundle,\n ]),\n );\n const visited = new Set<string>();\n let bundle = writerProjection.documentManifest;\n for (;;) {\n const manifest = readAccessManifest(bundle.manifest, `${label} manifest`);\n if (\n manifest.objectKind !== \"document\" ||\n manifest.objectId !== input.documentId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${label} manifest chain names another document`,\n );\n }\n if (manifest.previousManifestHash === null) {\n const createEvent = readAccessEvent(\n bundle.event.event,\n `${label} create event`,\n );\n if (createEvent.signerUserId !== input.expectedSignerUserId) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n `${label} create event was signed by another user`,\n );\n }\n return;\n }\n if (visited.has(bundle.manifestHash)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `${label} manifest history is cyclic`,\n );\n }\n visited.add(bundle.manifestHash);\n const previous = historyByHash.get(manifest.previousManifestHash);\n if (!previous) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `${label} does not expose its create event`,\n );\n }\n bundle = previous;\n }\n}\n\nfunction assertExpectedAdoptionScope(\n input: RemoteDocumentAdoptionInput,\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n const linkedContainerIds =\n readLinkedContainerIdsFromDocumentManifest(writerProjection);\n const expectedPath = writerProjection.authorizingContainerPaths.find(\n (projection) =>\n projection.containerId === input.expectedContainerId &&\n projection.organizationId === input.expectedOrganizationId,\n );\n if (\n linkedContainerIds.length !== 1 ||\n linkedContainerIds[0] !== input.expectedContainerId ||\n !expectedPath\n ) {\n throw new Error(\n \"Document create conflict belongs to another container or organization\",\n );\n }\n}\n\n/** Recover a committed retry only when it belongs to the intended org scope. */\nexport async function adoptExistingRemoteDocument(\n input: RemoteDocumentAdoptionInput,\n): Promise<CreateRemoteDocumentResult | null> {\n const writerProjection = await input.apiClient.getDocumentWriterProjection(\n input.documentId,\n );\n if (!writerProjection) return null;\n\n // Reject a foreign collision before verification can pin its checkpoints.\n // A refusal drops any held bundles the projection took, so a retry\n // fetches them.\n await checkWithHeldBundleRecovery(\n {\n execSql: input.execSql,\n projection: writerProjection,\n stillCurrent: input.stillCurrent,\n },\n async () => {\n assertExpectedAdoptionScope(input, writerProjection);\n assertCreateEventSignedLocally(input, writerProjection);\n },\n );\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache = new Map<string, VerifiedPrincipalPolicy>();\n const targets = await assertDocumentWriterProjectionConsistent(\n writerProjection,\n {\n execSql: input.execSql,\n principalPolicyCache,\n verifiedByHash,\n ...projectionVerificationOptions(input),\n },\n );\n if (\n targets.length !== 1 ||\n targets[0]?.containerId !== input.expectedContainerId\n ) {\n throw new Error(\n \"Document create conflict belongs to another container or organization\",\n );\n }\n const contentKey = await unwrapDocumentContentKeyFromWriterProjection({\n execSql: input.execSql,\n principalPolicyCache,\n secretKey: input.targetSecretKey,\n verifiedByHash,\n writerProjection,\n ...projectionVerificationOptions(input),\n });\n if (input.stillCurrent?.() === false) return null;\n input.apiClient.primeDocumentWriterProjection(\n writerProjection.documentId,\n writerProjection,\n );\n return {\n contentKey,\n documentId: writerProjection.documentId,\n persistedState:\n persistedDocumentCreateStateFromWriterProjection(writerProjection),\n writerProjection,\n };\n}\n"]}
|
|
@@ -11,6 +11,7 @@ export async function acknowledgeRemoteDocumentCreate(input) {
|
|
|
11
11
|
const acknowledged = acknowledgedDocumentCreate(materializedPlan.plan, response);
|
|
12
12
|
const persistedState = persistedDocumentStateFromAcknowledgement(acknowledged);
|
|
13
13
|
await acknowledgeDocumentMutation({
|
|
14
|
+
bundleDigest: response.bundleDigest,
|
|
14
15
|
execSql: input.execSql,
|
|
15
16
|
plan: materializedPlan.plan,
|
|
16
17
|
stillCurrent: input.stillCurrent,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createResponse.js","sourceRoot":"","sources":["createResponse.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AAErG,OAAO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,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 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"]}
|
|
@@ -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.stillCurrent,
|
|
@@ -1 +1 @@
|
|
|
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,2BAA2B,EAAE,MAAM,6DAA6D,CAAC;AAS1G,OAAO,EACL,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAE5G,OAAO,EAAE,iCAAiC,EAAE,MAAM,wBAAwB,CAAC;AAG3E,OAAO,EAAE,8BAA8B,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,4CAA4C,EAAE,MAAM,SAAS,CAAC;AACvE,OAAO,EAEL,8BAA8B,EAC9B,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,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,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,2BAA2B,EAAE,MAAM,6DAA6D,CAAC;AAS1G,OAAO,EACL,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAE5G,OAAO,EAAE,iCAAiC,EAAE,MAAM,wBAAwB,CAAC;AAG3E,OAAO,EAAE,8BAA8B,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,4CAA4C,EAAE,MAAM,SAAS,CAAC;AACvE,OAAO,EAEL,8BAA8B,EAC9B,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,oBAAoB,EACpB,0BAA0B,EAG1B,mBAAmB,EAEnB,uBAAuB,EACvB,sBAAsB,EACtB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAEtE,KAAK,UAAU,qBAAqB,C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xD,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,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;AAC5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,4CAA4C,CAAC;AAEzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EAClB,iCAAiC,EACjC,wBAAwB,EACxB,cAAc,GACf,MAAM,6BAA6B,CAAC;AAErC,OAAO,EACL,oCAAoC,EACpC,oCAAoC,GACrC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,iCAAiC,EAAE,MAAM,6CAA6C,CAAC;AAChG,OAAO,EAAE,2BAA2B,EAAE,MAAM,mCAAmC,CAAC;AAGhF;;;;;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,KAAK,CAAC,IAAI,CAAC,YAAY;YACrC,gBAAgB,EAAE,QAAQ,CAAC,UAAU;SACtC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,oCAAoC;YACvD,OAAO,OAAgB,CAAC;QAC1B,IAAI,KAAK,YAAY,oCAAoC,EAAE,CAAC;YAC1D,OAAO,qBAAqB,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAClD,CAAC;QACD,IAAI,KAAK,YAAY,mCAAmC,EAAE,CAAC;YACzD,OAAO,iCAAiC,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC9D,CAAC;QACD,IAAI,CAAC,+BAA+B,CAAC,KAAK,CAAC,EAAE,CAAC;YAC5C,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,wBAAwB,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACrD,CAAC;AACH,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } 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;A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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;A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E,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":"A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C,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"]}
|
|
@@ -138,6 +138,7 @@ async function prepareDirectory(input, expectedHead, memberHead) {
|
|
|
138
138
|
adminProjection,
|
|
139
139
|
adminUsers,
|
|
140
140
|
currentPolicy: context.organizationCurrent.current,
|
|
141
|
+
currentUserSecretKey: input.currentUserSecretKey,
|
|
141
142
|
descriptor: context.organizationDescriptor,
|
|
142
143
|
groupHeads,
|
|
143
144
|
signerUserId: input.signerUserId,
|
|
@@ -1 +1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AC,mBAAmB,CAAC,OAAO,CAAC,YAAY,CAAC,SAAS,CAAC;QAE/D,MAAM,IAAI,KAAK,CACb,kEAAkE,CACnE,CAAC;IACJ,IAAI,UAAU,GAAG,4BAA4B,CAAC;QAC5C,UAAU,EAAE,OAAO,CAAC,sBAAsB;QAC1C,QAAQ,EAAE,YAAY;KACvB,CAAC,CAAC;IACH,IAAI,UAAU;QACZ,UAAU,GAAG,4BAA4B,CAAC;YACxC,UAAU,EAAE,EAAE,GAAG,OAAO,CAAC,sBAAsB,EAAE,UAAU,EAAE;YAC7D,QAAQ,EAAE,UAAU;SACrB,CAAC,CAAC;IACL,MAAM,eAAe,GAAG,OAAO,CAAC,yBAAyB;QACvD,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU;QAC1B,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,iBAAiB,CAAC;IACnD,MAAM,UAAU,GAAG,MAAM,6BAA6B,CAAC;QACrD,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;QAC5D,OAAO,EAAE,iBAAiB,CAAC,eAAe,CAAC;KAC5C,CAAC,CAAC;IACH,OAAO,4CAA4C,CAAC;QAClD,eAAe;QACf,UAAU;QACV,aAAa,EAAE,OAAO,CAAC,mBAAmB,CAAC,OAAO;QAClD,UAAU,EAAE,OAAO,CAAC,sBAAsB;QAC1C,UAAU;QACV,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n SigningKeyPair,\n VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"../../../data/principals/organizationGroupDirectoryRequest\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type {\n PreparedPrincipalContainerRematerializationBatch,\n PrincipalRematerializationPredecessor,\n} from \"../../containers/rematerialization\";\nimport { assertAuthoredPrincipalMutationReceipt } from \"../principalMutations/principalMutationReceipt\";\nimport type { RuntimeCurrentGroupMutationContext } from \"../principalMutations/runtimeCurrentGroupMutation\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\nimport { prepareAuthoredGroupPolicy } from \"./groupPolicyMutationAcknowledgement\";\nimport {\n type PrincipalPolicyReadWriteApi,\n submitGroupPolicyCommit,\n} from \"./groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"./groupPolicyMutationHead\";\n\ninterface GroupPolicyChange {\n readonly context: RuntimeCurrentGroupMutationContext;\n readonly request: PutPrincipalPolicyRequest;\n readonly prepareContainerMutations: (\n nextPolicy: VerifiedPrincipalPolicyCurrent,\n preceding?: PrincipalRematerializationPredecessor | undefined,\n ) => Promise<PreparedPrincipalContainerRematerializationBatch>;\n}\n\ninterface CommitInput extends GroupPolicyChange {\n readonly member?: GroupPolicyChange | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\n/** Commit and retain the group, optional roster enrollment and directory together. */\nexport async function commitCurrentGroupPolicyMutation(\n input: CommitInput,\n): Promise<PrincipalPolicyMutationResponse> {\n const { context } = input;\n assertProjectionVerificationCurrent(context.stillCurrent);\n const [signer] = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: [input.signerUserId],\n });\n if (!signer) throw new Error(\"Group policy signer is unavailable\");\n const member = input.member\n ? await prepareChange(input.member, signer)\n : null;\n const { expectedHead, prepared } = await prepareChange(\n input,\n signer,\n member?.preceding,\n );\n const organizationRequest = await prepareDirectory(\n input,\n expectedHead,\n member?.expectedHead,\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n const response = await submitGroupPolicyCommit({\n apiClient: input.apiClient,\n groupId: input.groupId,\n organizationId: input.organizationId,\n request: input.request,\n organizationRequest,\n memberRequest: input.member?.request,\n // A compound retry must rebuild both batches' shared speculative heads.\n // Refuse the whole transaction if a damaged-key repair needs extra rekeys;\n // ordinary adds preserve key epochs and need no descendant carry retry.\n carryDescendantRekeys: member ? undefined : prepared.carry,\n refreshContainerMutations: member\n ? undefined\n : prepared.refreshAfterConflict,\n stillCurrent: context.stillCurrent,\n });\n if (!response) throw new Error(\"Group policy update failed\");\n assertProjectionVerificationCurrent(context.stillCurrent);\n await assertAuthoredPrincipalMutationReceipt(\n {\n groupPolicy: input.request,\n organizationPolicy: organizationRequest,\n ...(input.member ? { memberPolicy: input.member.request } : {}),\n },\n response,\n );\n await context.retainAcknowledged({\n additionalGroups:\n input.member && response.memberPolicy\n ? [\n {\n ...input.member.context.groupRetention,\n request: input.member.request,\n response: response.memberPolicy,\n retiredContainerIds: member?.prepared.retiredContainerIds,\n },\n ]\n : [],\n request: input.request,\n organizationRequest,\n response,\n retiredContainerIds: prepared.retiredContainerIds,\n });\n if (member && response.memberPolicy) {\n await member.prepared.acknowledge(\n response.memberPolicy.containerMutations,\n context.stillCurrent,\n );\n }\n await prepared.acknowledge(\n response.groupPolicy.containerMutations,\n context.stillCurrent,\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n return response.groupPolicy;\n}\n\nasync function prepareChange(\n change: GroupPolicyChange,\n signer: Awaited<ReturnType<typeof resolveRequiredUserIdentities>>[number],\n preceding?: PrincipalRematerializationPredecessor,\n) {\n const expectedHead = await groupPolicyMutationHead(change.request);\n const nextPolicy = await prepareAuthoredGroupPolicy({\n verifiedCurrentPolicy: change.context.verifiedCurrentPolicy,\n expectedHead,\n request: change.request,\n signerPublicKeys: [signer],\n externalAuthority: change.context.externalAuthority,\n localPolicyCheckpoint: change.context.localPolicyCheckpoint,\n stillCurrent: change.context.stillCurrent,\n });\n const authored = [\n ...(preceding?.authored ?? []),\n {\n organizationId: change.context.organizationDescriptor.organizationId,\n policy: nextPolicy,\n dependencies: [\n change.context.organizationCurrent.policy,\n change.context.adminCurrent.policy,\n ],\n stillCurrent: change.context.stillCurrent,\n },\n ];\n // A level the batch plans under its own rotation cites this successor\n // before the transaction commits, so the batch resolves it as authored,\n // exactly as the next group in a compound transaction does (#2646).\n const prepared = await change.prepareContainerMutations(nextPolicy, {\n policies: preceding?.policies ?? [],\n projections: preceding?.projections ?? [],\n knownContainerKeks: preceding?.knownContainerKeks ?? new Map(),\n authored,\n });\n change.request.containerMutations = [...prepared.requests];\n return {\n expectedHead,\n prepared,\n preceding: prepared.preceding\n ? { ...prepared.preceding, authored }\n : undefined,\n };\n}\n\nasync function prepareDirectory(\n input: CommitInput,\n expectedHead: Awaited<ReturnType<typeof groupPolicyMutationHead>>,\n memberHead: Awaited<ReturnType<typeof groupPolicyMutationHead>> | undefined,\n) {\n const { context } = input;\n if (\n input.member &&\n (input.member.context.currentPolicy.currentState.principalId !==\n context.memberGroupId ||\n input.member.context.organizationCurrent.current.currentState\n .stateHash !==\n context.organizationCurrent.current.currentState.stateHash)\n )\n throw new Error(\n \"Roster and group changes must share the same organization policy\",\n );\n let groupHeads = replaceOrganizationGroupHead({\n descriptor: context.organizationDescriptor,\n nextHead: expectedHead,\n });\n if (memberHead)\n groupHeads = replaceOrganizationGroupHead({\n descriptor: { ...context.organizationDescriptor, groupHeads },\n nextHead: memberHead,\n });\n const adminProjection = context.isOrganizationAdminsGroup\n ? input.request.projection\n : context.adminCurrent.current.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n return buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: context.organizationCurrent.current,\n descriptor: context.organizationDescriptor,\n groupHeads,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"commitCurrentGroupPolicyMutation.js","sourceRoot":"","sources":["commitCurrentGroupPolicyMutation.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EACL,4CAA4C,EAC5C,4BAA4B,GAC7B,MAAM,4DAA4D,CAAC;AAMpE,OAAO,EAAE,sCAAsC,EAAE,MAAM,gDAAgD,CAAC;AAExG,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,0BAA0B,EAAE,MAAM,sCAAsC,CAAC;AAClF,OAAO,EAEL,uBAAuB,GACxB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAwBpE,sFAAsF;AACtF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAkB;IAElB,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IAC1B,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,6BAA6B,CAAC;QACnD,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;QAC5D,OAAO,EAAE,CAAC,KAAK,CAAC,YAAY,CAAC;KAC9B,CAAC,CAAC;IACH,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IACnE,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM;QACzB,CAAC,CAAC,MAAM,aAAa,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC;QAC3C,CAAC,CAAC,IAAI,CA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n VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"../../../data/principals/organizationGroupDirectoryRequest\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type {\n PreparedPrincipalContainerRematerializationBatch,\n PrincipalRematerializationPredecessor,\n} from \"../../containers/rematerialization\";\nimport { assertAuthoredPrincipalMutationReceipt } from \"../principalMutations/principalMutationReceipt\";\nimport type { RuntimeCurrentGroupMutationContext } from \"../principalMutations/runtimeCurrentGroupMutation\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\nimport { prepareAuthoredGroupPolicy } from \"./groupPolicyMutationAcknowledgement\";\nimport {\n type PrincipalPolicyReadWriteApi,\n submitGroupPolicyCommit,\n} from \"./groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"./groupPolicyMutationHead\";\n\ninterface GroupPolicyChange {\n readonly context: RuntimeCurrentGroupMutationContext;\n readonly request: PutPrincipalPolicyRequest;\n readonly prepareContainerMutations: (\n nextPolicy: VerifiedPrincipalPolicyCurrent,\n preceding?: PrincipalRematerializationPredecessor | undefined,\n ) => Promise<PreparedPrincipalContainerRematerializationBatch>;\n}\n\ninterface CommitInput extends GroupPolicyChange {\n readonly member?: GroupPolicyChange | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n /** The signer's KEM secret; it keeps the directory key when admins grow. */\n readonly currentUserSecretKey: Uint8Array | null;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\n/** Commit and retain the group, optional roster enrollment and directory together. */\nexport async function commitCurrentGroupPolicyMutation(\n input: CommitInput,\n): Promise<PrincipalPolicyMutationResponse> {\n const { context } = input;\n assertProjectionVerificationCurrent(context.stillCurrent);\n const [signer] = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: [input.signerUserId],\n });\n if (!signer) throw new Error(\"Group policy signer is unavailable\");\n const member = input.member\n ? await prepareChange(input.member, signer)\n : null;\n const { expectedHead, prepared } = await prepareChange(\n input,\n signer,\n member?.preceding,\n );\n const organizationRequest = await prepareDirectory(\n input,\n expectedHead,\n member?.expectedHead,\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n const response = await submitGroupPolicyCommit({\n apiClient: input.apiClient,\n groupId: input.groupId,\n organizationId: input.organizationId,\n request: input.request,\n organizationRequest,\n memberRequest: input.member?.request,\n // A compound retry must rebuild both batches' shared speculative heads.\n // Refuse the whole transaction if a damaged-key repair needs extra rekeys;\n // ordinary adds preserve key epochs and need no descendant carry retry.\n carryDescendantRekeys: member ? undefined : prepared.carry,\n refreshContainerMutations: member\n ? undefined\n : prepared.refreshAfterConflict,\n stillCurrent: context.stillCurrent,\n });\n if (!response) throw new Error(\"Group policy update failed\");\n assertProjectionVerificationCurrent(context.stillCurrent);\n await assertAuthoredPrincipalMutationReceipt(\n {\n groupPolicy: input.request,\n organizationPolicy: organizationRequest,\n ...(input.member ? { memberPolicy: input.member.request } : {}),\n },\n response,\n );\n await context.retainAcknowledged({\n additionalGroups:\n input.member && response.memberPolicy\n ? [\n {\n ...input.member.context.groupRetention,\n request: input.member.request,\n response: response.memberPolicy,\n retiredContainerIds: member?.prepared.retiredContainerIds,\n },\n ]\n : [],\n request: input.request,\n organizationRequest,\n response,\n retiredContainerIds: prepared.retiredContainerIds,\n });\n if (member && response.memberPolicy) {\n await member.prepared.acknowledge(\n response.memberPolicy.containerMutations,\n context.stillCurrent,\n );\n }\n await prepared.acknowledge(\n response.groupPolicy.containerMutations,\n context.stillCurrent,\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n return response.groupPolicy;\n}\n\nasync function prepareChange(\n change: GroupPolicyChange,\n signer: Awaited<ReturnType<typeof resolveRequiredUserIdentities>>[number],\n preceding?: PrincipalRematerializationPredecessor,\n) {\n const expectedHead = await groupPolicyMutationHead(change.request);\n const nextPolicy = await prepareAuthoredGroupPolicy({\n verifiedCurrentPolicy: change.context.verifiedCurrentPolicy,\n expectedHead,\n request: change.request,\n signerPublicKeys: [signer],\n externalAuthority: change.context.externalAuthority,\n localPolicyCheckpoint: change.context.localPolicyCheckpoint,\n stillCurrent: change.context.stillCurrent,\n });\n const authored = [\n ...(preceding?.authored ?? []),\n {\n organizationId: change.context.organizationDescriptor.organizationId,\n policy: nextPolicy,\n dependencies: [\n change.context.organizationCurrent.policy,\n change.context.adminCurrent.policy,\n ],\n stillCurrent: change.context.stillCurrent,\n },\n ];\n // A level the batch plans under its own rotation cites this successor\n // before the transaction commits, so the batch resolves it as authored,\n // exactly as the next group in a compound transaction does (#2646).\n const prepared = await change.prepareContainerMutations(nextPolicy, {\n policies: preceding?.policies ?? [],\n projections: preceding?.projections ?? [],\n knownContainerKeks: preceding?.knownContainerKeks ?? new Map(),\n authored,\n });\n change.request.containerMutations = [...prepared.requests];\n return {\n expectedHead,\n prepared,\n preceding: prepared.preceding\n ? { ...prepared.preceding, authored }\n : undefined,\n };\n}\n\nasync function prepareDirectory(\n input: CommitInput,\n expectedHead: Awaited<ReturnType<typeof groupPolicyMutationHead>>,\n memberHead: Awaited<ReturnType<typeof groupPolicyMutationHead>> | undefined,\n) {\n const { context } = input;\n if (\n input.member &&\n (input.member.context.currentPolicy.currentState.principalId !==\n context.memberGroupId ||\n input.member.context.organizationCurrent.current.currentState\n .stateHash !==\n context.organizationCurrent.current.currentState.stateHash)\n )\n throw new Error(\n \"Roster and group changes must share the same organization policy\",\n );\n let groupHeads = replaceOrganizationGroupHead({\n descriptor: context.organizationDescriptor,\n nextHead: expectedHead,\n });\n if (memberHead)\n groupHeads = replaceOrganizationGroupHead({\n descriptor: { ...context.organizationDescriptor, groupHeads },\n nextHead: memberHead,\n });\n const adminProjection = context.isOrganizationAdminsGroup\n ? input.request.projection\n : context.adminCurrent.current.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n return buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: context.organizationCurrent.current,\n currentUserSecretKey: input.currentUserSecretKey,\n descriptor: context.organizationDescriptor,\n groupHeads,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n}\n"]}
|
|
@@ -33,6 +33,9 @@ export async function commitCurrentShareGrant(input) {
|
|
|
33
33
|
const response = await commitCurrentGroupPolicyMutation({
|
|
34
34
|
apiClient: share.apiClient,
|
|
35
35
|
context,
|
|
36
|
+
// A grant change keeps the admins; the signer's key checks that its
|
|
37
|
+
// envelope still opens the kept directory key.
|
|
38
|
+
currentUserSecretKey: input.runtime.crypto.encapsulationKeyPair?.secretKey ?? null,
|
|
36
39
|
groupId: share.recipientGroupId,
|
|
37
40
|
organizationId: share.author.organizationId,
|
|
38
41
|
request,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"currentShareGrantMutation.js","sourceRoot":"","sources":["currentShareGrantMutation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,uBAAuB,EAAE,MAAM,iDAAiD,CAAC;AAC1F,OAAO,EAEL,+CAA+C,GAChD,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AACzF,OAAO,EAAE,gCAAgC,EAAE,MAAM,iDAAiD,CAAC;AACnG,OAAO,EAAE,wCAAwC,EAAE,MAAM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,CAAC;AACxD,CAAC;AAED,KAAK,UAAU,2BAA2B,CACxC,OAAuE,EACvE,KAA0D,EAC1D,OAA2C,EAC3C,YAAoB;IAEpB,MAAM,QAAQ,GAAG,MAAM,uBAAuB,CAC5C,OAAO,CAAC,aAAa,EACrB,YAAY,EACZ,gCAAgC,CAC9B,OAAO,EACP,KAAK,CAAC,MAAM,CAAC,cAAc,EAC3B,OAAO,CAAC,YAAY,EACpB,OAAO,CAAC,uBAAuB,CAChC,CAAC,QAAQ,CACX,CAAC;IACF,IAAI,QAAQ;QACV,MAAM,IAAI,2BAA2B,CACnC,mEAAmE,CACpE,CAAC;IACJ,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,6BAA6B,CACpC,KAA0D,EAC1D,OAA2C,EAC3C,EACE,UAAU,EACV,SAAS,GAIV,EACD,sBAAsC;IAEtC,OAAO,+CAA+C,CAAC;QACrD,GAAG,KAAK;QACR,SAAS;QACT,MAAM,EAAE;YACN,GAAG,IAAI,GAAG,CACR,CAAC,GAAG,OAAO,CAAC,aAAa,CAAC,aAAa,EAAE,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,CAChE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,KAAK,CAAU,CAC/C,CACF,CAAC,MAAM,EAAE;SACX;QACD,OAAO,EAAE,KAAK,CAAC,gBAAgB;QAC/B,UAAU;QACV,+BAA+B,EAAE,OAAO,CAAC,+BAA+B;QACxE,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,sBAAsB;KACvB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { MaterializedContainerSharePlan } from \"../../../data/containers/shared/types\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { groupPolicyNameMismatch } from \"../../../data/principals/principalPolicyRequest\";\nimport {\n type PreparedPrincipalContainerRematerializationBatch,\n preparePrincipalContainerRematerializationBatch,\n} from \"../../containers/rematerialization\";\nimport { createRuntimeGroupMetadataAccess } from \"../groupMetadata/groupMetadataRuntime\";\nimport { commitCurrentGroupPolicyMutation } from \"../groupPolicy/commitCurrentGroupPolicyMutation\";\nimport { buildSetGroupContainerGrantPolicyRequest } from \"../groupPolicy/groupPolicyRequests\";\nimport type {\n createRuntimeCurrentGroupMutation,\n RuntimeCurrentGroupMutationContext,\n} from \"../principalMutations/runtimeCurrentGroupMutation\";\nimport type { createRuntimeCurrentSharePrincipalPolicy } from \"./currentSharePrincipalPolicy\";\nimport { GroupShareNameMismatchError } from \"./sharePrincipalPolicy\";\nimport type { shareRemoteContainerWithGroup } from \"./shareWithGroup\";\n\n/** Fresh mutation authority rechecks the chosen name before authoring a grant. */\nexport async function commitCurrentShareGrant(input: {\n readonly runtime: Parameters<\n typeof createRuntimeCurrentSharePrincipalPolicy\n >[0];\n readonly share: Parameters<typeof shareRemoteContainerWithGroup>[0];\n readonly recitationStillCurrent?: (() => boolean) | undefined;\n readonly mutate: NonNullable<\n ReturnType<typeof createRuntimeCurrentGroupMutation>\n >;\n}): ReturnType<typeof shareRemoteContainerWithGroup> {\n const share = input.share;\n const expectedName = share.expectedGroupName;\n if (expectedName === null)\n throw new Error(\n \"Minting a group grant requires the chosen group name; only a re-wrap of an existing signed grant may omit it\",\n );\n const signingKeyPair = share.signingKeyPair;\n if (!signingKeyPair)\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n return input.mutate(\n {\n groupId: share.recipientGroupId,\n organizationId: share.author.organizationId,\n signerUserId: share.author.signerUserId,\n stillCurrent: share.stillCurrent ?? (() => true),\n },\n async (context) => {\n await assertCurrentShareGrantName(\n input.runtime,\n share,\n context,\n expectedName,\n );\n const request = await buildSetGroupContainerGrantPolicyRequest({\n ...context,\n accessLevel: share.accessLevel,\n containerId: share.containerId,\n signerUserId: share.author.signerUserId,\n signingFingerprint: share.author.signerKeyFingerprint,\n signingKeyPair,\n });\n const prepared: {\n batch?: PreparedPrincipalContainerRematerializationBatch;\n } = {};\n const response = await commitCurrentGroupPolicyMutation({\n apiClient: share.apiClient,\n context,\n groupId: share.recipientGroupId,\n organizationId: share.author.organizationId,\n request,\n signerUserId: share.author.signerUserId,\n signingFingerprint: share.author.signerKeyFingerprint,\n signingKeyPair,\n resolveTrustedUserIdentity: share.resolveTrustedUserIdentity,\n prepareContainerMutations: async (nextPolicy, preceding) => {\n prepared.batch = await prepareCurrentShareGrantBatch(\n share,\n context,\n { nextPolicy, preceding },\n input.recitationStillCurrent,\n );\n return prepared.batch;\n },\n });\n const index =\n prepared.batch?.plans.findIndex(\n (planned) => planned.plan.containerId === share.containerId,\n ) ?? -1;\n const plan = prepared.batch?.plans[index];\n const acknowledgement = response.containerMutations[index];\n if (!plan || !acknowledgement || !isSharePlan(plan))\n throw new Error(\"Container group share acknowledgement is incomplete\");\n return {\n containerKey: plan.containerKey,\n plan: plan.plan,\n response: acknowledgement,\n };\n },\n );\n}\n\nfunction isSharePlan(\n plan: PreparedPrincipalContainerRematerializationBatch[\"plans\"][number],\n): plan is MaterializedContainerSharePlan {\n return plan.plan.body.eventType === \"container.grant\";\n}\n\nasync function assertCurrentShareGrantName(\n runtime: Parameters<typeof createRuntimeCurrentSharePrincipalPolicy>[0],\n share: Parameters<typeof shareRemoteContainerWithGroup>[0],\n context: RuntimeCurrentGroupMutationContext,\n expectedName: string,\n) {\n const mismatch = await groupPolicyNameMismatch(\n context.currentPolicy,\n expectedName,\n createRuntimeGroupMetadataAccess(\n runtime,\n share.author.organizationId,\n context.stillCurrent,\n context.verifyMetadataContainer,\n ).readName,\n );\n if (mismatch)\n throw new GroupShareNameMismatchError(\n \"Container share group name does not match the signed group policy\",\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n}\n\nfunction prepareCurrentShareGrantBatch(\n share: Parameters<typeof shareRemoteContainerWithGroup>[0],\n context: RuntimeCurrentGroupMutationContext,\n {\n nextPolicy,\n preceding,\n }: Pick<\n Parameters<typeof preparePrincipalContainerRematerializationBatch>[0],\n \"nextPolicy\" | \"preceding\"\n >,\n recitationStillCurrent?: () => boolean,\n) {\n return preparePrincipalContainerRematerializationBatch({\n ...share,\n preceding,\n grants: [\n ...new Map(\n [...context.currentPolicy.currentGrants, ...nextPolicy.grants].map(\n (grant) => [grant.containerId, grant] as const,\n ),\n ).values(),\n ],\n groupId: share.recipientGroupId,\n nextPolicy,\n resolveAuthoredPolicyReferences: context.resolveAuthoredPolicyReferences,\n stillCurrent: context.stillCurrent,\n recitationStillCurrent,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"currentShareGrantMutation.js","sourceRoot":"","sources":["currentShareGrantMutation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,uBAAuB,EAAE,MAAM,iDAAiD,CAAC;AAC1F,OAAO,EAEL,+CAA+C,GAChD,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AACzF,OAAO,EAAE,gCAAgC,EAAE,MAAM,iDAAiD,CAAC;AACnG,OAAO,EAAE,wCAAwC,EAAE,MAAM,oCAAoC,CAAC;AAM9F,OAAO,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;AAGrE,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,KAS7C;IACC,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;IAC1B,MAAM,YAAY,GAAG,KAAK,CAAC,iBAAiB,CAAC;IAC7C,IAAI,YAAY,KAAK,IAAI;QACvB,MAAM,IAAI,KAAK,CACb,8GAA8G,CAC/G,CAAC;IACJ,MAAM,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IAC5C,IAAI,CAAC,cAAc;QACjB,MAAM,IAAI,KAAK,CACb,iEAAiE,CAClE,CAAC;IACJ,OAAO,KAAK,CAAC,MAAM,CACjB;QACE,OAAO,EAAE,KAAK,CAAC,gBA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AC;IACJ,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,6BAA6B,CACpC,KAA0D,EAC1D,OAA2C,EAC3C,EACE,UAAU,EACV,SAAS,GAIV,EACD,sBAAsC;IAEtC,OAAO,+CAA+C,CAAC;QACrD,GAAG,KAAK;QACR,SAAS;QACT,MAAM,EAAE;YACN,GAAG,IAAI,GAAG,CACR,CAAC,GAAG,OAAO,CAAC,aAAa,CAAC,aAAa,EAAE,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,CAChE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,KAAK,CAAU,CAC/C,CACF,CAAC,MAAM,EAAE;SACX;QACD,OAAO,EAAE,KAAK,CAAC,gBAAgB;QAC/B,UAAU;QACV,+BAA+B,EAAE,OAAO,CAAC,+BAA+B;QACxE,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,sBAAsB;KACvB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { MaterializedContainerSharePlan } from \"../../../data/containers/shared/types\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { groupPolicyNameMismatch } from \"../../../data/principals/principalPolicyRequest\";\nimport {\n type PreparedPrincipalContainerRematerializationBatch,\n preparePrincipalContainerRematerializationBatch,\n} from \"../../containers/rematerialization\";\nimport { createRuntimeGroupMetadataAccess } from \"../groupMetadata/groupMetadataRuntime\";\nimport { commitCurrentGroupPolicyMutation } from \"../groupPolicy/commitCurrentGroupPolicyMutation\";\nimport { buildSetGroupContainerGrantPolicyRequest } from \"../groupPolicy/groupPolicyRequests\";\nimport type {\n createRuntimeCurrentGroupMutation,\n RuntimeCurrentGroupMutationContext,\n} from \"../principalMutations/runtimeCurrentGroupMutation\";\nimport type { createRuntimeCurrentSharePrincipalPolicy } from \"./currentSharePrincipalPolicy\";\nimport { GroupShareNameMismatchError } from \"./sharePrincipalPolicy\";\nimport type { shareRemoteContainerWithGroup } from \"./shareWithGroup\";\n\n/** Fresh mutation authority rechecks the chosen name before authoring a grant. */\nexport async function commitCurrentShareGrant(input: {\n readonly runtime: Parameters<\n typeof createRuntimeCurrentSharePrincipalPolicy\n >[0];\n readonly share: Parameters<typeof shareRemoteContainerWithGroup>[0];\n readonly recitationStillCurrent?: (() => boolean) | undefined;\n readonly mutate: NonNullable<\n ReturnType<typeof createRuntimeCurrentGroupMutation>\n >;\n}): ReturnType<typeof shareRemoteContainerWithGroup> {\n const share = input.share;\n const expectedName = share.expectedGroupName;\n if (expectedName === null)\n throw new Error(\n \"Minting a group grant requires the chosen group name; only a re-wrap of an existing signed grant may omit it\",\n );\n const signingKeyPair = share.signingKeyPair;\n if (!signingKeyPair)\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n return input.mutate(\n {\n groupId: share.recipientGroupId,\n organizationId: share.author.organizationId,\n signerUserId: share.author.signerUserId,\n stillCurrent: share.stillCurrent ?? (() => true),\n },\n async (context) => {\n await assertCurrentShareGrantName(\n input.runtime,\n share,\n context,\n expectedName,\n );\n const request = await buildSetGroupContainerGrantPolicyRequest({\n ...context,\n accessLevel: share.accessLevel,\n containerId: share.containerId,\n signerUserId: share.author.signerUserId,\n signingFingerprint: share.author.signerKeyFingerprint,\n signingKeyPair,\n });\n const prepared: {\n batch?: PreparedPrincipalContainerRematerializationBatch;\n } = {};\n const response = await commitCurrentGroupPolicyMutation({\n apiClient: share.apiClient,\n context,\n // A grant change keeps the admins; the signer's key checks that its\n // envelope still opens the kept directory key.\n currentUserSecretKey:\n input.runtime.crypto.encapsulationKeyPair?.secretKey ?? null,\n groupId: share.recipientGroupId,\n organizationId: share.author.organizationId,\n request,\n signerUserId: share.author.signerUserId,\n signingFingerprint: share.author.signerKeyFingerprint,\n signingKeyPair,\n resolveTrustedUserIdentity: share.resolveTrustedUserIdentity,\n prepareContainerMutations: async (nextPolicy, preceding) => {\n prepared.batch = await prepareCurrentShareGrantBatch(\n share,\n context,\n { nextPolicy, preceding },\n input.recitationStillCurrent,\n );\n return prepared.batch;\n },\n });\n const index =\n prepared.batch?.plans.findIndex(\n (planned) => planned.plan.containerId === share.containerId,\n ) ?? -1;\n const plan = prepared.batch?.plans[index];\n const acknowledgement = response.containerMutations[index];\n if (!plan || !acknowledgement || !isSharePlan(plan))\n throw new Error(\"Container group share acknowledgement is incomplete\");\n return {\n containerKey: plan.containerKey,\n plan: plan.plan,\n response: acknowledgement,\n };\n },\n );\n}\n\nfunction isSharePlan(\n plan: PreparedPrincipalContainerRematerializationBatch[\"plans\"][number],\n): plan is MaterializedContainerSharePlan {\n return plan.plan.body.eventType === \"container.grant\";\n}\n\nasync function assertCurrentShareGrantName(\n runtime: Parameters<typeof createRuntimeCurrentSharePrincipalPolicy>[0],\n share: Parameters<typeof shareRemoteContainerWithGroup>[0],\n context: RuntimeCurrentGroupMutationContext,\n expectedName: string,\n) {\n const mismatch = await groupPolicyNameMismatch(\n context.currentPolicy,\n expectedName,\n createRuntimeGroupMetadataAccess(\n runtime,\n share.author.organizationId,\n context.stillCurrent,\n context.verifyMetadataContainer,\n ).readName,\n );\n if (mismatch)\n throw new GroupShareNameMismatchError(\n \"Container share group name does not match the signed group policy\",\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n}\n\nfunction prepareCurrentShareGrantBatch(\n share: Parameters<typeof shareRemoteContainerWithGroup>[0],\n context: RuntimeCurrentGroupMutationContext,\n {\n nextPolicy,\n preceding,\n }: Pick<\n Parameters<typeof preparePrincipalContainerRematerializationBatch>[0],\n \"nextPolicy\" | \"preceding\"\n >,\n recitationStillCurrent?: () => boolean,\n) {\n return preparePrincipalContainerRematerializationBatch({\n ...share,\n preceding,\n grants: [\n ...new Map(\n [...context.currentPolicy.currentGrants, ...nextPolicy.grants].map(\n (grant) => [grant.containerId, grant] as const,\n ),\n ).values(),\n ],\n groupId: share.recipientGroupId,\n nextPolicy,\n resolveAuthoredPolicyReferences: context.resolveAuthoredPolicyReferences,\n stillCurrent: context.stillCurrent,\n recitationStillCurrent,\n });\n}\n"]}
|