advisers 0.2.0-preview.71 → 0.2.0

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/lib/imap.js CHANGED
@@ -8,12 +8,19 @@
8
8
  * The client is intentionally tiny: no OAuth flow, no Gmail API, no cloud SDK.
9
9
  * Credentials come from the caller (env in the CLI), are never written to disk
10
10
  * and never logged.
11
+ *
12
+ * Robustness (2026-11-17 audit P1-9): one managed inactivity timer instead of a
13
+ * new socket.setTimeout listener per read, a total request deadline, a literal
14
+ * size cap, and the real server UID (parsed from the FETCH UID attribute)
15
+ * instead of the message sequence number.
11
16
  */
12
17
  import net from 'node:net'
13
18
  import tls from 'node:tls'
14
19
 
15
20
  const CRLF = '\r\n'
16
21
  const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
22
+ const DEFAULT_TIMEOUT_MS = 30_000
23
+ const MAX_LITERAL_BYTES = 25 * 1024 * 1024
17
24
 
18
25
  export function imapQuote(value) {
19
26
  return '"' + String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"'
@@ -24,19 +31,42 @@ export function imapSinceDate(days = 30, now = new Date()) {
24
31
  return `${String(d.getUTCDate()).padStart(2, '0')}-${MONTHS[d.getUTCMonth()]}-${d.getUTCFullYear()}`
25
32
  }
26
33
 
27
- function createReader(socket) {
34
+ function createReader(socket, { idleTimeoutMs = DEFAULT_TIMEOUT_MS, deadline = Number.POSITIVE_INFINITY, totalTimeoutMs = DEFAULT_TIMEOUT_MS, maxLiteralBytes = MAX_LITERAL_BYTES } = {}) {
28
35
  let buffer = Buffer.alloc(0)
29
36
  let ended = false
30
37
  let error
31
38
  let wake = null
32
- socket.on('data', (chunk) => { buffer = Buffer.concat([buffer, chunk]); if (wake) { const w = wake; wake = null; w() } })
33
- socket.on('end', () => { ended = true; if (wake) { const w = wake; wake = null; w() } })
34
- socket.on('error', (e) => { error = e; if (wake) { const w = wake; wake = null; w() } })
39
+ let timer = null
40
+
41
+ const clearTimer = () => {
42
+ if (timer) { clearTimeout(timer); timer = null }
43
+ }
44
+ const wakeUp = () => {
45
+ clearTimer()
46
+ if (wake) { const w = wake; wake = null; w() }
47
+ }
48
+ socket.on('data', (chunk) => { buffer = Buffer.concat([buffer, chunk]); wakeUp() })
49
+ socket.on('end', () => { ended = true; wakeUp() })
50
+ socket.on('error', (e) => { error = e; wakeUp() })
51
+
35
52
  const waitData = () => new Promise((resolve) => {
36
53
  if (buffer.length || ended || error) return resolve()
54
+ const remaining = deadline - Date.now()
55
+ if (remaining <= 0) {
56
+ error = new Error(`IMAP request timed out after ${totalTimeoutMs}ms`)
57
+ return resolve()
58
+ }
37
59
  wake = resolve
38
- socket.setTimeout?.(30_000, () => { error = new Error('IMAP socket timeout'); wake?.(); wake = null })
60
+ const waitMs = Math.max(1, Math.min(idleTimeoutMs, remaining))
61
+ timer = setTimeout(() => {
62
+ timer = null
63
+ error = remaining <= idleTimeoutMs
64
+ ? new Error(`IMAP request timed out after ${totalTimeoutMs}ms`)
65
+ : new Error(`IMAP connection idle for more than ${idleTimeoutMs}ms`)
66
+ wakeUp()
67
+ }, waitMs)
39
68
  })
69
+
40
70
  async function readLine() {
41
71
  for (;;) {
42
72
  const idx = buffer.indexOf('\r\n')
@@ -47,6 +77,7 @@ function createReader(socket) {
47
77
  }
48
78
  }
49
79
  async function readBytes(n) {
80
+ if (n > maxLiteralBytes) throw new Error(`IMAP literal is larger than the ${maxLiteralBytes}-byte limit`)
50
81
  while (buffer.length < n) {
51
82
  if (error) throw error
52
83
  if (ended) throw new Error('IMAP connection ended inside a literal')
@@ -62,29 +93,55 @@ function createReader(socket) {
62
93
  if (line.startsWith(tag + ' ')) return { untagged, literals, status: line }
63
94
  const m = /\{(\d+)\}$/.exec(line)
64
95
  untagged.push(line)
65
- if (m) literals.push(await readBytes(Number(m[1])))
96
+ if (m) {
97
+ const size = Number(m[1])
98
+ if (size > maxLiteralBytes) throw new Error(`IMAP literal is larger than the ${maxLiteralBytes}-byte limit`)
99
+ literals.push(await readBytes(size))
100
+ }
66
101
  }
67
102
  }
68
- return { readLine, response }
103
+ return { readLine, response, clearTimer }
69
104
  }
70
105
 
71
106
  export async function fetchImapMessages({
72
107
  host, port = 993, secure = true, user, pass, mailbox = 'INBOX', sinceDays = 30, limit = 20,
73
- rejectUnauthorized = true, connect, timeoutMs = 30_000,
108
+ rejectUnauthorized = true, connect, timeoutMs = DEFAULT_TIMEOUT_MS, idleTimeoutMs = DEFAULT_TIMEOUT_MS,
109
+ maxLiteralBytes = MAX_LITERAL_BYTES,
74
110
  } = {}) {
75
111
  if (!host || !user || !pass) throw new Error('IMAP host/user/password are required')
76
- if (typeof fetch !== 'undefined' && !globalThis.__advisersImapTestHook && connect === undefined) {
77
- // No network in tests unless a connector is injected; real calls use TLS below.
78
- }
79
112
  const socket = await new Promise((resolve, reject) => {
80
- const onError = (e) => reject(e)
81
- const s = connect ? connect({ host, port, secure }) : secure ? tls.connect({ host, port, rejectUnauthorized }) : net.connect({ host, port })
82
- if (typeof s.then === 'function') { s.then((x) => resolve(x), reject); return }
113
+ let settled = false
114
+ const timer = setTimeout(() => {
115
+ if (settled) return
116
+ settled = true
117
+ try { s?.destroy?.() } catch {}
118
+ reject(new Error(`IMAP connect timed out after ${timeoutMs}ms`))
119
+ }, timeoutMs)
120
+ const finish = (fn, value) => {
121
+ if (settled) return
122
+ settled = true
123
+ clearTimeout(timer)
124
+ fn(value)
125
+ }
126
+ const onError = (e) => finish(reject, e)
127
+ let s
128
+ try {
129
+ s = connect ? connect({ host, port, secure }) : secure ? tls.connect({ host, port, rejectUnauthorized }) : net.connect({ host, port })
130
+ } catch (error) {
131
+ finish(reject, error)
132
+ return
133
+ }
134
+ if (typeof s.then === 'function') {
135
+ s.then((x) => finish(resolve, x), (e) => finish(reject, e))
136
+ return
137
+ }
83
138
  s.once('error', onError)
84
- s.once(secure ? 'secureConnect' : 'connect', () => { s.off('error', onError); resolve(s) })
139
+ s.once(secure ? 'secureConnect' : 'connect', () => {
140
+ s.off?.('error', onError)
141
+ finish(resolve, s)
142
+ })
85
143
  })
86
- socket.setTimeout?.(timeoutMs)
87
- const reader = createReader(socket)
144
+ const reader = createReader(socket, { idleTimeoutMs, totalTimeoutMs: timeoutMs, deadline: Date.now() + timeoutMs, maxLiteralBytes })
88
145
  let tagNo = 0
89
146
  const tag = () => 'A' + (++tagNo)
90
147
  const command = async (text) => {
@@ -105,18 +162,19 @@ export async function fetchImapMessages({
105
162
  const searchLine = search.untagged.find((l) => /^\* SEARCH/i.test(l)) ?? ''
106
163
  const uids = searchLine.split(/\s+/).slice(2).filter((x) => /^\d+$/.test(x)).map(Number)
107
164
  const wanted = uids.slice(-Math.max(0, limit))
108
- const messages = []
165
+ let messages = []
109
166
  if (wanted.length) {
110
- const fetched = await command(`UID FETCH ${wanted.join(',')} (BODY.PEEK[])`)
111
- for (const literal of fetched.literals) messages.push({ uid: null, raw: literal })
112
- const uidMatches = fetched.untagged.filter((l) => /^\* \d+ FETCH/i.test(l))
113
- for (let i = 0; i < uidMatches.length && i < messages.length; i++) {
114
- const m = /^\* (\d+) FETCH/i.exec(uidMatches[i]); if (m) messages[i].uid = Number(m[1])
115
- }
167
+ const fetched = await command(`UID FETCH ${wanted.join(',')} (UID BODY.PEEK[])`)
168
+ const fetchLines = fetched.untagged.filter((l) => /^\* \d+ FETCH/i.test(l))
169
+ messages = fetched.literals.map((raw, index) => {
170
+ const uidMatch = /\bUID (\d+)\b/i.exec(fetchLines[index] ?? '')
171
+ return { uid: uidMatch ? Number(uidMatch[1]) : null, raw }
172
+ })
116
173
  }
117
174
  await command('LOGOUT').catch(() => {})
118
175
  return messages
119
176
  } finally {
177
+ reader.clearTimer()
120
178
  try { socket.end() } catch {}
121
179
  try { socket.destroy?.() } catch {}
122
180
  }