@remit/mailbox-service 0.0.49 → 0.0.51

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.49",
3
+ "version": "0.0.51",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
package/src/index.ts CHANGED
@@ -197,6 +197,24 @@ export {
197
197
  type SyncedMessage,
198
198
  type SyncMessagesResult,
199
199
  } from "./message-sync.js";
200
+ export {
201
+ type CompleteOutboxAttachmentInput,
202
+ type CompleteOutboxAttachmentOutcome,
203
+ type MintOutboxAttachmentInput,
204
+ type MintOutboxAttachmentOutcome,
205
+ OUTBOX_ATTACHMENT_MAX_COUNT,
206
+ OUTBOX_ATTACHMENT_MAX_TOTAL_BYTES,
207
+ type OutboxAttachmentConfig,
208
+ type OutboxAttachmentRejectionDetail,
209
+ type OutboxAttachmentRejectionReasonValue,
210
+ type OutboxAttachmentReservation,
211
+ OutboxAttachmentService,
212
+ } from "./outbox-attachment.js";
213
+ export {
214
+ FALLBACK_CONTENT_TYPE,
215
+ normalizeAttachmentContentType,
216
+ sanitizeAttachmentFilename,
217
+ } from "./outbox-attachment-filename.js";
200
218
  export {
201
219
  type CreateDraftInput,
202
220
  type OutboxQueueConfig,
@@ -14,7 +14,11 @@ import type {
14
14
  UpdateMailboxInput,
15
15
  UpdateThreadMessageInput,
16
16
  } from "@remit/data-ports";
17
- import { MailboxCursorState, MessageSystemFlag } from "@remit/domain-enums";
17
+ import {
18
+ MailboxCursorState,
19
+ MessageKeywordFlag,
20
+ MessageSystemFlag,
21
+ } from "@remit/domain-enums";
18
22
  import type { ManagedConnectionFactory } from "./connection-factory.js";
19
23
  import type { FlagPushService } from "./flag-push.js";
20
24
  import { FlagQueueService } from "./flag-queue.js";
@@ -112,6 +116,8 @@ interface Harness {
112
116
  /** The canonical flag record after the round. */
113
117
  flagStore: Set<string>;
114
118
  messageFlagService: IMessageFlagRepository;
119
+ /** Method names invoked on the top-level address repository. */
120
+ addressCalls: string[];
115
121
  }
116
122
 
117
123
  const buildHarness = (options: HarnessOptions): Harness => {
@@ -241,12 +247,29 @@ const buildHarness = (options: HarnessOptions): Harness => {
241
247
  },
242
248
  } as unknown as IMessageFlagRepository;
243
249
 
250
+ // The existing-message path (applyChange -> applyServerFlags) never
251
+ // touches this repository. Recording every call, rather than leaving the
252
+ // stub as `{}`, is what makes "$Junk stays message state" an assertion
253
+ // instead of an assumption a future change could silently break.
254
+ const addressCalls: string[] = [];
255
+ const addressRepository = new Proxy(
256
+ {},
257
+ {
258
+ get:
259
+ (_target, prop: string) =>
260
+ (..._args: unknown[]) => {
261
+ addressCalls.push(prop);
262
+ throw new Error(`unexpected IAddressRepository.${prop} call`);
263
+ },
264
+ },
265
+ ) as IAddressRepository;
266
+
244
267
  const service = new MessageSyncService(
245
268
  connectionFactory,
246
269
  mailboxService,
247
270
  {} as IMessageRepository,
248
271
  {} as IEnvelopeRepository,
249
- {} as IAddressRepository,
272
+ addressRepository,
250
273
  threadMessageService,
251
274
  logger,
252
275
  unitOfWork,
@@ -263,6 +286,7 @@ const buildHarness = (options: HarnessOptions): Harness => {
263
286
  errors,
264
287
  flagStore,
265
288
  messageFlagService,
289
+ addressCalls,
266
290
  };
267
291
  };
268
292
 
@@ -603,6 +627,71 @@ describe("MessageSyncService CHANGEDSINCE path", () => {
603
627
  });
604
628
  });
