Skip to content

goldstone ​

@c9up/goldstone: reading mail for ream: IMAP mailboxes (watched in real time with IDLE) and the inbound mail providers post to a webhook, each message parsed as hostile input, its HTML sanitized and its sender checked (DKIM, SPF, DMARC, ARC). Sending stays with rover.

Installation ​

bash
pnpm add @c9up/goldstone

Add () => import('@c9up/goldstone/provider') to the providers in reamrc.ts and create config/inbox.ts. Parsing and the sender checks run on a Rust engine. @c9up/ream is an optional peer.

The native engine comes as one small package per platform, @c9up/goldstone-<platform>, for linux x64 and arm64 (glibc), macOS x64 and arm64, and Windows x64. @c9up/goldstone lists them as optional dependencies, and your package manager installs only the one that matches your machine. No Rust toolchain is needed. Do not install with optional dependencies turned off (--no-optional, --omit=optional): the engine would be left out.

There is no JavaScript fallback. Without the engine, the first parse throws E_GOLDSTONE_NATIVE_REQUIRED, and its message names the package to install, for example @c9up/goldstone-linux-x64-gnu.

Entry points ​

ImportContents
@c9up/goldstonedefineConfig, InboxManager, Mailbox, message parsing (parseMessage, readMessage), the sender check (authenticate), the Mailgun inbound handler and the error classes.
@c9up/goldstone/providerGoldstoneProvider (default export): binds the InboxManager built from config/inbox.ts.
@c9up/goldstone/services/mainThe application's InboxManager (default export), resolved on first member access.

Exports ​

@c9up/goldstone ​

