@tearleads/client-sdk 0.1.243 → 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.
Files changed (111) hide show
  1. package/client/organizations/principalMutations.d.ts +5 -0
  2. package/data/containers/shared/mutationAcknowledgement.d.ts +1 -1
  3. package/data/containers/shared/mutationAcknowledgement.js +3 -8
  4. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  5. package/data/documents/shared/sync/mutationAcknowledgement.js +11 -2
  6. package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -1
  7. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.d.ts +26 -0
  8. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js +46 -0
  9. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js.map +1 -0
  10. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +7 -4
  11. package/data/keyingProjectionVerification/container/containerDestinationVerification.js +5 -1
  12. package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -1
  13. package/data/keyingProjectionVerification/container/containerProjectionVerification.js +9 -2
  14. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  15. package/data/keyingProjectionVerification/document/documentContainerProjections.js +2 -1
  16. package/data/keyingProjectionVerification/document/documentContainerProjections.js.map +1 -1
  17. package/data/keyingProjectionVerification/document/documentProjectionVerification.js +9 -2
  18. package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
  19. package/data/keyingProjectionVerification/index.d.ts +1 -0
  20. package/data/keyingProjectionVerification/index.js +1 -0
  21. package/data/keyingProjectionVerification/index.js.map +1 -1
  22. package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js +16 -4
  23. package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js.map +1 -1
  24. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts +13 -0
  25. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +11 -0
  26. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
  27. package/data/persistence/verifiedCitations/authoredBundleCitation.d.ts +20 -0
  28. package/data/persistence/verifiedCitations/authoredBundleCitation.js +32 -0
  29. package/data/persistence/verifiedCitations/authoredBundleCitation.js.map +1 -0
  30. package/data/persistence/verifiedManifestBundlePersistence.d.ts +10 -0
  31. package/data/persistence/verifiedManifestBundlePersistence.js +95 -9
  32. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  33. package/internal/api-client/ApiClient.d.ts +55 -0
  34. package/internal/api-client/client/containerMutations.d.ts +11 -0
  35. package/internal/api-client/client/documents.d.ts +5 -0
  36. package/internal/api-client/client/organizations.d.ts +20 -0
  37. package/internal/api-client/client/principalPolicies.d.ts +9 -0
  38. package/internal/api-client/client/session.d.ts +10 -0
  39. package/internal/api-client/principalPolicyRequests.d.ts +7 -0
  40. package/internal/api-client/writerProjectionCitations.d.ts +3 -0
  41. package/internal/api-client/writerProjectionCitations.js +12 -0
  42. package/internal/api-client/writerProjectionCitations.js.map +1 -1
  43. package/internal/crypto/index.d.ts +1 -1
  44. package/internal/crypto/index.js +1 -1
  45. package/internal/crypto/index.js.map +1 -1
  46. package/internal/crypto/keying/canonicalJsonGuard.d.ts +13 -0
  47. package/internal/crypto/keying/canonicalJsonGuard.js +23 -0
  48. package/internal/crypto/keying/canonicalJsonGuard.js.map +1 -1
  49. package/internal/crypto/keying/index.d.ts +1 -1
  50. package/internal/crypto/keying/index.js +1 -1
  51. package/internal/crypto/keying/index.js.map +1 -1
  52. package/internal/crypto/keying/keyingHashDomains.d.ts +1 -1
  53. package/internal/crypto/keying/keyingHashDomains.js.map +1 -1
  54. package/internal/validators/operation/auth.d.ts +40 -0
  55. package/internal/validators/operation/containerMutations.d.ts +44 -0
  56. package/internal/validators/operation/documentMutations.d.ts +12 -0
  57. package/internal/validators/operation/organizations.d.ts +48 -0
  58. package/internal/validators/operation/principals.d.ts +16 -0
  59. package/internal/validators/response/areas/containers.d.ts +1 -1
  60. package/internal/validators/response/areas/containers.js +1 -1
  61. package/internal/validators/response/areas/containers.js.map +1 -1
  62. package/internal/validators/response/container.d.ts +16 -0
  63. package/internal/validators/response/container.js +3 -0
  64. package/internal/validators/response/container.js.map +1 -1
  65. package/internal/validators/response/containerMetadata.d.ts +8 -0
  66. package/internal/validators/response/documentMutation.d.ts +8 -0
  67. package/internal/validators/response/documentMutation.js +2 -1
  68. package/internal/validators/response/documentMutation.js.map +1 -1
  69. package/internal/validators/response/organization.d.ts +8 -0
  70. package/internal/validators/response/organizationProvisioning.d.ts +113 -0
  71. package/internal/validators/response/organizationProvisioning.js +2 -1
  72. package/internal/validators/response/organizationProvisioning.js.map +1 -1
  73. package/internal/validators/response/principal.d.ts +16 -0
  74. package/internal/validators/response/registration.d.ts +40 -0
  75. package/internal/validators/response/writerProjectionWire.d.ts +25 -0
  76. package/internal/validators/response/writerProjectionWire.js +109 -3
  77. package/internal/validators/response/writerProjectionWire.js.map +1 -1
  78. package/package.json +1 -1
  79. package/stores/documents/documentStore/rotation/index.js +3 -1
  80. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  81. package/stores/documents/documentStore/sync/syncAttachments.js +4 -1
  82. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  83. package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -1
  84. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
  85. package/stores/documents/documentStore/sync/syncRequest.js +3 -1
  86. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  87. package/workflows/container-contents/container-state/create/createAdoption.js +11 -3
  88. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  89. package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
  90. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  91. package/workflows/container-contents/container-state/projectionCache.js +3 -0
  92. package/workflows/container-contents/container-state/projectionCache.js.map +1 -1
  93. package/workflows/container-contents/metadata/index.js +5 -2
  94. package/workflows/container-contents/metadata/index.js.map +1 -1
  95. package/workflows/containers/child/recite.js +4 -2
  96. package/workflows/containers/child/recite.js.map +1 -1
  97. package/workflows/documents/create/createAdoption.js +11 -2
  98. package/workflows/documents/create/createAdoption.js.map +1 -1
  99. package/workflows/documents/create/createResponse.js +1 -0
  100. package/workflows/documents/create/createResponse.js.map +1 -1
  101. package/workflows/documents/linkSet/linkSetRemote.js +1 -0
  102. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
  103. package/workflows/documents/sync/syncAttemptPlanning.js +8 -2
  104. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  105. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +3 -2
  106. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  107. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js +3 -2
  108. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js.map +1 -1
  109. package/workflows/registration/organizationCreation/organizationCreationIntent.d.ts +10 -0
  110. package/workflows/registration/provisioningAcknowledgement.js +16 -11
  111. 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,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C,OAAO;QACtB,oBAAoB;QACpB,cAAc;QACd,GAAG,6BAA6B,CAAC,KAAK,CAAC;KACxC,CACF,CAAC;IACF,IACE,OAAO,CAAC,MAAM,KAAK,CAAC;QACpB,OAAO,CAAC,CAAC,CAAC,EAAE,WAAW,KAAK,KAAK,CAAC,mBAAmB,EACrD,CAAC;QACD,MAAM,IAAI,KAAK,CACb,uEAAuE,CACxE,CAAC;IACJ,CAAC;IACD,MAAM,UAAU,GAAG,MAAM,4CAA4C,CAAC;QACpE,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,oBAAoB;QACpB,SAAS,EAAE,KAAK,CAAC,eAAe;QAChC,cAAc;QACd,gBAAgB;QAChB,GAAG,6BAA6B,CAAC,KAAK,CAAC;KACxC,CAAC,CAAC;IACH,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;AAK5G,OAAO,EAAE,2BAA2B,EAAE,MAAM,4CAA4C,CAAC;AACzF,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,CAAC,UAAU,EACtC,CAAC;YACD,MAAM,IAAI,uBAAuB,CAC/B,iB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K,CAAC,OAAO;QACtB,oBAAoB;QACpB,SAAS,EAAE,KAAK,CAAC,eAAe;QAChC,cAAc;QACd,gBAAgB;QAChB,GAAG,6BAA6B,CAAC,KAAK,CAAC;KACxC,CAAC,CAAC;IACH,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 { 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,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,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 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,CA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Q,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,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AuB,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACrE,OAAO,QAAQ,CAAC,OAAO,CAAC;IAC1B,CAAC,CAAC;IACF,OAAO,iCAAiC,CACtC,GAAG,EAAE,CACH,wCAAwC,CAAC,GAAG,EAAE,CAC5C,4CAA4C,CAAC;QAC3C,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,kBAAkB;QAClB,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,yBAAyB;QACzB,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,+BAA+B,EAC7B,KAAK,CAAC,+BAA+B;QACvC,gBAAgB;KACjB,CAAC,CACH,EACH,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import type {\n DocumentContentKeyTarget,\n DocumentLinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type { DocumentLinkSetMutationRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentLinkSetMutationResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n acknowledgedDocumentLinkSetMutation,\n persistedDocumentStateFromAcknowledgement,\n} from \"../../../data/documents/shared/responses\";\nimport { acknowledgeDocumentMutation } from \"../../../data/documents/shared/sync/mutationAcknowledgement\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationApi,\n DocumentLinkSetMutationOperation,\n RelinkRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { documentMayHaveAttachments } from \"../../../data/persistence/documents/documentAttachmentPresence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { recordDocumentAuthorAccessFailure } from \"../authorAccessFailure\";\nimport type { SubtreePurgeRoot } from \"../purge/subtreePurgeScope\";\nimport type { RemoteDocumentCollaborators } from \"../remote/remoteDocumentCollaborators\";\nimport { completeLinkSetMutationRequest } from \"../rotationBaseline\";\nimport { buildMaterializedDocumentLinkSetMutationPlan } from \"./index\";\nimport {\n type LinkSetAttachmentReuse,\n prepareDocumentLinkBlobRewraps,\n reuseCommittedBlobRewraps,\n} from \"./linkSetBlobRewraps\";\nimport {\n holdsLinkSetRefusals,\n INITIAL_LINK_SET_LEG_STATE,\n type LinkSetLegAttempt,\n type LinkSetSubmitFailure,\n linkSetAttemptEvent,\n type PreparedLinkSetRewraps,\n recordLinkSetLegRewraps,\n startLinkSetLegAttempt,\n transitionLinkSetLeg,\n} from \"./linkSetLegMachine\";\nimport { seedLinkSetWriterProjection } from \"./linkSetProjectionSeed\";\n\nasync function submitLinkSetMutation(input: {\n apiClient: DocumentLinkSetMutationApi;\n documentId: string;\n expectedOrganizationId: string;\n onFailure: (failure: LinkSetSubmitFailure) => void;\n operation: DocumentLinkSetMutationOperation;\n request: DocumentLinkSetMutationRequest;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<DocumentLinkSetMutationResponse | null> {\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input;\n // Preserve the HTTP failure for the durable move-intent queue. Its host\n // report waits until the leg knows the refusal is not one it recovers from.\n const resultFn =\n input.operation === \"link\"\n ? apiClient.linkDocumentResult.bind(apiClient)\n : apiClient.unlinkDocumentResult.bind(apiClient);\n const result = await resultFn(input.documentId, input.request, {\n expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,\n reportErrors: false,\n });\n if (result.ok) {\n return result.data;\n }\n // A refusal the operation no longer waits for is neither retried nor\n // reported.\n if (input.stillCurrent?.() === false) return null;\n input.onFailure({\n code: result.code,\n message: result.message,\n report: result.report,\n status: result.status,\n });\n return null;\n}\n\n/** Hand a refusal the leg does not recover from to its host and caller. */\nfunction reportLinkSetFailure(\n input: Pick<RelinkRemoteDocumentInput, \"onFailure\">,\n failure: LinkSetSubmitFailure,\n): void {\n failure.report?.();\n input.onFailure?.({\n code: failure.code,\n message: failure.message,\n status: failure.status,\n });\n}\n\ninterface LinkSetProjectionFetch<TProjection> {\n failure: LinkSetSubmitFailure | null;\n projection: TProjection | null;\n}\n\n// Cold-cache projection fetches must keep their HTTP status: collapsing a\n// 403 to null would leave an access-denied link/unlink routinely retriable\n// instead of parking its move for the access-restored signal (row 7).\nasync function fetchLinkSetProjection<TProjection>(input: {\n fetchProjectionResult: () => Promise<\n | { readonly data: TProjection; readonly ok: true }\n | DocumentSyncSubmitFailure\n >;\n}): Promise<LinkSetProjectionFetch<TProjection>> {\n const result = await input.fetchProjectionResult();\n if (result.ok) {\n return { failure: null, projection: result.data };\n }\n return {\n failure: {\n code: result.code,\n message: result.message,\n report: result.report,\n status: result.status,\n },\n projection: null,\n };\n}\n\nfunction fetchLinkSetDocumentProjection(\n apiClient: DocumentLinkSetMutationApi,\n documentId: string,\n): Promise<LinkSetProjectionFetch<DocumentWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getDocumentWriterProjectionResult.bind(\n apiClient,\n documentId,\n { reportErrors: false },\n ),\n });\n}\n\nfunction fetchLinkSetContainerProjection(\n apiClient: DocumentLinkSetMutationApi,\n containerId: string,\n): Promise<LinkSetProjectionFetch<ContainerWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getContainerWriterProjectionResult.bind(\n apiClient,\n containerId,\n { reportErrors: false },\n ),\n });\n}\n\nasync function completeRemoteDocumentLinkSet(input: {\n completedPlan: Parameters<typeof acknowledgedDocumentLinkSetMutation>[0];\n execSql: ExecSql;\n materializedPlan: Awaited<\n ReturnType<typeof buildMaterializedDocumentLinkSetMutationPlan>\n >;\n operation: DocumentLinkSetMutationOperation;\n response: DocumentLinkSetMutationResponse;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n apiClient: DocumentLinkSetMutationApi;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const acknowledged = acknowledgedDocumentLinkSetMutation(\n input.completedPlan,\n input.response,\n );\n const persistedState =\n persistedDocumentStateFromAcknowledgement(acknowledged);\n await acknowledgeDocumentMutation({\n execSql: input.execSql,\n plan: input.completedPlan,\n stillCurrent: input.stillCurrent,\n });\n await seedLinkSetWriterProjection({\n apiClient: input.apiClient,\n execSql: input.execSql,\n operation: input.operation,\n priorProjection: input.writerProjection,\n response: acknowledged,\n targetContainerId: input.targetContainerId,\n targetContainerProjection: input.targetContainerProjection,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n return {\n contentKey: input.materializedPlan.contentKey,\n contentKeyRotated: input.materializedPlan.contentKeyRotated,\n documentId: input.response.id,\n linkedContainerIds: [\n ...input.materializedPlan.plan.state.linkedContainerIds,\n ],\n persistedState,\n plan: input.completedPlan,\n response: input.response,\n };\n}\n\n/** What varies per link or unlink leg; the collaborators bind the rest. */\nexport interface RelinkRemoteDocumentRequest {\n /** Shared by the legs of one move or trash workflow. */\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n author: DocumentCreateAuthor;\n contentKey?: Uint8Array | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n eventId?: string | undefined;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: DocumentLinkSetMutationOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RelinkRemoteDocumentInput extends RelinkRemoteDocumentRequest {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetSecretKey: Uint8Array;\n}\n\n/**\n * A leg that cited rewraps without listing and was refused because the\n * attachment set (or a re-cited key epoch) moved lists and retries once, as a\n * leg that listed would have; that first refusal is neither reported nor\n * retried once the operation is no longer current (`transitionLinkSetLeg`).\n */\nexport async function relinkRemoteDocument(\n remote: RemoteDocumentCollaborators,\n request: RelinkRemoteDocumentRequest,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (!remote.encapsulationSecretKey) {\n throw new Error(\n \"Remote document link-set mutation requires an encapsulation key\",\n );\n }\n const input: RelinkRemoteDocumentInput = {\n ...request,\n apiClient: remote.api,\n execSql: remote.execSql,\n targetSecretKey: remote.encapsulationSecretKey,\n };\n const reuse = input.attachmentReuse;\n let leg = INITIAL_LINK_SET_LEG_STATE;\n let result: RelinkRemoteDocumentResult | null = null;\n while (leg.status === \"speculative\" || leg.status === \"fresh\") {\n const attempt = { current: startLinkSetLegAttempt(leg) };\n const heldFailures: LinkSetSubmitFailure[] = [];\n result = await relinkRemoteDocumentOnce(input, attempt, (failure) => {\n if (holdsLinkSetRefusals(attempt.current)) heldFailures.push(failure);\n else reportLinkSetFailure(input, failure);\n }).catch((error: unknown) => {\n // A leg that threw may have committed before failing: list again next.\n if (reuse) reuse.committed = null;\n throw error;\n });\n const event = linkSetAttemptEvent({\n attempt: attempt.current,\n committed: result !== null,\n heldFailures,\n stillCurrent: input.stillCurrent?.() !== false,\n });\n if (reuse)\n reuse.committed =\n event.type === \"attemptCommitted\" ? event.rewraps : null;\n leg = transitionLinkSetLeg(leg, event);\n }\n if (leg.status === \"failed\") {\n for (const failure of leg.unreported) reportLinkSetFailure(input, failure);\n }\n return result;\n}\n\n/** The attempt in flight; preparation replaces it with what it signed. */\ninterface LinkSetAttemptSlot {\n current: LinkSetLegAttempt;\n}\n\nasync function relinkRemoteDocumentOnce(\n input: RelinkRemoteDocumentInput,\n attempt: LinkSetAttemptSlot,\n onSubmitFailure: (failure: LinkSetSubmitFailure) => void,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (input.operation === \"unlink\" && !input.rotationSnapshot) {\n throw new Error(\n \"Document unlink requires a proven full-history rotation snapshot\",\n );\n }\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote document link-set mutation\",\n );\n const [writerFetch, targetContainerFetch] = await Promise.all([\n fetchLinkSetDocumentProjection(input.apiClient, input.documentId),\n fetchLinkSetContainerProjection(input.apiClient, input.targetContainerId),\n ]);\n if (!writerFetch.projection || !targetContainerFetch.projection) {\n // A failure the operation no longer waits for is not reported.\n if (input.stillCurrent?.() === false) return null;\n for (const failure of orderedProjectionFailures([\n writerFetch.failure,\n targetContainerFetch.failure,\n ])) {\n reportLinkSetFailure(input, failure);\n }\n return null;\n }\n const writerProjection = writerFetch.projection;\n const targetContainerProjection = targetContainerFetch.projection;\n if (input.stillCurrent?.() === false) return null;\n\n const signedAt = input.signedAt ?? new Date().toISOString();\n const materializedPlan = await prepareRemoteLinkSetMutation(\n { ...input, resolveProjectionUserKey, signedAt },\n writerProjection,\n targetContainerProjection,\n attempt,\n );\n if (!materializedPlan) return null;\n const request = await completeLinkSetMutationRequest({\n author: input.author,\n materializedPlan,\n operation: input.operation,\n rotationSnapshot: input.rotationSnapshot,\n signedAt,\n });\n const completedPlan = { ...materializedPlan.plan, request };\n if (input.beforeSubmit && !(await input.beforeSubmit())) return null;\n const response = await submitLinkSetMutation({\n apiClient: input.apiClient,\n documentId: completedPlan.documentId,\n expectedOrganizationId: completedPlan.state.organizationId,\n onFailure: onSubmitFailure,\n operation: input.operation,\n request: completedPlan.request,\n stillCurrent: input.stillCurrent,\n });\n if (!response) {\n return null;\n }\n if (input.stillCurrent?.() === false) return null;\n return completeRemoteDocumentLinkSet({\n apiClient: input.apiClient,\n completedPlan,\n execSql: input.execSql,\n materializedPlan,\n operation: input.operation,\n response,\n stillCurrent: input.stillCurrent,\n targetContainerId: input.targetContainerId,\n targetContainerProjection,\n writerProjection,\n });\n}\n\n// Every projection failure reaches the handler: the queued-move accumulator\n// classifies a vanished container from ANY coded container 404, so a document\n// fetch failure must not hide a container one (or vice versa). A 403 is\n// delivered last, so a single-slot consumer keeps the denial that parks the\n// move (row 7) while the accumulator still sees both.\nfunction orderedProjectionFailures(\n failures: readonly (LinkSetSubmitFailure | null)[],\n): LinkSetSubmitFailure[] {\n const present = failures.filter(\n (failure): failure is LinkSetSubmitFailure => failure !== null,\n );\n return [\n ...present.filter((failure) => failure.status !== 403),\n ...present.filter((failure) => failure.status === 403),\n ];\n}\n\n/**\n * Rewraps a first attempt may sign without listing: the previous leg's\n * envelopes, or none when the local view holds no attachment for the\n * document. The server's binding check at commit refuses either if stale.\n */\nasync function speculativeBlobRewraps(\n input: RelinkRemoteDocumentInput,\n writerProjection: DocumentWriterProjectionResponse,\n targets: readonly DocumentContentKeyTarget[],\n): Promise<{\n readonly rewraps: DocumentLinkAccessEventBody[\"blobRewraps\"];\n readonly source: \"reused\" | \"skipped\";\n} | null> {\n const committed = input.attachmentReuse?.committed;\n if (committed) {\n const reused = reuseCommittedBlobRewraps({\n committed,\n documentId: writerProjection.documentId,\n targets,\n });\n if (reused) return { rewraps: reused, source: \"reused\" };\n // The previous leg cited attachments this leg cannot re-cite: list them.\n if (committed.length > 0) return null;\n }\n if (\n await documentMayHaveAttachments(input.execSql, writerProjection.documentId)\n )\n return null;\n return { rewraps: [], source: \"skipped\" };\n}\n\nfunction prepareRemoteLinkSetMutation(\n input: RelinkRemoteDocumentInput & {\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt: string;\n },\n writerProjection: DocumentWriterProjectionResponse,\n targetContainerProjection: ContainerWriterProjectionResponse,\n attempt: LinkSetAttemptSlot,\n) {\n const prepareBlobRewraps = async (\n targets: readonly DocumentContentKeyTarget[],\n ) => {\n const prepared: PreparedLinkSetRewraps = (attempt.current.listing ===\n \"speculative\"\n ? await speculativeBlobRewraps(input, writerProjection, targets)\n : null) ?? {\n rewraps: await prepareDocumentLinkBlobRewraps({\n ...input,\n refreshListing: attempt.current.listing === \"fresh\",\n targets,\n targetContainerProjection,\n writerProjection,\n }),\n source: \"listed\",\n };\n attempt.current = recordLinkSetLegRewraps(attempt.current, prepared);\n return prepared.rewraps;\n };\n return recordDocumentAuthorAccessFailure(\n () =>\n nullOnProjectionVerificationCancellation(() =>\n buildMaterializedDocumentLinkSetMutationPlan({\n author: input.author,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n prepareBlobRewraps,\n contentKey: input.contentKey,\n eventId: input.eventId,\n execSql: input.execSql,\n operation: input.operation,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetContainerProjection,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n writerProjection,\n }),\n ),\n input.onFailure,\n );\n}\n"]}
