@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
@@ -0,0 +1,367 @@
1
+ import { NotFoundError } from "@remit/data-ports/errors";
2
+ import { FilterClauseField, FilterDisabledReason, FilterState, } from "@remit/domain-enums";
3
+ import { logger } from "@remit/logger";
4
+ import { FilterPipeline, literalClausesMatch, literalClauseTerms, NO_ACTION, PlacementMoveService, } from "@remit/mailbox-service";
5
+ import { buildFilterConfig } from "@remit/mailbox-service/filter-config";
6
+ /**
7
+ * Hard cap on both the previewed and the applied set. A back-apply is a
8
+ * data-heavy corpus pass (remit-data-heavy: frugal), bounded by counting
9
+ * MATCHES as it pages a store-side narrowed listing, and the final match set
10
+ * never exceeds this. It bounds the answer, never the corpus the question is
11
+ * asked of (#459).
12
+ */
13
+ export const ORGANIZE_MATCH_LIMIT = 500;
14
+ /**
15
+ * The predicate a back-apply job snapshotted onto its row, read back verbatim so
16
+ * the worker runs exactly what the request asked for.
17
+ */
18
+ export const predicateFromJob = (job) => ({
19
+ matchOperator: job.matchOperator,
20
+ literalClauses: job.literalClauses,
21
+ actionLabelId: job.actionLabelId,
22
+ actionMailboxId: job.actionMailboxId,
23
+ });
24
+ /**
25
+ * A `HasWords` clause matches the message body (RFC 031, `clauseMatches`). The
26
+ * live index-time filter evaluates it against the full parsed body
27
+ * (`body-sync.ts` `toFilterMessage`); the corpus slice carries only
28
+ * `From`/`Subject` at full fidelity and no faithful body, so it cannot serve a
29
+ * body-content clause without silently narrowing the match to whatever preview
30
+ * happened to be stored. A body-content clause on an "all like these" pass is
31
+ * refused instead of returning a wrong set.
32
+ */
33
+ export const BODY_CONTENT_REJECTION_MESSAGE = "Organize cannot match a body-content (HasWords) clause over the mailbox: it reads only each message's preview, not its body";
34
+ const bodyContentRejection = (clauses) => clauses.some((clause) => clause.field === FilterClauseField.HasWords)
35
+ ? {
36
+ reason: "BodyContentUnsupported",
37
+ message: BODY_CONTENT_REJECTION_MESSAGE,
38
+ }
39
+ : null;
40
+ /**
41
+ * The refusal a predicate carries on its own, decidable without reading the
42
+ * corpus: a body-content clause is refused up front. `createOrganizeJob` runs
43
+ * this before enqueueing and {@link matchOrganize} runs it too, so preview, the
44
+ * worker and the request boundary all refuse the same rule (reader #463).
45
+ */
46
+ export const organizePredicateRejection = (predicate) => bodyContentRejection(predicate.literalClauses);
47
+ /**
48
+ * The store selects on the clause terms, this refines what it returned and
49
+ * stops at `limit` MATCHES. Serves `From`/`Subject` clauses at
50
+ * full fidelity from the core thread rows; body-content (`HasWords`) clauses are
51
+ * refused before this runs (see {@link bodyContentRejection}).
52
+ *
53
+ * The terms are a narrowing, not the verdict ({@link literalClauseTerms}), so
54
+ * every page is still run through {@link literalClausesMatch} — and paging
55
+ * continues until the cap fills or the store runs out, which is what makes the
56
+ * bound a bound on results rather than on the newest `limit` rows (#459).
57
+ * Deduped by message id: the same mail filed in two folders is one match.
58
+ */
59
+ const matchLiteral = async (deps, accountConfigId, predicate, limit, scope) => {
60
+ const clauses = predicate.literalClauses;
61
+ const narrowing = literalClauseTerms(clauses, predicate.matchOperator);
62
+ if (!narrowing)
63
+ return [];
64
+ const matched = [];
65
+ const seen = new Set();
66
+ let continuationToken;
67
+ do {
68
+ const page = await deps.listAccountFilterMessages(accountConfigId, {
69
+ ...narrowing,
70
+ limit,
71
+ continuationToken,
72
+ mailboxIds: scope.mailboxIds,
73
+ });
74
+ for (const { messageId, message } of page.items) {
75
+ if (seen.has(messageId))
76
+ continue;
77
+ seen.add(messageId);
78
+ if (!literalClausesMatch(clauses, predicate.matchOperator, message)) {
79
+ continue;
80
+ }
81
+ matched.push(messageId);
82
+ if (matched.length >= limit)
83
+ return matched;
84
+ }
85
+ continuationToken = page.continuationToken;
86
+ } while (continuationToken);
87
+ return matched;
88
+ };
89
+ /**
90
+ * The matcher shared by preview and apply — the previewed set equals the applied
91
+ * set for the same input. Read-only. Returns the matching message ids, bounded.
92
+ *
93
+ * - An ad-hoc predicate with no clause matches nothing: a run-now request
94
+ * carries none, and an empty predicate must never sweep the whole mailbox.
95
+ * - A predicate the corpus read cannot evaluate (a body-content clause on an
96
+ * "all like these" pass, see {@link bodyContentRejection}) comes back as a
97
+ * rejection, so a caller can tell a refused rule from a broken deployment
98
+ * (reader #463).
99
+ */
100
+ export const matchOrganize = async (deps, accountConfigId, predicate, limit = ORGANIZE_MATCH_LIMIT, scope = {}) => {
101
+ if (predicate.literalClauses.length === 0) {
102
+ return { rejected: null, messageIds: [] };
103
+ }
104
+ const rejection = scope.filterId
105
+ ? null
106
+ : organizePredicateRejection(predicate);
107
+ if (rejection)
108
+ return { rejected: rejection };
109
+ const messageIds = await matchLiteral(deps, accountConfigId, predicate, limit, scope);
110
+ return { rejected: null, messageIds };
111
+ };
112
+ /**
113
+ * The corpus read for a back-apply: one page of the account's messages,
114
+ * newest-first across every mailbox, with the clause terms evaluated in the
115
+ * query.
116
+ *
117
+ * `From`/`Subject`/`listId` come from the row verbatim (full fidelity), so a
118
+ * `From`, `Subject`, `FromDomain` or `ListId` clause matches here exactly as it
119
+ * does at index time. `text` is the row's stored body preview (`snippet`),
120
+ * the same text search matches free words against. An "all like these" pass
121
+ * refuses a body-content (`HasWords`) clause before reading it (see
122
+ * {@link bodyContentRejection}); a filter back-apply matches it on the
123
+ * preview, the mail search showed the user when the rule was made (#1354).
124
+ */
125
+ const listAccountFilterMessagesFromClient = (client) => async (accountConfigId, query) => {
126
+ const page = await client.threadMessage.listByFieldTerms(accountConfigId, query.terms, {
127
+ operator: query.operator,
128
+ limit: query.limit,
129
+ continuationToken: query.continuationToken,
130
+ excludeDeleted: true,
131
+ mailboxIds: query.mailboxIds,
132
+ });
133
+ return {
134
+ items: page.items.map((row) => ({
135
+ messageId: row.messageId,
136
+ message: {
137
+ from: row.fromEmail ?? "",
138
+ fromName: row.fromName ?? "",
139
+ subject: row.subject ?? "",
140
+ text: row.snippet ?? "",
141
+ listId: row.listId ?? "",
142
+ },
143
+ })),
144
+ continuationToken: page.continuationToken,
145
+ };
146
+ };
147
+ /** The matcher deps for the running backend/worker. */
148
+ export const buildOrganizeMatchDeps = (client) => ({
149
+ listAccountFilterMessages: listAccountFilterMessagesFromClient(client),
150
+ });
151
+ /**
152
+ * The exclusive-move arm of a back-apply, wired exactly like the body-sync
153
+ * placement mover (`sync-message-body.ts`): the local-first
154
+ * {@link PlacementMoveService} over the shared message-management queue. A move
155
+ * commits locally (marker + ThreadMessage + Message row) and enqueues a
156
+ * `PLACEMENT_MOVE_PUSH` for the reconciler; its marker state engine makes a
157
+ * redelivered job idempotent (mirrors #1297).
158
+ */
159
+ export const buildOrganizeMoveService = (client) => new PlacementMoveService({
160
+ messageService: client.message,
161
+ threadMessageService: client.threadMessage,
162
+ markerService: client.placementMove,
163
+ addressService: client.address,
164
+ mailboxSpecialUseService: client.mailboxSpecialUse,
165
+ mailboxService: client.mailbox,
166
+ queue: client.queues.messageManagement,
167
+ });
168
+ /**
169
+ * Apply the back-apply action to every matched message, reusing the index-time
170
+ * apply plumbing: an idempotent MessageLabel upsert (additive) with
171
+ * `appliedByFilterId` deliberately ABSENT — this path attributes to no filter,
172
+ * exactly like a hand-applied label (RFC 034 Decision 3.3) — and an idempotent
173
+ * folder move (exclusive). One poisoned message never fails the batch; it is
174
+ * counted as failed and the pass continues.
175
+ *
176
+ * Every requested move happens. A standing filter acts at exactly two moments —
177
+ * when a message is first seen, and when the user presses "run rules now" — and
178
+ * holds no claim on that message afterwards, so it never arbitrates against a
179
+ * later user-initiated apply (reader #497). Cross-filter precedence stays where
180
+ * two filters collide over the same message at the same trigger
181
+ * (`FilterPipeline`/`selectMoveWinner`), and `applied` therefore counts moves
182
+ * that actually happened.
183
+ */
184
+ export const applyOrganize = async (deps, accountConfigId, messageIds, predicate) => {
185
+ const { client, moveService } = deps;
186
+ const applyLabel = predicate.actionLabelId !== NO_ACTION && predicate.actionLabelId !== "";
187
+ const applyMove = predicate.actionMailboxId !== NO_ACTION && predicate.actionMailboxId !== "";
188
+ const applyToMessage = async (messageId) => {
189
+ if (applyMove) {
190
+ const message = await client.message.get(messageId);
191
+ const accountId = await client.mailbox.resolveAccountId(message.mailboxId);
192
+ if (!accountId) {
193
+ throw new Error(`Cannot resolve owning account for mailbox ${message.mailboxId}`);
194
+ }
195
+ const outcome = await moveService.moveMessage(accountConfigId, messageId, predicate.actionMailboxId, accountId);
196
+ if (outcome === "refused")
197
+ return { kind: "skipped" };
198
+ }
199
+ if (applyLabel) {
200
+ await client.messageLabel.apply({
201
+ messageId,
202
+ labelId: predicate.actionLabelId,
203
+ accountConfigId,
204
+ });
205
+ }
206
+ return { kind: "applied" };
207
+ };
208
+ const result = {
209
+ applied: 0,
210
+ failed: 0,
211
+ failures: [],
212
+ };
213
+ for (const messageId of messageIds) {
214
+ // Per-message isolation: one poisoned message is counted, its reason kept
215
+ // for the job, and the pass continues.
216
+ const outcome = await applyToMessage(messageId).catch((error) => ({
217
+ kind: "failed",
218
+ reason: error instanceof Error ? error.message : String(error),
219
+ }));
220
+ if (outcome.kind === "skipped")
221
+ continue;
222
+ if (outcome.kind === "applied") {
223
+ result.applied += 1;
224
+ continue;
225
+ }
226
+ result.failed += 1;
227
+ result.failures.push(outcome.reason);
228
+ logger.warn({ accountConfigId, messageId, reason: outcome.reason }, "Organize could not apply its action to a message");
229
+ }
230
+ return result;
231
+ };
232
+ const FILTER_NOT_ACTIVE_MESSAGE = "This filter is turned off or has expired. Turn it on to run it over the inbox.";
233
+ const FOLDER_MISSING_MESSAGE = "The folder this filter moves mail into no longer exists, so the filter was turned off. Pick another folder in the rule, then turn it on.";
234
+ const FILTER_MISSING_MESSAGE = "This filter was deleted before it could run over the inbox.";
235
+ const rejectFilter = (reason, message) => ({ rejected: { reason, message } });
236
+ /** A standing filter's predicate and action, read the way index time reads them. */
237
+ const predicateFromFilter = (filter) => ({
238
+ matchOperator: filter.matchOperator,
239
+ literalClauses: filter.literalClauses,
240
+ actionLabelId: filter.actionLabelId,
241
+ actionMailboxId: filter.actionMailboxId,
242
+ });
243
+ /**
244
+ * Read the filter a job names: refused when it was deleted or is not Active,
245
+ * since index time evaluates neither.
246
+ */
247
+ const loadFilter = async (client, accountConfigId, filterId) => {
248
+ const stored = await client.filter
249
+ .get(accountConfigId, filterId)
250
+ .catch((error) => {
251
+ if (error instanceof NotFoundError)
252
+ return null;
253
+ throw error;
254
+ });
255
+ if (!stored)
256
+ return rejectFilter("FilterMissing", FILTER_MISSING_MESSAGE);
257
+ const filter = await client.filter.refreshExpiry(stored);
258
+ if (filter.state !== FilterState.Active) {
259
+ return rejectFilter("FilterNotActive", FILTER_NOT_ACTIVE_MESSAGE);
260
+ }
261
+ return { rejected: null, filter, predicate: predicateFromFilter(filter) };
262
+ };
263
+ /** Every inbox under the config — the folders a filter back-apply runs over. */
264
+ const inboxMailboxIds = async (client, accountConfigId) => {
265
+ const accounts = await client.account.listMailSourcesByAccountConfig(accountConfigId);
266
+ const inboxes = await Promise.all(accounts.map((account) => client.mailboxSpecialUse.findInboxMailbox(account.accountId)));
267
+ return inboxes.flatMap((inbox) => (inbox ? [inbox.mailboxId] : []));
268
+ };
269
+ /**
270
+ * The message as the index-time pipeline reads it, from its thread row. The
271
+ * body is the stored preview, so a `HasWords` clause matches what search
272
+ * matched. A message deleted since the match has no row.
273
+ */
274
+ const filterMessageOf = async (client, accountConfigId, messageId) => {
275
+ const row = await client.threadMessage
276
+ .getByMessageId(accountConfigId, messageId)
277
+ .catch((error) => {
278
+ if (error instanceof NotFoundError)
279
+ return null;
280
+ throw error;
281
+ });
282
+ if (!row)
283
+ return null;
284
+ return {
285
+ from: row.fromEmail ?? "",
286
+ fromName: row.fromName ?? "",
287
+ subject: row.subject ?? "",
288
+ text: row.snippet ?? "",
289
+ listId: row.listId ?? "",
290
+ };
291
+ };
292
+ /**
293
+ * Run one standing filter over the inbox as if each matching message had just
294
+ * arrived. Every message the matcher returns is a match: its label always
295
+ * applies, being additive. The index-time {@link FilterPipeline} only orders
296
+ * the exclusive move, so the move is skipped where it names another active
297
+ * filter. The pipeline sees the stored preview rather than the full body, so
298
+ * its verdict on whether this filter matches is not asked; and an evaluate it
299
+ * could not finish names no other filter, so the move goes ahead rather than
300
+ * silently dropping out.
301
+ */
302
+ export const backApplyFilter = async (deps, accountConfigId, filterId) => {
303
+ const { client, matchDeps, moveService } = deps;
304
+ const loaded = await loadFilter(client, accountConfigId, filterId);
305
+ if (loaded.rejected)
306
+ return loaded;
307
+ const config = buildFilterConfig({
308
+ filterService: client.filter,
309
+ messageLabelService: client.messageLabel,
310
+ mailboxService: client.mailbox,
311
+ placementMoveService: moveService,
312
+ });
313
+ const pipeline = new FilterPipeline(config, logger);
314
+ const mailboxIds = await inboxMailboxIds(client, accountConfigId);
315
+ const nothing = {
316
+ rejected: null,
317
+ matched: 0,
318
+ applied: 0,
319
+ failed: 0,
320
+ failures: [],
321
+ };
322
+ if (mailboxIds.length === 0)
323
+ return nothing;
324
+ const match = await matchOrganize(matchDeps, accountConfigId, loaded.predicate, ORGANIZE_MATCH_LIMIT, { filterId, mailboxIds });
325
+ if (match.rejected)
326
+ return match;
327
+ const { filter, predicate } = loaded;
328
+ const folderAccountId = filter.actionMailboxId === NO_ACTION
329
+ ? undefined
330
+ : await client.mailbox.resolveAccountId(filter.actionMailboxId);
331
+ if (folderAccountId === null) {
332
+ await client.filter.update(accountConfigId, filterId, {
333
+ state: FilterState.Disabled,
334
+ disabledReason: FilterDisabledReason.FolderMissing,
335
+ });
336
+ return rejectFilter("FolderMissing", FOLDER_MISSING_MESSAGE);
337
+ }
338
+ const result = {
339
+ ...nothing,
340
+ matched: match.messageIds.length,
341
+ };
342
+ for (const messageId of match.messageIds) {
343
+ const message = await filterMessageOf(client, accountConfigId, messageId);
344
+ if (!message)
345
+ continue;
346
+ const accountId = await client.mailbox.resolveAccountId((await client.message.get(messageId)).mailboxId);
347
+ if (!accountId)
348
+ continue;
349
+ if (folderAccountId !== undefined && folderAccountId !== accountId) {
350
+ continue;
351
+ }
352
+ const decision = await pipeline.evaluate(accountConfigId, accountId, messageId, message);
353
+ const move = (decision.move?.filterId ?? filterId) === filterId;
354
+ if (!move && filter.actionLabelId === NO_ACTION)
355
+ continue;
356
+ const outcome = await applyOrganize({ client, moveService }, accountConfigId, [messageId], {
357
+ ...predicate,
358
+ actionMailboxId: move ? filter.actionMailboxId : NO_ACTION,
359
+ });
360
+ result.applied += outcome.applied;
361
+ result.failed += outcome.failed;
362
+ result.failures.push(...outcome.failures);
363
+ }
364
+ return result;
365
+ };
366
+ /** Whether a job row runs a standing filter rather than its own snapshot. */
367
+ export const isFilterJob = (job) => job.filterId !== NO_ACTION;
@@ -0,0 +1,12 @@
1
+ import type { AccountFanoutEvent, FifoQueueProducer, QueueProducer } from "@remit/data-ports";
2
+ import type { FlagPushEvent, MailboxManagementEvent, MessageMoveQueueEvent, PlacementMovePushEvent, SendMessageEvent, SyncMessageBodyEvent } from "@remit/mailbox-service";
3
+ import type { SyncMailboxesEvent } from "./trigger-sync.js";
4
+ export type SyncQueueEvent = SyncMailboxesEvent | FlagPushEvent | MailboxManagementEvent | MessageMoveQueueEvent;
5
+ export interface RemitClientQueues {
6
+ sync: FifoQueueProducer<SyncQueueEvent>;
7
+ accountFanout: QueueProducer<AccountFanoutEvent>;
8
+ smtp: FifoQueueProducer<SendMessageEvent>;
9
+ messageManagement: QueueProducer<PlacementMovePushEvent>;
10
+ body: QueueProducer<SyncMessageBodyEvent>;
11
+ }
12
+ export type QueueName = keyof RemitClientQueues;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ import { type HTTPError } from "@remit/data-ports/errors";
2
+ import type { Refusable, Refusal } from "@remit/mailbox-service";
3
+ export declare const refusalError: (refusal: Refusal) => HTTPError;
4
+ export declare const unwrap: <T>(outcome: Refusable<T>) => T;
@@ -0,0 +1,20 @@
1
+ import { BadRequestError, ConflictError, ForbiddenError, MailboxNotSettledError, NotFoundError, } from "@remit/data-ports/errors";
2
+ export const refusalError = (refusal) => {
3
+ switch (refusal.kind) {
4
+ case "Invalid":
5
+ return new BadRequestError(refusal.message);
6
+ case "Forbidden":
7
+ return new ForbiddenError(refusal.message);
8
+ case "NotFound":
9
+ return new NotFoundError(refusal.message);
10
+ case "Conflict":
11
+ return new ConflictError(refusal.message);
12
+ case "NotSettled":
13
+ return new MailboxNotSettledError(refusal.message, refusal.mailboxId, refusal.syncStatus);
14
+ }
15
+ };
16
+ export const unwrap = (outcome) => {
17
+ if (outcome.ok)
18
+ return outcome.value;
19
+ throw refusalError(outcome.refusal);
20
+ };
@@ -0,0 +1,51 @@
1
+ import type { MessageCategoryValue } from "@remit/mailbox-service";
2
+ import type { RemitClient } from "./data-client.js";
3
+ /**
4
+ * How much of a sender's already-classified mail one override reaches: the
5
+ * newest 500 of their messages held in the local store. A back-apply is a
6
+ * bounded recent batch, never the sender's whole history — the store-side
7
+ * narrowing pages until this many MATCHES, so a quiet sender's mail is reached
8
+ * however old it is, and a bulk sender's oldest mail is deliberately left as
9
+ * the classifier decided it. The same constant the organize back-apply bounds
10
+ * its match set with (`ORGANIZE_MATCH_LIMIT`), for the same reason.
11
+ */
12
+ export declare const SENDER_CATEGORY_BACKAPPLY_LIMIT = 500;
13
+ export interface SenderCategoryBackApplyDeps {
14
+ client: Pick<RemitClient, "message" | "threadMessage">;
15
+ }
16
+ export interface SenderCategoryBackApplyResult {
17
+ matched: number;
18
+ applied: number;
19
+ failed: number;
20
+ }
21
+ /**
22
+ * Back-apply a sender's `Address.flags.category` override to mail that was
23
+ * already classified before the override was set (#415). Issue #299 gave the
24
+ * override full effect on the sender's NEXT message only; this is the
25
+ * retroactive half, deliberately bounded to
26
+ * {@link SENDER_CATEGORY_BACKAPPLY_LIMIT}.
27
+ *
28
+ * This is the one path that intentionally rewrites an already-decided
29
+ * `Message.category`, so it does not — and must not — reuse body sync's
30
+ * `hasDecidedCategory` write-once guard. Its consistency story is that
31
+ * `category` is a key attribute of no provisioned index: the DynamoDB LSI that
32
+ * would have sorted on it was never provisioned and cannot be (#516), and the
33
+ * filtered-mailbox read path is served by the SQL-only
34
+ * `tm_by_mailbox_category_date` index, where an update simply moves the row.
35
+ * What a rewrite can still break is the Message/ThreadMessage pair disagreeing
36
+ * — the badge is served from the thread row and so is the category filter — so
37
+ * both are written per message, thread rows first, and a redelivered job
38
+ * re-runs the same idempotent writes.
39
+ *
40
+ * Nothing here touches placement: `category` is not an input to
41
+ * `classifyPlacement`, so an override re-labels mail where it already sits and
42
+ * files nothing. No remote mail-server state changes, which is why this is not
43
+ * an IMAP mutation and does not take the mutator pattern.
44
+ *
45
+ * Per-message isolation, exactly as `applyOrganize` has it: one poisoned
46
+ * message is counted as failed and the pass continues, so a single missing
47
+ * thread row never costs the other 499 their re-label. Unlike a job row, this
48
+ * count is not the end of the story — the caller is expected to leave a pass
49
+ * with failures unacknowledged so redelivery converges the rest.
50
+ */
51
+ export declare const backApplySenderCategory: (deps: SenderCategoryBackApplyDeps, accountConfigId: string, normalizedEmail: string, category: MessageCategoryValue, limit?: number) => Promise<SenderCategoryBackApplyResult>;
@@ -1,7 +1,4 @@
1
- import type { MessageCategoryValue } from "@remit/mailbox-service";
2
1
  import { denormalizeMessageCategory } from "@remit/mailbox-service";
