@tearleads/client-sdk 0.1.57 → 0.1.59

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 (414) hide show
  1. package/Tearleads.d.ts +2 -2
  2. package/Tearleads.js +1 -1
  3. package/Tearleads.js.map +1 -1
  4. package/client/blobs.d.ts +1 -1
  5. package/client/blobs.js.map +1 -1
  6. package/client/deviceFirst.js.map +1 -1
  7. package/client/identity.js +1 -1
  8. package/client/identity.js.map +1 -1
  9. package/client/index.d.ts +1 -1
  10. package/client/index.js +1 -1
  11. package/client/index.js.map +1 -1
  12. package/client/organizations/organizationAccessRestoration.js.map +1 -1
  13. package/client/organizations/organizationDataUsage.js.map +1 -1
  14. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  15. package/client/organizations/organizationMetadataProfileSync.js +1 -1
  16. package/client/organizations/organizationMetadataProfileSync.js.map +1 -1
  17. package/client/organizations/organizationReadModels.js.map +1 -1
  18. package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
  19. package/client/rootContainerAdoption.js.map +1 -1
  20. package/client/securityIncidents.d.ts +1 -1
  21. package/client/securityIncidents.js.map +1 -1
  22. package/client/session/sessionLoginRefusal.js.map +1 -1
  23. package/client/session/sessionRootAuthority.js.map +1 -1
  24. package/client/session/sessionTypes.d.ts +1 -1
  25. package/client/session/sessionTypes.js.map +1 -1
  26. package/client/userIdentities.d.ts +1 -1
  27. package/client/userIdentities.js.map +1 -1
  28. package/client/workflowRuntime.d.ts +2 -2
  29. package/client/workflowRuntime.js.map +1 -1
  30. package/data/blobs/createBlobStore.d.ts +1 -1
  31. package/data/blobs/createBlobStore.js.map +1 -1
  32. package/data/blobs/encryptedBlobByteSource.js +1 -1
  33. package/data/blobs/encryptedBlobByteSource.js.map +1 -1
  34. package/data/blobs/encryptedBlobEnvelope.d.ts +1 -1
  35. package/data/blobs/encryptedBlobEnvelope.js +2 -2
  36. package/data/blobs/encryptedBlobEnvelope.js.map +1 -1
  37. package/data/blobs/encryptedBlobStore.d.ts +1 -1
  38. package/data/blobs/encryptedBlobStore.js +1 -1
  39. package/data/blobs/encryptedBlobStore.js.map +1 -1
  40. package/data/blobs/memoryBlobStore.d.ts +1 -1
  41. package/data/blobs/memoryBlobStore.js +1 -1
  42. package/data/blobs/memoryBlobStore.js.map +1 -1
  43. package/data/blobs/opfsBlobStore.d.ts +1 -1
  44. package/data/blobs/opfsBlobStore.js +1 -1
  45. package/data/blobs/opfsBlobStore.js.map +1 -1
  46. package/data/containers/containerMetadataDocument.js +1 -1
  47. package/data/containers/containerMetadataDocument.js.map +1 -1
  48. package/data/containers/shared/events.js +1 -1
  49. package/data/containers/shared/events.js.map +1 -1
  50. package/data/containers/shared/heldContainerHeads.js +1 -1
  51. package/data/containers/shared/heldContainerHeads.js.map +1 -1
  52. package/data/containers/shared/mutationAcknowledgement.js +1 -1
  53. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  54. package/data/containers/shared/principalPolicies.js +1 -1
  55. package/data/containers/shared/principalPolicies.js.map +1 -1
  56. package/data/containers/shared/readers.js +2 -2
  57. package/data/containers/shared/readers.js.map +1 -1
  58. package/data/documents/attachmentContentIdentity.js +1 -1
  59. package/data/documents/attachmentContentIdentity.js.map +1 -1
  60. package/data/documents/blob/shared/blobEnvelopeStream.js.map +1 -1
  61. package/data/documents/blob/shared/blobSourceSnapshot.d.ts +1 -1
  62. package/data/documents/blob/shared/blobSourceSnapshot.js.map +1 -1
  63. package/data/documents/blob/shared/chunkedBlobCrypto.js.map +1 -1
  64. package/data/documents/blob/shared/encryptedUploadParts.js.map +1 -1
  65. package/data/documents/blob/shared/events.js +1 -1
  66. package/data/documents/blob/shared/events.js.map +1 -1
  67. package/data/documents/blob/shared/types.d.ts +2 -2
  68. package/data/documents/blob/shared/types.js.map +1 -1
  69. package/data/documents/shared/containerKekPathHistory.js +1 -1
  70. package/data/documents/shared/containerKekPathHistory.js.map +1 -1
  71. package/data/documents/shared/containerKekPathVerification.d.ts +1 -1
  72. package/data/documents/shared/containerKekPathVerification.js +1 -1
  73. package/data/documents/shared/events.js +1 -1
  74. package/data/documents/shared/events.js.map +1 -1
  75. package/data/documents/shared/manifestBundleReaders.js +2 -2
  76. package/data/documents/shared/manifestBundleReaders.js.map +1 -1
  77. package/data/documents/shared/projection.d.ts +1 -1
  78. package/data/documents/shared/projection.js +2 -2
  79. package/data/documents/shared/projection.js.map +1 -1
  80. package/data/documents/shared/projectionContentKeys.d.ts +1 -1
  81. package/data/documents/shared/readers.js +3 -3
  82. package/data/documents/shared/readers.js.map +1 -1
  83. package/data/documents/shared/stableDocumentId.js +1 -1
  84. package/data/documents/shared/stableDocumentId.js.map +1 -1
  85. package/data/documents/shared/types.d.ts +1 -1
  86. package/data/documents/shared/types.js +1 -1
  87. package/data/{keyingCanonicalJson.js → keying/canonicalJson.js} +3 -3
  88. package/data/keying/canonicalJson.js.map +1 -0
  89. package/data/keyingProjectionVerification/bundleVerification.js +1 -1
  90. package/data/keyingProjectionVerification/bundleVerification.js.map +1 -1
  91. package/data/keyingProjectionVerification/containerAncestorCitations.js +1 -1
  92. package/data/keyingProjectionVerification/containerAncestorCitations.js.map +1 -1
  93. package/data/keyingProjectionVerification/containerManifestVerification.js +1 -1
  94. package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
  95. package/data/keyingProjectionVerification/documentManifestVerification.js +1 -1
  96. package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
  97. package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js +1 -1
  98. package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js.map +1 -1
  99. package/data/keyingProjectionVerification/error.js +1 -1
  100. package/data/keyingProjectionVerification/error.js.map +1 -1
  101. package/data/keyingProjectionVerification/index.d.ts +9 -0
  102. package/data/{keyingProjectionVerification.js → keyingProjectionVerification/index.js} +8 -8
  103. package/data/keyingProjectionVerification/index.js.map +1 -0
  104. package/data/keyingProjectionVerification/principalPolicyCache.js +1 -1
  105. package/data/keyingProjectionVerification/principalPolicyCache.js.map +1 -1
  106. package/data/keyingProjectionVerification/principalPolicyVerification.js +1 -1
  107. package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
  108. package/data/keyingProjectionVerification/readers.d.ts +1 -1
  109. package/data/keyingProjectionVerification/readers.js +3 -3
  110. package/data/keyingProjectionVerification/readers.js.map +1 -1
  111. package/data/keyingProjectionVerification/userKeyResolver.d.ts +1 -1
  112. package/data/keyingProjectionVerification/userKeyResolver.js.map +1 -1
  113. package/data/persistence/containers/containerPersistence.js +1 -1
  114. package/data/persistence/containers/containerPersistence.js.map +1 -1
  115. package/data/persistence/documents/documentDiscoveryCandidate.js +1 -1
  116. package/data/persistence/documents/documentDiscoveryCandidate.js.map +1 -1
  117. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +1 -1
  118. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  119. package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
  120. package/data/persistence/documents/internal/documentProjectionRows.js.map +1 -1
  121. package/data/persistence/documents/internal/documentRows.js +1 -1
  122. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  123. package/data/persistence/principalPolicyBundleIntegrity.js +1 -1
  124. package/data/persistence/principalPolicyBundleIntegrity.js.map +1 -1
  125. package/data/persistence/principalPolicyReferenceCheckpoint.js +1 -1
  126. package/data/persistence/principalPolicyReferenceCheckpoint.js.map +1 -1
  127. package/data/persistence/principalPolicyReferenceIndexPersistence.js +1 -1
  128. package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +1 -1
  129. package/data/persistence/principalPolicyReferencePersistence.js +1 -1
  130. package/data/persistence/principalPolicyReferencePersistence.js.map +1 -1
  131. package/data/persistence/securityIncidentPersistence.js.map +1 -1
  132. package/data/persistence/verifiedPrincipalPolicyBundle.js +1 -1
  133. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +1 -1
  134. package/data/persistence/verifiedPrincipalPolicyCurrent.js +1 -1
  135. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +1 -1
  136. package/data/principals/principalMutationJournal.js +1 -1
  137. package/data/principals/principalMutationJournal.js.map +1 -1
  138. package/data/{securityIncidents.d.ts → shared/securityIncidents.d.ts} +1 -1
  139. package/data/sqlite/documentRecordPersistence.js +1 -1
  140. package/data/sqlite/documentRecordPersistence.js.map +1 -1
  141. package/data/sync/crdtPeerSeed.d.ts +18 -0
  142. package/data/sync/originatedDocuments.d.ts +1 -1
  143. package/data/sync/originatedDocuments.js.map +1 -1
  144. package/data/sync/syncCoordinator.d.ts +1 -1
  145. package/data/sync/syncCoordinator.js.map +1 -1
  146. package/index.d.ts +4 -4
  147. package/index.js +2 -2
  148. package/index.js.map +1 -1
  149. package/package.json +1 -1
  150. package/stores/container-contents/backgroundHydration.js +1 -1
  151. package/stores/container-contents/backgroundHydration.js.map +1 -1
  152. package/stores/container-contents/containerContentsStore.d.ts +1 -1
  153. package/stores/container-contents/containerContentsStore.js.map +1 -1
  154. package/stores/container-contents/localRefresh.js +1 -1
  155. package/stores/container-contents/localRefresh.js.map +1 -1
  156. package/stores/container-contents/remoteContainerIngestion.js +1 -1
  157. package/stores/container-contents/remoteContainerIngestion.js.map +1 -1
  158. package/stores/container-contents/remoteWriteQueue.js +1 -1
  159. package/stores/container-contents/remoteWriteQueue.js.map +1 -1
  160. package/stores/container-contents/systemContainerHydration.js +1 -1
  161. package/stores/container-contents/systemContainerHydration.js.map +1 -1
  162. package/stores/container-contents/utils.js +1 -1
  163. package/stores/container-contents/utils.js.map +1 -1
  164. package/stores/documents/documentStore/attachmentIntents.js +1 -1
  165. package/stores/documents/documentStore/attachmentIntents.js.map +1 -1
  166. package/stores/documents/documentStore/attachmentSourceUpload.js.map +1 -1
  167. package/stores/documents/documentStore/attachmentStaging.js +1 -1
  168. package/stores/documents/documentStore/attachmentStaging.js.map +1 -1
  169. package/stores/documents/documentStore/attachmentUploadLane.js.map +1 -1
  170. package/stores/documents/documentStore/persistence.js +2 -2
  171. package/stores/documents/documentStore/persistence.js.map +1 -1
  172. package/stores/documents/documentStore/state.js +1 -1
  173. package/stores/documents/documentStore/state.js.map +1 -1
  174. package/stores/documents/documentStore/storedDocument.js +1 -1
  175. package/stores/documents/documentStore/storedDocument.js.map +1 -1
  176. package/stores/documents/documentStore/syncAttachments.js.map +1 -1
  177. package/stores/documents/documentStore.d.ts +1 -1
  178. package/stores/documents/documentStore.js.map +1 -1
  179. package/stores/documents/registry.d.ts +1 -1
  180. package/stores/documents/registry.js.map +1 -1
  181. package/stores/documents/types.d.ts +1 -1
  182. package/stores/documents/types.js.map +1 -1
  183. package/stores/local-projection/registry.d.ts +1 -1
  184. package/stores/local-projection/registry.js.map +1 -1
  185. package/sync/reconciliation/serviceTypes.d.ts +1 -1
  186. package/sync/reconciliation/serviceTypes.js.map +1 -1
  187. package/sync/reconciliation/triggers.d.ts +1 -1
  188. package/sync/reconciliation/triggers.js.map +1 -1
  189. package/workflows/blobs/attachmentBindingVerification.js +2 -2
  190. package/workflows/blobs/attachmentBindingVerification.js.map +1 -1
  191. package/workflows/blobs/blobChunkDecryption.js.map +1 -1
  192. package/workflows/blobs/decrypt.d.ts +1 -1
  193. package/workflows/blobs/decrypt.js +2 -2
  194. package/workflows/blobs/decrypt.js.map +1 -1
  195. package/workflows/blobs/detach.js +2 -2
  196. package/workflows/blobs/detach.js.map +1 -1
  197. package/workflows/blobs/hydrate.d.ts +3 -3
  198. package/workflows/blobs/hydrate.js +1 -1
  199. package/workflows/blobs/hydrate.js.map +1 -1
  200. package/workflows/blobs/hydrationResults.js.map +1 -1
  201. package/workflows/blobs/index.d.ts +2 -2
  202. package/workflows/blobs/index.js +1 -1
  203. package/workflows/blobs/index.js.map +1 -1
  204. package/workflows/blobs/multipartFirstParts.js.map +1 -1
  205. package/workflows/blobs/retainedAttachmentVerification.js +1 -1
  206. package/workflows/blobs/upload.js +3 -3
  207. package/workflows/blobs/upload.js.map +1 -1
  208. package/workflows/container-contents/container-state/createAdoption.js +1 -1
  209. package/workflows/container-contents/container-state/createAdoption.js.map +1 -1
  210. package/workflows/container-contents/container-state/createChild.js +1 -1
  211. package/workflows/container-contents/container-state/createChild.js.map +1 -1
  212. package/workflows/container-contents/container-state/createIntentSync.js +1 -1
  213. package/workflows/container-contents/container-state/createIntentSync.js.map +1 -1
  214. package/workflows/container-contents/container-state/groupGrantVerification.js +1 -1
  215. package/workflows/container-contents/container-state/moveIntentSync.js +1 -1
  216. package/workflows/container-contents/container-state/moveIntentSync.js.map +1 -1
  217. package/workflows/container-contents/container-state/purgeTreeScope.js +1 -1
  218. package/workflows/container-contents/container-state/purgeTreeScope.js.map +1 -1
  219. package/workflows/container-contents/container-state/share.js +1 -1
  220. package/workflows/container-contents/documentDiscoveryInputs.js +1 -1
  221. package/workflows/container-contents/documentDiscoveryInputs.js.map +1 -1
  222. package/workflows/container-contents/documentInfo.d.ts +1 -1
  223. package/workflows/container-contents/documentInfo.js.map +1 -1
  224. package/workflows/container-contents/documentLinks.d.ts +1 -1
  225. package/workflows/container-contents/documentLinks.js +1 -1
  226. package/workflows/container-contents/documentLinks.js.map +1 -1
  227. package/workflows/container-contents/documentMoveIntentSync.js +1 -1
  228. package/workflows/container-contents/documentMoveIntentSync.js.map +1 -1
  229. package/workflows/container-contents/documentPurge.d.ts +1 -1
  230. package/workflows/container-contents/documentPurge.js +1 -1
  231. package/workflows/container-contents/documentPurge.js.map +1 -1
  232. package/workflows/container-contents/documentQueries/rows.js +1 -1
  233. package/workflows/container-contents/documentQueries/rows.js.map +1 -1
  234. package/workflows/container-contents/metadata.d.ts +1 -1
  235. package/workflows/container-contents/metadataMutationPreparation.js +1 -1
  236. package/workflows/container-contents/metadataMutationPreparation.js.map +1 -1
  237. package/workflows/container-contents/metadataRemoteSync.d.ts +1 -1
  238. package/workflows/container-contents/metadataSyncErrors.js.map +1 -1
  239. package/workflows/container-contents/projectionKeys.d.ts +1 -1
  240. package/workflows/container-contents/syncLane.d.ts +1 -1
  241. package/workflows/container-contents/syncLane.js.map +1 -1
  242. package/workflows/containers/child/carriedDescendantRekeys.js +1 -1
  243. package/workflows/containers/child/create.d.ts +1 -1
  244. package/workflows/containers/child/create.js +2 -2
  245. package/workflows/containers/child/create.js.map +1 -1
  246. package/workflows/containers/child/createProjection.js +1 -1
  247. package/workflows/containers/child/createProjection.js.map +1 -1
  248. package/workflows/containers/child/createSubmission.d.ts +2 -2
  249. package/workflows/containers/child/createSubmission.js.map +1 -1
  250. package/workflows/containers/child/move.d.ts +2 -2
  251. package/workflows/containers/child/move.js +2 -2
  252. package/workflows/containers/child/move.js.map +1 -1
  253. package/workflows/containers/child/moveWraps.js +1 -1
  254. package/workflows/containers/child/mutationRequestCore.js +1 -1
  255. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  256. package/workflows/containers/child/mutationSubmit.js.map +1 -1
  257. package/workflows/containers/child/recite.js.map +1 -1
  258. package/workflows/containers/child/recitePlan.js +1 -1
  259. package/workflows/containers/child/recitePlan.js.map +1 -1
  260. package/workflows/containers/child/rekey.d.ts +1 -1
  261. package/workflows/containers/child/rekey.js +2 -2
  262. package/workflows/containers/child/rekey.js.map +1 -1
  263. package/workflows/containers/child/rekeyProjection.js +1 -1
  264. package/workflows/containers/child/rekeyProjection.js.map +1 -1
  265. package/workflows/containers/child/rekeyRemote.d.ts +2 -2
  266. package/workflows/containers/child/rekeyRemote.js.map +1 -1
  267. package/workflows/containers/child/revoke.d.ts +2 -2
  268. package/workflows/containers/child/revoke.js +2 -2
  269. package/workflows/containers/child/revoke.js.map +1 -1
  270. package/workflows/containers/child/rotationPrincipalPolicies.js +1 -1
  271. package/workflows/containers/child/runtimeCurrentGroupShare.js +1 -1
  272. package/workflows/containers/child/share.d.ts +2 -2
  273. package/workflows/containers/child/share.js +1 -1
  274. package/workflows/containers/child/share.js.map +1 -1
  275. package/workflows/containers/child/shareAncestorRepair.js.map +1 -1
  276. package/workflows/containers/child/shareMaterialization.d.ts +1 -1
  277. package/workflows/containers/child/sharePlanCore.d.ts +1 -1
  278. package/workflows/containers/child/sharePlanCore.js +1 -1
  279. package/workflows/containers/root/create.js +1 -1
  280. package/workflows/containers/root/create.js.map +1 -1
  281. package/workflows/containers/root/initialGroupPolicy.js +1 -1
  282. package/workflows/containers/root/initialGroupPolicy.js.map +1 -1
  283. package/workflows/documents/create.d.ts +1 -1
  284. package/workflows/documents/create.js +1 -1
  285. package/workflows/documents/documentMutationPreparation.js +1 -1
  286. package/workflows/documents/documentMutationPreparation.js.map +1 -1
  287. package/workflows/documents/historyContent.js +1 -1
  288. package/workflows/documents/historyContent.js.map +1 -1
  289. package/workflows/documents/linkSet.js +1 -1
  290. package/workflows/documents/linkSet.js.map +1 -1
  291. package/workflows/documents/linkSetAuthority.js +1 -1
  292. package/workflows/documents/linkSetBlobRewraps.js +2 -2
  293. package/workflows/documents/linkSetBlobRewraps.js.map +1 -1
  294. package/workflows/documents/linkSetRemote.d.ts +1 -1
  295. package/workflows/documents/linkSetRemote.js +1 -1
  296. package/workflows/documents/orphanBlobReclaims.js +1 -1
  297. package/workflows/documents/orphanBlobReclaims.js.map +1 -1
  298. package/workflows/documents/projectionKeys.d.ts +1 -1
  299. package/workflows/documents/purge.d.ts +1 -1
  300. package/workflows/documents/purge.js +2 -2
  301. package/workflows/documents/purge.js.map +1 -1
  302. package/workflows/documents/readOnlySync.d.ts +1 -1
  303. package/workflows/documents/readOnlySync.js +1 -1
  304. package/workflows/documents/readOnlySync.js.map +1 -1
  305. package/workflows/documents/sync.js +1 -1
  306. package/workflows/documents/syncContainerRekeyPreparation.js +1 -1
  307. package/workflows/documents/syncLane.d.ts +1 -1
  308. package/workflows/documents/syncLane.js.map +1 -1
  309. package/workflows/documents/syncPlanIdentity.js +1 -1
  310. package/workflows/documents/syncPlanIdentity.js.map +1 -1
  311. package/workflows/documents/syncRepairAccess.js +1 -1
  312. package/workflows/documents/syncSubmittedResult.js +1 -1
  313. package/workflows/organizations/authoredPrincipalPolicyWarmer.js +1 -1
  314. package/workflows/organizations/authoredPrincipalPolicyWarmer.js.map +1 -1
  315. package/workflows/organizations/containerGrantRevocation.d.ts +2 -2
  316. package/workflows/organizations/containerGrantRevocation.js.map +1 -1
  317. package/workflows/organizations/createCurrentOrganizationGroup.js.map +1 -1
  318. package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -1
  319. package/workflows/organizations/currentOrganizationMutationRetention.js +1 -1
  320. package/workflows/organizations/currentOrganizationMutationRetention.js.map +1 -1
  321. package/workflows/organizations/currentPolicyMutationAcknowledgement.js +1 -1
  322. package/workflows/organizations/currentPolicyMutationAcknowledgement.js.map +1 -1
  323. package/workflows/organizations/groupCreation.d.ts +1 -1
  324. package/workflows/organizations/groupCreation.js.map +1 -1
  325. package/workflows/organizations/groupMetadataAccess.d.ts +1 -1
  326. package/workflows/organizations/groupMetadataContainerAuthority.js.map +1 -1
  327. package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
  328. package/workflows/organizations/groupNameUniqueness.js.map +1 -1
  329. package/workflows/organizations/groupPolicyMutationAcknowledgement.js +1 -1
  330. package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
  331. package/workflows/organizations/groupPolicyRequests.js.map +1 -1
  332. package/workflows/organizations/index.d.ts +0 -1
  333. package/workflows/organizations/index.js +0 -1
  334. package/workflows/organizations/index.js.map +1 -1
  335. package/workflows/organizations/loadPolicyHistoryDetails.js.map +1 -1
  336. package/workflows/organizations/organizationGroupDirectory.js.map +1 -1
  337. package/workflows/organizations/organizationProfile.js +1 -1
  338. package/workflows/organizations/organizationProfile.js.map +1 -1
  339. package/workflows/organizations/policyHistoryCache.js.map +1 -1
  340. package/workflows/organizations/principalContainerRematerialization.js +1 -1
  341. package/workflows/organizations/principalContainerRematerializationPlanning.js.map +1 -1
  342. package/workflows/organizations/principalMutationJournalManagement.js +1 -1
  343. package/workflows/organizations/principalMutationJournalManagement.js.map +1 -1
  344. package/workflows/organizations/principalMutationReceipt.js +1 -1
  345. package/workflows/organizations/principalMutationReceipt.js.map +1 -1
  346. package/workflows/organizations/principalPolicy.d.ts +1 -1
  347. package/workflows/organizations/principalPolicy.js.map +1 -1
  348. package/workflows/organizations/principalPolicyReceiptArtifacts.js +1 -1
  349. package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +1 -1
  350. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +4 -24
  351. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +13 -133
  352. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -1
  353. package/workflows/organizations/rosterProfileContainer.js +1 -1
  354. package/workflows/organizations/rosterProfileContainer.js.map +1 -1
  355. package/workflows/organizations/runtimeCurrentGroupMutation.js +1 -1
  356. package/workflows/organizations/runtimeCurrentGroupMutation.js.map +1 -1
  357. package/workflows/principals/acknowledgedPrincipalCurrents.d.ts +33 -0
  358. package/workflows/principals/acknowledgedPrincipalCurrents.js +140 -0
  359. package/workflows/principals/acknowledgedPrincipalCurrents.js.map +1 -0
  360. package/workflows/{organizations → principals}/acknowledgedPrincipalPredecessor.d.ts +1 -1
  361. package/workflows/{organizations → principals}/acknowledgedPrincipalPredecessor.js +1 -1
  362. package/workflows/principals/acknowledgedPrincipalPredecessor.js.map +1 -0
  363. package/workflows/principals/index.d.ts +1 -0
  364. package/workflows/principals/index.js +1 -0
  365. package/workflows/principals/index.js.map +1 -1
  366. package/workflows/{organizations → principals}/initialPrincipalCurrentPublication.js +5 -7
  367. package/workflows/principals/initialPrincipalCurrentPublication.js.map +1 -0
  368. package/workflows/principals/policyCache.d.ts +1 -1
  369. package/workflows/principals/policyCache.js +2 -2
  370. package/workflows/principals/policyCache.js.map +1 -1
  371. package/workflows/principals/principalAcknowledgementChecks.d.ts +30 -0
  372. package/workflows/principals/principalAcknowledgementChecks.js +2 -0
  373. package/workflows/principals/principalAcknowledgementChecks.js.map +1 -0
  374. package/workflows/{organizations → principals}/principalCurrentPublicationSeal.js.map +1 -1
  375. package/workflows/{organizations → principals}/reconcileAcknowledgedPrincipalCurrent.js +2 -2
  376. package/workflows/principals/reconcileAcknowledgedPrincipalCurrent.js.map +1 -0
  377. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  378. package/workflows/principals/runtimePolicyWarmer.js +1 -1
  379. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
  380. package/workflows/registration/persistRegistrationBootstrap.js +1 -1
  381. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  382. package/workflows/runtimeInput.d.ts +3 -3
  383. package/workflows/runtimeInput.js.map +1 -1
  384. package/workflows/sync/index.d.ts +2 -1
  385. package/workflows/sync/index.js +2 -1
  386. package/workflows/sync/index.js.map +1 -1
  387. package/data/keyingCanonicalJson.js.map +0 -1
  388. package/data/keyingProjectionVerification.d.ts +0 -9
  389. package/data/keyingProjectionVerification.js.map +0 -1
  390. package/workflows/organizations/acknowledgedPrincipalPredecessor.js.map +0 -1
  391. package/workflows/organizations/initialPrincipalCurrentPublication.js.map +0 -1
  392. package/workflows/organizations/reconcileAcknowledgedPrincipalCurrent.js.map +0 -1
  393. /package/data/{blobContracts.d.ts → blobs/blobContracts.d.ts} +0 -0
  394. /package/data/{blobContracts.js → blobs/blobContracts.js} +0 -0
  395. /package/data/{blobContracts.js.map → blobs/blobContracts.js.map} +0 -0
  396. /package/data/{accessLevel.js → keying/accessLevel.js} +0 -0
  397. /package/data/{accessLevel.js.map → keying/accessLevel.js.map} +0 -0
  398. /package/data/{stableUuid.js → keying/stableUuid.js} +0 -0
  399. /package/data/{stableUuid.js.map → keying/stableUuid.js.map} +0 -0
  400. /package/data/{principalPolicyStates.js → principals/principalPolicyStates.js} +0 -0
  401. /package/data/{principalPolicyStates.js.map → principals/principalPolicyStates.js.map} +0 -0
  402. /package/data/{domainScope.d.ts → shared/domainScope.d.ts} +0 -0
  403. /package/data/{domainScope.js → shared/domainScope.js} +0 -0
  404. /package/data/{domainScope.js.map → shared/domainScope.js.map} +0 -0
  405. /package/data/{errorMessage.js → shared/errorMessage.js} +0 -0
  406. /package/data/{errorMessage.js.map → shared/errorMessage.js.map} +0 -0
  407. /package/data/{recordReaders.d.ts → shared/recordReaders.d.ts} +0 -0
  408. /package/data/{recordReaders.js → shared/recordReaders.js} +0 -0
  409. /package/data/{recordReaders.js.map → shared/recordReaders.js.map} +0 -0
  410. /package/data/{securityIncidents.js → shared/securityIncidents.js} +0 -0
  411. /package/data/{securityIncidents.js.map → shared/securityIncidents.js.map} +0 -0
  412. /package/data/{crdtPeerSeed.js → sync/crdtPeerSeed.js} +0 -0
  413. /package/data/{crdtPeerSeed.js.map → sync/crdtPeerSeed.js.map} +0 -0
  414. /package/workflows/{organizations → principals}/principalCurrentPublicationSeal.js +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"documentRows.js","sourceRoot":"","sources":["documentRows.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AACrE,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,qCAAqC,EAAE,MAAM,4CAA4C,CAAC;AAEnG,OAAO,EACL,kBAAkB,EAClB,sBAAsB,EACtB,SAAS,GACV,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAGlD,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EACL,yBAAyB,EACzB,iBAAiB,EACjB,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAElC,MAAM,UAAU,gBAAgB,CAAC,OAAe;IAC9C,OAAO;QACL,OAAO,EAAE,kBAAkB;QAC3B,OAAO;KACR,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,OAAgB,E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\"drizzle-orm\";\nimport { normalizeEffectiveAccessLevel } from \"../../../accessLevel\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../documents/documentConstants\";\nimport { deriveStoredDocumentTitle } from \"../../../documents/documentKinds\";\nimport { serializeDocumentSyncPullContinuation } from \"../../../documents/shared/pullContinuation\";\nimport type { DocumentScope } from \"../../../sqlite/documentPersistence\";\nimport {\n documentProjection,\n documentProjectionText,\n documents,\n} from \"../../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport { DOCUMENTS_APP_KIND } from \"./constants\";\nimport {\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n getProjectionUpdatedAt,\n} from \"./documentProjectionRows\";\n\nexport function getDocumentScope(localId: string): DocumentScope {\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId,\n };\n}\n\nexport async function hasDocumentRow(\n execSql: ExecSql,\n localId: string,\n): Promise<boolean> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nfunction toDocumentRecordRow(input: {\n document: StoredDocumentRecord;\n updatedAt: string;\n}) {\n const { document, updatedAt } = input;\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId: document.id,\n documentId: document.documentId,\n recoveryGeneration: document.recoveryGeneration ?? 0,\n recoveryDocumentId: document.documentId\n ? null\n : (document.recoveryDocumentId ?? null),\n snapshotEndVersion: document.snapshotEndVersion,\n accessEpoch: document.accessEpoch,\n accessStateHash: document.accessStateHash ?? null,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n document.effectiveAccessLevel,\n ),\n lastCommitLsn: document.lastCommitLsn ?? null,\n documentManifestBundle: document.documentManifestBundle ?? null,\n contentKeyBundle: document.contentKeyBundle ?? null,\n documentKekTargets: document.documentKekTargets ?? null,\n // Only touch the outgoing-delta marker when the caller manages it. Callers\n // that leave it undefined (e.g. discovery upserts, registration bootstrap)\n // must not clobber a marker a device-first deferRemoteSync write persisted.\n ...(document.pendingBaseVersion === undefined\n ? {}\n : { pendingBaseVersion: document.pendingBaseVersion }),\n ...(document.pullContinuation === undefined\n ? {}\n : {\n pullContinuation: serializeDocumentSyncPullContinuation(\n document.pullContinuation,\n ),\n }),\n updatedAt,\n };\n}\n\nasync function saveDocumentProjectionRows(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<void> {\n const { document, tx, updatedAt } = input;\n const projectionRow = {\n localId: document.id,\n documentId: document.documentId,\n containerId: document.containerId,\n documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,\n title: document.title ?? deriveStoredDocumentTitle(document.text),\n updatedAt,\n };\n await tx\n .insert(documentProjection)\n .values(projectionRow)\n .onConflictDoUpdate({\n target: documentProjection.localId,\n set: projectionRow,\n })\n .run();\n\n const projectionTextRow = {\n localId: document.id,\n text: document.text,\n };\n await tx\n .insert(documentProjectionText)\n .values(projectionTextRow)\n .onConflictDoUpdate({\n target: documentProjectionText.localId,\n set: projectionTextRow,\n })\n .run();\n}\n\nexport async function createDocumentRowsIfAbsent(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = toDocumentRecordRow({ document, updatedAt });\n const inserted = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoNothing({\n target: [documents.appKind, documents.localId],\n })\n .returning({ localId: documents.localId });\n if (inserted.length === 0) {\n return false;\n }\n\n await saveDocumentProjectionRows(input);\n return true;\n}\n\nexport async function saveDocumentRows(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = toDocumentRecordRow({ document, updatedAt });\n // The recovery-generation fence rides on the upsert: a stored row from a\n // newer recovery generation is left untouched and returns no row, so a\n // stale writer skips the projection writes without a separate read.\n const saved = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoUpdate({\n target: [documents.appKind, documents.localId],\n set: documentRow,\n setWhere: lte(\n documents.recoveryGeneration,\n documentRow.recoveryGeneration,\n ),\n })\n .returning({ localId: documents.localId });\n if (saved.length === 0) {\n return false;\n }\n await saveDocumentProjectionRows(input);\n return true;\n}\n\nfunction didStoredDocumentContentChange(\n existing: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n > | null,\n next: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n >,\n): boolean {\n return (\n existing === null ||\n existing.documentKind !== (next.documentKind ?? DEFAULT_DOCUMENT_KIND) ||\n existing.snapshotEndVersion !== next.snapshotEndVersion ||\n existing.text !== next.text ||\n existing.title !== (next.title ?? deriveStoredDocumentTitle(next.text))\n );\n}\n\nexport async function resolveDocumentSaveTimestamp(input: {\n document: StoredDocumentRecord;\n options?: { updatedAt?: string } | undefined;\n tx: ClientSQLiteTransactionScope;\n}): Promise<string> {\n const { document, options, tx } = input;\n if (options?.updatedAt) {\n return options.updatedAt;\n }\n\n // One read for the stored row and its projection; the projection columns\n // are not nullable, so they are null exactly when the projection is absent.\n const [existing] = await tx\n .select({\n snapshotEndVersion: documents.snapshotEndVersion,\n documentKind: documentProjection.documentKind,\n text: documentProjectionText.text,\n title: documentProjection.title,\n updatedAt: documentProjection.updatedAt,\n })\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, document.id),\n ),\n )\n .limit(1);\n const existingProjection =\n existing?.documentKind != null &&\n existing.title != null &&\n existing.updatedAt != null\n ? {\n documentKind: existing.documentKind,\n text: existing.text,\n title: existing.title,\n updatedAt: existing.updatedAt,\n }\n : undefined;\n const now = new Date().toISOString();\n return didStoredDocumentContentChange(\n existing\n ? {\n documentKind: getProjectionDocumentKind(existingProjection),\n snapshotEndVersion: existing.snapshotEndVersion,\n text: getProjectionText(existingProjection),\n title: getProjectionTitle(existingProjection),\n }\n : null,\n document,\n )\n ? now\n : getProjectionUpdatedAt(existingProjection) || now;\n}\n"]}