1
+ {"version":3,"file":"linkSetRemote.js","sourceRoot":"","sources":["linkSetRemote.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,mCAAmC,EACnC,yCAAyC,GAC1C,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,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;A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AAwC,CAAC,GAAG,EAAE,CAC5C,4CAA4C,CAAC;QAC3C,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,kBAAkB;QAClB,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,yBAAyB;QACzB,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,+BAA+B,EAC7B,KAAK,CAAC,+BAA+B;QACvC,gBAAgB;KACjB,CAAC,CACH,EACH,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import type {\n DocumentContentKeyTarget,\n DocumentLinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type { DocumentLinkSetMutationRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentLinkSetMutationResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n acknowledgedDocumentLinkSetMutation,\n persistedDocumentStateFromAcknowledgement,\n} from \"../../../data/documents/shared/responses\";\nimport { acknowledgeDocumentMutation } from \"../../../data/documents/shared/sync/mutationAcknowledgement\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationApi,\n DocumentLinkSetMutationOperation,\n RelinkRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { documentMayHaveAttachments } from \"../../../data/persistence/documents/documentAttachmentPresence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { recordDocumentAuthorAccessFailure } from \"../authorAccessFailure\";\nimport type { SubtreePurgeRoot } from \"../purge/subtreePurgeScope\";\nimport type { RemoteDocumentCollaborators } from \"../remote/remoteDocumentCollaborators\";\nimport { completeLinkSetMutationRequest } from \"../rotationBaseline\";\nimport { buildMaterializedDocumentLinkSetMutationPlan } from \"./index\";\nimport {\n type LinkSetAttachmentReuse,\n prepareDocumentLinkBlobRewraps,\n reuseCommittedBlobRewraps,\n} from \"./linkSetBlobRewraps\";\nimport {\n holdsLinkSetRefusals,\n INITIAL_LINK_SET_LEG_STATE,\n type LinkSetLegAttempt,\n type LinkSetSubmitFailure,\n linkSetAttemptEvent,\n type PreparedLinkSetRewraps,\n recordLinkSetLegRewraps,\n startLinkSetLegAttempt,\n transitionLinkSetLeg,\n} from \"./linkSetLegMachine\";\nimport { seedLinkSetWriterProjection } from \"./linkSetProjectionSeed\";\n\nasync function submitLinkSetMutation(input: {\n apiClient: DocumentLinkSetMutationApi;\n documentId: string;\n expectedOrganizationId: string;\n onFailure: (failure: LinkSetSubmitFailure) => void;\n operation: DocumentLinkSetMutationOperation;\n request: DocumentLinkSetMutationRequest;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<DocumentLinkSetMutationResponse | null> {\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input;\n // Preserve the HTTP failure for the durable move-intent queue. Its host\n // report waits until the leg knows the refusal is not one it recovers from.\n const resultFn =\n input.operation === \"link\"\n ? apiClient.linkDocumentResult.bind(apiClient)\n : apiClient.unlinkDocumentResult.bind(apiClient);\n const result = await resultFn(input.documentId, input.request, {\n expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,\n reportErrors: false,\n });\n if (result.ok) {\n return result.data;\n }\n // A refusal the operation no longer waits for is neither retried nor\n // reported.\n if (input.stillCurrent?.() === false) return null;\n input.onFailure({\n code: result.code,\n message: result.message,\n report: result.report,\n status: result.status,\n });\n return null;\n}\n\n/** Hand a refusal the leg does not recover from to its host and caller. */\nfunction reportLinkSetFailure(\n input: Pick<RelinkRemoteDocumentInput, \"onFailure\">,\n failure: LinkSetSubmitFailure,\n): void {\n failure.report?.();\n input.onFailure?.({\n code: failure.code,\n message: failure.message,\n status: failure.status,\n });\n}\n\ninterface LinkSetProjectionFetch<TProjection> {\n failure: LinkSetSubmitFailure | null;\n projection: TProjection | null;\n}\n\n// Cold-cache projection fetches must keep their HTTP status: collapsing a\n// 403 to null would leave an access-denied link/unlink routinely retriable\n// instead of parking its move for the access-restored signal (row 7).\nasync function fetchLinkSetProjection<TProjection>(input: {\n fetchProjectionResult: () => Promise<\n | { readonly data: TProjection; readonly ok: true }\n | DocumentSyncSubmitFailure\n >;\n}): Promise<LinkSetProjectionFetch<TProjection>> {\n const result = await input.fetchProjectionResult();\n if (result.ok) {\n return { failure: null, projection: result.data };\n }\n return {\n failure: {\n code: result.code,\n message: result.message,\n report: result.report,\n status: result.status,\n },\n projection: null,\n };\n}\n\nfunction fetchLinkSetDocumentProjection(\n apiClient: DocumentLinkSetMutationApi,\n documentId: string,\n): Promise<LinkSetProjectionFetch<DocumentWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getDocumentWriterProjectionResult.bind(\n apiClient,\n documentId,\n { reportErrors: false },\n ),\n });\n}\n\nfunction fetchLinkSetContainerProjection(\n apiClient: DocumentLinkSetMutationApi,\n containerId: string,\n): Promise<LinkSetProjectionFetch<ContainerWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getContainerWriterProjectionResult.bind(\n apiClient,\n containerId,\n { reportErrors: false },\n ),\n });\n}\n\nasync function completeRemoteDocumentLinkSet(input: {\n completedPlan: Parameters<typeof acknowledgedDocumentLinkSetMutation>[0];\n execSql: ExecSql;\n materializedPlan: Awaited<\n ReturnType<typeof buildMaterializedDocumentLinkSetMutationPlan>\n >;\n operation: DocumentLinkSetMutationOperation;\n response: DocumentLinkSetMutationResponse;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n apiClient: DocumentLinkSetMutationApi;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const acknowledged = acknowledgedDocumentLinkSetMutation(\n input.completedPlan,\n input.response,\n );\n const persistedState =\n persistedDocumentStateFromAcknowledgement(acknowledged);\n await acknowledgeDocumentMutation({\n bundleDigest: input.response.bundleDigest,\n execSql: input.execSql,\n plan: input.completedPlan,\n stillCurrent: input.stillCurrent,\n });\n await seedLinkSetWriterProjection({\n apiClient: input.apiClient,\n execSql: input.execSql,\n operation: input.operation,\n priorProjection: input.writerProjection,\n response: acknowledged,\n targetContainerId: input.targetContainerId,\n targetContainerProjection: input.targetContainerProjection,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n return {\n contentKey: input.materializedPlan.contentKey,\n contentKeyRotated: input.materializedPlan.contentKeyRotated,\n documentId: input.response.id,\n linkedContainerIds: [\n ...input.materializedPlan.plan.state.linkedContainerIds,\n ],\n persistedState,\n plan: input.completedPlan,\n response: input.response,\n };\n}\n\n/** What varies per link or unlink leg; the collaborators bind the rest. */\nexport interface RelinkRemoteDocumentRequest {\n /** Shared by the legs of one move or trash workflow. */\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n author: DocumentCreateAuthor;\n contentKey?: Uint8Array | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n eventId?: string | undefined;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: DocumentLinkSetMutationOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RelinkRemoteDocumentInput extends RelinkRemoteDocumentRequest {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetSecretKey: Uint8Array;\n}\n\n/**\n * A leg that cited rewraps without listing and was refused because the\n * attachment set (or a re-cited key epoch) moved lists and retries once, as a\n * leg that listed would have; that first refusal is neither reported nor\n * retried once the operation is no longer current (`transitionLinkSetLeg`).\n */\nexport async function relinkRemoteDocument(\n remote: RemoteDocumentCollaborators,\n request: RelinkRemoteDocumentRequest,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (!remote.encapsulationSecretKey) {\n throw new Error(\n \"Remote document link-set mutation requires an encapsulation key\",\n );\n }\n const input: RelinkRemoteDocumentInput = {\n ...request,\n apiClient: remote.api,\n execSql: remote.execSql,\n targetSecretKey: remote.encapsulationSecretKey,\n };\n const reuse = input.attachmentReuse;\n let leg = INITIAL_LINK_SET_LEG_STATE;\n let result: RelinkRemoteDocumentResult | null = null;\n while (leg.status === \"speculative\" || leg.status === \"fresh\") {\n const attempt = { current: startLinkSetLegAttempt(leg) };\n const heldFailures: LinkSetSubmitFailure[] = [];\n result = await relinkRemoteDocumentOnce(input, attempt, (failure) => {\n if (holdsLinkSetRefusals(attempt.current)) heldFailures.push(failure);\n else reportLinkSetFailure(input, failure);\n }).catch((error: unknown) => {\n // A leg that threw may have committed before failing: list again next.\n if (reuse) reuse.committed = null;\n throw error;\n });\n const event = linkSetAttemptEvent({\n attempt: attempt.current,\n committed: result !== null,\n heldFailures,\n stillCurrent: input.stillCurrent?.() !== false,\n });\n if (reuse)\n reuse.committed =\n event.type === \"attemptCommitted\" ? event.rewraps : null;\n leg = transitionLinkSetLeg(leg, event);\n }\n if (leg.status === \"failed\") {\n for (const failure of leg.unreported) reportLinkSetFailure(input, failure);\n }\n return result;\n}\n\n/** The attempt in flight; preparation replaces it with what it signed. */\ninterface LinkSetAttemptSlot {\n current: LinkSetLegAttempt;\n}\n\nasync function relinkRemoteDocumentOnce(\n input: RelinkRemoteDocumentInput,\n attempt: LinkSetAttemptSlot,\n onSubmitFailure: (failure: LinkSetSubmitFailure) => void,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (input.operation === \"unlink\" && !input.rotationSnapshot) {\n throw new Error(\n \"Document unlink requires a proven full-history rotation snapshot\",\n );\n }\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote document link-set mutation\",\n );\n const [writerFetch, targetContainerFetch] = await Promise.all([\n fetchLinkSetDocumentProjection(input.apiClient, input.documentId),\n fetchLinkSetContainerProjection(input.apiClient, input.targetContainerId),\n ]);\n if (!writerFetch.projection || !targetContainerFetch.projection) {\n // A failure the operation no longer waits for is not reported.\n if (input.stillCurrent?.() === false) return null;\n for (const failure of orderedProjectionFailures([\n writerFetch.failure,\n targetContainerFetch.failure,\n ])) {\n reportLinkSetFailure(input, failure);\n }\n return null;\n }\n const writerProjection = writerFetch.projection;\n const targetContainerProjection = targetContainerFetch.projection;\n if (input.stillCurrent?.() === false) return null;\n\n const signedAt = input.signedAt ?? new Date().toISOString();\n const materializedPlan = await prepareRemoteLinkSetMutation(\n { ...input, resolveProjectionUserKey, signedAt },\n writerProjection,\n targetContainerProjection,\n attempt,\n );\n if (!materializedPlan) return null;\n const request = await completeLinkSetMutationRequest({\n author: input.author,\n materializedPlan,\n operation: input.operation,\n rotationSnapshot: input.rotationSnapshot,\n signedAt,\n });\n const completedPlan = { ...materializedPlan.plan, request };\n if (input.beforeSubmit && !(await input.beforeSubmit())) return null;\n const response = await submitLinkSetMutation({\n apiClient: input.apiClient,\n documentId: completedPlan.documentId,\n expectedOrganizationId: completedPlan.state.organizationId,\n onFailure: onSubmitFailure,\n operation: input.operation,\n request: completedPlan.request,\n stillCurrent: input.stillCurrent,\n });\n if (!response) {\n return null;\n }\n if (input.stillCurrent?.() === false) return null;\n return completeRemoteDocumentLinkSet({\n apiClient: input.apiClient,\n completedPlan,\n execSql: input.execSql,\n materializedPlan,\n operation: input.operation,\n response,\n stillCurrent: input.stillCurrent,\n targetContainerId: input.targetContainerId,\n targetContainerProjection,\n writerProjection,\n });\n}\n\n// Every projection failure reaches the handler: the queued-move accumulator\n// classifies a vanished container from ANY coded container 404, so a document\n// fetch failure must not hide a container one (or vice versa). A 403 is\n// delivered last, so a single-slot consumer keeps the denial that parks the\n// move (row 7) while the accumulator still sees both.\nfunction orderedProjectionFailures(\n failures: readonly (LinkSetSubmitFailure | null)[],\n): LinkSetSubmitFailure[] {\n const present = failures.filter(\n (failure): failure is LinkSetSubmitFailure => failure !== null,\n );\n return [\n ...present.filter((failure) => failure.status !== 403),\n ...present.filter((failure) => failure.status === 403),\n ];\n}\n\n/**\n * Rewraps a first attempt may sign without listing: the previous leg's\n * envelopes, or none when the local view holds no attachment for the\n * document. The server's binding check at commit refuses either if stale.\n */\nasync function speculativeBlobRewraps(\n input: RelinkRemoteDocumentInput,\n writerProjection: DocumentWriterProjectionResponse,\n targets: readonly DocumentContentKeyTarget[],\n): Promise<{\n readonly rewraps: DocumentLinkAccessEventBody[\"blobRewraps\"];\n readonly source: \"reused\" | \"skipped\";\n} | null> {\n const committed = input.attachmentReuse?.committed;\n if (committed) {\n const reused = reuseCommittedBlobRewraps({\n committed,\n documentId: writerProjection.documentId,\n targets,\n });\n if (reused) return { rewraps: reused, source: \"reused\" };\n // The previous leg cited attachments this leg cannot re-cite: list them.\n if (committed.length > 0) return null;\n }\n if (\n await documentMayHaveAttachments(input.execSql, writerProjection.documentId)\n )\n return null;\n return { rewraps: [], source: \"skipped\" };\n}\n\nfunction prepareRemoteLinkSetMutation(\n input: RelinkRemoteDocumentInput & {\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt: string;\n },\n writerProjection: DocumentWriterProjectionResponse,\n targetContainerProjection: ContainerWriterProjectionResponse,\n attempt: LinkSetAttemptSlot,\n) {\n const prepareBlobRewraps = async (\n targets: readonly DocumentContentKeyTarget[],\n ) => {\n const prepared: PreparedLinkSetRewraps = (attempt.current.listing ===\n \"speculative\"\n ? await speculativeBlobRewraps(input, writerProjection, targets)\n : null) ?? {\n rewraps: await prepareDocumentLinkBlobRewraps({\n ...input,\n refreshListing: attempt.current.listing === \"fresh\",\n targets,\n targetContainerProjection,\n writerProjection,\n }),\n source: \"listed\",\n };\n attempt.current = recordLinkSetLegRewraps(attempt.current, prepared);\n return prepared.rewraps;\n };\n return recordDocumentAuthorAccessFailure(\n () =>\n nullOnProjectionVerificationCancellation(() =>\n buildMaterializedDocumentLinkSetMutationPlan({\n author: input.author,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n prepareBlobRewraps,\n contentKey: input.contentKey,\n eventId: input.eventId,\n execSql: input.execSql,\n operation: input.operation,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetContainerProjection,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n writerProjection,\n }),\n ),\n input.onFailure,\n );\n}\n"]}
@@ -2,6 +2,7 @@ import { ContainerKekRepairInaccessibleError } from "../../../data/documents/sha
2
2
  import { assertDocumentManifestBundleConsistent } from "../../../data/documents/shared/readers.js";
