@remit/backend 0.0.143 → 0.0.145

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 (279) hide show
  1. package/dist/dev-server/content-handler.d.ts +38 -0
  2. package/dist/dev-server/content-handler.js +46 -0
  3. package/dist/src/api.d.ts +5 -0
  4. package/dist/src/api.js +73 -0
  5. package/dist/src/auth.d.ts +24 -0
  6. package/dist/src/auth.js +81 -0
  7. package/dist/src/config/api-config.d.ts +20 -0
  8. package/dist/src/config/api-config.js +1 -0
  9. package/dist/src/config/from-env.d.ts +2 -0
  10. package/dist/src/config/from-env.js +65 -0
  11. package/dist/src/config/msoauth-secrets-manager.d.ts +2 -0
  12. package/dist/src/config/msoauth-secrets-manager.js +28 -0
  13. package/dist/src/config/msoauth.d.ts +19 -0
  14. package/dist/src/config/msoauth.js +6 -0
  15. package/{src/derive/autoMoved.ts → dist/src/derive/autoMoved.d.ts} +1 -29
  16. package/dist/src/derive/autoMoved.js +49 -0
  17. package/dist/src/derive/contentSignature.d.ts +40 -0
  18. package/{src/derive/contentSignature.ts → dist/src/derive/contentSignature.js} +23 -77
  19. package/dist/src/derive/contentUrl.d.ts +33 -0
  20. package/dist/src/derive/contentUrl.js +27 -0
  21. package/{src/derive/deriveMuted.ts → dist/src/derive/deriveMuted.d.ts} +1 -3
  22. package/dist/src/derive/deriveMuted.js +7 -0
  23. package/dist/src/derive/enrichThreadRows.d.ts +118 -0
  24. package/dist/src/derive/enrichThreadRows.js +151 -0
  25. package/dist/src/derive/filterThreadCriteria.d.ts +23 -0
  26. package/dist/src/derive/filterThreadCriteria.js +24 -0
  27. package/{src/derive/pendingMoveCounts.ts → dist/src/derive/pendingMoveCounts.d.ts} +5 -53
  28. package/dist/src/derive/pendingMoveCounts.js +53 -0
  29. package/{src/derive/senderTrust.ts → dist/src/derive/senderTrust.d.ts} +1 -9
  30. package/dist/src/derive/senderTrust.js +19 -0
  31. package/dist/src/error.d.ts +21 -0
  32. package/dist/src/error.js +85 -0
  33. package/dist/src/handlers/account-guards.d.ts +36 -0
  34. package/dist/src/handlers/account-guards.js +107 -0
  35. package/dist/src/handlers/account-oauth.d.ts +15 -0
  36. package/dist/src/handlers/account-oauth.js +334 -0
  37. package/dist/src/handlers/account-overrides.d.ts +53 -0
  38. package/dist/src/handlers/account-overrides.js +233 -0
  39. package/dist/src/handlers/account-signature.d.ts +28 -0
  40. package/dist/src/handlers/account-signature.js +85 -0
  41. package/dist/src/handlers/account.d.ts +7 -0
  42. package/dist/src/handlers/account.js +337 -0
  43. package/dist/src/handlers/address.d.ts +35 -0
  44. package/dist/src/handlers/address.js +133 -0
  45. package/dist/src/handlers/calendar-event.d.ts +70 -0
  46. package/dist/src/handlers/calendar-event.js +417 -0
  47. package/dist/src/handlers/calendar-feed.d.ts +47 -0
  48. package/dist/src/handlers/calendar-feed.js +184 -0
  49. package/dist/src/handlers/calendar-suggestion.d.ts +47 -0
  50. package/dist/src/handlers/calendar-suggestion.js +204 -0
  51. package/dist/src/handlers/calendar.d.ts +116 -0
  52. package/dist/src/handlers/calendar.js +323 -0
  53. package/dist/src/handlers/config.d.ts +43 -0
  54. package/dist/src/handlers/config.js +164 -0
  55. package/dist/src/handlers/ensure-account-config.d.ts +9 -0
  56. package/dist/src/handlers/ensure-account-config.js +27 -0
  57. package/dist/src/handlers/filter.d.ts +3 -0
  58. package/dist/src/handlers/filter.js +88 -0
  59. package/dist/src/handlers/folder-role-appointments.d.ts +68 -0
  60. package/dist/src/handlers/folder-role-appointments.js +168 -0
  61. package/dist/src/handlers/folder-role-labels.d.ts +26 -0
  62. package/dist/src/handlers/folder-role-labels.js +40 -0
  63. package/dist/src/handlers/folder-role.d.ts +9 -0
  64. package/dist/src/handlers/folder-role.js +37 -0
  65. package/dist/src/handlers/index.d.ts +88 -0
  66. package/dist/src/handlers/index.js +62 -0
  67. package/dist/src/handlers/label.d.ts +43 -0
  68. package/dist/src/handlers/label.js +107 -0
  69. package/dist/src/handlers/mailbox-bindings.d.ts +41 -0
  70. package/dist/src/handlers/mailbox-bindings.js +61 -0
  71. package/dist/src/handlers/mailbox.d.ts +23 -0
  72. package/dist/src/handlers/mailbox.js +211 -0
  73. package/dist/src/handlers/me.d.ts +2 -0
  74. package/dist/src/handlers/me.js +117 -0
  75. package/dist/src/handlers/message.d.ts +82 -0
  76. package/dist/src/handlers/message.js +595 -0
  77. package/dist/src/handlers/organize.d.ts +10 -0
  78. package/dist/src/handlers/organize.js +103 -0
  79. package/dist/src/handlers/outbox-attachment.d.ts +25 -0
  80. package/dist/src/handlers/outbox-attachment.js +77 -0
  81. package/dist/src/handlers/outbox.d.ts +4 -0
  82. package/dist/src/handlers/outbox.js +136 -0
  83. package/dist/src/handlers/sync-progress.d.ts +46 -0
  84. package/dist/src/handlers/sync-progress.js +63 -0
  85. package/dist/src/handlers/sync.d.ts +28 -0
  86. package/dist/src/handlers/sync.js +73 -0
  87. package/dist/src/handlers/system-update.d.ts +2 -0
  88. package/dist/src/handlers/system-update.js +159 -0
  89. package/dist/src/handlers/thread.d.ts +148 -0
  90. package/dist/src/handlers/thread.js +228 -0
  91. package/dist/src/handlers/unified-threads.d.ts +247 -0
  92. package/dist/src/handlers/unified-threads.js +406 -0
  93. package/{src/handlers/vip-suggestions.ts → dist/src/handlers/vip-suggestions.d.ts} +1 -13
  94. package/dist/src/handlers/vip-suggestions.js +16 -0
  95. package/dist/src/index.d.ts +5 -0
  96. package/dist/src/index.js +53 -0
  97. package/{src/json.ts → dist/src/json.d.ts} +1 -4
  98. package/dist/src/json.js +10 -0
  99. package/dist/src/jwt-auth.d.ts +15 -0
  100. package/dist/src/jwt-auth.js +45 -0
  101. package/dist/src/lambda.d.ts +13 -0
  102. package/dist/src/lambda.js +33 -0
  103. package/dist/src/request.d.ts +9 -0
  104. package/dist/src/request.js +17 -0
  105. package/dist/src/response.d.ts +44 -0
  106. package/dist/src/response.js +80 -0
  107. package/dist/src/serve.d.ts +31 -0
  108. package/dist/src/serve.js +117 -0
  109. package/dist/src/service/account-deletion.d.ts +20 -0
  110. package/dist/src/service/account-deletion.js +33 -0
  111. package/dist/src/service/compose-sqlite.d.ts +3 -0
  112. package/dist/src/service/compose-sqlite.js +13 -0
  113. package/dist/src/service/create-remit-client.d.ts +109 -0
  114. package/dist/src/service/create-remit-client.js +188 -0
  115. package/dist/src/service/data-client.d.ts +12 -0
  116. package/dist/src/service/data-client.js +42 -0
  117. package/dist/src/service/export-identity.d.ts +4 -0
  118. package/dist/src/service/export-identity.js +33 -0
  119. package/dist/src/service/fire-and-forget.d.ts +54 -0
  120. package/dist/src/service/fire-and-forget.js +37 -0
  121. package/dist/src/service/organize.d.ts +181 -0
  122. package/dist/src/service/organize.js +367 -0
  123. package/dist/src/service/queues.d.ts +12 -0
  124. package/dist/src/service/queues.js +1 -0
  125. package/dist/src/service/refusal.d.ts +4 -0
  126. package/dist/src/service/refusal.js +20 -0
  127. package/dist/src/service/sender-category.d.ts +51 -0
  128. package/{src/service/sender-category.ts → dist/src/service/sender-category.js} +40 -81
  129. package/dist/src/service/shared-deps.d.ts +6 -0
  130. package/dist/src/service/shared-deps.js +24 -0
  131. package/dist/src/service/trigger-sync.d.ts +57 -0
  132. package/dist/src/service/trigger-sync.js +31 -0
  133. package/dist/src/types.d.ts +72 -0
  134. package/dist/src/types.js +1 -0
  135. package/package.json +125 -98
  136. package/.env.test +0 -4
  137. package/dev-server/content-auth.test.ts +0 -113
  138. package/dev-server/content-auth.ts +0 -54
  139. package/dev-server/content-handler.test.ts +0 -105
  140. package/dev-server/content-handler.ts +0 -79
  141. package/dev-server/content-path.test.ts +0 -37
  142. package/dev-server/content-path.ts +0 -27
  143. package/dev-server/cors.test.ts +0 -48
  144. package/dev-server/cors.ts +0 -25
  145. package/dev-server/keep-alive.test.ts +0 -24
  146. package/dev-server/lambda-helpers.ts +0 -69
  147. package/dev-server/log-output.test.ts +0 -173
  148. package/dev-server/oauth-callback-route.test.ts +0 -66
  149. package/dev-server/relational-health.test.ts +0 -83
  150. package/dev-server/relational-health.ts +0 -39
  151. package/dev-server/server.ts +0 -384
  152. package/dev-server/sync-age.test.ts +0 -91
  153. package/dev-server/sync-age.ts +0 -55
  154. package/dev-server/upload-handler.ts +0 -132
  155. package/dev-server/upload-route.test.ts +0 -196
  156. package/scripts/backfill-classification.ts +0 -91
  157. package/scripts/backfill-list-id.ts +0 -83
  158. package/scripts/config-save.ts +0 -128
  159. package/src/auth.test.ts +0 -12
  160. package/src/auth.ts +0 -92
  161. package/src/config/msoauth.test.ts +0 -48
  162. package/src/config/msoauth.ts +0 -48
  163. package/src/data-backend.test.ts +0 -23
  164. package/src/data-backend.ts +0 -14
  165. package/src/derive/autoMoved.test.ts +0 -104
  166. package/src/derive/contentSignature.test.ts +0 -161
  167. package/src/derive/contentUrl.test.ts +0 -172
  168. package/src/derive/contentUrl.ts +0 -86
  169. package/src/derive/deriveMuted.test.ts +0 -34
  170. package/src/derive/enrichThreadRows.test.ts +0 -360
  171. package/src/derive/enrichThreadRows.ts +0 -234
  172. package/src/derive/filterThreadCriteria.test.ts +0 -126
  173. package/src/derive/filterThreadCriteria.ts +0 -51
  174. package/src/derive/senderTrust.test.ts +0 -67
  175. package/src/error.test.ts +0 -201
  176. package/src/error.ts +0 -123
  177. package/src/handlers/account-guards.test.ts +0 -67
  178. package/src/handlers/account-guards.ts +0 -169
  179. package/src/handlers/account-oauth-callback.test.ts +0 -155
  180. package/src/handlers/account-oauth-consent.test.ts +0 -336
  181. package/src/handlers/account-oauth-start.test.ts +0 -191
  182. package/src/handlers/account-oauth.test.ts +0 -439
  183. package/src/handlers/account-oauth.ts +0 -635
  184. package/src/handlers/account-overrides.test.ts +0 -88
  185. package/src/handlers/account-overrides.ts +0 -323
  186. package/src/handlers/account-ownership.ts +0 -25
  187. package/src/handlers/account-signature.ts +0 -117
  188. package/src/handlers/account-synced-services.test.ts +0 -245
  189. package/src/handlers/account.ts +0 -552
  190. package/src/handlers/address.test.ts +0 -381
  191. package/src/handlers/address.ts +0 -200
  192. package/src/handlers/calendar-event.test.ts +0 -685
  193. package/src/handlers/calendar-event.ts +0 -738
  194. package/src/handlers/calendar-feed-validators.test.ts +0 -228
  195. package/src/handlers/calendar-feed.test.ts +0 -439
  196. package/src/handlers/calendar-feed.ts +0 -291
  197. package/src/handlers/calendar-sqlite-fixture.ts +0 -36
  198. package/src/handlers/calendar-suggestion.test.ts +0 -1269
  199. package/src/handlers/calendar-suggestion.ts +0 -425
  200. package/src/handlers/calendar.test.ts +0 -1080
  201. package/src/handlers/calendar.ts +0 -517
  202. package/src/handlers/config.test.ts +0 -245
  203. package/src/handlers/config.ts +0 -332
  204. package/src/handlers/ensure-account-config.ts +0 -30
  205. package/src/handlers/filter.test.ts +0 -644
  206. package/src/handlers/filter.ts +0 -518
  207. package/src/handlers/folder-role-appointments.test.ts +0 -438
  208. package/src/handlers/folder-role-appointments.ts +0 -249
  209. package/src/handlers/folder-role-labels.ts +0 -63
  210. package/src/handlers/folder-role.test.ts +0 -209
  211. package/src/handlers/folder-role.ts +0 -80
  212. package/src/handlers/index.ts +0 -83
  213. package/src/handlers/label.test.ts +0 -112
  214. package/src/handlers/label.ts +0 -210
  215. package/src/handlers/mailbox-bindings.ts +0 -111
  216. package/src/handlers/mailbox-rename-refusal.test.ts +0 -247
  217. package/src/handlers/mailbox-settled-target.test.ts +0 -251
  218. package/src/handlers/mailbox.test.ts +0 -280
  219. package/src/handlers/mailbox.ts +0 -581
  220. package/src/handlers/me.test.ts +0 -81
  221. package/src/handlers/me.ts +0 -203
  222. package/src/handlers/message-read-backfill.test.ts +0 -103
  223. package/src/handlers/message.test.ts +0 -131
  224. package/src/handlers/message.ts +0 -1131
  225. package/src/handlers/organize.test.ts +0 -277
  226. package/src/handlers/organize.ts +0 -197
  227. package/src/handlers/outbox-attachment.test.ts +0 -765
  228. package/src/handlers/outbox-attachment.ts +0 -126
  229. package/src/handlers/outbox-list.test.ts +0 -179
  230. package/src/handlers/outbox.test.ts +0 -772
  231. package/src/handlers/outbox.ts +0 -258
  232. package/src/handlers/search.test.ts +0 -161
  233. package/src/handlers/search.ts +0 -105
  234. package/src/handlers/sync-progress.test.ts +0 -205
  235. package/src/handlers/sync-progress.ts +0 -99
  236. package/src/handlers/sync.test.ts +0 -168
  237. package/src/handlers/sync.ts +0 -118
  238. package/src/handlers/system-update.test.ts +0 -497
  239. package/src/handlers/system-update.ts +0 -230
  240. package/src/handlers/thread.test.ts +0 -396
  241. package/src/handlers/thread.ts +0 -427
  242. package/src/handlers/unified-threads-mail-sources.sqlite.test.ts +0 -197
  243. package/src/handlers/unified-threads.test.ts +0 -785
  244. package/src/handlers/unified-threads.ts +0 -669
  245. package/src/index.test.ts +0 -83
  246. package/src/index.ts +0 -228
  247. package/src/jwt-auth.test.ts +0 -152
  248. package/src/jwt-auth.ts +0 -132
  249. package/src/log-redaction.test.ts +0 -144
  250. package/src/openapi-spec.test.ts +0 -118
  251. package/src/request-context.test.ts +0 -61
  252. package/src/request-context.ts +0 -33
  253. package/src/request-pipeline.test.ts +0 -88
  254. package/src/request.ts +0 -10
  255. package/src/response.test.ts +0 -130
  256. package/src/response.ts +0 -144
  257. package/src/service/compose-sqlite.ts +0 -98
  258. package/src/service/config-import.ts +0 -39
  259. package/src/service/create-remit-client.ts +0 -522
  260. package/src/service/data-client.test.ts +0 -97
  261. package/src/service/data-client.ts +0 -58
  262. package/src/service/export-identity.ts +0 -39
  263. package/src/service/filter.ts +0 -40
  264. package/src/service/fire-and-forget.test.ts +0 -126
  265. package/src/service/fire-and-forget.ts +0 -79
  266. package/src/service/localhost-env-config.test.ts +0 -36
  267. package/src/service/organize-queue.ts +0 -98
  268. package/src/service/organize.test.ts +0 -1451
  269. package/src/service/organize.ts +0 -1025
  270. package/src/service/read-path-filter-config.test.ts +0 -243
  271. package/src/service/semantic-capability.test.ts +0 -78
  272. package/src/service/semantic-capability.ts +0 -95
  273. package/src/service/sender-category.test.ts +0 -235
  274. package/src/service/sqs.ts +0 -4
  275. package/src/service/trigger-sync.test.ts +0 -205
  276. package/src/service/trigger-sync.ts +0 -100
  277. package/src/stdout-capture-fixture.ts +0 -40
  278. package/src/types.ts +0 -271
  279. package/tsconfig.json +0 -7
