@open-e2ee/signal-protocol-sdk 7.2.0 → 8.0.0

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 (688) hide show
  1. package/ADAPTERS.md +54 -7
  2. package/ARCHITECTURE.md +1 -0
  3. package/CHANGELOG.md +503 -0
  4. package/README.md +9 -5
  5. package/SECURITY.md +2 -2
  6. package/THIRD_PARTY_NOTICES.md +429 -0
  7. package/client/README.md +1 -2
  8. package/device/README.md +50 -19
  9. package/dist/client/client.d.ts +31 -5
  10. package/dist/client/client.d.ts.map +1 -1
  11. package/dist/client/client.js +149 -90
  12. package/dist/client/client.js.map +1 -1
  13. package/dist/client/event-hooks.d.ts.map +1 -1
  14. package/dist/client/event-hooks.js +2 -0
  15. package/dist/client/event-hooks.js.map +1 -1
  16. package/dist/client/files.d.ts.map +1 -1
  17. package/dist/client/files.js +19 -2
  18. package/dist/client/files.js.map +1 -1
  19. package/dist/client/headless.d.ts +1 -1
  20. package/dist/client/headless.js +1 -1
  21. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -1
  22. package/dist/client/hosted-anonymous-delivery.js +2 -1
  23. package/dist/client/hosted-anonymous-delivery.js.map +1 -1
  24. package/dist/client/hosted-connection.d.ts +1 -1
  25. package/dist/client/hosted-connection.d.ts.map +1 -1
  26. package/dist/client/hosted-connection.js +8 -12
  27. package/dist/client/hosted-connection.js.map +1 -1
  28. package/dist/client/hosted-group-authority.d.ts.map +1 -1
  29. package/dist/client/hosted-group-authority.js +2 -1
  30. package/dist/client/hosted-group-authority.js.map +1 -1
  31. package/dist/client/hosted-groups.d.ts.map +1 -1
  32. package/dist/client/hosted-groups.js +2 -1
  33. package/dist/client/hosted-groups.js.map +1 -1
  34. package/dist/client/hosted-push.d.ts.map +1 -1
  35. package/dist/client/hosted-push.js +2 -1
  36. package/dist/client/hosted-push.js.map +1 -1
  37. package/dist/client/hosted-transport.d.ts.map +1 -1
  38. package/dist/client/hosted-transport.js +10 -11
  39. package/dist/client/hosted-transport.js.map +1 -1
  40. package/dist/client/hosted-trust.d.ts +11 -11
  41. package/dist/client/hosted-trust.d.ts.map +1 -1
  42. package/dist/client/hosted-trust.js +12 -12
  43. package/dist/client/hosted-trust.js.map +1 -1
  44. package/dist/client/messages.d.ts.map +1 -1
  45. package/dist/client/messages.js +6 -1
  46. package/dist/client/messages.js.map +1 -1
  47. package/dist/client/multi-device.d.ts.map +1 -1
  48. package/dist/client/multi-device.js +2 -1
  49. package/dist/client/multi-device.js.map +1 -1
  50. package/dist/client/relay-work.d.ts +30 -0
  51. package/dist/client/relay-work.d.ts.map +1 -0
  52. package/dist/client/relay-work.js +189 -0
  53. package/dist/client/relay-work.js.map +1 -0
  54. package/dist/client/retry.d.ts.map +1 -1
  55. package/dist/client/retry.js +2 -0
  56. package/dist/client/retry.js.map +1 -1
  57. package/dist/client/sessions.d.ts.map +1 -1
  58. package/dist/client/sessions.js +3 -0
  59. package/dist/client/sessions.js.map +1 -1
  60. package/dist/client/signal-service-cipher.d.ts +19 -11
  61. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  62. package/dist/client/signal-service-cipher.js +48 -46
  63. package/dist/client/signal-service-cipher.js.map +1 -1
  64. package/dist/client/state.d.ts +8 -0
  65. package/dist/client/state.d.ts.map +1 -1
  66. package/dist/client/state.js +11 -0
  67. package/dist/client/state.js.map +1 -1
  68. package/dist/device/connection.d.ts +1 -1
  69. package/dist/device/connection.d.ts.map +1 -1
  70. package/dist/device/connection.js +4 -11
  71. package/dist/device/connection.js.map +1 -1
  72. package/dist/device/device-id.d.ts +10 -4
  73. package/dist/device/device-id.d.ts.map +1 -1
  74. package/dist/device/device-id.js +15 -9
  75. package/dist/device/device-id.js.map +1 -1
  76. package/dist/device/device-name-crypto.d.ts.map +1 -1
  77. package/dist/device/device-name-crypto.js +2 -2
  78. package/dist/device/device-name-crypto.js.map +1 -1
  79. package/dist/device/expo/index.d.ts +25 -8
  80. package/dist/device/expo/index.d.ts.map +1 -1
  81. package/dist/device/expo/index.js +58 -8
  82. package/dist/device/expo/index.js.map +1 -1
  83. package/dist/device/index.d.ts +2 -2
  84. package/dist/device/index.d.ts.map +1 -1
  85. package/dist/device/index.js +3 -2
  86. package/dist/device/index.js.map +1 -1
  87. package/dist/device/lifecycle/index.d.ts +4 -2
  88. package/dist/device/lifecycle/index.d.ts.map +1 -1
  89. package/dist/device/lifecycle/index.js.map +1 -1
  90. package/dist/device/lifecycle/manager.d.ts +12 -14
  91. package/dist/device/lifecycle/manager.d.ts.map +1 -1
  92. package/dist/device/lifecycle/manager.js +52 -97
  93. package/dist/device/lifecycle/manager.js.map +1 -1
  94. package/dist/device/lifecycle/types.d.ts +26 -16
  95. package/dist/device/lifecycle/types.d.ts.map +1 -1
  96. package/dist/device/lifecycle/utils.d.ts +8 -4
  97. package/dist/device/lifecycle/utils.d.ts.map +1 -1
  98. package/dist/device/lifecycle/utils.js +12 -16
  99. package/dist/device/lifecycle/utils.js.map +1 -1
  100. package/dist/device/provisioning.d.ts.map +1 -1
  101. package/dist/device/provisioning.js +6 -8
  102. package/dist/device/provisioning.js.map +1 -1
  103. package/dist/device/react-native/index.d.ts +40 -0
  104. package/dist/device/react-native/index.d.ts.map +1 -0
  105. package/dist/device/react-native/index.js +74 -0
  106. package/dist/device/react-native/index.js.map +1 -0
  107. package/dist/device/transfer.d.ts +15 -7
  108. package/dist/device/transfer.d.ts.map +1 -1
  109. package/dist/device/transfer.js +30 -22
  110. package/dist/device/transfer.js.map +1 -1
  111. package/dist/device/types.d.ts +15 -7
  112. package/dist/device/types.d.ts.map +1 -1
  113. package/dist/device/types.js.map +1 -1
  114. package/dist/device/vault-text.d.ts +13 -0
  115. package/dist/device/vault-text.d.ts.map +1 -0
  116. package/dist/device/vault-text.js +17 -0
  117. package/dist/device/vault-text.js.map +1 -0
  118. package/dist/index.d.ts +9 -5
  119. package/dist/index.d.ts.map +1 -1
  120. package/dist/index.js +9 -5
  121. package/dist/index.js.map +1 -1
  122. package/dist/internal/crypto/index.d.ts +3 -3
  123. package/dist/internal/crypto/index.d.ts.map +1 -1
  124. package/dist/internal/crypto/index.js +3 -3
  125. package/dist/internal/crypto/index.js.map +1 -1
  126. package/dist/internal/crypto/random-host.d.ts +1 -1
  127. package/dist/internal/crypto/random-host.d.ts.map +1 -1
  128. package/dist/internal/crypto/random-host.js +3 -2
  129. package/dist/internal/crypto/random-host.js.map +1 -1
  130. package/dist/internal/crypto/random-host.native.d.ts +6 -1
  131. package/dist/internal/crypto/random-host.native.d.ts.map +1 -1
  132. package/dist/internal/crypto/random-host.native.js +14 -10
  133. package/dist/internal/crypto/random-host.native.js.map +1 -1
  134. package/dist/internal/crypto/random-host.node.d.ts +1 -1
  135. package/dist/internal/crypto/random-host.node.d.ts.map +1 -1
  136. package/dist/internal/crypto/random-host.node.js +1 -1
  137. package/dist/internal/crypto/random-host.node.js.map +1 -1
  138. package/dist/internal/crypto/random.d.ts +12 -3
  139. package/dist/internal/crypto/random.d.ts.map +1 -1
  140. package/dist/internal/crypto/random.js +14 -3
  141. package/dist/internal/crypto/random.js.map +1 -1
  142. package/dist/internal/crypto/utils.d.ts.map +1 -1
  143. package/dist/internal/crypto/utils.js +10 -6
  144. package/dist/internal/crypto/utils.js.map +1 -1
  145. package/dist/internal/encoding/proto/primitives.d.ts +2 -0
  146. package/dist/internal/encoding/proto/primitives.d.ts.map +1 -1
  147. package/dist/internal/encoding/proto/primitives.js +2 -1
  148. package/dist/internal/encoding/proto/primitives.js.map +1 -1
  149. package/dist/internal/encoding/proto/signal-message.d.ts +1 -0
  150. package/dist/internal/encoding/proto/signal-message.d.ts.map +1 -1
  151. package/dist/internal/encoding/proto/signal-message.js +2 -1
  152. package/dist/internal/encoding/proto/signal-message.js.map +1 -1
  153. package/dist/internal/groups/authority-certificate.d.ts.map +1 -1
  154. package/dist/internal/groups/authority-certificate.js +2 -1
  155. package/dist/internal/groups/authority-certificate.js.map +1 -1
  156. package/dist/internal/groups/encrypted-state.d.ts.map +1 -1
  157. package/dist/internal/groups/encrypted-state.js +9 -7
  158. package/dist/internal/groups/encrypted-state.js.map +1 -1
  159. package/dist/internal/groups/invite-link.d.ts.map +1 -1
  160. package/dist/internal/groups/invite-link.js +2 -1
  161. package/dist/internal/groups/invite-link.js.map +1 -1
  162. package/dist/internal/groups/manager.d.ts.map +1 -1
  163. package/dist/internal/groups/manager.js +5 -5
  164. package/dist/internal/groups/manager.js.map +1 -1
  165. package/dist/internal/groups/sdk-store.d.ts.map +1 -1
  166. package/dist/internal/groups/sdk-store.js +4 -3
  167. package/dist/internal/groups/sdk-store.js.map +1 -1
  168. package/dist/internal/groups/server-engine.d.ts +6 -1
  169. package/dist/internal/groups/server-engine.d.ts.map +1 -1
  170. package/dist/internal/groups/server-engine.js +11 -15
  171. package/dist/internal/groups/server-engine.js.map +1 -1
  172. package/dist/internal/groups/wire.d.ts.map +1 -1
  173. package/dist/internal/groups/wire.js +2 -1
  174. package/dist/internal/groups/wire.js.map +1 -1
  175. package/dist/internal/platform/blob.d.ts +10 -0
  176. package/dist/internal/platform/blob.d.ts.map +1 -0
  177. package/dist/internal/platform/blob.js +30 -0
  178. package/dist/internal/platform/blob.js.map +1 -0
  179. package/dist/internal/platform/env.d.ts +13 -0
  180. package/dist/internal/platform/env.d.ts.map +1 -0
  181. package/dist/internal/platform/env.js +17 -0
  182. package/dist/internal/platform/env.js.map +1 -0
  183. package/dist/internal/platform/index.d.ts +5 -0
  184. package/dist/internal/platform/index.d.ts.map +1 -0
  185. package/dist/internal/platform/index.js +5 -0
  186. package/dist/internal/platform/index.js.map +1 -0
  187. package/dist/internal/platform/url.d.ts +72 -0
  188. package/dist/internal/platform/url.d.ts.map +1 -0
  189. package/dist/internal/platform/url.js +275 -0
  190. package/dist/internal/platform/url.js.map +1 -0
  191. package/dist/internal/platform/utf8.d.ts +28 -0
  192. package/dist/internal/platform/utf8.d.ts.map +1 -0
  193. package/dist/internal/platform/utf8.js +167 -0
  194. package/dist/internal/platform/utf8.js.map +1 -0
  195. package/dist/internal/protocol/sealed-sender/delivery-token.d.ts +1 -1
  196. package/dist/internal/protocol/sealed-sender/delivery-token.d.ts.map +1 -1
  197. package/dist/internal/protocol/sealed-sender/delivery-token.js +5 -10
  198. package/dist/internal/protocol/sealed-sender/delivery-token.js.map +1 -1
  199. package/dist/internal/protocol/sealed-sender/proto/index.d.ts.map +1 -1
  200. package/dist/internal/protocol/sealed-sender/proto/index.js +2 -4
  201. package/dist/internal/protocol/sealed-sender/proto/index.js.map +1 -1
  202. package/dist/internal/protocol/sender-keys/manager.d.ts.map +1 -1
  203. package/dist/internal/protocol/sender-keys/manager.js +4 -3
  204. package/dist/internal/protocol/sender-keys/manager.js.map +1 -1
  205. package/dist/internal/protocol/spqr/ml-kem-braid/noble-pq/index.d.ts +4 -4
  206. package/dist/internal/protocol/spqr/ml-kem-braid/noble-pq/index.d.ts.map +1 -1
  207. package/dist/internal/protocol/spqr/ml-kem-braid/noble-pq/index.js +8 -10
  208. package/dist/internal/protocol/spqr/ml-kem-braid/noble-pq/index.js.map +1 -1
  209. package/dist/internal/protocol/username/hash.d.ts.map +1 -1
  210. package/dist/internal/protocol/username/hash.js +18 -3
  211. package/dist/internal/protocol/username/hash.js.map +1 -1
  212. package/dist/internal/protocol/username/link.d.ts.map +1 -1
  213. package/dist/internal/protocol/username/link.js +2 -1
  214. package/dist/internal/protocol/username/link.js.map +1 -1
  215. package/dist/internal/protocol/username/proof.d.ts.map +1 -1
  216. package/dist/internal/protocol/username/proof.js +2 -1
  217. package/dist/internal/protocol/username/proof.js.map +1 -1
  218. package/dist/internal/sesame/device-registry.d.ts +16 -3
  219. package/dist/internal/sesame/device-registry.d.ts.map +1 -1
  220. package/dist/internal/sesame/device-registry.js +10 -7
  221. package/dist/internal/sesame/device-registry.js.map +1 -1
  222. package/dist/internal/sesame/index.d.ts +1 -1
  223. package/dist/internal/sesame/index.d.ts.map +1 -1
  224. package/dist/internal/sesame/manager.d.ts.map +1 -1
  225. package/dist/internal/sesame/manager.js +3 -2
  226. package/dist/internal/sesame/manager.js.map +1 -1
  227. package/dist/internal/session/index.d.ts +1 -2
  228. package/dist/internal/session/index.d.ts.map +1 -1
  229. package/dist/internal/session/index.js +1 -1
  230. package/dist/internal/session/index.js.map +1 -1
  231. package/dist/internal/session/validation.d.ts +0 -80
  232. package/dist/internal/session/validation.d.ts.map +1 -1
  233. package/dist/internal/session/validation.js +0 -134
  234. package/dist/internal/session/validation.js.map +1 -1
  235. package/dist/local/store/device-record.d.ts +18 -0
  236. package/dist/local/store/device-record.d.ts.map +1 -0
  237. package/dist/local/store/device-record.js +34 -0
  238. package/dist/local/store/device-record.js.map +1 -0
  239. package/dist/local/store/expo/adapter.d.ts +59 -238
  240. package/dist/local/store/expo/adapter.d.ts.map +1 -1
  241. package/dist/local/store/expo/adapter.js +83 -640
  242. package/dist/local/store/expo/adapter.js.map +1 -1
  243. package/dist/local/store/expo/driver.d.ts +16 -0
  244. package/dist/local/store/expo/driver.d.ts.map +1 -0
  245. package/dist/local/store/expo/driver.js +141 -0
  246. package/dist/local/store/expo/driver.js.map +1 -0
  247. package/dist/local/store/expo/index.d.ts +3 -12
  248. package/dist/local/store/expo/index.d.ts.map +1 -1
  249. package/dist/local/store/expo/index.js +1 -8
  250. package/dist/local/store/expo/index.js.map +1 -1
  251. package/dist/local/store/expo/maintenance.d.ts +3 -2
  252. package/dist/local/store/expo/maintenance.d.ts.map +1 -1
  253. package/dist/local/store/expo/maintenance.js +5 -34
  254. package/dist/local/store/expo/maintenance.js.map +1 -1
  255. package/dist/local/store/index.d.ts +10 -5
  256. package/dist/local/store/index.d.ts.map +1 -1
  257. package/dist/local/store/index.js +10 -5
  258. package/dist/local/store/index.js.map +1 -1
  259. package/dist/local/store/key-value/adapter.d.ts +326 -0
  260. package/dist/local/store/key-value/adapter.d.ts.map +1 -0
  261. package/dist/local/store/key-value/adapter.js +1472 -0
  262. package/dist/local/store/key-value/adapter.js.map +1 -0
  263. package/dist/local/store/{react-native → key-value}/backend-conformance.d.ts +6 -6
  264. package/dist/local/store/key-value/backend-conformance.d.ts.map +1 -0
  265. package/dist/local/store/{react-native → key-value}/backend-conformance.js +3 -3
  266. package/dist/local/store/key-value/backend-conformance.js.map +1 -0
  267. package/dist/local/store/key-value/batch.d.ts +41 -0
  268. package/dist/local/store/key-value/batch.d.ts.map +1 -0
  269. package/dist/local/store/key-value/batch.js +77 -0
  270. package/dist/local/store/key-value/batch.js.map +1 -0
  271. package/dist/local/store/key-value/device-record.d.ts +23 -0
  272. package/dist/local/store/key-value/device-record.d.ts.map +1 -0
  273. package/dist/local/store/key-value/device-record.js +33 -0
  274. package/dist/local/store/key-value/device-record.js.map +1 -0
  275. package/dist/local/store/key-value/index.d.ts +24 -0
  276. package/dist/local/store/key-value/index.d.ts.map +1 -0
  277. package/dist/local/store/key-value/index.js +8 -0
  278. package/dist/local/store/key-value/index.js.map +1 -0
  279. package/dist/local/store/key-value/realm/index.d.ts +83 -0
  280. package/dist/local/store/key-value/realm/index.d.ts.map +1 -0
  281. package/dist/local/store/key-value/realm/index.js +102 -0
  282. package/dist/local/store/key-value/realm/index.js.map +1 -0
  283. package/dist/local/store/{react-native → key-value}/storage.d.ts +6 -6
  284. package/dist/local/store/key-value/storage.d.ts.map +1 -0
  285. package/dist/local/store/key-value/storage.js.map +1 -0
  286. package/dist/local/store/key-value/transactional-backend.d.ts +50 -0
  287. package/dist/local/store/key-value/transactional-backend.d.ts.map +1 -0
  288. package/dist/local/store/key-value/transactional-backend.js +90 -0
  289. package/dist/local/store/key-value/transactional-backend.js.map +1 -0
  290. package/dist/local/store/key-value/value-key.d.ts +34 -0
  291. package/dist/local/store/key-value/value-key.d.ts.map +1 -0
  292. package/dist/local/store/key-value/value-key.js +83 -0
  293. package/dist/local/store/key-value/value-key.js.map +1 -0
  294. package/dist/local/store/memory/adapter.d.ts +8 -0
  295. package/dist/local/store/memory/adapter.d.ts.map +1 -1
  296. package/dist/local/store/memory/adapter.js +60 -75
  297. package/dist/local/store/memory/adapter.js.map +1 -1
  298. package/dist/local/store/node/adapter.d.ts +74 -130
  299. package/dist/local/store/node/adapter.d.ts.map +1 -1
  300. package/dist/local/store/node/adapter.js +83 -727
  301. package/dist/local/store/node/adapter.js.map +1 -1
  302. package/dist/local/store/node/index.d.ts +8 -6
  303. package/dist/local/store/node/index.d.ts.map +1 -1
  304. package/dist/local/store/node/index.js +3 -7
  305. package/dist/local/store/node/index.js.map +1 -1
  306. package/dist/local/store/node/maintenance.d.ts +5 -0
  307. package/dist/local/store/node/maintenance.d.ts.map +1 -0
  308. package/dist/local/store/node/maintenance.js +7 -0
  309. package/dist/local/store/node/maintenance.js.map +1 -0
  310. package/dist/local/store/node/owner-lock.d.ts +26 -0
  311. package/dist/local/store/node/owner-lock.d.ts.map +1 -0
  312. package/dist/local/store/node/owner-lock.js +88 -0
  313. package/dist/local/store/node/owner-lock.js.map +1 -0
  314. package/dist/local/store/react-native/adapter.d.ts +63 -274
  315. package/dist/local/store/react-native/adapter.d.ts.map +1 -1
  316. package/dist/local/store/react-native/adapter.js +80 -1406
  317. package/dist/local/store/react-native/adapter.js.map +1 -1
  318. package/dist/local/store/react-native/index.d.ts +7 -19
  319. package/dist/local/store/react-native/index.d.ts.map +1 -1
  320. package/dist/local/store/react-native/index.js +2 -7
  321. package/dist/local/store/react-native/index.js.map +1 -1
  322. package/dist/local/store/react-native/maintenance.d.ts +5 -0
  323. package/dist/local/store/react-native/maintenance.d.ts.map +1 -0
  324. package/dist/local/store/react-native/maintenance.js +7 -0
  325. package/dist/local/store/react-native/maintenance.js.map +1 -0
  326. package/dist/local/store/sqlite/better-sqlite3-multiple-ciphers-driver.d.ts +38 -0
  327. package/dist/local/store/sqlite/better-sqlite3-multiple-ciphers-driver.d.ts.map +1 -0
  328. package/dist/local/store/sqlite/better-sqlite3-multiple-ciphers-driver.js +196 -0
  329. package/dist/local/store/sqlite/better-sqlite3-multiple-ciphers-driver.js.map +1 -0
  330. package/dist/local/store/sqlite/database.d.ts +20 -0
  331. package/dist/local/store/sqlite/database.d.ts.map +1 -0
  332. package/dist/local/store/sqlite/database.js +41 -0
  333. package/dist/local/store/sqlite/database.js.map +1 -0
  334. package/dist/local/store/sqlite/driver.d.ts +138 -0
  335. package/dist/local/store/sqlite/driver.d.ts.map +1 -0
  336. package/dist/local/store/sqlite/driver.js +10 -0
  337. package/dist/local/store/sqlite/driver.js.map +1 -0
  338. package/dist/local/store/sqlite/encryption.d.ts +61 -0
  339. package/dist/local/store/sqlite/encryption.d.ts.map +1 -0
  340. package/dist/local/store/sqlite/encryption.js +98 -0
  341. package/dist/local/store/sqlite/encryption.js.map +1 -0
  342. package/dist/local/store/sqlite/errors.d.ts +70 -0
  343. package/dist/local/store/sqlite/errors.d.ts.map +1 -0
  344. package/dist/local/store/sqlite/errors.js +101 -0
  345. package/dist/local/store/sqlite/errors.js.map +1 -0
  346. package/dist/local/store/sqlite/executor.d.ts +22 -0
  347. package/dist/local/store/sqlite/executor.d.ts.map +1 -0
  348. package/dist/local/store/sqlite/executor.js +129 -0
  349. package/dist/local/store/sqlite/executor.js.map +1 -0
  350. package/dist/local/store/sqlite/index.d.ts +20 -0
  351. package/dist/local/store/sqlite/index.d.ts.map +1 -0
  352. package/dist/local/store/sqlite/index.js +18 -0
  353. package/dist/local/store/sqlite/index.js.map +1 -0
  354. package/dist/local/store/sqlite/key-storage/account.d.ts +45 -0
  355. package/dist/local/store/sqlite/key-storage/account.d.ts.map +1 -0
  356. package/dist/local/store/sqlite/key-storage/account.js +125 -0
  357. package/dist/local/store/sqlite/key-storage/account.js.map +1 -0
  358. package/dist/local/store/sqlite/key-storage/contact-identities.d.ts +19 -0
  359. package/dist/local/store/sqlite/key-storage/contact-identities.d.ts.map +1 -0
  360. package/dist/local/store/sqlite/key-storage/contact-identities.js +85 -0
  361. package/dist/local/store/sqlite/key-storage/contact-identities.js.map +1 -0
  362. package/dist/local/store/sqlite/key-storage/context.d.ts +19 -0
  363. package/dist/local/store/sqlite/key-storage/context.d.ts.map +1 -0
  364. package/dist/local/store/sqlite/key-storage/context.js +18 -0
  365. package/dist/local/store/sqlite/key-storage/context.js.map +1 -0
  366. package/dist/local/store/sqlite/key-storage/identity-keys.d.ts +18 -0
  367. package/dist/local/store/sqlite/key-storage/identity-keys.d.ts.map +1 -0
  368. package/dist/local/store/sqlite/key-storage/identity-keys.js +88 -0
  369. package/dist/local/store/sqlite/key-storage/identity-keys.js.map +1 -0
  370. package/dist/local/store/sqlite/key-storage/index.d.ts +108 -0
  371. package/dist/local/store/sqlite/key-storage/index.d.ts.map +1 -0
  372. package/dist/local/store/sqlite/key-storage/index.js +241 -0
  373. package/dist/local/store/sqlite/key-storage/index.js.map +1 -0
  374. package/dist/local/store/sqlite/key-storage/message-records.d.ts +41 -0
  375. package/dist/local/store/sqlite/key-storage/message-records.d.ts.map +1 -0
  376. package/dist/local/store/sqlite/key-storage/message-records.js +133 -0
  377. package/dist/local/store/sqlite/key-storage/message-records.js.map +1 -0
  378. package/dist/local/store/sqlite/key-storage/metadata.d.ts +16 -0
  379. package/dist/local/store/sqlite/key-storage/metadata.d.ts.map +1 -0
  380. package/dist/local/store/sqlite/key-storage/metadata.js +53 -0
  381. package/dist/local/store/sqlite/key-storage/metadata.js.map +1 -0
  382. package/dist/local/store/sqlite/key-storage/one-time-prekeys.d.ts +36 -0
  383. package/dist/local/store/sqlite/key-storage/one-time-prekeys.d.ts.map +1 -0
  384. package/dist/local/store/sqlite/key-storage/one-time-prekeys.js +129 -0
  385. package/dist/local/store/sqlite/key-storage/one-time-prekeys.js.map +1 -0
  386. package/dist/local/store/sqlite/key-storage/session-trust.d.ts +10 -0
  387. package/dist/local/store/sqlite/key-storage/session-trust.d.ts.map +1 -0
  388. package/dist/local/store/sqlite/key-storage/session-trust.js +88 -0
  389. package/dist/local/store/sqlite/key-storage/session-trust.js.map +1 -0
  390. package/dist/local/store/sqlite/key-storage/sessions.d.ts +50 -0
  391. package/dist/local/store/sqlite/key-storage/sessions.d.ts.map +1 -0
  392. package/dist/local/store/sqlite/key-storage/sessions.js +209 -0
  393. package/dist/local/store/sqlite/key-storage/sessions.js.map +1 -0
  394. package/dist/local/store/sqlite/key-storage/signed-prekeys.d.ts +69 -0
  395. package/dist/local/store/sqlite/key-storage/signed-prekeys.d.ts.map +1 -0
  396. package/dist/local/store/sqlite/key-storage/signed-prekeys.js +219 -0
  397. package/dist/local/store/sqlite/key-storage/signed-prekeys.js.map +1 -0
  398. package/dist/local/store/sqlite/maintenance.d.ts +7 -0
  399. package/dist/local/store/sqlite/maintenance.d.ts.map +1 -0
  400. package/dist/local/store/sqlite/maintenance.js +32 -0
  401. package/dist/local/store/sqlite/maintenance.js.map +1 -0
  402. package/dist/local/store/sqlite/migrations.d.ts +31 -0
  403. package/dist/local/store/sqlite/migrations.d.ts.map +1 -0
  404. package/dist/local/store/sqlite/migrations.js +232 -0
  405. package/dist/local/store/sqlite/migrations.js.map +1 -0
  406. package/dist/local/store/{expo → sqlite}/models/ec-one-time-prekey.d.ts +17 -22
  407. package/dist/local/store/sqlite/models/ec-one-time-prekey.d.ts.map +1 -0
  408. package/dist/local/store/{expo → sqlite}/models/ec-one-time-prekey.js +61 -99
  409. package/dist/local/store/sqlite/models/ec-one-time-prekey.js.map +1 -0
  410. package/dist/local/store/{expo → sqlite}/models/ec-signed-prekey.d.ts +22 -25
  411. package/dist/local/store/sqlite/models/ec-signed-prekey.d.ts.map +1 -0
  412. package/dist/local/store/{expo → sqlite}/models/ec-signed-prekey.js +82 -128
  413. package/dist/local/store/sqlite/models/ec-signed-prekey.js.map +1 -0
  414. package/dist/local/store/sqlite/models/identity-key-id.d.ts.map +1 -0
  415. package/dist/local/store/sqlite/models/identity-key-id.js.map +1 -0
  416. package/dist/local/store/{expo → sqlite}/models/index.d.ts +5 -5
  417. package/dist/local/store/sqlite/models/index.d.ts.map +1 -0
  418. package/dist/local/store/{expo → sqlite}/models/index.js +12 -5
  419. package/dist/local/store/sqlite/models/index.js.map +1 -0
  420. package/dist/local/store/{expo → sqlite}/models/kyber-one-time-prekey.d.ts +17 -20
  421. package/dist/local/store/sqlite/models/kyber-one-time-prekey.d.ts.map +1 -0
  422. package/dist/local/store/{expo → sqlite}/models/kyber-one-time-prekey.js +65 -105
  423. package/dist/local/store/sqlite/models/kyber-one-time-prekey.js.map +1 -0
  424. package/dist/local/store/{expo → sqlite}/models/kyber-prekey-used.d.ts +3 -3
  425. package/dist/local/store/sqlite/models/kyber-prekey-used.d.ts.map +1 -0
  426. package/dist/local/store/{expo → sqlite}/models/kyber-prekey-used.js +13 -25
  427. package/dist/local/store/sqlite/models/kyber-prekey-used.js.map +1 -0
  428. package/dist/local/store/{expo → sqlite}/models/kyber-prekey.d.ts +16 -19
  429. package/dist/local/store/sqlite/models/kyber-prekey.d.ts.map +1 -0
  430. package/dist/local/store/{expo → sqlite}/models/kyber-prekey.js +67 -111
  431. package/dist/local/store/sqlite/models/kyber-prekey.js.map +1 -0
  432. package/dist/local/store/sqlite/models/local-identity.d.ts +51 -0
  433. package/dist/local/store/sqlite/models/local-identity.d.ts.map +1 -0
  434. package/dist/local/store/sqlite/models/local-identity.js +150 -0
  435. package/dist/local/store/sqlite/models/local-identity.js.map +1 -0
  436. package/dist/local/store/{expo → sqlite}/models/message-record.d.ts +15 -44
  437. package/dist/local/store/sqlite/models/message-record.d.ts.map +1 -0
  438. package/dist/local/store/{expo → sqlite}/models/message-record.js +43 -109
  439. package/dist/local/store/sqlite/models/message-record.js.map +1 -0
  440. package/dist/local/store/sqlite/models/recipient-identity.d.ts +21 -0
  441. package/dist/local/store/sqlite/models/recipient-identity.d.ts.map +1 -0
  442. package/dist/local/store/sqlite/models/recipient-identity.js +59 -0
  443. package/dist/local/store/sqlite/models/recipient-identity.js.map +1 -0
  444. package/dist/local/store/sqlite/models/replaced-prekeys.d.ts +23 -0
  445. package/dist/local/store/sqlite/models/replaced-prekeys.d.ts.map +1 -0
  446. package/dist/local/store/sqlite/models/replaced-prekeys.js +42 -0
  447. package/dist/local/store/sqlite/models/replaced-prekeys.js.map +1 -0
  448. package/dist/local/store/{expo → sqlite}/models/sender-key.d.ts +22 -23
  449. package/dist/local/store/sqlite/models/sender-key.d.ts.map +1 -0
  450. package/dist/local/store/{expo → sqlite}/models/sender-key.js +66 -94
  451. package/dist/local/store/sqlite/models/sender-key.js.map +1 -0
  452. package/dist/local/store/sqlite/models/sesame-user-record.d.ts +32 -0
  453. package/dist/local/store/sqlite/models/sesame-user-record.d.ts.map +1 -0
  454. package/dist/local/store/sqlite/models/sesame-user-record.js +78 -0
  455. package/dist/local/store/sqlite/models/sesame-user-record.js.map +1 -0
  456. package/dist/local/store/{expo → sqlite}/models/session.d.ts +24 -20
  457. package/dist/local/store/sqlite/models/session.d.ts.map +1 -0
  458. package/dist/local/store/{expo → sqlite}/models/session.js +54 -72
  459. package/dist/local/store/sqlite/models/session.js.map +1 -0
  460. package/dist/local/store/sqlite/models/skipped-sender-key.d.ts +24 -0
  461. package/dist/local/store/sqlite/models/skipped-sender-key.d.ts.map +1 -0
  462. package/dist/local/store/sqlite/models/skipped-sender-key.js +62 -0
  463. package/dist/local/store/sqlite/models/skipped-sender-key.js.map +1 -0
  464. package/dist/local/store/sqlite/op-sqlite-driver.d.ts +14 -0
  465. package/dist/local/store/sqlite/op-sqlite-driver.d.ts.map +1 -0
  466. package/dist/local/store/sqlite/op-sqlite-driver.js +180 -0
  467. package/dist/local/store/sqlite/op-sqlite-driver.js.map +1 -0
  468. package/dist/local/store/sqlite/open-store.d.ts +83 -0
  469. package/dist/local/store/sqlite/open-store.d.ts.map +1 -0
  470. package/dist/local/store/sqlite/open-store.js +177 -0
  471. package/dist/local/store/sqlite/open-store.js.map +1 -0
  472. package/dist/local/store/sqlite/schema.d.ts +102 -0
  473. package/dist/local/store/sqlite/schema.d.ts.map +1 -0
  474. package/dist/local/store/sqlite/schema.js +61 -0
  475. package/dist/local/store/sqlite/schema.js.map +1 -0
  476. package/dist/local/store/sqlite/store.d.ts +199 -0
  477. package/dist/local/store/sqlite/store.d.ts.map +1 -0
  478. package/dist/local/store/sqlite/store.js +494 -0
  479. package/dist/local/store/sqlite/store.js.map +1 -0
  480. package/dist/local/store/sqlite/web/driver.d.ts +50 -0
  481. package/dist/local/store/sqlite/web/driver.d.ts.map +1 -0
  482. package/dist/local/store/sqlite/web/driver.js +169 -0
  483. package/dist/local/store/sqlite/web/driver.js.map +1 -0
  484. package/dist/local/store/sqlite/web/protocol.d.ts +80 -0
  485. package/dist/local/store/sqlite/web/protocol.d.ts.map +1 -0
  486. package/dist/local/store/sqlite/web/protocol.js +13 -0
  487. package/dist/local/store/sqlite/web/protocol.js.map +1 -0
  488. package/dist/local/store/sqlite/web/sqlite3mc/sqlite3.mjs +14526 -0
  489. package/dist/local/store/sqlite/web/sqlite3mc/sqlite3.wasm +0 -0
  490. package/dist/local/store/sqlite/web/worker.d.ts +36 -0
  491. package/dist/local/store/sqlite/web/worker.d.ts.map +1 -0
  492. package/dist/local/store/sqlite/web/worker.js +616 -0
  493. package/dist/local/store/sqlite/web/worker.js.map +1 -0
  494. package/dist/local/store/web/adapter.d.ts +5 -14
  495. package/dist/local/store/web/adapter.d.ts.map +1 -1
  496. package/dist/local/store/web/adapter.js +119 -106
  497. package/dist/local/store/web/adapter.js.map +1 -1
  498. package/dist/local/store/web/device-record.d.ts +23 -0
  499. package/dist/local/store/web/device-record.d.ts.map +1 -0
  500. package/dist/local/store/web/device-record.js +31 -0
  501. package/dist/local/store/web/device-record.js.map +1 -0
  502. package/dist/local/store/web-sqlite/adapter.d.ts +98 -0
  503. package/dist/local/store/web-sqlite/adapter.d.ts.map +1 -0
  504. package/dist/local/store/web-sqlite/adapter.js +151 -0
  505. package/dist/local/store/web-sqlite/adapter.js.map +1 -0
  506. package/dist/local/store/web-sqlite/index.d.ts +14 -0
  507. package/dist/local/store/web-sqlite/index.d.ts.map +1 -0
  508. package/dist/local/store/web-sqlite/index.js +3 -0
  509. package/dist/local/store/web-sqlite/index.js.map +1 -0
  510. package/dist/local/store/web-sqlite/maintenance.d.ts +5 -0
  511. package/dist/local/store/web-sqlite/maintenance.d.ts.map +1 -0
  512. package/dist/local/store/web-sqlite/maintenance.js +7 -0
  513. package/dist/local/store/web-sqlite/maintenance.js.map +1 -0
  514. package/dist/local/store/web-sqlite/store-locks.d.ts +33 -0
  515. package/dist/local/store/web-sqlite/store-locks.d.ts.map +1 -0
  516. package/dist/local/store/web-sqlite/store-locks.js +60 -0
  517. package/dist/local/store/web-sqlite/store-locks.js.map +1 -0
  518. package/dist/local/vault/electron-safe-storage.d.ts +45 -0
  519. package/dist/local/vault/electron-safe-storage.d.ts.map +1 -0
  520. package/dist/local/vault/electron-safe-storage.js +212 -0
  521. package/dist/local/vault/electron-safe-storage.js.map +1 -0
  522. package/dist/local/vault/index.d.ts +4 -2
  523. package/dist/local/vault/index.d.ts.map +1 -1
  524. package/dist/local/vault/indexed-db.d.ts +37 -0
  525. package/dist/local/vault/indexed-db.d.ts.map +1 -0
  526. package/dist/local/vault/indexed-db.js +102 -0
  527. package/dist/local/vault/indexed-db.js.map +1 -0
  528. package/dist/local/vault/react-native-keychain.d.ts +12 -0
  529. package/dist/local/vault/react-native-keychain.d.ts.map +1 -0
  530. package/dist/local/vault/react-native-keychain.js +71 -0
  531. package/dist/local/vault/react-native-keychain.js.map +1 -0
  532. package/dist/local/vault/require.d.ts +10 -0
  533. package/dist/local/vault/require.d.ts.map +1 -0
  534. package/dist/local/vault/require.js +16 -0
  535. package/dist/local/vault/require.js.map +1 -0
  536. package/dist/logger.d.ts.map +1 -1
  537. package/dist/logger.js +2 -1
  538. package/dist/logger.js.map +1 -1
  539. package/dist/media/index.d.ts.map +1 -1
  540. package/dist/media/index.js +2 -1
  541. package/dist/media/index.js.map +1 -1
  542. package/dist/profile/contact-state.d.ts.map +1 -1
  543. package/dist/profile/contact-state.js +2 -4
  544. package/dist/profile/contact-state.js.map +1 -1
  545. package/dist/profile/index.d.ts +0 -1
  546. package/dist/profile/index.d.ts.map +1 -1
  547. package/dist/profile/index.js +0 -2
  548. package/dist/profile/index.js.map +1 -1
  549. package/dist/profile/profile-key.d.ts +16 -11
  550. package/dist/profile/profile-key.d.ts.map +1 -1
  551. package/dist/profile/profile-key.js +29 -29
  552. package/dist/profile/profile-key.js.map +1 -1
  553. package/dist/profile/update-service.d.ts +6 -0
  554. package/dist/profile/update-service.d.ts.map +1 -1
  555. package/dist/profile/update-service.js +3 -1
  556. package/dist/profile/update-service.js.map +1 -1
  557. package/dist/remote/object-store/validation.d.ts.map +1 -1
  558. package/dist/remote/object-store/validation.js +2 -1
  559. package/dist/remote/object-store/validation.js.map +1 -1
  560. package/dist/remote/relay/memory/adapter.d.ts +2 -3
  561. package/dist/remote/relay/memory/adapter.d.ts.map +1 -1
  562. package/dist/remote/relay/memory/adapter.js +22 -30
  563. package/dist/remote/relay/memory/adapter.js.map +1 -1
  564. package/dist/remote/relay/memory/failures.d.ts.map +1 -1
  565. package/dist/remote/relay/memory/failures.js +2 -1
  566. package/dist/remote/relay/memory/failures.js.map +1 -1
  567. package/dist/remote/relay/memory/group-server.d.ts +5 -1
  568. package/dist/remote/relay/memory/group-server.d.ts.map +1 -1
  569. package/dist/remote/relay/memory/group-server.js +11 -1
  570. package/dist/remote/relay/memory/group-server.js.map +1 -1
  571. package/dist/safety/url.d.ts.map +1 -1
  572. package/dist/safety/url.js +21 -26
  573. package/dist/safety/url.js.map +1 -1
  574. package/dist/types/api.d.ts +15 -2
  575. package/dist/types/api.d.ts.map +1 -1
  576. package/dist/types/errors.d.ts +97 -1
  577. package/dist/types/errors.d.ts.map +1 -1
  578. package/dist/types/errors.js +105 -1
  579. package/dist/types/errors.js.map +1 -1
  580. package/dist/types/session.d.ts.map +1 -1
  581. package/dist/types/session.js +2 -1
  582. package/dist/types/session.js.map +1 -1
  583. package/dist/utils/retry.d.ts +2 -0
  584. package/dist/utils/retry.d.ts.map +1 -1
  585. package/dist/utils/retry.js +4 -2
  586. package/dist/utils/retry.js.map +1 -1
  587. package/docs/ASSURANCE.md +80 -8
  588. package/docs/CLIENT_COMPOSITION.md +1 -2
  589. package/docs/DEVIATIONS.md +1 -1
  590. package/docs/ERROR_HANDLING.md +6 -0
  591. package/docs/GETTING_STARTED.md +1 -2
  592. package/docs/PACKAGE_SURFACE.md +29 -11
  593. package/docs/RECIPES.md +1 -2
  594. package/examples/browser/index.html +1 -1
  595. package/local/store/README.md +117 -37
  596. package/local/store/expo/README.md +67 -47
  597. package/local/store/key-value/README.md +278 -0
  598. package/local/store/node/README.md +206 -46
  599. package/local/store/react-native/README.md +120 -61
  600. package/local/store/web/README.md +9 -0
  601. package/local/store/web-sqlite/README.md +202 -0
  602. package/local/vault/README.md +115 -2
  603. package/package.json +42 -23
  604. package/profile/README.md +9 -11
  605. package/remote/README.md +1 -2
  606. package/dist/local/store/expo/database-key.d.ts +0 -142
  607. package/dist/local/store/expo/database-key.d.ts.map +0 -1
  608. package/dist/local/store/expo/database-key.js +0 -312
  609. package/dist/local/store/expo/database-key.js.map +0 -1
  610. package/dist/local/store/expo/db.d.ts +0 -95
  611. package/dist/local/store/expo/db.d.ts.map +0 -1
  612. package/dist/local/store/expo/db.js +0 -147
  613. package/dist/local/store/expo/db.js.map +0 -1
  614. package/dist/local/store/expo/key-storage.d.ts +0 -429
  615. package/dist/local/store/expo/key-storage.d.ts.map +0 -1
  616. package/dist/local/store/expo/key-storage.js +0 -1361
  617. package/dist/local/store/expo/key-storage.js.map +0 -1
  618. package/dist/local/store/expo/models/ec-one-time-prekey.d.ts.map +0 -1
  619. package/dist/local/store/expo/models/ec-one-time-prekey.js.map +0 -1
  620. package/dist/local/store/expo/models/ec-signed-prekey.d.ts.map +0 -1
  621. package/dist/local/store/expo/models/ec-signed-prekey.js.map +0 -1
  622. package/dist/local/store/expo/models/identity-key-id.d.ts.map +0 -1
  623. package/dist/local/store/expo/models/identity-key-id.js.map +0 -1
  624. package/dist/local/store/expo/models/index.d.ts.map +0 -1
  625. package/dist/local/store/expo/models/index.js.map +0 -1
  626. package/dist/local/store/expo/models/kyber-one-time-prekey.d.ts.map +0 -1
  627. package/dist/local/store/expo/models/kyber-one-time-prekey.js.map +0 -1
  628. package/dist/local/store/expo/models/kyber-prekey-used.d.ts.map +0 -1
  629. package/dist/local/store/expo/models/kyber-prekey-used.js.map +0 -1
  630. package/dist/local/store/expo/models/kyber-prekey.d.ts.map +0 -1
  631. package/dist/local/store/expo/models/kyber-prekey.js.map +0 -1
  632. package/dist/local/store/expo/models/local-identity.d.ts +0 -52
  633. package/dist/local/store/expo/models/local-identity.d.ts.map +0 -1
  634. package/dist/local/store/expo/models/local-identity.js +0 -166
  635. package/dist/local/store/expo/models/local-identity.js.map +0 -1
  636. package/dist/local/store/expo/models/message-record.d.ts.map +0 -1
  637. package/dist/local/store/expo/models/message-record.js.map +0 -1
  638. package/dist/local/store/expo/models/recipient-identity.d.ts +0 -21
  639. package/dist/local/store/expo/models/recipient-identity.d.ts.map +0 -1
  640. package/dist/local/store/expo/models/recipient-identity.js +0 -66
  641. package/dist/local/store/expo/models/recipient-identity.js.map +0 -1
  642. package/dist/local/store/expo/models/replaced-prekey-utils.d.ts +0 -33
  643. package/dist/local/store/expo/models/replaced-prekey-utils.d.ts.map +0 -1
  644. package/dist/local/store/expo/models/replaced-prekey-utils.js +0 -54
  645. package/dist/local/store/expo/models/replaced-prekey-utils.js.map +0 -1
  646. package/dist/local/store/expo/models/sender-key.d.ts.map +0 -1
  647. package/dist/local/store/expo/models/sender-key.js.map +0 -1
  648. package/dist/local/store/expo/models/session.d.ts.map +0 -1
  649. package/dist/local/store/expo/models/session.js.map +0 -1
  650. package/dist/local/store/expo/schema.d.ts +0 -1917
  651. package/dist/local/store/expo/schema.d.ts.map +0 -1
  652. package/dist/local/store/expo/schema.js +0 -197
  653. package/dist/local/store/expo/schema.js.map +0 -1
  654. package/dist/local/store/node/database-encryption.d.ts +0 -109
  655. package/dist/local/store/node/database-encryption.d.ts.map +0 -1
  656. package/dist/local/store/node/database-encryption.js +0 -202
  657. package/dist/local/store/node/database-encryption.js.map +0 -1
  658. package/dist/local/store/node/database-file-commit.d.ts +0 -8
  659. package/dist/local/store/node/database-file-commit.d.ts.map +0 -1
  660. package/dist/local/store/node/database-file-commit.js +0 -62
  661. package/dist/local/store/node/database-file-commit.js.map +0 -1
  662. package/dist/local/store/node/database-key.d.ts +0 -129
  663. package/dist/local/store/node/database-key.d.ts.map +0 -1
  664. package/dist/local/store/node/database-key.js +0 -293
  665. package/dist/local/store/node/database-key.js.map +0 -1
  666. package/dist/local/store/node/database-lock.d.ts +0 -8
  667. package/dist/local/store/node/database-lock.d.ts.map +0 -1
  668. package/dist/local/store/node/database-lock.js +0 -44
  669. package/dist/local/store/node/database-lock.js.map +0 -1
  670. package/dist/local/store/node/database.d.ts +0 -226
  671. package/dist/local/store/node/database.d.ts.map +0 -1
  672. package/dist/local/store/node/database.js +0 -813
  673. package/dist/local/store/node/database.js.map +0 -1
  674. package/dist/local/store/react-native/backend-conformance.d.ts.map +0 -1
  675. package/dist/local/store/react-native/backend-conformance.js.map +0 -1
  676. package/dist/local/store/react-native/reference-backend.d.ts +0 -43
  677. package/dist/local/store/react-native/reference-backend.d.ts.map +0 -1
  678. package/dist/local/store/react-native/reference-backend.js +0 -178
  679. package/dist/local/store/react-native/reference-backend.js.map +0 -1
  680. package/dist/local/store/react-native/storage.d.ts.map +0 -1
  681. package/dist/local/store/react-native/storage.js.map +0 -1
  682. package/dist/profile/storage.d.ts +0 -61
  683. package/dist/profile/storage.d.ts.map +0 -1
  684. package/dist/profile/storage.js +0 -145
  685. package/dist/profile/storage.js.map +0 -1
  686. /package/dist/local/store/{react-native → key-value}/storage.js +0 -0
  687. /package/dist/local/store/{expo → sqlite}/models/identity-key-id.d.ts +0 -0
  688. /package/dist/local/store/{expo → sqlite}/models/identity-key-id.js +0 -0
