@rapidmx/web-client 0.35.0 → 0.37.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 (268) hide show
  1. package/apps/escrow/matters/[uid].tsx +4 -3
  2. package/apps/shared/calendar/calendarReminders.ts +35 -0
  3. package/apps/shared/calendar/sealedEvents.ts +113 -0
  4. package/apps/shared/calendar/useCalendarReminders.ts +28 -9
  5. package/apps/shared/components/admin/settings/DomainDnsSetup.tsx +4 -0
  6. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +89 -3
  7. package/apps/shared/components/calendar/EventDetails.tsx +13 -2
  8. package/apps/shared/components/calendar/EventEditor.tsx +124 -17
  9. package/apps/shared/components/calendar/EventFormParts.tsx +1 -0
  10. package/apps/shared/components/calendar/EventModal.tsx +19 -2
  11. package/apps/shared/components/calendar/RequestChangeForm.tsx +4 -1
  12. package/apps/shared/components/calendar/eventForm.ts +2 -0
  13. package/apps/shared/components/contacts/ContactCard.tsx +13 -1
  14. package/apps/shared/components/contacts/ContactDetailPane.tsx +189 -9
  15. package/apps/shared/components/contacts/ContactForm.tsx +56 -7
  16. package/apps/shared/components/contacts/KeyChangeReview.tsx +5 -1
  17. package/apps/shared/components/contacts/contactCardData.ts +8 -4
  18. package/apps/shared/components/contacts/contactKeys.ts +3 -3
  19. package/apps/shared/components/layout/AppShell.tsx +34 -5
  20. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +30 -1
  21. package/apps/shared/components/layout/SharedMailboxKeyManager.tsx +122 -0
  22. package/apps/shared/components/layout/UnlockPromptProvider.tsx +34 -0
  23. package/apps/shared/components/mail/ConversationList.tsx +1 -1
  24. package/apps/shared/components/mail/InviteCard.tsx +11 -1
  25. package/apps/shared/components/mail/MessageDetailPane.tsx +59 -26
  26. package/apps/shared/components/mail/compose/ComposeWindow.tsx +9 -2
  27. package/apps/shared/components/mail/compose/RecipientInput.tsx +2 -1
  28. package/apps/shared/components/mail/compose/draftResume.ts +28 -3
  29. package/apps/shared/components/mail/compose/protectedContactSuggestions.ts +121 -0
  30. package/apps/shared/components/mail/compose/quotedBody.ts +4 -3
  31. package/apps/shared/components/mail/invite/inviteStore.ts +17 -1
  32. package/apps/shared/components/mail/layout/MailShell.tsx +2 -0
  33. package/apps/shared/components/mail/pinnedSigners.ts +14 -0
  34. package/apps/shared/components/mail/reading/conversationPrint.ts +3 -3
  35. package/apps/shared/components/mail/reading/useMessageActions.ts +4 -1
  36. package/apps/shared/components/settings/KeyExportSetting.tsx +173 -0
  37. package/apps/shared/components/settings/OpenPgpKeySetting.tsx +240 -0
  38. package/apps/shared/components/settings/PolicyLockedNotice.tsx +23 -0
  39. package/apps/shared/components/settings/ZeroAccessSetting.tsx +128 -0
  40. package/apps/shared/components/settings/ZeroAccessTypes.tsx +175 -0
  41. package/apps/shared/components/settings/layout/SettingsShell.tsx +9 -2
  42. package/apps/shared/mail/decryptedMessages.ts +11 -3
  43. package/apps/shared/mail/outbox/sendJob.ts +349 -50
  44. package/apps/shared/mail/outbox/sendOutcomes.ts +91 -20
  45. package/apps/shared/mail/reportNotices.ts +3 -1
  46. package/apps/shared/mail/zeroAccessSource.ts +27 -0
  47. package/apps/shared/search/LocalIndexLifecycle.tsx +84 -24
  48. package/apps/shared/search/localIndexBuilder.ts +57 -20
  49. package/apps/shared/search/localIndexRpcClient.ts +96 -12
  50. package/apps/shared/search/localIndexSchema.ts +20 -4
  51. package/apps/shared/search/localIndexTransport.ts +6 -2
  52. package/apps/shared/search/localIndexWorker.ts +37 -18
  53. package/apps/shared/search/searchTier2.ts +5 -0
  54. package/apps/shared/search/zeroAccessIndexSync.ts +679 -0
  55. package/apps/shared/search/zeroAccessSyncState.ts +70 -0
  56. package/apps/shared/zeroAccess/ProtectedMark.tsx +19 -0
  57. package/apps/shared/zeroAccess/useKeysLocked.ts +25 -0
  58. package/apps/shared/zeroAccess/useOpenedRecord.ts +71 -0
  59. package/apps/www/_shell.tsx +2 -0
  60. package/apps/www/calendar/index.tsx +225 -61
  61. package/apps/www/contacts/index.tsx +67 -11
  62. package/apps/www/index.tsx +19 -3
  63. package/apps/www/settings/encryption/index.tsx +21 -1
  64. package/apps/www/settings/privacy/index.tsx +89 -39
  65. package/apps/www/tasks/index.tsx +24 -6
  66. package/dist/apps/escrow/matters/[uid].js +2 -2
  67. package/dist/apps/shared/calendar/calendarReminders.d.ts +14 -0
  68. package/dist/apps/shared/calendar/calendarReminders.js +26 -0
  69. package/dist/apps/shared/calendar/sealedEvents.d.ts +14 -0
  70. package/dist/apps/shared/calendar/sealedEvents.js +85 -0
  71. package/dist/apps/shared/calendar/useCalendarReminders.d.ts +2 -1
  72. package/dist/apps/shared/calendar/useCalendarReminders.js +27 -9
  73. package/dist/apps/shared/components/admin/settings/DomainDnsSetup.js +3 -0
  74. package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.js +25 -2
  75. package/dist/apps/shared/components/calendar/EventDetails.js +13 -2
  76. package/dist/apps/shared/components/calendar/EventEditor.js +115 -18
  77. package/dist/apps/shared/components/calendar/EventFormParts.js +1 -1
  78. package/dist/apps/shared/components/calendar/EventModal.d.ts +1 -1
  79. package/dist/apps/shared/components/calendar/EventModal.js +15 -2
  80. package/dist/apps/shared/components/calendar/RequestChangeForm.d.ts +3 -0
  81. package/dist/apps/shared/components/calendar/RequestChangeForm.js +1 -1
  82. package/dist/apps/shared/components/calendar/eventForm.d.ts +2 -0
  83. package/dist/apps/shared/components/contacts/ContactCard.js +12 -1
  84. package/dist/apps/shared/components/contacts/ContactDetailPane.d.ts +2 -1
  85. package/dist/apps/shared/components/contacts/ContactDetailPane.js +103 -9
  86. package/dist/apps/shared/components/contacts/ContactForm.d.ts +4 -1
  87. package/dist/apps/shared/components/contacts/ContactForm.js +37 -7
  88. package/dist/apps/shared/components/contacts/KeyChangeReview.d.ts +3 -1
  89. package/dist/apps/shared/components/contacts/KeyChangeReview.js +3 -2
  90. package/dist/apps/shared/components/contacts/contactCardData.js +8 -4
  91. package/dist/apps/shared/components/contacts/contactKeys.d.ts +1 -1
  92. package/dist/apps/shared/components/contacts/contactKeys.js +3 -3
  93. package/dist/apps/shared/components/layout/AppShell.d.ts +18 -1
  94. package/dist/apps/shared/components/layout/AppShell.js +17 -6
  95. package/dist/apps/shared/components/layout/KeyEnrollmentGate.js +27 -2
  96. package/dist/apps/shared/components/layout/SharedMailboxKeyManager.d.ts +17 -0
  97. package/dist/apps/shared/components/layout/SharedMailboxKeyManager.js +98 -0
  98. package/dist/apps/shared/components/layout/UnlockPromptProvider.d.ts +3 -0
  99. package/dist/apps/shared/components/layout/UnlockPromptProvider.js +32 -0
  100. package/dist/apps/shared/components/mail/ConversationList.js +1 -1
  101. package/dist/apps/shared/components/mail/InviteCard.js +11 -1
  102. package/dist/apps/shared/components/mail/MessageDetailPane.js +46 -21
  103. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +2 -2
  104. package/dist/apps/shared/components/mail/compose/RecipientInput.js +3 -2
  105. package/dist/apps/shared/components/mail/compose/draftResume.d.ts +2 -0
  106. package/dist/apps/shared/components/mail/compose/draftResume.js +28 -3
  107. package/dist/apps/shared/components/mail/compose/protectedContactSuggestions.d.ts +14 -0
  108. package/dist/apps/shared/components/mail/compose/protectedContactSuggestions.js +96 -0
  109. package/dist/apps/shared/components/mail/compose/quotedBody.d.ts +1 -1
  110. package/dist/apps/shared/components/mail/compose/quotedBody.js +4 -3
  111. package/dist/apps/shared/components/mail/invite/inviteStore.js +16 -1
  112. package/dist/apps/shared/components/mail/layout/MailShell.js +2 -1
  113. package/dist/apps/shared/components/mail/pinnedSigners.d.ts +6 -0
  114. package/dist/apps/shared/components/mail/pinnedSigners.js +10 -1
  115. package/dist/apps/shared/components/mail/reading/conversationPrint.d.ts +2 -2
  116. package/dist/apps/shared/components/mail/reading/conversationPrint.js +3 -3
  117. package/dist/apps/shared/components/mail/reading/useMessageActions.js +4 -1
  118. package/dist/apps/shared/components/settings/KeyExportSetting.d.ts +13 -0
  119. package/dist/apps/shared/components/settings/KeyExportSetting.js +90 -0
  120. package/dist/apps/shared/components/settings/OpenPgpKeySetting.d.ts +13 -0
  121. package/dist/apps/shared/components/settings/OpenPgpKeySetting.js +143 -0
  122. package/dist/apps/shared/components/settings/PolicyLockedNotice.d.ts +11 -0
  123. package/dist/apps/shared/components/settings/PolicyLockedNotice.js +9 -0
  124. package/dist/apps/shared/components/settings/ZeroAccessSetting.d.ts +16 -0
  125. package/dist/apps/shared/components/settings/ZeroAccessSetting.js +80 -0
  126. package/dist/apps/shared/components/settings/ZeroAccessTypes.d.ts +29 -0
  127. package/dist/apps/shared/components/settings/ZeroAccessTypes.js +107 -0
  128. package/dist/apps/shared/components/settings/layout/SettingsShell.d.ts +3 -0
  129. package/dist/apps/shared/components/settings/layout/SettingsShell.js +3 -2
  130. package/dist/apps/shared/mail/decryptedMessages.d.ts +1 -1
  131. package/dist/apps/shared/mail/decryptedMessages.js +11 -3
  132. package/dist/apps/shared/mail/outbox/sendJob.d.ts +37 -4
  133. package/dist/apps/shared/mail/outbox/sendJob.js +287 -42
  134. package/dist/apps/shared/mail/outbox/sendOutcomes.d.ts +12 -0
  135. package/dist/apps/shared/mail/outbox/sendOutcomes.js +76 -20
  136. package/dist/apps/shared/mail/reportNotices.js +3 -1
  137. package/dist/apps/shared/mail/zeroAccessSource.d.ts +8 -0
  138. package/dist/apps/shared/mail/zeroAccessSource.js +26 -0
  139. package/dist/apps/shared/search/LocalIndexLifecycle.d.ts +2 -0
  140. package/dist/apps/shared/search/LocalIndexLifecycle.js +74 -24
  141. package/dist/apps/shared/search/localIndexBuilder.d.ts +9 -1
  142. package/dist/apps/shared/search/localIndexBuilder.js +50 -17
  143. package/dist/apps/shared/search/localIndexRpcClient.d.ts +5 -39
  144. package/dist/apps/shared/search/localIndexRpcClient.js +129 -11
  145. package/dist/apps/shared/search/localIndexSchema.d.ts +14 -2
  146. package/dist/apps/shared/search/localIndexSchema.js +18 -4
  147. package/dist/apps/shared/search/localIndexTransport.d.ts +6 -2
  148. package/dist/apps/shared/search/localIndexWorker.d.ts +11 -0
  149. package/dist/apps/shared/search/localIndexWorker.js +22 -15
  150. package/dist/apps/shared/search/searchTier2.js +5 -0
  151. package/dist/apps/shared/search/zeroAccessIndexSync.d.ts +102 -0
  152. package/dist/apps/shared/search/zeroAccessIndexSync.js +544 -0
  153. package/dist/apps/shared/search/zeroAccessSyncState.d.ts +20 -0
  154. package/dist/apps/shared/search/zeroAccessSyncState.js +65 -0
  155. package/dist/apps/shared/zeroAccess/ProtectedMark.d.ts +7 -0
  156. package/dist/apps/shared/zeroAccess/ProtectedMark.js +10 -0
  157. package/dist/apps/shared/zeroAccess/useKeysLocked.d.ts +6 -0
  158. package/dist/apps/shared/zeroAccess/useKeysLocked.js +20 -0
  159. package/dist/apps/shared/zeroAccess/useOpenedRecord.d.ts +18 -0
  160. package/dist/apps/shared/zeroAccess/useOpenedRecord.js +66 -0
  161. package/dist/apps/www/_shell.d.ts +1 -1
  162. package/dist/apps/www/_shell.js +2 -2
  163. package/dist/apps/www/calendar/index.js +88 -20
  164. package/dist/apps/www/contacts/index.js +64 -11
  165. package/dist/apps/www/index.js +19 -3
  166. package/dist/apps/www/settings/encryption/index.js +16 -4
  167. package/dist/apps/www/settings/privacy/index.js +47 -6
  168. package/dist/apps/www/tasks/index.js +21 -7
  169. package/dist/lib/admin/domainsApi.d.ts +1 -1
  170. package/dist/lib/admin/escrowAccessRequestsApi.d.ts +6 -0
  171. package/dist/lib/calendar/calendarApi.d.ts +52 -6
  172. package/dist/lib/calendar/calendarApi.js +110 -17
  173. package/dist/lib/calendar/calendarMutations.d.ts +20 -7
  174. package/dist/lib/calendar/calendarMutations.js +73 -14
  175. package/dist/lib/calendar/inviteApi.d.ts +17 -3
  176. package/dist/lib/calendar/inviteApi.js +86 -7
  177. package/dist/lib/calendar/protectedEvents.d.ts +31 -0
  178. package/dist/lib/calendar/protectedEvents.js +113 -0
  179. package/dist/lib/calendar/recurrence.d.ts +2 -0
  180. package/dist/lib/calendar/recurrence.js +16 -0
  181. package/dist/lib/calendar/sealedInvites.d.ts +9 -0
  182. package/dist/lib/calendar/sealedInvites.js +65 -0
  183. package/dist/lib/contacts/contactsApi.d.ts +29 -3
  184. package/dist/lib/contacts/contactsApi.js +23 -7
  185. package/dist/lib/contacts/useContactPhotoSrc.d.ts +5 -2
  186. package/dist/lib/contacts/useContactPhotoSrc.js +91 -11
  187. package/dist/lib/crypto/composeSecurity.d.ts +11 -3
  188. package/dist/lib/crypto/composeSecurity.js +13 -5
  189. package/dist/lib/crypto/keyExport.d.ts +54 -0
  190. package/dist/lib/crypto/keyExport.js +161 -0
  191. package/dist/lib/crypto/keyPairMatch.d.ts +9 -0
  192. package/dist/lib/crypto/keyPairMatch.js +65 -0
  193. package/dist/lib/crypto/keySession.d.ts +64 -3
  194. package/dist/lib/crypto/keySession.js +179 -12
  195. package/dist/lib/crypto/keyvaultApi.d.ts +129 -8
  196. package/dist/lib/crypto/keyvaultApi.js +45 -3
  197. package/dist/lib/crypto/meetingKeys.d.ts +25 -0
  198. package/dist/lib/crypto/meetingKeys.js +87 -0
  199. package/dist/lib/crypto/messageSecurity.d.ts +56 -3
  200. package/dist/lib/crypto/messageSecurity.js +201 -13
  201. package/dist/lib/crypto/mime.d.ts +5 -0
  202. package/dist/lib/crypto/mime.js +25 -0
  203. package/dist/lib/crypto/openPgpKey.d.ts +39 -0
  204. package/dist/lib/crypto/openPgpKey.js +89 -0
  205. package/dist/lib/crypto/openpgp.d.ts +47 -0
  206. package/dist/lib/crypto/openpgp.js +88 -0
  207. package/dist/lib/crypto/pgpMessage.d.ts +51 -0
  208. package/dist/lib/crypto/pgpMessage.js +271 -0
  209. package/dist/lib/crypto/sharedMailboxKeys.d.ts +62 -0
  210. package/dist/lib/crypto/sharedMailboxKeys.js +337 -0
  211. package/dist/lib/crypto/smimeMessage.d.ts +21 -0
  212. package/dist/lib/crypto/smimeMessage.js +11 -7
  213. package/dist/lib/crypto/zeroAccessKey.d.ts +32 -0
  214. package/dist/lib/crypto/zeroAccessKey.js +71 -0
  215. package/dist/lib/mail/conversationsApi.d.ts +6 -0
  216. package/dist/lib/mail/mailApi.d.ts +63 -2
  217. package/dist/lib/mail/mailApi.js +5 -1
  218. package/dist/lib/mail/mailboxImportApi.d.ts +10 -0
  219. package/dist/lib/mail/mailboxImportApi.js +15 -0
  220. package/dist/lib/search/zeroAccessIndexApi.d.ts +85 -0
  221. package/dist/lib/search/zeroAccessIndexApi.js +35 -0
  222. package/dist/lib/tasks/tasksApi.d.ts +11 -1
  223. package/dist/lib/tasks/tasksApi.js +10 -4
  224. package/dist/lib/util/clientPlatform.d.ts +14 -0
  225. package/dist/lib/util/clientPlatform.js +26 -0
  226. package/dist/lib/videoconf/protectedMeetings.d.ts +74 -0
  227. package/dist/lib/videoconf/protectedMeetings.js +181 -0
  228. package/dist/lib/videoconf/videoMeetingsApi.d.ts +25 -4
  229. package/dist/lib/videoconf/videoMeetingsApi.js +1 -1
  230. package/dist/lib/zeroAccess/sealedMoves.d.ts +41 -0
  231. package/dist/lib/zeroAccess/sealedMoves.js +63 -0
  232. package/dist/lib/zeroAccess/sealedRecords.d.ts +29 -0
  233. package/dist/lib/zeroAccess/sealedRecords.js +136 -0
  234. package/lib/admin/domainsApi.ts +1 -1
  235. package/lib/admin/escrowAccessRequestsApi.ts +6 -0
  236. package/lib/calendar/calendarApi.ts +143 -17
  237. package/lib/calendar/calendarMutations.ts +79 -12
  238. package/lib/calendar/inviteApi.ts +101 -8
  239. package/lib/calendar/protectedEvents.ts +143 -0
  240. package/lib/calendar/recurrence.ts +17 -0
  241. package/lib/calendar/sealedInvites.ts +73 -0
  242. package/lib/contacts/contactsApi.ts +43 -17
  243. package/lib/contacts/useContactPhotoSrc.ts +103 -13
  244. package/lib/crypto/composeSecurity.ts +20 -5
  245. package/lib/crypto/keyExport.ts +229 -0
  246. package/lib/crypto/keyPairMatch.ts +69 -0
  247. package/lib/crypto/keySession.ts +216 -12
  248. package/lib/crypto/keyvaultApi.ts +174 -10
  249. package/lib/crypto/meetingKeys.ts +118 -0
  250. package/lib/crypto/messageSecurity.ts +284 -16
  251. package/lib/crypto/mime.ts +26 -0
  252. package/lib/crypto/openPgpKey.ts +118 -0
  253. package/lib/crypto/openpgp.ts +115 -0
  254. package/lib/crypto/pgpMessage.ts +336 -0
  255. package/lib/crypto/sharedMailboxKeys.ts +402 -0
  256. package/lib/crypto/smimeMessage.ts +11 -7
  257. package/lib/crypto/zeroAccessKey.ts +102 -0
  258. package/lib/mail/conversationsApi.ts +3 -0
  259. package/lib/mail/mailApi.ts +60 -3
  260. package/lib/mail/mailboxImportApi.ts +24 -0
  261. package/lib/search/zeroAccessIndexApi.ts +123 -0
  262. package/lib/tasks/tasksApi.ts +19 -5
  263. package/lib/util/clientPlatform.ts +50 -0
  264. package/lib/videoconf/protectedMeetings.ts +221 -0
  265. package/lib/videoconf/videoMeetingsApi.ts +15 -4
  266. package/lib/zeroAccess/sealedMoves.ts +79 -0
  267. package/lib/zeroAccess/sealedRecords.ts +153 -0
  268. package/package.json +14 -5