@@ -1,1131 +0,0 @@
1
- import type {
2
- BodyPartResponse,
3
- EnvelopeAddressResponse,
4
- EnvelopeResponse,
5
- } from "@remit/api-openapi-types";
6
- import type { MailboxItem } from "@remit/data-ports";
7
- import {
8
- BadRequestError,
9
- ForbiddenError,
10
- MessagePlacementUnsettledError,
11
- NotFoundError,
12
- UnrecoverableBodyError,
13
- } from "@remit/data-ports/errors";
14
- import {
15
- ContentDisposition,
16
- MediaType,
17
- MessageCategory,
18
- SenderTrust,
19
- type StarColor,
20
- } from "@remit/domain-enums";
21
- import { logger } from "@remit/logger-lambda";
22
- import {
23
- guardConnectionCursor,
24
- isCursorRebuildNeeded,
25
- isMessageBodySyncBroken,
26
- MailboxCursorPausedError,
27
- MoveNotSettledError,
28
- NoJunkMailboxError,
29
- resolveFolderPlacement,
30
- } from "@remit/mailbox-service";
31
- import {
32
- isStorageNotFoundError as isStorageNotFoundErrorFromService,
33
- parseStorageUri,
34
- } from "@remit/storage-service";
35
- import type { APIGatewayProxyEvent } from "aws-lambda";
36
- import type { Context } from "openapi-backend";
37
- import { getAccountConfigIdFromEvent, getSubFromEvent } from "../auth.js";
38
- import { deriveAutoMoved } from "../derive/autoMoved.js";
39
- import {
40
- type ContentSigner,
41
- getContentSigner,
42
- } from "../derive/contentSignature.js";
43
- import {
44
- buildContentUrl,
45
- getContentDeliveryDomain,
46
- } from "../derive/contentUrl.js";
47
- import { deriveSenderTrust } from "../derive/senderTrust.js";
48
- import { getClient } from "../service/data-client.js";
49
- import type {
50
- MessageBulkOperationIds,
51
- MessageOperationIds,
52
- OperationHandler,
53
- } from "../types.js";
54
- import { assertMailboxSettled } from "./mailbox.js";
55
-
56
- type StarColorValue = (typeof StarColor)[keyof typeof StarColor];
57
-
58
- interface MessageOwnershipClient {
59
- message: { get(messageId: string): Promise<{ mailboxId: string }> };
60
- mailbox: {
61
- get(
62
- accountId: string,
63
- mailboxIds: string[],
64
- ): Promise<{ mailboxId: string; accountId: string }[]>;
65
- };
66
- account: {
67
- listAllByAccountConfig(
68
- accountConfigId: string,
69
- ): Promise<{ accountId: string }[]>;
70
- };
71
- }
72
-
73
- /**
74
- * Resolve the account that owns every message in `messageIds` and assert the
75
- * caller owns it. Messages have no tenant column, so ownership resolves through
76
- * the mailbox: the caller's own accounts (from their accountConfigId) scope a
77
- * mailbox lookup, and a mailbox resolves only under the account that owns it —
78
- * a foreign message never resolves and throws before any content is returned or
79
- * mutated (`read` -> 404, no existence leak; `act` -> 403). The tenant comes
80
- * from the caller's config, never from the row being read. The whole batch must
81
- * resolve to a single account — the downstream flag/move/delete services take
82
- * one accountId — so a batch spanning accounts is rejected. Returns that
83
- * accountId so callers reuse it without another lookup.
84
- */
85
- export const assertMessagesOwned = async (
86
- client: MessageOwnershipClient,
87
- messageIds: string[],
88
- callerAccountConfigId: string,
89
- mode: "read" | "act",
90
- ): Promise<string> => {
91
- const messages = await Promise.all(
92
- messageIds.map((id) => client.message.get(id)),
93
- );
94
- const mailboxIds = [...new Set(messages.map((m) => m.mailboxId))];
95
-
96
- const ownedAccounts = await client.account.listAllByAccountConfig(
97
- callerAccountConfigId,
98
- );
99
-
100
- const accountByMailbox = new Map<string, string>();
101
- for (const { accountId } of ownedAccounts) {
102
- const rows = await client.mailbox.get(accountId, mailboxIds);
103
- for (const row of rows) {
104
- accountByMailbox.set(row.mailboxId, row.accountId);
105
- }
106
- }
107
-
108
- if (mailboxIds.some((id) => !accountByMailbox.has(id))) {
109
- if (mode === "read") {
110
- throw new NotFoundError("Message not found");
111
- }
112
- throw new ForbiddenError("Message not in account config");
113
- }
114
-
115
- const accountIds = [...new Set(accountByMailbox.values())];
116
- if (accountIds.length !== 1) {
117
- throw new BadRequestError("All messages must belong to the same account");
118
- }
119
-
120
- return accountIds[0];
121
- };
122
-
123
- export const isStorageNotFoundError = (error: unknown): boolean =>
124
- isStorageNotFoundErrorFromService(error);
125
-
126
- /**
127
- * Decode the raw `.eml` bytes into a string for inspection. RFC822/MIME
128
- * sources are 7-bit/8-bit ASCII-compatible (non-ASCII bytes are encoded via
129
- * quoted-printable / base64 inside the body), so `latin1` round-trips every
130
- * byte 1:1 without loss or replacement characters — unlike `utf8`, which would
131
- * mangle raw 8-bit bytes. Headers and structure stay byte-accurate.
132
- */
133
- export const decodeRawEml = (body: Buffer): string => body.toString("latin1");
134
-
135
- /**
136
- * Extract the accountConfigId + accountId segments from a bodyStorageKey URI
137
- * such as
138
- * `s3://bucket/accounts/{accountConfigId}/{accountId}/messages/{messageId}/body.eml`.
139
- * Returns null when the URI shape doesn't match — caller falls back to the
140
- * slow path without writing a parsed-body cache.
141
- */
142
- export const extractAccountIdsFromBodyKey = (
143
- uri: string,
144
- ): { accountConfigId: string; accountId: string } | null => {
145
- const parsed = parseStorageUri(uri);
146
- const match = parsed.storageKey.match(
147
- /^accounts\/([^/]+)\/([^/]+)\/messages\//,
148
- );
149
- if (!match) return null;
150
- return { accountConfigId: match[1], accountId: match[2] };
151
- };
152
-
153
- /**
154
- * Map a list of stored `BodyPart` rows to API `BodyPartResponse` objects,
155
- * populating `contentUrl` from the CloudFront distribution domain. Pure
156
- * function so the URL-construction contract can be pinned in tests without
157
- * standing up the full handler. The contract requires every `contentUrl`
158
- * to be a real URL (#299) — `getContentDeliveryDomain` throws when the
159
- * Lambda env is missing the domain, and this function expects a non-empty
160
- * string from the caller.
161
- */
162
- export interface BodyPartLike {
163
- bodyPartId: string;
164
- mediaType: string;
165
- mediaSubtype: string;
166
- sizeOctets: number;
167
- disposition?: string;
168
- dispositionFilename?: string;
169
- isMultipart: boolean;
170
- contentId?: string;
171
- partPath: string;
172
- }
173
-
174
- const MEDIA_TYPE_VALUES: ReadonlySet<string> = new Set(
175
- Object.values(MediaType),
176
- );
177
- const CONTENT_DISPOSITION_VALUES: ReadonlySet<string> = new Set(
178
- Object.values(ContentDisposition),
179
- );
180
-
181
- export const isMediaType = (
182
- value: unknown,
183
- ): value is BodyPartResponse["mediaType"] =>
184
- typeof value === "string" && MEDIA_TYPE_VALUES.has(value);
185
-
186
- export const isContentDisposition = (
187
- value: unknown,
188
- ): value is NonNullable<BodyPartResponse["disposition"]> =>
189
- typeof value === "string" && CONTENT_DISPOSITION_VALUES.has(value);
190
-
191
- const assertMediaType = (
192
- value: string,
193
- bodyPartId: string,
194
- ): BodyPartResponse["mediaType"] => {
195
- if (!isMediaType(value)) {
196
- throw new Error(
197
- `Invalid mediaType "${value}" on BodyPart ${bodyPartId}; expected one of ${[...MEDIA_TYPE_VALUES].join(", ")}`,
198
- );
199
- }
200
- return value;
201
- };
202
-
203
- const assertDisposition = (
204
- value: string | undefined,
205
- bodyPartId: string,
206
- ): BodyPartResponse["disposition"] => {
207
- if (value === undefined) return undefined;
208
- if (!isContentDisposition(value)) {
209
- throw new Error(
210
- `Invalid disposition "${value}" on BodyPart ${bodyPartId}; expected one of ${[...CONTENT_DISPOSITION_VALUES].join(", ")}`,
211
- );
212
- }
213
- return value;
214
- };
215
-
216
- export const buildBodyPartResponses = (
217
- parts: readonly BodyPartLike[],
218
- context: {
219
- contentDeliveryDomain: string;
220
- accountConfigId: string;
221
- accountId: string;
222
- messageId: string;
223
- sign?: ContentSigner;
224
- },
225
- ): BodyPartResponse[] => {
226
- return parts.map((part) => ({
227
- bodyPartId: part.bodyPartId,
228
- mediaType: assertMediaType(part.mediaType, part.bodyPartId),
229
- mediaSubtype: part.mediaSubtype,
230
- sizeOctets: part.sizeOctets,
231
- disposition: assertDisposition(part.disposition, part.bodyPartId),
232
- dispositionFilename: part.dispositionFilename,
233
- isMultipart: part.isMultipart,
234
- contentId: part.contentId,
235
- contentUrl: buildContentUrl({
236
- domain: context.contentDeliveryDomain,
237
- accountConfigId: context.accountConfigId,
238
- accountId: context.accountId,
239
- messageId: context.messageId,
240
- partPath: part.partPath,
241
- sign: context.sign,
242
- }),
243
- }));
244
- };
245
-
246
- /**
247
- * The slice of `BodySyncService` the read path needs to lazily materialize
248
- * deferred per-part objects. Narrowed to one method so the orchestration below
249
- * can be unit-tested without standing up the whole client.
250
- */
251
- export interface BodyPartMaterializer {
252
- ensureBodyPartsStored(
253
- accountConfigId: string,
254
- accountId: string,
255
- messageId: string,
256
- bodyStorageKey: string,
257
- ): Promise<unknown>;
258
- }
259
-
260
- export interface MaterializeLogger {
261
- warn(obj: Record<string, unknown>, msg: string): void;
262
- error(obj: Record<string, unknown>, msg: string): void;
263
- }
264
-
265
- /**
266
- * Re-arms the body-sync cue for one message (the read-path slice of
267
- * `BodySyncQueueService`). Narrowed to one method so the orchestration below can
268
- * be unit-tested without an SQS client.
269
- */
270
- export interface BodySyncCue {
271
- requestBodySync(input: {
272
- accountId: string;
273
- mailboxId: string;
274
- messageId: string;
275
- uid?: number;
276
- }): Promise<void>;
277
- }
278
-
279
- export interface MaterializeResult {
280
- /** `false` when the body object was missing — the caller must not 200 the body. */
281
- ready: boolean;
282
- }
283
-
284
- /**
285
- * Materialize the deferred per-part storage objects for a message before the
286
- * SPA fetches any `contentUrl`. Distinguishes the two failure modes the body
287
- * contract cares about:
288
- *
289
- * - Missing storage object (never synced or lost) — re-arm the SYNC_MESSAGE_BODY
290
- * cue so the worker (re)stores the body, and report `ready: false`. Not a
291
- * 500: a retry succeeds once the worker catches up.
292
- * - Any other error — rethrow so the request 500s and the bug is observable.
293
- * Never swallowed, never "best-effort".
294
- *
295
- * No-op (`ready: true`) when the body isn't stored yet (no `bodyStorageKey`) or
296
- * when the parts were written eagerly.
297
- */
298
- export const materializeBodyParts = async (
299
- materializer: BodyPartMaterializer,
300
- args: {
301
- accountConfigId: string;
302
- accountId: string;
303
- mailboxId: string;
304
- messageId: string;
305
- uid?: number;
306
- bodyStorageKey: string | undefined;
307
- cue: BodySyncCue | undefined;
308
- logger: MaterializeLogger;
309
- },
310
- ): Promise<MaterializeResult> => {
311
- const { accountConfigId, accountId, mailboxId, messageId, uid } = args;
312
- if (!args.bodyStorageKey) return { ready: true };
313
-
314
- try {
315
- await materializer.ensureBodyPartsStored(
316
- accountConfigId,
317
- accountId,
318
- messageId,
319
- args.bodyStorageKey,
320
- );
321
- return { ready: true };
322
- } catch (error: unknown) {
323
- if (!isStorageNotFoundError(error)) throw error;
324
-
325
- args.logger.warn(
326
- { messageId, accountId, mailboxId },
327
- "Body object missing on read; re-arming body-sync cue and signalling retry",
328
- );
329
- await args.cue?.requestBodySync({ accountId, mailboxId, messageId, uid });
330
- return { ready: false };
331
- }
332
- };
333
-
334
- export interface SpamReportBulkFailure {
335
- messageId: string;
336
- reason: string;
337
- }
338
-
339
- export interface SpamReportBulkOutcome {
340
- successCount: number;
341
- failureCount: number;
342
- failures?: SpamReportBulkFailure[];
343
- }
344
-
345
- /**
346
- * The fallback for a failure nobody designed copy for — an AWS SDK message
347
- * naming a queue URL, an `ECONNREFUSED host:port`, a programmer error.
348
- * Everything reaching it is flattened, same policy as `error.ts`'s "Internal
349
- * server error" flattening, because `SpamReportBulkResult.reason` is shown to
350
- * the user as-is. It says "try again" because retrying is the only thing left
351
- * to say about a cause we cannot name; an outcome the service DOES understand
352
- * carries its own text through `DESIGNED_FAILURES` instead of landing here.
353
- */
354
- export const GENERIC_FAILURE_REASON =
355
- "This message could not be processed. Please try again. If it keeps failing, report it.";
356
-
357
- /**
358
- * The designed, user-facing outcomes whose own message is returned verbatim:
359
- * each names what happened and what the user can do about it, which the
360
- * generic text cannot.
361
- */
362
- const DESIGNED_FAILURES = [
363
- MoveNotSettledError,
364
- NoJunkMailboxError,
365
- MessagePlacementUnsettledError,
366
- ];
367
-
368
- const isDesignedFailure = (reason: unknown): reason is Error =>
369
- DESIGNED_FAILURES.some((designed) => reason instanceof designed);
370
-
371
- /**
372
- * The placement refusal is the one designed outcome whose own message is not
373
- * the text to ship: it names a uuid and no remedy. One remedy answers it, and
374
- * only one refusal reaches it — a mutation still in flight, which settles on
375
- * its own (imap-mutations R3). Worded here, the way the delete path words the
376
- * same refusal for the client.
377
- */
378
- const placementRefusalReason = (
379
- _error: MessagePlacementUnsettledError,
380
- ): string =>
381
- "This message is still being moved on the mail server. Try again in a moment.";
382
-
383
- const failureReason = (reason: unknown): string => {
384
- if (!isDesignedFailure(reason)) return GENERIC_FAILURE_REASON;
385
- if (reason instanceof MessagePlacementUnsettledError)
386
- return placementRefusalReason(reason);
387
- return reason.message;
388
- };
389
-
390
- /**
391
- * Drive one report-spam/not-spam operation per message, concurrently. Each
392
- * message's own wait for its move to settle (SpamReportService's R2 wait) is
393
- * bounded on its own, but running the batch sequentially would let those
394
- * waits accumulate across the whole request — 50 messages could each wait
395
- * seconds, serializing into minutes and dying at the proxy. Running them
396
- * concurrently instead bounds the whole request by a single message's wait,
397
- * regardless of batch size.
398
- */
399
- export const settleSpamReportBulk = async (
400
- messageIds: string[],
401
- run: (messageId: string) => Promise<void>,
402
- ): Promise<SpamReportBulkOutcome> => {
403
- const results = await Promise.allSettled(
404
- messageIds.map((messageId) => run(messageId)),
405
- );
406
-
407
- let successCount = 0;
408
- const failures: SpamReportBulkFailure[] = [];
409
- results.forEach((result, index) => {
410
- if (result.status === "fulfilled") {
411
- successCount += 1;
412
- return;
413
- }
414
- const messageId = messageIds[index];
415
- failures.push({ messageId, reason: failureReason(result.reason) });
416
- logger.error(
417
- { messageId, error: result.reason },
418
- "spam-report bulk operation failed for one message",
419
- );
420
- });
421
-
422
- return {
423
- successCount,
424
- failureCount: failures.length,
425
- ...(failures.length > 0 ? { failures } : {}),
426
- };
427
- };
428
-
429
- export const MessageOperations: Record<
430
- MessageOperationIds,
431
- OperationHandler<MessageOperationIds>
432
- > = {
433
- MessageOperations_describeMessage: async (
434
- context: Context,
435
- ...args: unknown[]
436
- ) => {
437
- const event = args[0] as APIGatewayProxyEvent;
438
- const accountConfigId = getAccountConfigIdFromEvent(event);
439
- const { messageId } = context.request.params as { messageId: string };
440
- const client = await getClient();
441
- const ownedAccountId = await assertMessagesOwned(
442
- client,
443
- [messageId],
444
- accountConfigId,
445
- "read",
446
- );
447
- const description = await client.message.describe(messageId);
448
-
449
- const message = description.message[0];
450
- const envelope = description.envelope[0];
451
-
452
- const autoMoved = deriveAutoMoved(message);
453
-
454
- // Labels applied to this message (issue #26) — filter-, organize-, and
455
- // manually-applied alike. A message rarely carries more than a handful, so
456
- // a `get` per label id (not a batch fetch) is the whole cost.
457
- const messageLabelRows = await client.messageLabel.listByMessageId(
458
- message.messageId,
459
- );
460
- const labels = await Promise.all(
461
- messageLabelRows.map(async (row) => {
462
- const label = await client.label.get(accountConfigId, row.labelId);
463
- return { labelId: label.labelId, name: label.name, color: label.color };
464
- }),
465
- );
466
-
467
- // Not typed against the generated `MessageSummaryResponse`: `labels` is a
468
- // new field on it in this same PR, and that package publishes separately
469
- // from this repo — a local-codegen-only field would fail
470
- // `check-consumer-typecheck`/`release:dry-run`, which resolve generated
471
- // `@remit/*` packages off the registry, not the local `build/` output.
472
- const messageSummary = {
473
- messageId: message.messageId,
474
- mailboxId: message.mailboxId,
475
- uid: message.uid,
476
- rfc822Size: message.rfc822Size,
477
- internalDate: message.internalDate,
478
- messageIdHeader: message.messageIdHeader,
479
- authenticity: message.authenticity,
480
- status: message.status,
481
- syncStatus: message.syncStatus,
482
- abandonedMutation: message.abandonedMutation,
483
- ...(autoMoved ? { autoMoved } : {}),
484
- ...(labels.length > 0 ? { labels } : {}),
485
- ...(message.spamReport ? { spamReport: message.spamReport } : {}),
486
- };
487
-
488
- // Batch-fetch the resolved Address rows so each EnvelopeAddressResponse can
489
- // carry the sender-level `flags` map. Without this the From-line UI would
490
- // need a second round-trip to render trust state on every message open.
491
- const uniqueAddressIds = Array.from(
492
- new Set(description.envelopeAddress.map((a) => a.addressId)),
493
- );
494
- const addresses = uniqueAddressIds.length
495
- ? await client.address.getAddress(accountConfigId, uniqueAddressIds)
496
- : [];
497
- const flagsByAddressId = new Map(
498
- addresses.map((a) => [a.addressId, a.flags]),
499
- );
500
-
501
- const groupedAddresses = description.envelopeAddress.reduce(
502
- (acc, addr) => {
503
- const role = addr.addressRole;
504
- if (!acc[role]) acc[role] = [];
505
- acc[role].push({
506
- addressId: addr.addressId,
507
- displayName: addr.displayName,
508
- normalizedEmail: addr.normalizedEmail,
509
- addressRole: addr.addressRole,
510
- addressOrder: addr.addressOrder,
511
- flags: flagsByAddressId.get(addr.addressId),
512
- });
513
- return acc;
514
- },
515
- {} as Record<string, EnvelopeAddressResponse[]>,
516
- );
517
-
518
- const fromAddress = groupedAddresses.from?.[0];
519
- const fromFlags = fromAddress
520
- ? flagsByAddressId.get(fromAddress.addressId)
521
- : undefined;
522
- const senderTrust = fromAddress
523
- ? deriveSenderTrust(fromFlags)
524
- : SenderTrust.Unknown;
525
-
526
- const envelopeResponse: EnvelopeResponse = {
527
- messageId: envelope?.messageId ?? messageId,
528
- date: envelope?.dateValue ?? message.internalDate,
529
- subject: envelope?.subject,
530
- messageIdValue: envelope?.messageIdValue,
531
- from: groupedAddresses.from ?? [],
532
- to: groupedAddresses.to ?? [],
533
- cc: groupedAddresses.cc ?? [],
534
- bcc: groupedAddresses.bcc ?? [],
535
- replyTo: groupedAddresses.reply_to ?? [],
536
- category: message.category ?? MessageCategory.uncategorized,
537
- senderTrust,
538
- };
539
-
540
- const flags = description.messageFlag.map((f) => f.flagName);
541
-
542
- // `accountId` is needed to build per-part `contentUrl` values for the
543
- // BodyPartResponse list and on the IMAP-backfill path. Resolve it from
544
- // the bodyStorageKey when the body has already been synced (free — the
545
- // URI encodes both ids), or fall back to a single Mailbox.get() lookup
546
- // to avoid a redundant query on the fast path.
547
- const idsFromKey = message.bodyStorageKey
548
- ? extractAccountIdsFromBodyKey(message.bodyStorageKey)
549
- : null;
550
- let accountId = idsFromKey?.accountId;
551
- let mailbox: MailboxItem | undefined;
552
- if (!accountId) {
553
- mailbox = await client.mailbox.get(ownedAccountId, message.mailboxId);
554
- accountId = mailbox.accountId;
555
- }
556
-
557
- // Trigger an IMAP backfill when the body has never been stored. The
558
- // fetcher writes the raw .eml + parsed.json.gz cache + per-part rows
559
- // as a side-effect; the SPA then renders body content via each
560
- // BodyPartResponse.contentUrl (CloudFront-fronted, JWT-authorized at
561
- // the edge). The handler no longer returns body text/html — that
562
- // payload moved to per-part fetches once content delivery cut over
563
- // (#224 PR 3/3). When bodyStorageKey is already set we skip IMAP
564
- // entirely; the worker has already populated parts.
565
- let bodyPartRows = description.bodyPart;
566
- let bodyStorageKey = message.bodyStorageKey;
567
- if (!bodyStorageKey) {
568
- // A message whose body-sync exhausted every retry against real
569
- // (broken) content never gets a bodyStorageKey (issue #1270 / epic
570
- // #1281 invariant 3) — this branch is the ONLY place that condition
571
- // can occur, so the sentinel check lives here instead of unconditionally
572
- // at the top of the handler, which would tax every already-synced
573
- // read with an S3 HEAD it can never need. Checking before the backfill
574
- // attempt stops a client from looping through repeated 202s
575
- // (materializeBodyParts) or repeated synchronous IMAP round-trips
576
- // (fetchAndGetBody) on a message that can never succeed.
577
- if (
578
- await isMessageBodySyncBroken(
579
- client.storage,
580
- accountConfigId,
581
- accountId,
582
- messageId,
583
- )
584
- ) {
585
- throw new UnrecoverableBodyError(
586
- "This message's content could not be retrieved. Please report this issue.",
587
- );
588
- }
589
-
590
- if (!mailbox) {
591
- mailbox = await client.mailbox.get(accountId, message.mailboxId);
592
- }
593
-
594
- // Cheap frugal skip (epic #1281 invariant 6): a mailbox already known
595
- // paused never even opens a connection. Optimization only —
596
- // guardConnectionCursor's openBox wrap below is the structural
597
- // guarantee (issue #1272's read-path detection point).
598
- if (isCursorRebuildNeeded(mailbox.cursorState)) {
599
- logger.debug(
600
- {
601
- accountId,
602
- mailboxId: mailbox.mailboxId,
603
- messageId,
604
- cursorState: mailbox.cursorState,
605
- },
606
- "Mailbox cursor not normal; skipping IMAP body backfill for this request",
607
- );
608
- } else {
609
- const folder = {
610
- fullPath: mailbox.fullPath,
611
- placement: await resolveFolderPlacement(
612
- client.mailboxSpecialUse,
613
- accountId,
614
- mailbox.mailboxId,
615
- ),
616
- };
617
- const scope = await client.createConnectionScope(accountId);
618
- // Guard at the one choke point every UID-based IMAP op already
619
- // passes through: openBox. A mismatch trips the mailbox to
620
- // cursor_invalid and throws; caught below as a routine skip (epic
621
- // #1281 invariant 3) — the request just returns without a fresh
622
- // backfill this time.
623
- const connection = guardConnectionCursor(
624
- await scope.getConnection(),
625
- { mailboxService: client.mailbox },
626
- accountId,
627
- mailbox,
628
- );
629
-
630
- await client.bodySync
631
- .fetchAndGetBody(messageId, accountId, accountConfigId, folder, () =>
632
- Promise.resolve(connection),
633
- )
634
- .catch((error: unknown) => {
635
- if (error instanceof MailboxCursorPausedError) {
636
- logger.debug(
637
- {
638
- accountId,
639
- mailboxId: mailbox?.mailboxId,
640
- messageId,
641
- cursorState: error.state,
642
- },
643
- "Mailbox cursor not normal; skipping IMAP body backfill for this request",
644
- );
645
- return;
646
- }
647
- throw error;
648
- })
649
- .finally(() => scope.disconnect());
650
-
651
- // Body just landed via IMAP — re-read so the response includes the
652
- // parts the worker just wrote. Without this the first describe of a
653
- // never-synced message would return an empty bodyParts array.
654
- const refreshed = await client.message.describe(messageId);
655
- bodyPartRows = refreshed.bodyPart;
656
- bodyStorageKey = refreshed.message[0]?.bodyStorageKey;
657
- }
658
- }
659
-
660
- // Per-part storage objects are deferred during bulk sync (DEFER_BODY_PARTS)
661
- // to cut write amplification. Content delivery serves each part straight
662
- // from storage with no Lambda in the request path, so a deferred (missing)
663
- // object would surface to the SPA as a hard failure. Materialize them here —
664
- // idempotent, skips parts already stored — so every contentUrl below
665
- // resolves on first open. No-op when parts were written eagerly.
666
- //
667
- // A missing body object re-arms the SYNC_MESSAGE_BODY cue (so the worker
668
- // (re)stores it) and leaves the contentUrls to surface a retryable 202 on
669
- // the content route; any other error is rethrown and 500s loudly.
670
- await materializeBodyParts(client.bodySync, {
671
- accountConfigId,
672
- accountId,
673
- mailboxId: message.mailboxId,
674
- messageId,
675
- uid: message.uid,
676
- bodyStorageKey,
677
- cue: client.bodySyncQueue,
678
- logger,
679
- });
680
-
681
- const bodyParts = buildBodyPartResponses(bodyPartRows, {
682
- contentDeliveryDomain: getContentDeliveryDomain(),
683
- accountConfigId,
684
- accountId,
685
- messageId,
686
- sign: getContentSigner(),
687
- });
688
-
689
- const references = description.messageReference.map((ref) => ({
690
- messageIdValue: ref.messageIdValue,
691
- referenceType: ref.referenceType,
692
- referenceOrder: ref.referenceOrder,
693
- }));
694
-
695
- return {
696
- message: messageSummary,
697
- envelope: envelopeResponse,
698
- flags,
699
- bodyParts,
700
- references,
701
- };
702
- },
703
-
704
- MessageOperations_getRawMessage: async (
705
- context: Context,
706
- ...args: unknown[]
707
- ) => {
708
- const event = args[0] as APIGatewayProxyEvent;
709
- const accountConfigId = getAccountConfigIdFromEvent(event);
710
- const { messageId } = context.request.params as { messageId: string };
711
- const client = await getClient();
712
-
713
- // Cross-tenant ownership guard. Returning raw RFC822 bytes is sensitive,
714
- // so resolve the owning account and prove the caller owns it BEFORE any
715
- // storage read or backfill. `read` mode throws NotFoundError (→ 404) on a
716
- // foreign message and never leaks the owner's accountConfigId.
717
- const accountId = await assertMessagesOwned(
718
- client,
719
- [messageId],
720
- accountConfigId,
721
- "read",
722
- );
723
-
724
- // Resolve the message row for its mailboxId / bodyStorageKey.
725
- const message = await client.message.get(messageId);
726
-
727
- // Backfill from IMAP when the body has never been stored, reusing the
728
- // exact path describeMessage uses. fetchAndGetBody writes the raw .eml +
729
- // parsed cache + per-part rows and sets message.bodyStorageKey as a
730
- // side-effect; we then re-read the row to pick up the freshly written key.
731
- if (!message.bodyStorageKey) {
732
- const mailbox = await client.mailbox.get(accountId, message.mailboxId);
733
-
734
- // Cheap frugal skip (epic #1281 invariant 6): a mailbox already known
735
- // paused never even opens a connection. The existing "no
736
- // bodyStorageKey after backfill" check just past this block is
737
- // already the right signal for that case, so no new response shape
738
- // is needed here.
739
- if (isCursorRebuildNeeded(mailbox.cursorState)) {
740
- logger.debug(
741
- {
742
- accountId,
743
- mailboxId: mailbox.mailboxId,
744
- messageId,
745
- cursorState: mailbox.cursorState,
746
- },
747
- "Mailbox cursor not normal; skipping IMAP body backfill for this request",
748
- );
749
- } else {
750
- const folder = {
751
- fullPath: mailbox.fullPath,
752
- placement: await resolveFolderPlacement(
753
- client.mailboxSpecialUse,
754
- accountId,
755
- mailbox.mailboxId,
756
- ),
757
- };
758
- const scope = await client.createConnectionScope(accountId);
759
- // Guard at the openBox choke point — a fresh mismatch trips the
760
- // mailbox and throws once the SELECT reveals it; caught below.
761
- const connection = guardConnectionCursor(
762
- await scope.getConnection(),
763
- { mailboxService: client.mailbox },
764
- accountId,
765
- mailbox,
766
- );
767
- await client.bodySync
768
- .fetchAndGetBody(messageId, accountId, accountConfigId, folder, () =>
769
- Promise.resolve(connection),
770
- )
771
- .catch((error: unknown) => {
772
- if (error instanceof MailboxCursorPausedError) {
773
- logger.debug(
774
- {
775
- accountId,
776
- mailboxId: mailbox.mailboxId,
777
- messageId,
778
- cursorState: error.state,
779
- },
780
- "Mailbox cursor not normal; skipping IMAP body backfill for this request",
781
- );
782
- return;
783
- }
784
- throw error;
785
- })
786
- .finally(() => scope.disconnect());
787
- }
788
- }
789
-
790
- // Re-read so we have the bodyStorageKey the backfill just wrote (or the
791
- // key that was already present), then pull the raw bytes from storage.
792
- const stored = await client.message.get(messageId);
793
- if (!stored.bodyStorageKey) {
794
- throw new Error(
795
- `Raw source unavailable for message ${messageId}: no bodyStorageKey after backfill`,
796
- );
797
- }
798
-
799
- const body = await client.storage.retrieve(stored.bodyStorageKey);
800
-
801
- return { raw: decodeRawEml(body) };
802
- },
803
-
804
- MessageOperations_updateMessageFlags: async (context, ...args: unknown[]) => {
805
- const event = args[0] as APIGatewayProxyEvent;
806
- const accountConfigId = getAccountConfigIdFromEvent(event);
807
- const { messageId } = context.request.params as { messageId: string };
808
- const { isRead, isStarred, starColor } = context.request.requestBody as {
809
- isRead?: boolean;
810
- isStarred?: boolean;
811
- starColor?: string;
812
- };
813
-
814
- const client = await getClient();
815
- const accountId = await assertMessagesOwned(
816
- client,
817
- [messageId],
818
- accountConfigId,
819
- "act",
820
- );
821
-
822
- // FlagQueueService handles: MessageFlag + ThreadMessage updates + SQS event
823
- const result = await client.flagQueue.updateFlags(
824
- accountConfigId,
825
- messageId,
826
- accountId,
827
- {
828
- isRead,
829
- isStarred,
830
- starColor: starColor as StarColorValue | undefined,
831
- },
832
- );
833
-
834
- return {
835
- messageId: result.messageId,
836
- isRead: result.isRead,
837
- isStarred: result.isStarred,
838
- };
839
- },
840
- };
841
-
842
- export const MessageBulkOperations: Record<
843
- MessageBulkOperationIds,
844
- OperationHandler<MessageBulkOperationIds>
845
- > = {
846
- MessageBulkOperations_updateFlags: async (context, ...args: unknown[]) => {
847
- const event = args[0] as APIGatewayProxyEvent;
848
- const accountConfigId = getAccountConfigIdFromEvent(event);
849
- const { messageIds, isRead, isStarred, starColor } = context.request
850
- .requestBody as {
851
- messageIds: string[];
852
- isRead?: boolean;
853
- isStarred?: boolean;
854
- starColor?: string;
855
- };
856
-
857
- if (messageIds.length === 0) {
858
- return { successCount: 0, failureCount: 0 };
859
- }
860
-
861
- const client = await getClient();
862
- const accountId = await assertMessagesOwned(
863
- client,
864
- messageIds,
865
- accountConfigId,
866
- "act",
867
- );
868
-
869
- // FlagQueueService handles: MessageFlag + ThreadMessage updates + SQS events
870
- // Process each message individually (same pattern as moveMessages)
871
- for (const messageId of messageIds) {
872
- await client.flagQueue.updateFlags(
873
- accountConfigId,
874
- messageId,
875
- accountId,
876
- {
877
- isRead,
878
- isStarred,
879
- starColor: starColor as StarColorValue | undefined,
880
- },
881
- );
882
- }
883
-
884
- return {
885
- successCount: messageIds.length,
886
- failureCount: 0,
887
- };
888
- },
889
-
890
- MessageBulkOperations_deleteMessages: async (context, ...args: unknown[]) => {
891
- const event = args[0] as APIGatewayProxyEvent;
892
- const accountConfigId = getAccountConfigIdFromEvent(event);
893
- const { messageIds, permanent } = context.request.requestBody as {
894
- messageIds: string[];
895
- permanent?: boolean;
896
- };
897
-
898
- if (messageIds.length === 0) {
899
- return { successCount: 0, failureCount: 0 };
900
- }
901
-
902
- const client = await getClient();
903
- const accountId = await assertMessagesOwned(
904
- client,
905
- messageIds,
906
- accountConfigId,
907
- "act",
908
- );
909
-
910
- // MessageMoveService handles: Message + ThreadMessage updates + SQS events
911
- const { refusedMessageIds } = await client.messageMove.deleteMessages(
912
- accountConfigId,
913
- messageIds,
914
- accountId,
915
- {
916
- permanent,
917
- },
918
- );
919
-
920
- // A row whose placement changed under the batch is reported, not dropped.
921
- // The response already carries per-row counts, which is the honest shape
922
- // for a batch that partly applied — a 409 over it would deny the deletes
923
- // that did happen, and silence leaves the client's optimistic removal to
924
- // reappear with nothing said (imap-mutations R3).
925
- return {
926
- successCount: messageIds.length - refusedMessageIds.length,
927
- failureCount: refusedMessageIds.length,
928
- };
929
- },
930
-
931
- MessageBulkOperations_moveMessages: async (context, ...args: unknown[]) => {
932
- const event = args[0] as APIGatewayProxyEvent;
933
- const accountConfigId = getAccountConfigIdFromEvent(event);
934
- const { messageIds, destinationMailboxId } = context.request
935
- .requestBody as {
936
- messageIds: string[];
937
- destinationMailboxId: string;
938
- };
939
-
940
- if (messageIds.length === 0) {
941
- return { successCount: 0, failureCount: 0 };
942
- }
943
-
944
- const client = await getClient();
945
- const accountId = await assertMessagesOwned(
946
- client,
947
- messageIds,
948
- accountConfigId,
949
- "act",
950
- );
951
-
952
- // Destination must belong to the same (caller-owned) account, and must be
953
- // a folder the mail server has settled: the row records the destination
954
- // before the move confirms, so binding to a folder that may never exist
955
- // leaves the message pointing at nothing (D12, first row).
956
- const destination = await client.mailbox.get(
957
- accountId,
958
- destinationMailboxId,
959
- );
960
- if (destination.accountId !== accountId) {
961
- throw new ForbiddenError(
962
- `Destination mailbox ${destinationMailboxId} not in account`,
963
- );
964
- }
965
- assertMailboxSettled(destination);
966
-
967
- // MessageMoveService handles: Message + ThreadMessage updates + SQS events
968
- await client.messageMove.moveMessages(
969
- accountConfigId,
970
- messageIds,
971
- destinationMailboxId,
972
- accountId,
973
- );
974
-
975
- return {
976
- successCount: messageIds.length,
977
- failureCount: 0,
978
- };
979
- },
980
-
981
- MessageBulkOperations_copyMessages: async (context, ...args: unknown[]) => {
982
- const event = args[0] as APIGatewayProxyEvent;
983
- const accountConfigId = getAccountConfigIdFromEvent(event);
984
- const { messageIds, destinationMailboxId } = context.request
985
- .requestBody as {
986
- messageIds: string[];
987
- destinationMailboxId: string;
988
- };
989
-
990
- if (messageIds.length === 0) {
991
- return { successCount: 0, failureCount: 0 };
992
- }
993
-
994
- const client = await getClient();
995
- const accountId = await assertMessagesOwned(
996
- client,
997
- messageIds,
998
- accountConfigId,
999
- "act",
1000
- );
1001
-
1002
- // Destination must belong to the same (caller-owned) account, and must be
1003
- // a folder the mail server has settled: the row records the destination
1004
- // before the move confirms, so binding to a folder that may never exist
1005
- // leaves the message pointing at nothing (D12, first row).
1006
- const destination = await client.mailbox.get(
1007
- accountId,
1008
- destinationMailboxId,
1009
- );
1010
- if (destination.accountId !== accountId) {
1011
- throw new ForbiddenError(
1012
- `Destination mailbox ${destinationMailboxId} not in account`,
1013
- );
1014
- }
1015
- assertMailboxSettled(destination);
1016
-
1017
- // MessageMoveService handles: Message copies + ThreadMessage creation + SQS events
1018
- await client.messageMove.copyMessages(
1019
- accountConfigId,
1020
- messageIds,
1021
- destinationMailboxId,
1022
- accountId,
1023
- );
1024
-
1025
- return {
1026
- successCount: messageIds.length,
1027
- failureCount: 0,
1028
- };
1029
- },
1030
-
1031
- MessageBulkOperations_updateMessageLabels: async (
1032
- context,
1033
- ...args: unknown[]
1034
- ) => {
1035
- const event = args[0] as APIGatewayProxyEvent;
1036
- const accountConfigId = getAccountConfigIdFromEvent(event);
1037
- const { messageIds, labelId, action } = context.request.requestBody as {
1038
- messageIds: string[];
1039
- labelId: string;
1040
- action: "Apply" | "Remove";
1041
- };
1042
-
1043
- if (messageIds.length === 0) {
1044
- return { successCount: 0, failureCount: 0 };
1045
- }
1046
-
1047
- const client = await getClient();
1048
- await assertMessagesOwned(client, messageIds, accountConfigId, "act");
1049
-
1050
- // Scoped by accountConfigId (RFC 030) — a foreign labelId 404s here rather
1051
- // than silently applying to messages under someone else's label.
1052
- await client.label.get(accountConfigId, labelId);
1053
-
1054
- // `appliedByFilterId` stays absent — this is the manual "just these" scope
1055
- // (RFC 034 Decision 3.3), never filter-attributed.
1056
- if (action === "Apply") {
1057
- for (const messageId of messageIds) {
1058
- await client.messageLabel.apply({
1059
- accountConfigId,
1060
- messageId,
1061
- labelId,
1062
- });
1063
- }
1064
- } else {
1065
- for (const messageId of messageIds) {
1066
- await client.messageLabel.remove(messageId, labelId);
1067
- }
1068
- }
1069
-
1070
- return {
1071
- successCount: messageIds.length,
1072
- failureCount: 0,
1073
- };
1074
- },
1075
-
1076
- MessageBulkOperations_reportSpam: async (context, ...args: unknown[]) => {
1077
- const event = args[0] as APIGatewayProxyEvent;
1078
- const accountConfigId = getAccountConfigIdFromEvent(event);
1079
- const { messageIds: requestedIds } = context.request.requestBody as {
1080
- messageIds: string[];
1081
- };
1082
- const messageIds = [...new Set(requestedIds)];
1083
-
1084
- if (messageIds.length === 0) {
1085
- return { successCount: 0, failureCount: 0 };
1086
- }
1087
-
1088
- const client = await getClient();
1089
- const accountId = await assertMessagesOwned(
1090
- client,
1091
- messageIds,
1092
- accountConfigId,
1093
- "act",
1094
- );
1095
- const setBy = getSubFromEvent(event) ?? accountConfigId;
1096
-
1097
- return settleSpamReportBulk(messageIds, (messageId) =>
1098
- client.spamReport.reportSpam({
1099
- accountConfigId,
1100
- accountId,
1101
- messageId,
1102
- setBy,
1103
- }),
1104
- );
1105
- },
1106
-
1107
- MessageBulkOperations_notSpam: async (context, ...args: unknown[]) => {
1108
- const event = args[0] as APIGatewayProxyEvent;
1109
- const accountConfigId = getAccountConfigIdFromEvent(event);
1110
- const { messageIds: requestedIds } = context.request.requestBody as {
1111
- messageIds: string[];
1112
- };
1113
- const messageIds = [...new Set(requestedIds)];
1114
-
1115
- if (messageIds.length === 0) {
1116
- return { successCount: 0, failureCount: 0 };
1117
- }
1118
-
1119
- const client = await getClient();
1120
- const accountId = await assertMessagesOwned(
1121
- client,
1122
- messageIds,
1123
- accountConfigId,
1124
- "act",
1125
- );
1126
-
1127
- return settleSpamReportBulk(messageIds, (messageId) =>
1128
- client.spamReport.notSpam({ accountConfigId, accountId, messageId }),
1129
- );
1130
- },
1131
- };