STAXIS

staxis js platform -> gitlab project
staxis on gitlab gitlab project 🏷️ V-0.X-Beta
We’re actively updating this manual. Content and layout may change as we refine it.

mailer

Official sources are open to Staxis GitLab group members: how to join and view the code.
Repository: mailer development
Versions: tags and releases


Description

mailer manages mail account profiles and their native SMTP and optional IMAP clients. SMTP handles outgoing messages; IMAP inspects incoming message headers through a separate connection. The layer uses Node.js core modules without Nodemailer or another mail library. Its manifest.label and manifest.typology are both mailer.

Account profiles are persisted separately from live connections. Credentials are encrypted, and each account has an owner token whose hash is stored with the profile. Other layers obtain the internal API through the normal Staxis permission flow; this pack does not mount HTTP routes. The current release is still under development; see Current Development State for the implementation boundaries.


Read before flight

  • We suggest using direct TLS or TCP with STARTTLS for authenticated provider connections. Check the provider's transport, port, and authentication requirements; TCP by itself does not encrypt SMTP traffic. IMAP requires TLS or STARTTLS.

  • We suggest storing the raw owner token securely when registration returns it. It is returned once and only its hash is persisted. Keep credentials and account storage outside public files, and back up the storage before pack updates.

  • We suggest granting the API only to trusted consumers: any permitted consumer can register accounts. Keep mail-server profiles under application control and avoid accepting arbitrary connection targets from public requests.

  • We suggest awaiting operations sequentially on each account connection and closing sessions when finished. The layer does not provide a bulk-mail queue or a global delivery scheduler; IMAP rejects concurrent protocol commands on one connection.


Requirements and Installation

No other layer or external npm mail package is required by the manifest. The host must be able to reach your SMTP server and, when configured, your IMAP server. Install through the Manager:

                manager -> install -> mailer
            

Place mailer before its consumers. Prepare the project's Vault and integrity keys, including KEY:MAILER for the mailer typology, through the normal project setup. Node.js built-in imports must remain allowed by your Guardian policy.


Files Map

File Purpose
manifest.json Declares the mailer label, runtime slot, and permitted API consumers
configs.js Defines the account-storage path and Guardian filesystem rule
main.js Manages accounts, owner tokens, encrypted credentials, and protocol clients
smtp.js Implements native SMTP transport, authentication, and plain-text message delivery
imap.js Implements native IMAP transport and read-only inbox header inspection
smtp.accounts.json Stores account profiles, owner-token hashes, and encrypted credentials
.fomap Lists the resources handled by pack installation and export
README.md Original pack reference

Configuration and Account Storage

In config.js, the storage option belongs to config.serveropt.smtpStorage. The relative filename is resolved through engine.fileaccess from the mailer layer, so the supplied value points to system-lrpcks/mailer/smtp.accounts.json. Its filesystem allowance belongs to config.engineopt.guard.allowedFileAccess. Merge these branches into the exported config, preserving other packs' rules:

                // config.js -> config (merge into the exported object)
                engineopt: {
                    guard: {
                        allowedFileAccess: [{
                            pack: 'mailer',
                            roots: ['./system-lrpcks/mailer/smtp.accounts.json']
                        }]
                    }
                },
                serveropt: {
                    smtpStorage: 'smtp.accounts.json'
                }
            

The storage file must already exist and contain an accounts array. For a new empty store, its minimal shape is shown below. Do not replace an existing account store with this example. If you change smtpStorage, update the Guardian rule to permit the resolved file too.

                {
                    "accounts": []
                }
            

Each stored account has an id, label, SMTP profile, optional IMAP profile, an owner-token hash, and encrypted auth data containing the shared user and password. SMTP and IMAP share those credentials but use separate sockets. Encryption currently derives its AES-256-GCM key from the layer's own Vault access token, rather than a dedicated stable credential key.


Authorize a Calling Layer

The supplied mailer manifest permits mailer itself. Add your consumer's manifest.label to system-lrpcks/mailer/manifest.json, preserving the existing entries:

                {
                    "permits": ["mailer", "someOtherLayer"]
                }
            

