@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,143 @@
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ /**
6
+ * Writes to an event of a calendar zero-access encryption protects (restapi `specs/search.md` §3 *What It Covers*, *Calendar invitations*).
7
+ * The server stores its title, location and description sealed, with placeholders in their place, so it can't tell what changed or invite
8
+ * with them by itself. A write therefore sends only the content fields that differ from what this device shows, and - when the event was
9
+ * opened here - the whole content as `invitationContent`, which the server invites with and never stores. A content field of an opened
10
+ * event that held a value and is emptied is named in `clearedFields`, the only way restapi applies an empty sealed field as a clear.
11
+ */
12
+ import type { CalendarEvent } from "./calendarApi.js";
13
+ import { isOpenedRecord, isProtectedRecord } from "../zeroAccess/sealedRecords.js";
14
+ import { KeysLockedError } from "../crypto/masterKey.js";
15
+
16
+ /** The fields zero-access encryption seals on an event. */
17
+ export const EVENT_CONTENT_FIELDS = ["title", "location", "description", "descriptionHtml"] as const;
18
+
19
+ /** What the server composes a protected event's invitations with. */
20
+ export interface InvitationContent {
21
+ title: string;
22
+ location?: string;
23
+ description?: string;
24
+ descriptionHtml?: string;
25
+ }
26
+
27
+ const text = (value: unknown): string => (typeof value === "string" ? value : "");
28
+
29
+ /** Set on an event made from a zero-access invitation (`sealedContent`) whose sealed content was opened on this device
30
+ * (`apps/shared/calendar/sealedEvents.ts`). A symbol, so it survives a spread copy (an occurrence) and is never sent. */
31
+ const CONTENT_OPENED = Symbol("openedSealedContent");
32
+
33
+ /** `event` marked as holding its opened `sealedContent` (its real title, location and description). */
34
+ export function markSealedContentOpened<T extends CalendarEvent>(event: T): T {
35
+ return { ...event, [CONTENT_OPENED]: true };
36
+ }
37
+
38
+ /** Whether `event`'s `sealedContent` was opened on this device: its title, location and description are the real ones. */
39
+ export function isSealedContentOpened(event: CalendarEvent | undefined): boolean {
40
+ return !!event && (event as any)[CONTENT_OPENED] === true;
41
+ }
42
+
43
+ /** Whether `event` shows its real content: nothing of it is sealed, or every sealed part (`sealedFields`, `sealedContent`) was opened. */
44
+ function shownOpened(event: CalendarEvent): boolean {
45
+ return (!isProtectedRecord(event) || isOpenedRecord(event)) && (!event.sealedContent || isSealedContentOpened(event));
46
+ }
47
+
48
+ /** `current`'s content with `changes` applied, for the server to invite (or name a reply or change request) with - `undefined` unless
49
+ * `current` is protected (`sealedFields`) or made from a zero-access invitation (`sealedContent`) and was opened on this device (its values
50
+ * are otherwise placeholders). */
51
+ export function invitationContentOf(current: CalendarEvent | undefined, changes: Record<string, unknown> = {}): InvitationContent | undefined {
52
+ if (!current || !(isProtectedRecord(current) || current.sealedContent) || !shownOpened(current)) {
53
+ return undefined;
54
+ }
55
+ const value = (field: (typeof EVENT_CONTENT_FIELDS)[number]): string => text(field in changes ? changes[field] : current[field]);
56
+ const title = value("title");
57
+ if (!title) {
58
+ return undefined;
59
+ }
60
+ const optional = (field: (typeof EVENT_CONTENT_FIELDS)[number]): string | undefined => value(field) || undefined;
61
+ return { title, location: optional("location"), description: optional("description"), descriptionHtml: optional("descriptionHtml") };
62
+ }
63
+
64
+ /**
65
+ * `input` as written to `current`: unchanged when `current` isn't protected. Otherwise without the content fields whose values `current`
66
+ * already shows (a placeholder is "unchanged" too, so a locked device's write never overwrites the sealed value), and with
67
+ * `invitationContent` when `current` was opened - and `clearedFields` naming the sealed ones it empties.
68
+ */
69
+ export function protectedEventWrite<T extends object>(current: CalendarEvent | undefined, input: T): T {
70
+ if (current?.sealedContent) {
71
+ return sealedContentWrite(current, input);
72
+ }
73
+ if (!isProtectedRecord(current)) {
74
+ return input;
75
+ }
76
+ const changes: Record<string, unknown> = { ...(input as Record<string, unknown>) };
77
+ const clearedFields: string[] = [];
78
+ for (const field of EVENT_CONTENT_FIELDS) {
79
+ if (!(field in changes)) {
80
+ continue;
81
+ }
82
+ if (text(changes[field]) === text(current![field])) {
83
+ delete changes[field];
84
+ } else if (!text(changes[field]) && current!.sealedFields![field] !== undefined && isOpenedRecord(current)) {
85
+ clearedFields.push(field);
86
+ }
87
+ }
88
+ if (clearedFields.length > 0) {
89
+ changes.clearedFields = clearedFields;
90
+ }
91
+ const invitationContent = invitationContentOf(current, changes);
92
+ return (invitationContent ? { ...changes, invitationContent } : changes) as T;
93
+ }
94
+
95
+ /**
96
+ * `input` as written to `current`, an event made from a zero-access invitation (`sealedContent`). restapi seals its whole content again
97
+ * from the content fields a write sends (`BaseCalendarEventRoute.keepSealed()`), dropping one the write leaves out, since it can't read the
98
+ * sealed value to keep it. So a write that sends any of them sends them all: those it leaves out (the event dialog sends an unchanged
99
+ * description not at all) are filled in with what `current` shows opened - the description and its HTML as one, as the dialog sends them.
100
+ * This holds too for a row that also keeps its title sealed field by field (`sealedFields.title`), whose sealed content's title is empty.
101
+ * Shown with placeholders (its mailbox is locked), the placeholders it would send back are left out, so nothing is sealed again, and a
102
+ * changed content field is refused (`KeysLockedError`) before anything is sent: the rest of the content can't be sent with it. Opened, a
103
+ * write whose location, description or description HTML differs from the one shown raises `sequence` past `current`'s, the only way
104
+ * restapi learns it changed.
105
+ */
106
+ function sealedContentWrite<T extends object>(current: CalendarEvent, input: T): T {
107
+ const given = input as Record<string, unknown>;
108
+ if (!EVENT_CONTENT_FIELDS.some((field) => given[field] !== undefined)) {
109
+ return input;
110
+ }
111
+ const changes: Record<string, unknown> = { ...given };
112
+ if (!shownOpened(current)) {
113
+ for (const field of EVENT_CONTENT_FIELDS) {
114
+ if (field in changes && text(changes[field]) === text(current[field])) {
115
+ delete changes[field];
116
+ }
117
+ }
118
+ if (EVENT_CONTENT_FIELDS.some((field) => changes[field] !== undefined)) {
119
+ throw new KeysLockedError("This event is protected and your mailbox is locked. Unlock it to change its title, location or description.");
120
+ }
121
+ return changes as T;
122
+ }
123
+ for (const field of ["title", "location"] as const) {
124
+ if (changes[field] === undefined) {
125
+ changes[field] = current[field] ?? null;
126
+ }
127
+ }
128
+ if (changes.description === undefined && changes.descriptionHtml === undefined) {
129
+ changes.description = current.description ?? null;
130
+ changes.descriptionHtml = current.descriptionHtml ?? null;
131
+ }
132
+ // restapi can't compare a location or description sealed whole (it holds placeholders), so a real change raises the sequence here: an
133
+ // organizer-owned meeting then invites again, as for a readable event's new location or description. A description field the write
134
+ // doesn't send is compared no more than restapi compares it for a readable event. An unchanged one leaves it alone.
135
+ const descriptionChanged = (["description", "descriptionHtml"] as const).some(
136
+ (field) => changes[field] !== undefined && text(changes[field]) !== text(current[field])
137
+ );
138
+ if (descriptionChanged || text(changes.location) !== text(current.location)) {
139
+ changes.sequence = (current.sequence ?? 0) + 1;
140
+ }
141
+ const invitationContent = isProtectedRecord(current) ? invitationContentOf(current, changes) : undefined;
142
+ return (invitationContent ? { ...changes, invitationContent } : changes) as T;
143
+ }
@@ -334,3 +334,20 @@ export const WEEKDAY_LABELS: Record<WeekdayCode, string> = {
334
334
  SA: "Sat",
335
335
  SU: "Sun",
336
336
  };