@@ -1,1424 +1,98 @@
1
1
  /**
2
- * React Native Storage Adapter (Bare Workflow)
2
+ * React Native SQLite Signal Protocol Store
3
3
  *
4
- * Storage adapter for React Native applications without Expo.
5
- * Uses:
6
- * - a caller-provided persistent key-value backend
7
- * - expo-crypto for secure random number generation. A bare React Native app
8
- * must install Expo modules for expo-crypto to load.
9
- * - Signal Protocol crypto module for AES-256-GCM encryption. It uses Web Crypto
10
- * when `crypto.subtle` exists and the bundled Noble AES otherwise.
11
- *
12
- * Security Considerations:
13
- * - All sensitive data encrypted with AES-256-GCM (128-bit auth tag)
14
- * - Database encryption key stored in the provided key-value backend
15
- * - For production apps, keep the database key in a platform secret vault
16
- *
17
- * @example
18
- * ```typescript
19
- * const keyValueStorage = yourPersistentKeyValueStorage;
20
- * const storage = await ReactNativeSignalProtocolStore.create({ storage: keyValueStorage });
21
- *
22
- * // Store identity key
23
- * await storage.storeIdentityKey(keyPair);
24
- * ```
4
+ * The SDK owns the database file. One call opens it in the op-sqlite default
5
+ * location, gets or creates its key through the local secret vault, applies
6
+ * the SDK migrations, and returns the store.
25
7
  */
