@remit/mailbox-service 0.0.21 → 0.0.23

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remit/mailbox-service",
3
- "version": "0.0.21",
3
+ "version": "0.0.23",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -20,7 +20,7 @@
20
20
  },
21
21
  "scripts": {
22
22
  "test:typecheck": "tsgo --noEmit",
23
- "test:run": "node --env-file=../../localhost-test-unit.env --import tsx --experimental-test-coverage --test-coverage-include='src/**' --test-coverage-exclude='src/**/*.test.ts' --test-coverage-exclude='src/**/*.test.tsx' --test-coverage-lines=75 --test 'src/**/*.test.ts'",
23
+ "test:run": "node --env-file=../../localhost-test-unit.env --import tsx --experimental-test-coverage --test-coverage-include='src/**' --test-coverage-exclude='src/**/*.test.ts' --test-coverage-exclude='src/**/*.test.tsx' --test-coverage-lines=86 --test 'src/**/*.test.ts'",
24
24
  "test:integ": "RUN_INTEG_TESTS=1 node --env-file=../../localhost-test-unit.env --import tsx --test 'src/**/*.integ.test.ts'",
25
25
  "test:e2e": "RUN_E2E_TESTS=1 node --env-file=../../localhost-test-e2e.env --import tsx --test --test-concurrency=1 'src/**/*.e2e.test.ts'",
26
26
  "test": "npm run test:typecheck && npm run test:run"
@@ -0,0 +1,231 @@
1
+ /**
2
+ * The read path (describeMessage / getRawMessage → fetchAndGetBody) and the
3
+ * imap-worker sync path share BodySyncService.applyPostStoreSteps, so a body
4
+ * materialized by a read must run the account's standing filters — the same
5
+ * move and marker the sync path writes. The backend wires `filterConfig` into
6
+ * its BodySyncService for exactly this (create-remit-client.ts); without it a
7
+ * message opened before background body-sync is classified but never
8
+ * filter-moved (issue #223).
9
+ *
10
+ * These drive fetchAndGetBody with a matching literal filter and assert the
11
+ * move and the `filterMove` marker — and that the marker is written only for a
12
+ * real relocation: a message already sitting in the filter's destination
13
+ * matches by content but was not moved by Remit, so it must get no marker (and
14
+ * no spurious "Moved by Remit" badge with a no-op Undo).
15
+ */
16
+
17
+ import assert from "node:assert/strict";
18
+ import { describe, it } from "node:test";
19
+ import type {
20
+ FilterItem,
21
+ IAddressRepository,
22
+ IEnvelopeRepository,
23
+ IFilterAnchorRepository,
24
+ IFilterRepository,
25
+ IMessageLabelRepository,
26
+ IMessageRepository,
27
+ IThreadMessageRepository,
28
+ MessageItem,
29
+ UpdateMessageInput,
30
+ } from "@remit/data-ports";
31
+ import {
32
+ FilterClauseField,
33
+ FilterMatchOperator,
34
+ FilterState,
35
+ } from "@remit/domain-enums";
36
+ import type { StorageService } from "@remit/storage-service";
37
+ import { BodySyncService } from "./body-sync.js";
38
+ import { NO_ACTION } from "./filters/match.js";
39
+ import type { FilterConfig } from "./filters/pipeline.js";
40
+ import type { PlacementMoveService } from "./placement-move.js";
41
+ import type { IImapConnection } from "./types.js";
42
+
43
+ const INVITATION_EML = Buffer.from(
44
+ [
45
+ "From: Someone <someone@example.com>",
46
+ "To: me@example.com",
47
+ "Subject: You have a new invitation to Travel",
48
+ "Content-Type: text/plain",
49
+ "",
50
+ "details",
51
+ ].join("\r\n"),
52
+ );
53
+
54
+ interface MoveCall {
55
+ messageId: string;
56
+ destinationMailboxId: string;
57
+ }
58
+
59
+ interface Harness {
60
+ service: BodySyncService;
61
+ messageUpdates: Array<{ messageId: string; input: UpdateMessageInput }>;
62
+ moves: MoveCall[];
63
+ }
64
+
65
+ /** A standing literal filter that moves subjects containing "invitation" to `destinationMailboxId`. */
66
+ const buildFilter = (destinationMailboxId: string): FilterItem =>
67
+ ({
68
+ filterId: "flt-1",
69
+ accountConfigId: "cfg-1",
70
+ name: "Invitations",
71
+ scope: "Standing",
72
+ state: FilterState.Active,
73
+ hasAnchor: false,
74
+ ruleChangedAt: 1,
75
+ matchOperator: FilterMatchOperator.And,
76
+ literalClauses: [{ field: FilterClauseField.Subject, value: "invitation" }],
77
+ actionLabelId: NO_ACTION,
78
+ actionMailboxId: destinationMailboxId,
79
+ createdAt: 1,
80
+ updatedAt: 1,
81
+ }) as unknown as FilterItem;
82
+
83
+ const buildHarness = (
84
+ message: Pick<MessageItem, "messageId" | "mailboxId">,
85
+ filter: FilterItem,
86
+ ): Harness => {
87
+ const messageUpdates: Array<{
88
+ messageId: string;
89
+ input: UpdateMessageInput;
90
+ }> = [];
91
+ const moves: MoveCall[] = [];
92
+
93
+ const messageService = {
94
+ get: async (messageId: string) => ({
95
+ messageId,
96
+ mailboxId: message.mailboxId,
97
+ uid: 1,
98
+ }),
99
+ update: async (messageId: string, input: UpdateMessageInput) => {
100
+ messageUpdates.push({ messageId, input });
101
+ },
102
+ } as unknown as IMessageRepository;
103
+
104
+ const threadMessageService = {
105
+ getByMessageId: async () => ({
106
+ threadMessageId: "tm-1",
107
+ sentDate: 1,
108
+ mailboxId: message.mailboxId,
109
+ isRead: false,
110
+ isDeleted: false,
111
+ hasStars: false,
112
+ hasAttachment: false,
113
+ }),
114
+ update: async () => {},
115
+ } as unknown as IThreadMessageRepository;
116
+
117
+ const storageService = {
118
+ storeMessageBody: async () => ({ uri: "s3://bodies/m-1" }),
119
+ storeParsedBody: async () => {},
120
+ listBodyParts: async () => [],
121
+ } as unknown as StorageService;
122
+
123
+ const addressService = {
124
+ incrementInboundCount: async () => {},
125
+ } as unknown as IAddressRepository;
126
+
127
+ const envelopeService = {
128
+ listBodyParts: async () => [],
129
+ } as unknown as IEnvelopeRepository;
130
+
131
+ const placementMoveService = {
132
+ moveMessage: async (
133
+ _accountConfigId: string,
134
+ messageId: string,
135
+ destinationMailboxId: string,
136
+ ) => {
137
+ moves.push({ messageId, destinationMailboxId });
138
+ },
139
+ } as unknown as PlacementMoveService;
140
+
141
+ const filterConfig: FilterConfig = {
142
+ filterService: {
143
+ listByAccountAndState: async () => [filter],
144
+ refreshExpiry: async (f: FilterItem) => f,
145
+ } as unknown as IFilterRepository,
146
+ filterAnchorService: {
147
+ get: async () => undefined,
148
+ } as unknown as IFilterAnchorRepository,
149
+ messageLabelService: {
150
+ apply: async () => {},
151
+ } as unknown as IMessageLabelRepository,
152
+ placementMoveService,
153
+ };
154
+
155
+ const service = new BodySyncService(
156
+ messageService,
157
+ storageService,
158
+ threadMessageService,
159
+ addressService,
160
+ envelopeService,
161
+ { info: () => {} },
162
+ undefined,
163
+ filterConfig,
164
+ );
165
+
166
+ return { service, messageUpdates, moves };
167
+ };
168
+
169
+ const readBody = async (service: BodySyncService, mailboxPath = "INBOX") => {
170
+ const connection = {
171
+ openBox: async () => {},
172
+ fetchMessageBody: async () => INVITATION_EML,
173
+ } as unknown as IImapConnection;
174
+ return service.fetchAndGetBody(
175
+ "m-1",
176
+ "acc-1",
177
+ "cfg-1",
178
+ mailboxPath,
179
+ async () => connection,
180
+ );
181
+ };
182
+
183
+ describe("body-sync read-path standing filter", () => {
184
+ it("runs the standing filter on a read-path body backfill and records the move + marker", async () => {
185
+ const harness = buildHarness(
186
+ { messageId: "m-1", mailboxId: "mb-inbox" },
187
+ buildFilter("mb-travel"),
188
+ );
189
+
190
+ await readBody(harness.service);
191
+
192
+ // (a) the move fired to the filter's destination
193
+ assert.deepEqual(harness.moves, [
194
+ { messageId: "m-1", destinationMailboxId: "mb-travel" },
195
+ ]);
196
+
197
+ // (b) the emitted update carries the marker with the correct source/dest
198
+ assert.equal(harness.messageUpdates.length, 1);
199
+ const { input } = harness.messageUpdates[0];
200
+ assert.equal(input.movedByRemit, true);
201
+ assert.deepEqual(
202
+ {
203
+ filterId: input.filterMove?.filterId,
204
+ sourceMailboxId: input.filterMove?.sourceMailboxId,
205
+ destinationMailboxId: input.filterMove?.destinationMailboxId,
206
+ },
207
+ {
208
+ filterId: "flt-1",
209
+ sourceMailboxId: "mb-inbox",
210
+ destinationMailboxId: "mb-travel",
211
+ },
212
+ );
213
+ });
214
+
215
+ it("writes no marker when the message already sits in the filter's destination", async () => {
216
+ // Matches the filter by content, but is already in the destination (a
217
+ // server-side rule delivered it there, or the user filed it). Remit moved
218
+ // nothing — no marker, no movedByRemit, so no badge and no no-op Undo.
219
+ const harness = buildHarness(
220
+ { messageId: "m-1", mailboxId: "mb-travel" },
221
+ buildFilter("mb-travel"),
222
+ );
223
+
224
+ await readBody(harness.service);
225
+
226
+ assert.equal(harness.messageUpdates.length, 1);
227
+ const { input } = harness.messageUpdates[0];
228
+ assert.equal(input.filterMove, undefined);
229
+ assert.equal(input.movedByRemit, undefined);
230
+ });
231
+ });
package/src/body-sync.ts CHANGED
@@ -58,6 +58,8 @@ type MessagePlacementVerdict = NonNullable<
58
58
  UpdateMessageInput["placementVerdict"]
59
59
  >;
60
60
 
61
+ type MessageFilterMove = NonNullable<UpdateMessageInput["filterMove"]>;
62
+
61
63
  type ThreadMessageCategory = ThreadMessageItem["category"];
62
64
 
63
65
  /**
@@ -709,13 +711,38 @@ export class BodySyncService {
709
711
  // classifier's placement move (RFC 034 Decision 3.1) — an explicit user
710
712
  // rule wins the single mailbox a message occupies — so at most one move is
711
713
  // enqueued. A non-confident/leave verdict with no filter move is a no-op.
714
+ let filterMove: MessageFilterMove | undefined;
715
+ let filterMoved = false;
712
716
  if (filterDecision.move) {
717
+ const destinationMailboxId = filterDecision.move.destinationMailboxId;
718
+ // Capture the source mailbox BEFORE the move rewrites mailboxId, so the
719
+ // auto-moved badge can name where the filter took the message from and
720
+ // offer an undo back to it (issue #223). Snapshotted into the marker
721
+ // rather than read from `originalMailboxId` at derive time, which a
722
+ // later user move would overwrite — the filter's source must survive an
723
+ // undo to stay derivable.
724
+ const sourceMailboxId = (await this.messageService.get(messageId))
725
+ .mailboxId;
713
726
  await this.filterConfig?.placementMoveService.moveMessage(
714
727
  accountConfigId,
715
728
  messageId,
716
- filterDecision.move.destinationMailboxId,
729
+ destinationMailboxId,
717
730
  accountId,
718
731
  );
732
+ // A filter matches by content, not location: a message delivered
733
+ // straight into the destination (a server-side rule) or already filed
734
+ // there matches but was not moved by Remit. `moveMessage` no-ops in that
735
+ // case; record neither the marker nor `movedByRemit`, so the badge never
736
+ // claims a move that did not happen and its Undo is never a no-op.
737
+ if (sourceMailboxId !== destinationMailboxId) {
738
+ filterMoved = true;
739
+ filterMove = {
740
+ filterId: filterDecision.move.filterId,
741
+ sourceMailboxId,
742
+ destinationMailboxId,
743
+ decidedAt: Date.now(),
744
+ };
745
+ }
719
746
  } else if (resolved.move) {
720
747
  await this.placementConfig?.placementMoveService.moveMessage(
721
748
  accountConfigId,
@@ -738,7 +765,7 @@ export class BodySyncService {
738
765
  });
739
766
  }
740
767
 
741
- const moved = Boolean(resolved.move || filterDecision.move);
768
+ const moved = Boolean(resolved.move || filterMoved);
742
769
 
743
770
  // ONE Message UpdateItem per synced message: bodyStorageKey + every
744
771
  // classification/derived field + the move flag + the audit verdict. Each
@@ -753,6 +780,7 @@ export class BodySyncService {
753
780
  ...classification,
754
781
  ...(moved ? { movedByRemit: true } : {}),
755
782
  ...(resolved.verdict ? { placementVerdict: resolved.verdict } : {}),
783
+ ...(filterMove ? { filterMove } : {}),
756
784
  };
757
785
  await this.messageService.update(messageId, update);
758
786
  this.log.info({ messageId, storageKey: bodyRef.uri }, "Body stored");