3
3
  import { isDocumentSyncRequestLimitError } from "../../../data/documents/shared/sync/documentSyncOutgoingBatch.js";
4
4
  import { resolvePullContinuationMinLsn, } from "../../../data/documents/shared/sync/syncPagination.js";
5
+ import { checkWithHeldBundleRecovery } from "../../../data/keyingProjectionVerification/index.js";
5
6
  import { retrySyncPlanOrAbandon } from "../syncFailures/index.js";
6
7
  import { abandonAncestorRepair, abandonBlockedSync, abandonInaccessibleAncestorRepair, abandonOversizedSyncPlan, isPullUnderWay, } from "../syncFailures/syncAbandon.js";
7
8
  import { DocumentAncestorRepairAbandonedError, DocumentSyncPreparationRequiredError, } from "../syncFailures/syncRepairAbandon.js";
@@ -34,10 +35,15 @@ async function plannedPendingUpdates(input) {
34
35
  return [];
35
36
  if (input.pendingUpdates.length === 0)
36
37
  return input.pendingUpdates;
37
- const { organizationId } = await assertDocumentManifestBundleConsistent({
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;AAE5D,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;;;;;;;;;GASG;AACH,MAAM,UAAU,wBAAwB,CACtC,KAA6B,EAC7B,yBAAkC;IAElC,OAAO,yBAAyB;QAC9B,CAAC,CAAC,KAAK,CAAC,uBAAuB;QAC/B,CAAC,CAAC,KAAK,CAAC,2BAA2B,CAAC;AACxC,CAAC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AAC,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 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 const { organizationId } = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document sync manifest\",\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
+ {"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,M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ACjB,CAAC;YACJ,UAAU,EAAE,KAAK,CAAC,IAAI,CAAC,UAAU;YACjC,uBAAuB,EAAE,KAAK,CAAC,IAAI,CAAC,uBAAuB;YAC3D,eAAe,EAAE,KAAK,CAAC,IAAI,CAAC,eAAe;YAC3C,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW;YACnC,iBAAiB,EAAE,wBAAwB,CACzC,KAAK,CAAC,IAAI,EACV,KAAK,CAAC,yBAAyB,CAChC;YACD,YAAY,EAAE,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;AAC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,oCAAoC,CAAC,SAAS,CAAC,CAAC;YAC5D,CAAC;YACD,qEAAqE;YACrE,uEAAuE;YACvE,uEAAuE;YACvE,MAAM,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC;gBACtC,CAAC,CAAC,IAAI,mCAAmC,CACrC,kBAAkB,CAAC,WAAW,CAC/B;gBACH,CAAC,CAAC,KAAK,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,UAAU,CAAC,GAAG,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;QAC/C,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpB,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { MAX_INLINE_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { buildMaterializedContainerRekeyPlan } from \"../../containers\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { hasOtherLinkedWriteAccess } from \"../syncFailures/syncRepairAccess\";\nimport { applyContainerRekeyPlan } from \"./syncContainerRekeyProjection\";\n\ninterface StaleContainer {\n /** The stale container is the one the document itself is linked into. */\n readonly isPathTarget: boolean;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\nfunction firstStaleContainer(\n projection: DocumentWriterProjectionResponse,\n): StaleContainer | null {\n for (const path of documentContainerProjections(projection)) {\n for (let index = 1; index < path.containerKeks.length; index += 1) {\n const parent = path.containerKeks[index - 1];\n const child = path.containerKeks[index];\n if (!parent || !child)\n throw new Error(\"Container KEK path is incomplete\");\n if (child.parentContainerKeyEpochId === parent.containerKeyEpochId) {\n continue;\n }\n return {\n isPathTarget: index === path.containerKeks.length - 1,\n projection: {\n ...path,\n containerId: child.containerId,\n containerKeks: path.containerKeks.slice(0, index + 1),\n path: path.path.slice(0, index + 1),\n },\n };\n }\n }\n return null;\n}\n\n/**\n * The stale container is not this writer's to re-key: no wrap on the verified\n * path opens it, or the signed path grants the signer no write access there.\n * Both are judged against the path sliced at the stale container, so a grant\n * held only further down never counts — exactly the API's `container.rekey`\n * rule. Anything else (keyring damage, a forged path) stays an error.\n *\n * A target's write refusal is handled separately: another linked target may\n * still authorize the document write. Key unwrap failures on a target stay\n * errors, because this path's readable grant should open its own key.\n */\nfunction isRepairInaccessible(error: unknown, stale: StaleContainer): boolean {\n if (stale.isPathTarget) return false;\n return (\n error instanceof ContainerAuthorAccessError ||\n (error instanceof ContainerKekTargetUnreachableError &&\n error.containerId === stale.projection.containerId)\n );\n}\n\n/** Prepare parent-first repairs; the sync transaction commits them with the write. */\nexport async function buildAutomaticContainerRekeys(\n sync: RemoteDocumentSyncPass,\n initialProjection: DocumentWriterProjectionResponse,\n): Promise<{ plans: MaterializedContainerRekeyPlan[]; hasMore: boolean }> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const plannedIds = new Set<string>();\n let projection = initialProjection;\n for (;;) {\n const stale = firstStaleContainer(projection);\n if (!stale) return { plans, hasMore: false };\n const previousProjection = stale.projection;\n if (plans.length >= MAX_INLINE_CONTAINER_REKEYS) {\n return { plans, hasMore: true };\n }\n // Use the shared cancellation sentinel: syncRemoteDocument converts only\n // that to a graceful null, so a plain Error would report a routine\n // generation flip mid-repair as a real sync failure.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n if (plannedIds.has(previousProjection.containerId)) {\n // Abandon like every other routine repair failure: two linked paths\n // disagreeing about a container is a concurrent-rotation race, not a\n // defect, and a raw Error would crash the sync lane instead.\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n // Assert rather than adopt: resolveRotationContext compares the verified\n // manifest's organization against the author's, so substituting the path's\n // own organization here would make that the only cross-org check and leave\n // it comparing a server-supplied value with itself.\n if (previousProjection.organizationId !== sync.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair crosses the author's organization\",\n );\n }\n const planned = await buildMaterializedContainerRekeyPlan({\n author: sync.author,\n persistVerificationCheckpoints: false,\n previousProjection,\n signedAt: sync.signedAt,\n targetSecretKey: sync.targetSecretKey,\n resolveProjectionUserKey: sync.resolveProjectionUserKey,\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n execSql: sync.execSql,\n }).catch(async (error: unknown) => {\n if (error instanceof ContainerAuthorAccessError && stale.isPathTarget) {\n if (\n await hasOtherLinkedWriteAccess(\n sync,\n initialProjection,\n previousProjection.containerId,\n )\n ) {\n throw new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n );\n }\n await sync.onTerminalSubmitFailure?.({\n code: error.code,\n message: error.message,\n ok: false,\n report: () => undefined,\n status: error.status,\n });\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // Repairs run parent-first and access inherits downward, so only the\n // first stale container can be out of reach. Retry-classified like any\n // stale path: one refetch sees a repair a capable member already made.\n throw isRepairInaccessible(error, stale)\n ? new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n )\n : error;\n });\n plannedIds.add(previousProjection.containerId);\n plans.push(planned);\n projection = await applyContainerRekeyPlan(projection, planned);\n }\n}\n"]}
1
+ {"version":3,"file":"syncAutomaticContainerRekeys.js","sourceRoot":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AC,uBAAuB,EAAE,CAAC;oBACnC,IAAI,EAAE,KAAK,CAAC,IAAI;oBAChB,OAAO,EAAE,KAAK,CAAC,OAAO;oBACtB,EAAE,EAAE,KAAK;oBACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;oBACvB,MAAM,EAAE,KAAK,CAAC,MAAM;iBACrB,CAAC,CAAC;gBACH,MAAM,IAAI,oCAAoC,CAAC,SAAS,CAAC,CAAC;YAC5D,CAAC;YACD,qEAAqE;YACrE,uEAAuE;YACvE,uEAAuE;YACvE,MAAM,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC;gBACtC,CAAC,CAAC,IAAI,mCAAmC,CACrC,kBAAkB,CAAC,WAAW,CAC/B;gBACH,CAAC,CAAC,KAAK,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,UAAU,CAAC,GAAG,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;QAC/C,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpB,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n type ContainerWriterProjectionResponse,\n type DocumentWriterProjectionResponse,\n deriveDecodedProjection,\n} from \"@tearleads/validators/response\";\nimport { MAX_INLINE_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { buildMaterializedContainerRekeyPlan } from \"../../containers\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { hasOtherLinkedWriteAccess } from \"../syncFailures/syncRepairAccess\";\nimport { applyContainerRekeyPlan } from \"./syncContainerRekeyProjection\";\n\ninterface StaleContainer {\n /** The stale container is the one the document itself is linked into. */\n readonly isPathTarget: boolean;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\nfunction firstStaleContainer(\n projection: DocumentWriterProjectionResponse,\n): StaleContainer | null {\n for (const path of documentContainerProjections(projection)) {\n for (let index = 1; index < path.containerKeks.length; index += 1) {\n const parent = path.containerKeks[index - 1];\n const child = path.containerKeks[index];\n if (!parent || !child)\n throw new Error(\"Container KEK path is incomplete\");\n if (child.parentContainerKeyEpochId === parent.containerKeyEpochId) {\n continue;\n }\n return {\n isPathTarget: index === path.containerKeks.length - 1,\n projection: deriveDecodedProjection(path, {\n ...path,\n containerId: child.containerId,\n containerKeks: path.containerKeks.slice(0, index + 1),\n path: path.path.slice(0, index + 1),\n }),\n };\n }\n }\n return null;\n}\n\n/**\n * The stale container is not this writer's to re-key: no wrap on the verified\n * path opens it, or the signed path grants the signer no write access there.\n * Both are judged against the path sliced at the stale container, so a grant\n * held only further down never counts — exactly the API's `container.rekey`\n * rule. Anything else (keyring damage, a forged path) stays an error.\n *\n * A target's write refusal is handled separately: another linked target may\n * still authorize the document write. Key unwrap failures on a target stay\n * errors, because this path's readable grant should open its own key.\n */\nfunction isRepairInaccessible(error: unknown, stale: StaleContainer): boolean {\n if (stale.isPathTarget) return false;\n return (\n error instanceof ContainerAuthorAccessError ||\n (error instanceof ContainerKekTargetUnreachableError &&\n error.containerId === stale.projection.containerId)\n );\n}\n\n/** Prepare parent-first repairs; the sync transaction commits them with the write. */\nexport async function buildAutomaticContainerRekeys(\n sync: RemoteDocumentSyncPass,\n initialProjection: DocumentWriterProjectionResponse,\n): Promise<{ plans: MaterializedContainerRekeyPlan[]; hasMore: boolean }> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const plannedIds = new Set<string>();\n let projection = initialProjection;\n for (;;) {\n const stale = firstStaleContainer(projection);\n if (!stale) return { plans, hasMore: false };\n const previousProjection = stale.projection;\n if (plans.length >= MAX_INLINE_CONTAINER_REKEYS) {\n return { plans, hasMore: true };\n }\n // Use the shared cancellation sentinel: syncRemoteDocument converts only\n // that to a graceful null, so a plain Error would report a routine\n // generation flip mid-repair as a real sync failure.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n if (plannedIds.has(previousProjection.containerId)) {\n // Abandon like every other routine repair failure: two linked paths\n // disagreeing about a container is a concurrent-rotation race, not a\n // defect, and a raw Error would crash the sync lane instead.\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n // Assert rather than adopt: resolveRotationContext compares the verified\n // manifest's organization against the author's, so substituting the path's\n // own organization here would make that the only cross-org check and leave\n // it comparing a server-supplied value with itself.\n if (previousProjection.organizationId !== sync.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair crosses the author's organization\",\n );\n }\n const planned = await buildMaterializedContainerRekeyPlan({\n author: sync.author,\n persistVerificationCheckpoints: false,\n previousProjection,\n signedAt: sync.signedAt,\n targetSecretKey: sync.targetSecretKey,\n resolveProjectionUserKey: sync.resolveProjectionUserKey,\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n execSql: sync.execSql,\n }).catch(async (error: unknown) => {\n if (error instanceof ContainerAuthorAccessError && stale.isPathTarget) {\n if (\n await hasOtherLinkedWriteAccess(\n sync,\n initialProjection,\n previousProjection.containerId,\n )\n ) {\n throw new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n );\n }\n await sync.onTerminalSubmitFailure?.({\n code: error.code,\n message: error.message,\n ok: false,\n report: () => undefined,\n status: error.status,\n });\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // Repairs run parent-first and access inherits downward, so only the\n // first stale container can be out of reach. Retry-classified like any\n // stale path: one refetch sees a repair a capable member already made.\n throw isRepairInaccessible(error, stale)\n ? new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n )\n : error;\n });\n plannedIds.add(previousProjection.containerId);\n plans.push(planned);\n projection = await applyContainerRekeyPlan(projection, planned);\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { computeDocumentContentKeyTargetHash } from "../../../internal/crypto/index.js";
2
+ import { deriveDecodedProjection, } from "../../../internal/validators/response/index.js";
2
3
  import { normalizeDocumentKekTargetResponse, readManifestContainerId, } from "../../../data/documents/shared/readers.js";
3
4
  function replaceRekeyedPathNode(input) {
4
5
  const index = input.projection.path.findIndex((bundle) => readManifestContainerId(bundle) === input.plan.plan.containerId);
@@ -54,7 +55,7 @@ export async function applyContainerRekeyPlan(writerProjection, plan) {
54
55
  throw new Error("Document inline rekey does not belong to its writer projection");
55
56
  }
56
57
  const documentKeyTargetHash = await computeDocumentContentKeyTargetHash(targets);
57
- return {
58
+ return deriveDecodedProjection(writerProjection, {
58
59
  ...writerProjection,
59
60
  authorizingContainerPaths,
60
61
  ...(documentKeyTargetHash === writerProjection.contentKeyBundle.targetHash
@@ -67,7 +68,7 @@ export async function applyContainerRekeyPlan(writerProjection, plan) {
67
68
  linkedContainerManifestHashes: targets.map((target) => target.containerManifestHash),
68
69
  targets: targets.map((target) => ({ ...target })),
69
70
  },
70
- };
71
+ });
71
72
  }
72
73
  export async function applyDocumentSyncContainerRekeys(input) {
73
74
  let projection = input.writerProjection;
@@ -1 +1 @@
1
- {"version":3,"file":"syncContainerRekeyProjection.js","sourceRoot":"","sources":["syncContainerRekeyProjection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;AAGxE,OAAO,EACL,kCAAkC,EAClC,uBAAuB,GACxB,MAAM,wCAAwC,CAAC;AAEhD,SAAS,sBAAsB,CAAC,KAG/B;IACC,MAAM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,YAAY,CAAC,YAAY;SACjD,CAAC;IACJ,CAAC,CAAC,CAAC;IACH,IAAI,CAAC,YAAY,IAAI,CAAC,cAAc,EAAE,CAAC;QACrC,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;IACJ,CAAC;IACD,MAAM,qBAAqB,GACzB,MAAM,mCAAmC,CAAC,OAAO,CAAC,CAAC;IACrD,OAAO;QACL,GAAG,gBAAgB;QACnB,yBAAyB;QACzB,GAAG,CAAC,qBAAqB,KAAK,gBAAgB,CAAC,gBAAgB,CAAC,UAAU;YACxE,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,EAAE,qBAAqB,EAAE,IAAa,EAAE,CAAC;QAC7C,kBAAkB,EAAE;YAClB,GAAG,gBAAgB,CAAC,kBAAkB;YACtC,qBAAqB;YACrB,0BAA0B,EAAE,OAAO,CAAC,GAAG,CACrC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,mBAAmB,CACvC;YACD,6BAA6B,EAAE,OAAO,CAAC,GAAG,CACxC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,qBAAqB,CACzC;YACD,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;SAClD;KACF,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gCAAgC,CAAC,KAGtD;IACC,IAAI,UAAU,GAAG,KAAK,CAAC,gBAAgB,CAAC;IACxC,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;QAC/B,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { computeDocumentContentKeyTargetHash } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } 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 {\n ...writerProjection,\n authorizingContainerPaths,\n ...(documentKeyTargetHash === writerProjection.contentKeyBundle.targetHash\n ? {}\n : { contentKeyBundleStale: true as const }),\n documentKekTargets: {\n ...writerProjection.documentKekTargets,\n documentKeyTargetHash,\n linkedContainerKeyEpochIds: targets.map(\n (target) => target.containerKeyEpochId,\n ),\n linkedContainerManifestHashes: targets.map(\n (target) => target.containerManifestHash,\n ),\n targets: targets.map((target) => ({ ...target })),\n },\n };\n}\n\nexport async function applyDocumentSyncContainerRekeys(input: {\n plans: readonly MaterializedContainerRekeyPlan[];\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<DocumentWriterProjectionResponse> {\n let projection = input.writerProjection;\n for (const plan of input.plans) {\n projection = await applyContainerRekeyPlan(projection, plan);\n }\n return projection;\n}\n"]}
1
+ {"version":3,"file":"syncContainerRekeyProjection.js","sourceRoot":"","sources":["syncContainerRekeyProjection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,EAEL,uBAAuB,GACxB,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,kCAAkC,EAClC,uBAAuB,GACxB,MAAM,wCAAwC,CAAC;AAEhD,SAAS,sBAAsB,CAAC,KAG/B;IACC,MAAM,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS,CAC3C,CAAC,MAAM,EAAE,EAAE,CAAC,uBAAuB,CAAC,MAAM,CAAC,KAAK,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAC5E,CAAC;IACF,IAAI,KAAK,GAAG,CAAC;QAAE,OAAO,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,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AgB,EAAE;QAC/C,GAAG,gBAAgB;QACnB,yBAAyB;QACzB,GAAG,CAAC,qBAAqB,KAAK,gBAAgB,CAAC,gBAAgB,CAAC,UAAU;YACxE,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,EAAE,qBAAqB,EAAE,IAAa,EAAE,CAAC;QAC7C,kBAAkB,EAAE;YAClB,GAAG,gBAAgB,CAAC,kBAAkB;YACtC,qBAAqB;YACrB,0BAA0B,EAAE,OAAO,CAAC,GAAG,CACrC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,mBAAmB,CACvC;YACD,6BAA6B,EAAE,OAAO,CAAC,GAAG,CACxC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,qBAAqB,CACzC;YACD,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;SAClD;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gCAAgC,CAAC,KAGtD;IACC,IAAI,UAAU,GAAG,KAAK,CAAC,gBAAgB,CAAC;IACxC,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;QAC/B,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { computeDocumentContentKeyTargetHash } from \"@tearleads/crypto\";\nimport {\n type DocumentWriterProjectionResponse,\n deriveDecodedProjection,\n} from \"@tearleads/validators/response\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport {\n normalizeDocumentKekTargetResponse,\n readManifestContainerId,\n} from \"../../../data/documents/shared/readers\";\n\nfunction replaceRekeyedPathNode(input: {\n plan: MaterializedContainerRekeyPlan;\n projection: DocumentWriterProjectionResponse[\"authorizingContainerPaths\"][number];\n}) {\n const index = input.projection.path.findIndex(\n (bundle) => readManifestContainerId(bundle) === input.plan.plan.containerId,\n );\n if (index < 0) return { projection: input.projection, replaced: false };\n const previousManifest = input.projection.path[index];\n const previousKek = input.projection.containerKeks[index];\n const nextManifest = input.plan.writerProjection.path.at(-1);\n const nextKek = input.plan.writerProjection.containerKeks.at(-1);\n if (\n !previousManifest ||\n !previousKek ||\n !nextManifest ||\n !nextKek ||\n previousManifest.manifestHash !==\n input.plan.plan.previousManifest.manifestHash ||\n previousKek.accessManifestHash !== previousManifest.manifestHash\n ) {\n throw new Error(\"Document inline rekey projection predecessor mismatch\");\n }\n const path = [...input.projection.path];\n const containerKeks = [...input.projection.containerKeks];\n path[index] = nextManifest;\n containerKeks[index] = nextKek;\n return {\n projection: { ...input.projection, containerKeks, path },\n replaced: true,\n };\n}\n\nexport async function applyContainerRekeyPlan(\n writerProjection: DocumentWriterProjectionResponse,\n plan: MaterializedContainerRekeyPlan,\n): Promise<DocumentWriterProjectionResponse> {\n let replacedPath = false;\n const authorizingContainerPaths =\n writerProjection.authorizingContainerPaths.map((projection) => {\n const replaced = replaceRekeyedPathNode({ plan, projection });\n replacedPath ||= replaced.replaced;\n return replaced.projection;\n });\n const nextKek = plan.writerProjection.containerKeks.at(-1);\n const nextManifest = plan.writerProjection.path.at(-1);\n if (!nextKek || !nextManifest) {\n throw new Error(\"Document inline rekey projection is empty\");\n }\n let replacedTarget = false;\n const targets = normalizeDocumentKekTargetResponse(\n writerProjection.documentKekTargets,\n ).map((target) => {\n if (target.containerId !== plan.plan.containerId) return target;\n replacedTarget = true;\n return {\n ...target,\n containerKeyEpoch: nextKek.containerKeyEpoch,\n containerKeyEpochId: nextKek.containerKeyEpochId,\n containerManifestHash: nextManifest.manifestHash,\n };\n });\n if (!replacedPath && !replacedTarget) {\n throw new Error(\n \"Document inline rekey does not belong to its writer projection\",\n );\n }\n const documentKeyTargetHash =\n await computeDocumentContentKeyTargetHash(targets);\n return deriveDecodedProjection(writerProjection, {\n ...writerProjection,\n authorizingContainerPaths,\n ...(documentKeyTargetHash === writerProjection.contentKeyBundle.targetHash\n ? {}\n : { contentKeyBundleStale: true as const }),\n documentKekTargets: {\n ...writerProjection.documentKekTargets,\n documentKeyTargetHash,\n linkedContainerKeyEpochIds: targets.map(\n (target) => target.containerKeyEpochId,\n ),\n linkedContainerManifestHashes: targets.map(\n (target) => target.containerManifestHash,\n ),\n targets: targets.map((target) => ({ ...target })),\n },\n });\n}\n\nexport async function applyDocumentSyncContainerRekeys(input: {\n plans: readonly MaterializedContainerRekeyPlan[];\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<DocumentWriterProjectionResponse> {\n let projection = input.writerProjection;\n for (const plan of input.plans) {\n projection = await applyContainerRekeyPlan(projection, plan);\n }\n return projection;\n}\n"]}
@@ -48,6 +48,7 @@ export declare function requestOrganizationCreation(input: {
48
48
  keyTargetHash: string;
49
49
  parentContainerKeyEpochId: string | null;
50
50
  };
51
+ bundleDigest: string;
51
52
  containerId: string;
52
53
  createdAt: string;
53
54
  eventHash: string;
@@ -62,6 +63,7 @@ export declare function requestOrganizationCreation(input: {
62
63
  };
63
64
  metadataDocument: {
64
65
  createdAt: string;
66
+ bundleDigest: string;
65
67
  contentKeyEpoch: number;
66
68
  eventHash: string;
67
69
  id: string;
@@ -75,11 +77,13 @@ export declare function requestOrganizationCreation(input: {
75
77
  };
76
78
  };
77
79
  organizationMetadataContainerId: string;
80
+ rootBundleDigest: string;
78
81
  rootContainerId: string;
79
82
  rootMetadataAccessEpoch: number;
80
83
  rootMetadataAccessStateHash: string;
81
84
  rootMetadataDocument: {
82
85
  createdAt: string;
86
+ bundleDigest: string;
83
87
  contentKeyEpoch: number;
84
88
  eventHash: string;
85
89
  id: string;
@@ -102,6 +106,7 @@ export declare function requestOrganizationCreation(input: {
102
106
  keyTargetHash: string;
103
107
  parentContainerKeyEpochId: string | null;
104
108
  };
109
+ bundleDigest: string;
105
110
  containerId: string;
106
111
  createdAt: string;
107
112
  eventHash: string;
@@ -116,6 +121,7 @@ export declare function requestOrganizationCreation(input: {
116
121
  };
117
122
  metadataDocument: {
118
123
  createdAt: string;
124
+ bundleDigest: string;
119
125
  contentKeyEpoch: number;
120
126
  eventHash: string;
121
127
  id: string;
@@ -131,6 +137,7 @@ export declare function requestOrganizationCreation(input: {
131
137
  userId: string;
132
138
  organizationProfileDocument?: {
133
139
  createdAt: string;
140
+ bundleDigest: string;
134
141
  contentKeyEpoch: number;
135
142
  eventHash: string;
136
143
  id: string;
@@ -153,6 +160,7 @@ export declare function requestOrganizationCreation(input: {
153
160
  keyTargetHash: string;
154
161
  parentContainerKeyEpochId: string | null;
155
162
  };
163
+ bundleDigest: string;
156
164
  containerId: string;
157
165
  createdAt: string;
158
166
  eventHash: string;
@@ -167,6 +175,7 @@ export declare function requestOrganizationCreation(input: {
167
175
  };
168
176
  metadataDocument: {
169
177
  createdAt: string;
178
+ bundleDigest: string;
170
179
  contentKeyEpoch: number;
171
180
  eventHash: string;
172
181
  id: string;
@@ -182,6 +191,7 @@ export declare function requestOrganizationCreation(input: {
182
191
  rosterProfileContainerId?: string | undefined;
183
192
  rosterProfileDocument?: {
184
193
  createdAt: string;
194
+ bundleDigest: string;
185
195
  contentKeyEpoch: number;
186
196
  eventHash: string;
187
197
  id: string;
@@ -1,6 +1,7 @@
1
1
  import { locallyAcknowledgedContainerMutationHead } from "../../data/containers/shared/mutationAcknowledgement.js";
2
2
  import { assertDocumentCreateResponseMatchesPlan } from "../../data/documents/shared/responses.js";
3
- import { locallyAuthoredAccessManifestHead, } from "../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
3
+ import { locallyAcknowledgedDocumentHead } from "../../data/documents/shared/sync/mutationAcknowledgement.js";
4
+ import { locallyAcknowledgedAuthoredHead, } from "../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
4
5
  function requireResponse(value, label) {
5
6
  if (!value) {
6
7
  throw new Error(`Organization provisioning response is missing ${label}`);
@@ -30,12 +31,19 @@ async function containerArtifactHeads(input) {
30
31
  plan: input.artifact.containerPlan,
31
32
  response: input.response.container,
32
33
  }),
33
- locallyAuthoredAccessManifestHead(input.artifact.metadataDocumentPlan),
34
+ await locallyAcknowledgedDocumentHead(input.artifact.metadataDocumentPlan, input.response.metadataDocument.bundleDigest),
34
35
  ];
35
36
  }
36
37
  function documentHead(input) {
37
38
  assertDocumentCreateResponseMatchesPlan(input.plan, input.response);
38
- return locallyAuthoredAccessManifestHead(input.plan);
39
+ return locallyAcknowledgedDocumentHead(input.plan, input.response.bundleDigest);
40
+ }
41
+ function assertProvisionedArtifactIds(input) {
42
+ const { response } = input;
43
+ assertId(response.rosterProfileContainerId, input.rosterProfile.containerPlan.containerId, "roster profile container id");
44
+ assertId(response.rosterProfileDocumentId, input.rosterProfileDocumentPlan.documentId, "roster profile document id");
45
+ assertId(response.organizationMetadataContainerId, input.organizationMetadata.containerPlan.containerId, "organization metadata container id");
46
+ assertId(response.organizationProfileDocumentId, input.organizationProfileDocumentPlan.documentId, "organization profile document id");
39
47
  }
40
48
  export async function provisioningAcknowledgedAccessHeads(input) {
41
49
  assertProvisioningIdentity(input);
@@ -45,22 +53,19 @@ export async function provisioningAcknowledgedAccessHeads(input) {
45
53
  const rosterDocument = requireResponse(response.rosterProfileDocument, "roster profile document");
46
54
  const organizationContainer = requireResponse(response.organizationMetadataContainer, "organization metadata container");
47
55
  const organizationDocument = requireResponse(response.organizationProfileDocument, "organization profile document");
48
- assertId(response.rosterProfileContainerId, input.rosterProfile.containerPlan.containerId, "roster profile container id");
49
- assertId(response.rosterProfileDocumentId, input.rosterProfileDocumentPlan.documentId, "roster profile document id");
50
- assertId(response.organizationMetadataContainerId, input.organizationMetadata.containerPlan.containerId, "organization metadata container id");
51
- assertId(response.organizationProfileDocumentId, input.organizationProfileDocumentPlan.documentId, "organization profile document id");
56
+ assertProvisionedArtifactIds(input);
52
57
  const systemResponses = response.systemContainers;
53
58
  if (systemResponses.length !== input.systemContainers.length) {
54
59
  throw new Error("Organization provisioning response system container count mismatch");
55
60
  }
56
61
  const heads = [
57
- locallyAuthoredAccessManifestHead(input.rootContainerPlan),
58
- locallyAuthoredAccessManifestHead(input.rootMetadataDocumentPlan),
62
+ await locallyAcknowledgedAuthoredHead(input.rootContainerPlan, response.rootBundleDigest),
63
+ await locallyAcknowledgedDocumentHead(input.rootMetadataDocumentPlan, response.rootMetadataDocument.bundleDigest),
59
64
  ...(await containerArtifactHeads({
60
65
  artifact: input.rosterProfile,
61
66
  response: rosterContainer,
62
67
  })),
63
- documentHead({
68
+ await documentHead({
64
69
  plan: input.rosterProfileDocumentPlan,
65
70
  response: rosterDocument,
66
71
  }),
@@ -68,7 +73,7 @@ export async function provisioningAcknowledgedAccessHeads(input) {
68
73
  artifact: input.organizationMetadata,
69
74
  response: organizationContainer,
70
75
  })),
71
- documentHead({
76
+ await documentHead({
72
77
  plan: input.organizationProfileDocumentPlan,
73
78
  response: organizationDocument,
74
79
  }),