26
- import * as Crypto from 'expo-crypto';
27
- import * as SignalProtocolCrypto from '../../../internal/crypto/index.js';
28
- import { MAX_UNACKNOWLEDGED_SESSION_AGE_MS } from '../../../types/protocol-config.js';
29
- import { assertCurrentSessionRecord } from '../../../types/session.js';
30
- import { acceptContactIdentityRotation as acceptRotation, createUnverifiedContactIdentityRecord, evaluateContactIdentityCandidate, validateContactIdentityRecord, verifyContactIdentityRecord, } from '../../../keys/identity.js';
31
- import { IdentityKeyChange, StorageQuotaExceededError } from '../../../types/index.js';
32
- import { deserializeSessionRecord, serializeSessionRecord } from '../session-codec.js';
33
- import { parseReceivedContent } from '../received-content.js';
34
- import { createKyberPreKeyState, createKyberPreKeyInstanceId, getCurrentKyberPreKey, getRetainedKyberPreKey, recordKyberPreKeyUse, recordKyberPreKeyUseById, retainKyberPreKey, } from '../kyber-prekey-lifecycle.js';
35
- const STORAGE_KEYS = {
36
- DATABASE_KEY: '@signal:databaseKey',
37
- IDENTITY_KEY_PREFIX: '@signal:identity:keyPair:',
38
- REGISTRATION_ID_PREFIX: '@signal:metadata:registrationId:',
39
- METADATA_PREFIX: '@signal:metadata:value:',
40
- CONTACT_PREFIX: '@signal:contacts:',
41
- CONTACT_V1_PREFIX: '@signal:contacts:v1:',
42
- PREKEY_PREFIX: '@signal:prekeys:',
43
- SESSION_PREFIX: '@signal:sessions:',
44
- SESAME_USER_PREFIX: '@signal:sesame:user:',
45
- SENDER_KEY_RECORD_PREFIX: '@signal:sender-key-record:',
46
- // Maps an opaque `senderKeyId` to the record that holds it. A received group
47
- // message names its sender key by that id and nothing else. This backend is
48
- // a flat key-value store with no secondary indexes, so the reverse lookup
49
- // has to be a stored pointer. The pointer value is a record key, not key
50
- // material. The ids in it already travel unencrypted on the wire.
51
- //
52
- // The pointer is scoped by sender, not by id alone. A sender chooses its own
53
- // id and announces it in a distribution message. Two senders can therefore
54
- // name the same one, by accident or deliberately, after reading a shared
55
- // group's distribution. A single global slot per id would let the second
56
- // writer silently take over the first's pointer. Every subsequent message
57
- // from the first sender would then fail to resolve.
58
- // See `getSenderKeyIdPointerKey`.
59
- SENDER_KEY_ID_INDEX_PREFIX: '@signal:sender-key-id:',
60
- SKIPPED_SENDER_KEY_PREFIX: '@signal:skipped-sender-key:',
61
- MESSAGE_RECORD_PREFIX: '@signal:message-record:',
62
- SECURITY_EVENTS: '@signal:security-events',
63
- };
64
- /**
65
- * Escape a value so it cannot contain the `:` that joins composite keys.
66
- *
67
- * Composite keys in this backend are `:`-joined strings. The components are
68
- * identifiers the adapter does not get to choose. They are group IDs, sender
69
- * key IDs read straight off the wire, and user IDs handed over by the host
70
- * application's identify hook.
71
- *
72
- * None of them are validated, and a tenant-scoped `tenant:alice` is an
73
- * ordinary thing for a host to produce. So "components contain no `:`" is an
74
- * assumption rather than a fact, and the encoding has to make it one.
75
- *
76
- * `%` is escaped first so the escape character itself round-trips: without it
77
- * a literal `%3A` in an identifier would unescape into a separator. Values
78
- * containing neither character escape to themselves, so an existing
79
- * deployment whose IDs are already well behaved keeps the keys it has.
80
- */
81
- function escapeKeyComponent(value) {
82
- return value.replace(/%/g, '%25').replace(/:/g, '%3A');
8
+ import { ReactNativeKeychainSignalProtocolSecretVault } from '../../vault/react-native-keychain.js';
9
+ import { createOpSqliteDriver } from '../sqlite/op-sqlite-driver.js';
10
+ import { openSqliteStore, resetSqliteStore, } from '../sqlite/open-store.js';
11
+ import { SqliteSignalProtocolStore } from '../sqlite/store.js';
12
+ /** The database file name when the options name none. */
13
+ const DEFAULT_DATABASE_NAME = 'open-e2ee-signal-protocol.db';
14
+ function storeOptions(options) {
15
+ return {
16
+ ...options,
17
+ driver: createOpSqliteDriver(),
18
+ name: options.name ?? DEFAULT_DATABASE_NAME,
19
+ vault: options.vault ?? new ReactNativeKeychainSignalProtocolSecretVault(),
20
+ };
83
21
  }
84
- /** Inverse of {@link escapeKeyComponent}. It unescapes in the opposite order. */
85
- function unescapeKeyComponent(value) {
86
- return value.replace(/%3A/g, ':').replace(/%25/g, '%');
22
+ /** The database of each open store, for the helpers of this entry. */
23
+ const databases = new WeakMap();
24
+ /** The executor of an open store. Not exported from the entry. */
25
+ export function reactNativeStoreDatabase(store) {
26
+ const database = databases.get(store);
27
+ if (!database)
28
+ throw new TypeError('Open the store with reactNativeStore().');
29
+ return database;
87
30
  }
88
31
  /**
89
- * A write the injected backend rejects for want of space fails with an error
90
- * named `QuotaExceededError`. Checked by name rather than instanceof, as in
91
- * the web adapter. The backend is application-supplied, so no error class is
92
- * shared with it, and the name is the documented signal.
93
- */
94
- function isQuotaExceededError(error) {
95
- return (typeof error === 'object' &&
96
- error !== null &&
97
- error.name === 'QuotaExceededError');
98
- }
99
- function mapQuotaFailure(operation, error) {
100
- if (!isQuotaExceededError(error))
101
- return error;
102
- // The failure is Error-shaped by the name check above, but not always
103
- // instanceof Error: a backend may surface a platform exception object.
104
- return new StorageQuotaExceededError(operation, error);
105
- }
106
- /**
107
- * Rebinds every method of the store so a QuotaExceededError from the
108
- * injected backend crosses the adapter boundary as the typed
109
- * StorageQuotaExceededError. Quota exhaustion can surface from any setItem
110
- * or atomicWrite the backend runs. The mapping therefore lives at this one
111
- * seam, instead of inside each of the adapter's write paths. A method added
112
- * later is covered without a wrapper of its own. The backend contract
113
- * commits nothing from a rejected write, so the typed error always means
114
- * the write did not persist.
115
- *
116
- * Wrapping runs inside the private constructor, and `create` is the only
117
- * construction path, so every caller-visible instance is wrapped before any
118
- * method can run.
119
- */
120
- function mapQuotaFailuresAtBoundary(store) {
121
- const methods = new Map();
122
- for (let prototype = Object.getPrototypeOf(store); prototype !== null && prototype !== Object.prototype; prototype = Object.getPrototypeOf(prototype)) {
123
- for (const name of Object.getOwnPropertyNames(prototype)) {
124
- // First found wins: the walk goes most-derived first.
125
- if (name === 'constructor' || methods.has(name))
126
- continue;
127
- const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
128
- if (typeof descriptor?.value !== 'function')
129
- continue;
130
- methods.set(name, descriptor.value);
131
- }
132
- }
133
- for (const [name, method] of methods) {
134
- store[name] = function mapped(...args) {
135
- let result;
136
- try {
137
- result = method.apply(this, args);
138
- }
139
- catch (error) {
140
- throw mapQuotaFailure(name, error);
141
- }
142
- // Duck-typed rather than instanceof Promise so a cross-realm
143
- // promise or plain thenable from an override maps too.
144
- if (result !== null &&
145
- typeof result === 'object' &&
146
- typeof result.then === 'function') {
147
- return Promise.resolve(result).catch((error) => {
148
- throw mapQuotaFailure(name, error);
149
- });
150
- }
151
- return result;
152
- };
153
- }
154
- }
155
- /**
156
- * React Native storage adapter implementation
157
- *
158
- * Provides secure storage for Signal Protocol keys using an injected
159
- * React Native key-value backend and expo-crypto.
32
+ * Local Signal Protocol state for bare React Native, in an SDK-owned SQLCipher
33
+ * database on op-sqlite.
160
34
  *
161
- * @example
162
- * ```typescript
163
- * const keyValueStorage = yourPersistentKeyValueStorage;
164
- * const storage = await ReactNativeSignalProtocolStore.create({ storage: keyValueStorage });
35
+ * Open it with {@link reactNativeStore}. The store holds the database
36
+ * file until {@link ReactNativeSignalProtocolStore.close}. A second open
37
+ * of the same name in the process fails with `INVALID_STATE`.
165
38
  *
166
- * // Store identity key
167
- * await storage.storeIdentityKey(keyPair);
39
+ * Every table holds material that must not leave the device, including the
40
+ * group sender keys. SQLCipher encrypts the whole file, so the database key
41
+ * in the vault is the only thing that protects it.
168
42
  *
169
- * // Get identity key
170
- * const keyPair = await storage.getIdentityKey();
171
- * ```
43
+ * @category Key Storage
44
+ * @see {@link SignalProtocolLocalStore} for interface documentation
172
45
  */
173
- export class ReactNativeSignalProtocolStore {
174
- databaseKey = null;
175
- initialized = false;
176
- storageBackend;
177
- constructor(options) {
178
- this.storageBackend = options.storage;
179
- mapQuotaFailuresAtBoundary(this);
180
- }
181
- static async create(options) {
182
- const store = new ReactNativeSignalProtocolStore(options);
183
- await store.initialize();
184
- return store;
185
- }
186
- // ============================================================================
187
- // Initialization
188
- // ============================================================================
189
- /**
190
- * Initialize the storage adapter
191
- *
192
- * - Loads or generates database encryption key
193
- * - Stores key in the configured key-value backend
194
- */
195
- async initialize() {
196
- if (this.initialized) {
197
- return;
198
- }
199
- // Get or generate database encryption key
200
- const storedKey = await this.storageBackend.getItem(STORAGE_KEYS.DATABASE_KEY);
201
- if (storedKey) {
202
- // Decode from base64
203
- this.databaseKey = this.base64ToUint8Array(storedKey);
204
- }
205
- else {
206
- // Generate new 32-byte key
207
- this.databaseKey = Crypto.getRandomBytes(32);
208
- // Store as base64
209
- await this.storageBackend.setItem(STORAGE_KEYS.DATABASE_KEY, this.uint8ArrayToBase64(this.databaseKey));
210
- console.warn('[ReactNativeSignalProtocolStore] Database encryption key stored in the configured React Native storage backend. ' +
211
- 'For production apps, configure a platform secret vault for database-key custody.');
212
- }
213
- this.initialized = true;
214
- }
215
- /**
216
- * Get the database encryption key
217
- *
218
- * @returns 32-byte AES-256 key
219
- * @throws Error if not initialized
220
- */
221
- async getDatabaseKey() {
222
- this.ensureInitialized();
223
- return this.databaseKey;
224
- }
225
- // ============================================================================
226
- // Identity Key Management - Own Keys
227
- // ============================================================================
228
- async storeIdentityKey(keyPair, identityType) {
229
- this.ensureInitialized();
230
- const encrypted = await this.encrypt(JSON.stringify(keyPair));
231
- await this.storageBackend.setItem(this.getIdentityKeyStorageKey(identityType), encrypted);
232
- }
233
- async getIdentityKey(identityType) {
234
- this.ensureInitialized();
235
- const encrypted = await this.storageBackend.getItem(this.getIdentityKeyStorageKey(identityType));
236
- if (!encrypted)
237
- return null;
238
- const decrypted = await this.decrypt(encrypted);
239
- return JSON.parse(decrypted);
240
- }
241
- async hasIdentityKey(identityType) {
242
- this.ensureInitialized();
243
- const key = await this.storageBackend.getItem(this.getIdentityKeyStorageKey(identityType));
244
- return key !== null;
245
- }
246
- async getLocalRegistrationId(identityType) {
247
- this.ensureInitialized();
248
- const id = await this.storageBackend.getItem(this.getRegistrationIdStorageKey(identityType));
249
- if (!id)
250
- return 0;
251
- return parseInt(id, 10);
252
- }
253
- async setLocalRegistrationId(id, identityType) {
254
- this.ensureInitialized();
255
- await this.storageBackend.setItem(this.getRegistrationIdStorageKey(identityType), id.toString());
256
- }
257
- // ============================================================================
258
- // Identity Verification - Contact Keys (TOFU)
259
- // ============================================================================
260
- async saveContactIdentity(address, identity, identityType, suppliedCommitment) {
261
- this.ensureInitialized();
262
- const storageKey = this.getContactStorageKey(address, identityType);
263
- const existing = await this.readContactRecord(address, identityType);
264
- const status = evaluateContactIdentityCandidate(existing, identity, suppliedCommitment);
265
- if (status === 'NEW') {
266
- await this.writeContactRecord(storageKey, createUnverifiedContactIdentityRecord(identity, Date.now()));
267
- return IdentityKeyChange.NEW_IDENTITY;
268
- }
269
- if (status === 'MATCH')
270
- return IdentityKeyChange.UNCHANGED;
271
- if (status === 'ROLLBACK')
272
- return IdentityKeyChange.ROLLBACK;
273
- return IdentityKeyChange.CHANGED;
274
- }
275
- async getContactIdentity(address, identityType) {
276
- this.ensureInitialized();
277
- return await this.readContactRecord(address, identityType);
278
- }
279
- async acceptContactIdentityRotation(address, identity, identityType, suppliedCommitment) {
280
- return await this.acceptContactIdentityRotationAndDeleteSessions(address, identity, identityType, suppliedCommitment);
281
- }
282
- async acceptContactIdentityRotationAndDeleteSessions(address, identity, identityType, suppliedCommitment) {
283
- this.ensureInitialized();
284
- const contactKey = this.getContactStorageKey(address, identityType);
285
- const existingValue = await this.storageBackend.getItem(contactKey);
286
- if (!existingValue)
287
- throw new Error('Cannot rotate an unseen identity');
288
- const existing = JSON.parse(await this.decrypt(existingValue));
289
- validateContactIdentityRecord(existing);
290
- const replacement = acceptRotation(existing, identity, Date.now(), suppliedCommitment);
291
- validateContactIdentityRecord(replacement);
292
- await this.storageBackend.atomicWrite([
293
- { type: 'check', key: contactKey, expectedValue: existingValue },
294
- { type: 'set', key: contactKey, value: await this.encrypt(JSON.stringify(replacement)) },
295
- {
296
- type: 'removeSessionsForUser',
297
- keyPrefix: STORAGE_KEYS.SESSION_PREFIX,
298
- userId: address.userId,
299
- },
300
- ]);
301
- return replacement;
302
- }
303
- async verifyContactIdentity(address, identity, identityType, suppliedCommitment) {
304
- this.ensureInitialized();
305
- const contactKey = this.getContactStorageKey(address, identityType);
306
- const existingValue = await this.storageBackend.getItem(contactKey);
307
- const existing = existingValue
308
- ? JSON.parse(await this.decrypt(existingValue))
309
- : null;
310
- if (!existing)
311
- throw new Error('Cannot verify an unseen identity');
312
- validateContactIdentityRecord(existing);
313
- const verified = verifyContactIdentityRecord(existing, identity, Date.now(), suppliedCommitment);
314
- await this.storageBackend.atomicWrite([
315
- { type: 'check', key: contactKey, expectedValue: existingValue },
316
- { type: 'set', key: contactKey, value: await this.encrypt(JSON.stringify(verified)) },
317
- ]);
318
- return verified;
319
- }
320
- async isTrustedIdentity(address, identity, _direction, identityType) {
321
- this.ensureInitialized();
322
- const status = evaluateContactIdentityCandidate(await this.readContactRecord(address, identityType), identity);
323
- return status === 'NEW' || status === 'MATCH';
324
- }
325
- // ============================================================================
326
- // PreKey Management
327
- // ============================================================================
328
- async storeEcSignedPreKey(signedPreKey, identityType) {
329
- this.ensureInitialized();
330
- // Get existing prekeys and add/update the new one
331
- const allPrekeys = await this.getAllEcSignedPreKeys(identityType);
332
- const existingIndex = allPrekeys.findIndex((k) => k.keyId === signedPreKey.keyId);
333
- if (existingIndex >= 0) {
334
- allPrekeys[existingIndex] = signedPreKey;
335
- }
336
- else {
337
- allPrekeys.push(signedPreKey);
338
- }
339
- // Cleanup expired prekeys
340
- const cutoff = Date.now() - MAX_UNACKNOWLEDGED_SESSION_AGE_MS;
341
- const newest = allPrekeys.reduce((a, b) => (a.keyId > b.keyId ? a : b));
342
- const filtered = allPrekeys.filter((k) => k.keyId === newest.keyId || (k.timestamp && k.timestamp > cutoff));
343
- const encrypted = await this.encrypt(JSON.stringify(filtered));
344
- await this.storageBackend.setItem(this.getSignedPreKeyStorageKey(identityType), encrypted);
345
- }
346
- async getEcSignedPreKey(keyId, identityType) {
347
- this.ensureInitialized();
348
- const allPrekeys = await this.getAllEcSignedPreKeys(identityType);
349
- if (allPrekeys.length === 0)
350
- return null;
351
- if (keyId !== undefined) {
352
- // Look up by specific keyId
353
- return allPrekeys.find((k) => k.keyId === keyId) ?? null;
354
- }
355
- // Return the most recent (highest keyId)
356
- return allPrekeys.reduce((latest, current) => current.keyId > latest.keyId ? current : latest);
357
- }
358
- async getAllEcSignedPreKeys(identityType) {
359
- this.ensureInitialized();
360
- const encrypted = await this.storageBackend.getItem(this.getSignedPreKeyStorageKey(identityType));
361
- if (!encrypted) {
362
- return [];
363
- }
364
- const decrypted = await this.decrypt(encrypted);
365
- return JSON.parse(decrypted);
366
- }
367
- async removeEcSignedPreKey(keyId, identityType) {
368
- this.ensureInitialized();
369
- const allPrekeys = await this.getAllEcSignedPreKeys(identityType);
370
- const filtered = allPrekeys.filter((k) => k.keyId !== keyId);
371
- const encrypted = await this.encrypt(JSON.stringify(filtered));
372
- await this.storageBackend.setItem(this.getSignedPreKeyStorageKey(identityType), encrypted);
373
- }
374
- async storeEcOneTimePreKeys(prekeys, identityType) {
375
- this.ensureInitialized();
376
- const existing = await this.getEcOneTimePreKeys(identityType);
377
- await this.storageBackend.setItem(this.getEcOneTimePreKeyStorageKey(identityType), await this.encrypt(JSON.stringify([...existing, ...prekeys])));
378
- }
379
- async getEcOneTimePreKeys(identityType) {
380
- this.ensureInitialized();
381
- const encrypted = await this.storageBackend.getItem(this.getEcOneTimePreKeyStorageKey(identityType));
382
- if (!encrypted)
383
- return [];
384
- const decrypted = await this.decrypt(encrypted);
385
- return JSON.parse(decrypted);
386
- }
387
- async removeEcOneTimePreKey(preKeyId, identityType) {
388
- this.ensureInitialized();
389
- const prekeys = await this.getEcOneTimePreKeys(identityType);
390
- const filtered = prekeys.filter((pk) => pk.keyId !== preKeyId);
391
- await this.storageBackend.setItem(this.getEcOneTimePreKeyStorageKey(identityType), await this.encrypt(JSON.stringify(filtered)));
392
- }
393
- async storeKyberPreKey(kyberPreKey, identityType) {
394
- this.ensureInitialized();
395
- const it = identityType ?? 'aci';
396
- const storageKey = this.getKyberPreKeyStorageKey(it);
397
- const stored = await this.storageBackend.getItem(storageKey);
398
- const state = stored
399
- ? JSON.parse(await this.decrypt(stored))
400
- : createKyberPreKeyState();
401
- const instanceId = await createKyberPreKeyInstanceId();
402
- if (!retainKyberPreKey(state, kyberPreKey, it, Date.now(), instanceId))
403
- return;
404
- await this.storageBackend.atomicWrite([
405
- { type: 'check', key: storageKey, expectedValue: stored },
406
- { type: 'set', key: storageKey, value: await this.encrypt(JSON.stringify(state)) },
407
- ]);
408
- }
409
- async getKyberPreKey(identityType) {
410
- this.ensureInitialized();
411
- const encrypted = await this.storageBackend.getItem(this.getKyberPreKeyStorageKey(identityType));
412
- if (!encrypted)
413
- return null;
414
- const decrypted = await this.decrypt(encrypted);
415
- return getCurrentKyberPreKey(JSON.parse(decrypted));
416
- }
417
- async getKyberPreKeyById(keyId, identityType) {
418
- this.ensureInitialized();
419
- const encrypted = await this.storageBackend.getItem(this.getKyberPreKeyStorageKey(identityType));
420
- if (!encrypted)
421
- return null;
422
- return getRetainedKyberPreKey(JSON.parse(await this.decrypt(encrypted)), keyId);
423
- }
424
- async markKyberPreKeyUsed(kyberPreKeyId, signedPreKeyId, baseKeyBytes, identityType) {
425
- this.ensureInitialized();
426
- const it = identityType ?? 'aci';
427
- const storageKey = this.getKyberPreKeyStorageKey(it);
428
- const stored = await this.storageBackend.getItem(storageKey);
429
- const state = stored
430
- ? JSON.parse(await this.decrypt(stored))
431
- : null;
432
- recordKyberPreKeyUseById(state, it, { kyberPreKeyId, signedPreKeyId, baseKeyBytes });
433
- await this.storageBackend.atomicWrite([
434
- { type: 'check', key: storageKey, expectedValue: stored },
435
- { type: 'set', key: storageKey, value: await this.encrypt(JSON.stringify(state)) },
436
- ]);
437
- }
438
- // ============================================================================
439
- // KEM One-Time PreKey Management (Per-Session Post-Quantum Forward Secrecy)
440
- // ============================================================================
441
- // NOTE: This adapter is for bare React Native (non-Expo) apps.
442
- // Expo apps should still prefer ExpoSignalProtocolStore for the native SQLite backend.
443
- async storeKemOneTimePreKeys(prekeys, identityType) {
444
- this.ensureInitialized();
445
- const existing = await this.getKemOneTimePreKeys(identityType);
446
- await this.storageBackend.setItem(this.getKemOneTimePreKeyStorageKey(identityType), await this.encrypt(JSON.stringify([...existing, ...prekeys])));
447
- }
448
- async getKemOneTimePreKeys(identityType) {
449
- this.ensureInitialized();
450
- const encrypted = await this.storageBackend.getItem(this.getKemOneTimePreKeyStorageKey(identityType));
451
- if (!encrypted)
452
- return [];
453
- const decrypted = await this.decrypt(encrypted);
454
- return JSON.parse(decrypted);
455
- }
456
- async getKemOneTimePreKey(keyId, identityType) {
457
- const prekeys = await this.getKemOneTimePreKeys(identityType);
458
- return prekeys.find((prekey) => prekey.keyId === keyId) ?? null;
459
- }
460
- async removeKemOneTimePreKey(keyId, identityType) {
461
- this.ensureInitialized();
462
- const prekeys = await this.getKemOneTimePreKeys(identityType);
463
- const filtered = prekeys.filter((prekey) => prekey.keyId !== keyId);
464
- await this.storageBackend.setItem(this.getKemOneTimePreKeyStorageKey(identityType), await this.encrypt(JSON.stringify(filtered)));
465
- }
466
- async getKemOneTimePreKeyCount(identityType) {
467
- const prekeys = await this.getKemOneTimePreKeys(identityType);
468
- return prekeys.length;
469
- }
470
- // ============================================================================
471
- // Session Management - Modern API
472
- // ============================================================================
473
- async storeSessionRecord(address, record) {
474
- this.ensureInitialized();
475
- assertCurrentSessionRecord(record);
476
- const addressKey = this.serializeAddress(address);
477
- const storageKey = `${STORAGE_KEYS.SESSION_PREFIX}${addressKey}`;
478
- const encrypted = await this.encrypt(serializeSessionRecord(record));
479
- const storedRecord = {
480
- userId: address.userId,
481
- deviceId: address.deviceId,
482
- data: encrypted,
483
- updatedAt: Date.now(),
484
- };
485
- await this.storageBackend.setItem(storageKey, JSON.stringify(storedRecord));
486
- }
487
- async getSessionRecord(address) {
488
- this.ensureInitialized();
489
- const addressKey = this.serializeAddress(address);
490
- const storageKey = `${STORAGE_KEYS.SESSION_PREFIX}${addressKey}`;
491
- const storedJson = await this.storageBackend.getItem(storageKey);
492
- if (!storedJson)
493
- return null;
494
- const stored = JSON.parse(storedJson);
495
- const decrypted = await this.decrypt(stored.data);
496
- try {
497
- return deserializeSessionRecord(decrypted);
498
- }
499
- catch {
500
- await this.storageBackend.removeItem(storageKey);
501
- return null;
502
- }
503
- }
504
- async commitSessionTrust(commit) {
505
- this.ensureInitialized();
506
- assertCurrentSessionRecord(commit.record);
507
- const addressKey = this.serializeAddress(commit.address);
508
- const contactStorageKey = this.getContactStorageKey(commit.address, commit.contactIdentityType);
509
- const existingContactValue = await this.storageBackend.getItem(contactStorageKey);
510
- const existingContact = existingContactValue
511
- ? JSON.parse(await this.decrypt(existingContactValue))
512
- : null;
513
- if (existingContact)
514
- validateContactIdentityRecord(existingContact);
515
- const contactStatus = evaluateContactIdentityCandidate(existingContact, commit.contactIdentity);
516
- if (contactStatus !== 'NEW' && contactStatus !== 'MATCH') {
517
- throw new Error(`Atomic session/trust commit rejected contact identity status ${contactStatus}`);
518
- }
519
- const sessionStorageKey = `${STORAGE_KEYS.SESSION_PREFIX}${addressKey}`;
520
- const sessionValue = JSON.stringify({
521
- userId: commit.address.userId,
522
- deviceId: commit.address.deviceId,
523
- data: await this.encrypt(serializeSessionRecord(commit.record)),
524
- updatedAt: Date.now(),
525
- });
526
- const ecStorageKey = this.getEcOneTimePreKeyStorageKey(commit.localIdentityType);
527
- const kemStorageKey = this.getKemOneTimePreKeyStorageKey(commit.localIdentityType);
528
- const ecPrekeyValue = commit.oneTimePreKeyId === undefined ? null : await this.storageBackend.getItem(ecStorageKey);
529
- const kemPrekeyValue = commit.kemOneTimePreKeyId === undefined
530
- ? null
531
- : await this.storageBackend.getItem(kemStorageKey);
532
- const kyberStorageKey = this.getKyberPreKeyStorageKey(commit.localIdentityType);
533
- const kyberStateValue = commit.kyberPreKeyUse
534
- ? await this.storageBackend.getItem(kyberStorageKey)
535
- : null;
536
- const ecPrekeys = ecPrekeyValue
537
- ? JSON.parse(await this.decrypt(ecPrekeyValue))
538
- : [];
539
- const kemPrekeys = kemPrekeyValue
540
- ? JSON.parse(await this.decrypt(kemPrekeyValue))
541
- : [];
542
- if (commit.oneTimePreKeyId !== undefined &&
543
- !ecPrekeys.some((key) => key.keyId === commit.oneTimePreKeyId)) {
544
- throw new Error('Atomic session/trust commit cannot consume a missing EC one-time prekey');
545
- }
546
- if (commit.kemOneTimePreKeyId !== undefined &&
547
- !kemPrekeys.some((key) => key.keyId === commit.kemOneTimePreKeyId)) {
548
- throw new Error('Atomic session/trust commit cannot consume a missing KEM one-time prekey');
549
- }
550
- let updatedKyberStateValue = null;
551
- if (commit.kyberPreKeyUse) {
552
- const state = kyberStateValue
553
- ? JSON.parse(await this.decrypt(kyberStateValue))
554
- : null;
555
- recordKyberPreKeyUse(state, commit.localIdentityType, commit.kyberPreKeyUse);
556
- updatedKyberStateValue = await this.encrypt(JSON.stringify(state));
557
- }
558
- const operations = [
559
- { type: 'check', key: contactStorageKey, expectedValue: existingContactValue },
560
- { type: 'set', key: sessionStorageKey, value: sessionValue },
561
- ];
562
- if (contactStatus === 'NEW') {
563
- const newContact = createUnverifiedContactIdentityRecord(commit.contactIdentity, Date.now());
564
- operations.push({
565
- type: 'set',
566
- key: contactStorageKey,
567
- value: await this.encrypt(JSON.stringify(newContact)),
568
- });
569
- }
570
- if (commit.oneTimePreKeyId !== undefined) {
571
- operations.push({ type: 'check', key: ecStorageKey, expectedValue: ecPrekeyValue });
572
- operations.push({
573
- type: 'set',
574
- key: ecStorageKey,
575
- value: await this.encrypt(JSON.stringify(ecPrekeys.filter((key) => key.keyId !== commit.oneTimePreKeyId))),
576
- });
577
- }
578
- if (commit.kemOneTimePreKeyId !== undefined) {
579
- operations.push({ type: 'check', key: kemStorageKey, expectedValue: kemPrekeyValue });
580
- operations.push({
581
- type: 'set',
582
- key: kemStorageKey,
583
- value: await this.encrypt(JSON.stringify(kemPrekeys.filter((key) => key.keyId !== commit.kemOneTimePreKeyId))),
584
- });
585
- }
586
- if (commit.kyberPreKeyUse && updatedKyberStateValue) {
587
- operations.push({ type: 'check', key: kyberStorageKey, expectedValue: kyberStateValue });
588
- operations.push({ type: 'set', key: kyberStorageKey, value: updatedKyberStateValue });
589
- }
590
- if (commit.receivedContent)
591
- operations.push({
592
- type: 'set',
593
- key: `@signal:received-content:${commit.receivedContent.id}`,
594
- value: await this.encrypt(JSON.stringify(commit.receivedContent)),
595
- });
596
- await this.storageBackend.atomicWrite(operations);
597
- }
598
- async getReceivedContent(id) {
599
- this.ensureInitialized();
600
- const value = await this.storageBackend.getItem(`@signal:received-content:${id}`);
601
- return value ? parseReceivedContent(await this.decrypt(value), id) : null;
602
- }
603
- async deleteReceivedContent(id) {
604
- this.ensureInitialized();
605
- await this.storageBackend.removeItem(`@signal:received-content:${id}`);
606
- }
607
- async deleteExpiredReceivedContent(before) {
608
- this.ensureInitialized();
609
- const prefix = '@signal:received-content:';
610
- const keys = (await this.storageBackend.getAllKeys()).filter((key) => key.startsWith(prefix));
611
- const expired = [];
612
- for (const key of keys) {
613
- const value = await this.getReceivedContent(key.slice(prefix.length));
614
- if (value && value.receivedAt < before)
615
- expired.push(key);
616
- }
617
- if (expired.length)
618
- await this.storageBackend.atomicWrite(expired.map((key) => ({ type: 'remove', key })));
619
- return expired.length;
620
- }
621
- async deleteSessionRecord(address) {
622
- this.ensureInitialized();
623
- const addressKey = this.serializeAddress(address);
624
- const storageKey = `${STORAGE_KEYS.SESSION_PREFIX}${addressKey}`;
625
- await this.storageBackend.removeItem(storageKey);
626
- }
627
- async archiveCurrentSession(address, newSession) {
628
- this.ensureInitialized();
629
- // With SessionRecord, archiving is handled at the DeviceRecord level
630
- // This method updates or replaces the session state
631
- if (newSession) {
632
- const record = await this.getSessionRecord(address);
633
- if (record) {
634
- // Update existing session with new state
635
- record.currentSession = newSession;
636
- if (record.metadata) {
637
- record.metadata.lastSentAt = Date.now();
638
- }
639
- await this.storeSessionRecord(address, record);
640
- }
641
- }
642
- else {
643
- // If no new session, just delete the old one
644
- await this.deleteSessionRecord(address);
645
- }
646
- }
647
- async getSessionsForUser(userId) {
648
- this.ensureInitialized();
649
- // Get all keys with session prefix
650
- const allKeys = await this.storageBackend.getAllKeys();
651
- const sessionKeys = allKeys.filter((key) => key.startsWith(STORAGE_KEYS.SESSION_PREFIX));
652
- const sessions = [];
653
- for (const key of sessionKeys) {
654
- const storedJson = await this.storageBackend.getItem(key);
655
- if (storedJson) {
656
- const stored = JSON.parse(storedJson);
657
- if (stored.userId === userId) {
658
- const decrypted = await this.decrypt(stored.data);
659
- try {
660
- sessions.push(deserializeSessionRecord(decrypted));
661
- }
662
- catch {
663
- await this.storageBackend.removeItem(key);
664
- }
665
- }
666
- }
667
- }
668
- return sessions;
669
- }
670
- async hasSession(address) {
671
- this.ensureInitialized();
672
- const record = await this.getSessionRecord(address);
673
- return record !== null && record.currentSession !== null;
674
- }
675
- // ============================================================================
676
- // Utility
677
- // ============================================================================
678
- async getSessionCount() {
679
- this.ensureInitialized();
680
- // Get all session keys
681
- const allKeys = await this.storageBackend.getAllKeys();
682
- const sessionKeys = allKeys.filter((key) => key.startsWith(STORAGE_KEYS.SESSION_PREFIX));
683
- return sessionKeys.length;
684
- }
685
- async clearAllKeys() {
686
- this.ensureInitialized();
687
- // Get all keys
688
- const allKeys = await this.storageBackend.getAllKeys();
689
- // Filter for signal keys
690
- const signalKeys = allKeys.filter((key) => key.startsWith('@signal:'));
691
- // Remove all signal keys
692
- await this.storageBackend.removeMany(signalKeys);
693
- // Regenerate database key
694
- this.databaseKey = Crypto.getRandomBytes(32);
695
- await this.storageBackend.setItem(STORAGE_KEYS.DATABASE_KEY, this.uint8ArrayToBase64(this.databaseKey));
696
- }
697
- // ============================================================================
698
- // Metadata storage
699
- // ============================================================================
700
- async getMetadata(key) {
701
- return this.storageBackend.getItem(this.getMetadataStorageKey(key));
702
- }
703
- async setMetadata(key, value) {
704
- await this.storageBackend.setItem(this.getMetadataStorageKey(key), value);
705
- }
706
- async deleteMetadata(key) {
707
- await this.storageBackend.removeItem(this.getMetadataStorageKey(key));
708
- }
709
- async compareAndSetMetadata(key, expected, value) {
710
- const storageKey = this.getMetadataStorageKey(key);
711
- try {
712
- await this.storageBackend.atomicWrite([
713
- { type: 'check', key: storageKey, expectedValue: expected },
714
- value === null
715
- ? { type: 'remove', key: storageKey }
716
- : { type: 'set', key: storageKey, value },
717
- ]);
718
- return true;
719
- }
720
- catch (error) {
721
- // A failed batch commits nothing. Do not report capacity failure as contention.
722
- if (error &&
723
- typeof error === 'object' &&
724
- 'name' in error &&
725
- error.name === 'QuotaExceededError')
726
- throw error;
727
- if ((await this.storageBackend.getItem(storageKey)) !== expected)
728
- return false;
729
- throw error;
730
- }
731
- }
732
- // ============================================================================
733
- // Private Helper Methods
734
- // ============================================================================
735
- /**
736
- * Throw when the adapter is not initialized
737
- * @throws Error if not initialized
738
- */
739
- ensureInitialized() {
740
- if (!this.initialized || !this.databaseKey) {
741
- throw new Error('ReactNativeSignalProtocolStore was used before initialization completed. Create it with ReactNativeSignalProtocolStore.create(...).');
742
- }
743
- }
744
- /**
745
- * Serialize ProtocolAddress to string key
746
- */
747
- serializeAddress(address) {
748
- return `${address.userId}.${address.deviceId}`;
749
- }
750
- getContactStorageKey(address, identityType) {
751
- return `${STORAGE_KEYS.CONTACT_V1_PREFIX}${address.userId}:${identityType ?? 'aci'}`;
752
- }
753
- async readContactRecord(address, identityType) {
754
- const encrypted = await this.storageBackend.getItem(this.getContactStorageKey(address, identityType));
755
- if (!encrypted) {
756
- // A miss here can still leave an obsolete single-publicKey row under the
757
- // unsuffixed key, which no read path can interpret. Delete it.
758
- await this.storageBackend.removeItem(`${STORAGE_KEYS.CONTACT_PREFIX}${address.userId}`);
759
- return null;
760
- }
761
- const record = JSON.parse(await this.decrypt(encrypted));
762
- validateContactIdentityRecord(record);
763
- return record;
764
- }
765
- async writeContactRecord(storageKey, record) {
766
- validateContactIdentityRecord(record);
767
- await this.storageBackend.setItem(storageKey, await this.encrypt(JSON.stringify(record)));
768
- }
769
- /**
770
- * Encrypt data using AES-256-GCM
771
- *
772
- * Uses Signal Protocol crypto module with Web Crypto API.
773
- *
774
- * @param plaintext - Data to encrypt
775
- * @returns Base64-encoded: IV (12 bytes) + ciphertext + auth tag (16 bytes)
776
- */
777
- async encrypt(plaintext) {
778
- if (!this.databaseKey) {
779
- throw new Error('Database key not available');
780
- }
781
- // Generate random IV (12 bytes for GCM)
782
- const iv = Crypto.getRandomBytes(12);
783
- // Encode plaintext
784
- const data = new TextEncoder().encode(plaintext);
785
- // Encrypt using proper AES-256-GCM via Signal Protocol crypto module
786
- const encrypted = await this.aesGcmEncrypt(data, this.databaseKey, iv);
787
- // Combine IV + ciphertext and encode as base64
788
- const combined = new Uint8Array(12 + encrypted.length);
789
- combined.set(iv, 0);
790
- combined.set(encrypted, 12);
791
- return this.uint8ArrayToBase64(combined);
792
- }
793
- /**
794
- * Decrypt data using AES-256-GCM
795
- *
796
- * @param encrypted - Base64-encoded: IV (12 bytes) + ciphertext + auth tag (16 bytes)
797
- * @returns Decrypted plaintext
798
- */
799
- async decrypt(encrypted) {
800
- if (!this.databaseKey) {
801
- throw new Error('Database key not available');
802
- }
803
- // Decode from base64
804
- const combined = this.base64ToUint8Array(encrypted);
805
- // Extract IV and ciphertext
806
- const iv = combined.slice(0, 12);
807
- const ciphertext = combined.slice(12);
808
- // Decrypt
809
- const plaintext = await this.aesGcmDecrypt(ciphertext, this.databaseKey, iv);
810
- // Decode plaintext
811
- return new TextDecoder().decode(plaintext);
812
- }
813
- /**
814
- * AES-256-GCM encryption
815
- *
816
- * Uses the Signal Protocol crypto module, which uses Web Crypto when
817
- * `crypto.subtle` exists and the bundled Noble AES otherwise.
818
- *
819
- * @param data - Plaintext to encrypt
820
- * @param key - 32-byte AES-256 key
821
- * @param iv - 12-byte initialization vector (already generated in encrypt())
822
- * @returns Ciphertext with appended 16-byte auth tag
823
- */
824
- async aesGcmEncrypt(data, key, iv) {
825
- // Use the Signal Protocol crypto module's AES-GCM implementation
826
- const result = await SignalProtocolCrypto.aesGcmEncryptWithIV(key, data, iv);
827
- // Combine ciphertext + authTag into single buffer
828
- const ciphertextBytes = SignalProtocolCrypto.base64ToBytes(result.ciphertext);
829
- const authTagBytes = SignalProtocolCrypto.base64ToBytes(result.authTag);
830
- const combined = new Uint8Array(ciphertextBytes.length + authTagBytes.length);
831
- combined.set(ciphertextBytes, 0);
832
- combined.set(authTagBytes, ciphertextBytes.length);
833
- return combined;
834
- }
835
- /**
836
- * AES-256-GCM decryption
837
- *
838
- * Uses the Signal Protocol crypto module, which uses Web Crypto when
839
- * `crypto.subtle` exists and the bundled Noble AES otherwise.
840
- *
841
- * @param ciphertext - Encrypted data with appended 16-byte auth tag
842
- * @param key - 32-byte AES-256 key
843
- * @param iv - 12-byte initialization vector
844
- * @returns Decrypted plaintext
845
- */
846
- async aesGcmDecrypt(ciphertext, key, iv) {
847
- // Validate minimum ciphertext length (must be at least 16 bytes for auth tag)
848
- const AES_GCM_TAG_BYTES = 16;
849
- if (ciphertext.length < AES_GCM_TAG_BYTES) {
850
- throw new Error(`Ciphertext too short: ${ciphertext.length} bytes (minimum ${AES_GCM_TAG_BYTES} for auth tag)`);
851
- }
852
- // Split ciphertext and auth tag (last 16 bytes)
853
- const ciphertextOnly = ciphertext.slice(0, -AES_GCM_TAG_BYTES);
854
- const authTag = ciphertext.slice(-AES_GCM_TAG_BYTES);
855
- // Use the Signal Protocol crypto module's AES-GCM implementation
856
- return await SignalProtocolCrypto.aesGcmDecrypt(key, SignalProtocolCrypto.bytesToBase64(ciphertextOnly), SignalProtocolCrypto.bytesToBase64(iv), SignalProtocolCrypto.bytesToBase64(authTag));
857
- }
858
- /**
859
- * Log security event
860
- */
861
- async logSecurityEvent(event) {
862
- const eventsJson = await this.storageBackend.getItem(STORAGE_KEYS.SECURITY_EVENTS);
863
- const events = eventsJson ? JSON.parse(eventsJson) : [];
864
- events.push(event);
865
- // Keep only last 100 events
866
- const trimmed = events.slice(-100);
867
- await this.storageBackend.setItem(STORAGE_KEYS.SECURITY_EVENTS, JSON.stringify(trimmed));
868
- }
869
- /**
870
- * Convert Uint8Array to base64
871
- */
872
- uint8ArrayToBase64(bytes) {
873
- let binary = '';
874
- for (let i = 0; i < bytes.length; i++) {
875
- binary += String.fromCharCode(bytes[i]);
876
- }
877
- return Buffer.from(binary, 'binary').toString('base64');
878
- }
879
- /**
880
- * Convert base64 to Uint8Array
881
- */
882
- base64ToUint8Array(base64) {
883
- const binary = Buffer.from(base64, 'base64').toString('binary');
884
- const bytes = new Uint8Array(binary.length);
885
- for (let i = 0; i < binary.length; i++) {
886
- bytes[i] = binary.charCodeAt(i);
887
- }
888
- return bytes;
889
- }
890
- serializeUserRecord(record) {
891
- return { ...record, devices: Array.from(record.devices.entries()) };
892
- }
893
- deserializeUserRecord(data) {
894
- return { ...data, devices: new Map(data.devices) };
895
- }
896
- getIdentityKeyStorageKey(identityType) {
897
- return `${STORAGE_KEYS.IDENTITY_KEY_PREFIX}${identityType ?? 'aci'}`;
898
- }
899
- getRegistrationIdStorageKey(identityType) {
900
- return `${STORAGE_KEYS.REGISTRATION_ID_PREFIX}${identityType ?? 'aci'}`;
901
- }
902
- getMetadataStorageKey(key) {
903
- return `${STORAGE_KEYS.METADATA_PREFIX}${key}`;
904
- }
905
- getSignedPreKeyStorageKey(identityType) {
906
- return `${STORAGE_KEYS.PREKEY_PREFIX}signed-all:${identityType ?? 'aci'}`;
907
- }
908
- getEcOneTimePreKeyStorageKey(identityType) {
909
- return `${STORAGE_KEYS.PREKEY_PREFIX}one-time:${identityType ?? 'aci'}`;
910
- }
911
- getKyberPreKeyStorageKey(identityType) {
912
- return `${STORAGE_KEYS.PREKEY_PREFIX}kyber:${identityType ?? 'aci'}`;
913
- }
914
- getKemOneTimePreKeyStorageKey(identityType) {
915
- return `${STORAGE_KEYS.PREKEY_PREFIX}kem-one-time:${identityType ?? 'aci'}`;
916
- }
917
- getSesameUserStorageKey(userId) {
918
- return `${STORAGE_KEYS.SESAME_USER_PREFIX}${userId}`;
919
- }
920
- getSenderKeyRecordStorageKey(groupId, userId, deviceId) {
921
- return `${this.getSenderKeyRecordGroupPrefix(groupId)}${escapeKeyComponent(userId)}:${deviceId}`;
922
- }
923
- /** Prefix matching every sender key record stored for one group. */
924
- getSenderKeyRecordGroupPrefix(groupId) {
925
- return `${STORAGE_KEYS.SENDER_KEY_RECORD_PREFIX}${escapeKeyComponent(groupId)}:`;
926
- }
927
- /**
928
- * Prefix matching every skipped key of one sender in one group.
929
- *
930
- * Trailing `:` included: the chain index follows it, and without it the
931
- * prefix for device 1 would also match device 10's keys.
932
- */
933
- getSkippedSenderKeyPrefix(groupId, senderId, senderDeviceId) {
934
- return `${STORAGE_KEYS.SKIPPED_SENDER_KEY_PREFIX}${escapeKeyComponent(groupId)}:${escapeKeyComponent(senderId)}:${senderDeviceId}:`;
935
- }
936
- getSkippedSenderKeyStorageKey(groupId, senderId, senderDeviceId, chainIndex) {
937
- return `${this.getSkippedSenderKeyPrefix(groupId, senderId, senderDeviceId)}${chainIndex}`;
938
- }
939
- getMessageRecordStorageKey(sessionId, timestamp) {
940
- return `${this.getMessageRecordSessionPrefix(sessionId)}${timestamp}`;
941
- }
942
- /** Prefix matching every retry record stored for one session. */
943
- getMessageRecordSessionPrefix(sessionId) {
944
- return `${STORAGE_KEYS.MESSAGE_RECORD_PREFIX}${escapeKeyComponent(sessionId)}:`;
945
- }
946
- // ============================================================================
947
- // SESAME Multi-Device Session Management
948
- // ============================================================================
949
- async getUserRecord(userId) {
950
- this.ensureInitialized();
951
- const encrypted = await this.storageBackend.getItem(this.getSesameUserStorageKey(userId));
952
- if (!encrypted) {
953
- return null;
954
- }
955
- const decrypted = await this.decrypt(encrypted);
956
- return this.deserializeUserRecord(JSON.parse(decrypted));
957
- }
958
- async setUserRecord(userId, record) {
959
- this.ensureInitialized();
960
- const encrypted = await this.encrypt(JSON.stringify(this.serializeUserRecord(record)));
961
- await this.storageBackend.setItem(this.getSesameUserStorageKey(userId), encrypted);
962
- }
963
- async getDeviceRecord(userId, deviceId) {
964
- const userRecord = await this.getUserRecord(userId);
965
- return userRecord?.devices.get(deviceId) ?? null;
966
- }
967
- async setDeviceRecord(userId, deviceId, record) {
968
- let userRecord = await this.getUserRecord(userId);
969
- if (!userRecord) {
970
- userRecord = { userId, devices: new Map(), createdAt: Date.now(), updatedAt: Date.now() };
971
- }
972
- userRecord.devices.set(deviceId, record);
973
- userRecord.updatedAt = Date.now();
974
- await this.setUserRecord(userId, userRecord);
975
- }
976
- async deleteDeviceRecord(userId, deviceId) {
977
- const userRecord = await this.getUserRecord(userId);
978
- if (!userRecord) {
979
- return;
980
- }
981
- userRecord.devices.delete(deviceId);
982
- userRecord.updatedAt = Date.now();
983
- if (userRecord.devices.size === 0) {
984
- await this.storageBackend.removeItem(this.getSesameUserStorageKey(userId));
985
- return;
986
- }
987
- await this.setUserRecord(userId, userRecord);
988
- }
989
- async deleteStaleRecords(maxLatency) {
990
- const now = Date.now();
991
- let deletedCount = 0;
992
- for (const userId of await this.getAllUserIds()) {
993
- const userRecord = await this.getUserRecord(userId);
994
- if (!userRecord)
995
- continue;
996
- const devicesToDelete = [];
997
- for (const [deviceId, deviceRecord] of userRecord.devices) {
998
- const hasNoSessions = !deviceRecord.session ||
999
- (!deviceRecord.session.currentSession &&
1000
- Object.keys(deviceRecord.session.archivedSessions).length === 0);
1001
- const isStale = now - deviceRecord.updatedAt > maxLatency;
1002
- if (hasNoSessions && isStale) {
1003
- devicesToDelete.push(deviceId);
1004
- }
1005
- }
1006
- for (const deviceId of devicesToDelete) {
1007
- await this.deleteDeviceRecord(userId, deviceId);
1008
- deletedCount++;
1009
- }
1010
- }
1011
- return deletedCount;
46
+ export class ReactNativeSignalProtocolStore extends SqliteSignalProtocolStore {
47
+ constructor(database, logger) {
48
+ super(database, { logger });
49
+ databases.set(this, database);
1012
50
  }
1013
- async cleanupExpiredSessions(maxRecv) {
1014
- const now = Date.now();
1015
- let deletedCount = 0;
1016
- for (const userId of await this.getAllUserIds()) {
1017
- const userRecord = await this.getUserRecord(userId);
1018
- if (!userRecord)
1019
- continue;
1020
- for (const [deviceId, deviceRecord] of userRecord.devices) {
1021
- if (!deviceRecord.session)
1022
- continue;
1023
- let modified = false;
1024
- if (deviceRecord.session.currentSession) {
1025
- const createdAt = deviceRecord.session.metadata?.createdAt ??
1026
- deviceRecord.session.currentSession.createdAt;
1027
- if (now - createdAt > maxRecv) {
1028
- deviceRecord.session.currentSession = null;
1029
- modified = true;
1030
- deletedCount++;
1031
- }
1032
- }
1033
- const originalCount = Object.keys(deviceRecord.session.archivedSessions).length;
1034
- const archivedKeys = Object.keys(deviceRecord.session.archivedSessions);
1035
- for (const baseKey of archivedKeys) {
1036
- const session = deviceRecord.session.archivedSessions[baseKey];
1037
- if (session && now - session.createdAt > maxRecv) {
1038
- delete deviceRecord.session.archivedSessions[baseKey];
1039
- }
1040
- }
1041
- const removed = originalCount - Object.keys(deviceRecord.session.archivedSessions).length;
1042
- if (removed > 0) {
1043
- deletedCount += removed;
1044
- modified = true;
1045
- }
1046
- if (modified) {
1047
- deviceRecord.updatedAt = Date.now();
1048
- await this.setDeviceRecord(userId, deviceId, deviceRecord);
1049
- }
1050
- }
1051
- }
1052
- return deletedCount;
51
+ /** @internal Use {@link reactNativeStore}. */
52
+ static async open(options) {
53
+ const database = await openSqliteStore(storeOptions(options));
54
+ return new ReactNativeSignalProtocolStore(database, options.logger);
1053
55
  }
1054
- async getAllUserIds() {
1055
- this.ensureInitialized();
1056
- const allKeys = await this.storageBackend.getAllKeys();
1057
- return allKeys
1058
- .filter((key) => key.startsWith(STORAGE_KEYS.SESAME_USER_PREFIX))
1059
- .map((key) => key.slice(STORAGE_KEYS.SESAME_USER_PREFIX.length));
1060
- }
1061
- async getSesameDeviceIds(userId) {
1062
- const userRecord = await this.getUserRecord(userId);
1063
- return userRecord ? Array.from(userRecord.devices.keys()) : [];
1064
- }
1065
- async getDeviceSession(userId, deviceId) {
1066
- const deviceRecord = await this.getDeviceRecord(userId, deviceId);
1067
- return deviceRecord?.session ?? null;
1068
- }
1069
- async setDeviceSession(userId, deviceId, session) {
1070
- const deviceRecord = await this.getDeviceRecord(userId, deviceId);
1071
- if (deviceRecord) {
1072
- deviceRecord.session = session;
1073
- await this.setDeviceRecord(userId, deviceId, deviceRecord);
1074
- }
1075
- }
1076
- // ============================================================================
1077
- // Sender Keys Management (Group Messaging)
1078
- // ============================================================================
1079
- async storeSenderKey(groupId, userId, deviceId, state) {
1080
- await this.storeSenderKeyRecord(groupId, userId, deviceId, [state]);
1081
- }
1082
- async getSenderKey(groupId, userId, deviceId) {
1083
- const record = await this.getSenderKeyRecord(groupId, userId, deviceId);
1084
- return record?.[0] ?? null;
1085
- }
1086
- async deleteSenderKey(groupId, userId, deviceId) {
1087
- this.ensureInitialized();
1088
- await this.removeSenderKeyIdPointers(groupId, userId, deviceId);
1089
- await this.storageBackend.removeItem(this.getSenderKeyRecordStorageKey(groupId, userId, deviceId));
56
+ /** @internal Use {@link resetReactNativeStore}. */
57
+ static async reset(options) {
58
+ const database = await resetSqliteStore(storeOptions(options));
59
+ return new ReactNativeSignalProtocolStore(database, options.logger);
1090
60
  }
1091
61
  /**
1092
- * Build the storage key for a `senderKeyId` pointer.
1093
- *
1094
- * Scoped by sender, so one sender's id can never displace another's. That
1095
- * scoping is only worth anything if the join is injective, and a
1096
- * `senderKeyId` is the component least entitled to trust. It is whatever
1097
- * bytes the sender put in the frame's distribution field, validated
1098
- * nowhere, so it is escaped rather than reasoned about. With every
1099
- * component escaped, no choice of id can synthesize another sender's
1100
- * `:<deviceId>:<userId>` tail.
62
+ * Wait for the queued work, then close the database. Every later call
63
+ * rejects with `SqliteStoreClosedError`.
1101
64
  */
1102
- getSenderKeyIdPointerKey(senderKeyId, userId, deviceId) {
1103
- return `${STORAGE_KEYS.SENDER_KEY_ID_INDEX_PREFIX}${escapeKeyComponent(senderKeyId)}:${deviceId}:${escapeKeyComponent(userId)}`;
1104
- }
1105
- /**
1106
- * Drop the `senderKeyId` pointers a record owns, before the record goes.
1107
- *
1108
- * Ordered that way deliberately. A pointer that outlives its record is
1109
- * self-healing, because `resolveGroupForSenderKeyId` confirms and deletes
1110
- * it. A record that outlives its pointers is simply unreachable by id.
1111
- */
1112
- async removeSenderKeyIdPointers(groupId, userId, deviceId) {
1113
- const record = await this.getSenderKeyRecord(groupId, userId, deviceId);
1114
- if (!record)
1115
- return;
1116
- await this.storageBackend.removeMany(record
1117
- .map((state) => state.senderKeyId)
1118
- .filter(Boolean)
1119
- .map((senderKeyId) => this.getSenderKeyIdPointerKey(senderKeyId, userId, deviceId)));
1120
- }
1121
- async resolveGroupForSenderKeyId(senderKeyId, userId, deviceId) {
1122
- this.ensureInitialized();
1123
- if (!senderKeyId)
1124
- return null;
1125
- const recordKey = await this.storageBackend.getItem(this.getSenderKeyIdPointerKey(senderKeyId, userId, deviceId));
1126
- if (!recordKey)
1127
- return null;
1128
- // The pointer is a cache over the records, so it is confirmed against the
1129
- // record rather than trusted. The sender check is an invariant assertion
1130
- // now that the pointer key is itself sender-scoped. A mismatch would mean
1131
- // the two disagree, so resolve to nothing rather than reaching into
1132
- // another sender's record. It is deliberately not deleted. The key
1133
- // belongs to this sender, and a wrong value is a bug to notice, not a
1134
- // stale entry to sweep.
1135
- const parsed = this.parseSenderKeyRecordStorageKey(recordKey);
1136
- if (!parsed || parsed.userId !== userId || parsed.deviceId !== deviceId) {
1137
- return null;
1138
- }
1139
- const record = await this.getSenderKeyRecord(parsed.groupId, userId, deviceId);
1140
- if (!record?.some((state) => state.senderKeyId === senderKeyId)) {
1141
- await this.storageBackend.removeItem(this.getSenderKeyIdPointerKey(senderKeyId, userId, deviceId));
1142
- return null;
1143
- }
1144
- return parsed.groupId;
1145
- }
1146
- /**
1147
- * Split a record storage key back into its parts.
1148
- *
1149
- * The components were escaped on the way in, so the body holds exactly three
1150
- * `:`-separated fields and the split is unambiguous. Anything else is a key
1151
- * this adapter did not write.
1152
- */
1153
- parseSenderKeyRecordStorageKey(recordKey) {
1154
- if (!recordKey.startsWith(STORAGE_KEYS.SENDER_KEY_RECORD_PREFIX))
1155
- return null;
1156
- const body = recordKey.slice(STORAGE_KEYS.SENDER_KEY_RECORD_PREFIX.length);
1157
- const parts = body.split(':');
1158
- if (parts.length !== 3)
1159
- return null;
1160
- const [groupId, userId, device] = parts;
1161
- if (!groupId || !userId || !device)
1162
- return null;
1163
- const deviceId = Number(device);
1164
- if (!Number.isInteger(deviceId))
1165
- return null;
1166
- return {
1167
- groupId: unescapeKeyComponent(groupId),
1168
- userId: unescapeKeyComponent(userId),
1169
- deviceId,
1170
- };
1171
- }
1172
- async getAllSenderKeysForGroup(groupId) {
1173
- this.ensureInitialized();
1174
- const allKeys = await this.storageBackend.getAllKeys();
1175
- const senderKeys = allKeys.filter((key) => key.startsWith(this.getSenderKeyRecordGroupPrefix(groupId)));
1176
- const states = [];
1177
- for (const key of senderKeys) {
1178
- const encrypted = await this.storageBackend.getItem(key);
1179
- if (!encrypted)
1180
- continue;
1181
- const decrypted = await this.decrypt(encrypted);
1182
- const record = JSON.parse(decrypted);
1183
- if (record[0]) {
1184
- states.push(record[0]);
1185
- }
1186
- }
1187
- return states;
1188
- }
1189
- async deleteAllSenderKeysForGroup(groupId) {
1190
- this.ensureInitialized();
1191
- const allKeys = await this.storageBackend.getAllKeys();
1192
- const senderKeys = allKeys.filter((key) => key.startsWith(this.getSenderKeyRecordGroupPrefix(groupId)));
1193
- for (const recordKey of senderKeys) {
1194
- const parsed = this.parseSenderKeyRecordStorageKey(recordKey);
1195
- if (parsed) {
1196
- await this.removeSenderKeyIdPointers(parsed.groupId, parsed.userId, parsed.deviceId);
1197
- }
1198
- }
1199
- await this.storageBackend.removeMany(senderKeys);
1200
- return senderKeys.length;
1201
- }
1202
- async storeSenderKeyRecord(groupId, userId, deviceId, states, receive) {
1203
- this.ensureInitialized();
1204
- if (states.length === 0) {
1205
- return;
1206
- }
1207
- const recordKey = this.getSenderKeyRecordStorageKey(groupId, userId, deviceId);
1208
- // Rotation drops the oldest state out of the record. Its pointer has to go
1209
- // with it. Otherwise a replayed message naming a discarded key still
1210
- // resolves to a group, and fails one layer deeper than it should.
1211
- const superseded = await this.getSenderKeyRecord(groupId, userId, deviceId);
1212
- const retained = new Set(states.map((state) => state.senderKeyId));
1213
- const operations = [];
1214
- if (superseded) {
1215
- operations.push(...superseded
1216
- .map((state) => state.senderKeyId)
1217
- .filter((senderKeyId) => senderKeyId && !retained.has(senderKeyId))
1218
- .map((senderKeyId) => ({
1219
- type: 'remove',
1220
- key: this.getSenderKeyIdPointerKey(senderKeyId, userId, deviceId),
1221
- })));
1222
- }
1223
- operations.push({
1224
- type: 'set',
1225
- key: recordKey,
1226
- value: await this.encrypt(JSON.stringify(states)),
1227
- });
1228
- for (const senderKeyId of retained) {
1229
- if (!senderKeyId)
1230
- continue;
1231
- operations.push({
1232
- type: 'set',
1233
- key: this.getSenderKeyIdPointerKey(senderKeyId, userId, deviceId),
1234
- value: recordKey,
1235
- });
1236
- }
1237
- if (receive) {
1238
- operations.push({
1239
- type: 'set',
1240
- key: `@signal:received-content:${receive.content.id}`,
1241
- value: await this.encrypt(JSON.stringify(receive.content)),
1242
- });
1243
- if (receive.consumedChainIndex !== undefined)
1244
- operations.push({
1245
- type: 'remove',
1246
- key: this.getSkippedSenderKeyStorageKey(groupId, userId, deviceId, receive.consumedChainIndex),
1247
- });
1248
- }
1249
- await this.storageBackend.atomicWrite(operations);
1250
- }
1251
- async getSenderKeyRecord(groupId, userId, deviceId) {
1252
- this.ensureInitialized();
1253
- const encrypted = await this.storageBackend.getItem(this.getSenderKeyRecordStorageKey(groupId, userId, deviceId));
1254
- if (!encrypted) {
1255
- return null;
1256
- }
1257
- const decrypted = await this.decrypt(encrypted);
1258
- return JSON.parse(decrypted);
1259
- }
1260
- // ============================================================================
1261
- // Skipped Sender Keys
1262
- // ============================================================================
1263
- async storeSkippedSenderKey(groupId, senderId, senderDeviceId, chainIndex, messageKey) {
1264
- this.ensureInitialized();
1265
- await this.storageBackend.setItem(this.getSkippedSenderKeyStorageKey(groupId, senderId, senderDeviceId, chainIndex), await this.encrypt(JSON.stringify(messageKey)));
1266
- }
1267
- async getSkippedSenderKey(groupId, senderId, senderDeviceId, chainIndex) {
1268
- this.ensureInitialized();
1269
- const encrypted = await this.storageBackend.getItem(this.getSkippedSenderKeyStorageKey(groupId, senderId, senderDeviceId, chainIndex));
1270
- if (!encrypted) {
1271
- return null;
1272
- }
1273
- const decrypted = await this.decrypt(encrypted);
1274
- return JSON.parse(decrypted);
1275
- }
1276
- async deleteSkippedSenderKey(groupId, senderId, senderDeviceId, chainIndex) {
1277
- this.ensureInitialized();
1278
- await this.storageBackend.removeItem(this.getSkippedSenderKeyStorageKey(groupId, senderId, senderDeviceId, chainIndex));
1279
- }
1280
- async countSkippedSenderKeys(groupId, senderId, senderDeviceId) {
1281
- this.ensureInitialized();
1282
- const allKeys = await this.storageBackend.getAllKeys();
1283
- return allKeys.filter((key) => key.startsWith(this.getSkippedSenderKeyPrefix(groupId, senderId, senderDeviceId))).length;
1284
- }
1285
- async deleteOldestSkippedSenderKeys(groupId, senderId, senderDeviceId, count) {
1286
- this.ensureInitialized();
1287
- const allKeys = await this.storageBackend.getAllKeys();
1288
- const prefix = this.getSkippedSenderKeyPrefix(groupId, senderId, senderDeviceId);
1289
- const matches = allKeys
1290
- .filter((key) => key.startsWith(prefix))
1291
- .map((key) => ({ key, chainIndex: parseInt(key.split(':').pop() ?? '0', 10) }))
1292
- .sort((a, b) => a.chainIndex - b.chainIndex)
1293
- .slice(0, count);
1294
- await this.storageBackend.removeMany(matches.map(({ key }) => key));
1295
- return matches.length;
1296
- }
1297
- // ============================================================================
1298
- // Message Record Storage (Not Yet Implemented)
1299
- // Retry records are indexed by the client timestamp assigned before encryption.
1300
- // ============================================================================
1301
- async storeMessageRecord(record) {
1302
- this.ensureInitialized();
1303
- await this.storageBackend.setItem(this.getMessageRecordStorageKey(record.sessionId, record.timestamp), await this.encrypt(JSON.stringify(record)));
1304
- }
1305
- async getMessageRecord(sessionId, timestamp) {
1306
- this.ensureInitialized();
1307
- const encrypted = await this.storageBackend.getItem(this.getMessageRecordStorageKey(sessionId, timestamp));
1308
- if (!encrypted) {
1309
- return null;
1310
- }
1311
- const decrypted = await this.decrypt(encrypted);
1312
- return JSON.parse(decrypted);
1313
- }
1314
- async deleteMessageRecord(sessionId, timestamp) {
1315
- this.ensureInitialized();
1316
- await this.storageBackend.removeItem(this.getMessageRecordStorageKey(sessionId, timestamp));
1317
- }
1318
- async deleteExpiredMessageRecords(maxAgeMs) {
1319
- this.ensureInitialized();
1320
- const cutoff = Date.now() - maxAgeMs;
1321
- const allKeys = await this.storageBackend.getAllKeys();
1322
- const messageKeys = allKeys.filter((key) => key.startsWith(STORAGE_KEYS.MESSAGE_RECORD_PREFIX));
1323
- const toDelete = [];
1324
- for (const key of messageKeys) {
1325
- const encrypted = await this.storageBackend.getItem(key);
1326
- if (!encrypted)
1327
- continue;
1328
- const decrypted = await this.decrypt(encrypted);
1329
- const record = JSON.parse(decrypted);
1330
- if (record.createdAt < cutoff) {
1331
- toDelete.push(key);
1332
- }
1333
- }
1334
- if (toDelete.length > 0) {
1335
- await this.storageBackend.removeMany(toDelete);
1336
- }
1337
- return toDelete.length;
1338
- }
1339
- async clearAllMessageRecords() {
1340
- this.ensureInitialized();
1341
- const allKeys = await this.storageBackend.getAllKeys();
1342
- const messageKeys = allKeys.filter((key) => key.startsWith(STORAGE_KEYS.MESSAGE_RECORD_PREFIX));
1343
- if (messageKeys.length > 0) {
1344
- await this.storageBackend.removeMany(messageKeys);
1345
- }
1346
- return messageKeys.length;
1347
- }
1348
- async deleteMessageRecordsForSession(sessionId) {
1349
- this.ensureInitialized();
1350
- const allKeys = await this.storageBackend.getAllKeys();
1351
- const messageKeys = allKeys.filter((key) => key.startsWith(this.getMessageRecordSessionPrefix(sessionId)));
1352
- if (messageKeys.length > 0) {
1353
- await this.storageBackend.removeMany(messageKeys);
1354
- }
1355
- return messageKeys.length;
1356
- }
1357
- // ============================================================================
1358
- // Key Recovery Methods (Bug #7 - Identifier Collision Recovery)
1359
- // ============================================================================
1360
- async getEcSignedPreKeyMaxId(identityType) {
1361
- const prekeys = await this.getAllEcSignedPreKeys(identityType);
1362
- return prekeys.reduce((max, prekey) => Math.max(max, prekey.keyId), 0);
1363
- }
1364
- async getKyberPreKeyMaxId(identityType) {
1365
- const stored = await this.storageBackend.getItem(this.getKyberPreKeyStorageKey(identityType));
1366
- if (!stored)
1367
- return 0;
1368
- const state = JSON.parse(await this.decrypt(stored));
1369
- return Object.keys(state.instances).reduce((max, id) => Math.max(max, Number(id)), 0);
1370
- }
1371
- async deleteAllPreKeys(identityType) {
1372
- this.ensureInitialized();
1373
- const signedPreKeys = await this.getAllEcSignedPreKeys(identityType);
1374
- const ecOneTimePreKeys = await this.getEcOneTimePreKeys(identityType);
1375
- const kyberStateValue = await this.storageBackend.getItem(this.getKyberPreKeyStorageKey(identityType));
1376
- const kyberPreKeyCount = kyberStateValue
1377
- ? Object.keys(JSON.parse(await this.decrypt(kyberStateValue)).instances).length
1378
- : 0;
1379
- const kemOneTimePreKeys = await this.getKemOneTimePreKeys(identityType);
1380
- const it = identityType ?? 'aci';
1381
- await this.storageBackend.removeMany([
1382
- this.getSignedPreKeyStorageKey(identityType),
1383
- this.getEcOneTimePreKeyStorageKey(identityType),
1384
- this.getKyberPreKeyStorageKey(identityType),
1385
- this.getKemOneTimePreKeyStorageKey(identityType),
1386
- ]);
1387
- const allKeys = await this.storageBackend.getAllKeys();
1388
- const kyberUsageKeys = allKeys.filter((key) => key.startsWith(`${STORAGE_KEYS.PREKEY_PREFIX}kyber-usage:${it}:`));
1389
- if (kyberUsageKeys.length > 0) {
1390
- await this.storageBackend.removeMany(kyberUsageKeys);
1391
- }
1392
- return {
1393
- ecSignedPreKeys: signedPreKeys.length,
1394
- ecOneTimePreKeys: ecOneTimePreKeys.length,
1395
- kyberPreKeys: kyberPreKeyCount,
1396
- kemOneTimePreKeys: kemOneTimePreKeys.length,
1397
- };
1398
- }
1399
- async clearAllSessions() {
1400
- this.ensureInitialized();
1401
- const allKeys = await this.storageBackend.getAllKeys();
1402
- const sessionKeys = allKeys.filter((key) => key.startsWith(STORAGE_KEYS.SESSION_PREFIX) ||
1403
- key.startsWith(STORAGE_KEYS.SESAME_USER_PREFIX));
1404
- if (sessionKeys.length > 0) {
1405
- await this.storageBackend.removeMany(sessionKeys);
1406
- }
1407
- }
1408
- async getDetailedStats() {
1409
- this.ensureInitialized();
1410
- const allKeys = await this.storageBackend.getAllKeys();
1411
- return {
1412
- sessions: allKeys.filter((key) => key.startsWith(STORAGE_KEYS.SESSION_PREFIX)).length,
1413
- ecSignedPreKeys: (await this.getAllEcSignedPreKeys('aci')).length +
1414
- (await this.getAllEcSignedPreKeys('pni')).length,
1415
- ecOneTimePreKeys: (await this.getEcOneTimePreKeys('aci')).length +
1416
- (await this.getEcOneTimePreKeys('pni')).length,
1417
- kyberPreKeys: ((await this.getKyberPreKey('aci')) ? 1 : 0) + ((await this.getKyberPreKey('pni')) ? 1 : 0),
1418
- kemOneTimePreKeys: (await this.getKemOneTimePreKeys('aci')).length +
1419
- (await this.getKemOneTimePreKeys('pni')).length,
1420
- users: allKeys.filter((key) => key.startsWith(STORAGE_KEYS.SESAME_USER_PREFIX)).length,
1421
- };
65
+ close() {
66
+ return reactNativeStoreDatabase(this).close();
1422
67
  }
1423
68
  }
69
+ /**
70
+ * Open the store. On first use it creates the database key in the vault, then
71
+ * the database file. With `encryptionAtRest: false` it does not use the vault.
72
+ *
73
+ * @throws EncryptionError with `LOCAL_STORE_KEY_LOST` when the database file
74
+ * exists and the vault holds no key for it. Restore the vault entry, or call
75
+ * {@link resetReactNativeStore}.
76
+ * @throws EncryptionError with `KEY_STORAGE_ERROR` when the vault fails or
77
+ * holds a key of the wrong size, when the key does not open the file, when
78
+ * the file was created with the other `encryptionAtRest` setting, when
79
+ * op-sqlite is not built with SQLCipher, or when another connection holds
80
+ * the file.
81
+ * @throws EncryptionError with `INVALID_STATE` when the name is not valid,
82
+ * when a store of this process holds the name, or when a newer SDK wrote
83
+ * the file.
84
+ */
85
+ export function reactNativeStore(options = {}) {
86
+ return ReactNativeSignalProtocolStore.open(options);
87
+ }
88
+ /**
89
+ * Delete the database file, then create a new key, and return the open, empty
90
+ * store. This is the only way to open a store whose key is lost.
91
+ *
92
+ * @throws EncryptionError with `INVALID_STATE` when the name is not valid, or
93
+ * when a store of this process holds the name. Close that store first.
94
+ */
95
+ export function resetReactNativeStore(options = {}) {
96
+ return ReactNativeSignalProtocolStore.reset(options);
97
+ }
1424
98
  //# sourceMappingURL=adapter.js.map