ExportKindDescription
defineConfigfunctionChecks and types config/inbox.ts.
InboxConfiginterfaceThe inbox config.
MailboxConfiginterfaceOne IMAP mailbox.
PasswordAuth, TokenAuthinterfaceA mailbox's credentials.
InboxManagerclassThe configured mailboxes, by name.
MailboxclassOne IMAP mailbox: search, fetch, flag, move, delete, watch.
MailboxOptionsinterfacelimits, authenticate, remoteContent for every message read.
SearchCriteriatypeIMAP search criteria (imapflow's search object).
WatchOptionsinterfaceOptions of Mailbox.watch.
reconnectDelayfunctionThe wait before reconnect attempt n.
parseMessagefunctionParses raw message bytes, without DNS.
readMessagefunctionParses raw message bytes and checks the sender.
ReceivedMessageclassA parsed message.
ParseOptions, ReadOptionsinterfaceOptions of parseMessage and readMessage.
LimitsinterfaceBounds applied while parsing.
Addressinterface{ readonly name?: string; readonly address?: string }.
Headerinterface{ readonly name: string; readonly value: string }, the value as received.
AttachmentinterfaceOne attachment.
authenticatefunctionChecks who sent raw message bytes.
AuthenticityinterfaceThe sender verdict.
AuthenticateOptionsinterfaceThe envelope and bounds of the check.
AuthResulttype'pass' | 'fail' | 'softfail' | 'neutral' | 'none' | 'temperror' | 'permerror'.
DkimVerdictinterfaceOne DKIM signature's verdict.
DmarcPolicytype'none' | 'quarantine' | 'reject' | 'unspecified'.
createMailgunInboundHandlerfunctionA route handler for Mailgun's inbound mail.
MailgunInboundOptionsinterfaceIts options.
InboundMetainterface{ recipient?: string; sender?: string }: the SMTP envelope.
InboundHttpContext, InboundResponseinterfaceThe HTTP context the handler needs.
ReplayGuardinterfaceWhere handled delivery tokens are remembered.
MemoryReplayGuardclassThe in-process ReplayGuard.
isNativeAvailablefunctionWhether the Rust engine is loaded.
errorsnamespaceThe package's errors, one class per code, see Errors. Each is a flare Exception with a string code.
fromEnginefunctionTurns an engine failure into the errors class of its code.

InboxManager ​

MemberSignatureDescription
constructornew InboxManager<Mailboxes>(config: InboxConfig<Mailboxes>)
mailboxmailbox(name?: keyof Mailboxes & string): MailboxA mailbox by name, the default one without; opens nothing yet. An unknown name throws E_GOLDSTONE_UNKNOWN_MAILBOX.
closeAllcloseAll(): Promise<void>Stops every watch and logs out of every mailbox.

Mailbox ​

Every method that takes a folder defaults to 'INBOX'. Messages are read with readMessage, under the mailbox's limits.

MemberSignatureDescription
constructornew Mailbox(name: string, config: MailboxConfig, options?: MailboxOptions)Refuses a connection without TLS or certificate check (see Configuration).
namereadonly name: string
foldersfolders(): Promise<string[]>Every folder's path.
searchsearch(criteria: SearchCriteria, folder?: string): Promise<number[]>UIDs of the matching messages, sorted.
fetchfetch(uid: number, folder?: string): Promise<ReceivedMessage | undefined>One message, or undefined when no message has that UID. A message the server says is over maxBytes is refused before download.
markSeen, markUnseen(uids: number | number[], folder?: string): Promise<void>Sets or clears \Seen.
movemove(uids: number | number[], to: string, folder?: string): Promise<void>Moves messages to another folder.
deletedelete(uids: number | number[], folder?: string): Promise<void>Deletes messages.
watchwatch(handler: (message: ReceivedMessage, meta: { uid: number }) => unknown, options?: WatchOptions): () => Promise<void>Calls handler for each new message as it arrives, on its own connection; returns the function that stops the watch. A lost connection reopens with a growing wait and nothing is skipped or delivered twice; a handler that throws does not stop the watch.
closeclose(): Promise<void>Stops every watch and logs out.
WatchOptions fieldTypeDefaultDescription
folderstring'INBOX'The folder watched.
afterUidnumberDeliver messages after this UID; without it, only what arrives once watching started.
onError(error: unknown) => voidconsole.errorTold about what does not stop the watch: a lost connection, a refused message, a handler that threw, UIDs reset (E_GOLDSTONE_UIDVALIDITY_CHANGED).
FunctionSignatureDescription
reconnectDelayreconnectDelay(attempt: number): number0.5 s, 1 s, 2 s… up to 30 s, in ms.

Parsing ​

FunctionSignatureDescription
parseMessageparseMessage(raw: Uint8Array, options?: ParseOptions): Promise<ReceivedMessage>Parses raw RFC 5322 bytes off the event loop. No DNS: authenticity is absent.
readMessagereadMessage(raw: Uint8Array, options?: ReadOptions): Promise<ReceivedMessage>Parses and checks the sender from one parse, the verdict on message.authenticity.
authenticateauthenticate(raw: Uint8Array, options?: AuthenticateOptions): Promise<Authenticity>Checks who sent the message.
isNativeAvailableisNativeAvailable(): boolean
fromEnginefromEngine(error: unknown): Exception
OptionTypeDefaultDescription
ParseOptions.limitsLimitssee belowBounds applied while parsing.
ParseOptions.remoteContent'block' | 'allow''block'Whether the sanitized html may load remote images, backgrounds and posters. cid: references and links with a scheme stay either way.
ReadOptions.authenticateboolean | AuthenticateOptionstrueCheck DKIM, SPF and DMARC.
AuthenticateOptions.ip, helo, mailFromstringThe delivering server's IP, HELO and MAIL FROM: what SPF checks. Without them SPF is none.
AuthenticateOptions.maxDkimSignaturesnumber5DKIM signatures checked, at most.
AuthenticateOptions.timeoutMsnumber10000For the whole check; past it, temperror.
AuthenticateOptions.maxBytesnumber25 MiBSize of the raw message, checked first.
Limits fieldDefaultDescription
maxBytes25 MiBSize of the raw message, checked before parsing.
maxParts1000MIME parts, carried messages' parts included.
maxDepth32Nesting depth of multiparts and carried messages.
maxHeaders1000Header fields in one header block.
maxHeaderBytes1 MiBSize of one header block.
maxPartHeaderBytes1 MiBSize of the header blocks of the parts and carried messages, all together. The message's own block is bounded by maxHeaderBytes alone.
maxAddresses5000Addresses in the address headers (From, To, Cc, Bcc, Reply-To, Sender, Resent-*, List-*) of every header block, the parts' included; a group counts as one more. Checked before the message is parsed.
maxAttachments100Number of attachments.
maxAttachmentBytes25 MiBSize of one decoded attachment.
maxHtmlBytes512 KiBSize of the HTML body that is sanitized; over it, the message is read without html.

Every limit is a positive integer under 2^32.

ReceivedMessage ​

MemberTypeDescription
messageId, subjectstring | undefined
dateDate | undefined
from, to, cc, bcc, replyToreadonly Address[]
inReplyTo, referencesreadonly string[]
headersreadonly Header[]Every header, as received.
textstring | undefinedThe text body.
htmlstring | undefinedSanitized for display: no script, no event handler, no javascript: URL, no remote content unless allowed, and no URL without a scheme (/path, ../x, //host, ?q, #id): a mail has no base URL in the page that shows it, so such a URL would point into your application. The element stays, without the attribute. To resolve these URLs against a base of your own, start from unsanitizedHtml().
htmlErrorException | undefinedWhy html is absent although the message has an HTML body (E_GOLDSTONE_HTML_TOO_LARGE, …_TOO_DEEP, …_TOO_COMPLEX). The depth and the complexity are measured on the tree the HTML parser builds.
attachmentsreadonly Attachment[]
authenticityAuthenticity | undefinedPresent when read with readMessage.
header(name)header(name: string): string | undefinedThe first header of that name, any case.
unsanitizedHtml()unsanitizedHtml(): string | undefinedThe HTML as the sender wrote it; never render it.
Attachment fieldTypeDescription
fileNamestringSafe to save under on any system.
originalNamestring | undefinedThe name as the sender wrote it, for display only.
contentTypestring
sizenumber
contentUint8Array
contentIdstring | undefined
inlineboolean

Authenticity ​

FieldTypeDescription
summary'pass' | 'fail' | 'none' | 'temperror'pass only when DMARC passed for fromDomain; fail when it failed or the From is ambiguous; temperror when a check could not complete.
dkimreadonly DkimVerdict[]One per signature: result, domain, selector, reason.
spfAuthResultnone when no envelope was given.
dmarcAuthResult
dmarcPolicyDmarcPolicy
dmarcDomainstring | undefinedThe From domain DMARC was evaluated for.
fromDomainstring | undefinedThe domain of the message's one From address; absent when missing or ambiguous. The display name is never authenticated.
arcAuthResult

Inbound mail ​

FunctionSignatureDescription
createMailgunInboundHandlercreateMailgunInboundHandler(options: MailgunInboundOptions): (ctx: InboundHttpContext, next?: () => Promise<void>) => Promise<void>Verifies Mailgun's signature on timestamp and token and refuses a wrong or stale one (401), reads body-mime (422 when missing) with readMessage, and calls onMessage. A token already handled is acknowledged (204) and not handled again. A message goldstone refuses answers 406 so Mailgun does not retry; when onMessage throws, the token is given back and the error propagates, so Mailgun retries; success answers 204.
MailgunInboundOptions fieldTypeDefaultDescription
signingKeystringrequiredThe webhook signing key.
onMessage(message: ReceivedMessage, meta: InboundMeta) => unknownrequiredHandles one message.
maxAgeSecondsnumber120A signed request older than this is refused; an integer from 1 to 86400.
replayGuardReplayGuardMemoryReplayGuardWhere handled tokens are kept; share one across instances.
limitsLimits
authenticateboolean | Omit<AuthenticateOptions, 'ip' | 'helo'>trueDKIM and DMARC on each message.
remoteContent'block' | 'allow''block'

The route must run behind the body parser, with form and multipart limits above the largest message accepted, and the Mailgun route must forward to a URL ending in mime.

MemberSignatureDescription
ReplayGuard.claimclaim(token: string, ttlSeconds: number): boolean | Promise<boolean>Takes the token; false when already taken. Must be atomic.
ReplayGuard.releaserelease(token: string): void | Promise<void>Gives a token back.
MemoryReplayGuard constructornew MemoryReplayGuard(capacity?: number)Default capacity 100000.

@c9up/goldstone/provider ​

ExportKindDescription
GoldstoneProviderprovider (default)register() builds the InboxManager from the inbox config (it opens no connection); shutdown() closes every mailbox.

@c9up/goldstone/services/main ​

ExportKindDescription
defaultconstThe application's InboxManager.
ts
import inbox from '@c9up/goldstone/services/main'

const unread = await inbox.mailbox().search({ seen: false })

Configuration ​

config/inbox.ts, returned through defineConfig. defineConfig refuses, at boot, a config with no mailbox, a default that is not declared, and a mailbox that would connect without TLS or without checking the server's certificate.

OptionTypeDefaultDescription
mailboxstringrequiredThe mailbox inbox.mailbox() returns with no argument.
mailboxesRecord<string, MailboxConfig>requiredThe mailboxes, by name.
limitsLimitsBounds on every message read.
authenticatebooleantrueCheck DKIM, SPF and DMARC on every message read.
remoteContent'block' | 'allow''block'Remote content in message.html.
MailboxConfig fieldTypeDefaultDescription
hoststringrequired
portnumber993, or 143 with starttls
securebooleantrue unless starttlsTLS from the first byte.
starttlsbooleanUpgrade a plaintext connection, and refuse to go on when the server does not offer it. Not with secure: true.
allowInsecurebooleanAllow no TLS or no certificate check: a local test server only.
tls{ ca?: string | Buffer; servername?: string; rejectUnauthorized?: boolean }Passed to Node's TLS.
authPasswordAuth | TokenAuthrequired{ user, pass }, or { user, accessToken } for XOAUTH2, where accessToken is a string or a function called on every connection.

Container bindings ​

TokenResolves to
InboxManagerThe InboxManager singleton.
'goldstone.inbox'The same instance.
'inbox'The same instance.

The string tokens are declared on ContainerBindings.

Errors ​

Each code is a class of the errors namespace (import { errors } from '@c9up/goldstone'): a flare Exception with code and status. The refusals of a message's content (E_GOLDSTONE_MESSAGE_TOO_LARGE through E_GOLDSTONE_HTML_TOO_COMPLEX below) have status 422; the others 500.

CodeRaised when
E_GOLDSTONE_MESSAGE_TOO_LARGEA message is over maxBytes; refused before download when the server announces its size.
E_GOLDSTONE_NOT_A_MESSAGEThe bytes are not a mail message.
E_GOLDSTONE_TOO_MANY_PARTSA message has more MIME parts than allowed.
E_GOLDSTONE_TOO_DEEPMIME parts are nested deeper than allowed.
E_GOLDSTONE_TOO_MANY_HEADERSA header block has more fields than allowed.
E_GOLDSTONE_HEADERS_TOO_LARGEA header block is over maxHeaderBytes, or the header blocks of the parts are over maxPartHeaderBytes together.
E_GOLDSTONE_TOO_MANY_ADDRESSESThe address headers hold more addresses than maxAddresses.
E_GOLDSTONE_MISSING_BOUNDARIESA multipart message declares boundaries that never appear.
E_GOLDSTONE_BOUNDARY_TOO_LONGA multipart boundary is too long.
E_GOLDSTONE_TOO_MANY_ATTACHMENTSA message has more attachments than allowed.
E_GOLDSTONE_ATTACHMENT_TOO_LARGEAn attachment is over the size limit.
E_GOLDSTONE_HTML_TOO_LARGEThe HTML body is over maxHtmlBytes (on htmlError).
E_GOLDSTONE_HTML_TOO_DEEPThe HTML body nests more than 1000 elements deep (on htmlError).
E_GOLDSTONE_HTML_TOO_COMPLEXThe HTML body builds a tree out of proportion to its markup: too many nodes, or too much work to place them, such as stray tags in a table (on htmlError).
E_GOLDSTONE_DNS_UNAVAILABLEA sender check needed DNS and DNS failed.
E_GOLDSTONE_INVALID_ENVELOPEThe envelope given to a sender check is invalid.
E_GOLDSTONE_ENGINEThe engine failed without one of the codes above.
E_GOLDSTONE_NATIVE_REQUIREDThe Rust mail engine is not loaded.
E_GOLDSTONE_INVALID_LIMITSA parsing limit is not a positive integer under 2^32.
E_GOLDSTONE_INVALID_OPTIONSA sender check option, remoteContent or a replay TTL is invalid.
E_GOLDSTONE_INVALID_CONFIGThe inbox config or the inbound handler's options are invalid.
E_GOLDSTONE_INSECURE_CONNECTIONA mailbox would connect without TLS or without checking the certificate.
E_GOLDSTONE_UNKNOWN_MAILBOXA mailbox name is not configured.
E_GOLDSTONE_UIDVALIDITY_CHANGEDA watched folder renumbered its messages; watching resumes from the newest.
E_GOLDSTONE_MISSING_CONFIGGoldstoneProvider registered with no config/inbox.ts.
E_GOLDSTONE_NOT_BOOTEDThe services/main inbox was used before GoldstoneProvider registered or setInbox() was called.

Migration ​

  • GoldstoneError is gone: test error.code, or error instanceof errors.E_GOLDSTONE_* with import { errors } from '@c9up/goldstone'.
  • GoldstoneNativeRequiredError becomes errors.E_GOLDSTONE_NATIVE_REQUIRED.
  • fromEngine() and htmlError return a flare Exception, the class of the code.
  • A refusal of a message's content now has status 422 (see Errors).
  • The sanitized html no longer keeps URLs without a scheme (href="/account", src="/logo.png", href="#top", href="//host/x"): the attribute is removed, the element kept. If you need them, resolve them yourself from unsanitizedHtml() against the base you choose.
  • A message whose address headers hold more than 5000 addresses in all is now refused with E_GOLDSTONE_TOO_MANY_ADDRESSES. Raise limits.maxAddresses if you receive mail sent to more recipients.
  • A message whose parts' header blocks are over 1 MiB together is now refused with E_GOLDSTONE_HEADERS_TOO_LARGE. Raise limits.maxPartHeaderBytes if you import messages that carry many forwarded messages.
  • HTML that places many stray tags in a table, or that nests deeper than 1000 elements behind a comment or a misnested tag, now has no html and an htmlError (E_GOLDSTONE_HTML_TOO_COMPLEX or E_GOLDSTONE_HTML_TOO_DEEP). HTML padded with many character references (&nbsp;) is no longer refused.

See also ​