imapkit 4.1.1 → 4.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.
@@ -0,0 +1,332 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ServerScript = void 0;
4
+ exports.sendOutput = sendOutput;
5
+ exports.handleLine = handleLine;
6
+ const EVENTS = ['greeting', 'command', 'input', 'response', 'continuation'];
7
+ const OUTPUT_EVENTS = ['greeting', 'response', 'continuation'];
8
+ // the events where a key is valid, every other key is a typo and refused
9
+ const KEYS = {
10
+ on: EVENTS,
11
+ command: ['command', 'input', 'response', 'continuation'],
12
+ tag: ['command', 'input', 'response', 'continuation'],
13
+ description: ['response', 'continuation'],
14
+ session: EVENTS,
15
+ user: EVENTS,
16
+ state: EVENTS,
17
+ mailbox: EVENTS,
18
+ untagged: ['response'],
19
+ match: EVENTS,
20
+ when: EVENTS,
21
+ nth: EVENTS,
22
+ times: EVENTS,
23
+ mutate: ['response', 'continuation'],
24
+ send: EVENTS,
25
+ before: OUTPUT_EVENTS,
26
+ after: OUTPUT_EVENTS,
27
+ run: ['command', 'input'],
28
+ drop: EVENTS,
29
+ delay: ['greeting', 'command', 'response', 'continuation'],
30
+ chunk: EVENTS,
31
+ chunkDelay: EVENTS,
32
+ truncate: EVENTS,
33
+ close: EVENTS
34
+ };
35
+ const ACTIONS = ['mutate', 'send', 'before', 'after', 'run', 'drop', 'delay', 'chunk', 'truncate', 'close'];
36
+ const DEFAULT_CHUNK_DELAY = 10;
37
+ // matchers that list accepted values, kept as Sets so that matching an event allocates nothing
38
+ const SET_MATCHERS = ['command', 'description', 'session', 'state', 'user', 'mailbox'];
39
+ /**
40
+ * Turns bytes of a rule into a Buffer. A string is a binary string (one character per octet) like everywhere
41
+ * in ImapKit, unless it has characters above U+00FF, then it is sent as UTF-8
42
+ */
43
+ function resolveBytes(value, context) {
44
+ if (value === undefined) {
45
+ return null;
46
+ }
47
+ const bytes = typeof value === 'function' ? value(context) : value;
48
+ if (Buffer.isBuffer(bytes)) {
49
+ return bytes;
50
+ }
51
+ const text = String(bytes).replace(/\$TAG/g, () => context.tag || '*');
52
+ return Buffer.from(text, /[\u0100-\uffff]/.test(text) ? 'utf-8' : 'binary');
53
+ }
54
+ /**
55
+ * Checks a rule given by the caller, a mistake is a TypeError right away instead of a rule that silently never fires
56
+ *
57
+ * @param {Object} rule Rule to check
58
+ * @return {RegExp|null} the `match` expression
59
+ */
60
+ function validateRule(rule) {
61
+ if (!rule || typeof rule !== 'object') {
62
+ throw new TypeError('A script rule must be an object');
63
+ }
64
+ if (!EVENTS.includes(rule.on)) {
65
+ throw new TypeError('Script rule "on" must be one of ' + EVENTS.join(', '));
66
+ }
67
+ for (const key of Object.keys(rule)) {
68
+ const events = Object.hasOwn(KEYS, key) ? KEYS[key] : null;
69
+ if (!events) {
70
+ throw new TypeError('Unknown script rule option "' + key + '"');
71
+ }
72
+ if (!events.includes(rule.on)) {
73
+ throw new TypeError('Script rule option "' + key + '" can not be used with "on": "' + rule.on + '"');
74
+ }
75
+ }
76
+ if (!ACTIONS.some(key => rule[key] !== undefined && rule[key] !== false)) {
77
+ throw new TypeError('A script rule needs an action (' + ACTIONS.join(', ') + ')');
78
+ }
79
+ if (rule.drop && (rule.send !== undefined || rule.run)) {
80
+ throw new TypeError('Script rule option "drop" can not be combined with "send" or "run"');
81
+ }
82
+ if (rule.run && (rule.close || rule.truncate !== undefined)) {
83
+ throw new TypeError('Script rule option "run" can not be combined with "close" or "truncate"');
84
+ }
85
+ if (rule.chunkDelay !== undefined && rule.chunk === undefined) {
86
+ throw new TypeError('Script rule option "chunkDelay" needs "chunk"');
87
+ }
88
+ if (!OUTPUT_EVENTS.includes(rule.on) && rule.send === undefined && (rule.chunk !== undefined || rule.truncate !== undefined)) {
89
+ // a command or input line has no output of its own to cut or split
90
+ throw new TypeError('Script rule options "chunk" and "truncate" need "send" with "on": "' + rule.on + '"');
91
+ }
92
+ for (const key of ['nth', 'times', 'chunk']) {
93
+ if (rule[key] !== undefined && !(Number.isInteger(rule[key]) && rule[key] > 0)) {
94
+ throw new TypeError('Script rule option "' + key + '" must be a positive integer');
95
+ }
96
+ }
97
+ for (const key of ['delay', 'chunkDelay', 'truncate']) {
98
+ if (rule[key] !== undefined && !(Number.isInteger(rule[key]) && rule[key] >= 0)) {
99
+ throw new TypeError('Script rule option "' + key + '" must be a non-negative integer');
100
+ }
101
+ }
102
+ for (const key of ['when', 'mutate']) {
103
+ if (rule[key] !== undefined && typeof rule[key] !== 'function') {
104
+ throw new TypeError('Script rule option "' + key + '" must be a function');
105
+ }
106
+ }
107
+ for (const key of ['send', 'before', 'after']) {
108
+ const value = rule[key];
109
+ if (value !== undefined && typeof value !== 'string' && typeof value !== 'function' && !Buffer.isBuffer(value)) {
110
+ throw new TypeError('Script rule option "' + key + '" must be a string, a Buffer or a function');
111
+ }
112
+ }
113
+ if (rule.close !== undefined && typeof rule.close !== 'boolean' && rule.close !== 'reset') {
114
+ throw new TypeError('Script rule option "close" must be true, false or "reset"');
115
+ }
116
+ if (rule.match === undefined) {
117
+ return null;
118
+ }
119
+ if (rule.match instanceof RegExp) {
120
+ // a global or sticky expression would keep its position between events
121
+ return new RegExp(rule.match.source, rule.match.flags.replace(/[gy]/g, ''));
122
+ }
123
+ if (typeof rule.match !== 'string') {
124
+ throw new TypeError('Script rule option "match" must be a string or a RegExp');
125
+ }
126
+ try {
127
+ return new RegExp(rule.match);
128
+ }
129
+ catch (err) {
130
+ throw new TypeError('Script rule option "match" is not a valid regular expression: ' + err.message, { cause: err });
131
+ }
132
+ }
133
+ /**
134
+ * The script of a server, `server.script`
135
+ */
136
+ class ServerScript {
137
+ constructor(server, rules) {
138
+ this.server = server;
139
+ this.entries = [];
140
+ this.watched = new Set();
141
+ if (rules) {
142
+ this.add(rules);
143
+ }
144
+ }
145
+ /** the rules that were added, in the order they are checked */
146
+ get rules() {
147
+ return this.entries.slice();
148
+ }
149
+ add(rules) {
150
+ if (Array.isArray(rules)) {
151
+ // all rules are checked before any is added
152
+ const matches = rules.map(validateRule);
153
+ return rules.map((rule, i) => this.addEntry(rule, matches[i]));
154
+ }
155
+ return this.addEntry(rules, validateRule(rules));
156
+ }
157
+ /** removes every rule */
158
+ clear() {
159
+ this.setEntries([]);
160
+ }
161
+ /**
162
+ * Checks if any rule watches an event, so that the event can skip building a context
163
+ *
164
+ * @param {String} event Event name
165
+ * @return {Boolean} true if a rule watches the event
166
+ */
167
+ watches(event) {
168
+ return this.watched.has(event);
169
+ }
170
+ /**
171
+ * Finds the rule that handles an event of a connection
172
+ *
173
+ * @param {Object} connection IMAP connection
174
+ * @param {String} event Event name
175
+ * @param {Object} fields `data`, and `tag`, `command`, `description`, `response` where they are known
176
+ * @return {Object|null} `{ rule, context }`, or null if no rule handles the event
177
+ */
178
+ check(connection, event, fields) {
179
+ if (!this.watched.has(event)) {
180
+ return null;
181
+ }
182
+ const context = scriptContext(connection, event, fields);
183
+ const rule = this.find(context);
184
+ return rule ? { rule, context } : null;
185
+ }
186
+ setEntries(entries) {
187
+ this.entries = entries;
188
+ this.watched = new Set(entries.map(entry => entry.rule.on));
189
+ }
190
+ addEntry(rule, match) {
191
+ // a copy, so that changing the caller's object later does not change the rule
192
+ const copy = Object.freeze(Object.assign({}, rule));
193
+ const sets = {};
194
+ for (const key of SET_MATCHERS) {
195
+ if (copy[key] !== undefined) {
196
+ // command names are compared in upper case
197
+ const values = [].concat(copy[key]);
198
+ sets[key] = new Set(key === 'command' ? values.map(value => String(value).toUpperCase()) : values);
199
+ }
200
+ }
201
+ const entry = {
202
+ rule: copy,
203
+ match,
204
+ sets,
205
+ matched: 0,
206
+ hits: 0,
207
+ remove: () => this.setEntries(this.entries.filter(item => item !== entry))
208
+ };
209
+ this.setEntries(this.entries.concat(entry));
210
+ return entry;
211
+ }
212
+ /**
213
+ * Finds the rule that handles an event and counts it
214
+ *
215
+ * @param {Object} context Event context
216
+ * @return {Object|null} the rule, or null if no rule handles the event
217
+ */
218
+ find(context) {
219
+ for (const entry of this.entries) {
220
+ const rule = entry.rule;
221
+ if (rule.on !== context.event || !this.matches(entry, context)) {
222
+ continue;
223
+ }
224
+ entry.matched++;
225
+ if (entry.matched < (rule.nth || 1) || (rule.times !== undefined && entry.hits >= rule.times)) {
226
+ continue;
227
+ }
228
+ entry.hits++;
229
+ this.server.emit('script', { rule, event: context.event, session: context.session, tag: context.tag, command: context.command });
230
+ return rule;
231
+ }
232
+ return null;
233
+ }
234
+ matches(entry, context) {
235
+ const rule = entry.rule;
236
+ for (const key of SET_MATCHERS) {
237
+ const set = entry.sets[key];
238
+ const value = context[key];
239
+ if (set && (value === null || value === undefined || !set.has(value))) {
240
+ return false;
241
+ }
242
+ }
243
+ if (rule.tag !== undefined && (context.tag === null || (rule.tag instanceof RegExp ? !rule.tag.test(context.tag) : rule.tag !== context.tag))) {
244
+ return false;
245
+ }
246
+ if (rule.untagged !== undefined && rule.untagged !== (!context.response || context.response.tag === '*')) {
247
+ return false;
248
+ }
249
+ if (entry.match && !entry.match.test(context.data)) {
250
+ return false;
251
+ }
252
+ return !rule.when || !!rule.when(context);
253
+ }
254
+ }
255
+ exports.ServerScript = ServerScript;
256
+ /**
257
+ * Builds the context of an event on a connection
258
+ *
259
+ * @param {Object} connection IMAP connection
260
+ * @param {String} event Event name
261
+ * @param {Object} fields `data`, and `tag`, `command`, `description`, `response` where they are known
262
+ * @return {Object} Event context
263
+ */
264
+ function scriptContext(connection, event, fields) {
265
+ // after its handler returned, a command whose input handler reads the lines (IDLE, AUTHENTICATE) is the one
266
+ // the events belong to
267
+ const running = connection._runningCommand
268
+ ? connection._runningCommand.parsed
269
+ : connection.inputHandler
270
+ ? connection.inputCommand
271
+ : null;
272
+ return Object.assign({
273
+ event,
274
+ connection,
275
+ session: connection.sessionNumber,
276
+ state: connection.state,
277
+ user: connection.username || null,
278
+ mailbox: connection.selectedMailbox ? connection.selectedMailbox.path : null,
279
+ tag: running ? running.tag : null,
280
+ command: running ? String(running.command).toUpperCase() : null
281
+ }, fields);
282
+ }
283
+ /**
284
+ * Sends output through the rule that handles it: the output itself (unless dropped or replaced with `send`)
285
+ * between `before` and `after`, cut by `truncate`, with the timing of `delay` and `chunk`
286
+ *
287
+ * @param {Object} connection IMAP connection
288
+ * @param {Object} rule Rule that handles the output
289
+ * @param {Object} context Event context
290
+ * @param {Buffer} output The output
291
+ */
292
+ function sendOutput(connection, rule, context, output) {
293
+ const replaced = rule.drop ? Buffer.alloc(0) : resolveBytes(rule.send, context) || output;
294
+ const parts = [resolveBytes(rule.before, context), replaced, resolveBytes(rule.after, context)].filter((part) => !!part);
295
+ sendBytes(connection, rule, Buffer.concat(parts), rule.delay);
296
+ }
297
+ /**
298
+ * Sends the bytes of a rule with its timing, `truncate` closes the connection after the cut
299
+ *
300
+ * @param {Object} connection IMAP connection
301
+ * @param {Object} rule Rule
302
+ * @param {Buffer} data Bytes to send
303
+ * @param {Number} [delay] Milliseconds to wait first
304
+ */
305
+ function sendBytes(connection, rule, data, delay) {
306
+ connection.queueOutput({
307
+ data: rule.truncate === undefined ? data : data.subarray(0, rule.truncate),
308
+ delay,
309
+ chunk: rule.chunk,
310
+ chunkDelay: rule.chunkDelay === undefined ? DEFAULT_CHUNK_DELAY : rule.chunkDelay,
311
+ close: rule.close || (rule.truncate === undefined ? undefined : true)
312
+ });
313
+ }
314
+ /**
315
+ * Handles a command or input line with the rule that matched it: sends the bytes of `send`, closes the connection,
316
+ * and processes the line as usual with `run` (or when the rule only delays it)
317
+ *
318
+ * @param {Object} connection IMAP connection
319
+ * @param {Object} rule Rule that matched
320
+ * @param {Object} context Event context
321
+ * @param {Function} run Processes the line as usual
322
+ */
323
+ function handleLine(connection, rule, context, run) {
324
+ const bytes = resolveBytes(rule.send, context);
325
+ if (bytes || rule.close) {
326
+ sendBytes(connection, rule, bytes || Buffer.alloc(0));
327
+ }
328
+ // a rule that only delays the line does not replace it
329
+ if (rule.run || (!rule.drop && !bytes && !rule.close)) {
330
+ run();
331
+ }
332
+ }
@@ -3,6 +3,8 @@ import net from 'node:net';
3
3
  import tls from 'node:tls';