The consumer can declare "require": ["mailer"]. Inside that consumer, use its engine and layers equipment to obtain the API:

                const tokenAccess = engine.vault.requireAccess(
                    'someOtherLayer', // Requesting pack's manifest.label
                    'mailer'          // Provider pack's manifest.label
                )

                if (typeof tokenAccess !== 'string' || tokenAccess.startsWith('error:')) {
                    throw new Error('Mailer layer access was denied')
                }

                const instance = layers.require(
                    'mailer', // Provider's manifest.typology: its runtime slot
                    tokenAccess,
                    false
                )

                const mailer = instance?.assets

                if (mailer?.status !== 'active') {
                    throw new Error('Mailer layer is unavailable')
                }
            

tokenAccess authorizes access to the Staxis API. It is different from the account's owner token. The layer's own self-issued Vault token is its administrative authority; a consumer's access token does not automatically become that administrative token. The examples below use the account-owner path, passing the owner token in the key field.


Public Account API

Member Purpose
status active after successful storage and Vault initialization; this does not mean protocol connections are open
connections() Count persisted account records, not currently open sockets
registerAccount(accountdata) Register an account and return its id, label, and one-time raw owner token
getAccounts({ key }) Return the accounts visible to the supplied owner or exact administrative authority
updateAccount({ id, key, ...changes }) Update an authorized account and replace its protocol clients; see the current cleanup limitation below
removeAccount({ id, key }) Remove an authorized account and close its clients; see the current cleanup limitation below

Account-management calls return promises resolving to errors, message, and payload. Check errors before using payload. Protocol connection methods can reject or throw, so await them inside the application's normal error-handling flow.


Register an Account

Supply a label of at least four characters, common credentials, and a complete SMTP profile. Add an IMAP profile only when you need incoming-mail inspection. Read credentials from your trusted backend secret source; these environment variable names are examples, not configuration automatically populated by Staxis.

                const user = process.env.MAIL_ACCOUNT_USER
                const password = process.env.MAIL_ACCOUNT_PASSWORD

                if (!user || !password) {
                    throw new Error('Mail account credentials are missing')
                }

                const registered = await mailer.registerAccount({
                    label: 'support',
                    user,
                    password,
                    smtp: {
                        host: 'smtp.example.com',
                        port: 465,
                        secure: 'TLS',
                        starttls: false,
                        from: ['Support <[email protected]>']
                    },
                    imap: {
                        host: 'imap.example.com',
                        port: 993,
                        secure: 'TLS',
                        starttls: false,
                        mailbox: 'INBOX'
                    }
                })

                if (registered.errors) {
                    throw new Error(registered.message)
                }

                const accountId = registered.payload.id
                const ownerToken = registered.payload.token

                // Save ownerToken in a private secret store; do not log it.
            

Replace the example hosts, ports, sender, and credentials with your provider's settings. Each smtp.from entry must use the form Display Name <[email protected]>. Registration creates runtime client instances but does not open network sessions. The label demo is reserved by the implementation and cannot be used for normal account operations.


Get the Owned Account

                const listed = await mailer.getAccounts({ key: ownerToken })

                if (listed.errors) {
                    throw new Error(listed.message)
                }

                const account = listed.payload.find(entry => entry.id === accountId)

                if (!account) {
                    throw new Error('The requested mail account is unavailable')
                }

                const connection = account.connection
            

An owner sees only the owned account; administrative authority can see all accounts. Listings provide technical profiles and a runtime connection facade, without decrypting the persisted credentials for the caller. The smtp.from field in the listing is a sender count, not the original sender array. Keep the connection reference in backend code.


Send a Plain-Text Message