1
+ {"version":3,"file":"documentRows.js","sourceRoot":"","sources":["documentRows.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,qCAAqC,EAAE,MAAM,4CAA4C,CAAC;AACnG,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAE5E,OAAO,EACL,kBAAkB,EAClB,sBAAsB,EACtB,SAAS,GACV,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAGlD,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EACL,yBAAyB,EACzB,iBAAiB,EACjB,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAElC,MAAM,UAAU,gBAAgB,CAAC,OAAe;IAC9C,OAAO;QACL,OAAO,EAAE,kBAAkB;QAC3B,OAAO;KACR,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,OAAgB,EAChB,OAAe;IAEf,MAAM,EAAE,EAAE,EAAE,GA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\"../../../documents/documentConstants\";\nimport { deriveStoredDocumentTitle } from \"../../../documents/documentKinds\";\nimport { serializeDocumentSyncPullContinuation } from \"../../../documents/shared/pullContinuation\";\nimport { normalizeEffectiveAccessLevel } from \"../../../keying/accessLevel\";\nimport type { DocumentScope } from \"../../../sqlite/documentPersistence\";\nimport {\n documentProjection,\n documentProjectionText,\n documents,\n} from \"../../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport { DOCUMENTS_APP_KIND } from \"./constants\";\nimport {\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n getProjectionUpdatedAt,\n} from \"./documentProjectionRows\";\n\nexport function getDocumentScope(localId: string): DocumentScope {\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId,\n };\n}\n\nexport async function hasDocumentRow(\n execSql: ExecSql,\n localId: string,\n): Promise<boolean> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nfunction toDocumentRecordRow(input: {\n document: StoredDocumentRecord;\n updatedAt: string;\n}) {\n const { document, updatedAt } = input;\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId: document.id,\n documentId: document.documentId,\n recoveryGeneration: document.recoveryGeneration ?? 0,\n recoveryDocumentId: document.documentId\n ? null\n : (document.recoveryDocumentId ?? null),\n snapshotEndVersion: document.snapshotEndVersion,\n accessEpoch: document.accessEpoch,\n accessStateHash: document.accessStateHash ?? null,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n document.effectiveAccessLevel,\n ),\n lastCommitLsn: document.lastCommitLsn ?? null,\n documentManifestBundle: document.documentManifestBundle ?? null,\n contentKeyBundle: document.contentKeyBundle ?? null,\n documentKekTargets: document.documentKekTargets ?? null,\n // Only touch the outgoing-delta marker when the caller manages it. Callers\n // that leave it undefined (e.g. discovery upserts, registration bootstrap)\n // must not clobber a marker a device-first deferRemoteSync write persisted.\n ...(document.pendingBaseVersion === undefined\n ? {}\n : { pendingBaseVersion: document.pendingBaseVersion }),\n ...(document.pullContinuation === undefined\n ? {}\n : {\n pullContinuation: serializeDocumentSyncPullContinuation(\n document.pullContinuation,\n ),\n }),\n updatedAt,\n };\n}\n\nasync function saveDocumentProjectionRows(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<void> {\n const { document, tx, updatedAt } = input;\n const projectionRow = {\n localId: document.id,\n documentId: document.documentId,\n containerId: document.containerId,\n documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,\n title: document.title ?? deriveStoredDocumentTitle(document.text),\n updatedAt,\n };\n await tx\n .insert(documentProjection)\n .values(projectionRow)\n .onConflictDoUpdate({\n target: documentProjection.localId,\n set: projectionRow,\n })\n .run();\n\n const projectionTextRow = {\n localId: document.id,\n text: document.text,\n };\n await tx\n .insert(documentProjectionText)\n .values(projectionTextRow)\n .onConflictDoUpdate({\n target: documentProjectionText.localId,\n set: projectionTextRow,\n })\n .run();\n}\n\nexport async function createDocumentRowsIfAbsent(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = toDocumentRecordRow({ document, updatedAt });\n const inserted = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoNothing({\n target: [documents.appKind, documents.localId],\n })\n .returning({ localId: documents.localId });\n if (inserted.length === 0) {\n return false;\n }\n\n await saveDocumentProjectionRows(input);\n return true;\n}\n\nexport async function saveDocumentRows(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = toDocumentRecordRow({ document, updatedAt });\n // The recovery-generation fence rides on the upsert: a stored row from a\n // newer recovery generation is left untouched and returns no row, so a\n // stale writer skips the projection writes without a separate read.\n const saved = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoUpdate({\n target: [documents.appKind, documents.localId],\n set: documentRow,\n setWhere: lte(\n documents.recoveryGeneration,\n documentRow.recoveryGeneration,\n ),\n })\n .returning({ localId: documents.localId });\n if (saved.length === 0) {\n return false;\n }\n await saveDocumentProjectionRows(input);\n return true;\n}\n\nfunction didStoredDocumentContentChange(\n existing: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n > | null,\n next: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n >,\n): boolean {\n return (\n existing === null ||\n existing.documentKind !== (next.documentKind ?? DEFAULT_DOCUMENT_KIND) ||\n existing.snapshotEndVersion !== next.snapshotEndVersion ||\n existing.text !== next.text ||\n existing.title !== (next.title ?? deriveStoredDocumentTitle(next.text))\n );\n}\n\nexport async function resolveDocumentSaveTimestamp(input: {\n document: StoredDocumentRecord;\n options?: { updatedAt?: string } | undefined;\n tx: ClientSQLiteTransactionScope;\n}): Promise<string> {\n const { document, options, tx } = input;\n if (options?.updatedAt) {\n return options.updatedAt;\n }\n\n // One read for the stored row and its projection; the projection columns\n // are not nullable, so they are null exactly when the projection is absent.\n const [existing] = await tx\n .select({\n snapshotEndVersion: documents.snapshotEndVersion,\n documentKind: documentProjection.documentKind,\n text: documentProjectionText.text,\n title: documentProjection.title,\n updatedAt: documentProjection.updatedAt,\n })\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, document.id),\n ),\n )\n .limit(1);\n const existingProjection =\n existing?.documentKind != null &&\n existing.title != null &&\n existing.updatedAt != null\n ? {\n documentKind: existing.documentKind,\n text: existing.text,\n title: existing.title,\n updatedAt: existing.updatedAt,\n }\n : undefined;\n const now = new Date().toISOString();\n return didStoredDocumentContentChange(\n existing\n ? {\n documentKind: getProjectionDocumentKind(existingProjection),\n snapshotEndVersion: existing.snapshotEndVersion,\n text: getProjectionText(existingProjection),\n title: getProjectionTitle(existingProjection),\n }\n : null,\n document,\n )\n ? now\n : getProjectionUpdatedAt(existingProjection) || now;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { compareCanonicalStrings, KeyingVerificationError, normalizePrincipalContainerGrants, normalizePrincipalProjectionMembers, } from "../../internal/crypto/index.js";
2
2
  import { isPrincipalPolicyBundleResponse } from "../../internal/validators/response/index.js";
3
- import { canonicalKeyingJsonString } from "../keyingCanonicalJson.js";
3
+ import { canonicalKeyingJsonString } from "../keying/canonicalJson.js";
4
4
  import { storedPrincipalPolicyBundleFromJson, } from "./storedPrincipalPolicyBundle.js";
5
5
  function parseBundle(row) {
6
6
  const bundle = storedPrincipalPolicyBundleFromJson(row);
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyBundleIntegrity.js","sourceRoot":"","sources":["principalPolicyBundleIntegrity.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,GACpC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAEL,mCAAmC,GACpC,MAAM,+BAA+B,CAAC;AAEvC,SAAS,WAAW,CAClB,GAAoC;IAEpC,MAAM,MAAM,GAAG,mCAAmC,CAAC,GAAG,CAAC,CAAC;IACxD,IAAI,CAAC,+BAA+B,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7C,MAAM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C,IAAI,CAAC;QACH,IACE,SAAS,CAAC,eAAe,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;YAC/C,SAAS,CAAC,eAAe,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC,EACjD,CAAC;YACD,OAAO;QACT,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,2EAA2E;QAC3E,2EAA2E;IAC7E,CAAC;IACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,mFAAmF,CACpF,CAAC;AACJ,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { isPrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../keyingCanonicalJson\";\nimport {\n type StoredPrincipalPolicyBundleJson,\n storedPrincipalPolicyBundleFromJson,\n} from \"./storedPrincipalPolicyBundle\";\n\nfunction parseBundle(\n row: StoredPrincipalPolicyBundleJson,\n): PrincipalPolicyBundleResponse {\n const bundle = storedPrincipalPolicyBundleFromJson(row);\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new Error(\"Stored principal policy bundle is invalid\");\n }\n return bundle;\n}\n\nfunction canonical(value: unknown): string {\n return canonicalKeyingJsonString(\n value,\n \"principal policy bundle security content\",\n );\n}\n\nfunction withoutCreatedAt<T extends { readonly createdAt: string }>(\n value: T,\n): Omit<T, \"createdAt\"> {\n const { createdAt: _createdAt, ...content } = value;\n return content;\n}\n\nfunction securityContent(bundle: PrincipalPolicyBundleResponse) {\n return {\n currentMemberEnvelopes: {\n ...bundle.currentMemberEnvelopes,\n envelopes: [...bundle.currentMemberEnvelopes.envelopes].sort((a, b) =>\n compareCanonicalStrings(canonical(a), canonical(b)),\n ),\n },\n currentPayload: withoutCreatedAt(bundle.currentPayload),\n currentProjection: normalizePrincipalProjectionMembers(\n bundle.currentProjection,\n ),\n currentGrants: normalizePrincipalContainerGrants(bundle.currentGrants),\n currentState: withoutCreatedAt(bundle.currentState),\n previousStates: bundle.previousStates.map((entry) => ({\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n state: withoutCreatedAt(entry.state),\n })),\n };\n}\n\nexport function assertSameHeadPrincipalPolicyBundle(\n stored: StoredPrincipalPolicyBundleJson,\n incoming: StoredPrincipalPolicyBundleJson,\n): void {\n try {\n if (\n canonical(securityContent(parseBundle(stored))) ===\n canonical(securityContent(parseBundle(incoming)))\n ) {\n return;\n }\n } catch {\n // Invalid same-head cache content is also an integrity conflict: replacing\n // it would erase the only durable evidence that the head was inconsistent.\n }\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy bundle content conflicts with the cached bundle at the same head\",\n );\n}\n"]}
1
+ {"version":3,"file":"principalPolicyBundleIntegrity.js","sourceRoot":"","sources":["principalPolicyBundleIntegrity.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,GACpC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAEL,mCAAmC,GACpC,MAAM,+BAA+B,CAAC;AAEvC,SAAS,WAAW,CAClB,GAAoC;IAEpC,MAAM,MAAM,GAAG,mCAAmC,CAAC,GAAG,CAAC,CAAC;IACxD,IAAI,CAAC,+BAA+B,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7C,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,SAAS,CAAC,KAAc;IAC/B,OAAO,yBAAyB,CAC9B,KAAK,EACL,0CAA0C,CAC3C,CAAC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ACT,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,2EAA2E;QAC3E,2EAA2E;IAC7E,CAAC;IACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,mFAAmF,CACpF,CAAC;AACJ,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { isPrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../keying/canonicalJson\";\nimport {\n type StoredPrincipalPolicyBundleJson,\n storedPrincipalPolicyBundleFromJson,\n} from \"./storedPrincipalPolicyBundle\";\n\nfunction parseBundle(\n row: StoredPrincipalPolicyBundleJson,\n): PrincipalPolicyBundleResponse {\n const bundle = storedPrincipalPolicyBundleFromJson(row);\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new Error(\"Stored principal policy bundle is invalid\");\n }\n return bundle;\n}\n\nfunction canonical(value: unknown): string {\n return canonicalKeyingJsonString(\n value,\n \"principal policy bundle security content\",\n );\n}\n\nfunction withoutCreatedAt<T extends { readonly createdAt: string }>(\n value: T,\n): Omit<T, \"createdAt\"> {\n const { createdAt: _createdAt, ...content } = value;\n return content;\n}\n\nfunction securityContent(bundle: PrincipalPolicyBundleResponse) {\n return {\n currentMemberEnvelopes: {\n ...bundle.currentMemberEnvelopes,\n envelopes: [...bundle.currentMemberEnvelopes.envelopes].sort((a, b) =>\n compareCanonicalStrings(canonical(a), canonical(b)),\n ),\n },\n currentPayload: withoutCreatedAt(bundle.currentPayload),\n currentProjection: normalizePrincipalProjectionMembers(\n bundle.currentProjection,\n ),\n currentGrants: normalizePrincipalContainerGrants(bundle.currentGrants),\n currentState: withoutCreatedAt(bundle.currentState),\n previousStates: bundle.previousStates.map((entry) => ({\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n state: withoutCreatedAt(entry.state),\n })),\n };\n}\n\nexport function assertSameHeadPrincipalPolicyBundle(\n stored: StoredPrincipalPolicyBundleJson,\n incoming: StoredPrincipalPolicyBundleJson,\n): void {\n try {\n if (\n canonical(securityContent(parseBundle(stored))) ===\n canonical(securityContent(parseBundle(incoming)))\n ) {\n return;\n }\n } catch {\n // Invalid same-head cache content is also an integrity conflict: replacing\n // it would erase the only durable evidence that the head was inconsistent.\n }\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy bundle content conflicts with the cached bundle at the same head\",\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { KeyingVerificationError, } from "../../internal/crypto/index.js";
2
- import { principalPolicyBundleStates } from "../principalPolicyStates.js";
2
+ import { principalPolicyBundleStates } from "../principals/principalPolicyStates.js";
3
3
  import { assertPrincipalPolicyCheckpointShape } from "./keyingCheckpointPersistence.js";
4
4
  export function applyPrincipalPolicyReferenceCheckpoint(bundle, checkpoint) {
5
5
  if (!checkpoint) {
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyReferenceCheckpoint.js","sourceRoot":"","sources":["principalPolicyReferenceCheckpoint.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,oCAAoC,EAAE,MAAM,+BAA+B,CAAC;AAErF,MAAM,UAAU,uCAAuC,CACrD,MAAqC,EACrC,UAA4C;IAE5C,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,oCAAoC,CAAC,UAAU,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC;IACtE,IAAI,MAAM,CAAC,YAAY,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO,EAAE,CAAC;QACrD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,MAAM,CAAC,YAAY,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,EAAE,CAAC;QACvD,IAAI,MAAM,CAAC,YAAY,CAAC,SAAS,KAAK,UAAU,CAAC,SAAS,EAAE,CAAC;YAC3D,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,2DAA2D,CAC5D,CAAC;QACJ,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,MAAM,gBAAgB,GAAG,2BAA2B,CAAC,MAAM,CAAC,CAAC,MAAM,CACjE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,CAChD,CAAC;IACF,IAAI,gBAAgB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAClC,MAAM,IAAI,uBAAuB,CAC/B,mBAAmB,EACnB,6DAA6D,CAC9D,CAAC;IACJ,CAAC;IACD,IACE,gBAAgB,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,KAAK,UAAU,CAAC,SAAS,CAAC,EAC1E,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,4DAA4D,CAC7D,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyBundleStates } from \"../principalPolicyStates\";\nimport { assertPrincipalPolicyCheckpointShape } from \"./keyingCheckpointPersistence\";\n\nexport function applyPrincipalPolicyReferenceCheckpoint(\n bundle: PrincipalPolicyBundleResponse,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): PrincipalPolicyBundleResponse | null {\n if (!checkpoint) {\n return bundle;\n }\n assertPrincipalPolicyCheckpointShape(checkpoint, bundle.currentState);\n if (bundle.currentState.version < checkpoint.version) {\n return null;\n }\n if (bundle.currentState.version === checkpoint.version) {\n if (bundle.currentState.stateHash !== checkpoint.stateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy head conflicts with the local checkpoint\",\n );\n }\n return bundle;\n }\n const checkpointStates = principalPolicyBundleStates(bundle).filter(\n (state) => state.version === checkpoint.version,\n );\n if (checkpointStates.length === 0) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"principal policy chain does not extend the local checkpoint\",\n );\n }\n if (\n checkpointStates.some((state) => state.stateHash !== checkpoint.stateHash)\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy chain conflicts with the local checkpoint\",\n );\n }\n return bundle;\n}\n"]}
1
+ {"version":3,"file":"principalPolicyReferenceCheckpoint.js","sourceRoot":"","sources":["principalPolicyReferenceCheckpoint.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,2BAA2B,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,EAAE,oCAAoC,EAAE,MAAM,+BAA+B,CAAC;AAErF,MAAM,UAAU,uCAAuC,CACrD,MAAqC,EACrC,UAA4C;IAE5C,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,oCAAoC,CAAC,UAAU,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC;IACtE,IAAI,MAAM,CAAC,YAAY,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO,EAAE,CAAC;QACrD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,MAAM,CAAC,YAAY,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,EAAE,CAAC;QACvD,IAAI,MAAM,CAAC,YAAY,CAAC,SAAS,KAAK,UAAU,CAAC,SAAS,EAAE,CAAC;YAC3D,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,2DAA2D,CAC5D,CAAC;QACJ,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,MAAM,gBAAgB,GAAG,2BAA2B,CAAC,MAAM,CAAC,CAAC,MAAM,CACjE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,CAChD,CAAC;IACF,IAAI,gBAAgB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAClC,MAAM,IAAI,uBAAuB,CAC/B,mBAAmB,EACnB,6DAA6D,CAC9D,CAAC;IACJ,CAAC;IACD,IACE,gBAAgB,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,KAAK,UAAU,CAAC,SAAS,CAAC,EAC1E,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,4DAA4D,CAC7D,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyBundleStates } from \"../principals/principalPolicyStates\";\nimport { assertPrincipalPolicyCheckpointShape } from \"./keyingCheckpointPersistence\";\n\nexport function applyPrincipalPolicyReferenceCheckpoint(\n bundle: PrincipalPolicyBundleResponse,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): PrincipalPolicyBundleResponse | null {\n if (!checkpoint) {\n return bundle;\n }\n assertPrincipalPolicyCheckpointShape(checkpoint, bundle.currentState);\n if (bundle.currentState.version < checkpoint.version) {\n return null;\n }\n if (bundle.currentState.version === checkpoint.version) {\n if (bundle.currentState.stateHash !== checkpoint.stateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy head conflicts with the local checkpoint\",\n );\n }\n return bundle;\n }\n const checkpointStates = principalPolicyBundleStates(bundle).filter(\n (state) => state.version === checkpoint.version,\n );\n if (checkpointStates.length === 0) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"principal policy chain does not extend the local checkpoint\",\n );\n }\n if (\n checkpointStates.some((state) => state.stateHash !== checkpoint.stateHash)\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy chain conflicts with the local checkpoint\",\n );\n }\n return bundle;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
2
  import { and, eq, inArray, or } from "drizzle-orm";
3
- import { principalPolicyBundleStates } from "../principalPolicyStates.js";
3
+ import { principalPolicyBundleStates } from "../principals/principalPolicyStates.js";
4
4
  import { principalPolicyBundleReferences } from "../sqlite/schema.js";
5
5
  import { sqliteInsertBatchSize, sqliteRowsPerStatement, } from "../sqlite/sqliteBindBudget.js";
6
6
  const REFERENCE_INSERT_BATCH_SIZE = sqliteInsertBatchSize(principalPolicyBundleReferences);
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyReferenceIndexPersistence.js","sourceRoot":"","sources":["principalPolicyReferenceIndexPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,+BAA+B,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,4BAA4B,CAAC;AAgBpC,MAAM,2BAA2B,GAAG,qBAAqB,CACvD,+BAA+B,CAChC,CAAC;AACF,0EAA0E;AAC1E,MAAM,yBAAyB,GAAG,sBAAsB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAE/D,yEAAyE;AACzE,SAAS,eAAe,CACtB,MAAsC,EACtC,GAAgC;IAEhC,OAAO,CACL,MAAM,CAAC,OAAO,KAAK,GAAG,CAAC,OAAO;QAC9B,MAAM,CAAC,SAAS,KAAK,GAAG,CAAC,SAAS;QAClC,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C,SAAS;QAC1B,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,aAAa,EAAE,IAAI,CAAC,OAAO;QAC3B,eAAe,EAAE,IAAI,CAAC,SAAS;KAChC,CAAC,CAAC,CAAC;IACJ,MAAM,MAAM,GACV,IAAI,CAAC,MAAM,KAAK,CAAC;QACf,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,MAAM,oBAAoB,CAAC,EAAE,EAAE,IAAI,EAAE;YACnC,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;SAC3C,CAAC,CAAC;IACT,IAAI,OAAO,GAAmC,IAAI,CAAC;IACnD,IAAI,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC;IAC3B,KAAK,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;QAC1C,OAAO,GAAG,iBAAiB,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QACzC,IAAI,OAAO,EAAE,CAAC;YACZ,QAAQ,GAAG,KAAK,CAAC;YACjB,MAAM;QACR,CAAC;IACH,CAAC;IACD,IAAI,CAAC,OAAO,IAAI,YAAY,KAAK,CAAC,CAAC;QACjC,OAAO,GAAG,IAAI,uBAAuB,CACnC,iBAAiB,EACjB,gEAAgE,CACjE,CAAC;IACJ,MAAM,uBAAuB,CAAC,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,CAAC;IACnE,IAAI,OAAO;QAAE,MAAM,OAAO,CAAC;AAC7B,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { and, eq, inArray, or } from \"drizzle-orm\";\nimport { principalPolicyBundleStates } from \"../principalPolicyStates\";\nimport { principalPolicyBundleReferences } from \"../sqlite/schema\";\nimport {\n sqliteInsertBatchSize,\n sqliteRowsPerStatement,\n} from \"../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\n\ntype PrincipalPolicyReferenceRow =\n typeof principalPolicyBundleReferences.$inferInsert;\n\ntype StoredPrincipalPolicyReference = Pick<\n typeof principalPolicyBundleReferences.$inferSelect,\n | \"version\"\n | \"stateHash\"\n | \"keyEpoch\"\n | \"keyFingerprint\"\n | \"bundleVersion\"\n | \"bundleStateHash\"\n>;\n\nconst REFERENCE_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n principalPolicyBundleReferences,\n);\n// Principal type and id plus the bundle version and state hash bind once.\nconst REFERENCE_LOOKUP_VERSIONS = sqliteRowsPerStatement(1, 4);\n\n/** The exact six-field match; the lookup already fixes the principal. */\nfunction isSameReference(\n stored: StoredPrincipalPolicyReference,\n row: PrincipalPolicyReferenceRow,\n): boolean {\n return (\n stored.version === row.version &&\n stored.stateHash === row.stateHash &&\n stored.keyEpoch === row.keyEpoch &&\n stored.keyFingerprint === row.keyFingerprint\n );\n}\n\n/** The table's primary key within one principal. */\nfunction referenceKey(\n row: Pick<\n StoredPrincipalPolicyReference,\n \"version\" | \"stateHash\" | \"keyEpoch\" | \"keyFingerprint\" | \"bundleStateHash\"\n >,\n): string {\n return JSON.stringify([\n row.version,\n row.stateHash,\n row.keyEpoch,\n row.keyFingerprint,\n row.bundleStateHash,\n ]);\n}\n\n/** Rows either equivocation check can match, read before this bundle's writes. */\nasync function loadStoredReferences(\n tx: ClientSQLiteTransactionScope,\n head: PrincipalPolicyBundleResponse[\"currentState\"],\n versions: readonly number[],\n): Promise<StoredPrincipalPolicyReference[]> {\n const stored: StoredPrincipalPolicyReference[] = [];\n for (\n let index = 0;\n index < versions.length;\n index += REFERENCE_LOOKUP_VERSIONS\n ) {\n stored.push(\n ...(await tx\n .select({\n version: principalPolicyBundleReferences.version,\n stateHash: principalPolicyBundleReferences.stateHash,\n keyEpoch: principalPolicyBundleReferences.keyEpoch,\n keyFingerprint: principalPolicyBundleReferences.keyFingerprint,\n bundleVersion: principalPolicyBundleReferences.bundleVersion,\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(\n principalPolicyBundleReferences.principalType,\n head.principalType,\n ),\n eq(principalPolicyBundleReferences.principalId, head.principalId),\n inArray(\n principalPolicyBundleReferences.version,\n versions.slice(index, index + REFERENCE_LOOKUP_VERSIONS),\n ),\n or(\n eq(principalPolicyBundleReferences.bundleVersion, head.version),\n eq(\n principalPolicyBundleReferences.bundleStateHash,\n head.stateHash,\n ),\n ),\n ),\n )),\n );\n }\n return stored;\n}\n\n/**\n * Rows written earlier in the same bundle all carry its head, so neither\n * check can match them: each state's outcome depends only on stored rows.\n */\nfunction referenceConflict(\n row: PrincipalPolicyReferenceRow,\n stored: readonly StoredPrincipalPolicyReference[],\n): KeyingVerificationError | null {\n const sameReference = stored.filter((candidate) =>\n isSameReference(candidate, row),\n );\n if (\n sameReference.some(\n (candidate) =>\n candidate.bundleVersion === row.bundleVersion &&\n candidate.bundleStateHash !== row.bundleStateHash,\n )\n )\n return new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference has conflicting bundle heads at one version\",\n );\n const indexed = sameReference.find(\n (candidate) => candidate.bundleStateHash === row.bundleStateHash,\n );\n if (indexed && indexed.bundleVersion !== row.bundleVersion)\n return new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index conflicts with the bundle head\",\n );\n return null;\n}\n\nasync function insertMissingReferences(\n tx: ClientSQLiteTransactionScope,\n rows: readonly PrincipalPolicyReferenceRow[],\n stored: readonly StoredPrincipalPolicyReference[],\n): Promise<void> {\n const present = new Set(stored.map(referenceKey));\n const missing = new Map<string, PrincipalPolicyReferenceRow>();\n for (const row of rows) {\n const key = referenceKey(row);\n if (!present.has(key) && !missing.has(key)) missing.set(key, row);\n }\n const values = [...missing.values()];\n for (\n let index = 0;\n index < values.length;\n index += REFERENCE_INSERT_BATCH_SIZE\n ) {\n await tx\n .insert(principalPolicyBundleReferences)\n .values(values.slice(index, index + REFERENCE_INSERT_BATCH_SIZE))\n .onConflictDoNothing()\n .run();\n }\n}\n\n/**\n * Index every state of a verified bundle under its head. Fails in state order\n * with the per-state checks' errors, keeping the states indexed before the\n * first failure.\n */\nexport async function indexPrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const head = bundle.currentState;\n const states = principalPolicyBundleStates(bundle);\n const foreignIndex = states.findIndex(\n (state) =>\n state.principalType !== head.principalType ||\n state.principalId !== head.principalId,\n );\n const rows: PrincipalPolicyReferenceRow[] = (\n foreignIndex === -1 ? states : states.slice(0, foreignIndex)\n ).map((state) => ({\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n bundleVersion: head.version,\n bundleStateHash: head.stateHash,\n }));\n const stored =\n rows.length === 0\n ? []\n : await loadStoredReferences(tx, head, [\n ...new Set(rows.map((row) => row.version)),\n ]);\n let failure: KeyingVerificationError | null = null;\n let accepted = rows.length;\n for (const [index, row] of rows.entries()) {\n failure = referenceConflict(row, stored);\n if (failure) {\n accepted = index;\n break;\n }\n }\n if (!failure && foreignIndex !== -1)\n failure = new KeyingVerificationError(\n \"object_mismatch\",\n \"principal policy bundle reference belongs to another principal\",\n );\n await insertMissingReferences(tx, rows.slice(0, accepted), stored);\n if (failure) throw failure;\n}\n"]}
1
+ {"version":3,"file":"principalPolicyReferenceIndexPersistence.js","sourceRoot":"","sources":["principalPolicyReferenceIndexPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO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C,IAAI,OAAO,EAAE,CAAC;YACZ,QAAQ,GAAG,KAAK,CAAC;YACjB,MAAM;QACR,CAAC;IACH,CAAC;IACD,IAAI,CAAC,OAAO,IAAI,YAAY,KAAK,CAAC,CAAC;QACjC,OAAO,GAAG,IAAI,uBAAuB,CACnC,iBAAiB,EACjB,gEAAgE,CACjE,CAAC;IACJ,MAAM,uBAAuB,CAAC,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,CAAC;IACnE,IAAI,OAAO;QAAE,MAAM,OAAO,CAAC;AAC7B,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { and, eq, inArray, or } from \"drizzle-orm\";\nimport { principalPolicyBundleStates } from \"../principals/principalPolicyStates\";\nimport { principalPolicyBundleReferences } from \"../sqlite/schema\";\nimport {\n sqliteInsertBatchSize,\n sqliteRowsPerStatement,\n} from \"../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\n\ntype PrincipalPolicyReferenceRow =\n typeof principalPolicyBundleReferences.$inferInsert;\n\ntype StoredPrincipalPolicyReference = Pick<\n typeof principalPolicyBundleReferences.$inferSelect,\n | \"version\"\n | \"stateHash\"\n | \"keyEpoch\"\n | \"keyFingerprint\"\n | \"bundleVersion\"\n | \"bundleStateHash\"\n>;\n\nconst REFERENCE_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n principalPolicyBundleReferences,\n);\n// Principal type and id plus the bundle version and state hash bind once.\nconst REFERENCE_LOOKUP_VERSIONS = sqliteRowsPerStatement(1, 4);\n\n/** The exact six-field match; the lookup already fixes the principal. */\nfunction isSameReference(\n stored: StoredPrincipalPolicyReference,\n row: PrincipalPolicyReferenceRow,\n): boolean {\n return (\n stored.version === row.version &&\n stored.stateHash === row.stateHash &&\n stored.keyEpoch === row.keyEpoch &&\n stored.keyFingerprint === row.keyFingerprint\n );\n}\n\n/** The table's primary key within one principal. */\nfunction referenceKey(\n row: Pick<\n StoredPrincipalPolicyReference,\n \"version\" | \"stateHash\" | \"keyEpoch\" | \"keyFingerprint\" | \"bundleStateHash\"\n >,\n): string {\n return JSON.stringify([\n row.version,\n row.stateHash,\n row.keyEpoch,\n row.keyFingerprint,\n row.bundleStateHash,\n ]);\n}\n\n/** Rows either equivocation check can match, read before this bundle's writes. */\nasync function loadStoredReferences(\n tx: ClientSQLiteTransactionScope,\n head: PrincipalPolicyBundleResponse[\"currentState\"],\n versions: readonly number[],\n): Promise<StoredPrincipalPolicyReference[]> {\n const stored: StoredPrincipalPolicyReference[] = [];\n for (\n let index = 0;\n index < versions.length;\n index += REFERENCE_LOOKUP_VERSIONS\n ) {\n stored.push(\n ...(await tx\n .select({\n version: principalPolicyBundleReferences.version,\n stateHash: principalPolicyBundleReferences.stateHash,\n keyEpoch: principalPolicyBundleReferences.keyEpoch,\n keyFingerprint: principalPolicyBundleReferences.keyFingerprint,\n bundleVersion: principalPolicyBundleReferences.bundleVersion,\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(\n principalPolicyBundleReferences.principalType,\n head.principalType,\n ),\n eq(principalPolicyBundleReferences.principalId, head.principalId),\n inArray(\n principalPolicyBundleReferences.version,\n versions.slice(index, index + REFERENCE_LOOKUP_VERSIONS),\n ),\n or(\n eq(principalPolicyBundleReferences.bundleVersion, head.version),\n eq(\n principalPolicyBundleReferences.bundleStateHash,\n head.stateHash,\n ),\n ),\n ),\n )),\n );\n }\n return stored;\n}\n\n/**\n * Rows written earlier in the same bundle all carry its head, so neither\n * check can match them: each state's outcome depends only on stored rows.\n */\nfunction referenceConflict(\n row: PrincipalPolicyReferenceRow,\n stored: readonly StoredPrincipalPolicyReference[],\n): KeyingVerificationError | null {\n const sameReference = stored.filter((candidate) =>\n isSameReference(candidate, row),\n );\n if (\n sameReference.some(\n (candidate) =>\n candidate.bundleVersion === row.bundleVersion &&\n candidate.bundleStateHash !== row.bundleStateHash,\n )\n )\n return new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference has conflicting bundle heads at one version\",\n );\n const indexed = sameReference.find(\n (candidate) => candidate.bundleStateHash === row.bundleStateHash,\n );\n if (indexed && indexed.bundleVersion !== row.bundleVersion)\n return new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index conflicts with the bundle head\",\n );\n return null;\n}\n\nasync function insertMissingReferences(\n tx: ClientSQLiteTransactionScope,\n rows: readonly PrincipalPolicyReferenceRow[],\n stored: readonly StoredPrincipalPolicyReference[],\n): Promise<void> {\n const present = new Set(stored.map(referenceKey));\n const missing = new Map<string, PrincipalPolicyReferenceRow>();\n for (const row of rows) {\n const key = referenceKey(row);\n if (!present.has(key) && !missing.has(key)) missing.set(key, row);\n }\n const values = [...missing.values()];\n for (\n let index = 0;\n index < values.length;\n index += REFERENCE_INSERT_BATCH_SIZE\n ) {\n await tx\n .insert(principalPolicyBundleReferences)\n .values(values.slice(index, index + REFERENCE_INSERT_BATCH_SIZE))\n .onConflictDoNothing()\n .run();\n }\n}\n\n/**\n * Index every state of a verified bundle under its head. Fails in state order\n * with the per-state checks' errors, keeping the states indexed before the\n * first failure.\n */\nexport async function indexPrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const head = bundle.currentState;\n const states = principalPolicyBundleStates(bundle);\n const foreignIndex = states.findIndex(\n (state) =>\n state.principalType !== head.principalType ||\n state.principalId !== head.principalId,\n );\n const rows: PrincipalPolicyReferenceRow[] = (\n foreignIndex === -1 ? states : states.slice(0, foreignIndex)\n ).map((state) => ({\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n bundleVersion: head.version,\n bundleStateHash: head.stateHash,\n }));\n const stored =\n rows.length === 0\n ? []\n : await loadStoredReferences(tx, head, [\n ...new Set(rows.map((row) => row.version)),\n ]);\n let failure: KeyingVerificationError | null = null;\n let accepted = rows.length;\n for (const [index, row] of rows.entries()) {\n failure = referenceConflict(row, stored);\n if (failure) {\n accepted = index;\n break;\n }\n }\n if (!failure && foreignIndex !== -1)\n failure = new KeyingVerificationError(\n \"object_mismatch\",\n \"principal policy bundle reference belongs to another principal\",\n );\n await insertMissingReferences(tx, rows.slice(0, accepted), stored);\n if (failure) throw failure;\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { KeyingVerificationError, } from "../../internal/crypto/index.js";
2
2
  import { isPrincipalPolicyBundleResponse, isReferencedPrincipalStateResponse, } from "../../internal/validators/response/index.js";
3
3
  import { and, eq, inArray } from "drizzle-orm";
4
- import { principalPolicyBundleContainsReference, principalPolicyBundleStates, } from "../principalPolicyStates.js";
4
+ import { principalPolicyBundleContainsReference, principalPolicyBundleStates, } from "../principals/principalPolicyStates.js";
5
5
  import { principalPolicies, principalPolicyBundleHistory, principalPolicyBundleReferences, } from "../sqlite/schema.js";
6
6
  import { getClientSQLitePersistenceRuntime } from "../sqlite/sqlitePersistenceRuntime.js";
7
7
  import { assertSameHeadPrincipalPolicyBundle } from "./principalPolicyBundleIntegrity.js";
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyReferencePersistence.js","sourceRoot":"","sources":["principalPolicyReferencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,GACnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EACL,sCAAsC,EACtC,2BAA2B,GAC5B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,iBAAiB,EACjB,4BAA4B,EAC5B,+BAA+B,GAChC,MA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S,CAAC;KACrC,CAAC,CAAC;IACH,MAAM,aAAa,GAAG,gBAAgB,CAAC,YAAY,CAAC,CAAC;IACrD,MAAM,YAAY,GAAG,MAAM,gBAAgB,CACzC,OAAO,EACP,SAAS,EACT,UAAU,EACV,aAAa,CACd,CAAC;IACF,MAAM,UAAU,GAAG,iBAAiB,CAClC,UAAU,EACV,YAAY,EACZ,aAAa,EACb,SAAS,CACV,CAAC;IACF,MAAM,QAAQ,GAAG,qBAAqB,CAAC,UAAU,CAAC,CAAC;IACnD,OAAO,QAAQ;QACb,CAAC,CAAC,uCAAuC,CAAC,QAAQ,EAAE,UAAU,CAAC;QAC/D,CAAC,CAAC,IAAI,CAAC;AACX,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n isPrincipalPolicyBundleResponse,\n isReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq, inArray } from \"drizzle-orm\";\nimport {\n principalPolicyBundleContainsReference,\n principalPolicyBundleStates,\n} from \"../principalPolicyStates\";\nimport {\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n} from \"../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport {\n ensurePrincipalPolicyTables,\n principalPolicyBundleSelection,\n type SelectedPrincipalPolicyRow,\n} from \"./principalPolicyPersistence\";\nimport { applyPrincipalPolicyReferenceCheckpoint } from \"./principalPolicyReferenceCheckpoint\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface IndexedBundleHead {\n readonly bundleStateHash: string;\n readonly bundleVersion: number;\n}\n\nfunction assertUnambiguousBundleChain(\n bundle: PrincipalPolicyBundleResponse,\n): void {\n const states = principalPolicyBundleStates(bundle);\n if (states.length !== bundle.currentState.version) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"stored principal policy bundle chain length does not match its head\",\n );\n }\n const versions = new Map<number, string>();\n for (const [index, state] of states.entries()) {\n if (\n state.principalType !== bundle.currentState.principalType ||\n state.principalId !== bundle.currentState.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle chain belongs to another principal\",\n );\n }\n if (\n !Number.isInteger(state.version) ||\n state.version !== index + 1 ||\n !Number.isSafeInteger(state.keyEpoch) ||\n state.keyEpoch < 1 ||\n state.principalId.length === 0 ||\n state.stateHash.length === 0 ||\n state.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle chain has an invalid version or epoch\",\n );\n }\n if (versions.has(state.version)) {\n const previousHash = versions.get(state.version);\n throw new KeyingVerificationError(\n previousHash === state.stateHash ? \"duplicate_entry\" : \"equivocation\",\n \"stored principal policy bundle chain repeats a version\",\n );\n }\n versions.set(state.version, state.stateHash);\n }\n}\n\nfunction parseBoundBundle(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n let bundle: unknown;\n try {\n bundle = storedPrincipalPolicyBundleFromJson(row);\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle contains malformed JSON\",\n );\n }\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle is invalid\",\n );\n }\n if (\n bundle.currentState.principalType !== row.principalType ||\n bundle.currentState.principalId !== row.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle row belongs to another principal\",\n );\n }\n if (bundle.currentState.stateHash !== row.stateHash) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle row has a different head hash\",\n );\n }\n assertUnambiguousBundleChain(bundle);\n return bundle;\n}\n\nfunction assertIndexedBundle(\n bundle: PrincipalPolicyBundleResponse,\n indexed: IndexedBundleHead,\n reference: ReferencedPrincipalHead,\n): void {\n if (\n bundle.currentState.stateHash !== indexed.bundleStateHash ||\n bundle.currentState.version !== indexed.bundleVersion\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index conflicts with its bundle head\",\n );\n }\n if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"indexed principal policy bundle does not contain the exact reference\",\n );\n }\n}\n\nfunction addCandidate(\n candidates: Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >,\n bundle: PrincipalPolicyBundleResponse,\n row: SelectedPrincipalPolicyRow,\n): void {\n const existing = candidates.get(bundle.currentState.stateHash);\n if (existing) {\n assertSameHeadPrincipalPolicyBundle(existing.row, row);\n return;\n }\n candidates.set(bundle.currentState.stateHash, { bundle, row });\n}\n\nfunction assertCurrentDoesNotConflict(\n bundle: PrincipalPolicyBundleResponse,\n reference: ReferencedPrincipalHead,\n): void {\n if (bundle.currentState.version < reference.version) {\n return;\n }\n const stateAtReference = principalPolicyBundleStates(bundle).find(\n (state) => state.version === reference.version,\n );\n if (!stateAtReference) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"current principal policy chain omits the referenced version\",\n );\n }\n if (stateAtReference.stateHash !== reference.stateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"current principal policy chain conflicts with the referenced version\",\n );\n }\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"current principal policy state does not match the exact reference\",\n );\n}\n\nfunction selectNewestCandidate(\n candidates: ReadonlyMap<\n string,\n { readonly bundle: PrincipalPolicyBundleResponse }\n >,\n): PrincipalPolicyBundleResponse | null {\n let selected: PrincipalPolicyBundleResponse | null = null;\n const stateHashByVersion = new Map<number, string>();\n for (const { bundle } of candidates.values()) {\n const existingHash = stateHashByVersion.get(bundle.currentState.version);\n if (\n existingHash !== undefined &&\n existingHash !== bundle.currentState.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"stored principal policy bundles conflict at one version\",\n );\n }\n stateHashByVersion.set(\n bundle.currentState.version,\n bundle.currentState.stateHash,\n );\n if (\n !selected ||\n bundle.currentState.version > selected.currentState.version\n ) {\n selected = bundle;\n }\n }\n return selected;\n}\n\nfunction assertReferenceShape(reference: ReferencedPrincipalHead): void {\n if (!isReferencedPrincipalStateResponse(reference)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n if (\n !Number.isInteger(reference.version) ||\n reference.version < 1 ||\n !Number.isSafeInteger(reference.keyEpoch) ||\n reference.keyEpoch < 1 ||\n reference.principalId.length === 0 ||\n reference.stateHash.length === 0 ||\n reference.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n}\n\nasync function loadCurrentRow(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n): Promise<SelectedPrincipalPolicyRow | undefined> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [row] = await db\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .where(\n and(\n eq(principalPolicies.principalType, reference.principalType),\n eq(principalPolicies.principalId, reference.principalId),\n ),\n )\n .limit(1);\n return row;\n}\n\nasync function loadIndexedHeads(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n): Promise<IndexedBundleHead[]> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select({\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n bundleVersion: principalPolicyBundleReferences.bundleVersion,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(\n principalPolicyBundleReferences.principalType,\n reference.principalType,\n ),\n eq(principalPolicyBundleReferences.principalId, reference.principalId),\n eq(principalPolicyBundleReferences.version, reference.version),\n eq(principalPolicyBundleReferences.stateHash, reference.stateHash),\n eq(principalPolicyBundleReferences.keyEpoch, reference.keyEpoch),\n eq(\n principalPolicyBundleReferences.keyFingerprint,\n reference.keyFingerprint,\n ),\n ),\n );\n}\n\nfunction indexHeadsByHash(\n heads: readonly IndexedBundleHead[],\n): Map<string, IndexedBundleHead> {\n const stateHashByVersion = new Map<number, string>();\n for (const head of heads) {\n if (\n !Number.isInteger(head.bundleVersion) ||\n head.bundleVersion < 1 ||\n head.bundleStateHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference index is malformed\",\n );\n }\n const indexedHash = stateHashByVersion.get(head.bundleVersion);\n if (indexedHash !== undefined && indexedHash !== head.bundleStateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index has conflicting bundle heads at one version\",\n );\n }\n stateHashByVersion.set(head.bundleVersion, head.bundleStateHash);\n }\n return new Map(heads.map((head) => [head.bundleStateHash, head]));\n}\n\nasync function loadRetainedRows(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n currentRow: SelectedPrincipalPolicyRow | undefined,\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n): Promise<SelectedPrincipalPolicyRow[]> {\n const hashes = new Set([reference.stateHash, ...indexedByHash.keys()]);\n if (currentRow) {\n hashes.delete(currentRow.stateHash);\n }\n if (hashes.size === 0) {\n return [];\n }\n // Remote reset deliberately clears mutable heads while retaining historical\n // key material, so an index target can outlive its bundle row. Such a target\n // is only a selection hint; rows that still exist remain authoritative.\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select(principalPolicyBundleSelection(principalPolicyBundleHistory))\n .from(principalPolicyBundleHistory)\n .where(\n and(\n eq(principalPolicyBundleHistory.principalType, reference.principalType),\n eq(principalPolicyBundleHistory.principalId, reference.principalId),\n inArray(principalPolicyBundleHistory.stateHash, [...hashes]),\n ),\n );\n}\n\nfunction collectCandidates(\n currentRow: SelectedPrincipalPolicyRow | undefined,\n retainedRows: readonly SelectedPrincipalPolicyRow[],\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n reference: ReferencedPrincipalHead,\n) {\n const candidates = new Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >();\n if (currentRow) {\n const bundle = parseBoundBundle(currentRow);\n const indexed = indexedByHash.get(currentRow.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n }\n if (principalPolicyBundleContainsReference(bundle, reference)) {\n addCandidate(candidates, bundle, currentRow);\n } else {\n assertCurrentDoesNotConflict(bundle, reference);\n }\n }\n for (const row of retainedRows) {\n const bundle = parseBoundBundle(row);\n const indexed = indexedByHash.get(row.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n } else if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle head does not match the exact reference\",\n );\n }\n addCandidate(candidates, bundle, row);\n }\n return candidates;\n}\n\nexport async function loadPrincipalPolicyBundleForReference(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<PrincipalPolicyBundleResponse | null> {\n assertReferenceShape(reference);\n await ensurePrincipalPolicyTables(execSql);\n const [currentRow, indexedHeads] = await Promise.all([\n loadCurrentRow(execSql, reference),\n loadIndexedHeads(execSql, reference),\n ]);\n const indexedByHash = indexHeadsByHash(indexedHeads);\n const retainedRows = await loadRetainedRows(\n execSql,\n reference,\n currentRow,\n indexedByHash,\n );\n const candidates = collectCandidates(\n currentRow,\n retainedRows,\n indexedByHash,\n reference,\n );\n const selected = selectNewestCandidate(candidates);\n return selected\n ? applyPrincipalPolicyReferenceCheckpoint(selected, checkpoint)\n : null;\n}\n"]}
1
+ {"version":3,"file":"principalPolicyReferencePersistence.js","sourceRoot":"","sources":["principalPolicyReferencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAC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AAM,CAAC,KAAK,UAAU,qCAAqC,CACzD,OAAgB,EAChB,SAAkC,EAClC,UAA4C;IAE5C,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAChC,MAAM,2BAA2B,CAAC,OAAO,CAAC,CAAC;IAC3C,MAAM,CAAC,UAAU,EAAE,YAAY,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACnD,cAAc,CAAC,OAAO,EAAE,SAAS,CAAC;QAClC,gBAAgB,CAAC,OAAO,EAAE,SAAS,CAAC;KACrC,CAAC,CAAC;IACH,MAAM,aAAa,GAAG,gBAAgB,CAAC,YAAY,CAAC,CAAC;IACrD,MAAM,YAAY,GAAG,MAAM,gBAAgB,CACzC,OAAO,EACP,SAAS,EACT,UAAU,EACV,aAAa,CACd,CAAC;IACF,MAAM,UAAU,GAAG,iBAAiB,CAClC,UAAU,EACV,YAAY,EACZ,aAAa,EACb,SAAS,CACV,CAAC;IACF,MAAM,QAAQ,GAAG,qBAAqB,CAAC,UAAU,CAAC,CAAC;IACnD,OAAO,QAAQ;QACb,CAAC,CAAC,uCAAuC,CAAC,QAAQ,EAAE,UAAU,CAAC;QAC/D,CAAC,CAAC,IAAI,CAAC;AACX,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n isPrincipalPolicyBundleResponse,\n isReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq, inArray } from \"drizzle-orm\";\nimport {\n principalPolicyBundleContainsReference,\n principalPolicyBundleStates,\n} from \"../principals/principalPolicyStates\";\nimport {\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n} from \"../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport {\n ensurePrincipalPolicyTables,\n principalPolicyBundleSelection,\n type SelectedPrincipalPolicyRow,\n} from \"./principalPolicyPersistence\";\nimport { applyPrincipalPolicyReferenceCheckpoint } from \"./principalPolicyReferenceCheckpoint\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface IndexedBundleHead {\n readonly bundleStateHash: string;\n readonly bundleVersion: number;\n}\n\nfunction assertUnambiguousBundleChain(\n bundle: PrincipalPolicyBundleResponse,\n): void {\n const states = principalPolicyBundleStates(bundle);\n if (states.length !== bundle.currentState.version) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"stored principal policy bundle chain length does not match its head\",\n );\n }\n const versions = new Map<number, string>();\n for (const [index, state] of states.entries()) {\n if (\n state.principalType !== bundle.currentState.principalType ||\n state.principalId !== bundle.currentState.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle chain belongs to another principal\",\n );\n }\n if (\n !Number.isInteger(state.version) ||\n state.version !== index + 1 ||\n !Number.isSafeInteger(state.keyEpoch) ||\n state.keyEpoch < 1 ||\n state.principalId.length === 0 ||\n state.stateHash.length === 0 ||\n state.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle chain has an invalid version or epoch\",\n );\n }\n if (versions.has(state.version)) {\n const previousHash = versions.get(state.version);\n throw new KeyingVerificationError(\n previousHash === state.stateHash ? \"duplicate_entry\" : \"equivocation\",\n \"stored principal policy bundle chain repeats a version\",\n );\n }\n versions.set(state.version, state.stateHash);\n }\n}\n\nfunction parseBoundBundle(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n let bundle: unknown;\n try {\n bundle = storedPrincipalPolicyBundleFromJson(row);\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle contains malformed JSON\",\n );\n }\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle is invalid\",\n );\n }\n if (\n bundle.currentState.principalType !== row.principalType ||\n bundle.currentState.principalId !== row.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle row belongs to another principal\",\n );\n }\n if (bundle.currentState.stateHash !== row.stateHash) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle row has a different head hash\",\n );\n }\n assertUnambiguousBundleChain(bundle);\n return bundle;\n}\n\nfunction assertIndexedBundle(\n bundle: PrincipalPolicyBundleResponse,\n indexed: IndexedBundleHead,\n reference: ReferencedPrincipalHead,\n): void {\n if (\n bundle.currentState.stateHash !== indexed.bundleStateHash ||\n bundle.currentState.version !== indexed.bundleVersion\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index conflicts with its bundle head\",\n );\n }\n if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"indexed principal policy bundle does not contain the exact reference\",\n );\n }\n}\n\nfunction addCandidate(\n candidates: Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >,\n bundle: PrincipalPolicyBundleResponse,\n row: SelectedPrincipalPolicyRow,\n): void {\n const existing = candidates.get(bundle.currentState.stateHash);\n if (existing) {\n assertSameHeadPrincipalPolicyBundle(existing.row, row);\n return;\n }\n candidates.set(bundle.currentState.stateHash, { bundle, row });\n}\n\nfunction assertCurrentDoesNotConflict(\n bundle: PrincipalPolicyBundleResponse,\n reference: ReferencedPrincipalHead,\n): void {\n if (bundle.currentState.version < reference.version) {\n return;\n }\n const stateAtReference = principalPolicyBundleStates(bundle).find(\n (state) => state.version === reference.version,\n );\n if (!stateAtReference) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"current principal policy chain omits the referenced version\",\n );\n }\n if (stateAtReference.stateHash !== reference.stateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"current principal policy chain conflicts with the referenced version\",\n );\n }\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"current principal policy state does not match the exact reference\",\n );\n}\n\nfunction selectNewestCandidate(\n candidates: ReadonlyMap<\n string,\n { readonly bundle: PrincipalPolicyBundleResponse }\n >,\n): PrincipalPolicyBundleResponse | null {\n let selected: PrincipalPolicyBundleResponse | null = null;\n const stateHashByVersion = new Map<number, string>();\n for (const { bundle } of candidates.values()) {\n const existingHash = stateHashByVersion.get(bundle.currentState.version);\n if (\n existingHash !== undefined &&\n existingHash !== bundle.currentState.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"stored principal policy bundles conflict at one version\",\n );\n }\n stateHashByVersion.set(\n bundle.currentState.version,\n bundle.currentState.stateHash,\n );\n if (\n !selected ||\n bundle.currentState.version > selected.currentState.version\n ) {\n selected = bundle;\n }\n }\n return selected;\n}\n\nfunction assertReferenceShape(reference: ReferencedPrincipalHead): void {\n if (!isReferencedPrincipalStateResponse(reference)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n if (\n !Number.isInteger(reference.version) ||\n reference.version < 1 ||\n !Number.isSafeInteger(reference.keyEpoch) ||\n reference.keyEpoch < 1 ||\n reference.principalId.length === 0 ||\n reference.stateHash.length === 0 ||\n reference.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n}\n\nasync function loadCurrentRow(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n): Promise<SelectedPrincipalPolicyRow | undefined> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [row] = await db\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .where(\n and(\n eq(principalPolicies.principalType, reference.principalType),\n eq(principalPolicies.principalId, reference.principalId),\n ),\n )\n .limit(1);\n return row;\n}\n\nasync function loadIndexedHeads(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n): Promise<IndexedBundleHead[]> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select({\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n bundleVersion: principalPolicyBundleReferences.bundleVersion,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(\n principalPolicyBundleReferences.principalType,\n reference.principalType,\n ),\n eq(principalPolicyBundleReferences.principalId, reference.principalId),\n eq(principalPolicyBundleReferences.version, reference.version),\n eq(principalPolicyBundleReferences.stateHash, reference.stateHash),\n eq(principalPolicyBundleReferences.keyEpoch, reference.keyEpoch),\n eq(\n principalPolicyBundleReferences.keyFingerprint,\n reference.keyFingerprint,\n ),\n ),\n );\n}\n\nfunction indexHeadsByHash(\n heads: readonly IndexedBundleHead[],\n): Map<string, IndexedBundleHead> {\n const stateHashByVersion = new Map<number, string>();\n for (const head of heads) {\n if (\n !Number.isInteger(head.bundleVersion) ||\n head.bundleVersion < 1 ||\n head.bundleStateHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference index is malformed\",\n );\n }\n const indexedHash = stateHashByVersion.get(head.bundleVersion);\n if (indexedHash !== undefined && indexedHash !== head.bundleStateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index has conflicting bundle heads at one version\",\n );\n }\n stateHashByVersion.set(head.bundleVersion, head.bundleStateHash);\n }\n return new Map(heads.map((head) => [head.bundleStateHash, head]));\n}\n\nasync function loadRetainedRows(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n currentRow: SelectedPrincipalPolicyRow | undefined,\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n): Promise<SelectedPrincipalPolicyRow[]> {\n const hashes = new Set([reference.stateHash, ...indexedByHash.keys()]);\n if (currentRow) {\n hashes.delete(currentRow.stateHash);\n }\n if (hashes.size === 0) {\n return [];\n }\n // Remote reset deliberately clears mutable heads while retaining historical\n // key material, so an index target can outlive its bundle row. Such a target\n // is only a selection hint; rows that still exist remain authoritative.\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select(principalPolicyBundleSelection(principalPolicyBundleHistory))\n .from(principalPolicyBundleHistory)\n .where(\n and(\n eq(principalPolicyBundleHistory.principalType, reference.principalType),\n eq(principalPolicyBundleHistory.principalId, reference.principalId),\n inArray(principalPolicyBundleHistory.stateHash, [...hashes]),\n ),\n );\n}\n\nfunction collectCandidates(\n currentRow: SelectedPrincipalPolicyRow | undefined,\n retainedRows: readonly SelectedPrincipalPolicyRow[],\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n reference: ReferencedPrincipalHead,\n) {\n const candidates = new Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >();\n if (currentRow) {\n const bundle = parseBoundBundle(currentRow);\n const indexed = indexedByHash.get(currentRow.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n }\n if (principalPolicyBundleContainsReference(bundle, reference)) {\n addCandidate(candidates, bundle, currentRow);\n } else {\n assertCurrentDoesNotConflict(bundle, reference);\n }\n }\n for (const row of retainedRows) {\n const bundle = parseBoundBundle(row);\n const indexed = indexedByHash.get(row.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n } else if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle head does not match the exact reference\",\n );\n }\n addCandidate(candidates, bundle, row);\n }\n return candidates;\n}\n\nexport async function loadPrincipalPolicyBundleForReference(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<PrincipalPolicyBundleResponse | null> {\n assertReferenceShape(reference);\n await ensurePrincipalPolicyTables(execSql);\n const [currentRow, indexedHeads] = await Promise.all([\n loadCurrentRow(execSql, reference),\n loadIndexedHeads(execSql, reference),\n ]);\n const indexedByHash = indexHeadsByHash(indexedHeads);\n const retainedRows = await loadRetainedRows(\n execSql,\n reference,\n currentRow,\n indexedByHash,\n );\n const candidates = collectCandidates(\n currentRow,\n retainedRows,\n indexedByHash,\n reference,\n );\n const selected = selectNewestCandidate(candidates);\n return selected\n ? applyPrincipalPolicyReferenceCheckpoint(selected, checkpoint)\n : null;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"securityIncidentPersistence.js","sourceRoot":"","sources":["securityIncidentPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAK7D,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAepE,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAEhD;;;;GAIG;AACH,SAAS,uBAAuB,CAC9B,cAA4D;IAE5D,OAAO,4BAA4B,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,IAAI,MAAe,CAAC;IACpB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC7B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACnE,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,MAAM,OAAO,GAA4B,EAAE,CAAC;IAC5C,KAAK,MAAM,CAAC,GAAG,EAAE,IAAI,CAA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,CAAC;IAC5C,OAAO,IAAI,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import {\n isKeyingVerificationCode,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { desc, eq, inArray, isNull, sql } from \"drizzle-orm\";\nimport type {\n SecurityIncident,\n SecurityIncidentObjectKind,\n} from \"../securityIncidents\";\nimport {\n securityIncidents,\n securityIncidentTable,\n} from \"../sqlite/securityIncidentSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\ninterface SecurityIncidentWrite {\n readonly trustDomain: string | null;\n readonly code: SecurityIncident[\"code\"];\n readonly operation: string;\n readonly objectKind: SecurityIncidentObjectKind;\n readonly objectId: string | null;\n readonly organizationId?: string | null | undefined;\n readonly evidenceHashes?: Readonly<Record<string, string>> | undefined;\n readonly detectedAt: string;\n readonly lastDetectedAt: string;\n readonly occurrenceCount: number;\n}\n\nconst SECURITY_INCIDENT_RETENTION_LIMIT = 1_000;\n\n/**\n * The incident id hashes this text, so it must be identical on every device:\n * code-unit key order, no locale collation, and no `Object` property-order\n * rules (which would float integer-like keys ahead of the sort).\n */\nfunction serializeEvidenceHashes(\n evidenceHashes: Readonly<Record<string, string>> | undefined,\n): string {\n return serializeKeyingCanonicalJson(evidenceHashes ?? {});\n}\n\nfunction parseEvidenceHashes(value: string): Readonly<Record<string, string>> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return {};\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return {};\n }\n const entries: Array<[string, string]> = [];\n for (const [key, item] of Object.entries(parsed)) {\n if (key.length === 0 || typeof item !== \"string\") {\n return {};\n }\n entries.push([key, item]);\n }\n // Object.fromEntries keeps every key, including \"__proto__\", which an index\n // assignment on a plain object would silently drop.\n return Object.fromEntries(entries);\n}\n\nfunction parseVerificationCode(value: string): SecurityIncident[\"code\"] {\n if (isKeyingVerificationCode(value)) return value;\n return \"unrecognized_verification_code\";\n}\n\nfunction parseObjectKind(value: string): SecurityIncidentObjectKind {\n switch (value) {\n case \"blob\":\n case \"container\":\n case \"document\":\n case \"principal\":\n case \"user\":\n case \"unknown\":\n return value;\n default:\n return \"unknown\";\n }\n}\n\nasync function ensureSecurityIncidentTable(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, [securityIncidentTable]);\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\nasync function deriveSecurityIncidentId(input: {\n readonly code: SecurityIncident[\"code\"];\n readonly evidenceHashes: string;\n readonly objectId: string | null;\n readonly objectKind: SecurityIncidentObjectKind;\n readonly operation: string;\n readonly organizationId: string | null;\n readonly trustDomain: string | null;\n}): Promise<string> {\n const canonicalIdentity = JSON.stringify([\n input.trustDomain,\n input.code,\n input.operation,\n input.objectKind,\n input.objectId,\n input.organizationId,\n input.evidenceHashes,\n ]);\n const digest = await crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(canonicalIdentity),\n );\n return `incident_v1_${bytesToHex(new Uint8Array(digest))}`;\n}\n\nfunction parseSecurityIncidentRow(\n row: typeof securityIncidents.$inferSelect,\n): SecurityIncident {\n return {\n ...row,\n code: parseVerificationCode(row.code),\n evidenceHashes: parseEvidenceHashes(row.evidenceHashes),\n objectKind: parseObjectKind(row.objectKind),\n trustDomain: row.trustDomain,\n };\n}\n\nexport async function appendSecurityIncident(\n execSql: ExecSql,\n incident: SecurityIncidentWrite,\n): Promise<SecurityIncident | null> {\n await ensureSecurityIncidentTable(execSql);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const evidenceHashes = serializeEvidenceHashes(incident.evidenceHashes);\n const organizationId = incident.organizationId ?? null;\n const id = await deriveSecurityIncidentId({\n code: incident.code,\n evidenceHashes,\n objectId: incident.objectId,\n objectKind: incident.objectKind,\n operation: incident.operation,\n organizationId,\n trustDomain: incident.trustDomain,\n });\n const row = await runtime.transaction(async (tx) => {\n await tx\n .insert(securityIncidents)\n .values({\n ...incident,\n evidenceHashes,\n id,\n organizationId,\n trustDomain: incident.trustDomain,\n })\n .onConflictDoUpdate({\n target: securityIncidents.id,\n set: {\n detectedAt: sql`min(${securityIncidents.detectedAt}, ${incident.detectedAt})`,\n lastDetectedAt: sql`max(${securityIncidents.lastDetectedAt}, ${incident.lastDetectedAt})`,\n occurrenceCount: sql`${securityIncidents.occurrenceCount} + ${incident.occurrenceCount}`,\n },\n })\n .run();\n const trustDomainCondition =\n incident.trustDomain === null\n ? isNull(securityIncidents.trustDomain)\n : eq(securityIncidents.trustDomain, incident.trustDomain);\n const staleRows = await tx\n .select({ id: securityIncidents.id })\n .from(securityIncidents)\n .where(trustDomainCondition)\n .orderBy(\n desc(securityIncidents.lastDetectedAt),\n desc(securityIncidents.id),\n )\n .limit(1)\n .offset(SECURITY_INCIDENT_RETENTION_LIMIT);\n // Each call can add at most one distinct row, so deleting the single 1,001st\n // row restores the cap. A future bulk writer must delete its whole excess.\n if (staleRows.length > 0) {\n await tx\n .delete(securityIncidents)\n .where(\n inArray(\n securityIncidents.id,\n staleRows.map((staleRow) => staleRow.id),\n ),\n )\n .run();\n }\n const [storedRow] = await tx\n .select()\n .from(securityIncidents)\n .where(eq(securityIncidents.id, id))\n .limit(1);\n return storedRow;\n });\n return row ? parseSecurityIncidentRow(row) : null;\n}\n\nexport async function listSecurityIncidents(\n execSql: ExecSql,\n trustDomain: string | null,\n): Promise<SecurityIncident[]> {\n await ensureSecurityIncidentTable(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select()\n .from(securityIncidents)\n .where(\n trustDomain === null\n ? isNull(securityIncidents.trustDomain)\n : eq(securityIncidents.trustDomain, trustDomain),\n )\n .orderBy(desc(securityIncidents.lastDetectedAt), desc(securityIncidents.id))\n .limit(SECURITY_INCIDENT_RETENTION_LIMIT);\n return rows.map(parseSecurityIncidentRow);\n}\n"]}
1
+ {"version":3,"file":"securityIncidentPersistence.js","sourceRoot":"","sources":["securityIncidentPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAK7D,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAepE,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAEhD;;;;GAIG;AACH,SAAS,uBAAuB,CAC9B,cAA4D;IAE5D,OAAO,4BAA4B,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,IAAI,MAAe,CAAC;IACpB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC7B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACnE,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,MAAM,OAAO,GAA4B,EAAE,CAAC;IAC5C,KAAK,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACjD,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YACjD,OAAO,EAAE,CAAC;QACZ,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ql } from \"drizzle-orm\";\nimport type {\n SecurityIncident,\n SecurityIncidentObjectKind,\n} from \"../shared/securityIncidents\";\nimport {\n securityIncidents,\n securityIncidentTable,\n} from \"../sqlite/securityIncidentSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\ninterface SecurityIncidentWrite {\n readonly trustDomain: string | null;\n readonly code: SecurityIncident[\"code\"];\n readonly operation: string;\n readonly objectKind: SecurityIncidentObjectKind;\n readonly objectId: string | null;\n readonly organizationId?: string | null | undefined;\n readonly evidenceHashes?: Readonly<Record<string, string>> | undefined;\n readonly detectedAt: string;\n readonly lastDetectedAt: string;\n readonly occurrenceCount: number;\n}\n\nconst SECURITY_INCIDENT_RETENTION_LIMIT = 1_000;\n\n/**\n * The incident id hashes this text, so it must be identical on every device:\n * code-unit key order, no locale collation, and no `Object` property-order\n * rules (which would float integer-like keys ahead of the sort).\n */\nfunction serializeEvidenceHashes(\n evidenceHashes: Readonly<Record<string, string>> | undefined,\n): string {\n return serializeKeyingCanonicalJson(evidenceHashes ?? {});\n}\n\nfunction parseEvidenceHashes(value: string): Readonly<Record<string, string>> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return {};\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return {};\n }\n const entries: Array<[string, string]> = [];\n for (const [key, item] of Object.entries(parsed)) {\n if (key.length === 0 || typeof item !== \"string\") {\n return {};\n }\n entries.push([key, item]);\n }\n // Object.fromEntries keeps every key, including \"__proto__\", which an index\n // assignment on a plain object would silently drop.\n return Object.fromEntries(entries);\n}\n\nfunction parseVerificationCode(value: string): SecurityIncident[\"code\"] {\n if (isKeyingVerificationCode(value)) return value;\n return \"unrecognized_verification_code\";\n}\n\nfunction parseObjectKind(value: string): SecurityIncidentObjectKind {\n switch (value) {\n case \"blob\":\n case \"container\":\n case \"document\":\n case \"principal\":\n case \"user\":\n case \"unknown\":\n return value;\n default:\n return \"unknown\";\n }\n}\n\nasync function ensureSecurityIncidentTable(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, [securityIncidentTable]);\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\nasync function deriveSecurityIncidentId(input: {\n readonly code: SecurityIncident[\"code\"];\n readonly evidenceHashes: string;\n readonly objectId: string | null;\n readonly objectKind: SecurityIncidentObjectKind;\n readonly operation: string;\n readonly organizationId: string | null;\n readonly trustDomain: string | null;\n}): Promise<string> {\n const canonicalIdentity = JSON.stringify([\n input.trustDomain,\n input.code,\n input.operation,\n input.objectKind,\n input.objectId,\n input.organizationId,\n input.evidenceHashes,\n ]);\n const digest = await crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(canonicalIdentity),\n );\n return `incident_v1_${bytesToHex(new Uint8Array(digest))}`;\n}\n\nfunction parseSecurityIncidentRow(\n row: typeof securityIncidents.$inferSelect,\n): SecurityIncident {\n return {\n ...row,\n code: parseVerificationCode(row.code),\n evidenceHashes: parseEvidenceHashes(row.evidenceHashes),\n objectKind: parseObjectKind(row.objectKind),\n trustDomain: row.trustDomain,\n };\n}\n\nexport async function appendSecurityIncident(\n execSql: ExecSql,\n incident: SecurityIncidentWrite,\n): Promise<SecurityIncident | null> {\n await ensureSecurityIncidentTable(execSql);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const evidenceHashes = serializeEvidenceHashes(incident.evidenceHashes);\n const organizationId = incident.organizationId ?? null;\n const id = await deriveSecurityIncidentId({\n code: incident.code,\n evidenceHashes,\n objectId: incident.objectId,\n objectKind: incident.objectKind,\n operation: incident.operation,\n organizationId,\n trustDomain: incident.trustDomain,\n });\n const row = await runtime.transaction(async (tx) => {\n await tx\n .insert(securityIncidents)\n .values({\n ...incident,\n evidenceHashes,\n id,\n organizationId,\n trustDomain: incident.trustDomain,\n })\n .onConflictDoUpdate({\n target: securityIncidents.id,\n set: {\n detectedAt: sql`min(${securityIncidents.detectedAt}, ${incident.detectedAt})`,\n lastDetectedAt: sql`max(${securityIncidents.lastDetectedAt}, ${incident.lastDetectedAt})`,\n occurrenceCount: sql`${securityIncidents.occurrenceCount} + ${incident.occurrenceCount}`,\n },\n })\n .run();\n const trustDomainCondition =\n incident.trustDomain === null\n ? isNull(securityIncidents.trustDomain)\n : eq(securityIncidents.trustDomain, incident.trustDomain);\n const staleRows = await tx\n .select({ id: securityIncidents.id })\n .from(securityIncidents)\n .where(trustDomainCondition)\n .orderBy(\n desc(securityIncidents.lastDetectedAt),\n desc(securityIncidents.id),\n )\n .limit(1)\n .offset(SECURITY_INCIDENT_RETENTION_LIMIT);\n // Each call can add at most one distinct row, so deleting the single 1,001st\n // row restores the cap. A future bulk writer must delete its whole excess.\n if (staleRows.length > 0) {\n await tx\n .delete(securityIncidents)\n .where(\n inArray(\n securityIncidents.id,\n staleRows.map((staleRow) => staleRow.id),\n ),\n )\n .run();\n }\n const [storedRow] = await tx\n .select()\n .from(securityIncidents)\n .where(eq(securityIncidents.id, id))\n .limit(1);\n return storedRow;\n });\n return row ? parseSecurityIncidentRow(row) : null;\n}\n\nexport async function listSecurityIncidents(\n execSql: ExecSql,\n trustDomain: string | null,\n): Promise<SecurityIncident[]> {\n await ensureSecurityIncidentTable(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select()\n .from(securityIncidents)\n .where(\n trustDomain === null\n ? isNull(securityIncidents.trustDomain)\n : eq(securityIncidents.trustDomain, trustDomain),\n )\n .orderBy(desc(securityIncidents.lastDetectedAt), desc(securityIncidents.id))\n .limit(SECURITY_INCIDENT_RETENTION_LIMIT);\n return rows.map(parseSecurityIncidentRow);\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { KeyingVerificationError, normalizePrincipalContainerGrants, normalizePrincipalProjectionMembers, } from "../../internal/crypto/index.js";
2
- import { canonicalKeyingJsonString } from "../keyingCanonicalJson.js";
2
+ import { canonicalKeyingJsonString } from "../keying/canonicalJson.js";
3
3
  import { assertCurrentMatchesVerifiedPolicy } from "./verifiedPrincipalPolicyCurrent.js";
4
4
  export async function assertBundleMatchesVerifiedPolicy(input) {
5
5
  const { bundle, policy } = input;
@@ -1 +1 @@
1
- {"version":3,"file":"verifiedPrincipalPolicyBundle.js","sourceRoot":"","sources":["verifiedPrincipalPolicyBundle.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,GAEpC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,kCAAkC,EAAE,MAAM,kCAAkC,CAAC;AAEtF,MAAM,CAAC,KAAK,UAAU,iCAAiC,CAAC,KAGvD;IACC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IACjC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC;IACrC,MAAM,aAAa,GAAG;QACpB,GAAG,MAAM,CAAC,cAAc;QACxB;YACE,KAAK,EAAE,MAAM,CAAC,YAAY;YAC1B,UAAU,EAAE,MAAM,CAAC,iBAAiB;YACpC,MAAM,EAAE,MAAM,CAAC,aAAa;SAC7B;KACF,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAChB,GAAG,KAAK;QACR,UAAU,EAAE,mCAAmC,CAAC,KAAK,CAAC,UAAU,CAAC;QACjE,MAAM,EAAE,iCAAiC,CAAC,KAAK,CAAC,MAAM,CAAC;KACxD,CAAC,CAAC,CAAC;IACJ,MAAM,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAC9C,GAAG,KAAK;QACR,UAAU,EAAE,mCAAmC,CAAC,KAAK,CAAC,UAAU,CAAC;QACjE,MAAM,EAAE,iCAAiC,CAAC,KAAK,CAAC,MAAM,CAAC;KACxD,CAAC,CAAC,CAAC;IACJ,IACE,yBAAyB,CACvB,aAAa,EACb,iCAAiC,CAClC;QACD,yBAAyB,CACvB,eAAe,EACf,mCAAmC,CACpC,EACD,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,mDAAmD,CACpD,CAAC;IACJ,CAAC;IACD,MAAM,kCAAkC,CAAC;QACvC,OAAO,EAAE,KAAK,CAAC,MAAM;QACrB,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../keyingCanonicalJson\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyCurrent\";\n\nexport async function assertBundleMatchesVerifiedPolicy(input: {\n bundle: PrincipalPolicyBundleResponse;\n policy: VerifiedPrincipalPolicy;\n}): Promise<void> {\n const { bundle, policy } = input;\n const history = policy.history ?? [];\n const expectedChain = [\n ...bundle.previousStates,\n {\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n },\n ].map((entry) => ({\n ...entry,\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n }));\n const verifiedHistory = history.map((entry) => ({\n ...entry,\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n }));\n if (\n canonicalKeyingJsonString(\n expectedChain,\n \"principal policy bundle history\",\n ) !==\n canonicalKeyingJsonString(\n verifiedHistory,\n \"verified principal policy history\",\n )\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Verified principal policy bundle history mismatch\",\n );\n }\n await assertCurrentMatchesVerifiedPolicy({\n current: input.bundle,\n policy: input.policy,\n });\n}\n"]}
1
+ {"version":3,"file":"verifiedPrincipalPolicyBundle.js","sourceRoot":"","sources":["verifiedPrincipalPolicyBundle.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,GAEpC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,kCAAkC,EAAE,MAAM,kCAAkC,CAAC;AAEtF,MAAM,CAAC,KAAK,UAAU,iCAAiC,CAAC,KAGvD;IACC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IACjC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC;IACrC,MAAM,aAAa,GAAG;QACpB,GAAG,MAAM,CAAC,cAAc;QACxB;YACE,KAAK,EAAE,MAAM,CAAC,YAAY;YAC1B,UAAU,EAAE,MAAM,CAAC,iBAAiB;YACpC,MAAM,EAAE,MAAM,CAAC,aAAa;SAC7B;KACF,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAChB,GAAG,KAAK;QACR,UAAU,EAAE,mCAAmC,CAAC,KAAK,CAAC,UAAU,CAAC;QACjE,MAAM,EAAE,iCAAiC,CAAC,KAAK,CAAC,MAAM,CAAC;KACxD,CAAC,CAAC,CAAC;IACJ,MAAM,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAC9C,GAAG,KAAK;QACR,UAAU,EAAE,mCAAmC,CAAC,KAAK,CAAC,UAAU,CAAC;QACjE,MAAM,EAAE,iCAAiC,CAAC,KAAK,CAAC,MAAM,CAAC;KACxD,CAAC,CAAC,CAAC;IACJ,IACE,yBAAyB,CACvB,aAAa,EACb,iCAAiC,CAClC;QACD,yBAAyB,CACvB,eAAe,EACf,mCAAmC,CACpC,EACD,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,mDAAmD,CACpD,CAAC;IACJ,CAAC;IACD,MAAM,kCAAkC,CAAC;QACvC,OAAO,EAAE,KAAK,CAAC,MAAM;QACrB,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../keying/canonicalJson\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyCurrent\";\n\nexport async function assertBundleMatchesVerifiedPolicy(input: {\n bundle: PrincipalPolicyBundleResponse;\n policy: VerifiedPrincipalPolicy;\n}): Promise<void> {\n const { bundle, policy } = input;\n const history = policy.history ?? [];\n const expectedChain = [\n ...bundle.previousStates,\n {\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n },\n ].map((entry) => ({\n ...entry,\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n }));\n const verifiedHistory = history.map((entry) => ({\n ...entry,\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n }));\n if (\n canonicalKeyingJsonString(\n expectedChain,\n \"principal policy bundle history\",\n ) !==\n canonicalKeyingJsonString(\n verifiedHistory,\n \"verified principal policy history\",\n )\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Verified principal policy bundle history mismatch\",\n );\n }\n await assertCurrentMatchesVerifiedPolicy({\n current: input.bundle,\n policy: input.policy,\n });\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { computePrincipalMemberEnvelopesRoot, computePrincipalStatePayloadCiphertextHash, KeyingVerificationError, normalizePrincipalContainerGrants, normalizePrincipalProjectionMembers, PrincipalMemberEnvelopeValidationError, } from "../../internal/crypto/index.js";
2
- import { canonicalKeyingJsonString } from "../keyingCanonicalJson.js";
2
+ import { canonicalKeyingJsonString } from "../keying/canonicalJson.js";
3
3
  function currentMismatch(message) {
4
4
  throw new KeyingVerificationError("equivocation", message);
5
5
  }
@@ -1 +1 @@
1
- {"version":3,"file":"verifiedPrincipalPolicyCurrent.js","sourceRoot":"","sources":["verifiedPrincipalPolicyCurrent.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mCAAmC,EACnC,0CAA0C,EAC1C,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,EACnC,sCAAsC,GAGvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AAMnE,SAAS,eAAe,CAAC,OAAe;IACtC,MAAM,IAAI,uBAAuB,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;AAC7D,CAAC;AAED,KAAK,UAAU,mBAAmB,CAChC,OAAmC;IAEnC,IAAI,CAAC;QACH,OAAO,MAAM,mCAAmC,CAC9C,OAAO,CAAC,sBAAsB,CAAC,SAAS,CACzC,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,sCAAsC,EAAE,CAAC;YAC5D,MAAM,IAAI,uBAAuB,CAAC,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QACpE,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,KAAK,UAAU,2BAA2B,CAAC,KAG1C;IACC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAClC,MAAM,WAAW,GAAG,MAAM,0CAA0C,CAClE,OAAO,CAAC,cAAc,CAAC,UAAU,CAClC,CAAC;IACF,MAAM,aAAa,GAAG,MAAM,mBAAmB,CAAC,OAAO,CAAC,CAAC;IACzD,IACE,OAAO,CAAC,cAAc,CAAC,aAAa,KAAK,MAAM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ACE,yBAAyB,CACvB,OAAO,CAAC,YAAY,EACpB,gCAAgC,CACjC;QACC,yBAAyB,CACvB,MAAM,CAAC,KAAK,EACZ,iCAAiC,CAClC;QACH,yBAAyB,CACvB,mCAAmC,CAAC,OAAO,CAAC,iBAAiB,CAAC,EAC9D,qCAAqC,CACtC;YACC,yBAAyB,CACvB,mCAAmC,CAAC,MAAM,CAAC,UAAU,CAAC,EACtD,sCAAsC,CACvC;QACH,yBAAyB,CACvB,iCAAiC,CAAC,OAAO,CAAC,aAAa,CAAC,EACxD,iCAAiC,CAClC;YACC,yBAAyB,CACvB,iCAAiC,CAAC,MAAM,CAAC,MAAM,CAAC,EAChD,kCAAkC,CACnC,EACH,CAAC;QACD,eAAe,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;IAED,MAAM,2BAA2B,CAAC,KAAK,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n computePrincipalMemberEnvelopesRoot,\n computePrincipalStatePayloadCiphertextHash,\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n PrincipalMemberEnvelopeValidationError,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { canonicalKeyingJsonString } from \"../keyingCanonicalJson\";\n\ntype VerifiedCurrentPolicy =\n | VerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\nfunction currentMismatch(message: string): never {\n throw new KeyingVerificationError(\"equivocation\", message);\n}\n\nasync function memberEnvelopesRoot(\n current: PrincipalPolicyPageCurrent,\n): Promise<string> {\n try {\n return await computePrincipalMemberEnvelopesRoot(\n current.currentMemberEnvelopes.envelopes,\n );\n } catch (error) {\n if (error instanceof PrincipalMemberEnvelopeValidationError) {\n throw new KeyingVerificationError(\"invalid_shape\", error.message);\n }\n throw error;\n }\n}\n\nasync function assertCurrentPayloadMatches(input: {\n current: PrincipalPolicyPageCurrent;\n policy: VerifiedCurrentPolicy;\n}): Promise<void> {\n const { current, policy } = input;\n const payloadHash = await computePrincipalStatePayloadCiphertextHash(\n current.currentPayload.ciphertext,\n );\n const envelopesRoot = await memberEnvelopesRoot(current);\n if (\n current.currentPayload.principalType !== policy.principalType ||\n current.currentPayload.principalId !== policy.principalId ||\n current.currentPayload.stateHash !== policy.stateHash ||\n current.currentPayload.ciphertextHash !== payloadHash ||\n policy.state.payloadCiphertextHash !== payloadHash ||\n current.currentMemberEnvelopes.principalType !== policy.principalType ||\n current.currentMemberEnvelopes.principalId !== policy.principalId ||\n current.currentMemberEnvelopes.stateHash !== policy.stateHash ||\n current.currentMemberEnvelopes.epoch !== policy.keyEpoch ||\n envelopesRoot !== policy.state.memberEnvelopesRoot\n ) {\n currentMismatch(\"Verified principal policy current payload mismatch\");\n }\n}\n\n/** Bind current wire artifacts to already verified policy evidence; never authenticate history. */\nexport async function assertCurrentMatchesVerifiedPolicy(input: {\n current: PrincipalPolicyPageCurrent;\n policy: VerifiedCurrentPolicy;\n}): Promise<void> {\n const { current, policy } = input;\n if (\n current.currentState.principalType !== policy.principalType ||\n current.currentState.principalId !== policy.principalId ||\n current.currentState.version !== policy.version ||\n current.currentState.keyEpoch !== policy.keyEpoch ||\n current.currentState.stateHash !== policy.stateHash ||\n policy.checkpoint.version !== policy.version ||\n policy.checkpoint.stateHash !== policy.stateHash\n ) {\n currentMismatch(\"Verified principal policy current head mismatch\");\n }\n if (\n canonicalKeyingJsonString(\n current.currentState,\n \"principal policy current state\",\n ) !==\n canonicalKeyingJsonString(\n policy.state,\n \"verified principal policy state\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(current.currentProjection),\n \"principal policy current projection\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(policy.projection),\n \"verified principal policy projection\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(current.currentGrants),\n \"principal policy current grants\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(policy.grants),\n \"verified principal policy grants\",\n )\n ) {\n currentMismatch(\"Verified principal policy current content mismatch\");\n }\n\n await assertCurrentPayloadMatches(input);\n}\n"]}
1
+ {"version":3,"file":"verifiedPrincipalPolicyCurrent.js","sourceRoot":"","sources":["verifiedPrincipalPolicyCurrent.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mCAAmC,EACnC,0CAA0C,EAC1C,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,EACnC,sCAAsC,GAGvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AAMpE,SAAS,eAAe,CAAC,OAAe;IACtC,MAAM,IAAI,uBAAuB,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;AAC7D,CAAC;AAED,KAAK,UAAU,mBAAmB,CAChC,OAAmC;IAEnC,IAAI,CAAC;QACH,OAAO,MAAM,mCAAmC,CAC9C,OAAO,CAAC,sBAAsB,CAAC,SAAS,CACzC,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,sCAAsC,EAAE,CAAC;YAC5D,MAAM,IAAI,uBAAuB,CAAC,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QACpE,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,KAAK,UAAU,2BAA2B,CAAC,KAG1C;IACC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAClC,MAAM,WAAW,GAAG,MAAM,0CAA0C,CAClE,OAAO,CAAC,cAAc,CAAC,UAAU,CAClC,CAAC;IACF,MAAM,aAAa,GAAG,MAAM,mBAAmB,CAAC,OAAO,CAAC,CAAC;IACzD,IACE,OAAO,CAAC,cAAc,CAAC,aAAa,KAAK,MAAM,CAAC,aAAa;QAC7D,OAAO,CAAC,cAAc,CAAC,WAAW,KAAK,MA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C,yBAAyB,CACvB,MAAM,CAAC,KAAK,EACZ,iCAAiC,CAClC;QACH,yBAAyB,CACvB,mCAAmC,CAAC,OAAO,CAAC,iBAAiB,CAAC,EAC9D,qCAAqC,CACtC;YACC,yBAAyB,CACvB,mCAAmC,CAAC,MAAM,CAAC,UAAU,CAAC,EACtD,sCAAsC,CACvC;QACH,yBAAyB,CACvB,iCAAiC,CAAC,OAAO,CAAC,aAAa,CAAC,EACxD,iCAAiC,CAClC;YACC,yBAAyB,CACvB,iCAAiC,CAAC,MAAM,CAAC,MAAM,CAAC,EAChD,kCAAkC,CACnC,EACH,CAAC;QACD,eAAe,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;IAED,MAAM,2BAA2B,CAAC,KAAK,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n computePrincipalMemberEnvelopesRoot,\n computePrincipalStatePayloadCiphertextHash,\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n PrincipalMemberEnvelopeValidationError,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { canonicalKeyingJsonString } from \"../keying/canonicalJson\";\n\ntype VerifiedCurrentPolicy =\n | VerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\nfunction currentMismatch(message: string): never {\n throw new KeyingVerificationError(\"equivocation\", message);\n}\n\nasync function memberEnvelopesRoot(\n current: PrincipalPolicyPageCurrent,\n): Promise<string> {\n try {\n return await computePrincipalMemberEnvelopesRoot(\n current.currentMemberEnvelopes.envelopes,\n );\n } catch (error) {\n if (error instanceof PrincipalMemberEnvelopeValidationError) {\n throw new KeyingVerificationError(\"invalid_shape\", error.message);\n }\n throw error;\n }\n}\n\nasync function assertCurrentPayloadMatches(input: {\n current: PrincipalPolicyPageCurrent;\n policy: VerifiedCurrentPolicy;\n}): Promise<void> {\n const { current, policy } = input;\n const payloadHash = await computePrincipalStatePayloadCiphertextHash(\n current.currentPayload.ciphertext,\n );\n const envelopesRoot = await memberEnvelopesRoot(current);\n if (\n current.currentPayload.principalType !== policy.principalType ||\n current.currentPayload.principalId !== policy.principalId ||\n current.currentPayload.stateHash !== policy.stateHash ||\n current.currentPayload.ciphertextHash !== payloadHash ||\n policy.state.payloadCiphertextHash !== payloadHash ||\n current.currentMemberEnvelopes.principalType !== policy.principalType ||\n current.currentMemberEnvelopes.principalId !== policy.principalId ||\n current.currentMemberEnvelopes.stateHash !== policy.stateHash ||\n current.currentMemberEnvelopes.epoch !== policy.keyEpoch ||\n envelopesRoot !== policy.state.memberEnvelopesRoot\n ) {\n currentMismatch(\"Verified principal policy current payload mismatch\");\n }\n}\n\n/** Bind current wire artifacts to already verified policy evidence; never authenticate history. */\nexport async function assertCurrentMatchesVerifiedPolicy(input: {\n current: PrincipalPolicyPageCurrent;\n policy: VerifiedCurrentPolicy;\n}): Promise<void> {\n const { current, policy } = input;\n if (\n current.currentState.principalType !== policy.principalType ||\n current.currentState.principalId !== policy.principalId ||\n current.currentState.version !== policy.version ||\n current.currentState.keyEpoch !== policy.keyEpoch ||\n current.currentState.stateHash !== policy.stateHash ||\n policy.checkpoint.version !== policy.version ||\n policy.checkpoint.stateHash !== policy.stateHash\n ) {\n currentMismatch(\"Verified principal policy current head mismatch\");\n }\n if (\n canonicalKeyingJsonString(\n current.currentState,\n \"principal policy current state\",\n ) !==\n canonicalKeyingJsonString(\n policy.state,\n \"verified principal policy state\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(current.currentProjection),\n \"principal policy current projection\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(policy.projection),\n \"verified principal policy projection\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(current.currentGrants),\n \"principal policy current grants\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(policy.grants),\n \"verified principal policy grants\",\n )\n ) {\n currentMismatch(\"Verified principal policy current content mismatch\");\n }\n\n await assertCurrentPayloadMatches(input);\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { KeyingVerificationError, sign, toFingerprint, verify, } from "../../internal/crypto/index.js";
2
2
  import { base64ToBytes, bytesToBase64 } from "../../internal/encoding/index.js";
3
- import { canonicalKeyingJsonString } from "../keyingCanonicalJson.js";
3
+ import { canonicalKeyingJsonString } from "../keying/canonicalJson.js";
4
4
  import { readPrincipalMutation, } from "./principalMutationJournalShape.js";
5
5
  const journalDomain = "tearleads.sdk.principal-mutation.v1";
6
6
  const encoder = new TextEncoder();
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutationJournal.js","sourceRoot":"","sources":["principalMutationJournal.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,IAAI,EACJ,aAAa,EACb,MAAM,GACP,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AAEnE,OAAO,EAEL,qBAAqB,GACtB,MAAM,iCAAiC,CAAC;AAWzC,MAAM,aAAa,GAAG,qCAAqC,CAAC;AAC5D,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,SAAS,SAAS,CAAC,KAAoC;IACrD,MAAM,MAAM,GAAG;QACb,KAAK,CAAC,mBAAmB;QACzB,KAAK,CAAC,cAAc;QACpB,KAAK,CAAC,MAAM;QACZ,KAAK,CAAC,kBAAkB;KACzB,CAAC;IACF,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC;QACzE,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,aAAa,EAAE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IACJ,CAAC;IACD,IAAI,CAAC;QACH,OAAO,qBAAqB,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,iBAAiB,CAAC,EAAE,KAAK,CAAC,CAAC;IACzE,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,uEAAuE,CACxE,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type SigningKeyPair,\n sign,\n toFingerprint,\n verify,\n} from \"@tearleads/crypto\";\nimport { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { canonicalKeyingJsonString } from \"../keyingCanonicalJson\";\nimport type { PrincipalMutationJournalRow } from \"../persistence/principalMutationJournalPersistence\";\nimport {\n type AuthoredPrincipalMutation,\n readPrincipalMutation,\n} from \"./principalMutationJournalShape\";\n\nexport interface PrincipalMutationJournalScope {\n readonly identityTrustDomain: string;\n readonly organizationId: string;\n readonly userId: string;\n readonly signingFingerprint: string;\n}\n\nexport type { AuthoredPrincipalMutation } from \"./principalMutationJournalShape\";\n\nconst journalDomain = \"tearleads.sdk.principal-mutation.v1\";\nconst encoder = new TextEncoder();\n\nfunction scopeJson(scope: PrincipalMutationJournalScope): string {\n const values = [\n scope.identityTrustDomain,\n scope.organizationId,\n scope.userId,\n scope.signingFingerprint,\n ];\n if (values.some((value) => typeof value !== \"string\" || value.length === 0))\n throw new Error(\"Principal mutation journal requires a complete scope\");\n return JSON.stringify([journalDomain, ...values]);\n}\n\nexport async function principalMutationJournalScopeId(\n scope: PrincipalMutationJournalScope,\n): Promise<string> {\n return bytesToBase64(\n new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", encoder.encode(scopeJson(scope))),\n ),\n );\n}\n\nfunction signedBytes(scope: PrincipalMutationJournalScope, request: string) {\n // The domain-tagged scope and JSON tuple separate these identity-key\n // signatures from policy state signatures and other authored formats.\n return encoder.encode(JSON.stringify([scopeJson(scope), request]));\n}\n\n/** Sign the complete wire body, including artifacts outside policy signatures. */\nexport async function sealPrincipalMutation(input: {\n readonly scope: PrincipalMutationJournalScope;\n readonly mutation: AuthoredPrincipalMutation;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PrincipalMutationJournalRow> {\n const scope = { ...input.scope };\n const mutation = readPrincipalMutation(\n JSON.parse(JSON.stringify(input.mutation)),\n scope,\n );\n const serializedRequest = canonicalKeyingJsonString(\n mutation,\n \"authored principal mutation\",\n );\n const publicKey = new Uint8Array(input.signingKeyPair.signingPublicKey);\n const privateKey = new Uint8Array(input.signingKeyPair.signingPrivateKey);\n try {\n if ((await toFingerprint(publicKey)) !== scope.signingFingerprint)\n throw new Error(\"Principal mutation journal signing key differs\");\n const bytes = signedBytes(scope, serializedRequest);\n const signature = sign(bytes, privateKey);\n if (!verify(signature, bytes, publicKey))\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"Principal mutation journal signing key pair differs\",\n );\n return {\n scopeId: await principalMutationJournalScopeId(scope),\n organizationId: scope.organizationId,\n serializedRequest,\n signature: bytesToBase64(signature),\n };\n } finally {\n privateKey.fill(0);\n }\n}\n\n/** Authentication precedes parsing or submission; corrupt authored work is retained. */\nexport async function openPrincipalMutation(input: {\n readonly scope: PrincipalMutationJournalScope;\n readonly row: PrincipalMutationJournalRow;\n readonly signingPublicKey: Uint8Array;\n}): Promise<AuthoredPrincipalMutation> {\n const scope = { ...input.scope };\n const row = { ...input.row };\n const publicKey = new Uint8Array(input.signingPublicKey);\n try {\n if (\n row.organizationId !== scope.organizationId ||\n row.scopeId !== (await principalMutationJournalScopeId(scope)) ||\n (await toFingerprint(publicKey)) !== scope.signingFingerprint ||\n !verify(\n base64ToBytes(row.signature),\n signedBytes(scope, row.serializedRequest),\n publicKey,\n )\n )\n throw new Error(\"Principal mutation journal authentication failed\");\n } catch {\n throw new KeyingVerificationError(\n \"signature_mismatch\",\n \"Saved principal mutation could not be authenticated\",\n );\n }\n try {\n return readPrincipalMutation(JSON.parse(row.serializedRequest), scope);\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Authenticated principal mutation has an unsupported or invalid format\",\n );\n }\n}\n"]}
1
+ {"version":3,"file":"principalMutationJournal.js","sourceRoot":"","sources":["principalMutationJournal.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,IAAI,EACJ,aAAa,EACb,MAAM,GACP,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AAEpE,OAAO,EAEL,qBAAqB,GACtB,MAAM,iCAAiC,CAAC;AAWzC,MAAM,aAAa,GAAG,qCAAqC,CAAC;AAC5D,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,SAAS,SAAS,CAAC,KAAoC;IACrD,MAAM,MAAM,GAAG;QACb,KAAK,CAAC,mBAAmB;QACzB,KAAK,CAAC,cAAc;QACpB,KAAK,CAAC,MAAM;QACZ,KAAK,CAAC,kBAAkB;KACzB,CAAC;IACF,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC;QACzE,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,aAAa,EAAE,GAAG,MAAM,CAAC,CAAC,CAAC;AACpD,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,+BAA+B,CACnD,KAAoC;IAEpC,OAAO,aAAa,CAClB,IAAI,UAAU,CACZ,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CACxE,CACF,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAAC,KAAoC,EAAE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"@tearleads/crypto\";\nimport { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { canonicalKeyingJsonString } from \"../keying/canonicalJson\";\nimport type { PrincipalMutationJournalRow } from \"../persistence/principalMutationJournalPersistence\";\nimport {\n type AuthoredPrincipalMutation,\n readPrincipalMutation,\n} from \"./principalMutationJournalShape\";\n\nexport interface PrincipalMutationJournalScope {\n readonly identityTrustDomain: string;\n readonly organizationId: string;\n readonly userId: string;\n readonly signingFingerprint: string;\n}\n\nexport type { AuthoredPrincipalMutation } from \"./principalMutationJournalShape\";\n\nconst journalDomain = \"tearleads.sdk.principal-mutation.v1\";\nconst encoder = new TextEncoder();\n\nfunction scopeJson(scope: PrincipalMutationJournalScope): string {\n const values = [\n scope.identityTrustDomain,\n scope.organizationId,\n scope.userId,\n scope.signingFingerprint,\n ];\n if (values.some((value) => typeof value !== \"string\" || value.length === 0))\n throw new Error(\"Principal mutation journal requires a complete scope\");\n return JSON.stringify([journalDomain, ...values]);\n}\n\nexport async function principalMutationJournalScopeId(\n scope: PrincipalMutationJournalScope,\n): Promise<string> {\n return bytesToBase64(\n new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", encoder.encode(scopeJson(scope))),\n ),\n );\n}\n\nfunction signedBytes(scope: PrincipalMutationJournalScope, request: string) {\n // The domain-tagged scope and JSON tuple separate these identity-key\n // signatures from policy state signatures and other authored formats.\n return encoder.encode(JSON.stringify([scopeJson(scope), request]));\n}\n\n/** Sign the complete wire body, including artifacts outside policy signatures. */\nexport async function sealPrincipalMutation(input: {\n readonly scope: PrincipalMutationJournalScope;\n readonly mutation: AuthoredPrincipalMutation;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PrincipalMutationJournalRow> {\n const scope = { ...input.scope };\n const mutation = readPrincipalMutation(\n JSON.parse(JSON.stringify(input.mutation)),\n scope,\n );\n const serializedRequest = canonicalKeyingJsonString(\n mutation,\n \"authored principal mutation\",\n );\n const publicKey = new Uint8Array(input.signingKeyPair.signingPublicKey);\n const privateKey = new Uint8Array(input.signingKeyPair.signingPrivateKey);\n try {\n if ((await toFingerprint(publicKey)) !== scope.signingFingerprint)\n throw new Error(\"Principal mutation journal signing key differs\");\n const bytes = signedBytes(scope, serializedRequest);\n const signature = sign(bytes, privateKey);\n if (!verify(signature, bytes, publicKey))\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"Principal mutation journal signing key pair differs\",\n );\n return {\n scopeId: await principalMutationJournalScopeId(scope),\n organizationId: scope.organizationId,\n serializedRequest,\n signature: bytesToBase64(signature),\n };\n } finally {\n privateKey.fill(0);\n }\n}\n\n/** Authentication precedes parsing or submission; corrupt authored work is retained. */\nexport async function openPrincipalMutation(input: {\n readonly scope: PrincipalMutationJournalScope;\n readonly row: PrincipalMutationJournalRow;\n readonly signingPublicKey: Uint8Array;\n}): Promise<AuthoredPrincipalMutation> {\n const scope = { ...input.scope };\n const row = { ...input.row };\n const publicKey = new Uint8Array(input.signingPublicKey);\n try {\n if (\n row.organizationId !== scope.organizationId ||\n row.scopeId !== (await principalMutationJournalScopeId(scope)) ||\n (await toFingerprint(publicKey)) !== scope.signingFingerprint ||\n !verify(\n base64ToBytes(row.signature),\n signedBytes(scope, row.serializedRequest),\n publicKey,\n )\n )\n throw new Error(\"Principal mutation journal authentication failed\");\n } catch {\n throw new KeyingVerificationError(\n \"signature_mismatch\",\n \"Saved principal mutation could not be authenticated\",\n );\n }\n try {\n return readPrincipalMutation(JSON.parse(row.serializedRequest), scope);\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Authenticated principal mutation has an unsupported or invalid format\",\n );\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { KeyingVerificationCode } from "../internal/crypto/index.js";
1
+ import type { KeyingVerificationCode } from "../../internal/crypto/index.js";
2
2
  export type SecurityIncidentObjectKind = "blob" | "container" | "document" | "principal" | "user" | "unknown";
3
3
  export interface SecurityIncident {
4
4
  readonly id: string;
@@ -1,6 +1,6 @@
1
1
  import { and, desc, eq, sql } from "drizzle-orm";
2
- import { normalizeEffectiveAccessLevel } from "../accessLevel.js";
3
2
  import { deserializeDocumentSyncPullContinuation } from "../documents/shared/pullContinuation.js";
3
+ import { normalizeEffectiveAccessLevel } from "../keying/accessLevel.js";
4
4
  import { documentHistoryUpdates, documents } from "./schema.js";
5
5
  import { getClientSQLitePersistenceRuntime } from "./sqlitePersistenceRuntime.js";
6
6
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"documentRecordPersistence.js","sourceRoot":"","sources":["documentRecordPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAE,uCAAuC,EAAE,MAAM,sCAAsC,CAAC;AAM/F,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAC7D,OAAO,EAAE,iCAAiC,EAAE,MAAM,4BAA4B,CAAC;AAG/E;;;;GAIG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,EAAE,EAAE,SAAS,CAAC,OAAO;IACrB,UAAU,EAAE,SAAS,CAAC,UAAU;IAChC,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;IAChD,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;IAChD,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;IAChD,WAAW,EAAE,SAAS,CAAC,WAAW;IAClC,eAAe,EAAE,SAAS,CAAC,eAAe;IAC1C,oBAAoB,EAAE,SAAS,CAAC,oBAAoB;IACpD,aAAa,EAAE,SAAS,CAAC,aAAa;IACtC,sBAAsB,EAAE,SAAS,CAAC,sBAAsB;IACxD,gBAAgB,EAAE,SAAS,CAAC,gBAAgB;IAC5C,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;IAChD,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;IAChD,gBA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AC;SACf,KAAK,CACJ,GAAG,CAAC,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC,CAC1E;QACD,yEAAyE;QACzE,oEAAoE;SACnE,OAAO,CACN,IAAI,CAAC,mBAAmB,CAAC,EACzB,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,EACzB,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CACxB;SACA,KAAK,CAAC,CAAC,CAAC,CAAC;IAEZ,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,OAAO,IAAI,IAAI,CAAC;AAClC,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,OAAgB,EAChB,KAAoB;IAEpB,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,EAAE;aACL,MAAM,CAAC,SAAS,CAAC;aACjB,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACpC,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CACrC,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, desc, eq, sql } from \"drizzle-orm\";\nimport { normalizeEffectiveAccessLevel } from \"../accessLevel\";\nimport { deserializeDocumentSyncPullContinuation } from \"../documents/shared/pullContinuation\";\nimport type {\n DocumentRecord,\n DocumentScope,\n SelectedDocumentRecordRow,\n} from \"./documentPersistenceTypes\";\nimport { documentHistoryUpdates, documents } from \"./schema\";\nimport { getClientSQLitePersistenceRuntime } from \"./sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"./sqlSchema\";\n\n/**\n * The ONE select shape for a full documents-row record: every reader that\n * feeds mapSelectedDocumentRecord spreads this, so a new record column cannot\n * silently miss one of them.\n */\nexport const documentRecordSelection = {\n id: documents.localId,\n documentId: documents.documentId,\n recoveryGeneration: documents.recoveryGeneration,\n recoveryDocumentId: documents.recoveryDocumentId,\n snapshotEndVersion: documents.snapshotEndVersion,\n accessEpoch: documents.accessEpoch,\n accessStateHash: documents.accessStateHash,\n effectiveAccessLevel: documents.effectiveAccessLevel,\n lastCommitLsn: documents.lastCommitLsn,\n documentManifestBundle: documents.documentManifestBundle,\n contentKeyBundle: documents.contentKeyBundle,\n documentKekTargets: documents.documentKekTargets,\n pendingBaseVersion: documents.pendingBaseVersion,\n pullContinuation: documents.pullContinuation,\n};\n\nexport function mapSelectedDocumentRecord(\n row: SelectedDocumentRecordRow,\n): DocumentRecord {\n const record: DocumentRecord = {\n id: row.id,\n documentId: row.documentId,\n recoveryGeneration: row.recoveryGeneration,\n snapshotEndVersion: row.snapshotEndVersion,\n accessEpoch: row.accessEpoch,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n row.effectiveAccessLevel,\n ),\n lastCommitLsn: row.lastCommitLsn,\n contentKeyBundle: row.contentKeyBundle,\n documentKekTargets: row.documentKekTargets,\n documentManifestBundle: row.documentManifestBundle,\n };\n\n if (row.accessStateHash !== null) {\n record.accessStateHash = row.accessStateHash;\n }\n\n if (row.recoveryDocumentId !== null) {\n record.recoveryDocumentId = row.recoveryDocumentId;\n }\n\n // Only surface the marker when one was persisted, so a row that never stored\n // one keeps its prior shape (and init falls through to seeding it).\n if (row.pendingBaseVersion !== null) {\n record.pendingBaseVersion = row.pendingBaseVersion;\n }\n\n const pullContinuation = deserializeDocumentSyncPullContinuation(\n row.pullContinuation,\n );\n if (pullContinuation !== null) {\n record.pullContinuation = pullContinuation;\n } else if (row.pullContinuation !== null) {\n record.pullContinuationRecoveryRequired = true;\n }\n\n return record;\n}\n\nexport async function loadDocumentRecord(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<DocumentRecord | null> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentRecordSelection)\n .from(documents)\n .where(\n and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n ),\n )\n .limit(1);\n\n return rows[0] ? mapSelectedDocumentRecord(rows[0]) : null;\n}\n\nexport async function findLocalIdByDocumentId(\n execSql: ExecSql,\n appKind: string,\n documentId: string,\n): Promise<string | null> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const hasPendingUpdates = sql<number>`EXISTS (\n SELECT 1\n FROM ${documentHistoryUpdates}\n WHERE ${documentHistoryUpdates.appKind} = ${documents.appKind}\n AND ${documentHistoryUpdates.localId} = ${documents.localId}\n AND ${documentHistoryUpdates.updateId} IS NOT NULL\n )`;\n const hasPendingLocalWork = sql<number>`(\n ${hasPendingUpdates}\n OR (\n ${documents.pendingBaseVersion} IS NOT NULL\n AND ${documents.pendingBaseVersion} <> ${documents.snapshotEndVersion}\n )\n )`;\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(eq(documents.appKind, appKind), eq(documents.documentId, documentId)),\n )\n // Duplicate remote identities can survive an interrupted local adoption.\n // Preserve queued or deferred edits, then make the fallback stable.\n .orderBy(\n desc(hasPendingLocalWork),\n desc(documents.updatedAt),\n desc(documents.localId),\n )\n .limit(1);\n\n return rows[0]?.localId ?? null;\n}\n\nexport async function deleteDocumentRecord(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .delete(documents)\n .where(\n and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n ),\n )\n .run();\n });\n}\n"]}
1
+ {"version":3,"file":"documentRecordPersistence.js","sourceRoot":"","sources":["documentRecordPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,uCAAuC,EAAE,MAAM,sCAAsC,CAAC;AAC/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pB,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,EAAE;aACL,MAAM,CAAC,SAAS,CAAC;aACjB,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACpC,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CACrC,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, desc, eq, sql } from \"drizzle-orm\";\nimport { deserializeDocumentSyncPullContinuation } from \"../documents/shared/pullContinuation\";\nimport { normalizeEffectiveAccessLevel } from \"../keying/accessLevel\";\nimport type {\n DocumentRecord,\n DocumentScope,\n SelectedDocumentRecordRow,\n} from \"./documentPersistenceTypes\";\nimport { documentHistoryUpdates, documents } from \"./schema\";\nimport { getClientSQLitePersistenceRuntime } from \"./sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"./sqlSchema\";\n\n/**\n * The ONE select shape for a full documents-row record: every reader that\n * feeds mapSelectedDocumentRecord spreads this, so a new record column cannot\n * silently miss one of them.\n */\nexport const documentRecordSelection = {\n id: documents.localId,\n documentId: documents.documentId,\n recoveryGeneration: documents.recoveryGeneration,\n recoveryDocumentId: documents.recoveryDocumentId,\n snapshotEndVersion: documents.snapshotEndVersion,\n accessEpoch: documents.accessEpoch,\n accessStateHash: documents.accessStateHash,\n effectiveAccessLevel: documents.effectiveAccessLevel,\n lastCommitLsn: documents.lastCommitLsn,\n documentManifestBundle: documents.documentManifestBundle,\n contentKeyBundle: documents.contentKeyBundle,\n documentKekTargets: documents.documentKekTargets,\n pendingBaseVersion: documents.pendingBaseVersion,\n pullContinuation: documents.pullContinuation,\n};\n\nexport function mapSelectedDocumentRecord(\n row: SelectedDocumentRecordRow,\n): DocumentRecord {\n const record: DocumentRecord = {\n id: row.id,\n documentId: row.documentId,\n recoveryGeneration: row.recoveryGeneration,\n snapshotEndVersion: row.snapshotEndVersion,\n accessEpoch: row.accessEpoch,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n row.effectiveAccessLevel,\n ),\n lastCommitLsn: row.lastCommitLsn,\n contentKeyBundle: row.contentKeyBundle,\n documentKekTargets: row.documentKekTargets,\n documentManifestBundle: row.documentManifestBundle,\n };\n\n if (row.accessStateHash !== null) {\n record.accessStateHash = row.accessStateHash;\n }\n\n if (row.recoveryDocumentId !== null) {\n record.recoveryDocumentId = row.recoveryDocumentId;\n }\n\n // Only surface the marker when one was persisted, so a row that never stored\n // one keeps its prior shape (and init falls through to seeding it).\n if (row.pendingBaseVersion !== null) {\n record.pendingBaseVersion = row.pendingBaseVersion;\n }\n\n const pullContinuation = deserializeDocumentSyncPullContinuation(\n row.pullContinuation,\n );\n if (pullContinuation !== null) {\n record.pullContinuation = pullContinuation;\n } else if (row.pullContinuation !== null) {\n record.pullContinuationRecoveryRequired = true;\n }\n\n return record;\n}\n\nexport async function loadDocumentRecord(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<DocumentRecord | null> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentRecordSelection)\n .from(documents)\n .where(\n and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n ),\n )\n .limit(1);\n\n return rows[0] ? mapSelectedDocumentRecord(rows[0]) : null;\n}\n\nexport async function findLocalIdByDocumentId(\n execSql: ExecSql,\n appKind: string,\n documentId: string,\n): Promise<string | null> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const hasPendingUpdates = sql<number>`EXISTS (\n SELECT 1\n FROM ${documentHistoryUpdates}\n WHERE ${documentHistoryUpdates.appKind} = ${documents.appKind}\n AND ${documentHistoryUpdates.localId} = ${documents.localId}\n AND ${documentHistoryUpdates.updateId} IS NOT NULL\n )`;\n const hasPendingLocalWork = sql<number>`(\n ${hasPendingUpdates}\n OR (\n ${documents.pendingBaseVersion} IS NOT NULL\n AND ${documents.pendingBaseVersion} <> ${documents.snapshotEndVersion}\n )\n )`;\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(eq(documents.appKind, appKind), eq(documents.documentId, documentId)),\n )\n // Duplicate remote identities can survive an interrupted local adoption.\n // Preserve queued or deferred edits, then make the fallback stable.\n .orderBy(\n desc(hasPendingLocalWork),\n desc(documents.updatedAt),\n desc(documents.localId),\n )\n .limit(1);\n\n return rows[0]?.localId ?? null;\n}\n\nexport async function deleteDocumentRecord(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .delete(documents)\n .where(\n and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n ),\n )\n .run();\n });\n}\n"]}