@haraka/test-fixtures 0.0.0-stage → 2.0.1
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/CHANGELOG.md +346 -0
- package/LICENSE +21 -0
- package/README.md +263 -2
- package/config/smtp.ini +64 -0
- package/index.js +41 -0
- package/lib/assertions.js +111 -0
- package/lib/connection.js +601 -0
- package/lib/dns.js +206 -0
- package/lib/helpers.js +150 -0
- package/lib/hooks.js +123 -0
- package/lib/invoke.js +55 -0
- package/lib/line_socket.js +68 -0
- package/lib/logger.js +125 -0
- package/lib/plugin.js +313 -0
- package/lib/stub.js +50 -0
- package/lib/transaction.js +270 -0
- package/package.json +72 -4
- package/types/index.d.ts +19 -0
- package/types/lib/assertions.d.ts +54 -0
- package/types/lib/connection.d.ts +150 -0
- package/types/lib/dns.d.ts +15 -0
- package/types/lib/helpers.d.ts +98 -0
- package/types/lib/hooks.d.ts +54 -0
- package/types/lib/invoke.d.ts +26 -0
- package/types/lib/line_socket.d.ts +14 -0
- package/types/lib/logger.d.ts +42 -0
- package/types/lib/plugin.d.ts +30 -0
- package/types/lib/stub.d.ts +38 -0
- package/types/lib/transaction.d.ts +72 -0
package/lib/dns.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// A tiny, zero-dependency DNS server for tests.
|
|
2
|
+
//
|
|
3
|
+
// It speaks just enough of the DNS wire protocol (RFC 1035) over UDP to
|
|
4
|
+
// answer A / AAAA / MX / TXT queries and to return real failure RCODEs,
|
|
5
|
+
// so plugin tests exercise the real node:dns -> haraka-net-utils -> plugin
|
|
6
|
+
// path with real Error objects instead of mocking the resolver.
|
|
7
|
+
//
|
|
8
|
+
// const dns = await fixtures.dns.start({
|
|
9
|
+
// 'good.example': { a: ['1.2.3.4'], mx: [{ preference: 10, exchange: 'mx.good.example' }] },
|
|
10
|
+
// 'broken.example': { rcode: 'SERVFAIL' },
|
|
11
|
+
// 'slow.example': { a: ['1.2.3.4'], delayMs: 50 },
|
|
12
|
+
// 'gone.example': { drop: true },
|
|
13
|
+
// })
|
|
14
|
+
// const resolver = dns.resolver({ timeout: 500 }) // node:dns Resolver -> test
|
|
15
|
+
// await resolver.resolveMx('good.example')
|
|
16
|
+
// await dns.close()
|
|
17
|
+
|
|
18
|
+
import dgram from 'node:dgram'
|
|
19
|
+
import { Resolver } from 'node:dns/promises'
|
|
20
|
+
import ipaddr from 'ipaddr.js'
|
|
21
|
+
|
|
22
|
+
// QTYPE / RR TYPE codes
|
|
23
|
+
export const TYPE = { A: 1, MX: 15, TXT: 16, AAAA: 28 }
|
|
24
|
+
|
|
25
|
+
// RCODEs (RFC 1035 §4.1.1 + RFC 6895)
|
|
26
|
+
export const RCODE = { NOERROR: 0, FORMERR: 1, SERVFAIL: 2, NXDOMAIN: 3, NOTIMP: 4, REFUSED: 5 }
|
|
27
|
+
|
|
28
|
+
function normalizeName(name) {
|
|
29
|
+
return String(name).toLowerCase().replace(/\.$/, '')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Decode the (single, uncompressed) question. Queries never use name
|
|
33
|
+
// compression, so a plain label loop is sufficient.
|
|
34
|
+
function parseQuestion(msg) {
|
|
35
|
+
const labels = []
|
|
36
|
+
let off = 12
|
|
37
|
+
for (;;) {
|
|
38
|
+
const len = msg[off]
|
|
39
|
+
if (len === undefined) throw new Error('truncated question')
|
|
40
|
+
if (len === 0) {
|
|
41
|
+
off += 1
|
|
42
|
+
break
|
|
43
|
+
}
|
|
44
|
+
if (len & 0xc0) throw new Error('unexpected compression in question')
|
|
45
|
+
labels.push(msg.toString('ascii', off + 1, off + 1 + len))
|
|
46
|
+
off += 1 + len
|
|
47
|
+
}
|
|
48
|
+
const qtype = msg.readUInt16BE(off)
|
|
49
|
+
const qclass = msg.readUInt16BE(off + 2)
|
|
50
|
+
return { name: labels.join('.').toLowerCase(), qtype, qclass, qEnd: off + 4 }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Encode a domain name as a sequence of length-prefixed labels (no
|
|
54
|
+
// compression). Resolvers accept uncompressed names inside RDATA.
|
|
55
|
+
function encodeName(name) {
|
|
56
|
+
const bufs = []
|
|
57
|
+
for (const label of normalizeName(name).split('.')) {
|
|
58
|
+
const b = Buffer.from(label, 'ascii')
|
|
59
|
+
if (b.length > 63) throw new Error(`label too long: ${label}`)
|
|
60
|
+
bufs.push(Buffer.from([b.length]), b)
|
|
61
|
+
}
|
|
62
|
+
bufs.push(Buffer.from([0]))
|
|
63
|
+
return Buffer.concat(bufs)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function ipBytes(addr) {
|
|
67
|
+
return Buffer.from(ipaddr.parse(addr).toByteArray())
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function mxRdata({ preference = 10, exchange }) {
|
|
71
|
+
const pref = Buffer.alloc(2)
|
|
72
|
+
pref.writeUInt16BE(preference, 0)
|
|
73
|
+
return Buffer.concat([pref, encodeName(exchange)])
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function txtRdata(txt) {
|
|
77
|
+
const strings = Array.isArray(txt) ? txt : [txt]
|
|
78
|
+
const bufs = []
|
|
79
|
+
for (const s of strings) {
|
|
80
|
+
const b = Buffer.from(String(s), 'utf8')
|
|
81
|
+
if (b.length > 255) throw new Error('TXT string > 255 bytes')
|
|
82
|
+
bufs.push(Buffer.from([b.length]), b)
|
|
83
|
+
}
|
|
84
|
+
return Buffer.concat(bufs)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Resolve a zone definition + query type into { rcode, answers }.
|
|
88
|
+
function answerFor(zone, qtype) {
|
|
89
|
+
if (!zone) return { rcode: RCODE.NXDOMAIN, answers: [] }
|
|
90
|
+
if (zone.rcode) {
|
|
91
|
+
const rc = RCODE[String(zone.rcode).toUpperCase()]
|
|
92
|
+
if (rc === undefined) throw new Error(`unknown rcode: ${zone.rcode}`)
|
|
93
|
+
return { rcode: rc, answers: [] }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const answers = []
|
|
97
|
+
if (qtype === TYPE.A && zone.a) for (const ip of zone.a) answers.push({ type: TYPE.A, rdata: ipBytes(ip) })
|
|
98
|
+
if (qtype === TYPE.AAAA && zone.aaaa)
|
|
99
|
+
for (const ip of zone.aaaa) answers.push({ type: TYPE.AAAA, rdata: ipBytes(ip) })
|
|
100
|
+
if (qtype === TYPE.MX && zone.mx) for (const mx of zone.mx) answers.push({ type: TYPE.MX, rdata: mxRdata(mx) })
|
|
101
|
+
if (qtype === TYPE.TXT && zone.txt) answers.push({ type: TYPE.TXT, rdata: txtRdata(zone.txt) })
|
|
102
|
+
|
|
103
|
+
// Name exists but has no record of this type: NOERROR / 0 answers,
|
|
104
|
+
// which the resolver surfaces as ENODATA.
|
|
105
|
+
return { rcode: RCODE.NOERROR, answers }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// One answer RR. NAME is a compression pointer to the question name at
|
|
109
|
+
// offset 12 (0xC00C), which every resolver understands.
|
|
110
|
+
function encodeRR({ type, ttl = 300, rdata }) {
|
|
111
|
+
const head = Buffer.alloc(12)
|
|
112
|
+
head.writeUInt16BE(0xc00c, 0) // NAME -> pointer to question
|
|
113
|
+
head.writeUInt16BE(type, 2) // TYPE
|
|
114
|
+
head.writeUInt16BE(1, 4) // CLASS IN
|
|
115
|
+
head.writeUInt32BE(ttl, 6) // TTL
|
|
116
|
+
head.writeUInt16BE(rdata.length, 10) // RDLENGTH
|
|
117
|
+
return Buffer.concat([head, rdata])
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function buildResponse(query, qEnd, rcode, answers) {
|
|
121
|
+
const header = Buffer.alloc(12)
|
|
122
|
+
header.writeUInt16BE(query.readUInt16BE(0), 0) // copy ID
|
|
123
|
+
const rd = (query.readUInt16BE(2) >> 8) & 0x01 // copy RD bit
|
|
124
|
+
// QR=1, Opcode=0, AA=1, TC=0, RD, RA=1, Z=0, RCODE
|
|
125
|
+
const flags = 0x8000 | (1 << 10) | (rd << 8) | (1 << 7) | (rcode & 0x0f)
|
|
126
|
+
header.writeUInt16BE(flags, 2)
|
|
127
|
+
header.writeUInt16BE(query.readUInt16BE(4), 4) // QDCOUNT (echo)
|
|
128
|
+
header.writeUInt16BE(answers.length, 6) // ANCOUNT
|
|
129
|
+
// NSCOUNT / ARCOUNT remain 0
|
|
130
|
+
const question = query.subarray(12, qEnd)
|
|
131
|
+
return Buffer.concat([header, question, ...answers.map(encodeRR)])
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Point an existing thing at this test server.
|
|
135
|
+
// - a node:dns promises Resolver -> setServers()
|
|
136
|
+
// - anything with getDnsResolver(), e.g. @haraka/net-utils -> patch that resolver
|
|
137
|
+
// Returns a restore() function. Kept dependency-free: the caller passes the object.
|
|
138
|
+
function patch(target, port) {
|
|
139
|
+
const servers = [`127.0.0.1:${port}`]
|
|
140
|
+
if (target && typeof target.getDnsResolver === 'function') {
|
|
141
|
+
const r = target.getDnsResolver()
|
|
142
|
+
const prev = r.getServers()
|
|
143
|
+
r.setServers(servers)
|
|
144
|
+
return () => r.setServers(prev)
|
|
145
|
+
}
|
|
146
|
+
if (target && typeof target.setServers === 'function') {
|
|
147
|
+
const prev = target.getServers()
|
|
148
|
+
target.setServers(servers)
|
|
149
|
+
return () => target.setServers(prev)
|
|
150
|
+
}
|
|
151
|
+
throw new Error('patch(): expected a node:dns Resolver or an object with getDnsResolver()')
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function start(zones = {}, opts = {}) {
|
|
155
|
+
return new Promise((resolve, reject) => {
|
|
156
|
+
const map = new Map()
|
|
157
|
+
const setZone = (name, cfg) => map.set(normalizeName(name), cfg)
|
|
158
|
+
for (const [name, cfg] of Object.entries(zones)) setZone(name, cfg)
|
|
159
|
+
|
|
160
|
+
const sock = dgram.createSocket('udp4')
|
|
161
|
+
|
|
162
|
+
sock.on('message', (msg, rinfo) => {
|
|
163
|
+
let q
|
|
164
|
+
try {
|
|
165
|
+
q = parseQuestion(msg)
|
|
166
|
+
} catch {
|
|
167
|
+
return // malformed packet: stay silent
|
|
168
|
+
}
|
|
169
|
+
const zone = map.get(q.name)
|
|
170
|
+
if (zone && zone.drop) return // simulate a black hole (-> ETIMEOUT)
|
|
171
|
+
|
|
172
|
+
const send = () => {
|
|
173
|
+
let resp
|
|
174
|
+
try {
|
|
175
|
+
const { rcode, answers } = answerFor(zone, q.qtype)
|
|
176
|
+
resp = buildResponse(msg, q.qEnd, rcode, answers)
|
|
177
|
+
} catch {
|
|
178
|
+
resp = buildResponse(msg, q.qEnd, RCODE.SERVFAIL, [])
|
|
179
|
+
}
|
|
180
|
+
sock.send(resp, rinfo.port, rinfo.address)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if (zone && zone.delayMs) setTimeout(send, zone.delayMs)
|
|
184
|
+
else send()
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
sock.once('error', reject)
|
|
188
|
+
sock.bind(opts.port || 0, '127.0.0.1', () => {
|
|
189
|
+
const { port, address } = sock.address()
|
|
190
|
+
resolve({
|
|
191
|
+
port,
|
|
192
|
+
address,
|
|
193
|
+
setZone,
|
|
194
|
+
clearZones: () => map.clear(),
|
|
195
|
+
close: () => new Promise((r) => sock.close(r)),
|
|
196
|
+
// A fresh node:dns Resolver already pointed at this server.
|
|
197
|
+
resolver: ({ timeout = 500, tries = 1 } = {}) => {
|
|
198
|
+
const r = new Resolver({ timeout, tries })
|
|
199
|
+
r.setServers([`127.0.0.1:${port}`])
|
|
200
|
+
return r
|
|
201
|
+
},
|
|
202
|
+
patch: (target) => patch(target, port),
|
|
203
|
+
})
|
|
204
|
+
})
|
|
205
|
+
})
|
|
206
|
+
}
|
package/lib/helpers.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
|
|
3
|
+
import { Address } from '@haraka/email-address'
|
|
4
|
+
|
|
5
|
+
import { createConnection } from './connection.js'
|
|
6
|
+
import { invoke } from './invoke.js'
|
|
7
|
+
import Plugin from './plugin.js'
|
|
8
|
+
import { stub } from './stub.js'
|
|
9
|
+
|
|
10
|
+
const LOG_METHODS = [
|
|
11
|
+
'logdebug',
|
|
12
|
+
'logprotocol',
|
|
13
|
+
'loginfo',
|
|
14
|
+
'lognotice',
|
|
15
|
+
'logwarn',
|
|
16
|
+
'logerror',
|
|
17
|
+
'logcrit',
|
|
18
|
+
'logalert',
|
|
19
|
+
'logemerg',
|
|
20
|
+
'logdata',
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
const toAddress = (v) => {
|
|
24
|
+
if (v instanceof Address) return v
|
|
25
|
+
if (typeof v === 'string') return new Address(v.startsWith('<') ? v : `<${v}>`)
|
|
26
|
+
if (v && typeof v === 'object' && v.address) return new Address(`<${v.address}>`)
|
|
27
|
+
return v
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Wraps a Haraka hook callback into an awaitable Promise.
|
|
32
|
+
*
|
|
33
|
+
* Haraka hooks follow the convention: plugin.method(next, connection, ...args)
|
|
34
|
+
* where next is called as next(rc, msg). This helper turns that into:
|
|
35
|
+
*
|
|
36
|
+
* const { rc, msg } = await callHook(plugin, 'bare_ip', connection, 'helo')
|
|
37
|
+
*
|
|
38
|
+
* Prefer the typed call helpers (callMail, callRcpt, etc.) when possible —
|
|
39
|
+
* they're more readable and resolve the method name automatically. Use this
|
|
40
|
+
* generic version for hooks without a typed wrapper, or to call a specific
|
|
41
|
+
* method directly.
|
|
42
|
+
*
|
|
43
|
+
* @param {import('./plugin.js').LoadedPlugin} plugin
|
|
44
|
+
* @param {string} method - Hook method name (e.g. 'hook_rcpt', 'bare_ip')
|
|
45
|
+
* @param {object} connection
|
|
46
|
+
* @param {...*} args - Additional hook arguments (params, helo host, etc.)
|
|
47
|
+
* @returns {Promise<{rc: *, msg: *}>}
|
|
48
|
+
*/
|
|
49
|
+
export const callHook = (plugin, method, connection, ...args) => invoke(plugin, method, [connection, ...args])
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Creates, optionally registers, and returns a Plugin instance.
|
|
53
|
+
*
|
|
54
|
+
* const plugin = makePlugin('helo.checks')
|
|
55
|
+
* const plugin = makePlugin('access', { configDir: __dirname })
|
|
56
|
+
*
|
|
57
|
+
* @param {string} name
|
|
58
|
+
* @param {object} [opts]
|
|
59
|
+
* @param {boolean} [opts.register=true] - call plugin.register() after creation
|
|
60
|
+
* @param {string} [opts.configDir] - resolve to plugin.config.module_config(path.resolve(configDir))
|
|
61
|
+
* *before* register() runs
|
|
62
|
+
* @returns {import('./plugin.js').LoadedPlugin}
|
|
63
|
+
*/
|
|
64
|
+
export const makePlugin = (name, { register = true, configDir } = {}) => {
|
|
65
|
+
const plugin = new Plugin(name)
|
|
66
|
+
if (configDir) plugin.config = plugin.config.module_config(path.resolve(configDir))
|
|
67
|
+
if (register) plugin.register()
|
|
68
|
+
return plugin
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Creates a Connection with commonly-needed options pre-applied.
|
|
73
|
+
*
|
|
74
|
+
* const conn = makeConnection({ ip: '1.2.3.4', mailFrom: 'user@host' })
|
|
75
|
+
*
|
|
76
|
+
* If mailFrom, rcptTo, or txNotes is given, a transaction is created
|
|
77
|
+
* automatically (no need to pass withTxn).
|
|
78
|
+
*
|
|
79
|
+
* @param {object} [opts]
|
|
80
|
+
* @param {string} [opts.ip='127.0.0.1'] - remote.ip
|
|
81
|
+
* @param {boolean} [opts.withTxn=false] - call init_transaction()
|
|
82
|
+
* @param {boolean} [opts.relaying=false] - connection._relaying
|
|
83
|
+
* @param {string} [opts.helo] - hello.host (EHLO hostname)
|
|
84
|
+
* @param {string|Address} [opts.mailFrom] - transaction.mail_from (string coerced to Address)
|
|
85
|
+
* @param {Array<string|Address>} [opts.rcptTo] - transaction.rcpt_to (strings coerced to Address)
|
|
86
|
+
* @param {object} [opts.notes] - seed connection.notes
|
|
87
|
+
* @param {object} [opts.txNotes] - seed transaction.notes
|
|
88
|
+
* @param {object} [opts.server] - assigned to connection.server; use for
|
|
89
|
+
* server.notes.* injection (e.g. shared redis handle)
|
|
90
|
+
* @param {string} [opts.host] - remote.host (rDNS hostname)
|
|
91
|
+
* @param {boolean} [opts.silent=false] - replace every log method with a no-op
|
|
92
|
+
* @param {boolean} [opts.stubLogs=false] - replace every log method with a recording stub()
|
|
93
|
+
* @returns {import('./connection.js').Connection}
|
|
94
|
+
*/
|
|
95
|
+
export const makeConnection = ({
|
|
96
|
+
ip = '127.0.0.1',
|
|
97
|
+
withTxn = false,
|
|
98
|
+
relaying = false,
|
|
99
|
+
helo,
|
|
100
|
+
host,
|
|
101
|
+
mailFrom,
|
|
102
|
+
rcptTo,
|
|
103
|
+
notes,
|
|
104
|
+
txNotes,
|
|
105
|
+
server,
|
|
106
|
+
silent = false,
|
|
107
|
+
stubLogs = false,
|
|
108
|
+
} = {}) => {
|
|
109
|
+
const conn = createConnection({}, server ?? {})
|
|
110
|
+
conn.remote.ip = ip
|
|
111
|
+
if (host) conn.remote.host = host
|
|
112
|
+
if (helo) {
|
|
113
|
+
conn.hello.host = helo
|
|
114
|
+
conn.hello.verb = 'EHLO'
|
|
115
|
+
}
|
|
116
|
+
if (silent || stubLogs) {
|
|
117
|
+
const replace = silent ? () => () => {} : () => stub()
|
|
118
|
+
for (const m of LOG_METHODS) conn[m] = replace()
|
|
119
|
+
}
|
|
120
|
+
if (notes) Object.assign(conn.notes, notes)
|
|
121
|
+
|
|
122
|
+
const needTransaction = withTxn || mailFrom || rcptTo || txNotes
|
|
123
|
+
if (needTransaction) conn.init_transaction()
|
|
124
|
+
if (mailFrom) conn.transaction.mail_from = toAddress(mailFrom)
|
|
125
|
+
if (rcptTo) conn.transaction.rcpt_to = rcptTo.map(toAddress)
|
|
126
|
+
if (txNotes) Object.assign(conn.transaction.notes, txNotes)
|
|
127
|
+
|
|
128
|
+
// Set relaying through the setter so it lands on transaction._relaying when
|
|
129
|
+
// a transaction exists (matches Connection.relaying semantics).
|
|
130
|
+
if (relaying) conn.relaying = true
|
|
131
|
+
|
|
132
|
+
return conn
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Returns the result-store entry for a plugin, accepting either the plugin
|
|
137
|
+
* instance or its string name. Falls back to an empty result object so
|
|
138
|
+
* callers can write `getResult(conn, plugin).pass.length` without null checks.
|
|
139
|
+
*
|
|
140
|
+
* const r = getResult(connection, plugin)
|
|
141
|
+
* assert.ok(r.pass.length)
|
|
142
|
+
*
|
|
143
|
+
* @param {object} connection
|
|
144
|
+
* @param {object|string} pluginOrName
|
|
145
|
+
* @returns {{ pass: string[], fail: string[], skip: string[], err: string[], data: object }}
|
|
146
|
+
*/
|
|
147
|
+
export const getResult = (connection, pluginOrName) => {
|
|
148
|
+
const name = typeof pluginOrName === 'string' ? pluginOrName : pluginOrName.name
|
|
149
|
+
return connection.results.get(name) ?? { pass: [], fail: [], skip: [], err: [], data: {} }
|
|
150
|
+
}
|
package/lib/hooks.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { Address } from '@haraka/email-address'
|
|
2
|
+
|
|
3
|
+
import { invoke } from './invoke.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Typed per-hook helpers.
|
|
7
|
+
*
|
|
8
|
+
* const { rc, msg } = await callMail(plugin, conn, 'user@host')
|
|
9
|
+
*
|
|
10
|
+
* Each helper:
|
|
11
|
+
* - takes natural args (string addresses, not [new Address('<x>'), {}])
|
|
12
|
+
* - resolves method name from plugin.hooks[hookName] when possible
|
|
13
|
+
* - returns Promise<{rc, msg}> via the dual-mode invoke() dispatcher,
|
|
14
|
+
* passing the expected 4.0 hook arity so the dispatcher can tell a
|
|
15
|
+
* genuine 4.0 async hook from a 3.x callback hook declared `async`
|
|
16
|
+
*
|
|
17
|
+
* For plugins that export the hook method under a non-default name
|
|
18
|
+
* (e.g. aliases registers 'aliases' for 'rcpt' via
|
|
19
|
+
* `this.register_hook('rcpt', 'aliases')`), the helper finds it via
|
|
20
|
+
* plugin.hooks (populated by register_hook). Callers can also pass
|
|
21
|
+
* an explicit method name as the last argument when they need to bypass
|
|
22
|
+
* the registry — useful for plugins that expose multiple methods on
|
|
23
|
+
* one hook (priority ordering, etc.).
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
export const resolveMethod = (plugin, hookName, explicit) => {
|
|
27
|
+
if (explicit) return explicit
|
|
28
|
+
const registered = plugin.hooks?.[hookName]
|
|
29
|
+
if (registered && registered.length) return registered[0]
|
|
30
|
+
for (const name of [`hook_${hookName}`, hookName]) {
|
|
31
|
+
if (typeof plugin[name] === 'function') return name
|
|
32
|
+
}
|
|
33
|
+
throw new Error(
|
|
34
|
+
`no method on plugin '${plugin.name}' for hook '${hookName}' (looked at plugin.hooks, hook_${hookName}, ${hookName})`,
|
|
35
|
+
)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const toAddress = (v) => {
|
|
39
|
+
if (v instanceof Address) return v
|
|
40
|
+
if (typeof v === 'string') return new Address(v.startsWith('<') ? v : `<${v}>`)
|
|
41
|
+
if (v && typeof v === 'object' && v.address) return new Address(`<${v.address}>`)
|
|
42
|
+
return v
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @typedef {import('./plugin.js').LoadedPlugin} LoadedPlugin */
|
|
46
|
+
/** @typedef {import('./connection.js').Connection} Connection */
|
|
47
|
+
/** @typedef {{ rc: any, msg: any }} HookResult */
|
|
48
|
+
|
|
49
|
+
/** @param {string} hookName */
|
|
50
|
+
const noArg =
|
|
51
|
+
(hookName) =>
|
|
52
|
+
/**
|
|
53
|
+
* @param {LoadedPlugin} plugin
|
|
54
|
+
* @param {Connection} conn
|
|
55
|
+
* @param {string} [method] call this method instead of the hook's registered one
|
|
56
|
+
* @returns {Promise<HookResult>}
|
|
57
|
+
*/
|
|
58
|
+
(plugin, conn, method) =>
|
|
59
|
+
invoke(plugin, resolveMethod(plugin, hookName, method), [conn], { asyncArity: 1 })
|
|
60
|
+
|
|
61
|
+
/** @param {string} hookName */
|
|
62
|
+
const stringArg =
|
|
63
|
+
(hookName) =>
|
|
64
|
+
/**
|
|
65
|
+
* @param {LoadedPlugin} plugin
|
|
66
|
+
* @param {Connection} conn
|
|
67
|
+
* @param {string} arg
|
|
68
|
+
* @param {string} [method] call this method instead of the hook's registered one
|
|
69
|
+
* @returns {Promise<HookResult>}
|
|
70
|
+
*/
|
|
71
|
+
(plugin, conn, arg, method) =>
|
|
72
|
+
invoke(plugin, resolveMethod(plugin, hookName, method), [conn, arg], { asyncArity: 2 })
|
|
73
|
+
|
|
74
|
+
/** @param {string} hookName */
|
|
75
|
+
const addressArg =
|
|
76
|
+
(hookName) =>
|
|
77
|
+
/**
|
|
78
|
+
* @param {LoadedPlugin} plugin
|
|
79
|
+
* @param {Connection} conn
|
|
80
|
+
* @param {string | Address} addr
|
|
81
|
+
* @param {object | string} [params] ESMTP params, or the method name
|
|
82
|
+
* @param {string} [method] call this method instead of the hook's registered one
|
|
83
|
+
* @returns {Promise<HookResult>}
|
|
84
|
+
*/
|
|
85
|
+
(plugin, conn, addr, params, method) => {
|
|
86
|
+
// A bare string in the `params` slot means the caller is using the
|
|
87
|
+
// 4-arg form to pass a method override (params is always an object).
|
|
88
|
+
if (typeof params === 'string' && method === undefined) {
|
|
89
|
+
method = params
|
|
90
|
+
params = undefined
|
|
91
|
+
}
|
|
92
|
+
return invoke(plugin, resolveMethod(plugin, hookName, method), [conn, [toAddress(addr), params ?? {}]], {
|
|
93
|
+
asyncArity: 2,
|
|
94
|
+
})
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export const callConnect = noArg('connect')
|
|
98
|
+
export const callHelo = stringArg('helo')
|
|
99
|
+
export const callEhlo = stringArg('ehlo')
|
|
100
|
+
export const callMail = addressArg('mail')
|
|
101
|
+
export const callRcpt = addressArg('rcpt')
|
|
102
|
+
/**
|
|
103
|
+
* @param {LoadedPlugin} plugin
|
|
104
|
+
* @param {Connection} conn
|
|
105
|
+
* @param {string | Address} rcpt
|
|
106
|
+
* @param {string} [method] call this method instead of the hook's registered one
|
|
107
|
+
* @returns {Promise<HookResult>}
|
|
108
|
+
*/
|
|
109
|
+
export const callRcptOk = (plugin, conn, rcpt, method) =>
|
|
110
|
+
invoke(plugin, resolveMethod(plugin, 'rcpt_ok', method), [conn, toAddress(rcpt)], { asyncArity: 2 })
|
|
111
|
+
export const callData = noArg('data')
|
|
112
|
+
export const callDataPost = noArg('data_post')
|
|
113
|
+
export const callQueue = noArg('queue')
|
|
114
|
+
/**
|
|
115
|
+
* @param {LoadedPlugin} plugin
|
|
116
|
+
* @param {Connection} conn
|
|
117
|
+
* @param {string} msg the queue's response
|
|
118
|
+
* @param {string} [method] call this method instead of the hook's registered one
|
|
119
|
+
* @returns {Promise<HookResult>}
|
|
120
|
+
*/
|
|
121
|
+
export const callQueueOk = (plugin, conn, msg, method) =>
|
|
122
|
+
invoke(plugin, resolveMethod(plugin, 'queue_ok', method), [conn, msg], { asyncArity: 2 })
|
|
123
|
+
export const callDisconnect = noArg('disconnect')
|
package/lib/invoke.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dual-mode hook dispatcher.
|
|
3
|
+
*
|
|
4
|
+
* Haraka 3.x plugin hooks are callback-style:
|
|
5
|
+
*
|
|
6
|
+
* export function hook_mail(next, connection, params) {
|
|
7
|
+
* next(DENY, 'no thanks')
|
|
8
|
+
* }
|
|
9
|
+
*
|
|
10
|
+
* Haraka 4.0 plan an async/return-value style:
|
|
11
|
+
*
|
|
12
|
+
* export async function hook_mail(connection, params) {
|
|
13
|
+
* return [DENY, 'no thanks'] // or { rc: DENY, msg: '...' } or just DENY
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* `invoke` accepts either shape. The 4.0 path is taken only when the function
|
|
17
|
+
* is `async` AND its declared arity matches the expected 4.0 arity for the
|
|
18
|
+
* hook (supplied by the typed call<Hook> helpers). This distinguishes a
|
|
19
|
+
* genuine 4.0 hook from a 3.x callback hook that happens to be declared
|
|
20
|
+
* `async` so it can `await` internally before invoking `next`.
|
|
21
|
+
*/
|
|
22
|
+
export function invoke(plugin, method, callArgs, opts = {}) {
|
|
23
|
+
const fn = plugin[method]
|
|
24
|
+
if (typeof fn !== 'function') {
|
|
25
|
+
return Promise.reject(new Error(`plugin '${plugin.name}' has no method '${method}'`))
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const isAsync = fn.constructor.name === 'AsyncFunction'
|
|
29
|
+
const is40 = isAsync && opts.asyncArity !== undefined && fn.length === opts.asyncArity
|
|
30
|
+
|
|
31
|
+
if (is40) {
|
|
32
|
+
return Promise.resolve(fn.call(plugin, ...callArgs)).then(normalize)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return new Promise((resolve, reject) => {
|
|
36
|
+
let settled = false
|
|
37
|
+
const next = (rc, msg) => {
|
|
38
|
+
if (settled) return
|
|
39
|
+
settled = true
|
|
40
|
+
resolve({ rc, msg })
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
fn.call(plugin, next, ...callArgs)
|
|
44
|
+
} catch (err) {
|
|
45
|
+
reject(err)
|
|
46
|
+
}
|
|
47
|
+
})
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function normalize(value) {
|
|
51
|
+
if (value === undefined || value === null) return { rc: undefined, msg: undefined }
|
|
52
|
+
if (Array.isArray(value)) return { rc: value[0], msg: value[1] }
|
|
53
|
+
if (typeof value === 'object' && 'rc' in value) return { rc: value.rc, msg: value.msg }
|
|
54
|
+
return { rc: value, msg: undefined }
|
|
55
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// A subclass of Socket which reads data by line
|
|
2
|
+
|
|
3
|
+
import Events from 'node:events'
|
|
4
|
+
|
|
5
|
+
import { stub } from './stub.js'
|
|
6
|
+
|
|
7
|
+
const LINE_REGEXP = /^([^\n]*\n)/
|
|
8
|
+
|
|
9
|
+
export class Socket extends Events {
|
|
10
|
+
constructor(port, host) {
|
|
11
|
+
super()
|
|
12
|
+
|
|
13
|
+
this.port = port
|
|
14
|
+
this.host = host
|
|
15
|
+
this.setTimeout = stub()
|
|
16
|
+
this.setKeepAlive = stub()
|
|
17
|
+
this.destroy = stub()
|
|
18
|
+
this.writable = true
|
|
19
|
+
this.readable = true
|
|
20
|
+
|
|
21
|
+
// Setup line processor
|
|
22
|
+
setupLineProcessor(this)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
write(data, encoding, callback) {
|
|
26
|
+
this.emit('data', data)
|
|
27
|
+
if (callback) callback()
|
|
28
|
+
return true
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
end(data, encoding, callback) {
|
|
32
|
+
if (data) {
|
|
33
|
+
this.write(data, encoding)
|
|
34
|
+
}
|
|
35
|
+
this.writable = false
|
|
36
|
+
this.emit('end')
|
|
37
|
+
if (callback) callback()
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function setupLineProcessor(socket) {
|
|
42
|
+
let currentData = ''
|
|
43
|
+
|
|
44
|
+
socket.on('data', function onSocketData(data) {
|
|
45
|
+
currentData += data
|
|
46
|
+
let results
|
|
47
|
+
while ((results = LINE_REGEXP.exec(currentData))) {
|
|
48
|
+
const thisLine = results[1]
|
|
49
|
+
currentData = currentData.slice(thisLine.length)
|
|
50
|
+
socket.emit('line', thisLine)
|
|
51
|
+
}
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
socket.on('end', function onSocketEnd() {
|
|
55
|
+
if (currentData.length) {
|
|
56
|
+
socket.emit('line', currentData)
|
|
57
|
+
}
|
|
58
|
+
currentData = ''
|
|
59
|
+
})
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function connect(port, host, cb) {
|
|
63
|
+
const sock = new Socket(port, host)
|
|
64
|
+
if (cb) {
|
|
65
|
+
sock.on('connect', cb)
|
|
66
|
+
}
|
|
67
|
+
return sock
|
|
68
|
+
}
|