Initialize SMTP explicitly. On a fresh connection, initSMTP returns the SMTP session with send and close methods. Keep that returned session for the current implementation; the account-level SMTP forwarding methods still need alignment. If SMTP is already ready, initSMTP returns true instead of a new session object. This example starts from a closed SMTP connection:

                const smtpSession = await connection.initSMTP()

                if (!smtpSession || typeof smtpSession.send !== 'function') {
                    throw new Error('Keep the SMTP session returned by the first initialization')
                }

                try {
                    const delivery = await smtpSession.send({
                        from: 'Support <[email protected]>',
                        to: ['[email protected]'],
                        subject: 'Staxis mailer example',
                        text: 'This is a plain-text message sent through the configured SMTP account.'
                    })

                    if (!delivery.accepted) {
                        throw new Error('The SMTP server did not accept the message')
                    }
                } finally {
                    await smtpSession.close()
                }
            

from must match an address allowed by the account's smtp.from profile; omitting it selects the first configured sender. to accepts one recipient string or an array. The result contains accepted, code, id, from, and to. accepted reports the SMTP server's acceptance response. The sender currently produces text/plain messages from text; it does not build HTML bodies or attachments.


Inspect Incoming Message Headers

Configure imap on the account, then initialize its separate connection. Inbox inspection uses EXAMINE and BODY.PEEK header fetching, so it does not mark returned messages as read:

                await connection.initIMAP()

                try {
                    const inbox = await connection.inbox({
                        unseen: true,
                        limit: 10
                    })

                    // inbox contains mailbox, total matching messages, and messages[].
                    // Each message includes uid, from, to, subject, date, messageId, size, and seen.
                } finally {
                    await connection.closeIMAP()
                }
            

unseen defaults to true; false searches all messages. limit defaults to 10 and accepts an integer from 1 to 100. The mailbox comes from the account profile, defaulting to INBOX. total counts search matches, while messages contains up to limit entries. This API reads selected headers and metadata, not message bodies or attachments.


SMTP and IMAP Transport

Profile setting Meaning
secure: 'TLS', starttls: false Connect with direct TLS and validate the server certificate
secure: 'TCP', starttls: true Open TCP, require the advertised STARTTLS capability, then upgrade before authentication
secure: 'TCP', starttls: false Plain SMTP transport; rejected for an IMAP account
secure: 'TLS', starttls: true Rejected: STARTTLS is an upgrade from TCP, not an extra step on direct TLS

SMTP supports AUTH PLAIN and LOGIN when advertised by the server. It repeats EHLO after a STARTTLS upgrade. IMAP uses LOGIN on an encrypted connection; OAuth authentication is not implemented. The configured common credentials apply to both protocols.


Update and Remove Accounts

Both actions identify the account by id or label and authorize it with key. An update can change label and connection profiles; partial SMTP/IMAP profile changes merge with the stored profile. Setting imap=false disables incoming-mail support. The README recommends removing and registering again when replacing an account's authentication identity.

                const updated = await mailer.updateAccount({
                    id: accountId,
                    key: ownerToken,
                    label: 'support-team',
                    imap: false
                })

                if (updated.errors) {
                    throw new Error(updated.message)
                }

                // When the account is no longer needed:
                const removed = await mailer.removeAccount({
                    id: accountId,
                    key: ownerToken
                })

                if (removed.errors) {
                    throw new Error(removed.message)
                }
            

These are the management request shapes. In the current release the SMTP cleanup mismatch described below can return an error after the persistent record has already changed. Check the resulting account state before retrying either action.


Current Development State

SMTP transport, read-only IMAP inspection, account authorization, and encrypted account storage are implemented. Two integration points still need correction: account-level SMTP send/close forwarding and SMTP cleanup call methods that are exposed on the returned session rather than the client instance; credential encryption uses a time-dependent Vault token, so persisted credentials cannot currently be reopened after initialization with a different token. Updates and removals can persist their changes before the cleanup failure is reported.

SMTP session references used above provide the direct send/close path. Account update, removal, detach cleanup, and persistent credential recovery require the corresponding integration fixes. No automatic credential migration is provided by the current implementation.

Planned work also includes a dedicated Vault credential-encryption subkey, IMAP MIME encoded-word decoding, message body and attachment parsing, IMAP OAuth authentication, and mailbox mutation operations.


Documentation

This page is the HTML adaptation of the pack's mailer README with configuration and API examples checked against the current implementation. Complete Staxis onboarding to request GitLab group access before opening the official source repository.