Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ Plugins must stay self-contained: if a plugin is not loaded, no trace of it shou

Per connection hooks for plugins that change the wire format: `connection.parserOptions` and `connection.compilerOptions` are passed to the `imap-handler` parser and compiler, `connection.importMailboxName(name)` converts every mailbox name argument (the `mailboxArguments` positions) to the modified UTF-7 storage name and throws a BAD error for an invalid name, and `connection.exportMailboxName(path)` converts a storage name for output. Every response that carries a mailbox name must convert it: either call `exportMailboxName` (LIST, LSUB, NAMESPACE), or put `{ type: 'MAILBOX', value: storageName }` in the attributes (also inside lists, like the MAILBOX correlator of ESEARCH), which `send` converts for the receiving session and sends as an atom or a string (STATUS, QUOTAROOT, METADATA, needed for notifications that go to several sessions). `matchFolders` takes the export function as its third argument. A command whose mailbox argument has no fixed position calls `importMailboxName` itself (GETMETADATA, ESEARCH). `connection.searchCharset` fixes the SEARCH charset of a session: a CHARSET argument is then BAD, and SORT/THREAD accept only that charset; `connection.defaultSearchCharset` only changes the charset assumed without CHARSET (IMAP4rev2: UTF-8). UTF8=ACCEPT and IMAP4rev2 set these through `src/utf8-session.ts`, which computes the UTF-8 state of a session from `connection.enabled`, so both plugins work in any load order. `connection.disabledSearchKeys` and `connection.disabledStatusItems` (Sets, or null) remove SEARCH keys and STATUS items from a session (BAD), `connection.addedStatusItems` allows STATUS items for one session only, `connection.number64` makes the `number64` SEARCH argument type (LARGER, SMALLER) take 63-bit values, and `connection.parserOptions.number64` (imap-handler) literal sizes and partial ranges (IMAP4rev2 sets both), `connection.messageGlobal` makes message/global parts encapsulate a message in BODYSTRUCTURE and section numbers (`resolveNode(tree, path, global)`, `embeddedMessage()` in `mimeparser.ts`), and `connection.getFlags(message)` can be replaced per connection (IMAP4rev2 leaves out `\Recent`). A plugin that needs another one lists its name in `plugin.requires` (UTF8=ACCEPT requires ENABLE), `src/load-plugins.ts` loads it first.

Other modules: `mimeparser.ts`, `bodystructure.ts`, `envelope.ts`, `addressparser.ts` produce BODYSTRUCTURE/ENVELOPE data from raw messages; `encoded-words.ts` decodes RFC 2047 encoded words for SEARCH header keys, SORT and THREAD; `sorting.ts` (collation, base subject, sent date, address and Message-ID values, and the search step) and `threading.ts` (THREAD command, ORDEREDSUBJECT and REFERENCES) back the SORT, SORT=DISPLAY and THREAD=* plugins; `maildir.ts` (`loadMaildir(dir)`, not in the package root or the browser bundle because it reads files) builds a storage object from a Maildir++ directory or a directory of `.eml` files for `imapkit --maildir`; `smtp-listener.ts` is the optional SMTP listener (built on the optional `smtp-server` peer dependency) that appends incoming mail to INBOX; `cert/` holds the self-signed localhost cert used for STARTTLS and `secureConnection` (embedded through the generated `src/cert.ts`).
Other modules: `mimeparser.ts`, `bodystructure.ts`, `envelope.ts`, `addressparser.ts` produce BODYSTRUCTURE/ENVELOPE data from raw messages; `encoded-words.ts` decodes RFC 2047 encoded words for SEARCH header keys, SORT and THREAD; `sorting.ts` (collation, base subject, sent date, address and Message-ID values, and the search step) and `threading.ts` (THREAD command, ORDEREDSUBJECT and REFERENCES) back the SORT, SORT=DISPLAY and THREAD=* plugins; `maildir.ts` (`loadMaildir(dir)`, not in the package root or the browser bundle because it reads files) builds a storage object from a Maildir++ directory or a directory of `.eml` files for `imapkit --maildir`; `corpus.ts` (`imapkit/lib/corpus`, Node-only like `maildir.ts`) downloads, caches and reads the Synthetic Email Corpus release archive (a streaming tar reader, no extraction) and builds its storage for `imapkit --corpus`, with the `imapkit corpus` commands in `bin/corpus.js`; `PINNED_CORPUS` there holds the version and digest a release serves by default; `smtp-listener.ts` is the optional SMTP listener (built on the optional `smtp-server` peer dependency) that appends incoming mail to INBOX; `cert/` holds the self-signed localhost cert used for STARTTLS and `secureConnection` (embedded through the generated `src/cert.ts`).