337
+
338
+ /** When `event`'s last occurrence ends: its own end, or a series' last occurrence's - far ahead for a series without an end. */
339
+ export function seriesEndDate(event: CalendarEvent): Date {
340
+ const rule = event.recurrenceRule;
341
+ const end = new Date(event.endDate);
342
+ if (!rule) {
343
+ return end;
344
+ }
345
+ if (!rule.until && !rule.count) {
346
+ return new Date(8.64e15);
347
+ }
348
+ const duration = end.valueOf() - new Date(event.startDate).valueOf();
349
+ const horizon = new Date(rule.until ? new Date(rule.until).valueOf() + 86_400_000 : Date.now() + 5 * 365 * 86_400_000);
350
+ const occurrences = expandOccurrences(event, new Date(event.startDate), horizon);
351
+ const last = occurrences[occurrences.length - 1];
352
+ return last ? new Date(new Date(last.startDate).valueOf() + duration) : end;
353
+ }
@@ -0,0 +1,73 @@
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ /**
6
+ * The calendar files of zero-access messages, as decrypted on this device (`MessageSecurityResult.calendar`). The server holds only
7
+ * the sealed copy of such a message, so every invitation call for it (`inviteApi.ts`) sends the file along. Kept in memory for the
8
+ * messages read most recently, only while their mailbox is unlocked: its lock forgets them (telling `onSealedInvitesForgotten()`
9
+ * listeners, so what was read with them goes too), and so does sign-out (`clearSealedInvites()`).
10
+ */
11
+ import { getUnlockedKeys, subscribeKeySession } from "../crypto/keySession.js";
12
+
13
+ /** How many messages' calendar files are kept. */
14
+ const MAX_SEALED_INVITES = 100;
15
+
16
+ const calendars: Map<string, { mailboxUid: string; ics: string }> = new Map();
17
+ const forgottenListeners = new Set<(messageUids: string[]) => void>();
18
+
19
+ let watchingKeys = false;
20
+
21
+ /** A mailbox's files go the moment it locks, so nothing opened outlives its key session. Subscribed on the first file, not on import. */
22
+ function forgetOnLock(): void {
23
+ if (watchingKeys) {
24
+ return;
25
+ }
26
+ watchingKeys = true;
27
+ subscribeKeySession(({ mailboxUid, state }) => {
28
+ if (state !== "locked") {
29
+ return;
30
+ }
31
+ const forgotten: string[] = [];
32
+ for (const [messageUid, entry] of calendars) {
33
+ if (entry.mailboxUid === mailboxUid) {
34
+ calendars.delete(messageUid);
35
+ forgotten.push(messageUid);
36
+ }
37
+ }
38
+ if (forgotten.length) {
39
+ forgottenListeners.forEach((listener) => listener(forgotten));
40
+ }
41
+ });
42
+ }
43
+
44
+ /** Remembers the decrypted calendar file of zero-access message `messageUid` of `mailboxUid` - not while that mailbox is locked (a
45
+ * pane still drawing what it decrypted before the lock). */
46
+ export function rememberSealedInvite(messageUid: string, ics: string, mailboxUid: string): void {
47
+ if (!getUnlockedKeys(mailboxUid)) {
48
+ return;
49
+ }
50
+ forgetOnLock();
51
+ calendars.delete(messageUid);
52
+ calendars.set(messageUid, { mailboxUid, ics });
53
+ while (calendars.size > MAX_SEALED_INVITES) {
54
+ calendars.delete(calendars.keys().next().value!);
55
+ }
56
+ }
57
+
58
+ /** The decrypted calendar file of zero-access message `messageUid`, when this device has read it and its mailbox is unlocked. */
59
+ export function sealedInviteCalendar(messageUid: string): string | undefined {
60
+ const entry = calendars.get(messageUid);
61
+ return entry && getUnlockedKeys(entry.mailboxUid) ? entry.ics : undefined;
62
+ }
63
+
64
+ /** Calls `listener` with the messages whose files a mailbox's lock forgot. Returns the unsubscribe. */
65
+ export function onSealedInvitesForgotten(listener: (messageUids: string[]) => void): () => void {
66
+ forgottenListeners.add(listener);
67
+ return () => forgottenListeners.delete(listener);
68
+ }
69
+
70
+ /** Forgets every remembered calendar file (sign-out). */
71
+ export function clearSealedInvites(): void {
72
+ calendars.clear();
73
+ }
@@ -5,16 +5,10 @@
5
5
  /** Typed wrappers over `@rapidmx/restapi`'s `/mail/contacts` REST surface — see `mailApi.ts`'s own header
6
6
  * comment for the shared ACL/authorization model every wrapper file here follows. */
