@bobfrankston/mailx-store 0.1.35 → 0.1.37

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/db.d.ts CHANGED
@@ -371,6 +371,27 @@ export declare class MailxDB {
371
371
  * here but NOT on the server gets its membership dropped (which
372
372
  * may then GC the messages row if it has no other folders). */
373
373
  getUidsForFolder(_accountId: string, folderId: number): number[];
374
+ /** List recent rows in a folder for a Sent-sweep / reconciliation pass.
375
+ * Returns only the columns the sweeper needs (uid, message_id, date,
376
+ * subject, size, has_attachments, preview, body_path) for every row in
377
+ * the given folder cached after `sinceMs`. Empty-message-id rows are
378
+ * excluded because the sweep keys on Message-ID. */
379
+ getRecentMessagesByCachedAt(accountId: string, folderId: number, sinceMs: number): {
380
+ uid: number;
381
+ message_id: string;
382
+ date: number;
383
+ subject: string;
384
+ size: number;
385
+ has_attachments: number;
386
+ preview: string;
387
+ body_path: string;
388
+ }[];
389
+ /** Rebind a local row to a different server UID without re-upserting.
390
+ * Used by the Sent-sweep to repair optimistic-insert mispredictions
391
+ * (local row was inserted at the predicted UIDNEXT but the server
392
+ * appended at a different real UID). Idempotent: if no row matches
393
+ * (already rebound by an earlier sync), it's a no-op. */
394
+ updateMessageUid(accountId: string, folderId: number, oldUid: number, newUid: number): void;
374
395
  /** Delete a message by account + UID. Reason is propagated into the
375
396
  * audit_log so the DB carries an authoritative trail of every removal. */
376
397
  deleteMessage(accountId: string, uid: number, reason?: string, source?: string): void;
package/db.js CHANGED
@@ -1977,6 +1977,41 @@ export class MailxDB {
1977
1977
  const rows = this.db.prepare("SELECT uid FROM message_folders WHERE folder_id = ?").all(folderId);
1978
1978
  return rows.map(r => r.uid);
1979
1979
  }
1980
+ /** List recent rows in a folder for a Sent-sweep / reconciliation pass.
1981
+ * Returns only the columns the sweeper needs (uid, message_id, date,
1982
+ * subject, size, has_attachments, preview, body_path) for every row in
1983
+ * the given folder cached after `sinceMs`. Empty-message-id rows are
1984
+ * excluded because the sweep keys on Message-ID. */
1985
+ getRecentMessagesByCachedAt(accountId, folderId, sinceMs) {
1986
+ return this.db.prepare(`SELECT uid, message_id, date, subject, size, has_attachments, preview, body_path
1987
+ FROM messages
1988
+ WHERE account_id = ? AND folder_id = ? AND cached_at >= ?
1989
+ AND message_id IS NOT NULL AND message_id <> ''`).all(accountId, folderId, sinceMs);
1990
+ }
1991
+ /** Rebind a local row to a different server UID without re-upserting.
1992
+ * Used by the Sent-sweep to repair optimistic-insert mispredictions
1993
+ * (local row was inserted at the predicted UIDNEXT but the server
1994
+ * appended at a different real UID). Idempotent: if no row matches
1995
+ * (already rebound by an earlier sync), it's a no-op. */
1996
+ updateMessageUid(accountId, folderId, oldUid, newUid) {
1997
+ if (oldUid === newUid)
1998
+ return;
1999
+ try {
2000
+ this.db.prepare(`UPDATE messages SET uid = ?, cached_at = ?
2001
+ WHERE account_id = ? AND folder_id = ? AND uid = ?`).run(newUid, Date.now(), accountId, folderId, oldUid);
2002
+ }
2003
+ catch (e) {
2004
+ // UNIQUE constraint can fire when both old and new UIDs already
2005
+ // exist in the row set (newer sync re-fetched the real UID).
2006
+ // Drop the stale predicted row in that case.
2007
+ if (/UNIQUE/i.test(e?.message || "")) {
2008
+ this.db.prepare(`DELETE FROM messages WHERE account_id = ? AND folder_id = ? AND uid = ?`).run(accountId, folderId, oldUid);
2009
+ }
2010
+ else {
2011
+ throw e;
2012
+ }
2013
+ }
2014
+ }
1980
2015
  /** Delete a message by account + UID. Reason is propagated into the
1981
2016
  * audit_log so the DB carries an authoritative trail of every removal. */
1982
2017
  deleteMessage(accountId, uid, reason, source) {
package/file-store.d.ts CHANGED
@@ -26,7 +26,16 @@ export declare class FileMessageStore implements MessageStore {
26
26
  private resolveStored;
27
27
  /** Write a new body. Returns a path RELATIVE to basePath; caller stores
28
28
  * it in `body_path`. The (folderId, uid) args are kept for interface
29
- * compatibility; they do NOT affect the filename. */
29
+ * compatibility; they do NOT affect the filename.
30
+ *
31
+ * Defensive content check: if the FIRST line of the would-be .eml
32
+ * matches an IMAP client-command pattern (`<tag> <UPPERCASE_CMD> ...`),
33
+ * the upstream IMAP parser desynced and wrote one of mailx's own
34
+ * outbound commands into the response stream — see the
35
+ * a39a84e1853441bcac09e1b3e1463e8d.eml corruption (2026-05-23). Refuse
36
+ * the write rather than persist garbage that the message-viewer will
37
+ * later render as broken. The caller's exception path treats this the
38
+ * same as any other transient fetch error; the reconciler re-enqueues. */
30
39
  putMessage(accountId: string, _folderId: number, _uid: number, raw: Buffer): Promise<string>;
31
40
  /** Resolve a stored body_path (relative or absolute) to an absolute
32
41
  * filesystem path. Returns "" if the input doesn't resolve to a file
package/file-store.js CHANGED
@@ -43,8 +43,33 @@ export class FileMessageStore {
43
43
  }
44
44
  /** Write a new body. Returns a path RELATIVE to basePath; caller stores
45
45
  * it in `body_path`. The (folderId, uid) args are kept for interface
46
- * compatibility; they do NOT affect the filename. */
46
+ * compatibility; they do NOT affect the filename.
47
+ *
48
+ * Defensive content check: if the FIRST line of the would-be .eml
49
+ * matches an IMAP client-command pattern (`<tag> <UPPERCASE_CMD> ...`),
50
+ * the upstream IMAP parser desynced and wrote one of mailx's own
51
+ * outbound commands into the response stream — see the
52
+ * a39a84e1853441bcac09e1b3e1463e8d.eml corruption (2026-05-23). Refuse
53
+ * the write rather than persist garbage that the message-viewer will
54
+ * later render as broken. The caller's exception path treats this the
55
+ * same as any other transient fetch error; the reconciler re-enqueues. */
47
56
  async putMessage(accountId, _folderId, _uid, raw) {
57
+ if (raw.length >= 6) {
58
+ // Look at the first ≤512 bytes to spot a leaked IMAP command.
59
+ // Pattern: optional CRLFs, then `<tag> <CMD> ...` where tag
60
+ // starts with a letter+digits (iflow tags are like `A123`,
61
+ // `B47`) and CMD is all-caps with at least 4 chars.
62
+ const sniff = raw.subarray(0, Math.min(512, raw.length)).toString("ascii");
63
+ const firstNonBlank = sniff.replace(/^\s+/, "");
64
+ // Strict: tag is letter + digits, then a space, then an
65
+ // all-caps IMAP command keyword. Real RFC822 headers can't
66
+ // match because they require a `Name: value` shape (colon),
67
+ // and `Return-Path:`, `Received:`, `Subject:` etc. are
68
+ // capitalized but include a colon and mixed case in tokens.
69
+ if (/^[A-Z]+\d+ (UID )?(FETCH|SEARCH|STORE|COPY|MOVE|EXPUNGE|SELECT|EXAMINE|APPEND|LIST|LSUB|STATUS|NOOP|IDLE|DONE|LOGIN|LOGOUT|CAPABILITY|AUTHENTICATE)\b/.test(firstNonBlank)) {
70
+ throw new Error(`putMessage: refusing to write corrupt body — IMAP command leaked into response stream (first line: ${firstNonBlank.split(/\r?\n/)[0].substring(0, 100)})`);
71
+ }
72
+ }
48
73
  const rel = this.newRelativePath(accountId);
49
74
  const abs = path.join(this.basePath, rel);
50
75
  fs.mkdirSync(path.dirname(abs), { recursive: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bobfrankston/mailx-store",
3
- "version": "0.1.35",
3
+ "version": "0.1.37",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",