@@ -0,0 +1,679 @@
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ /**
6
+ * Keeps this device's local search index (Tier 2) in step with a zero-access mailbox's server index (`specs/search.md` §7-8): the
7
+ * server extracted every message's text at delivery and stores it only encrypted to the mailbox's zero-access key, as one sealed
8
+ * entry per message until a client compacts a closed week into a segment. A sync pass reads the manifest; imports each segment it
9
+ * hasn't imported in its current generation, newest weeks first (the worker's byte budget evicts the oldest); imports the pending entries
10
+ * written since its last pass (the live tail, asked from a little before then, skipping what it has); and compacts a few closed weeks
11
+ * that still have pending entries - it decrypts them and the week's current segment, merges them, seals the result to the mailbox's
12
+ * active zero-access key and uploads it as the next generation. A lost race (`409`) is left to the next pass.
13
+ *
14
+ * A segment (format version 1, `specs/search.md` §16) is gzipped JSON `{ v: 1, documents }` of the same documents the entries carry, so
15
+ * everything is imported through `indexLocalEntities()` - no new storage primitive, on web and on tauri alike.
16
+ *
17
+ * **Client segments (Source C).** End-to-end mail never reaches the server readable, so the server has nothing to index for it: the local
18
+ * index builder (`localIndexBuilder.ts`) decrypts it on one device and uploads what it built with `uploadClientDocuments()`, as `origin:
19
+ * "client"` segments sealed to the same zero-access key, merged into the week's current one. Every device imports them
20
+ * (`importClientSegments()`, run by the builder before it decrypts anything and by each sync pass), so end-to-end mail is decrypted for
21
+ * search once per mailbox rather than once per device - a row imported at the message's current version is not decrypted again.
22
+ *
23
+ * Nothing here ever sends the server anything it can read: entries are decrypted on this device, and a segment is sealed before upload.
24
+ */
25
+ import { fromBase64, toBase64 } from "../../../lib/crypto/encoding.js";
26
+ import type { UnlockedKeys } from "../../../lib/crypto/keySession.js";
27
+ import { decryptEnvelopedDataWithKeys, encryptForRecipients } from "../../../lib/crypto/smime.js";
28
+ import {
29
+ getSearchIndexManifest,
30
+ getSearchIndexSegment,
31
+ type IndexSegment,
32
+ type IndexWeekEntries,
33
+ listSearchIndexEntries,
34
+ type SegmentManifest,
35
+ putSearchIndexSegment,
36
+ type SealedIndexEntry,
37
+ type ZeroAccessIndexDocument,
38
+ } from "../../../lib/search/zeroAccessIndexApi.js";
39
+ import { ApiRequestError, type ApiClient } from "../../../lib/util/api.js";
40
+ import { clientPlatform, isConstrainedConnection, type ClientPlatform } from "../../../lib/util/clientPlatform.js";
41
+ import { getMessage } from "../../../lib/mail/mailApi.js";
42
+ import { getIndexedVersions, getLocalCoverage, indexLocalEntities, moveLocalEntity } from "./localIndexRpcClient.js";
43
+ import { type LocalIndexEntity, messageRowFlags, messageRowVersion } from "./localIndexSchema.js";
44
+ import { forgetZeroAccessSync, zeroAccessSyncEpoch, zeroAccessSyncStateKey } from "./zeroAccessSyncState.js";
45
+
46
+ export { forgetZeroAccessSync };
47
+
48
+ /** The segment format this client writes and reads. */
49
+ export const SEGMENT_SCHEMA_VERSION = 1;
50
+
51
+ /** How far before its last pass the live tail asks again, so an entry committed late is never skipped. */
52
+ export const TAIL_OVERLAP_MS = 10 * 60 * 1000;
53
+
54
+ /** At most this many weeks are compacted per pass, so a large backlog is worked through over several passes. */
55
+ export const MAX_COMPACTIONS_PER_PASS = 4;
56
+
57
+ /** How long after a week's `compactableAt` each platform takes it (restapi `specs/search.md` §8 *Who compacts*): a computer first,
58
+ * a phone only when nothing else has for a day. */
59
+ export const COMPACTION_DELAY_MS: Record<ClientPlatform, number> = { desktop: 0, web: 6 * 3_600_000, mobile: 24 * 3_600_000 };
60
+
61
+ /** A mobile client declines a week whose pending entries and current segment together are larger than this. */
62
+ export const MOBILE_COMPACTION_MAX_BYTES = 5 * 1024 * 1024;
63
+
64
+ /**
65
+ * Whether this client should compact `week` now: it is compactable, has pending entries, and this platform's delay after its
66
+ * `compactableAt` has passed. A mobile client also declines on a cellular or data-saver connection, and a week larger than
67
+ * `MOBILE_COMPACTION_MAX_BYTES` with `segmentBytes` (its current segment's size) - or of unknown size, or from a server that
68
+ * doesn't say when it became compactable.
69
+ */
70
+ export function shouldCompact(
71
+ week: IndexWeekEntries,
72
+ segmentBytes: number,
73
+ platform: ClientPlatform = clientPlatform(),
74
+ now: number = Date.now(),
75
+ constrained: boolean = isConstrainedConnection(),
76
+ ): boolean {
77
+ if (!week.compactable || week.pendingEntries === 0) {
78
+ return false;
79
+ }
80
+ const since = week.compactableAt ? Date.parse(week.compactableAt) : NaN;
81
+ if (platform === "mobile") {
82
+ if (constrained || Number.isNaN(since) || week.pendingBytes === undefined || week.pendingBytes + segmentBytes > MOBILE_COMPACTION_MAX_BYTES) {
83
+ return false;
84
+ }
85
+ }
86
+ // A server that doesn't say when the week became compactable: compactable is all there is to go on.
87
+ return Number.isNaN(since) || since + COMPACTION_DELAY_MS[platform] <= now;
88
+ }
89
+
90
+ /** Entities handed to the worker per call. */
91
+ const IMPORT_BATCH = 200;
92
+
93
+ /** How many times `uploadClientDocuments()` re-reads a week's client segment after another device replaced it first. */
94
+ export const CLIENT_UPLOAD_ATTEMPTS = 3;
95
+
96
+ /** What a sync pass remembers between passes, per mailbox (`localStorage`): which segment generations it imported and when its live tail
97
+ * last ran. Forgotten whenever the local index is found empty (a new device, a sign-out, a destroyed index). */
98
+ interface SyncState {
99
+ /** `weekId:origin` -> the ETag imported. */
100
+ segments: Record<string, string>;
101
+ /** ISO 8601: when the last live-tail pass started. */
102
+ tailSince?: string;
103
+ /** Where a live-tail pass that ended early stopped: the listing it was paging through (`since`, absent for a whole one), the page
104
+ * after the last one it imported, and when it started - which the pass that finishes it records as `tailSince`, so nothing written
105
+ * while it was interrupted is skipped. */
106
+ tailCursor?: { since?: string; after: string; start: string };
107
+ }
108
+
109
+ /** What a pass did, for the caller's logging and tests. */
110
+ export interface ZeroAccessSyncResult {
111
+ segmentsImported: number;
112
+ /** Client segments (end-to-end mail other devices indexed) imported. */
113
+ clientSegmentsImported: number;
114
+ entriesImported: number;
115
+ weeksCompacted: number;
116
+ /** Entries or segments that wouldn't decrypt with this device's keys (a key it doesn't have) - left as they are. */
117
+ unreadable: number;
118
+ }
119
+
120
+ function loadState(mailboxUid: string): SyncState {
121
+ try {
122
+ const raw = localStorage.getItem(zeroAccessSyncStateKey(mailboxUid));
123
+ const parsed: unknown = raw ? JSON.parse(raw) : undefined;
124
+ if (parsed && typeof parsed === "object" && typeof (parsed as SyncState).segments === "object") {
125
+ return parsed as SyncState;
126
+ }
127
+ } catch {
128
+ // Storage unavailable or corrupt: start over, which only costs a re-import.
129
+ }
130
+ return { segments: {} };
131
+ }
132
+
133
+ /** Remembers `state` - unless the mailbox's local index was destroyed since the pass began (`epoch`, `zeroAccessSyncEpoch()` then): what
134
+ * the pass imported went with it, and a new index must not be taken for it. */
135
+ function saveState(mailboxUid: string, state: SyncState, epoch: string): void {
136
+ if (zeroAccessSyncEpoch(mailboxUid) !== epoch) {
137
+ return;
138
+ }
139
+ try {
140
+ localStorage.setItem(zeroAccessSyncStateKey(mailboxUid), JSON.stringify(state));
141
+ } catch {
142
+ // Not remembered: the next pass imports again, which is idempotent (entities are upserted).
143
+ }
144
+ }
145
+
146
+ async function transform(bytes: Uint8Array, stream: CompressionStream | DecompressionStream): Promise<Uint8Array> {
147
+ const output = new Blob([bytes as BlobPart]).stream().pipeThrough(stream);
148
+ return new Uint8Array(await new Response(output).arrayBuffer());
149
+ }
150
+
151
+ const gunzip = (bytes: Uint8Array): Promise<Uint8Array> => transform(bytes, new DecompressionStream("gzip"));
152
+ const gzip = (bytes: Uint8Array): Promise<Uint8Array> => transform(bytes, new CompressionStream("gzip"));
153
+
154
+ /** The keys that open what the server sealed for this mailbox. */
155
+ type ZeroAccessKeys = NonNullable<UnlockedKeys["zeroAccessKeys"]>;
156
+
157
+ /** Decrypts and gunzips `der` with `keys` and parses the JSON inside - `undefined` when no key opens it or it isn't JSON. */
158
+ async function openSealedJson(der: Uint8Array, keys: ZeroAccessKeys): Promise<unknown> {
159
+ try {
160
+ return JSON.parse(new TextDecoder().decode(await gunzip(await decryptEnvelopedDataWithKeys(der, keys))));
161
+ } catch {
162
+ return undefined;
163
+ }
164
+ }
165
+
166
+ function isDocument(value: unknown): value is ZeroAccessIndexDocument {
167
+ const doc = value as ZeroAccessIndexDocument | undefined;
168
+ return !!doc && doc.v === 1 && typeof doc.messageUid === "string" && typeof doc.subject === "string" && typeof doc.body === "string";
169
+ }
170
+
171
+ /** What the builder (`localIndexBuilder.ts`) knows of a zero-access message from the message list - none of it is in its document. */
172
+ export interface ZeroAccessRowMetadata {
173
+ folderUid: string;
174
+ entityVersion: string;
175
+ /** `,flag,flag,` */
176
+ flags: string;
177
+ }
178
+
179
+ /** At most this many messages' metadata are kept per mailbox for rows not imported yet; the oldest go first. */
180
+ export const MAX_REMEMBERED_METADATA = 50_000;
181
+
182
+ /** Folder, version and flags the builder recorded for zero-access messages, by mailbox and message uid, until their row is imported. */
183
+ const rememberedMetadata = new Map<string, Map<string, ZeroAccessRowMetadata>>();
184
+
185
+ /**
186
+ * Remembers zero-access message `messageUid`'s folder, version and flags for when its row is imported: the builder records them on the row
187
+ * as it walks, which does nothing for a row that isn't there yet (the index started empty - a new device, or after a lock - and this sync
188
+ * imports the rows after the build).
189
+ */
190
+ export function rememberZeroAccessMetadata(mailboxUid: string, messageUid: string, metadata: ZeroAccessRowMetadata): void {
191
+ let remembered = rememberedMetadata.get(mailboxUid);
192
+ if (!remembered) {
193
+ remembered = new Map();
194
+ rememberedMetadata.set(mailboxUid, remembered);
195
+ }
196
+ remembered.delete(messageUid);
197
+ remembered.set(messageUid, metadata);
198
+ if (remembered.size > MAX_REMEMBERED_METADATA) {
199
+ remembered.delete(remembered.keys().next().value!);
200
+ }
201
+ }
202
+
203
+ /** Records on the just-imported rows of `messageUids` what the builder remembered of them, once. */
204
+ async function applyRememberedMetadata(mailboxUid: string, messageUids: string[]): Promise<void> {
205
+ const remembered = rememberedMetadata.get(mailboxUid);
206
+ for (const uid of messageUids) {
207
+ const metadata = remembered?.get(uid);
208
+ if (metadata) {
209
+ await moveLocalEntity(mailboxUid, uid, metadata.folderUid, metadata.entityVersion, metadata.flags);
210
+ remembered!.delete(uid);
211
+ }
212
+ }
213
+ }
214
+
215
+ /** At most this many live-tail rows a pass looks up (`recordTailMetadata()`); the rest get theirs from the next build pass. */
216
+ export const MAX_TAIL_LOOKUPS = 500;
217
+
218
+ /** How many of those lookups run at once. */
219
+ const TAIL_LOOKUP_CONCURRENCY = 4;
220
+
221
+ /**
222
+ * Gives the live tail's rows that nothing recorded yet (`docs`: rows the builder hasn't seen - mail that arrived after its walk) their
223
+ * folder, version and flags at import, from the message itself, so a folder or flag filter finds them before the next build pass. At
224
+ * most `MAX_TAIL_LOOKUPS`. Best effort: a message that is gone, moved to another mailbox or won't load is left to the builder.
225
+ */
226
+ async function recordTailMetadata(mailboxUid: string, messageUids: string[], client?: ApiClient): Promise<void> {
227
+ const queue: string[] = messageUids.slice(0, MAX_TAIL_LOOKUPS);
228
+ const worker = async (): Promise<void> => {
229
+ for (let uid = queue.shift(); uid !== undefined; uid = queue.shift()) {
230
+ try {
231
+ const message = await getMessage(uid, client);
232
+ if (message.mailboxUid === mailboxUid && message.folderUid) {
233
+ await moveLocalEntity(mailboxUid, uid, message.folderUid, messageRowVersion(message), messageRowFlags(message));
234
+ }
235
+ } catch {
236
+ // Left to the next build pass.
237
+ }
238
+ }
239
+ };
240
+ await Promise.all(Array.from({ length: Math.min(TAIL_LOOKUP_CONCURRENCY, queue.length) }, worker));
241
+ }
242
+
243
+ /** A document as a row of the local index. Folder and flags aren't in the document - the builder records them (`localIndexBuilder.ts`,
244
+ * here through `rememberZeroAccessMetadata()` when the row came later; a live-tail row nothing recorded is looked up,
245
+ * `recordTailMetadata()`), and the upsert keeps what is already there. */
246
+ export function documentEntity(mailboxUid: string, doc: ZeroAccessIndexDocument): LocalIndexEntity {
247
+ const participants: string = (doc.participants ?? []).join(" ");
248
+ const attachmentText: string = [...(doc.attachmentNames ?? []), ...(doc.attachmentText ?? [])].join("\n");
249
+ return {
250
+ entityType: "message",
251
+ entityUid: doc.messageUid,
252
+ mailboxUid,
253
+ dateForSort: new Date(Number.isFinite(doc.dateForSort) ? doc.dateForSort : 0).toISOString(),
254
+ participants,
255
+ flags: "",
256
+ hasAttachments: (doc.attachmentNames ?? []).length > 0,
257
+ subject: doc.subject,
258
+ body: doc.body,
259
+ attachmentText,
260
+ byteSize: doc.subject.length + doc.body.length + attachmentText.length + participants.length,
261
+ };
262
+ }
263
+
264
+ async function importDocuments(mailboxUid: string, docs: ZeroAccessIndexDocument[]): Promise<void> {
265
+ for (let i = 0; i < docs.length; i += IMPORT_BATCH) {
266
+ const batch = docs.slice(i, i + IMPORT_BATCH);
267
+ await indexLocalEntities(
268
+ mailboxUid,
269
+ batch.map((doc) => documentEntity(mailboxUid, doc)),
270
+ );
271
+ await applyRememberedMetadata(
272
+ mailboxUid,
273
+ batch.map((doc) => doc.messageUid),
274
+ );
275
+ }
276
+ }
277
+
278
+ /** The documents of a segment generation that pass `accept`, or `undefined` when it won't open or is a format this client doesn't read. */
279
+ async function readSegmentAs<T>(
280
+ mailboxUid: string,
281
+ segment: IndexSegment,
282
+ keys: ZeroAccessKeys,
283
+ accept: (value: unknown) => value is T,
284
+ client?: ApiClient,
285
+ ): Promise<T[] | undefined> {
286
+ if (segment.schemaVersion !== SEGMENT_SCHEMA_VERSION) {
287
+ return undefined;
288
+ }
289
+ const bundle = (await openSealedJson(await getSearchIndexSegment(mailboxUid, segment, client), keys)) as { v?: number; documents?: unknown[] } | undefined;
290
+ return bundle?.v === SEGMENT_SCHEMA_VERSION && Array.isArray(bundle.documents) ? bundle.documents.filter(accept) : undefined;
291
+ }
292
+
293
+ const readSegment = (mailboxUid: string, segment: IndexSegment, keys: ZeroAccessKeys, client?: ApiClient): Promise<ZeroAccessIndexDocument[] | undefined> =>
294
+ readSegmentAs(mailboxUid, segment, keys, isDocument, client);
295
+
296
+ /** `documents` gzipped and sealed to `key` as a segment file, base64. */
297
+ async function sealSegment(documents: unknown[], key: ZeroAccessKeys[number]): Promise<string> {
298
+ const file = await gzip(new TextEncoder().encode(JSON.stringify({ v: SEGMENT_SCHEMA_VERSION, documents })));
299
+ return toBase64(await encryptForRecipients(file, [key.certDer]));
300
+ }
301
+
302
+ /** One document of a client segment: a local index row of an end-to-end message, as the device that decrypted it built it. */
303
+ export interface ClientIndexDocument {
304
+ v: 1;
305
+ messageUid: string;
306
+ folderUid?: string;
307
+ /** ISO 8601. */
308
+ dateForSort: string;
309
+ participants: string;
310
+ flags: string;
311
+ hasAttachments: boolean;
312
+ subject?: string;
313
+ body?: string;
314
+ attachmentText?: string;
315
+ /** The message's version when it was decrypted (`localIndexBuilder.ts`'s `versionOf()`). */
316
+ entityVersion?: string;
317
+ }
318
+
319
+ function isClientDocument(value: unknown): value is ClientIndexDocument {
320
+ const doc = value as ClientIndexDocument | undefined;
321
+ return !!doc && doc.v === 1 && typeof doc.messageUid === "string" && typeof doc.dateForSort === "string" && typeof doc.participants === "string";
322
+ }
323
+
324
+ /** A local index row as a client segment document. */
325
+ export function clientDocument(entity: LocalIndexEntity): ClientIndexDocument {
326
+ return {
327
+ v: 1,
328
+ messageUid: entity.entityUid,
329
+ folderUid: entity.folderUid,
330
+ dateForSort: entity.dateForSort,
331
+ participants: entity.participants,
332
+ flags: entity.flags,
333
+ hasAttachments: entity.hasAttachments,
334
+ subject: entity.subject,
335
+ body: entity.body,
336
+ attachmentText: entity.attachmentText,
337
+ entityVersion: entity.entityVersion,
338
+ };
339
+ }
340
+
341
+ /** A client segment document as a row of the local index. */
342
+ export function clientDocumentEntity(mailboxUid: string, doc: ClientIndexDocument): LocalIndexEntity {
343
+ const text: number = [doc.subject, doc.body, doc.attachmentText, doc.participants].reduce((total, value) => total + (value?.length ?? 0), 0);
344
+ return {
345
+ entityType: "message",
346
+ entityUid: doc.messageUid,
347
+ mailboxUid,
348
+ ...(doc.folderUid !== undefined ? { folderUid: doc.folderUid } : {}),
349
+ dateForSort: doc.dateForSort,
350
+ participants: doc.participants,
351
+ flags: typeof doc.flags === "string" ? doc.flags : "",
352
+ hasAttachments: doc.hasAttachments === true,
353
+ ...(doc.subject !== undefined ? { subject: doc.subject } : {}),
354
+ ...(doc.body !== undefined ? { body: doc.body } : {}),
355
+ ...(doc.attachmentText !== undefined ? { attachmentText: doc.attachmentText } : {}),
356
+ byteSize: text,
357
+ ...(doc.entityVersion !== undefined ? { entityVersion: doc.entityVersion } : {}),
358
+ };
359
+ }
360
+
361
+ /** The ISO 8601 week (UTC) of `date`, as `YYYY-Www` - the week a message's segment is filed under (restapi's `isoWeekId()`). */
362
+ export function isoWeekId(date: Date): string {
363
+ const day = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
364
+ // The Thursday of this ISO week decides its year (weeks start on Monday; getUTCDay() has Sunday as 0).
365
+ const weekday: number = day.getUTCDay() || 7;
366
+ day.setUTCDate(day.getUTCDate() + 4 - weekday);
367
+ const yearStart = new Date(Date.UTC(day.getUTCFullYear(), 0, 1));
368
+ const week: number = Math.ceil(((day.getTime() - yearStart.getTime()) / 86_400_000 + 1) / 7);
369
+ return `${day.getUTCFullYear()}-W${String(week).padStart(2, "0")}`;
370
+ }
371
+
372
+ /**
373
+ * The sync state, started over when the local index is empty (nothing remembered in it is there any more). What was stored is dropped then
374
+ * too: it describes an index that is gone (pruned, or discarded as corrupted, behind this module's back), and a later pass that found this
375
+ * index filled by the build's end-to-end mail would take it up and skip the segments it never got.
376
+ */
377
+ async function currentState(mailboxUid: string): Promise<SyncState> {
378
+ if ((await getLocalCoverage(mailboxUid)).indexedCount > 0) {
379
+ return loadState(mailboxUid);
380
+ }
381
+ try {
382
+ localStorage.removeItem(zeroAccessSyncStateKey(mailboxUid));
383
+ } catch {
384
+ // Nothing stored to drop.
385
+ }
386
+ return { segments: {} };
387
+ }
388
+
389
+ /**
390
+ * Imports the client segments of `mailboxUid` (end-to-end mail indexed by another device - see this module's comment) not yet imported in
391
+ * their current generation, newest week first: how many. `manifest` saves reading it again; `generation` is the calling build pass's (see
392
+ * `GenerationParams`). Segments this device can't open are skipped.
393
+ */
394
+ export async function importClientSegments(
395
+ mailboxUid: string,
396
+ unlocked: UnlockedKeys,
397
+ client?: ApiClient,
398
+ { manifest, generation }: { manifest?: SegmentManifest; generation?: number } = {},
399
+ ): Promise<number> {
400
+ const keys: ZeroAccessKeys | undefined = unlocked.zeroAccessKeys;
401
+ if (!keys?.length) {
402
+ return 0;
403
+ }
404
+ const epoch: string = zeroAccessSyncEpoch(mailboxUid);
405
+ // Read first, while a new index is still empty: its stale state is dropped even when the manifest can't be read.
406
+ const state: SyncState = await currentState(mailboxUid);
407
+ const segments: IndexSegment[] = (manifest ?? (await getSearchIndexManifest(mailboxUid, client))).segments.filter((segment) => segment.origin === "client");
408
+ let imported = 0;
409
+ for (const segment of segments.sort((a, b) => b.weekId.localeCompare(a.weekId))) {
410
+ const key = `${segment.weekId}:${segment.origin}`;
411
+ if (state.segments[key] === segment.etag) {
412
+ continue;
413
+ }
414
+ const docs = await readSegmentAs(mailboxUid, segment, keys, isClientDocument, client);
415
+ if (!docs) {
416
+ continue;
417
+ }
418
+ for (let i = 0; i < docs.length; i += IMPORT_BATCH) {
419
+ await indexLocalEntities(
420
+ mailboxUid,
421
+ docs.slice(i, i + IMPORT_BATCH).map((doc) => clientDocumentEntity(mailboxUid, doc)),
422
+ generation,
423
+ );
424
+ }
425
+ state.segments[key] = segment.etag;
426
+ saveState(mailboxUid, state, epoch);
427
+ imported++;
428
+ }
429
+ return imported;
430
+ }
431
+
432
+ /**
433
+ * Uploads end-to-end messages this device just decrypted and indexed (`entities`) to `mailboxUid`'s client segments, one per ISO week of
434
+ * `dateForSort`, each merged by message into the week's current segment and sealed to the active zero-access key: how many weeks were
435
+ * written. A week whose current segment this device can't read is left alone (merging would drop what is in it), as is one that already
436
+ * holds every document at the same version. Another device replacing a week first (`409`) is retried with its generation, up to
437
+ * `CLIENT_UPLOAD_ATTEMPTS` times. Does nothing without unlocked zero-access keys.
438
+ */
439
+ export async function uploadClientDocuments(mailboxUid: string, unlocked: UnlockedKeys, entities: LocalIndexEntity[], client?: ApiClient): Promise<number> {
440
+ const keys: ZeroAccessKeys | undefined = unlocked.zeroAccessKeys;
441
+ if (!keys?.length || entities.length === 0) {
442
+ return 0;
443
+ }
444
+ const weeks = new Map<string, ClientIndexDocument[]>();
445
+ for (const entity of entities) {
446
+ const weekId: string = isoWeekId(new Date(entity.dateForSort));
447
+ let week = weeks.get(weekId);
448
+ if (!week) {
449
+ week = [];
450
+ weeks.set(weekId, week);
451
+ }
452
+ week.push(clientDocument(entity));
453
+ }
454
+ const epoch: string = zeroAccessSyncEpoch(mailboxUid);
455
+ const state: SyncState = loadState(mailboxUid);
456
+ let written = 0;
457
+ let manifest: SegmentManifest | undefined;
458
+ for (const [weekId, docs] of weeks) {
459
+ for (let attempt = 0; attempt < CLIENT_UPLOAD_ATTEMPTS; attempt++) {
460
+ manifest ??= await getSearchIndexManifest(mailboxUid, client);
461
+ const current: IndexSegment | undefined = manifest.segments.find((segment) => segment.origin === "client" && segment.weekId === weekId);
462
+ const previous: ClientIndexDocument[] | undefined = current ? await readSegmentAs(mailboxUid, current, keys, isClientDocument, client) : [];
463
+ if (!previous) {
464
+ break;
465
+ }
466
+ const merged = new Map<string, ClientIndexDocument>(previous.map((doc) => [doc.messageUid, doc]));
467
+ if (docs.every((doc) => merged.has(doc.messageUid) && merged.get(doc.messageUid)!.entityVersion === doc.entityVersion)) {
468
+ break;
469
+ }
470
+ for (const doc of docs) {
471
+ merged.set(doc.messageUid, doc);
472
+ }
473
+ try {
474
+ const stored = await putSearchIndexSegment(
475
+ mailboxUid,
476
+ weekId,
477
+ {
478
+ expectedGeneration: current?.generation ?? 0,
479
+ segment: await sealSegment([...merged.values()], keys[0]),
480
+ keyFingerprint: keys[0].fingerprint,
481
+ schemaVersion: SEGMENT_SCHEMA_VERSION,
482
+ origin: "client",
483
+ },
484
+ client,
485
+ );
486
+ // This device already holds every document of the new generation only if it held the previous one.
487
+ if (current && state.segments[`${weekId}:client`] === current.etag) {
488
+ state.segments[`${weekId}:client`] = stored.etag;
489
+ saveState(mailboxUid, state, epoch);
490
+ }
491
+ written++;
492
+ break;
493
+ } catch (err) {
494
+ if (!(err instanceof ApiRequestError && err.status === 409)) {
495
+ throw err;
496
+ }
497
+ manifest = undefined;
498
+ }
499
+ }
500
+ }
501
+ return written;
502
+ }
503
+
504
+ /** Every pending entry of `week`, paged through. */
505
+ async function listAllEntries(mailboxUid: string, filter: { week: string }, client?: ApiClient): Promise<SealedIndexEntry[]> {
506
+ const entries: SealedIndexEntry[] = [];
507
+ let after: string | undefined;
508
+ do {
509
+ const page = await listSearchIndexEntries(mailboxUid, { ...filter, ...(after ? { after } : {}) }, client);
510
+ entries.push(...page.entries);
511
+ after = page.next;
512
+ } while (after);
513
+ return entries;
514
+ }
515
+
516
+ /** Per mailbox, the weeks a compaction found it can't fold on this device - a segment it can't read, or pending entries sealed to a key
517
+ * it doesn't hold (an older key a shared mailbox's member hasn't been given yet) - with how many entries were pending then, and the
518
+ * zero-access keys it had. Such a week stays pending, and the oldest weeks come first: without this, a few of them would take every pass's
519
+ * `MAX_COMPACTIONS_PER_PASS` and no other week would ever be compacted here. A week is tried again once its count changes (new entries,
520
+ * or another device folded it), and every week once this device's keys do. */
521
+ const stalled = new Map<string, { keys: string; weeks: Map<string, number> }>();
522
+
523
+ /** The weeks of `mailboxUid` this device found it can't fold with `keys` (see `stalled`). */
524
+ function stalledWeeks(mailboxUid: string, keys: ZeroAccessKeys): Map<string, number> {
525
+ const fingerprints: string = keys.map((key) => key.fingerprint).join(",");
526
+ let entry = stalled.get(mailboxUid);
527
+ if (entry?.keys !== fingerprints) {
528
+ entry = { keys: fingerprints, weeks: new Map() };
529
+ stalled.set(mailboxUid, entry);
530
+ }
531
+ return entry.weeks;
532
+ }
533
+
534
+ /** The documents of `entries` that open, with the uids of those entries; how many didn't. */
535
+ async function openEntries(entries: SealedIndexEntry[], keys: ZeroAccessKeys): Promise<{ docs: ZeroAccessIndexDocument[]; uids: string[]; unreadable: number }> {
536
+ const docs: ZeroAccessIndexDocument[] = [];
537
+ const uids: string[] = [];
538
+ let unreadable = 0;
539
+ for (const entry of entries) {
540
+ const doc = await openSealedJson(fromBase64(entry.sealed), keys);
541
+ if (isDocument(doc)) {
542
+ docs.push(doc);
543
+ uids.push(entry.uid);
544
+ } else {
545
+ unreadable++;
546
+ }
547
+ }
548
+ return { docs, uids, unreadable };
549
+ }
550
+
551
+ /**
552
+ * One sync pass for `mailboxUid` (see this module's comment). Does nothing without unlocked zero-access keys. Rejects when the manifest
553
+ * can't be read; any later failure ends the pass early with what it had done so far remembered.
554
+ */
555
+ export async function syncZeroAccessIndex(mailboxUid: string, unlocked: UnlockedKeys, client?: ApiClient): Promise<ZeroAccessSyncResult> {
556
+ const result: ZeroAccessSyncResult = { segmentsImported: 0, clientSegmentsImported: 0, entriesImported: 0, weeksCompacted: 0, unreadable: 0 };
557
+ const keys: ZeroAccessKeys | undefined = unlocked.zeroAccessKeys;
558
+ if (!keys?.length) {
559
+ return result;
560
+ }
561
+ const epoch: string = zeroAccessSyncEpoch(mailboxUid);
562
+ const manifest = await getSearchIndexManifest(mailboxUid, client);
563
+ let state: SyncState = await currentState(mailboxUid);
564
+
565
+ // Segments, newest week first.
566
+ const zeroAccessSegments: IndexSegment[] = manifest.segments.filter((segment) => segment.origin === "zero-access");
567
+ for (const segment of [...zeroAccessSegments].sort((a, b) => b.weekId.localeCompare(a.weekId))) {
568
+ const key = `${segment.weekId}:${segment.origin}`;
569
+ if (state.segments[key] === segment.etag) {
570
+ continue;
571
+ }
572
+ const docs = await readSegment(mailboxUid, segment, keys, client);
573
+ if (!docs) {
574
+ result.unreadable++;
575
+ continue;
576
+ }
577
+ await importDocuments(mailboxUid, docs);
578
+ state.segments[key] = segment.etag;
579
+ result.segmentsImported++;
580
+ saveState(mailboxUid, state, epoch);
581
+ }
582
+
583
+ // End-to-end mail other devices indexed.
584
+ saveState(mailboxUid, state, epoch);
585
+ result.clientSegmentsImported = await importClientSegments(mailboxUid, unlocked, client, { manifest });
586
+ state = loadState(mailboxUid);
587
+
588
+ // The live tail, a page at a time: without a `since` (a new or emptied local index) it is every pending entry of the mailbox, which
589
+ // after zero-access is turned on can be every message it has - never held, opened, all at once. Each page imported is remembered
590
+ // (`tailCursor`), so a pass that ends early is taken up where it stopped rather than from the start.
591
+ const since = state.tailSince ? new Date(new Date(state.tailSince).getTime() - TAIL_OVERLAP_MS).toISOString() : undefined;
592
+ const resumed = state.tailCursor?.since === since ? state.tailCursor : undefined;
593
+ const tailStart: string = resumed?.start ?? new Date().toISOString();
594
+ // Rows nothing has recorded a folder and flags for: not on this device with a version yet (the builder's mark), nor remembered by it.
595
+ // Asked in batches - a backlog's tail can be every message of the mailbox, past what one SQL statement may bind - and only until there
596
+ // are as many as a pass looks up.
597
+ const remembered = rememberedMetadata.get(mailboxUid);
598
+ const asked = new Set<string>();
599
+ const unrecorded: string[] = [];
600
+ let after: string | undefined = resumed?.after;
601
+ do {
602
+ const page = await listSearchIndexEntries(mailboxUid, { ...(since ? { since } : {}), ...(after ? { after } : {}) }, client);
603
+ const tail = await openEntries(page.entries, keys);
604
+ const tailUids: string[] = [...new Set(tail.docs.map((doc) => doc.messageUid))].filter((uid) => !asked.has(uid));
605
+ tailUids.forEach((uid) => asked.add(uid));
606
+ for (let i = 0; i < tailUids.length && unrecorded.length < MAX_TAIL_LOOKUPS; i += IMPORT_BATCH) {
607
+ const batch: string[] = tailUids.slice(i, i + IMPORT_BATCH);
608
+ const recorded: Record<string, string> = await getIndexedVersions(mailboxUid, batch);
609
+ unrecorded.push(...batch.filter((uid) => recorded[uid] === undefined && !remembered?.has(uid)));
610
+ }
611
+ await importDocuments(mailboxUid, tail.docs);
612
+ result.entriesImported += tail.docs.length;
613
+ result.unreadable += tail.unreadable;
614
+ after = page.next;
615
+ if (after) {
616
+ state.tailCursor = { ...(since ? { since } : {}), after, start: tailStart };
617
+ saveState(mailboxUid, state, epoch);
618
+ }
619
+ } while (after);
620
+ await recordTailMetadata(mailboxUid, unrecorded, client);
621
+ state.tailSince = tailStart;
622
+ delete state.tailCursor;
623
+ saveState(mailboxUid, state, epoch);
624
+
625
+ // Compaction of closed weeks, passing over those this device found it can't fold (`stalled`) while nothing has changed in them.
626
+ const active = keys[0];
627
+ const stalledHere: Map<string, number> = stalledWeeks(mailboxUid, keys);
628
+ const segmentOf = (weekId: string): IndexSegment | undefined => zeroAccessSegments.find((segment) => segment.weekId === weekId);
629
+ const weeks: IndexWeekEntries[] = manifest.weeks.filter((w) => stalledHere.get(w.weekId) !== w.pendingEntries && shouldCompact(w, segmentOf(w.weekId)?.bytes ?? 0));
630
+ for (const week of weeks.slice(0, MAX_COMPACTIONS_PER_PASS)) {
631
+ const current: IndexSegment | undefined = segmentOf(week.weekId);
632
+ const previous: ZeroAccessIndexDocument[] | undefined = current ? await readSegment(mailboxUid, current, keys, client) : [];
633
+ if (!previous) {
634
+ // A generation this device can't read can't be folded into: leave the week to a device that can.
635
+ stalledHere.set(week.weekId, week.pendingEntries);
636
+ continue;
637
+ }
638
+ const pending = await openEntries(await listAllEntries(mailboxUid, { week: week.weekId }, client), keys);
639
+ if (pending.uids.length === 0) {
640
+ stalledHere.set(week.weekId, week.pendingEntries);
641
+ continue;
642
+ }
643
+ // What this device can't open stays pending once the rest is folded: the week is passed over until that count changes.
644
+ if (pending.unreadable > 0) {
645
+ stalledHere.set(week.weekId, pending.unreadable);
646
+ } else {
647
+ stalledHere.delete(week.weekId);
648
+ }
649
+ const merged = new Map<string, ZeroAccessIndexDocument>(previous.map((doc) => [doc.messageUid, doc]));
650
+ for (const doc of pending.docs) {
651
+ merged.set(doc.messageUid, doc);
652
+ }
653
+ try {
654
+ const stored = await putSearchIndexSegment(
655
+ mailboxUid,
656
+ week.weekId,
657
+ {
658
+ expectedGeneration: current?.generation ?? 0,
659
+ segment: await sealSegment([...merged.values()], active),
660
+ keyFingerprint: active.fingerprint,
661
+ schemaVersion: SEGMENT_SCHEMA_VERSION,
662
+ foldedEntryUids: pending.uids,
663
+ },
664
+ client,
665
+ );
666
+ // This device already holds every document of the new generation.
667
+ await importDocuments(mailboxUid, pending.docs);
668
+ state.segments[`${stored.weekId}:${stored.origin}`] = stored.etag;
669
+ saveState(mailboxUid, state, epoch);
670
+ result.weeksCompacted++;
671
+ } catch (err) {
672
+ // Another device compacted the week first: the next pass imports its generation.
673
+ if (!(err instanceof ApiRequestError && err.status === 409)) {
674
+ throw err;
675
+ }
676
+ }
677
+ }
678
+ return result;
679
+ }