7
7
 
8
- import { ApiClient, apiUrl, withClient, withClientRaw } from "../util/api.js";
8
+ import { ApiClient, apiUrl, withClient, withClientBlob, withClientRaw } from "../util/api.js";
9
9
  import { ListParams, SETTINGS_LIST_LIMIT, buildQuery } from "../util/apiQuery.js";
10
- import {
11
- type EncryptionPreference,
12
- type KeyConflict,
13
- type PreviousKey,
14
- type PublicKey,
15
- type RejectedKey,
16
- signingKeyFingerprints,
17
- } from "../crypto/keyvaultApi.js";
10
+ import { guardSealedMove } from "../zeroAccess/sealedMoves.js";
11
+ import { type EncryptionPreference, type EndToEndFormat, type KeyConflict, type PreviousKey, type PublicKey, type RejectedKey, signingKeyFingerprints, isOpenPgpKey, isTrustedForVerification } from "../crypto/keyvaultApi.js";
18
12
 
19
13
  export type ContactAddressKind = "home" | "work" | "other";
20
14
 
@@ -68,6 +62,15 @@ export interface Contact {
68
62
  * via `crypto/keyvaultApi.ts`'s `lookupKeys()` at compose time, never fetched on message receipt
69
63
  * (that would leak read timing to the sender's server). */
70
64
  encryptPreference?: EncryptionPreference;
65
+ /** The protected details sealed to the mailbox's zero-access key while it protects contacts (`displayName` then shows the first email
66
+ * address, the other protected fields are empty) - opened with `openSealedRecords()`. Server-written. */
67
+ sealedFields?: Record<string, string> | null;
68
+ /** The photo (`photoBlobKey`) is sealed to the mailbox's zero-access key: it is fetched and opened, never shown by URL. Server-written. */
69
+ photoSealed?: boolean | null;
70
+ /** The end-to-end format the user chose for this contact ("Preferred format"); absent or null for automatic. */
71
+ preferredFormat?: EndToEndFormat | null;
72
+ /** The format this address was last seen using, from authenticated mail it sent (server-written). */
73
+ observedFormat?: { format: EndToEndFormat; at: number } | null;
71
74
  /** This contact's pinned public keys. Trust is TOFU (trust-on-first-use) — see `keyConflicts` for what
72
75
  * happens when a newly observed key differs from one of these. */
73
76
  keys?: PublicKey[];
@@ -89,6 +92,13 @@ const CONTACT_SORT = JSON.stringify({ displayName: "ASC", uid: "ASC" });
89
92
 
90
93
  /** Lists a folder's contacts, alphabetically by display name. Never includes soft-deleted contacts — see
91
94
  * `listDeletedContacts()` for those. */
95
+ /** The protected contact fields a list of contacts shows - all a list opens (`openSealedRecords(contacts, CONTACT_LIST_FIELDS)`); a view of
96
+ * one contact opens the rest. */
97
+ export const CONTACT_LIST_FIELDS: readonly string[] = ["displayName", "phones", "categories"];
98
+
99
+ /** The protected fields a duplicate check compares (an address-less card is matched by name and phone). */
100
+ export const CONTACT_MATCH_FIELDS: readonly string[] = ["displayName", "phones"];
101
+
92
102
  export function listContacts(folderUid: string, params: ListParams = {}, client?: ApiClient): Promise<Contact[]> {
93
103
  return withClient(client, `/mail/contacts?${buildQuery(params, { folderUid, sort: CONTACT_SORT })}`);
94
104
  }
@@ -106,6 +116,14 @@ export function pinnedSigningFingerprintsFor(contacts: Contact[], address: strin
106
116
  return [...new Set(contactsMatching(contacts, address).flatMap((contact) => signingKeyFingerprints(contact.keys, contact.previousKeys)))];
107
117
  }
108
118
 
119
+ /** The OpenPGP certificates (base64, `PublicKey.publicKey`) pinned on every contact in `contacts` for `address` - current and
120
+ * previous ones still trusted for verification (`isTrustedForVerification()`) - which an OpenPGP signature from that sender is
121
+ * checked against (an OpenPGP signature carries only a key ID, so the key itself is needed). De-duplicated by fingerprint. */
122
+ export function pinnedOpenPgpKeysFor(contacts: Contact[], address: string): string[] {
123
+ const keys = contactsMatching(contacts, address).flatMap((contact) => [...(contact.keys ?? []), ...(contact.previousKeys ?? [])]);
124
+ return uniqueByFingerprint(keys.filter((key) => isOpenPgpKey(key) && isTrustedForVerification(key))).map((key) => key.publicKey);
125
+ }
126
+
109
127
  /** Page size and page cap for `fetchPinnedSigningFingerprints()` and `fetchSignerKeyState()` (500 is restapi's own
110
128
  * `limit` cap). */
111
129
  export const PINNED_FINGERPRINT_PAGE_SIZE = 500;
@@ -149,6 +167,9 @@ export interface SignerKeyState {
149
167
  previous: PreviousKey[];
150
168
  /** The first unresolved signing-key conflict found, if any. */
151
169
  conflict?: KeyConflict;
170
+ /** The pinned OpenPGP certificates (which sign as well as encrypt), de-duplicated by fingerprint - what an OpenPGP signer's
171
+ * key-changed comparison shows. Absent when there are none. */
172
+ openPgp?: PublicKey[];
152
173
  }
153
174
 
154
175
  function uniqueByFingerprint<T extends PublicKey>(keys: T[]): T[] {
@@ -174,7 +195,8 @@ export function signerKeyStateFor(contacts: Contact[], address: string): SignerK
174
195
  matching.flatMap((contact) => (contact.previousKeys ?? []).filter((key) => key.useType === "sign")).sort((a, b) => b.replacedAt - a.replacedAt),
175
196
  );
176
197
  const conflict = matching.flatMap((contact) => contact.keyConflicts ?? []).find((entry) => entry.useType === "sign");
177
- return { pinned, previous, ...(conflict ? { conflict } : {}) };
198
+ const openPgp = uniqueByFingerprint(matching.flatMap((contact) => (contact.keys ?? []).filter((key) => isOpenPgpKey(key))));
199
+ return { pinned, previous, ...(conflict ? { conflict } : {}), ...(openPgp.length > 0 ? { openPgp } : {}) };
178
200
  }
179
201
 
180
202
  /** Fetches `signerKeyStateFor()` for `address` from the contacts in `folderUids`, paging exactly like
@@ -258,11 +280,15 @@ export interface UpdateContactInput extends ContactInput {
258
280
  * fetched `Contact`. An `UpdateContactInput` is also a valid `ContactPatch`. */
259
281
  export type ContactPatch = Partial<Contact> & Pick<Contact, "uid" | "version">;
260
282
 
261
- export function updateContact(patch: ContactPatch, client?: ApiClient): Promise<Contact> {
262
- return withClient(client, `/mail/contacts/${encodeURIComponent(patch.uid)}`, {
263
- method: "PUT",
264
- body: JSON.stringify(patch),
265
- });
283
+ /** Saves `patch`. A patch moving the contact to another mailbox (`mailboxUid`) is refused with `SealedMoveError` when the contact is
284
+ * protected - before sending anything when `current` (the contact as this device has it) says so, else from the server's refusal. */
285
+ export function updateContact(patch: ContactPatch, client?: ApiClient, current?: Contact): Promise<Contact> {
286
+ return guardSealedMove(current, patch.mailboxUid, () =>
287
+ withClient<Contact>(client, `/mail/contacts/${encodeURIComponent(patch.uid)}`, {
288
+ method: "PUT",
289
+ body: JSON.stringify(patch),
290
+ }),
291
+ );
266
292
  }
267
293
 
268
294
  /** Thin `updateContact()` wrapper for toggling favorite/star status — same pattern as `mailApi.ts`'s
@@ -291,8 +317,8 @@ export function uploadContactPhoto(uid: string, version: number, file: Blob, cli
291
317
  }
292
318
 
293
319
  /** The bytes of a contact's own picture through an explicit `client` - for one that authenticates with a token, whose `<img>` cannot (see `contactPhotoUrl()`). */
294
- export function fetchContactPhoto(uid: string, version: number, client: ApiClient): Promise<Blob> {
295
- return client.fetchBlob(`/mail/contacts/${encodeURIComponent(uid)}/photo?v=${version}`);
320
+ export function fetchContactPhoto(uid: string, version: number, client?: ApiClient): Promise<Blob> {
321
+ return withClientBlob(client, `/mail/contacts/${encodeURIComponent(uid)}/photo?v=${version}`, "Could not load the contact's picture.");
296
322
  }
297
323
 
298
324
  /** Removes a contact's own picture and returns the updated contact. */
@@ -2,10 +2,31 @@
2
2
  // Copyright (C) 2026 Jean-Philippe Steinmetz
3
3
  // SPDX-License-Identifier: MPL-2.0
4
4
  ///////////////////////////////////////////////////////////////////////////////
5
- import { useEffect, useState } from "react";
5
+ import { useEffect, useRef, useState } from "react";
6
6
  import type { ApiClient } from "../util/api.js";
7
+ import { getUnlockedKeys, subscribeKeySession } from "../crypto/keySession.js";
8
+ import { openSealedBytes } from "../zeroAccess/sealedRecords.js";
7
9
  import { type Contact, contactPhotoUrl, fetchContactPhoto } from "./contactsApi.js";
8
10
 
11
+ /** What a photo is fetched by: the contact's identity, and whether (and for which mailbox) it is sealed. */
12
+ type PhotoContact = Pick<Contact, "uid" | "version" | "photoBlobKey"> & Partial<Pick<Contact, "mailboxUid" | "photoSealed">>;
13
+
14
+ /** The cache identity of the global (cookie) client, for a sealed photo fetched without an explicit client. */
15
+ const GLOBAL_CLIENT = {} as ApiClient;
16
+
17
+ /** A contact's photo: the bytes as stored, or - sealed to the mailbox's zero-access key - opened (rejects when it can't be: initials show). */
18
+ async function loadPhoto(contact: PhotoContact, client: ApiClient | undefined): Promise<Blob> {
19
+ const blob = await fetchContactPhoto(contact.uid, contact.version, client);
20
+ if (!contact.photoSealed) {
21
+ return blob;
22
+ }
23
+ const opened = await openSealedBytes(contact.mailboxUid ?? "", new Uint8Array(await blob.arrayBuffer()));
24
+ if (!opened) {
25
+ throw new Error("The contact's picture is protected and can't be opened here.");
26
+ }
27
+ return new Blob([opened as BlobPart]);
28
+ }
29
+
9
30
  /** How many pictures stay loaded (as `blob:` URLs) after nothing shows them any more, so a list scrolled back over does not fetch them all again. */
10
31
  const CACHE_LIMIT = 50;
11
32
 
@@ -13,6 +34,8 @@ interface Entry {
13
34
  url: string;
14
35
  /** How many mounted avatars show this URL; it is never revoked while that is more than none. */
15
36
  refs: number;
37
+ /** A sealed picture's mailbox, whose keys opened it: dropped when that mailbox locks, shown or not, and never handed out while it is locked. */
38
+ mailboxUid?: string;
16
39
  }
17
40
 
18
41
  /** Least recently used first (a `Map` iterates in insertion order, and a use moves the entry to the end). */
@@ -22,6 +45,32 @@ const pending = new Map<string, { request: Promise<string>; waiters: number }>()
22
45
  const clientIds = new WeakMap<ApiClient, number>();
23
46
  let nextClientId = 0;
24
47
 
48
+ let watchingKeys = false;
49
+
50
+ /** A sealed picture opened with a mailbox's keys goes when that mailbox locks, like every other opened value (`sealedRecords.ts`): its URL
51
+ * is revoked even while an avatar shows it - each one drops it itself (`useContactPhoto()`). Subscribed with the first sealed picture. */
52
+ function forgetOnLock(): void {
53
+ if (watchingKeys) {
54
+ return;
55
+ }
56
+ watchingKeys = true;
57
+ subscribeKeySession(({ mailboxUid, state }) => {
58
+ if (state === "locked") {
59
+ forgetSealed(mailboxUid);
60
+ }
61
+ });
62
+ }
63
+
64
+ /** Revokes and forgets `mailboxUid`'s sealed pictures. */
65
+ function forgetSealed(mailboxUid: string): void {
66
+ for (const [key, entry] of entries) {
67
+ if (entry.mailboxUid === mailboxUid) {
68
+ URL.revokeObjectURL(entry.url);
69
+ entries.delete(key);
70
+ }
71
+ }
72
+ }
73
+
25
74
  /** One key per picture of one account: the same uid never collides across the clients of a multi-account app, and a replaced picture (new version) is a new key. */
26
75
  function keyOf(client: ApiClient, uid: string, version: number): string {
27
76
  let id = clientIds.get(client);
@@ -75,8 +124,20 @@ function limited<T>(task: () => Promise<T>): Promise<T> {
75
124
  });
76
125
  }
77
126
 
78
- /** The `blob:` URL for `key`, fetched with `load` unless it is cached, and counted as shown until `release()`. Concurrent callers share one fetch. */
79
- async function acquire(key: string, load: () => Promise<Blob>): Promise<string> {
127
+ /**
128
+ * The `blob:` URL for `key`, fetched with `load` unless it is cached, and counted as shown until `release()`. Concurrent callers share one fetch.
129
+ * `sealedMailboxUid` is a sealed picture's mailbox: opened only while it is unlocked, it is neither fetched, handed out from the cache nor
130
+ * stored once that mailbox is locked (rejects).
131
+ */
132
+ async function acquire(key: string, load: () => Promise<Blob>, sealedMailboxUid?: string): Promise<string> {
133
+ if (sealedMailboxUid !== undefined) {
134
+ forgetOnLock();
135
+ if (!getUnlockedKeys(sealedMailboxUid)) {
136
+ // Not fetched either: it couldn't be opened, and the avatar retries it once the mailbox unlocks (`useContactPhoto()`).
137
+ forgetSealed(sealedMailboxUid);
138
+ throw new Error("The contact's mailbox is locked.");
139
+ }
140
+ }
80
141
  const entry = entries.get(key);
81
142
  if (entry) {
82
143
  entry.refs++;
@@ -90,9 +151,13 @@ async function acquire(key: string, load: () => Promise<Blob>): Promise<string>
90
151
  waiters: 0,
91
152
  request: limited(load)
92
153
  .then((blob) => {
154
+ // Opened just before a lock came: nothing opened is kept past it.
155
+ if (sealedMailboxUid !== undefined && !getUnlockedKeys(sealedMailboxUid)) {
156
+ throw new Error("The contact's mailbox locked while its picture was opened.");
157
+ }
93
158
  const url = URL.createObjectURL(blob);
94
159
  // Claimed by everyone waiting from the start: an entry nobody holds yet could be trimmed before its avatar got to it.
95
- entries.set(key, { url, refs: created.waiters });
160
+ entries.set(key, { url, refs: created.waiters, mailboxUid: sealedMailboxUid });
96
161
  return url;
97
162
  })
98
163
  .finally(() => pending.delete(key)),
@@ -126,7 +191,7 @@ export function clearContactPhotoCache(): void {
126
191
  * token-authenticated client (the desktop and mobile apps) cannot do that - an `<img>` sends no `Authorization` header - so the picture is fetched through the client
127
192
  * and shown as a `blob:` URL, cached per client, contact and version with a small LRU and revoked once it falls out of it and nothing shows it.
128
193
  */
129
- export function useContactPhotoSrc(contact: Pick<Contact, "uid" | "version" | "photoBlobKey"> | undefined, client?: ApiClient): string | undefined {
194
+ export function useContactPhotoSrc(contact: PhotoContact | undefined, client?: ApiClient): string | undefined {
130
195
  return useContactPhoto(contact, client).src;
131
196
  }
132
197
 
@@ -135,23 +200,48 @@ export function useContactPhotoSrc(contact: Pick<Contact, "uid" | "version" | "p
135
200
  * that is not on screen yet has no reason to fetch its picture.
136
201
  */
137
202
  export function useContactPhoto(
138
- contact: Pick<Contact, "uid" | "version" | "photoBlobKey"> | undefined,
203
+ contact: PhotoContact | undefined,
139
204
  client?: ApiClient,
140
205
  active = true,
141
206
  ): { src: string | undefined; failed: boolean } {
142
207
  const [loaded, setLoaded] = useState<{ key: string; url: string } | undefined>();
143
208
  const [failedKey, setFailedKey] = useState<string | undefined>();
144
- const key = active && client && contact?.photoBlobKey ? keyOf(client, contact.uid, contact.version) : undefined;
145
- const uid = contact?.uid;
146
- const version = contact?.version;
209
+ // Bumped to load a sealed picture again: its mailbox locked (it can't be shown any more) or unlocked (one that failed can be now).
210
+ const [attempt, setAttempt] = useState(0);
211
+ // A sealed photo is always fetched (and opened) here: a URL would show the browser ciphertext.
212
+ const fetched = !!client || !!contact?.photoSealed;
213
+ const key = active && fetched && contact?.photoBlobKey ? keyOf(client ?? GLOBAL_CLIENT, contact.uid, contact.version) : undefined;
214
+ const sealedMailboxUid = contact?.photoSealed ? (contact.mailboxUid ?? "") : undefined;
215
+ const failedRef = useRef(failedKey);
216
+ failedRef.current = failedKey;
217
+
218
+ useEffect(() => {
219
+ if (!key || sealedMailboxUid === undefined) {
220
+ return;
221
+ }
222
+ return subscribeKeySession(({ mailboxUid, state }) => {
223
+ if (mailboxUid !== sealedMailboxUid) {
224
+ return;
225
+ }
226
+ if (state === "locked") {
227
+ // What the <img> decoded stays on screen until its src goes: drop it, then try again (it fails while locked: initials).
228
+ setLoaded(undefined);
229
+ setFailedKey(undefined);
230
+ setAttempt((n) => n + 1);
231
+ } else if (failedRef.current === key) {
232
+ setFailedKey(undefined);
233
+ setAttempt((n) => n + 1);
234
+ }
235
+ });
236
+ }, [key, sealedMailboxUid]);
147
237
 
148
238
  useEffect(() => {
149
- if (!key || !client) {
239
+ if (!key) {
150
240
  return;
151
241
  }
152
242
  let cancelled = false;
153
243
  let held = false;
154
- acquire(key, () => fetchContactPhoto(uid!, version!, client)).then(
244
+ acquire(key, () => loadPhoto(contact!, client), sealedMailboxUid).then(
155
245
  (url) => {
156
246
  if (cancelled) {
157
247
  release(key);
@@ -168,9 +258,9 @@ export function useContactPhoto(
168
258
  release(key);
169
259
  }
170
260
  };
171
- }, [key]);
261
+ }, [key, attempt]);
172
262
 
173
- if (client) {
263
+ if (fetched) {
174
264
  return { src: key !== undefined && loaded?.key === key ? loaded.url : undefined, failed: key !== undefined && failedKey === key };
175
265
  }
176
266
  return { src: contact && contactPhotoUrl(contact), failed: false };
@@ -47,9 +47,15 @@ function policyStateForTier(policy: EncryptionPolicy, tier: RecipientTier): Poli
47
47
  export interface RecipientEncryptionStatus {
48
48
  address: string;
49
49
  tier: RecipientTier;
50
- /** The recipient's currently-active encryption certificate, if they have published (and this device
50
+ /** The recipient's currently-active S/MIME encryption certificate, if they have published (and this device
51
51
  * has discovered) one. */
52
52
  encryptCert?: PublicKey;
53
+ /** The recipient's active OpenPGP certificate - only when they have no S/MIME certificate and the server allows OpenPGP
54
+ * (restapi `specs/end-to-end_encryption.md` *OpenPGP Interoperability*: S/MIME is preferred whenever it can be used). */
55
+ openPgpKey?: PublicKey;
56
+ /** Which format this recipient is encrypted in: `"smime"` whenever they have an S/MIME certificate, `"openpgp"` only for
57
+ * a recipient whose only key is an OpenPGP one. Absent when they can't be encrypted to. */
58
+ format?: "smime" | "openpgp";
53
59
  /** Whether this recipient *can* be encrypted to at all right now - false when there's no usable key,
54
60
  * or the tier's policy is `prohibited`. */
55
61
  canEncrypt: boolean;
@@ -64,15 +70,24 @@ export interface RecipientEncryptionStatus {
64
70
 
65
71
  /** Per-recipient encryption eligibility, given this device's own encryption preference and the
66
72
  * system-wide policy. One entry per (address, lookup result) pair the caller already resolved via
67
- * `lookupKeys()` - this function does no discovery itself. */
73
+ * `lookupKeys()` - this function does no discovery itself. `ownCanUseOpenPgp` false: the sender has no OpenPGP key to use here
74
+ * (an OpenPGP copy is encrypted to the sender too), so a recipient who prefers OpenPGP but has an S/MIME certificate gets S/MIME - a
75
+ * preference never leaves them unencrypted (restapi `specs/end-to-end_encryption.md` *Choosing the format*). */
68
76
  export function resolveRecipientEncryption(
69
77
  ownAddress: string,
70
78
  ownPrefersMutual: boolean,
71
79
  policy: EncryptionPolicy,
72
80
  recipientAddress: string,
73
81
  lookup: KeyLookupResult | undefined,
82
+ ownCanUseOpenPgp: boolean = true,
74
83
  ): RecipientEncryptionStatus {
75
- const encryptCert = lookup ? findActivePublicKey(lookup.keys, "encrypt") : undefined;
84
+ const smimeCert = lookup ? findActivePublicKey(lookup.keys, "encrypt") : undefined;
85
+ const usableOpenPgpKey = lookup && policy.allowOpenPgp === true ? findActivePublicKey(lookup.keys, "encrypt", "openpgp") : undefined;
86
+ // S/MIME, unless the recipient has no certificate or prefers OpenPGP (restapi *Choosing the format*: the user's choice for the
87
+ // contact, what the address advertises, what it was last seen using) - and OpenPGP only where the server allows it.
88
+ const useOpenPgp = !!usableOpenPgpKey && (!smimeCert || (lookup?.preferredFormat === "openpgp" && ownCanUseOpenPgp));
89
+ const encryptCert = useOpenPgp ? undefined : smimeCert;
90
+ const openPgpKey = useOpenPgp ? usableOpenPgpKey : undefined;
76
91
  const tier = classifyRecipientTier(ownAddress, recipientAddress, !!lookup && lookup.keys.length > 0);
77
92
  const policyState = policyStateForTier(policy, tier);
78
93
 
@@ -87,7 +102,7 @@ export function resolveRecipientEncryption(
87
102
  };
88
103
  }
89
104
 
90
- if (!encryptCert) {
105
+ if (!encryptCert && !openPgpKey) {
91
106
  return { address: recipientAddress, tier, canEncrypt: false, autoEncrypt: false };
92
107
  }
93
108
 
@@ -96,7 +111,7 @@ export function resolveRecipientEncryption(
96
111
  return {
97
112
  address: recipientAddress,
98
113
  tier,
99
- encryptCert,
114
+ ...(encryptCert ? { encryptCert, format: "smime" as const } : { openPgpKey, format: "openpgp" as const }),
100
115
  canEncrypt: true,
101
116
  autoEncrypt: policyState === "automatic" && mutual,
102
117
  };