## Tests

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Point your IMAP client to `localhost:1143` and log in with user name `testuser`

`imapkit -p 1143 --tls-port=1993` also listens for implicit TLS (IMAPS) connections on port 1993, both ports serve the same mailboxes. `imapkit --smtpPort=1025` also starts an SMTP server that appends every message it receives to INBOX. SMTP needs the optional [smtp-server](https://www.npmjs.com/package/smtp-server) package, which is not installed with ImapKit: `npm install -g smtp-server` (or `npm install smtp-server` next to a local install).

Run `imapkit --help` to see all command line options, the environment variables (`IMAPKIT_PORT`, `IMAPKIT_PLUGINS`, ...) and sample configuration data. For example, `imapkit -p 1143 --plugin=IDLE,MOVE,CONDSTORE --storage=storage.json` loads three plugins and the mailboxes of `storage.json`. `--maildir=<path>` loads the mailboxes from a Maildir++ directory or a directory of `.eml` files instead.
Run `imapkit --help` to see all command line options, the environment variables (`IMAPKIT_PORT`, `IMAPKIT_PLUGINS`, ...) and sample configuration data. For example, `imapkit -p 1143 --plugin=IDLE,MOVE,CONDSTORE --storage=storage.json` loads three plugins and the mailboxes of `storage.json`. `--maildir=<path>` loads the mailboxes from a Maildir++ directory or a directory of `.eml` files instead. `--corpus` serves the [Synthetic Email Corpus](https://github.com/postalsys/synthetic-email-corpus), 11,637 realistic messages that are downloaded once into a cache (`imapkit corpus find quirk:bare-cr` shows where a message with a given feature is).

### Include as a Node.js module

Expand Down
261 changes: 261 additions & 0 deletions bin/corpus.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
// The synthetic email corpus on the command line: `--corpus` for the server and the `imapkit corpus` commands.
// Progress and notes go to stderr, results (the find table, list, paths) to stdout

import v8 from 'node:v8';
import {
CORPUS_ATTRIBUTION,
PINNED_CORPUS,
cacheDir,
cachedVersions,
ensureCorpus,
findInCorpus,
loadCorpusArchive,
removeCached
} from '../dist/esm/corpus.js';

const MB = 1024 * 1024;
const count = value => Number(value).toLocaleString('en-US');
const megabytes = value => Math.round(value / MB) + ' MB';
const seconds = ms => (ms / 1000).toFixed(1) + 's';

/** a usage error, the command exits with status 2 */
class UsageError extends Error {}

/**
* Shows download progress: an updating bar on a terminal, a line every 25% otherwise (CI logs)
*
* @param {Object} stream Output stream, stderr
* @return {Object} `{ start(release, file), progress({ received, total }), done() }`
*/
export function progressReporter(stream = process.stderr) {
const tty = !!stream.isTTY;
let started = 0;
let lastDraw = 0;
let lastQuarter = -1;
let partFile = '';
const onInterrupt = () => {
stream.write((tty ? '\n' : '') + 'Download interrupted, it continues from ' + partFile + ' next time\n');
process.exit(130);
};
return {
start(release, file) {
started = Date.now();
partFile = file + '.part';
stream.write('Downloading synthetic-email-corpus ' + release.version + ' (' + megabytes(release.size) + ') to ' + file + '\n');
process.once('SIGINT', onInterrupt);
},
progress({ received, total }) {
const fraction = total ? Math.min(received / total, 1) : 0;
if (!tty) {
const quarter = Math.floor(fraction * 4);
if (quarter > lastQuarter && quarter > 0 && quarter < 4) {
lastQuarter = quarter;
stream.write(' ' + Math.round(fraction * 100) + '% (' + megabytes(received) + ' of ' + megabytes(total) + ')\n');
}
return;
}
const now = Date.now();
if (now - lastDraw < 100 && fraction < 1) {
return;
}
lastDraw = now;
const elapsed = (now - started) / 1000;
const rate = elapsed ? received / elapsed : 0;
const left = rate ? Math.max(0, Math.round((total - received) / rate)) + 's left' : '';
const status = ` ${megabytes(received)}/${megabytes(total)} ${Math.round(fraction * 100)}% ${(rate / MB).toFixed(1)} MB/s ${left}`;
const width = Math.max(10, Math.min(30, (stream.columns || 80) - status.length - 4));
const filled = Math.round(fraction * width);
stream.write('\r\x1b[2K ' + '#'.repeat(filled) + '-'.repeat(width - filled) + status);
},
done() {
process.removeListener('SIGINT', onInterrupt);
if (started) {
stream.write((tty ? '\r\x1b[2K' : '') + 'Downloaded and verified in ' + seconds(Date.now() - started) + '\n');
}
}
};
}

/** ensureCorpus with progress output */
async function fetchCorpus(version) {
const reporter = progressReporter();
try {
return await ensureCorpus(version, {
onDownload: (release, file) => reporter.start(release, file),
onProgress: progress => reporter.progress(progress)
});
} finally {
reporter.done();
}
}

/**
* The corpus settings from the command line and the environment (`options`: `version` is true, false, `true`,
* `false` or a version; `filter` a list of terms; `mutations` true, false or undefined), with the `corpus` key of
* the config file (true, a version, or `{ version, filter, mutations }`) for what they leave out. The key is removed
* from the config, the server does not know it
*
* @return {Object|null} `{ version, filter, mutations }`, null when the corpus is not used
*/
export function corpusSettings(options, config) {
let fromConfig = config.corpus;
delete config.corpus;
if (fromConfig && typeof fromConfig !== 'object') {
fromConfig = { version: fromConfig };
}
const version = options.version ?? fromConfig?.version;
if (version === undefined || version === false || version === 'false' || version === '') {
return null;
}
return {
version: version === true || version === 'true' ? undefined : version,
filter: options.filter.length ? options.filter : [].concat(fromConfig?.filter || []),
mutations: !!(options.mutations ?? fromConfig?.mutations)
};
}

/**
* Downloads (when needed) and loads the corpus for `--corpus`, with notes on stderr
*
* @return {Object} the loaded corpus and how long loading took
*/
export async function prepareCorpus(settings) {
const { version, file } = await fetchCorpus(settings.version);
// the whole corpus takes about 1 GB of heap once every message is parsed
const limit = v8.getHeapStatistics().heap_size_limit;
if (!settings.filter.length && limit < 1.5 * 1024 * MB) {
process.stderr.write(
`Note: the Node.js heap limit is ${megabytes(limit)} and the corpus needs about 1 GB. If ImapKit runs out of memory, start it with NODE_OPTIONS=--max-old-space-size=4096\n`
);
}
process.stderr.write(`Loading corpus ${version}${settings.filter.length ? ' (' + settings.filter.join(' ') + ')' : ''} ...\n`);
const started = Date.now();
const corpus = await loadCorpusArchive(file, { filter: settings.filter, mutations: settings.mutations, version });
return { corpus, loadTime: Date.now() - started };
}

/** the lines printed after the server started */
export function corpusSummary({ corpus, loadTime }) {
const counts = Object.entries(corpus.counts);
const total = counts.reduce((sum, [, value]) => sum + value, 0);
return [
`Corpus ${corpus.version}: ${count(total)} messages in ${counts.length} mailboxes, loaded in ${seconds(loadTime)}`,
' ' + counts.map(([name, value]) => name + ' ' + count(value)).join(', '),
' ' + CORPUS_ATTRIBUTION
];
}

/** pads table columns */
function table(rows) {
const widths = rows[0].map((_, i) => Math.max(...rows.map(row => String(row[i]).length)));
return rows.map(row => row.map((cell, i) => (i === row.length - 1 ? String(cell) : String(cell).padEnd(widths[i]))).join(' ')).join('\n');
}

const COMMANDS_HELP = `Usage: imapkit corpus <command> [options]

Commands:
pull [version] Downloads a corpus release into the cache (the
pinned ${PINNED_CORPUS.version} without a version, or latest)
list Lists the cached releases
find <terms...> Shows the mailbox and UID of the messages that match,
as --corpus serves them. Terms are key:value, the same
key means OR, different keys AND:
imapkit corpus find quirk:bare-cr
imapkit corpus find category:spam lang:et
Keys: id, category, lang, thread, spam, folder and the
feature tags of the manifest (ct, cs, cte, ew, ext,
size, quirk)
clean [version] Removes cached releases (all without a version)

Options:
--corpus=<version> Release that find uses (default ${PINNED_CORPUS.version})
--limit=<n> Rows that find shows, default 20, 0 for all
--json Machine readable output for list and find

The cache is ${cacheDir()}
(IMAPKIT_CACHE_DIR changes it)`;

/**
* Runs `imapkit corpus <command>`
*
* @param {String[]} args Positionals after "corpus"
* @param {Object} argv Parsed options
* @return {Number} exit status
*/
export async function runCorpusCommand(args, argv) {
const [command, ...rest] = args;
try {
switch (command) {
case 'pull': {
if (rest.length > 1) {
throw new UsageError('imapkit corpus pull takes one version');
}
const { version, file, downloaded } = await fetchCorpus(rest[0] ?? argv.corpus);
process.stdout.write((downloaded ? '' : version + ' is cached at ') + file + '\n');
return 0;
}
case 'list': {
const cached = cachedVersions();
if (argv.json) {
process.stdout.write(JSON.stringify(cached.map(item => ({ ...item, pinned: item.version === PINNED_CORPUS.version }))) + '\n');
return 0;
}
if (!cached.length) {
process.stdout.write(
`No corpus is cached in ${cacheDir()}\n` +
`imapkit corpus pull downloads ${PINNED_CORPUS.version} (${megabytes(PINNED_CORPUS.size)}), imapkit --corpus also starts a server with it\n`
);
return 0;
}
const rows = [['VERSION', 'SIZE', 'PINNED', 'FILE']].concat(
cached.map(item => [item.version, megabytes(item.size), item.version === PINNED_CORPUS.version ? 'yes' : '', item.file])
);
process.stdout.write(table(rows) + '\n');
return 0;
}
case 'find': {
if (!rest.length) {
throw new UsageError('imapkit corpus find needs at least one key:value term, e.g. imapkit corpus find quirk:bare-cr');
}
const { version, file } = await fetchCorpus(argv.corpus);
const matches = await findInCorpus(file, rest);
if (argv.json) {
process.stdout.write(
JSON.stringify(matches.map(({ id, path, uid, category, language, thread }) => ({ id, path, uid, category, language, thread }))) + '\n'
);
return 0;
}
const limit = argv.limit === undefined ? 20 : Number(argv.limit);
if (!Number.isInteger(limit) || limit < 0) {
throw new UsageError('--limit must be a number, 0 shows every match');
}
const shown = limit ? matches.slice(0, limit) : matches;
if (shown.length) {
const rows = [['ID', 'MAILBOX', 'UID', 'CATEGORY', 'LANG', 'THREAD']].concat(
shown.map(item => [item.id, item.path, item.uid, item.category, item.language, item.thread || ''])
);
process.stdout.write(table(rows) + '\n');
}
const more = matches.length > shown.length ? `, showing ${shown.length} (--limit=0 shows all)` : '';
process.stderr.write(`${count(matches.length)} messages in ${version} match${more}\n`);
return 0;
}
case 'clean': {
// the archives and the parts interrupted downloads left, of the versions given or of all
const { removed, size } = removeCached(rest);
const names = removed.map(item => item.version + (item.partial ? ' (partial download)' : ''));
process.stdout.write(names.length ? `Removed ${names.join(', ')}, ${megabytes(size)}\n` : `Nothing to remove in ${cacheDir()}\n`);
return 0;
}
case undefined:
case 'help':
process.stdout.write(COMMANDS_HELP + '\n');
return 0;
default:
throw new UsageError(`Unknown command "imapkit corpus ${command}"\n\n` + COMMANDS_HELP);
}
} catch (err) {
process.stderr.write((err instanceof UsageError ? '' : 'imapkit corpus: ') + err.message + '\n');
return err instanceof UsageError ? 2 : 1;
}
}
Loading