@tearleads/client-sdk 0.1.256 → 0.1.257

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 (99) hide show
  1. package/client/documents/index.d.ts +5 -2
  2. package/client/documents/index.js +6 -1
  3. package/client/documents/index.js.map +1 -1
  4. package/client/index.d.ts +1 -1
  5. package/client/index.js.map +1 -1
  6. package/data/blobs/attachments/types.d.ts +4 -2
  7. package/data/blobs/attachments/types.js.map +1 -1
  8. package/data/documents/documentContent.d.ts +2 -0
  9. package/data/documents/documentContent.js +7 -0
  10. package/data/documents/documentContent.js.map +1 -1
  11. package/data/documents/shared/manifestBundleReaders.js +1 -1
  12. package/data/documents/shared/manifestBundleReaders.js.map +1 -1
  13. package/data/documents/shared/projection/documentCreateSigner.d.ts +19 -0
  14. package/data/documents/shared/projection/documentCreateSigner.js +49 -0
  15. package/data/documents/shared/projection/documentCreateSigner.js.map +1 -0
  16. package/data/documents/shared/projection/index.d.ts +1 -0
  17. package/data/documents/shared/projection/index.js +1 -0
  18. package/data/documents/shared/projection/index.js.map +1 -1
  19. package/data/documents/shared/readers.js +1 -1
  20. package/data/documents/shared/readers.js.map +1 -1
  21. package/data/documents/shared/types.d.ts +1 -0
  22. package/data/documents/shared/types.js.map +1 -1
  23. package/data/persistence/documents/documentsPersistence.d.ts +1 -1
  24. package/data/persistence/documents/documentsPersistence.js +4 -1
  25. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  26. package/index.d.ts +3 -3
  27. package/index.js +2 -2
  28. package/index.js.map +1 -1
  29. package/internal/api-client/ApiClient.d.ts +2 -2
  30. package/internal/api-client/apiRequestRuntime.js +12 -8
  31. package/internal/api-client/apiRequestRuntime.js.map +1 -1
  32. package/internal/api-client/binaryResponseOperationTransport.js +2 -2
  33. package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
  34. package/internal/api-client/client/blobs.d.ts +2 -2
  35. package/internal/api-client/client/blobs.js +21 -9
  36. package/internal/api-client/client/blobs.js.map +1 -1
  37. package/internal/api-client/client/writerProjections.js +2 -1
  38. package/internal/api-client/client/writerProjections.js.map +1 -1
  39. package/internal/api-client/operationResponse.js +3 -3
  40. package/internal/api-client/operationResponse.js.map +1 -1
  41. package/internal/api-client/routes/blobs/multipartUpload.js +10 -3
  42. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  43. package/internal/api-client/sessionRefresh.js +6 -1
  44. package/internal/api-client/sessionRefresh.js.map +1 -1
  45. package/internal/api-client/sessionResponse.js +5 -2
  46. package/internal/api-client/sessionResponse.js.map +1 -1
  47. package/internal/api-client/types.d.ts +2 -0
  48. package/internal/api-client/types.js.map +1 -1
  49. package/package.json +1 -1
  50. package/stores/documents/documentStore/initialization/createSeededDocument.d.ts +16 -0
  51. package/stores/documents/documentStore/initialization/createSeededDocument.js +119 -0
  52. package/stores/documents/documentStore/initialization/createSeededDocument.js.map +1 -0
  53. package/stores/documents/documentStore/initialization/initialContent.js.map +1 -1
  54. package/stores/documents/documentStore/rows/rowAttribution.js.map +1 -1
  55. package/stores/documents/documentStore/state.js +3 -1
  56. package/stores/documents/documentStore/state.js.map +1 -1
  57. package/stores/documents/documentStore/sync/syncShared.js +3 -2
  58. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  59. package/stores/documents/index.d.ts +1 -0
  60. package/stores/documents/index.js +1 -0
  61. package/stores/documents/index.js.map +1 -1
  62. package/stores/documents/types.d.ts +1 -0
  63. package/stores/documents/types.js.map +1 -1
  64. package/workflows/blobs/upload/index.d.ts +1 -1
  65. package/workflows/blobs/upload/index.js +36 -18
  66. package/workflows/blobs/upload/index.js.map +1 -1
  67. package/workflows/blobs/upload/multipartStageResolution.js +12 -2
  68. package/workflows/blobs/upload/multipartStageResolution.js.map +1 -1
  69. package/workflows/blobs/upload/multipartUpload.js +10 -2
  70. package/workflows/blobs/upload/multipartUpload.js.map +1 -1
  71. package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.d.ts +160 -0
  72. package/workflows/container-contents/documentQueries/index.d.ts +1 -1
  73. package/workflows/container-contents/documentQueries/index.js +2 -2
  74. package/workflows/container-contents/documentQueries/index.js.map +1 -1
  75. package/workflows/container-contents/index.d.ts +1 -0
  76. package/workflows/container-contents/index.js +1 -0
  77. package/workflows/container-contents/index.js.map +1 -1
  78. package/workflows/container-contents/tombstones/documentTombstoneEvidence.d.ts +42 -0
  79. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +41 -17
  80. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  81. package/workflows/documents/create/createAdoption.js +2 -50
  82. package/workflows/documents/create/createAdoption.js.map +1 -1
  83. package/workflows/documents/create/createResponse.js +12 -1
  84. package/workflows/documents/create/createResponse.js.map +1 -1
  85. package/workflows/documents/create/createSubmission.js +14 -0
  86. package/workflows/documents/create/createSubmission.js.map +1 -0
  87. package/workflows/documents/create/index.d.ts +3 -14
  88. package/workflows/documents/create/index.js +76 -67
  89. package/workflows/documents/create/index.js.map +1 -1
  90. package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +16 -15
  91. package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -1
  92. package/workflows/documents/purge/absentDocumentPurge.d.ts +3 -0
  93. package/workflows/documents/purge/absentDocumentPurge.js +23 -0
  94. package/workflows/documents/purge/absentDocumentPurge.js.map +1 -0
  95. package/workflows/documents/purge/index.d.ts +1 -0
  96. package/workflows/documents/purge/index.js +1 -0
  97. package/workflows/documents/purge/index.js.map +1 -1
  98. package/workflows/documents/remote/remoteDocumentService.d.ts +2 -2
  99. package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"documentTombstoneEvidence.js","sourceRoot":"","sources":["documentTombstoneEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,6BAA6B,GAE9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE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AK,IAAI,EAAE;YACxB,OAAO,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE,2BAA2B,CAAC,EAAE,CAAC;gBACnE,MAAM,KAAK,GAAG,IAAI,EAAE,CAAC;gBACrB,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;gBAC5B,IAAI,CAAC,KAAK;oBAAE,MAAM;gBAClB,MAAM,CAAC,UAAU,EAAE,KAAK,CAAC,GAAG,KAAK,CAAC;gBAClC,MAAM,IAAI,GAAG,MAAM,cAAc,CAAC,UAAU,CAAC,CAAC;gBAC9C,IAAI,IAAI,KAAK,IAAI;oBAAE,QAAQ,CAAC,KAAK,CAAC,GAAG,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YACpE,CAAC;QACH,CAAC,CAAC;QACF,MAAM,OAAO,CAAC,GAAG,CACf,KAAK,CAAC,IAAI,CACR,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,8BAA8B,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,EACnE,MAAM,CACP,CACF,CAAC;QACF,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { DocumentPurgeCheckpoint } from \"../../../data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport { reportKeyingVerificationErrorInCauseChain } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { PrincipalPolicyOperation } from \"../../principals/principalPolicyService\";\nimport type {\n ContainerDocumentTombstone,\n ContainerDocumentTombstoneVerdict,\n ContainerDocumentTombstoneVerifier,\n} from \"../documentDiscovery/documentDiscoveryTypes\";\nimport { documentHeadMatchesOrganization } from \"../documentDiscovery/documentHeadScope\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport interface VerifiedDocumentHeadLinkSet {\n readonly organizationId: string | null;\n readonly accessEpoch: number;\n /** Present for a signed head; a terminal purge has no live access state. */\n readonly accessStateHash?: string;\n readonly linkedContainerIds: ReadonlyArray<string>;\n}\n\n/**\n * The document's verified head link set, or `null` when no verified head is\n * available: the projection could not be fetched (the requester may no\n * longer read the document, or it was purged) or failed verification.\n */\nexport type DocumentHeadLinkSetLoader = (\n documentId: string,\n expectedManifestHash?: string,\n) => Promise<VerifiedDocumentHeadLinkSet | \"not-found\" | null>;\n\n/** The highest access epoch local state records for the document. */\nexport type LocalDocumentAccessEpochLoader = (\n documentId: string,\n) => Promise<number>;\n\nexport interface DocumentHeadLinkSetLoaderDeps {\n readonly assertDocumentWriterProjectionConsistent: typeof assertDocumentWriterProjectionConsistent;\n readonly loadDocumentPurgeCheckpoint: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<DocumentPurgeCheckpoint | null>;\n}\n\nexport const HEAD_LINK_SET_LOAD_CONCURRENCY = 4;\n/**\n * Head loads per settle. Tombstones beyond it stay unverified and are held\n * for a later, backed-off retry, so a bulk move out of a folder does not cost\n * every device an unbounded burst of fetches before the watermark advances.\n */\nexport const HEAD_LINK_SET_LOADS_PER_RUN = 32;\n\nasync function verifiedHeadLinkSet(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps,\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n policyOperation: PrincipalPolicyOperation | undefined,\n): Promise<VerifiedDocumentHeadLinkSet> {\n const verified: { value?: VerifiedDocumentHeadLinkSet } = {};\n await deps.assertDocumentWriterProjectionConsistent(projection, {\n // Only the link set is read; a bundle wrapped to superseded KEK targets\n // still carries the signed head.\n allowStaleContentKeyBundle: true,\n execSql: runtime.infra.execSql,\n onVerifiedAuthorization: (authorization) => {\n const head = authorization.documentManifestByHash.get(\n projection.documentManifest.manifestHash,\n );\n if (head && head.state.documentId === documentId) {\n verified.value = {\n organizationId: head.state.organizationId,\n accessEpoch: head.state.epoch,\n accessStateHash: head.manifestHash,\n linkedContainerIds: uniqueSortedStrings(\n head.state.linkedContainerIds,\n ),\n };\n }\n },\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: policyOperation,\n }),\n });\n if (!verified.value) {\n throw new Error(\"Tombstone evidence lacks a verified document head\");\n }\n return verified.value;\n}\n\nasync function reportUnavailableHead(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n error: unknown,\n): Promise<void> {\n const integrityFailure = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: \"document.tombstone-evidence\",\n },\n );\n try {\n if (\n !integrityFailure &&\n error instanceof ProjectionDependencyUnavailableError\n ) {\n // A policy can advance without changing this document's hash. Drop its\n // cached evidence so the held head can recover on the next run.\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is awaiting current policy history`,\n );\n return;\n }\n runtime.util.logError?.(\n \"Container contents: tombstone evidence is unavailable\",\n error,\n );\n } catch {\n // A host logger that throws must not fail the discovery pass.\n }\n}\n\n/** Only a typed 404 proves absence; any other failure leaves the head unavailable. */\nfunction failedHeadVerdict(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n failure: {\n readonly code?: string | undefined;\n readonly status?: number | null | undefined;\n },\n): \"not-found\" | null {\n if (failure.status === 404 && failure.code === DOCUMENT_NOT_FOUND_ERROR_CODE)\n return \"not-found\";\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is unavailable (${failure.status ?? \"offline\"})`,\n );\n return null;\n}\n\n/** `policyOperation` lets one discovery pass share a directory discovery. */\nexport function createDocumentHeadLinkSetLoader(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps = {\n assertDocumentWriterProjectionConsistent,\n loadDocumentPurgeCheckpoint: (execSql, documentId) =>\n new KeyingCheckpointRepository(execSql).loadDocumentPurgeCheckpoint(\n documentId,\n ),\n },\n policyOperation?: PrincipalPolicyOperation,\n): DocumentHeadLinkSetLoader {\n return async (documentId, expectedManifestHash) => {\n try {\n // A verified purge proof is terminal signed evidence that the document\n // links nothing any more.\n if (\n await deps.loadDocumentPurgeCheckpoint(\n runtime.infra.execSql,\n documentId,\n )\n ) {\n return {\n organizationId: null,\n accessEpoch: Number.MAX_SAFE_INTEGER,\n linkedContainerIds: [],\n };\n }\n // Tombstones require a fresh head. Listings can reuse a matching cached\n // projection, whose signature and local checkpoint are still verified.\n if (!expectedManifestHash)\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n let result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n if (\n expectedManifestHash &&\n result.ok &&\n result.data.documentManifest.manifestHash !== expectedManifestHash\n ) {\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n }\n if (!result.ok) return failedHeadVerdict(runtime, documentId, result);\n return await verifiedHeadLinkSet(\n runtime,\n deps,\n documentId,\n result.data,\n policyOperation,\n );\n } catch (error) {\n // Any failure leaves the tombstone unverified (held and retried); a\n // thrown error here must not fail the whole discovery pass.\n await reportUnavailableHead(runtime, documentId, error);\n return null;\n }\n };\n}\n\nfunction judgeTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstone>,\n head: VerifiedDocumentHeadLinkSet | null,\n): ContainerDocumentTombstoneVerdict[] {\n return tombstones.map((tombstone): ContainerDocumentTombstoneVerdict => {\n if (head === null) {\n return { kind: \"unverified\", tombstone };\n }\n if (head.linkedContainerIds.includes(tombstone.containerId)) {\n return {\n kind: \"refuted\",\n linkedContainerIds: head.linkedContainerIds,\n tombstone,\n };\n }\n return {\n kind: \"verified\",\n tombstone: {\n ...tombstone,\n accessEpoch: head.accessEpoch,\n linkedContainerIds: head.linkedContainerIds,\n },\n };\n });\n}\n\n/**\n * Judge listing tombstones against each document's verified head link set,\n * fetched once per document with bounded concurrency and a per-run cap. A\n * head whose epoch is below local document state is no evidence: it may be a\n * lagging replica or a replay, and applying it could delete rows a newer\n * listing or settled move wrote.\n */\nexport function createContainerDocumentTombstoneVerifier(\n organizationId: string | undefined,\n loadDocumentHeadLinkSet: DocumentHeadLinkSetLoader,\n loadLocalDocumentAccessEpoch: LocalDocumentAccessEpochLoader,\n): ContainerDocumentTombstoneVerifier {\n return async (tombstones) => {\n const byDocumentId = new Map<string, ContainerDocumentTombstone[]>();\n for (const tombstone of tombstones) {\n const group = byDocumentId.get(tombstone.documentId) ?? [];\n group.push(tombstone);\n byDocumentId.set(tombstone.documentId, group);\n }\n const groups = [...byDocumentId.entries()];\n const verdicts: ContainerDocumentTombstoneVerdict[][] = groups.map(\n ([, group], index): ContainerDocumentTombstoneVerdict[] =>\n index < HEAD_LINK_SET_LOADS_PER_RUN\n ? judgeTombstones(group, null)\n : group.map((tombstone) => ({ kind: \"deferred\", tombstone })),\n );\n // A missing, foreign, or older-than-local head is no evidence.\n const evidentialHead = async (documentId: string) => {\n const head = await loadDocumentHeadLinkSet(documentId);\n if (head === null || head === \"not-found\") return null;\n if (!documentHeadMatchesOrganization(head, organizationId)) return null;\n // A local-state read that fails is treated like an unavailable head:\n // the tombstones stay held rather than failing the discovery pass.\n const localEpoch = await loadLocalDocumentAccessEpoch(documentId).catch(\n () => Number.MAX_SAFE_INTEGER,\n );\n return head.accessEpoch < localEpoch ? null : head;\n };\n let next = 0;\n const worker = async () => {\n while (next < Math.min(groups.length, HEAD_LINK_SET_LOADS_PER_RUN)) {\n const index = next++;\n const entry = groups[index];\n if (!entry) break;\n const [documentId, group] = entry;\n const head = await evidentialHead(documentId);\n if (head !== null) verdicts[index] = judgeTombstones(group, head);\n }\n };\n await Promise.all(\n Array.from(\n { length: Math.min(HEAD_LINK_SET_LOAD_CONCURRENCY, groups.length) },\n worker,\n ),\n );\n return verdicts.flat();\n };\n}\n"]}