4
4
  import type { CompilerOptions, ParserOptions } from 'imap-handler';
5
5
  import type { ResolvedCommandOptions } from './command-states.js';
6
+ import { ServerScript } from './script.js';
7
+ import type { OutputOperation, ScriptContext, ScriptEvent, ScriptRule } from './script.js';
6
8
  import type { AppendCheck, AppendCheckOptions, AppendDataHandler, AppendMessage, CapabilityCheck, CheckResult, ClosedCheck, CommandCheck, CommandContext, CommandOptions, CommandHandler, ConnectionHandler, ConnectionState, CopyHandler, FetchHandler, IMAPResponse, IMAPServerOptions, ListedMailbox, LiteralFilter, Mailbox, MailboxHandler, MailboxStatus, Message, MessageFilter, MessageHandler, MessageRange, Namespace, Notification, NotifyEvent, NotifyFilter, OutputHandler, ParsedCommand, RangeLimit, Refusal, SearchAccessCheck, SearchHandler, SearchLimit, ServerStorage, StatusHandler, StorageMailbox, StorageMessage, StoreHandler, SubscriptionStandIn, Transport, UrlAccessCheck, UserData } from './types.js';
7
9
  declare const TAG_REGEX: RegExp;
8
10
  /**
@@ -58,6 +60,10 @@ declare class IMAPServer extends Stream {
58
60
  uidvalidityCounter: number;
59
61
  subscriptions: Set<string>;
60
62
  folderCache: Record<string, Mailbox>;
63
+ /** scripted faults, see src/script.ts */
64
+ script: ServerScript;
65
+ /** connections accepted so far, the number of a connection is `connection.sessionNumber` */
66
+ sessionCounter: number;
61
67
  constructor(options?: IMAPServerOptions);