3
- import type { RemitClient } from "./data-client.js";
4
-
5
2
  /**
6
3
  * How much of a sender's already-classified mail one override reaches: the
7
4
  * newest 500 of their messages held in the local store. A back-apply is a
@@ -12,17 +9,6 @@ import type { RemitClient } from "./data-client.js";
12
9
  * its match set with (`ORGANIZE_MATCH_LIMIT`), for the same reason.
13
10
  */
14
11
  export const SENDER_CATEGORY_BACKAPPLY_LIMIT = 500;
15
-
16
- export interface SenderCategoryBackApplyDeps {
17
- client: Pick<RemitClient, "message" | "threadMessage">;
18
- }
19
-
20
- export interface SenderCategoryBackApplyResult {
21
- matched: number;
22
- applied: number;
23
- failed: number;
24
- }
25
-
26
12
  /**
27
13
  * The sender's newest messages in the local store, bounded at `limit`, newest
28
14
  * first and deduplicated by messageId.
@@ -34,36 +20,27 @@ export interface SenderCategoryBackApplyResult {
34
20
  * out, which is what makes the bound a bound on the sender's messages rather
35
21
  * than on how far back the read reached (#459).
36
22
  */
37
- const listSenderMessageIds = async (
38
- deps: SenderCategoryBackApplyDeps,
39
- accountConfigId: string,
40
- normalizedEmail: string,
41
- limit: number,
42
- ): Promise<string[]> => {
43
- const wanted = normalizedEmail.toLowerCase();
44
- const messageIds: string[] = [];
45
- const seen = new Set<string>();
46
- let continuationToken: string | undefined;
47
-
48
- do {
49
- const page = await deps.client.threadMessage.listByFieldTerms(
50
- accountConfigId,
51
- [{ field: "sender", contains: wanted }],
52
- { limit, continuationToken, excludeDeleted: true },
53
- );
54
- for (const row of page.items) {
55
- if (row.fromEmail?.toLowerCase() !== wanted) continue;
56
- if (seen.has(row.messageId)) continue;
57
- seen.add(row.messageId);
58
- messageIds.push(row.messageId);
59
- if (messageIds.length >= limit) return messageIds;
60
- }
61
- continuationToken = page.continuationToken;
62
- } while (continuationToken);
63
-
64
- return messageIds;
23
+ const listSenderMessageIds = async (deps, accountConfigId, normalizedEmail, limit) => {
24
+ const wanted = normalizedEmail.toLowerCase();
25
+ const messageIds = [];
26
+ const seen = new Set();
27
+ let continuationToken;
28
+ do {
29
+ const page = await deps.client.threadMessage.listByFieldTerms(accountConfigId, [{ field: "sender", contains: wanted }], { limit, continuationToken, excludeDeleted: true });
30
+ for (const row of page.items) {
31
+ if (row.fromEmail?.toLowerCase() !== wanted)
32
+ continue;
33
+ if (seen.has(row.messageId))
34
+ continue;
35
+ seen.add(row.messageId);
36
+ messageIds.push(row.messageId);
37
+ if (messageIds.length >= limit)
38
+ return messageIds;
39
+ }
40
+ continuationToken = page.continuationToken;
41
+ } while (continuationToken);
42
+ return messageIds;
65
43
  };
66
-
67
44
  /**
68
45
  * Back-apply a sender's `Address.flags.category` override to mail that was
69
46
  * already classified before the override was set (#415). Issue #299 gave the
@@ -94,42 +71,24 @@ const listSenderMessageIds = async (
94
71
  * count is not the end of the story — the caller is expected to leave a pass
95
72
  * with failures unacknowledged so redelivery converges the rest.
96
73
  */
97
- export const backApplySenderCategory = async (
98
- deps: SenderCategoryBackApplyDeps,
99
- accountConfigId: string,
100
- normalizedEmail: string,
101
- category: MessageCategoryValue,
102
- limit: number = SENDER_CATEGORY_BACKAPPLY_LIMIT,
103
- ): Promise<SenderCategoryBackApplyResult> => {
104
- const messageIds = await listSenderMessageIds(
105
- deps,
106
- accountConfigId,
107
- normalizedEmail,
108
- limit,
109
- );
110
-
111
- const relabel = async (messageId: string): Promise<void> => {
112
- await denormalizeMessageCategory(
113
- { threadMessageService: deps.client.threadMessage },
114
- accountConfigId,
115
- messageId,
116
- { category },
117
- );
118
- await deps.client.message.update(messageId, { category });
119
- };
120
-
121
- let applied = 0;
122
- let failed = 0;
123
- for (const messageId of messageIds) {
124
- const ok = await relabel(messageId)
125
- .then(() => true)
126
- .catch(() => false);
127
- if (ok) {
128
- applied += 1;
129
- } else {
130
- failed += 1;
131
- }
132
- }
133
-
134
- return { matched: messageIds.length, applied, failed };
74
+ export const backApplySenderCategory = async (deps, accountConfigId, normalizedEmail, category, limit = SENDER_CATEGORY_BACKAPPLY_LIMIT) => {
75
+ const messageIds = await listSenderMessageIds(deps, accountConfigId, normalizedEmail, limit);
76
+ const relabel = async (messageId) => {
77
+ await denormalizeMessageCategory({ threadMessageService: deps.client.threadMessage }, accountConfigId, messageId, { category });
78
+ await deps.client.message.update(messageId, { category });
79
+ };
80
+ let applied = 0;
81
+ let failed = 0;
82
+ for (const messageId of messageIds) {
83
+ const ok = await relabel(messageId)
84
+ .then(() => true)
85
+ .catch(() => false);
86
+ if (ok) {
87
+ applied += 1;
88
+ }
89
+ else {
90
+ failed += 1;
91
+ }
92
+ }
93
+ return { matched: messageIds.length, applied, failed };
135
94
  };
@@ -0,0 +1,6 @@
1
+ import type { RemitClientSharedDeps } from "./create-remit-client.js";
2
+ import type { QueueName, RemitClientQueues } from "./queues.js";
3
+ export type SqsQueueUrls = Record<QueueName, string>;
4
+ export declare const sqsQueueUrlsFromEnv: () => SqsQueueUrls;
5
+ export declare const sqsQueues: (urls: SqsQueueUrls) => RemitClientQueues;
6
+ export declare const buildSharedDeps: (queues: RemitClientQueues) => RemitClientSharedDeps;
@@ -0,0 +1,24 @@
1
+ import { createCachedDataKeyProvider, createSecretsService, } from "@remit/secrets-service";
2
+ import { createKmsDataKeyProvider, FAKE_KMS_KEY_ID, } from "@remit/secrets-service/kms";
3
+ import { createQueueProducer } from "@remit/sqs-client/producer";
4
+ import { createStorageService } from "@remit/storage-service/s3";
5
+ import { env } from "expect-env";
6
+ export const sqsQueueUrlsFromEnv = () => ({
7
+ sync: env.SQS_QUEUE_URL,
8
+ accountFanout: env.SQS_QUEUE_URL_ACCOUNT_FANOUT,
9
+ smtp: env.SQS_QUEUE_URL_SMTP,
10
+ messageManagement: env.SQS_QUEUE_URL_MESSAGE_MGMT,
11
+ body: env.SQS_QUEUE_URL_BODY,
12
+ });
13
+ export const sqsQueues = (urls) => ({
14
+ sync: createQueueProducer({ queueUrl: urls.sync }),
15
+ accountFanout: createQueueProducer({ queueUrl: urls.accountFanout }),
16
+ smtp: createQueueProducer({ queueUrl: urls.smtp }),
17
+ messageManagement: createQueueProducer({ queueUrl: urls.messageManagement }),
18
+ body: createQueueProducer({ queueUrl: urls.body }),
19
+ });
20
+ export const buildSharedDeps = (queues) => ({
21
+ storage: createStorageService(),
22
+ secrets: createSecretsService(createCachedDataKeyProvider(createKmsDataKeyProvider(process.env.KMS_KEY_ID ?? FAKE_KMS_KEY_ID))),
23
+ queues,
24
+ });