605
629
 
630
+ // $Junk/$NotJunk mirroring (report-spam epic, message-state slice). This
631
+ // mailbox is never remit-only — Apple Mail or another IMAP client is
632
+ // routinely connected too — so a keyword another client set is message
633
+ // state only. It must never become a standing rule about the sender.
634
+ describe("MessageSyncService mirrors $Junk/$NotJunk keywords", () => {
635
+ it("mirrors a server-side $Junk into the canonical flag record", async () => {
636
+ const harness = buildHarness({
637
+ mailbox: mailbox(),
638
+ supportsCondstore: true,
639
+ changed: [serverMessage({ flags: [MessageKeywordFlag.Junk] })],
640
+ storedRows: [storedRow()],
641
+ storedFlags: [],
642
+ });
643
+
644
+ await syncOnce(harness);
645
+
646
+ assert.ok(harness.flagStore.has(MessageKeywordFlag.Junk));
647
+ });
648
+
649
+ it("mirrors a server-side $NotJunk into the canonical flag record", async () => {
650
+ const harness = buildHarness({
651
+ mailbox: mailbox(),
652
+ supportsCondstore: true,
653
+ changed: [serverMessage({ flags: [MessageKeywordFlag.NotJunk] })],
654
+ storedRows: [storedRow()],
655
+ storedFlags: [],
656
+ });
657
+
658
+ await syncOnce(harness);
659
+
660
+ assert.ok(harness.flagStore.has(MessageKeywordFlag.NotJunk));
661
+ });
662
+
663
+ it("leaves $Junk alone while its local flip is still owed to IMAP", async () => {
664
+ const harness = buildHarness({
665
+ mailbox: mailbox(),
666
+ supportsCondstore: true,
667
+ // Server has not seen the local flip yet.
668
+ changed: [serverMessage({ flags: [] })],
669
+ storedRows: [storedRow()],
670
+ storedFlags: [MessageKeywordFlag.Junk],
671
+ pendingFlags: new Set([MessageKeywordFlag.Junk]),
672
+ });
673
+
674
+ await syncOnce(harness);
675
+
676
+ assert.ok(harness.flagStore.has(MessageKeywordFlag.Junk));
677
+ });
678
+
679
+ it("mirroring $Junk leaves the sender's Address record completely untouched", async () => {
680
+ const harness = buildHarness({
681
+ mailbox: mailbox(),
682
+ supportsCondstore: true,
683
+ changed: [serverMessage({ flags: [MessageKeywordFlag.Junk] })],
684
+ storedRows: [storedRow()],
685
+ storedFlags: [],
686
+ });
687
+
688
+ await syncOnce(harness);
689
+
690
+ assert.ok(harness.flagStore.has(MessageKeywordFlag.Junk));
691
+ assert.deepEqual(harness.addressCalls, []);
692
+ });
693
+ });
694
+
606
695
  describe("MessageSyncService without CONDSTORE", () => {
607
696
  it("falls back to full enumeration and never issues CHANGEDSINCE", async () => {
608
697
  const harness = buildHarness({
@@ -23,6 +23,7 @@ import {
23
23
  import {
24
24
  AddressRole,
25
25
  MailboxCursorState,
26
+ MessageKeywordFlag,
26
27
  MessageSystemFlag,
27
28
  StarColor,
28
29
  } from "@remit/domain-enums";
@@ -1025,8 +1026,9 @@ export class MessageSyncService {
1025
1026
  }
1026
1027
 
1027
1028
  /**
1028
- * Bring a stored row's read and star state in line with the server's
1029
- * flags.
1029
+ * Bring a stored row's read and star state, and the $Junk/$NotJunk
1030
+ * keywords on the canonical MessageFlag record, in line with the
1031
+ * server's flags.
1030
1032
  *
1031
1033
  * A field with a pending outbound push is left alone: the user flipped it
1032
1034
  * locally, IMAP has not been told yet, and the server's answer is
@@ -1073,6 +1075,17 @@ export class MessageSyncService {
1073
1075
  }
1074
1076
  }
1075
1077
 
1078
+ await this.mirrorKeywordFlag(
1079
+ existing.messageId,
1080
+ MessageKeywordFlag.Junk,
1081
+ flags,
1082
+ );
1083
+ await this.mirrorKeywordFlag(
1084
+ existing.messageId,
1085
+ MessageKeywordFlag.NotJunk,
1086
+ flags,
1087
+ );
1088
+
1076
1089
  if (Object.keys(updates).length === 0) return;
1077
1090
 
1078
1091
  // MessageFlag is the canonical flag record — `FlagQueueService` reads it
@@ -1157,6 +1170,32 @@ export class MessageSyncService {
1157
1170
  return marker !== null;
1158
1171
  }
1159
1172
 
1173
+ /**
1174
+ * Mirror one RFC 5788 keyword ($Junk / $NotJunk) from the server into the
1175
+ * canonical MessageFlag record, guarded the same way as the system flags:
1176
+ * a pending local push wins over the server's known-stale answer.
1177
+ *
1178
+ * This mailbox is never remit-only — Apple Mail or another IMAP client is
1179
+ * routinely connected too — so the keyword is message state, nothing
1180
+ * more. It never reaches the Address model: reading another client's
1181
+ * keyword as a standing rule about the sender is the exact fight this
1182
+ * mirror must not pick.
1183
+ */
1184
+ private async mirrorKeywordFlag(
1185
+ messageId: string,
1186
+ flagName: string,
1187
+ serverFlags: string[],
1188
+ ): Promise<void> {
1189
+ if (!this.messageFlagService) return;
1190
+ if (await this.hasPendingPush(messageId, flagName)) return;
1191
+
1192
+ const present = serverFlags.includes(flagName);
1193
+ const hasFlag = await this.messageFlagService.hasFlag(messageId, flagName);
1194
+ if (hasFlag === present) return;
1195
+
1196
+ await this.setMessageFlag(messageId, flagName, present);
1197
+ }
1198
+
1160
1199
  /**
1161
1200
  * Fetch a batch of messages using the managed connection.
1162
1201
  * Assumes mailbox is already open from fetchUidsToSync.
@@ -0,0 +1,132 @@
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "node:test";
3
+ import {
4
+ FALLBACK_CONTENT_TYPE,
5
+ normalizeAttachmentContentType,
6
+ sanitizeAttachmentFilename,
7
+ } from "./outbox-attachment-filename.js";
8
+
9
+ describe("sanitizeAttachmentFilename", () => {
10
+ it("keeps an ordinary name, accents and spaces included", () => {
11
+ assert.equal(
12
+ sanitizeAttachmentFilename("Facture décembre 2026.pdf"),
13
+ "Facture décembre 2026.pdf",
14
+ );
15
+ });
16
+
17
+ it("keeps only the basename of a traversal attempt", () => {
18
+ assert.equal(sanitizeAttachmentFilename("../../../etc/passwd"), "passwd");
19
+ });
20
+
21
+ it("keeps only the basename of a windows path", () => {
22
+ assert.equal(
23
+ sanitizeAttachmentFilename("C:\\Users\\me\\Desktop\\report.xlsx"),
24
+ "report.xlsx",
25
+ );
26
+ });
27
+
28
+ it("strips the bidi override that disguises an extension", () => {
29
+ assert.equal(
30
+ sanitizeAttachmentFilename("invoice\u202Egnp.exe"),
31
+ "invoicegnp.exe",
32
+ );
33
+ });
34
+
35
+ it("strips control characters that would break a header", () => {
36
+ assert.equal(
37
+ sanitizeAttachmentFilename("report\r\nBcc: someone@example.com.pdf"),
38
+ "reportBcc: someone@example.com.pdf",
39
+ );
40
+ });
41
+
42
+ it("refuses a name that is nothing but separators and dots", () => {
43
+ assert.equal(sanitizeAttachmentFilename("../.."), null);
44
+ assert.equal(sanitizeAttachmentFilename("."), null);
45
+ assert.equal(sanitizeAttachmentFilename(" "), null);
46
+ assert.equal(sanitizeAttachmentFilename("\u202A\u202B"), null);
47
+ });
48
+
49
+ it("truncates an overlong name but keeps its extension", () => {
50
+ const sanitized = sanitizeAttachmentFilename(`${"a".repeat(500)}.pdf`);
51
+ assert.ok(sanitized !== null);
52
+ assert.ok(sanitized.length <= 200);
53
+ assert.ok(sanitized.endsWith(".pdf"));
54
+ });
55
+
56
+ it("never cuts an emoji in half when it truncates", () => {
57
+ const sanitized = sanitizeAttachmentFilename(
58
+ `${"a".repeat(195)}\u{1F600}x.pdf`,
59
+ );
60
+ assert.ok(sanitized !== null);
61
+ assert.equal(
62
+ [...sanitized].some((character) => {
63
+ const code = character.charCodeAt(0);
64
+ return code >= 0xd800 && code <= 0xdfff && character.length === 1;
65
+ }),
66
+ false,
67
+ );
68
+ assert.equal(Buffer.from(sanitized, "utf8").includes("\uFFFD"), false);
69
+ assert.ok(sanitized.endsWith(".pdf"));
70
+ });
71
+
72
+ it("truncates a name whose trailing dot-segment is not a plausible extension", () => {
73
+ const sanitized = sanitizeAttachmentFilename(
74
+ `${"a".repeat(300)}.${"b".repeat(300)}`,
75
+ );
76
+ assert.ok(sanitized !== null);
77
+ assert.equal(sanitized.length, 200);
78
+ });
79
+ });
80
+
81
+ describe("normalizeAttachmentContentType", () => {
82
+ it("lowercases a media type and drops its parameters", () => {
83
+ assert.equal(
84
+ normalizeAttachmentContentType("TEXT/Plain; charset=utf-8"),
85
+ "text/plain",
86
+ );
87
+ });
88
+
89
+ it("passes an archive through — the receiving server decides what it takes", () => {
90
+ assert.equal(
91
+ normalizeAttachmentContentType("application/zip"),
92
+ "application/zip",
93
+ );
94
+ });
95
+
96
+ it("falls back when the browser sent nothing", () => {
97
+ assert.equal(normalizeAttachmentContentType(""), FALLBACK_CONTENT_TYPE);
98
+ });
99
+
100
+ it("falls back on a token long enough to overflow the field it lands in", () => {
101
+ assert.equal(
102
+ normalizeAttachmentContentType(`application/${"x".repeat(300)}`),
103
+ FALLBACK_CONTENT_TYPE,
104
+ );
105
+ });
106
+
107
+ it("falls back on a value that is not a media type", () => {
108
+ assert.equal(
109
+ normalizeAttachmentContentType("text/html<script>"),
110
+ FALLBACK_CONTENT_TYPE,
111
+ );
112
+ assert.equal(
113
+ normalizeAttachmentContentType("not-a-media-type"),
114
+ FALLBACK_CONTENT_TYPE,
115
+ );
116
+ });
117
+ });
118
+
119
+ describe("a filename that hides its separators behind control characters", () => {
120
+ it("takes the basename after the newline, not before it", () => {
121
+ // `.` does not match a newline, so a basename strip that runs first stops
122
+ // at it and leaves every separator that follows.
123
+ assert.equal(
124
+ sanitizeAttachmentFilename("report\r\n/../../.bashrc"),
125
+ "bashrc",
126
+ );
127
+ });
128
+
129
+ it("leaves nothing usable when the whole name is separators and a newline", () => {
130
+ assert.equal(sanitizeAttachmentFilename("..\n/../x.png"), "x.png");
131
+ });
132
+ });
@@ -0,0 +1,76 @@
1
+ /**
2
+ * A filename arrives from a browser's `File.name` and reaches a
3
+ * `Content-Disposition` header on a message a stranger opens. Nothing in the
4
+ * middle re-derives it, and the storage key never contains it — the key is a
5
+ * generated id — so this is the one place the value is made safe.
6
+ */
7
+
8
+ const PATH_SEPARATORS = /^.*[\\/]/;
9
+
10
+ // C0/C1 controls and DEL, then the bidi and directional-isolate formatting
11
+ // characters that let a name ending in "exe" render as if it ended in "png".
12
+ const UNSAFE_CHARACTERS =
13
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: stripping control characters is the point
14
+ /[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/g;
15
+
16
+ const MAX_FILENAME_LENGTH = 200;
17
+
18
+ // By code point, never by UTF-16 unit: cutting mid-surrogate leaves a lone half
19
+ // that a Content-Disposition encoder can only render as U+FFFD.
20
+ const truncateCodePoints = (value: string, limit: number): string =>
21
+ Array.from(value).slice(0, limit).join("");
22
+
23
+ const truncateKeepingExtension = (filename: string): string => {
24
+ const codePoints = Array.from(filename);
25
+ if (codePoints.length <= MAX_FILENAME_LENGTH) return filename;
26
+
27
+ const dot = filename.lastIndexOf(".");
28
+ const extension = dot > 0 ? Array.from(filename.slice(dot)) : [];
29
+ if (extension.length === 0 || extension.length > 16) {
30
+ return truncateCodePoints(filename, MAX_FILENAME_LENGTH);
31
+ }
32
+ return (
33
+ truncateCodePoints(filename, MAX_FILENAME_LENGTH - extension.length) +
34
+ extension.join("")
35
+ );
36
+ };
37
+
38
+ /**
39
+ * The filename to record, or null when nothing usable survives — a name made
40
+ * only of separators, dots or control characters is refused rather than
41
+ * replaced with something invented.
42
+ */
43
+ export const sanitizeAttachmentFilename = (raw: string): string | null => {
44
+ // Strip first, then take the basename. The other order is bypassable: `.`
45
+ // does not match a newline, so `PATH_SEPARATORS` stops at one and leaves
46
+ // every separator after it — "report\r\n/../../.bashrc" survives with its
47
+ // slashes intact.
48
+ const stripped = raw.replace(UNSAFE_CHARACTERS, "");
49
+ const basename = stripped.replace(PATH_SEPARATORS, "").trim();
50
+ const trimmed = basename.replace(/^\.+/, "").trim();
51
+
52
+ if (trimmed.length === 0) return null;
53
+
54
+ return truncateKeepingExtension(trimmed);
55
+ };
56
+
57
+ // RFC 9110 token characters, on both sides of the one slash.
58
+ const MEDIA_TYPE = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+\/[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
59
+
60
+ export const FALLBACK_CONTENT_TYPE = "application/octet-stream";
61
+
62
+ // The longest registered media type is well under this. A token run past it is
63
+ // a client inventing one, and it would overflow the response field it lands in.
64
+ const MAX_CONTENT_TYPE_LENGTH = 127;
65
+
66
+ /**
67
+ * The media type to record. Parameters (`; charset=…`) are dropped and anything
68
+ * that is not a bare type/subtype becomes the fallback: the value is recorded
69
+ * for the outgoing MIME part, never trusted for rendering.
70
+ */
71
+ export const normalizeAttachmentContentType = (raw: string): string => {
72
+ const bare = raw.split(";")[0].trim().toLowerCase();
73
+ if (bare.length > MAX_CONTENT_TYPE_LENGTH) return FALLBACK_CONTENT_TYPE;
74
+ if (!MEDIA_TYPE.test(bare)) return FALLBACK_CONTENT_TYPE;
75
+ return bare;
76
+ };