62
68
  /**
63
69
  * Starts accepting connections, takes the arguments of `net.Server#listen()`
@@ -446,6 +452,11 @@ declare class IMAPServer extends Stream {
446
452
  interface QueuedCommand {
447
453
  parsed: ParsedCommand;
448
454
  data: string;
455
+ /** a command line that a script rule handles instead of the parser and the command handler */
456
+ script?: {
457
+ rule: ScriptRule;
458
+ context: ScriptContext;
459
+ } | undefined;
449
460
  }
450
461
  declare class IMAPConnection {
451
462
  [key: string]: any;
@@ -471,6 +482,13 @@ declare class IMAPConnection {
471
482
  /** notifications are sent right away instead of before the next tagged response (IDLE) */
472
483
  directNotifications: boolean;
473
484
  notificationQueue: Notification[];
485
+ /** the number of the connection, 1 for the first one the server accepted (script rules match it) */
486
+ sessionNumber: number;
487
+ /** the tag and name of the command whose input handler reads the lines that follow (IDLE, AUTHENTICATE) */
488
+ inputCommand: {
489
+ tag: string;
490
+ command: string;
491
+ } | null | undefined;
474
492
  _remainder: string;
475
493
  _command: string;
476
494
  _literalRemaining: number;
@@ -488,6 +506,9 @@ declare class IMAPConnection {
488
506
  command: string;
489
507
  read: number | undefined;
490
508
  } | undefined;
509
+ /** output that waits behind a delay of a script rule, null when output is written right away */
510
+ _outputQueue: OutputOperation[] | null;
511
+ _outputTimer: ReturnType<typeof setTimeout> | null;
491
512
  constructor(server: IMAPServer, socket: net.Socket);
492
513
  /**
493
514
  * Writes protocol output to the client, through the transport layer if there is one
@@ -495,6 +516,45 @@ declare class IMAPConnection {
495
516
  * @param {Buffer|String} data Data to send, a string is sent as a binary string
496
517
  */
497
518
  write(data: Buffer | string): void;
519
+ /**
520
+ * Writes output, or puts it in the output queue while earlier output waits for a delay of a script rule.
521
+ * The transport layer is taken when the output is queued, so output from before COMPRESS is not compressed
522
+ *
523
+ * @param {Object} operation `{ data, delay, chunk, chunkDelay, close }`, see OutputOperation in src/script.ts
524
+ */
525
+ queueOutput(operation: OutputOperation): void;
526
+ /**
527
+ * Writes the output queue until it is empty or a delay stops it
528
+ */
529
+ flushOutput(): void;
530
+ /**
531
+ * Drops the output that waits for a delay of a script rule
532
+ */
533
+ clearOutputQueue(): void;
534
+ /**
535
+ * Writes output through a transport layer, or to the socket
536
+ *
537
+ * @param {Buffer} data Output
538
+ * @param {Object|null} transport Transport layer
539
+ */
540
+ writeLayer(data: Buffer, transport: Transport | null): void;
541
+ /**
542
+ * Sends output through the script rule that handles its event, if there is one
543
+ *
544
+ * @param {String} event Event name: greeting, response or continuation
545
+ * @param {String} output The output as a binary string
546
+ * @param {Object} fields Context fields of the event (tag, command, description, response)
547
+ * @param {Function} [compile] Compiles the response that a `mutate` action changed, null drops the output
548
+ */
549
+ scriptOutput(event: ScriptEvent, output: string, fields: Partial<ScriptContext>, compile?: (response: IMAPResponse) => string | null): void;
550
+ /**
551
+ * Sends a continuation request, `+ text`
552
+ *
553
+ * @param {String} text Human readable text, can be empty (SASL)
554
+ * @param {String} description Description for script rules
555
+ * @param {Function} [getLine] Returns the command line received so far, for the tag and the command of a literal continuation
556
+ */
557
+ sendContinuation(text: string, description: string, getLine?: () => string): void;
498
558
  /**
499
559
  * Writes data to the socket, below the transport layer
500
560
  *
@@ -512,6 +572,12 @@ declare class IMAPConnection {
512
572
  * holds, is written out
513
573
  */
514
574
  end(): void;
575
+ /**
576
+ * Closes the connection now, after the output written so far
577
+ *
578
+ * @param {Boolean|String} mode true ends the connection gracefully, "reset" destroys the socket (script rules)
579
+ */
580
+ closeNow(mode: boolean | 'reset'): void;
515
581
  /**
516
582
  * Sends an untagged BYE, drops unprocessed input and closes the connection (RFC 3501 section 7.1.5)
517
583
  *
@@ -564,6 +630,12 @@ declare class IMAPConnection {
564
630
  closeMailbox(): void;
565
631
  onClose(): void;
566
632
  onError(err: Error): void;
633
+ /**
634
+ * Passes a line to the input handler (IDLE, AUTHENTICATE), unless a script rule handles it
635
+ *
636
+ * @param {String} line Input line without CRLF
637
+ */
638
+ handleInput(line: string): void;
567
639
  onData(chunk: Buffer): void;
568
640
  /**
569
641
  * Reads literal data that the current command is waiting for. The data of a command that was
@@ -752,6 +824,13 @@ declare class IMAPConnection {
752
824
  * FETCH result. (This may have other names when used, like "affected".)
753
825
  */
754
826
  send(response: IMAPResponse, description?: string, parsed?: CommandContext | null, data?: string | null, ...extra: any[]): void;
827
+ /**
828
+ * Compiles a response for the wire
829
+ *
830
+ * @param {Object} response Response object
831
+ * @return {String|null} the response with its CRLF as a binary string, or null for an untagged response that does not compile
832
+ */
833
+ compileResponse(response: IMAPResponse): string | null;
755
834
  /**
756
835
  * Sends a tagged status response to a command
757
836
  *
@@ -848,7 +927,21 @@ declare class IMAPConnection {
848
927
  * @return {String} Mailbox name as a binary string
849
928
  */
850
929
  exportMailboxName(path: string): string;
851
- scheduleCommand(data: string): void;
930
+ /**
931
+ * Parses a command line and queues the command, or answers it right away when it can not run
932
+ *
933
+ * @param {String} data Command line with its literals, without the final CRLF
934
+ * @param {Boolean} [scripted] The line comes from a script rule with `run`, it is next in the queue
935
+ */
936
+ scheduleCommand(data: string, scripted?: boolean): void;
937
+ /**
938
+ * Handles a command line with the script rule that matched it, after the rule's delay. With `run` the line
939
+ * goes through the parser and the command handler as usual afterwards
940
+ *
941
+ * @param {Object} element Queued command with the rule
942
+ * @param {Function} next Releases the queue
943
+ */
944
+ runScriptedCommand(element: QueuedCommand, next: () => void): void;
852
945
  processQueue(force?: boolean): void;
853
946
  /**
854
947
  * Removes messages with \Deleted flag