1
+ {"version":3,"file":"documentTombstoneEvidence.js","sourceRoot":"","sources":["documentTombstoneEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,6BAA6B,GAE9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,0BAA0B,EAC1B,wCAAwC,GACzC,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,EAAE,2BAA2B,EAAE,MAAM,4CAA4C,CAAC;AACzF,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAE7G,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAClG,OAAO,EAAE,yCAAyC,EAAE,MAAM,wCAAwC,CAAC;AAQnG,OAAO,EAAE,+BAA+B,EAAE,MAAM,wCAAwC,CAAC;AAsCzF,MAAM,CAAC,MAAM,8BAA8B,GAAG,CAAC,CAAC;AAChD;;;;GAIG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,EAAE,CAAC;AAE9C,KAAK,UAAU,mBAAmB,CAChC,OAAyC,EACzC,IAAmC,EACnC,UAAkB,EAClB,UAA4C,EAC5C,eAAqD,EACrD,YAA2B;IAE3B,MAAM,QAAQ,GAA4C,EAAE,CAAC;IAC7D,MAAM,IAAI,CAAC,wCAAwC,CAAC,UAAU,EAAE;QAC9D,wEAAwE;QACxE,i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C;AACJ,CAAC","sourcesContent":["import {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n assertDocumentCreateSigner,\n assertDocumentWriterProjectionConsistent,\n} from \"../../../data/documents/shared/projection\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport { checkWithHeldBundleRecovery } from \"../../../data/keyingProjectionVerification\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { DocumentPurgeCheckpoint } from \"../../../data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport { reportKeyingVerificationErrorInCauseChain } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { PrincipalPolicyOperation } from \"../../principals/principalPolicyService\";\nimport type {\n ContainerDocumentTombstone,\n ContainerDocumentTombstoneVerdict,\n ContainerDocumentTombstoneVerifier,\n} from \"../documentDiscovery/documentDiscoveryTypes\";\nimport { documentHeadMatchesOrganization } from \"../documentDiscovery/documentHeadScope\";\nimport type {\n ContainerContentsStoreWorkflowRuntime,\n ContainerContentsWorkflowRuntime,\n} from \"../runtime\";\n\nexport interface VerifiedDocumentHeadLinkSet {\n readonly organizationId: string | null;\n readonly accessEpoch: number;\n /** Present for a signed head; a terminal purge has no live access state. */\n readonly accessStateHash?: string;\n readonly linkedContainerIds: ReadonlyArray<string>;\n}\n\n/**\n * The document's verified head link set, or `null` when no verified head is\n * available: the projection could not be fetched (the requester may no\n * longer read the document, or it was purged) or failed verification.\n */\nexport type DocumentHeadLinkSetLoader = (\n documentId: string,\n expectedManifestHash?: string,\n expectedSignerUserId?: string,\n) => Promise<VerifiedDocumentHeadLinkSet | \"not-found\" | null>;\n\n/** The highest access epoch local state records for the document. */\nexport type LocalDocumentAccessEpochLoader = (\n documentId: string,\n) => Promise<number>;\n\nexport interface DocumentHeadLinkSetLoaderDeps {\n readonly assertDocumentWriterProjectionConsistent: typeof assertDocumentWriterProjectionConsistent;\n readonly loadDocumentPurgeCheckpoint: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<DocumentPurgeCheckpoint | null>;\n}\n\nexport const HEAD_LINK_SET_LOAD_CONCURRENCY = 4;\n/**\n * Head loads per settle. Tombstones beyond it stay unverified and are held\n * for a later, backed-off retry, so a bulk move out of a folder does not cost\n * every device an unbounded burst of fetches before the watermark advances.\n */\nexport const HEAD_LINK_SET_LOADS_PER_RUN = 32;\n\nasync function verifiedHeadLinkSet(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps,\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n policyOperation: PrincipalPolicyOperation | undefined,\n stillCurrent: () => boolean,\n): Promise<VerifiedDocumentHeadLinkSet> {\n const verified: { value?: VerifiedDocumentHeadLinkSet } = {};\n await deps.assertDocumentWriterProjectionConsistent(projection, {\n // Only the link set is read; a bundle wrapped to superseded KEK targets\n // still carries the signed head.\n allowStaleContentKeyBundle: true,\n stillCurrent,\n execSql: runtime.infra.execSql,\n onVerifiedAuthorization: (authorization) => {\n const head = authorization.documentManifestByHash.get(\n projection.documentManifest.manifestHash,\n );\n if (head && head.state.documentId === documentId) {\n verified.value = {\n organizationId: head.state.organizationId,\n accessEpoch: head.state.epoch,\n accessStateHash: head.manifestHash,\n linkedContainerIds: uniqueSortedStrings(\n head.state.linkedContainerIds,\n ),\n };\n }\n },\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: policyOperation,\n }),\n });\n if (!verified.value) {\n throw new Error(\"Tombstone evidence lacks a verified document head\");\n }\n return verified.value;\n}\n\nasync function reportUnavailableHead(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n error: unknown,\n): Promise<void> {\n const integrityFailure = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: \"document.tombstone-evidence\",\n },\n );\n try {\n if (\n !integrityFailure &&\n error instanceof ProjectionDependencyUnavailableError\n ) {\n // A policy can advance without changing this document's hash. Drop its\n // cached evidence so the held head can recover on the next run.\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is awaiting current policy history`,\n );\n return;\n }\n runtime.util.logError?.(\n \"Container contents: tombstone evidence is unavailable\",\n error,\n );\n } catch {\n // A host logger that throws must not fail the discovery pass.\n }\n}\n\n/** Only a typed 404 proves absence; any other failure leaves the head unavailable. */\nfunction failedHeadVerdict(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n failure: {\n readonly code?: string | undefined;\n readonly status?: number | null | undefined;\n },\n): \"not-found\" | null {\n if (failure.status === 404 && failure.code === DOCUMENT_NOT_FOUND_ERROR_CODE)\n return \"not-found\";\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is unavailable (${failure.status ?? \"offline\"})`,\n );\n return null;\n}\n\nasync function fetchDocumentHead(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n expectedManifestHash: string | undefined,\n assertCurrent: () => void,\n requestGuard: (() => boolean) | undefined,\n) {\n // Tombstones require a fresh head. Listings can reuse a matching cached\n // projection, whose signature and local checkpoint are still verified.\n if (!expectedManifestHash)\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n let result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false, stillCurrent: requestGuard },\n );\n assertCurrent();\n if (\n expectedManifestHash &&\n result.ok &&\n result.data.documentManifest.manifestHash !== expectedManifestHash\n ) {\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false, stillCurrent: requestGuard },\n );\n }\n assertCurrent();\n return result;\n}\n\n/** `policyOperation` lets one discovery pass share a directory discovery. */\nexport function createDocumentHeadLinkSetLoader(\n runtime: ContainerContentsWorkflowRuntime &\n Pick<ContainerContentsStoreWorkflowRuntime, \"liveHydrationStatus\">,\n deps: DocumentHeadLinkSetLoaderDeps = {\n assertDocumentWriterProjectionConsistent,\n loadDocumentPurgeCheckpoint: (execSql, documentId) =>\n new KeyingCheckpointRepository(execSql).loadDocumentPurgeCheckpoint(\n documentId,\n ),\n },\n policyOperation?: PrincipalPolicyOperation,\n): DocumentHeadLinkSetLoader {\n const stillCurrent = () => runtime.liveHydrationStatus?.() !== \"retired\";\n function assertCurrent() {\n if (!stillCurrent()) throw new Error(\"Document head lookup scope changed.\");\n }\n return async (documentId, expectedManifestHash, expectedSignerUserId) => {\n try {\n // A verified purge proof is terminal signed evidence that the document\n // links nothing any more.\n assertCurrent();\n const purge = await deps.loadDocumentPurgeCheckpoint(\n runtime.infra.execSql,\n documentId,\n );\n assertCurrent();\n if (purge) {\n return {\n organizationId: null,\n accessEpoch: Number.MAX_SAFE_INTEGER,\n linkedContainerIds: [],\n };\n }\n const result = await fetchDocumentHead(\n runtime,\n documentId,\n expectedManifestHash,\n assertCurrent,\n expectedSignerUserId ? stillCurrent : undefined,\n );\n if (!result.ok) return failedHeadVerdict(runtime, documentId, result);\n const projection = result.data;\n if (expectedSignerUserId) {\n await checkWithHeldBundleRecovery(\n { execSql: runtime.infra.execSql, projection, stillCurrent },\n async () =>\n assertDocumentCreateSigner(\n { documentId, expectedSignerUserId },\n projection,\n ),\n );\n }\n assertCurrent();\n const head = await verifiedHeadLinkSet(\n runtime,\n deps,\n documentId,\n result.data,\n policyOperation,\n stillCurrent,\n );\n assertCurrent();\n return head;\n } catch (error) {\n // Any failure leaves the tombstone unverified (held and retried); a\n // thrown error here must not fail the whole discovery pass.\n if (stillCurrent())\n await reportUnavailableHead(runtime, documentId, error);\n return null;\n }\n };\n}\n\nfunction judgeTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstone>,\n head: VerifiedDocumentHeadLinkSet | null,\n): ContainerDocumentTombstoneVerdict[] {\n return tombstones.map((tombstone): ContainerDocumentTombstoneVerdict => {\n if (head === null) {\n return { kind: \"unverified\", tombstone };\n }\n if (head.linkedContainerIds.includes(tombstone.containerId)) {\n return {\n kind: \"refuted\",\n linkedContainerIds: head.linkedContainerIds,\n tombstone,\n };\n }\n return {\n kind: \"verified\",\n tombstone: {\n ...tombstone,\n accessEpoch: head.accessEpoch,\n linkedContainerIds: head.linkedContainerIds,\n },\n };\n });\n}\n\n/**\n * Judge listing tombstones against each document's verified head link set,\n * fetched once per document with bounded concurrency and a per-run cap. A\n * head whose epoch is below local document state is no evidence: it may be a\n * lagging replica or a replay, and applying it could delete rows a newer\n * listing or settled move wrote.\n */\nexport function createContainerDocumentTombstoneVerifier(\n organizationId: string | undefined,\n loadDocumentHeadLinkSet: DocumentHeadLinkSetLoader,\n loadLocalDocumentAccessEpoch: LocalDocumentAccessEpochLoader,\n): ContainerDocumentTombstoneVerifier {\n return async (tombstones) => {\n const byDocumentId = new Map<string, ContainerDocumentTombstone[]>();\n for (const tombstone of tombstones) {\n const group = byDocumentId.get(tombstone.documentId) ?? [];\n group.push(tombstone);\n byDocumentId.set(tombstone.documentId, group);\n }\n const groups = [...byDocumentId.entries()];\n const verdicts: ContainerDocumentTombstoneVerdict[][] = groups.map(\n ([, group], index): ContainerDocumentTombstoneVerdict[] =>\n index < HEAD_LINK_SET_LOADS_PER_RUN\n ? judgeTombstones(group, null)\n : group.map((tombstone) => ({ kind: \"deferred\", tombstone })),\n );\n // A missing, foreign, or older-than-local head is no evidence.\n const evidentialHead = async (documentId: string) => {\n const head = await loadDocumentHeadLinkSet(documentId);\n if (head === null || head === \"not-found\") return null;\n if (!documentHeadMatchesOrganization(head, organizationId)) return null;\n // A local-state read that fails is treated like an unavailable head:\n // the tombstones stay held rather than failing the discovery pass.\n const localEpoch = await loadLocalDocumentAccessEpoch(documentId).catch(\n () => Number.MAX_SAFE_INTEGER,\n );\n return head.accessEpoch < localEpoch ? null : head;\n };\n let next = 0;\n const worker = async () => {\n while (next < Math.min(groups.length, HEAD_LINK_SET_LOADS_PER_RUN)) {\n const index = next++;\n const entry = groups[index];\n if (!entry) break;\n const [documentId, group] = entry;\n const head = await evidentialHead(documentId);\n if (head !== null) verdicts[index] = judgeTombstones(group, head);\n }\n };\n await Promise.all(\n Array.from(\n { length: Math.min(HEAD_LINK_SET_LOAD_CONCURRENCY, groups.length) },\n worker,\n ),\n );\n return verdicts.flat();\n };\n}\n"]}
@@ -1,55 +1,7 @@
1
- import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
- import { assertDocumentWriterProjectionConsistent, readLinkedContainerIdsFromDocumentManifest, unwrapDocumentContentKeyFromWriterProjection, } from "../../../data/documents/shared/projection/index.js";
1
+ import { assertDocumentCreateSigner, assertDocumentWriterProjectionConsistent, readLinkedContainerIdsFromDocumentManifest, unwrapDocumentContentKeyFromWriterProjection, } from "../../../data/documents/shared/projection/index.js";
3
2
  import { projectionVerificationOptions } from "../../../data/documents/shared/projection/projectionVerificationOptions.js";
4
3
  import { persistedDocumentCreateStateFromWriterProjection } from "../../../data/documents/shared/responses.js";
5
4
  import { checkWithHeldBundleRecovery } from "../../../data/keyingProjectionVerification/index.js";
6
- import { readAccessEvent, readAccessManifest, } from "../../../data/keyingProjectionVerification/readers.js";
7
- /**
8
- * A retry after a lost create response can only recover the local user's own
9
- * create: the server serves whatever document holds the stable id we minted,
10
- * and an honest server only ever committed ours under it. A create event signed
11
- * by anyone else is a foreign document colliding on that id (a member with
12
- * write access on the same container, or a dishonest server), which must not be
13
- * adopted as if it were the pending local write.
14
- *
15
- * The create event is located by walking the served head's predecessor chain,
16
- * not by scanning the history for any parentless manifest: the history is
17
- * server-supplied, so a dishonest server could splice in a genesis this user
18
- * signed for a different document. Every manifest on the chain must also name
19
- * the requested document.
20
- */
21
- function assertCreateEventSignedLocally(input, writerProjection) {
22
- const label = "Document create conflict";
23
- const historyByHash = new Map(writerProjection.documentManifestHistory.map((bundle) => [
24
- bundle.manifestHash,
25
- bundle,
26
- ]));
27
- const visited = new Set();
28
- let bundle = writerProjection.documentManifest;
29
- for (;;) {
30
- const manifest = readAccessManifest(bundle.manifest, `${label} manifest`);
31
- if (manifest.objectKind !== "document" ||
32
- manifest.objectId !== input.documentId) {
33
- throw new KeyingVerificationError("object_mismatch", `${label} manifest chain names another document`);
34
- }
35
- if (manifest.previousManifestHash === null) {
36
- const createEvent = readAccessEvent(bundle.event.event, `${label} create event`);
37
- if (createEvent.signerUserId !== input.expectedSignerUserId) {
38
- throw new KeyingVerificationError("signer_mismatch", `${label} create event was signed by another user`);
39
- }
40
- return;
41
- }
42
- if (visited.has(bundle.manifestHash)) {
43
- throw new KeyingVerificationError("invalid_shape", `${label} manifest history is cyclic`);
44
- }
45
- visited.add(bundle.manifestHash);
46
- const previous = historyByHash.get(manifest.previousManifestHash);
47
- if (!previous) {
48
- throw new KeyingVerificationError("invalid_shape", `${label} does not expose its create event`);
49
- }
50
- bundle = previous;
51
- }
52
- }
53
5
  function assertExpectedAdoptionScope(input, writerProjection) {
54
6
  const linkedContainerIds = readLinkedContainerIdsFromDocumentManifest(writerProjection);
55
7
  const expectedPath = writerProjection.authorizingContainerPaths.find((projection) => projection.containerId === input.expectedContainerId &&
@@ -74,7 +26,7 @@ export async function adoptExistingRemoteDocument(input) {
74
26
  stillCurrent: input.stillCurrent,
75
27
  }, async () => {
76
28
  assertExpectedAdoptionScope(input, writerProjection);
77
- assertCreateEventSignedLocally(input, writerProjection);
29
+ assertDocumentCreateSigner(input, writerProjection);
78
30
  });
79
31
  const verifiedByHash = new Map();
80
32
  const principalPolicyCache = new Map();
@@ -1 +1 @@
1
- {"version":3,"file":"createAdoption.js","sourceRoot":"","sources":["createAdoption.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;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AAU,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"]}
1
+ {"version":3,"file":"createAdoption.js","sourceRoot":"","sources":["createAdoption.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,0BAA0B,EAC1B,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;AAK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AG,MAAM,wCAAwC,CAC5D,gBAAgB,EAChB;QACE,OAAO,EAAE,KAAK,CAAC,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 type {\n VerifiedContainerAccessManifest,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n assertDocumentCreateSigner,\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 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\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 assertDocumentCreateSigner(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"]}
@@ -5,6 +5,14 @@ import { nullOnProjectionVerificationCancellation } from "../../../data/keyingPr
5
5
  import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
6
6
  import { adoptExistingRemoteDocument } from "./createAdoption.js";
7
7
  import { documentWriterProjectionFromCreateResponse } from "./createProjection.js";
8
+ /** A strict importer can only proceed after its exact birth update is acknowledged. */
9
+ export function assertRequiredSeedAcknowledged(request, created) {
10
+ if (!request.requireSeededCreate)
11
+ return;
12
+ const accepted = created?.response?.initialSync?.acceptedOutgoingUpdateIds;
13
+ if (!request.seedUpdate || !accepted?.includes(request.seedUpdate.id))
14
+ throw new Error("The server did not acknowledge the initial document content.");
15
+ }
8
16
  /** A matched acknowledgement remains committed if authorization evidence races. */
9
17
  export async function acknowledgeRemoteDocumentCreate(input) {
10
18
  const { materializedPlan, response } = input;
@@ -33,13 +41,16 @@ export async function acknowledgeRemoteDocumentCreate(input) {
33
41
  // A principal pin can advance while POST is in flight. Recover the already
34
42
  // committed document from fresh evidence, without submitting another create.
35
43
  // The adoption path still verifies its author, scope, chain and key binding.
36
- return nullOnProjectionVerificationCancellation(() => adoptExistingRemoteDocument({
44
+ const recovered = await nullOnProjectionVerificationCancellation(() => adoptExistingRemoteDocument({
37
45
  ...input,
38
46
  documentId: response.id,
39
47
  expectedContainerId: input.containerProjection.containerId,
40
48
  expectedOrganizationId: input.containerProjection.organizationId,
41
49
  expectedSignerUserId: input.author.signerUserId,
42
50
  }));
51
+ return recovered && response.initialSync
52
+ ? { ...recovered, response }
53
+ : recovered;
43
54
  }
44
55
  input.apiClient.primeDocumentWriterProjection(response.id, writerProjection);
45
56
  return {
@@ -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,YAAY,EAAE,QAAQ,CAAC,YAAY;QACnC,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,IAAI,EAAE,gBAAgB,CAAC,IAAI;QAC3B,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC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CreateResponse,\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"]}
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;AAGhF,uFAAuF;AACvF,MAAM,UAAU,8BAA8B,CAC5C,OAAkC,EAClC,OAA0C;IAE1C,IAAI,CAAC,OAAO,CAAC,mBAAmB;QAAE,OAAO;IACzC,MAAM,QAAQ,GAAG,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,yBAAyB,CAA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QAC7E,MAAM,SAAS,GAAG,MAAM,wCAAwC,CAAC,GAAG,EAAE,CACpE,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;QACF,OAAO,SAAS,IAAI,QAAQ,CAAC,WAAW;YACtC,CAAC,CAAC,EAAE,GAAG,SAAS,EAAE,QAAQ,EAAE;YAC5B,CAAC,CAAC,SAAS,CAAC;IAChB,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\";\nimport type { DocumentSubmissionRequest } from \"./remoteDocumentCreateRequest\";\n\n/** A strict importer can only proceed after its exact birth update is acknowledged. */\nexport function assertRequiredSeedAcknowledged(\n request: DocumentSubmissionRequest,\n created: CreateRemoteDocumentResult | null,\n) {\n if (!request.requireSeededCreate) return;\n const accepted = created?.response?.initialSync?.acceptedOutgoingUpdateIds;\n if (!request.seedUpdate || !accepted?.includes(request.seedUpdate.id))\n throw new Error(\n \"The server did not acknowledge the initial document content.\",\n );\n}\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 const recovered = await 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 return recovered && response.initialSync\n ? { ...recovered, response }\n : recovered;\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"]}
@@ -0,0 +1,14 @@
1
+ import { DOCUMENT_SYNC_ERROR_CODES, } from "../../../internal/validators/response/index.js";
2
+ export function isStaleDocumentCreateTargetConflict(submission) {
3
+ return (!submission.ok &&
4
+ submission.status === 409 &&
5
+ submission.code === DOCUMENT_SYNC_ERROR_CODES.stateStale);
6
+ }
7
+ export async function submitDocumentCreate(apiClient, request, expectedOrganizationId, stillCurrent) {
8
+ return apiClient.createDocumentResult(request, {
9
+ expectedPaymentRequiredOrganizationId: expectedOrganizationId,
10
+ ...(stillCurrent ? { stillCurrent } : {}),
11
+ reportErrors: false,
12
+ });
13
+ }
14
+ //# sourceMappingURL=createSubmission.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createSubmission.js","sourceRoot":"","sources":["createSubmission.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,GAE1B,MAAM,gCAAgC,CAAC;AAgBxC,MAAM,UAAU,mCAAmC,CACjD,UAAoC;IAEpC,OAAO,CACL,CAAC,UAAU,CAAC,EAAE;QACd,UAAU,CAAC,MAAM,KAAK,GAAG;QACzB,UAAU,CAAC,IAAI,KAAK,yBAAyB,CAAC,UAAU,CACzD,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,SAA4B,EAC5B,OAA8B,EAC9B,sBAA8B,EAC9B,YAAyC;IAEzC,OAAO,SAAS,CAAC,oBAAoB,CAAC,OAAO,EAAE;QAC7C,qCAAqC,EAAE,sBAAsB;QAC7D,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACzC,YAAY,EAAE,KAAK;KACpB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentCreateRequest } from \"@tearleads/validators/request\";\nimport {\n DOCUMENT_SYNC_ERROR_CODES,\n type DocumentCreateResponse,\n} from \"@tearleads/validators/response\";\nimport type { DocumentCreateApi } from \"../../../data/documents/shared/types\";\n\nexport type DocumentCreateSubmission =\n | {\n readonly data: DocumentCreateResponse;\n readonly ok: true;\n }\n | {\n readonly code?: string | undefined;\n readonly message: string;\n readonly ok: false;\n readonly report?: (() => void) | undefined;\n readonly status: number | null;\n };\n\nexport function isStaleDocumentCreateTargetConflict(\n submission: DocumentCreateSubmission,\n): boolean {\n return (\n !submission.ok &&\n submission.status === 409 &&\n submission.code === DOCUMENT_SYNC_ERROR_CODES.stateStale\n );\n}\n\nexport async function submitDocumentCreate(\n apiClient: DocumentCreateApi,\n request: DocumentCreateRequest,\n expectedOrganizationId: string,\n stillCurrent: (() => boolean) | undefined,\n): Promise<DocumentCreateSubmission> {\n return apiClient.createDocumentResult(request, {\n expectedPaymentRequiredOrganizationId: expectedOrganizationId,\n ...(stillCurrent ? { stillCurrent } : {}),\n reportErrors: false,\n });\n}\n"]}
@@ -1,9 +1,9 @@
1
- import { type ContainerWriterProjectionResponse, type DocumentCreateResponse } from "../../../internal/validators/response/index.js";
1
+ import type { ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
2
2
  import type { ProjectionVerificationOptions } from "../../../data/documents/shared/projection/projectionVerificationOptions.js";
3
3
  import type { CreateRemoteDocumentResult, DocumentCreateAuthor, MaterializedDocumentCreatePlan } from "../../../data/documents/shared/types.js";
4
4
  import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
5
5
  import type { RemoteDocumentCollaborators } from "../remote/remoteDocumentCollaborators.js";
6
- import type { CreateRemoteDocumentRequest } from "./remoteDocumentCreateRequest.js";
6
+ import type { DocumentSubmissionRequest } from "./remoteDocumentCreateRequest.js";
7
7
  export declare function buildMaterializedDocumentCreatePlan(input: {
8
8
  author: DocumentCreateAuthor;
9
9
  containerProjection: ContainerWriterProjectionResponse;
@@ -19,15 +19,4 @@ export declare function buildMaterializedDocumentCreatePlan(input: {
19
19
  } & ProjectionVerificationOptions): Promise<MaterializedDocumentCreatePlan>;
20
20
  export { documentWriterProjectionFromCreateResponse } from "./createProjection.js";
21
21
  /** Throws when the collaborators carry no encapsulation secret key. */
22
- export declare function createRemoteDocument(remote: RemoteDocumentCollaborators, request: CreateRemoteDocumentRequest): Promise<CreateRemoteDocumentResult | null>;
23
- type DocumentCreateSubmission = {
24
- readonly data: DocumentCreateResponse;
25
- readonly ok: true;
26
- } | {
27
- readonly code?: string | undefined;
28
- readonly message: string;
29
- readonly ok: false;
30
- readonly report?: (() => void) | undefined;
31
- readonly status: number | null;
32
- };
33
- export declare function isStaleDocumentCreateTargetConflict(submission: DocumentCreateSubmission): boolean;
22
+ export declare function createRemoteDocument(remote: RemoteDocumentCollaborators, request: DocumentSubmissionRequest): Promise<CreateRemoteDocumentResult | null>;
@@ -1,4 +1,3 @@
1
- import { DOCUMENT_SYNC_ERROR_CODES, } from "../../../internal/validators/response/index.js";
2
1
  import { assertContainerAuthorAccess } from "../../../data/containers/shared/authorAccess.js";
3
2
  import { buildDocumentCreatePlan } from "../../../data/documents/shared/events.js";
4
3
  import { wrapDocumentContentKeyForCreate } from "../../../data/documents/shared/projection/index.js";
@@ -12,7 +11,8 @@ import { buildDocumentCreateSeedRequest, documentCreateSeed, documentCreateSeedF
12
11
  import { isDocumentManifestAlreadyExistsConflict } from "../syncFailures/syncFailureClassification.js";
13
12
  import { adoptExistingRemoteDocument } from "./createAdoption.js";
14
13
  import { fetchContainerWriterProjectionForCreate } from "./createProjectionFetch.js";
15
- import { acknowledgeRemoteDocumentCreate } from "./createResponse.js";
14
+ import { acknowledgeRemoteDocumentCreate, assertRequiredSeedAcknowledged, } from "./createResponse.js";
15
+ import { isStaleDocumentCreateTargetConflict, submitDocumentCreate, } from "./createSubmission.js";
16
16
  export async function buildMaterializedDocumentCreatePlan(input) {
17
17
  const contentKey = input.contentKey ?? crypto.getRandomValues(new Uint8Array(32));
18
18
  if (contentKey.byteLength !== 32) {
@@ -134,6 +134,8 @@ async function buildMaterializedDocumentCreatePlanWithFreshProjection(input) {
134
134
  async function submitPlannedDocumentCreateRequest(input, createPlan) {
135
135
  const request = createPlan.materializedPlan.plan.request;
136
136
  const organizationId = createPlan.containerProjection.organizationId;
137
+ const canSubmit = () => input.stillCurrent?.() !== false &&
138
+ !isRemoteDocumentCreatePlanBlocked(input, createPlan);
137
139
  const seed = input.seedUpdate
138
140
  ? await buildDocumentCreateSeedRequest({
139
141
  author: input.author,
@@ -143,18 +145,25 @@ async function submitPlannedDocumentCreateRequest(input, createPlan) {
143
145
  })
144
146
  : null;
145
147
  if (seed && documentCreateSeedFits(request, seed)) {
146
- if (input.stillCurrent?.() === false)
148
+ if (!canSubmit())
147
149
  return null;
148
- const seeded = await submitDocumentCreate(input.apiClient, { ...request, initialSync: documentCreateSeed(seed) }, organizationId);
149
- if (seeded.ok ||
150
+ const seeded = await submitDocumentCreate(input.apiClient, { ...request, initialSync: documentCreateSeed(seed) }, organizationId, canSubmit);
151
+ if (input.requireSeededCreate ||
152
+ seeded.ok ||
150
153
  isDocumentManifestAlreadyExistsConflict(seeded) ||
151
154
  isStaleDocumentCreateTargetConflict(seeded)) {
152
155
  return seeded;
153
156
  }
154
157
  }
155
- if (input.stillCurrent?.() === false)
158
+ if (!canSubmit())
156
159
  return null;
157
- return submitDocumentCreate(input.apiClient, request, organizationId);
160
+ if (input.requireSeededCreate)
161
+ return {
162
+ ok: false,
163
+ status: null,
164
+ message: "The initial document content must fit in one seeded create.",
165
+ };
166
+ return submitDocumentCreate(input.apiClient, request, organizationId, canSubmit);
158
167
  }
159
168
  function isRemoteDocumentCreatePlanBlocked(input, createPlan) {
160
169
  const organizationId = createPlan.containerProjection.organizationId;
@@ -192,43 +201,43 @@ async function submitPlannedDocumentCreate(input, resolveProjectionUserKey) {
192
201
  let submission = await submitPlannedDocumentCreateRequest(input, createPlan);
193
202
  if (!submission)
194
203
  return null;
195
- if (isStaleDocumentCreateTargetConflict(submission)) {
196
- if (input.stillCurrent?.() === false) {
197
- return { createPlan, submission };
198
- }
199
- input.apiClient.evictContainerWriterProjection(input.containerId);
200
- const firstPlan = createPlan.materializedPlan;
201
- const refreshedPlan = await buildMaterializedDocumentCreatePlanWithFreshProjection({
202
- apiClient: input.apiClient,
203
- author: input.author,
204
- containerId: input.containerId,
205
- contentKey: firstPlan.contentKey,
206
- contentKeyEpoch: firstPlan.plan.request.contentKeyBundle.contentKeyEpoch,
207
- documentId: firstPlan.plan.documentId,
208
- eventId: firstPlan.plan.event.eventId,
209
- execSql: input.execSql,
210
- expectedOrganizationId: input.expectedOrganizationId,
211
- knownContainerKeks: input.knownContainerKeks,
212
- onTerminalSubmitFailure: input.onTerminalSubmitFailure,
213
- resolveProjectionUserKey,
214
- signedAt: firstPlan.plan.event.signedAt,
215
- targetSecretKey: input.targetSecretKey,
216
- warmReferencedPrincipalPolicies,
217
- ...verificationOptions,
218
- });
219
- if (!refreshedPlan) {
220
- return null;
221
- }
222
- if (isRemoteDocumentCreatePlanBlocked(input, refreshedPlan))
223
- return null;
224
- createPlan = refreshedPlan;
225
- if (input.stillCurrent?.() === false)
226
- return null;
227
- submission = await submitPlannedDocumentCreateRequest(input, createPlan);
228
- if (!submission)
229
- return null;
204
+ if (!isStaleDocumentCreateTargetConflict(submission))
205
+ return { createPlan, submission };
206
+ if (input.stillCurrent?.() === false) {
207
+ return { createPlan, submission };
230
208
  }
231
- return { createPlan, submission };
209
+ input.apiClient.evictContainerWriterProjection(input.containerId);
210
+ const firstPlan = createPlan.materializedPlan;
211
+ const refreshedPlan = await buildMaterializedDocumentCreatePlanWithFreshProjection({
212
+ apiClient: input.apiClient,
213
+ author: input.author,
214
+ containerId: input.containerId,
215
+ contentKey: firstPlan.contentKey,
216
+ contentKeyEpoch: firstPlan.plan.request.contentKeyBundle.contentKeyEpoch,
217
+ documentId: firstPlan.plan.documentId,
218
+ eventId: firstPlan.plan.event.eventId,
219
+ execSql: input.execSql,
220
+ expectedOrganizationId: input.expectedOrganizationId,
221
+ knownContainerKeks: input.knownContainerKeks,
222
+ onTerminalSubmitFailure: input.onTerminalSubmitFailure,
223
+ resolveProjectionUserKey,
224
+ signedAt: firstPlan.plan.event.signedAt,
225
+ targetSecretKey: input.targetSecretKey,
226
+ warmReferencedPrincipalPolicies,
227
+ ...verificationOptions,
228
+ });
229
+ if (!refreshedPlan) {
230
+ return null;
231
+ }
232
+ if (isRemoteDocumentCreatePlanBlocked(input, refreshedPlan))
233
+ return null;
234
+ createPlan = refreshedPlan;
235
+ if (input.stillCurrent?.() === false)
236
+ return null;
237
+ submission = await submitPlannedDocumentCreateRequest(input, createPlan);
238
+ if (!submission)
239
+ return null;
240
+ return { createPlan, submission, retriedStaleTarget: true };
232
241
  }
233
242
  /**
234
243
  * Signs the deferred first update against the plan the server just accepted,
@@ -248,6 +257,22 @@ async function withDeferredSeed(created, createPlan, input) {
248
257
  ? { ...created, deferredSeed }
249
258
  : created;
250
259
  }
260
+ async function settleSubmittedCreate(input, createPlan, resolveProjectionUserKey, response, retriedStaleTarget) {
261
+ const created = await acknowledgeRemoteDocumentCreate({
262
+ ...input,
263
+ ...createPlan,
264
+ resolveProjectionUserKey,
265
+ response,
266
+ });
267
+ assertRequiredSeedAcknowledged(input, created);
268
+ if (input.stillCurrent?.() === false)
269
+ return null;
270
+ if (created && retriedStaleTarget)
271
+ input.onRecoveredStaleTarget?.();
272
+ return created && input.deferredSeedUpdate
273
+ ? withDeferredSeed(created, createPlan, input)
274
+ : created;
275
+ }
251
276
  /** Throws when the collaborators carry no encapsulation secret key. */
252
277
  export async function createRemoteDocument(remote, request) {
253
278
  if (!remote.encapsulationSecretKey) {
@@ -272,24 +297,17 @@ export async function createRemoteDocument(remote, request) {
272
297
  const { createPlan, submission } = plannedSubmission;
273
298
  if (input.stillCurrent?.() === false)
274
299
  return null;
275
- if (submission.ok) {
276
- const created = await acknowledgeRemoteDocumentCreate({
277
- ...input,
278
- ...createPlan,
279
- resolveProjectionUserKey,
280
- response: submission.data,
281
- });
282
- return created && input.deferredSeedUpdate
283
- ? withDeferredSeed(created, createPlan, input)
284
- : created;
285
- }
300
+ if (submission.ok)
301
+ return settleSubmittedCreate(input, createPlan, resolveProjectionUserKey, submission.data, plannedSubmission.retriedStaleTarget);
286
302
  // A stable documentId means a retry after a lost create response re-submits
287
303
  // the same id; the server then reports the manifest already exists. That is
288
304
  // not a failure — the first attempt committed. Adopt the existing remote
289
305
  // document instead of leaking a duplicate. Requires the stable id we sent, so
290
306
  // we can fetch its projection back.
291
307
  const stableDocumentId = input.documentId;
292
- if (stableDocumentId && isDocumentManifestAlreadyExistsConflict(submission)) {
308
+ if (stableDocumentId &&
309
+ !input.requireSeededCreate &&
310
+ isDocumentManifestAlreadyExistsConflict(submission)) {
293
311
  if (input.stillCurrent?.() === false)
294
312
  return null;
295
313
  const adopted = await nullOnProjectionVerificationCancellation(() => adoptExistingRemoteDocument({
@@ -314,19 +332,10 @@ export async function createRemoteDocument(remote, request) {
314
332
  // error — the sync engine retries and adopts it on a later tick.
315
333
  return null;
316
334
  }
317
- submission.report?.();
335
+ // Create-only callers handle the refusal directly, including a verified purge.
336
+ if (!input.requireSeededCreate)
337
+ submission.report?.();
318
338
  await input.onTerminalSubmitFailure?.(submission);
319
339
  return null;
320
340
  }
321
- export function isStaleDocumentCreateTargetConflict(submission) {
322
- return (!submission.ok &&
323
- submission.status === 409 &&
324
- submission.code === DOCUMENT_SYNC_ERROR_CODES.stateStale);
325
- }
326
- async function submitDocumentCreate(apiClient, request, expectedOrganizationId) {
327
- return apiClient.createDocumentResult(request, {
328
- expectedPaymentRequiredOrganizationId: expectedOrganizationId,
329
- reportErrors: false,
330
- });
331
- }
332
341
  //# sourceMappingURL=index.js.map