Inbox
Inbox gives your staff shared mailboxes for the messages people send you: the website contact form, email, WhatsApp, Messenger and Instagram. A message lands in a thread. Staff assign the thread, write internal notes, hide it from lower roles and reply. The reply goes out through the channel the message came in on. Every view and reply goes into an audit log. Closed threads are deleted after a retention period, and a contact's data can be exported or erased.
The package is @frigear-nu/inbox. Its mailboxes are owned by the platform or a team, and read by
staff. To send email or SMS without expecting an answer, use
Notify instead.
What you get
- Admin area (opt-in, needs Admin):
/admin/inbox, the thread list, filtered by mailbox, status, assignee and channel./admin/inbox/threads/:id, a thread with the conversation, a reply box and notes. It also has status, hide, the contact panel and an assignee picker that lists everyone with access to the thread. Contact details and email cc recipients needinbox:pii./admin/inbox/settings, the mailboxes and the channels connected to them.- An "Inbox" item in the admin sidebar, when Menu is installed.
- Channels:
form,email,whatsapp,messengerandinstagram. Modules add their own withextendInbox. - Webhooks:
POST /api/inbox/webhooks/email, andGETandPOST /api/inbox/webhooks/meta. - Dashboard items
inbox.unassignedandinbox.mineoncrew.homeand the hub's dashboard, when Dashboard is installed. - Push topic
inbox.messagefor the assignee, when Push is installed. - Retention: the Nitro task
inbox:retention, run every night.
- Admin, Menu and Widget: the staff pages and the sidebar item.
- Forms: the contact form channel.
- Teams: team mailboxes read by the team's leads.
- Push: notifications for the assignee.
- Dashboard: the two items.
Quick setup
Install Inbox
pnpm add @frigear-nu/inbox
Add it to nuxt.config.ts
export default defineNuxtConfig({
// Authorization brings the `role` grant kind the mailbox below uses.
modules: ['@nuxthub/core', '@frigear-nu/users', '@frigear-nu/authorization', '@frigear-nu/forms', '@frigear-nu/inbox'],
hub: { db: 'sqlite' },
inbox: {
mailboxes: [
{ key: 'support', name: { da: 'Support', en: 'Support' }, grants: [{ kind: 'role', role: 'coordinator' }] },
],
// Channel secrets are declared here, empty, and set from the environment.
secrets: { WHATSAPP_TOKEN: '' },
settings: { pages: { admin: true, adminThread: true, adminSettings: true } },
},
})
Set the webhook and channel secrets as environment variables, never in the config file:
NUXT_INBOX_EMAIL_WEBHOOK_SECRET=a-long-random-string
NUXT_INBOX_DOMAINS=inbox.example.org
NUXT_INBOX_META_APP_SECRET=the-meta-app-secret
NUXT_INBOX_META_VERIFY_TOKEN=a-token-you-also-enter-at-meta
NUXT_INBOX_SECRETS_WHATSAPP_TOKEN=the-whatsapp-access-token
Generate and commit a migration
Inbox adds seven tables. Generate a migration and commit it.
npx nuxt db generate
Connect the channels
Open /admin/inbox/settings as an admin and connect each channel to a mailbox:
- the contact form by its slug;
- the email address people write to;
- the WhatsApp phone number id;
- the Facebook page id;
- the Instagram account id.
/admin/inbox. A reply from the thread
page reaches the person by email.Options
Options go under the inbox key. The secrets also take environment variables, as above.
| Option | Type | Default | Purpose |
|---|---|---|---|
mailboxes | InboxMailboxSeed[] | [] | Mailboxes created on the first request when their key does not exist. They are never changed afterwards. |
channels | InboxChannelDefinition[] | [] | The host's own channels, the same as extendInbox. |
email.webhookSecret | string | none | The HMAC secret of the email webhook. Without it, the webhook answers 501 not_configured. |
email.domains | string[] | none | The inbox domains. NUXT_INBOX_DOMAINS (comma separated) replaces them at run time. |
email.inbound | { webhook?, cloudflare?, resend?, gmail?, imap? } | { webhook: true } | The built-in inbound email drivers to install. cloudflare also takes { authservIds, entry }, resend takes { webhookSecret, apiKey, apiBase }, gmail takes { clientEmail, privateKey, topic, audience, pushServiceAccount, apiBase, cron } and imap takes { cron }; the secrets are also set at run time (see each driver). |
email.outbound | 'cloudflare-binding' | 'resend' | 'ses' | 'cloudflare' | 'log' | Notify's driver | The Notify driver replies go out through, for inbox replies only. NUXT_INBOX_EMAIL_OUTBOUND sets it at run time. |
email.drivers | InboxEmailDriverDefinition[] | [] | The host's own inbound email drivers, the same as extendInbox's emailDrivers. |
meta.appSecret | string | none | The Meta app secret that X-Hub-Signature-256 is checked with. Without it, the Meta webhook answers 501 not_configured. |
meta.verifyToken | string | none | The verify token Meta's subscription check sends. Without it, the check answers 501 not_configured. |
meta.apiBase, meta.apiVersion | string | https://graph.facebook.com, v21.0 | The Graph API that replies go to. |
meta.timeoutMs | number | 10000 | How long a Graph API call may take. |
secrets | Record<string, string> | {} | Channel account secrets by secretRef. Declare each ref empty and set it with NUXT_INBOX_SECRETS_<REF>. |
shortLinks | boolean | true | Offer to send the links of a reply as short links, when Short links is installed. false turns it off. |
retention.days | number | false | 365 | Days a closed thread is kept when its mailbox sets none. false keeps them. |
retention.mode | 'delete' | 'anonymise' | 'delete' | Delete old threads, or keep them with their messages blanked. |
retention.cron | string | false | '30 3 * * *' | When inbox:retention runs. false registers it without a schedule. |
retention.batch | number | 500 | The most threads one run handles, shared fairly between the mailboxes. |
retention.tombstoneDays | number | 365 | Days the provider ids of messages retention removed are remembered, so a replayed webhook is not stored again. An erase's are kept for good. |
settings.pages.admin | string | boolean | off | The thread list. true is /admin/inbox. |
settings.pages.adminThread | string | boolean | off | The thread page. It must contain :id. |
settings.pages.adminSettings | string | boolean | off | Mailbox and channel settings. |
settings.dashboard | string | false | crew.home and the hub's | The dashboard the two items go on. A name puts them there only; false adds none. |
Retention. Each mailbox can set its own retentionDays. A mailbox without one uses retention.days. Inbox has no
retention table: a per-mailbox column and the module default cover it.
Permissions
Inbox registers these permissions with Authorization.
| Name | Who holds it | What it covers |
|---|---|---|
inbox:read | Every signed-in user (implicit) | Threads of the mailboxes the policy lets them read. |
inbox:reply | Every signed-in user (implicit) | Replies, notes and status, in the same mailboxes. |
inbox:assign | admin | Assigning threads. |
inbox:hide | admin | Hiding a thread from people below a role. |
inbox:manage | admin | Every mailbox; creating, editing and deleting mailboxes; erasing contacts. |
inbox:pii | admin (sensitive) | Contact email, phone and channel id; contact exports and erasure. |
inbox:channels | admin | Connecting channels and naming their secrets. |
inbox-audit:pii | admin (sensitive) | The audit log. |
Session only. Every inbox permission is sessionOnly: platform and team mailboxes hold outsiders' messages, so
they are never exposed to API tokens or OAuth apps, and every staff route answers a bearer with
403 session_required. There is no inbox scope.
The policy of inbox:read and inbox:reply allows:
- staff with
inbox:manage; - a team mailbox's leads;
- anyone the mailbox's grants admit.
Server
How mailboxes, threads and channels behave, and the utils other modules call.
Mailboxes
A mailbox has an owner: the platform, or a team (ownerType: 'team', ownerId the team id, checked through Teams'
teams:owner:resolve). Who reads it besides staff is a grant list (Auth's record audiences) in
grants: any one grant admits, such as { kind: 'role', role: 'coordinator' } (with
Authorization) or a team grant with a minimum role. A configured
mailbox whose grants name a kind no installed module registers stops the seeding, which is logged and retried.
- Never public, never everyone with an account. A mailbox holds outsiders' messages, so a
publicgrant and asigned-ingrant are refused (on create, on update and ininbox.mailboxes), and one stored anyway counts for nobody. - A platform mailbox must name who reads it. An empty list is refused for it. If a stored one is empty anyway, nobody but staff reads the mailbox: an empty list admits nobody.
- A team mailbox is read by the team's leads (
isTeamLeadof Teams). Its grants may add others. - Checked on write. An unknown kind, an invalid grant or a team or operation that does not exist is a
400(grantsValidate).
Hidden threads
POST .../hide with { role } sets hiddenBelow. From then on, only people who hold that global
role see the thread. Roles inherit along your role chain, so an admin who inherits coordinator sees threads hidden
below it. The role must be one the caller holds. Anyone else gets the same 404 as for an unknown thread, and the
thread is missing from their list. An assignee without the role is unassigned. { role: null } shows the thread
again.
Assignees
An assignee must be able to read and answer the thread themselves. The rule is evaluated for them, not
for the caller: they hold inbox:reply and the thread's hiddenBelow role, and they hold inbox:manage, lead the
team of a team mailbox, or are admitted by the mailbox's grants as themselves (grantsMatch with their own roles and teams). Anyone else is a
409 assignee_no_access (an unknown user is a 400).
The thread page's assignee picker lists those people: GET .../threads/:id/assignees evaluates the same rule for each
user, by name, and answers at most 50 (?q narrows by name). It looks at no more than 1,000 users per call, so on a
large user base search by name.
Channels
| Channel | Address | Inbound | Replies |
|---|---|---|---|
form | The form's slug | A listener on forms:submitted for forms with a form account | By email to the address the person gave, Reply-To the account's config.replyTo or the mailbox's email address (see Replies) |
email | The address people write to | The inbound email drivers | dispatchEmailNotification with the thread's reply address or the mailbox address as Reply-To, In-Reply-To and [ibt_...] in the subject (see Replies) |
whatsapp | The WhatsApp phone number id | GET and POST /api/inbox/webhooks/meta | The Graph API with the account's token |
messenger | The Facebook page id | The Meta webhook | The Graph API with the page access token |
instagram | The Instagram professional account id | The Meta webhook | The Graph API with the token |
Secrets never go into the database. A channel account's secretRef names a secret, such as WHATSAPP_TOKEN. The
server reads it from the runtime config only, inbox.secrets.WHATSAPP_TOKEN, never from process.env directly. A ref
is upper case letters, digits and _, so it can only name an inbox secret. A config key that looks like a secret is
refused. Set the value with an environment variable that overrides the runtime config:
NUXT_INBOX_SECRETS_<REF>, such asNUXT_INBOX_SECRETS_WHATSAPP_TOKEN. Nuxt only overrides keys that exist when the app is built, so declare each ref innuxt.config.tswith an empty value:inbox: { secrets: { WHATSAPP_TOKEN: '' } }.NUXT_INBOX_SECRETS, a JSON object of refs and values, such as{"WHATSAPP_TOKEN":"..."}. It adds refs that were not declared.
wrangler secret put NUXT_INBOX_SECRETS_WHATSAPP_TOKEN) and declare the ref empty in nuxt.config.ts as above. The
inbox reads the runtime config per request, where the Worker's secrets are applied.The contact form. Connect a form by its slug. Its answers are read from the fields name, email, phone,
subject and message. Change the keys with config.fields. Answers show the form's labels in the submission's
language, so a select shows its option's label, not its value. The thread is titled with the subject's label, or with
the text of a field shown only for that subject (an "Other, please specify" field with showIf on subject). The
message is followed by every other answered field as Label: value lines, so a submission that joins an open thread
keeps its subject. A form without a message field lists every answer.
Submissions only come in through Forms' own submit route, with the form's access rules, and the forms:submitted
hook: the inbox has no webhook for the form channel.
Short links in replies. With Short links installed, a reply that contains
http(s) links shows a Shorten links switch. It starts on for WhatsApp, Messenger and Instagram, where people read
links on a phone, and off for email and the contact form. A channel of your own sets its default with shortenLinks
on its registration. Staff can switch it for each reply. When it is on, the server swaps each link for the inbox's
short link of that URL (findOrCreateShortLink, owner inbox): one link per URL for the whole inbox, so the same URL
in another reply reuses it and its click counter adds up, and changing its target on /admin/short-links changes it
in every reply that sent it. The links never expire, so old replies keep working. The reply is stored as it was sent,
with the short links in it. Links that already are short links stay as they are. Without shortLinks.baseUrl or a site
URL there is no absolute short URL to send, and links go out as written; they also do when shortening fails. Clicks
are counted per link, not per reply or person: a short link has no subject that ties it to a thread.
Channels fail closed. Every inbound route needs its secret, and there is no unauthenticated default. Without
email.webhookSecret, meta.appSecret or meta.verifyToken, or a module channel's inboundSecret, the route answers
501 not_configured before it reads the request.
Email reaches the inbox through one or more inbound drivers. Replies go out through Notify. An email account is an
address connected to a mailbox at /admin/inbox/settings.
Inbox domains
An inbox domain is a domain whose mail all goes to the inbox, such as inbox.example.org. Set them with
email.domains or NUXT_INBOX_DOMAINS, a comma separated list that also replaces them at run time. The package has
no default. On an inbox domain:
- Replies carry a reply address. A reply from an account at
support@inbox.example.orggoes out withReply-To: support+ibt_...@inbox.example.org, the thread's own address. The answer finds its thread even when the person changed the subject or their client dropped the marker. - Unknown addresses bounce. An address on an inbox domain that no account has is unknown. A driver that can
bounces it (Cloudflare), the others answer
ignored.
The settings page warns about a mailbox that is answered by email (it has an email or contact form channel) but has no email address on an inbox domain.
NUXT_INBOX_DOMAINS=inbox.example.org,volunteer.example.org
Routing
Every inbound driver routes a recipient with inboxRouteRecipient(address), in this order:
- The email account with exactly this address.
- A plus address
local+<tag>@domainwhoselocal@domainis an account. A tag in the shape of a thread id (ibt_and 8 to 64 lower case letters or digits) is a thread hint. Any other tag routes to the account without a hint. - Any other address on an inbox domain is unknown. An address on another domain is not ours.
The recipients are to and cc (or the envelope recipient, for Cloudflare). Every email account among them gets the
message, so a mailbox that is only copied still receives it, and one email to two connected mailboxes is stored in each
(two threads). An account is reached once, however many of its addresses the email names.
Threading
Only an authenticated email joins an existing thread. It tries these threads in order, and the first that passes the checks wins:
- The thread its reply address names (
support+ibt_...@). - The thread of a stored message it answers:
In-Reply-To, thenReferencesfrom the newest back, matched against theemail:<Message-ID>provider ids of the same account, and against our own replies in the same mailbox when they went out with a Message-ID of ours (email:out:<Message-ID>, see Replies). - The
[ibt_...]marker in the subject. - The contact's latest email thread that is not closed.
Steps 1 to 3 check that the thread is in the same mailbox and that the sender is its contact or has the contact's email address. That is how an emailed answer to a contact form thread lands in that thread. A thread that fails the checks is skipped. A thread that retention or an erase anonymised is never joined: the answer starts a new thread, because a blanked thread never takes new content. An email that is not authenticated always starts a new thread, so a forged sender cannot write into someone else's conversation, whatever address, headers or subject it uses.
A channel whose sender address is a caller ID (SMS) sets callerId on the message: without being authenticated, it
joins the sender's latest open or pending thread on the same channel account, and nothing more (no named thread, no
rename, no account link).
Replies
A reply by email goes to the contact through Notify's dispatchEmailNotification:
Subject:Re: <subject> [ibt_...].Reply-To: the account'sconfig.replyTo, else its address. When that is on an inbox domain, the reply uses the thread's reply address on it instead. A contact form thread starts from the form account'sconfig.replyTo, else the mailbox's first enabled email account on an inbox domain, else its first enabled email account.In-Reply-ToandReferences: the Message-ID of the person's latest email in the thread, so their mail client files the reply with it. A contact form thread has none. Cloudflare Email Sending allows both headers.From: Notify'sfrom(NUXT_NOTIFY_EMAIL_FROM). Turn on Send replies from this address (config.sendFromAddress) on an email account to send from"<Mailbox name>" <address>instead; a contact form thread uses the setting of the email account above.Message-ID: the provider's own, unless the Notify driver reports the one it set. Notify'scloudflare-bindingdriver builds the message itself and does: the reply is then stored withemail:out:<Message-ID>, and an answer that names it inIn-Reply-ToorReferencesfinds the thread by its headers alone, a contact form thread too.
The driver of replies. Replies go out through Notify's driver (NUXT_NOTIFY_EMAIL_DRIVER). Set email.outbound
(NUXT_INBOX_EMAIL_OUTBOUND) to a built-in Notify driver to send only the inbox's replies through it, with Notify's
settings (from, credentials, binding name), while every other email of the app keeps Notify's driver:
NUXT_INBOX_EMAIL_OUTBOUND=cloudflare-binding
sendFromAddress. The provider Notify sends through (Resend, SES, Cloudflare
Email Sending) must have the address's domain verified for sending. Otherwise it refuses every reply, and the reply
fails with 502 delivery_failed.Cc. A reply copies (Notify's cc) the people that the contact's latest authenticated email in the thread copied, as
a reply-all would. The cc of an email that is not authenticated is kept and shown, but never sent to: a forged sender
cannot make your replies copy a list of strangers. Our own addresses are left out: every email account's address and
config.replyTo, any address on an inbox domain, the reply's Reply-To and From, Notify's sender and the contact's
own address. When that email copied nobody, the reply has no cc. Only valid email addresses are kept: a malformed Cc
entry is dropped from the inbound message and so never copied. The inbound cc is stored with the message, without the
mailbox's own address. The reply stores who it copied. The thread page shows both only to people with inbox:pii.
The reply address is checked the same way. A reply by email (an email or contact form thread) goes only to one
plain, valid address. A contact whose address is not one (a@x.org, b@y.org, a value with a line break) cannot be
answered by email: the reply is refused with 409 no_reply_address, as for a contact with no address.
Inbound drivers
Turn the built-in drivers on with email.inbound. Several can be on at once.
| Driver | Option | URL | Verified by | Sender authenticated when |
|---|---|---|---|---|
webhook | email.inbound.webhook (on by default) | POST /api/inbox/webhooks/email | X-Inbox-Signature with email.webhookSecret | The provider's verdict says so (authenticated) |
cloudflare | email.inbound.cloudflare | None: the cloudflare:email hook of the Worker | Cloudflare delivers it to the Worker | Cloudflare's Authentication-Results pass DMARC, or aligned DKIM or SPF, for the From domain |
resend | email.inbound.resend | POST /api/inbox/email/resend | The Svix signature with NUXT_INBOX_RESEND_WEBHOOK_SECRET | Resend reports DMARC or DKIM pass |
gmail | email.inbound.gmail | POST /api/inbox/email/gmail (Pub/Sub push), and the inbox:gmail task | Google's OIDC token on the push | Gmail's Authentication-Results (mx.google.com) pass DMARC, or aligned DKIM or SPF |
imap | email.inbound.imap | None: the inbox:imap task polls | The IMAP login | The server's Authentication-Results of the account's authservIds (none by default: unauthenticated) |
export default defineNuxtConfig({
inbox: {
email: {
domains: ['inbox.example.org'],
inbound: { webhook: true, cloudflare: true, resend: true },
},
},
})
Every driver stores a message once per Message-ID and channel account, and answers a redelivery as duplicate.
Control characters in subjects become spaces.
Files. The Cloudflare, Resend, Gmail and IMAP drivers store attachments in NuxtHub Blob
when the app has it, under inbox/email/<hash of the Message-ID>/, and keep the pathname on the message. Without Blob
only the file name, type and size are kept. Files of a message that is already stored, or that retention or an erase
removed, are not stored again. Retention and an erase delete the stored files with their messages. The
webhook keeps the metadata and the provider's url it was sent, never the bytes.
Cloudflare Email Routing
The app must run as a Worker with the cloudflare-module preset.
- Add each inbox domain to Cloudflare and turn on Email Routing for it.
- Under Routing rules, set the Catch-all address action to Send to a Worker and pick the app's Worker. To route single addresses instead, add a custom address per account.
- Set
NUXT_INBOX_DOMAINSand turn onemail.inbound.cloudflare.
Each recipient arrives on its own. An address that is not routed to an account is rejected with Unknown address,
and the sender gets a bounce. The raw message is parsed with postal-mime. Only the topmost Authentication-Results
header counts, and only when Cloudflare wrote it: headers further down came with the message. Its authserv-id is
mx.cloudflare.net; set others with email.inbound.cloudflare.authservIds or NUXT_INBOX_CLOUDFLARE_AUTHSERV_IDS
(comma separated). The message is then stored through the driver's own route in the same Worker, with a token that
lives only in the Worker's memory. Called from outside, that route answers 404.
Bounces need the inbox's Worker entry. Nitro 2's cloudflare-module entry runs the cloudflare:email hook in
waitUntil and returns at once, so Cloudflare has accepted the email before any hook could reject it. With the
Cloudflare driver on, the inbox builds the Worker from a small entry around the preset's own that waits for the hook,
so Unknown address reaches Cloudflare as a bounce. Nothing else of the preset changes. It is skipped (with a warning
at build time) when another module or the app replaced the entry, and turned off with
email.inbound.cloudflare.entry: false: unknown recipients are then accepted and dropped, with a log line.
Resend
- Add a receiving domain at Resend (or use your
*.resend.appaddress) and point its MX records at Resend. - Add a webhook for the
email.receivedevent with the URLhttps://<your app>/api/inbox/email/resend. - Set its signing secret as
NUXT_INBOX_RESEND_WEBHOOK_SECRET, and an API key that can read received emails asNUXT_INBOX_RESEND_API_KEY. Without both, the webhook answers 501not_configured. - Turn on
email.inbound.resend.
The webhook only names the email. The driver fetches it from the Resend API (GET /emails/receiving/:id) with its
text, headers and Resend's SPF, DKIM and DMARC verdicts, and its files when it reaches a mailbox. The driver answers:
- 401 for a bad signature, or a timestamp more than five minutes off;
- 502 when the Resend API fails, so Resend retries;
- 200 otherwise. An event other than
email.receivedisignored.
Google Workspace (Gmail)
The Gmail driver reads Google Workspace mailboxes through the Gmail API, so the mail stays in Gmail and the inbox gets
a copy. It runs on Workers and on Node: it uses fetch and WebCrypto only.
- A service account. In a Google Cloud project, turn on the Gmail API and Pub/Sub, create a service account and a
JSON key. Set
client_emailasNUXT_INBOX_GMAIL_CLIENT_EMAILandprivate_keyasNUXT_INBOX_GMAIL_PRIVATE_KEY(escaped\nline breaks are fine). - Domain-wide delegation. In the Workspace Admin console (Security > API controls > Domain-wide delegation),
add the service account's client id with the scope
https://www.googleapis.com/auth/gmail.readonly. The driver acts as each watched mailbox, read only. - A topic. Create a Pub/Sub topic, set it as
NUXT_INBOX_GMAIL_TOPIC(projects/<project>/topics/<topic>), and givegmail-api-push@system.gserviceaccount.comthe Pub/Sub Publisher role on it. - A push subscription on the topic, to
https://<your app>/api/inbox/email/gmail, with authentication on: pick a service account and an audience (the URL itself is fine). Set the audience asNUXT_INBOX_GMAIL_AUDIENCE, and that service account's email asNUXT_INBOX_GMAIL_PUSH_SERVICE_ACCOUNT(checked when set). - The accounts. Turn on
email.inbound.gmail, and connect each mailbox's address as an email account withconfig: { inbound: 'gmail' }. The address must be the Workspace user the driver acts as.
inbox: {
email: { inbound: { gmail: true } },
},
How it runs:
- Watches. The
inbox:gmailtask (email.inbound.gmail.cron, daily at15 4 * * *) callsusers.watchfor every Gmail account whose watch has less than two days left (a watch lasts seven days), then catches up on anything a push missed. An account takes in nothing before its first watch: run the task once after connecting one (Nitro'srunTask('inbox:gmail')), or wait for its next run. - Pushes. A push carries the mailbox and its new history id. The driver checks the OIDC token (Google's signature,
the audience, the service account), lists what was added to the inbox since the stored history id
(
users.history.list), fetches each new message raw (users.messages.get?format=raw) and stores it. Sent mail, drafts and spam are skipped. The history id is stored per account ininbox_email_cursors. - Answers. 501
not_configuredwithout the service account or the audience, 401 for a bad token, 200 once handled (an unknown mailbox isignored), 502 when the Gmail API fails, so Pub/Sub retries. A message is stored once per Message-ID, so a retry or a catch-up never stores it twice. - Recipients. A message is stored for the account it was fetched for (its
To/Ccplus addresses of it keep their thread hint). Other inbox accounts it names get it through their own mailbox. - The start. Mail older than the first watch is not imported. When Gmail no longer has the stored history (about a week without pushes or task runs), the driver starts over from now.
support@inbox.example.org. The mail then
arrives through the Cloudflare driver, and the original stays in Gmail. Replies need the same address to be on the
inbox domain to carry the thread's reply address.IMAP
The IMAP driver polls any IMAP mailbox with imapflow. It runs on Node and on Cloudflare Workers:
there it connects over cloudflare:sockets, which also handles STARTTLS.
- Turn on
email.inbound.imap. - Connect the address as an email account with
config.inbound: 'imap'and its connection inconfig.imap, and the password's name insecretRef. Set the password asNUXT_INBOX_SECRETS_<REF>: it never goes in the config or the database.
{
"inbound": "imap",
"imap": { "host": "imap.example.org", "port": 993, "secure": true, "user": "support@example.org", "mailbox": "INBOX", "authservIds": ["mx.example.org"] }
}
port defaults to 993 with secure (implicit TLS, the default) and 143 without (STARTTLS when the server offers it).
user defaults to the address, mailbox to INBOX.
The inbox:imap task (email.inbound.imap.cron, every five minutes) opens each mailbox read-only, and fetches the
messages with a UID above the last one it saw with BODY.PEEK[], so nothing is marked read or changed. It stores at most
50 messages per account and run, and keeps the last UID and the mailbox's UIDVALIDITY in inbox_email_cursors after
each one. The first poll of a mailbox, and the first after its UIDVALIDITY changed, imports nothing and starts after the
newest message. A failing account is logged; the others still run.
Authentication comes from the server's own Authentication-Results header, when the account names its authserv-ids
in config.imap.authservIds (Gmail and Workspace: mx.google.com). Without them every message is unauthenticated and
starts a new thread: set them for answers to thread.
The signed JSON webhook
Point any other provider's inbound webhook (Postmark, Mailgun, SendGrid, ...) at POST /api/inbox/webhooks/email
and map its payload to this JSON:
{
"messageId": "<CAF1234@mail.example.org>",
"from": { "email": "kari@example.org", "name": "Kari Nordmann" },
"to": "support@example.com",
"cc": [{ "email": "ola@example.org", "name": "Ola" }],
"subject": "Where is my ticket?",
"text": "Hello, I never got my ticket.",
"html": "<p>Hello, …</p>",
"inReplyTo": "<reply-1@example.com>",
"references": ["<first@mail.example.org>", "<reply-1@example.com>"],
"attachments": [{ "filename": "ticket.pdf", "contentType": "application/pdf", "size": 1200, "url": "https://…" }],
"authenticated": true
}
inReplyTo and references are optional. references is one header value or a list. Instead of these two fields,
you can pass the raw headers in headers, an object keyed by header name. Only In-Reply-To and References are read
from it.
authenticated. Set it to true only when the email passed SPF, DKIM or
DMARC at your provider; inbound providers report it, for example in an Authentication-Results header. An email
without it is treated as unverified: it always starts a new thread and never renames a contact.Sign the raw body with X-Inbox-Signature: sha256=<HMAC-SHA256 of the body with email.webhookSecret>.
- Wrong signature: 401.
- Larger than 1 MB: 413
payload_too_large(the same limit applies to the Meta and module webhooks). - Not an email: 400.
- Every other case: 200, so the provider stops retrying.
- A new message:
{ status: 'received', threadId, messageId }. - A redelivery:
{ status: 'duplicate' }. A message is stored once permessageIdand channel account. - An address no account has:
{ status: 'ignored', reason: 'no_account' }. - A message retention or an erase removed:
{ status: 'ignored', reason: 'removed' }(see Replays below).
- A new message:
The answer describes the first account's delivery. When more than one account matched, deliveries lists each, with
its mailboxId.
A driver of your own
A driver is a server file that default-exports defineInboxEmailDriver (from @frigear-nu/inbox/utils). It has a
name and a handler, a setup, or both:
handleris mounted atPOST /api/inbox/email/<name>. Verify the request there first.setup(nitroApp)runs once in a Nitro plugin, to register runtime hooks.
Map what the provider sends to the payload above and hand it to inboxIngestEmail(event, payload, options?). It routes,
threads and stores the email like the built-in drivers. Register the driver with email.drivers or a module's
extendInbox(nuxt, { emailDrivers }). A later driver with the same name replaces an earlier one.
import { defineInboxEmailDriver } from '@frigear-nu/inbox/utils'
export default defineInboxEmailDriver({
name: 'acme',
async handler(event) {
const raw = await inboxReadRawBody(event)
// ...verify Acme's signature over `raw`, then map its JSON to the inbox payload.
const payload = toInboxEmailPayload(JSON.parse(raw))
return (await inboxIngestEmail(event, payload)).response
},
})
inbox: {
email: { drivers: [{ name: 'acme', driver: fileURLToPath(new URL('./server/inbox/acme-mail.ts', import.meta.url)) }] },
},
Senders and contacts
Each inbound message records the contact who sent it (contactId on the message) and whether it was authenticated.
An emailed answer filed in a contact form thread belongs to the form's contact, but its sender is the email contact;
export and erase find it by that (see Privacy).
Contact form senders are verified only by their own address. Anybody can type someone else's email address into a
form, so a submission counts as verified only when a signed-in user typed their own account email. Then it may join
that contact's open thread, rename it and link it to the account (userId). Anything else, a submission without a
signed-in user or a signed-in user who typed another address, is unverified: it always starts a new thread, never
renames the contact and never sets its userId. A signed-in user who typed no address is keyed on their account
(user:<id>). A typed value that is not one valid address is not stored as the contact's email.
Meta: WhatsApp, Messenger and Instagram
One webhook URL serves all three: /api/inbox/webhooks/meta.
GETis Meta's subscription check. It echoeshub.challengewhenhub.verify_tokenmatchesmeta.verifyToken, and answers 403 otherwise. The token is compared in constant time: both sides are HMAC-ed with a random key and the digests compared, so neither its length nor where it differs shows in the timing.POSTis checked againstX-Hub-Signature-256with the app secret.- A wrong signature gets a 401.
- Otherwise it always answers 200 with counts:
{ received, duplicates, ignored, failed }. Meta retries and backs off on errors, so a duplicate or an unknown account never gets an error. - Each message goes to the account at the phone number id, page id or Instagram id it was sent to. Meta's signature vouches for the sender, so a message joins the contact's latest thread that is not closed.
- Read and delivery statuses and echoes of your own replies are skipped. Media arrives as a placeholder with the media id or link.
Replies call the Graph API with fetch and stop after meta.timeoutMs. When delivery fails, nothing is stored and
the caller gets a 502 delivery_failed. A missing token gives a 409 channel_not_configured.
Meta prerequisites. These take weeks, so start early:
- Business verification of your Meta Business account.
- A WhatsApp Business number in the Cloud API, and its phone number id. WhatsApp only delivers free text within
24 hours of the person's last message. Outside that window it needs an approved template, so a late reply fails
with
delivery_failed. - App review of a Meta app for the permissions that read and send messages:
- Messenger:
pages_messaging; - Instagram:
instagram_manage_messages; - WhatsApp:
whatsapp_business_messaging.
- Messenger:
- A webhook subscription in the app: the URL above, your verify token, and the
messagesfields of the WhatsApp, Page and Instagram products. - A long-lived token per account (a system user token for WhatsApp, a page access token for Messenger and
Instagram), set as
NUXT_INBOX_SECRETS_<REF>with the ref declared ininbox.secrets.
A channel of your own
A module adds a channel with extendInbox from @frigear-nu/inbox/utils. The adapter file default-exports
defineInboxChannel:
import { extendInbox } from '@frigear-nu/inbox/utils'
extendInbox(nuxt, {
channels: [{ id: 'acme.sms', label: { da: 'SMS', en: 'Text message' }, icon: 'i-lucide-message-square', adapter: resolver.resolve('./runtime/inbox/sms'), shortenLinks: true }],
})
import { z } from 'zod'
import { defineInboxChannel, secretsEqual } from '@frigear-nu/inbox/utils'
const smsWebhook = z.object({ id: z.string(), from: z.string(), to: z.string(), text: z.string() })
export default defineInboxChannel({
id: 'acme.sms',
// The `inbox.secrets` entry the webhook is verified with. Declare it empty and set NUXT_INBOX_SECRETS_ACME_SMS_WEBHOOK.
inboundSecret: 'ACME_SMS_WEBHOOK',
// POST /api/inbox/webhooks/acme.sms: verify the request with the secret, then return the messages in it. The inbox
// has read the body already, within its 1 MB limit, and passes it as `rawBody`.
async inbound(event, { secret, rawBody }) {
if (!(await secretsEqual(getRequestHeader(event, 'x-acme-token') ?? '', secret))) {
throw createError({ statusCode: 401, statusMessage: 'Bad token' })
}
const body = smsWebhook.parse(JSON.parse(rawBody))
// `authenticated`: the provider vouches for the sender, so the message may join the sender's open thread.
return [{ address: body.to, contact: { externalId: body.from, phone: body.from }, externalId: body.id, body: body.text, authenticated: true }]
},
// Deliver a reply; throw to fail it (nothing is stored then).
async send({ contact, message, secret }) {
const sent = await $fetch<{ id: string }>('https://sms.example/send', { method: 'POST', headers: { authorization: `Bearer ${secret}` }, body: { to: contact.phone, text: message.body } })
return { externalId: sent.id }
},
})
send may also return cc, the email addresses it copied: they are stored on the reply (invalid ones are dropped)
and shown with inbox:pii.
An adapter with inbound must name its inboundSecret, an inbox.secrets entry, and verify the request with it
(ctx.secret). Until that secret is set, the webhook answers 501 not_configured and never calls inbound, so a channel
is never open by default. The inbox reads the body before it calls inbound, at most 1 MB whether or not the request
declares a content-length (413 payload_too_large otherwise), and passes it as ctx.rawBody: verify a signature
over it and parse it rather than reading the request again. A message without authenticated: true always starts a new thread. A registration with the
id of a built-in channel replaces it, so a host can swap an adapter.
Privacy
- Audit log. These go in the log, with who did them:
- views (once per person and thread in 15 minutes);
- replies, notes, assignments, status changes and hiding;
- exports, erasures and retention runs.
GET .../auditlists only the entries whose subject the caller could see, as in the thread list. A thread's entries need its mailbox and itshiddenBelowrole (a deleted thread's, the mailbox recorded with the entry). A retention run needs its mailbox. An export or erase needs at least one of the contact's threads. - One person, several contacts. A contact is one identity on one channel, so a person who used the contact form
and then answered by email is two contacts, and the email answer sits in the form contact's thread. Export and erase
therefore cover the contact, every other contact with the same email address (
relatedin the export), and the messages any of them sent in other contacts' threads (found by the message's sending contact). - Export (
GET .../contacts/:id/export) returns the details of the contact and its related contacts, every message sent or received in their threads, without internal notes, and from other contacts' threads only the messages they sent there. A partial export would answer an access request incompletely, so the caller must see every one of those threads, as for an erase: mailboxes they read, and no thread hidden below a role they lack. A contact none of whose threads they see is a 404. A contact with a thread hidden from them is refused with a 409contact_threads_hidden, and nothing of the contact is returned: someone who sees all of the threads exports it. - Erase (
POST .../contacts/:id/erase) removes the name, email, phone and channel id of the contact and its related contacts. Every thread of theirs is closed and its messages blanked: bodies, attachments, cc recipients and provider ids (erased:<id>). The messages they sent in other contacts' threads are blanked the same way, and those threads' previews refreshed. The threads stay, empty, as a record that something was answered. The answer countsthreads,messages(in other threads) andcontacts. A new message from the same person starts a new contact.- All or nothing. The contact's details belong to all their threads, so the caller must see every one of them. A
contact with a thread hidden from the caller is refused with a 409
contact_threads_hidden, and nothing is erased: someone who sees all of the threads erases the contact.
- All or nothing. The contact's details belong to all their threads, so the caller must see every one of them. A
contact with a thread hidden from the caller is refused with a 409
- Replays. Webhook signatures carry no time, and an email payload has no reliable one, so a replayed request
cannot be judged by its age. Instead, when retention or an erase removes a message, its provider id is kept as a
tombstone: a SHA-256 of the channel account and the provider id, never the id itself, with the id of the contact who
sent it. A webhook that delivers it again answers
ignored(reason: 'removed') and stores nothing.- Retention's tombstones are pruned by the retention run
retention.tombstoneDays(365) after the removal. A replay after that is stored as a new message. - An erase's tombstones are kept for good, and an erase also keeps the tombstones of what retention removed of the person earlier: nothing erased comes back, however late the replay.
- Retention's tombstones are pruned by the retention run
- Form submissions and their files are stored by Forms, not by the inbox, and are erased there. The inbox keeps only the submission's text and the files' names and Blob pathnames.
- Export and erase are session only, like every inbox route: no API token can call them.
- Retention runs as the task
inbox:retention, every night at 03:30 unlessretention.cronsays otherwise.- It handles closed threads whose last message is older than their mailbox keeps them.
deleteremoves them with their messages, and contacts left without a thread or a message go too.anonymisekeeps them, closed, with their messages blanked as on erase. A contact left with only anonymised threads (their own and the ones they wrote in) is erased.- A run handles at most
retention.batchthreads, and deletes in chunks of 90 ids to stay within D1's limits. A backlog is worked off over several nights. - The batch is shared fairly: every mailbox with a retention period first gets an equal share, and what the others
left goes to the mailboxes with more to do, so one busy mailbox never starves the rest. The result says
more: truewhen a mailbox had more than the run could handle. - It also prunes retention's tombstones older than
retention.tombstoneDays(an erase's stay). - On Cloudflare the cron is added to
wrangler.jsonfor you. - Run it by hand with
runTask('inbox:retention', { payload: { now, mode, batch } }).
Dashboard items
With Dashboard installed and the thread page on, Inbox adds two items to the dashboard
named by settings.dashboard (by default crew.home and the hub's dashboard). Both need inbox:read, show on the
web only and read GET /api/admin/inbox/summary. They render nothing for someone who reads no mailbox. Each is a stat
card two columns wide, without a label of its own: the item's title is its heading.
| Item | Order | Shows |
|---|---|---|
inbox.unassigned | 80 | Open threads nobody is assigned to, with a link to the filtered list. |
inbox.mine | 81 | Open threads assigned to me, with a link to the filtered list. |
Texts are under inbox.dashboard.
Push topic
Inbox registers the topic inbox.message with Notify (push on by
default, email off, no SMS). When a message comes in on a thread with an assignee, the assignee hears about it through
notifyUser, with a link to the thread page, in the assignee's language (users.locale, English without one). The
text names neither the sender nor the message. An assignee who can no longer read and answer the thread (they lost
the mailbox's grant, inbox:reply or the role it is hidden below) hears nothing; the thread keeps them as its
assignee until someone reassigns it. The push reaches phones
with Push installed, and the assignee can turn the email on (or the push off) on the
account page of Preferences.
Server utils
Server utils for modules:
| Util | What it does |
|---|---|
inboxIngestEmail(event, payload, { recipients?, attachments? }) | Stores an inbound email for every mailbox it reaches: routes the recipients, threads and stores it. What every inbound email driver calls. Answers { response, deliveries, unknown }. |
inboxRouteRecipient(address) | Where an email to address goes: { kind: 'account', account, threadId }, unknown (an inbox domain address nobody has) or foreign. |
inboxDomains() | The inbox domains, read per request. |
inboxReceive(event, channel, message, account?) | Stores one InboxInboundMessage: finds the account, the contact and the thread, stores the message once per provider id and channel account (never one that retention or an erase removed) and fires the hooks. |
inboxRunRetention({ now?, mode?, batch? }) | One retention run, as the task does it. |
inboxDeliverRawEmail({ driver, raw, recipients, authservIds, event? }) | Parses a raw RFC 5322 email, stores its files and stores it, from a request or (through the driver's route) from a task. For a driver that receives raw mail. |
inboxGmailRun(), inboxImapRun({ limit? }) | One run of the inbox:gmail and inbox:imap tasks. |
inboxEraseContact(contactId) | Erases a contact with its related contacts (same email address) and blanks their messages, also those they sent in other contacts' threads. |
setInboxTeamLeadResolver(fn) | Decides who leads a team mailbox. Teams sets it when installed. |
App
The pages use the UI building blocks. Composables, auto-imported:
| Composable | What it does |
|---|---|
useInboxThreadActions() | setStatus, assign, hide, exportContact, eraseContact, menu(thread). |
useInboxMailboxActions() | create, edit, remove, menu(mailbox). |
useInboxChannelActions() | create, edit, toggle, remove, menu(account). |
useInboxLinks() | Locale-aware links to the staff pages. |
Thread actions of other modules
The thread page renders the inbox.thread.actions Widget area in the contact card (not for
an erased contact). Another module adds a button there with extendWidgets(nuxt, 'inbox.thread.actions', { component, permission }), without depending on inbox. Each widget gets InboxThreadActionContext as props: threadId, contact
(details only with inbox:pii; userId is the account of a verified contact) and onChanged, which refreshes the page.
Crew's Add to crew is one. Widget is a required module of
inbox for this.
Hooks
Your app answers these Nitro hooks from a server plugin (server/plugins/*.ts).
| Hook | Context | When |
|---|---|---|
inbox:message:received | { event, thread, message } | A message came in on a channel and was stored. A duplicate fires nothing. |
inbox:message:sent | { event, thread, message } | A reply went out and was stored. Notes fire nothing. |
inbox:thread:assigned | { event, thread, assigneeId, previous } | A thread got another assignee (null unassigns). |
inbox:thread:status-changed | { event, thread, from, to } | Staff changed the status, or a message reopened a pending or closed thread. |
inbox:thread:linked | { event, threadId, actorId, module, kind, label?, url?, userId? } | Another module did something for the thread's person from the thread. Inbox listens itself: it writes a linked audit entry when actorId can read and answer the thread. Call it by name (useNitroApp().hooks.callHook); nothing listens without inbox. |
Routes
Path builders come from @frigear-nu/inbox/api (inboxApi). A thread the caller may not read answers the same 404
as an unknown one.
| Route | Who | What |
|---|---|---|
GET /api/admin/inbox/summary | inbox:read | Unassigned and own open threads, for the dashboard items. |
GET, POST /api/admin/inbox/mailboxes | inbox:read, inbox:manage | The mailboxes the caller reads; creates one. |
GET, PATCH, DELETE /api/admin/inbox/mailboxes/:id | inbox:read, inbox:manage | One mailbox. Deleting one with threads is a 409 mailbox_not_empty. |
GET /api/admin/inbox/threads | inbox:read | Paginated threads, ?mailbox&status&assignee&channel&q. status defaults to active (open or pending); all lists every status. assignee is me, none or a user id. |
GET /api/admin/inbox/threads/:id | inbox:read | The thread, its messages and notes, and what the caller may do. In the audit log. |
PATCH /api/admin/inbox/threads/:id | inbox:reply (status), inbox:assign (assignee) | Changes the status or the assignee. |
GET /api/admin/inbox/threads/:id/assignees | inbox:assign | Up to 50 people who could be assigned the thread, ?q by name. |
POST /api/admin/inbox/threads/:id/messages | inbox:reply | Replies through the thread's channel, { body, status?, shortenLinks? }. |
POST /api/admin/inbox/threads/:id/notes | inbox:reply | An internal note. |
POST /api/admin/inbox/threads/:id/hide | inbox:hide | { role }: hides the thread below a role, or shows it again. |
GET, POST /api/admin/inbox/channels | inbox:channels | Channel accounts. |
PATCH, DELETE /api/admin/inbox/channels/:id | inbox:channels | One channel account. |
GET /api/admin/inbox/email | inbox:channels | The inbox domains and the installed inbound email drivers. |
GET /api/admin/inbox/audit | inbox-audit:pii | The audit log entries the caller may see, ?threadId&contactId&action. |
GET /api/admin/inbox/contacts/:id/export | inbox:pii | Everything stored about a contact, without internal notes. A 409 contact_threads_hidden when a thread of theirs is hidden from the caller. |
POST /api/admin/inbox/contacts/:id/erase | inbox:manage and inbox:pii | Erases the contact: details removed, messages blanked, threads kept. A 409 contact_threads_hidden when a thread of theirs is hidden from the caller. |
POST /api/inbox/webhooks/email | The HMAC signature | Inbound email (the webhook driver). |
POST /api/inbox/email/:driver | The driver's check | The webhook of an inbound email driver with a handler (resend: the Svix signature, gmail: Google's OIDC token). 501 not_configured without its secret, 404 for a driver without a handler (cloudflare and imap only take the server's own requests). |
GET, POST /api/inbox/webhooks/meta | The verify token, X-Hub-Signature-256 | WhatsApp, Messenger and Instagram. |
POST /api/inbox/webhooks/:channel | The channel's check with its inboundSecret | A module channel with an inbound reader. 501 not_configured without the secret. |
Database
Tables the module adds. Generate and commit a migration after installing.
| Table | What it holds |
|---|---|
inbox_mailboxes | id (ibx_), key (unique), ownerType, ownerId, name, grants (JSON, [] by default), retentionDays. |
inbox_channel_accounts | id (ica_), mailboxId, channel, address (unique per channel), config, secretRef, enabled. |
inbox_contacts | id (icn_), channel, externalId (unique per channel), name, email, phone, userId, erasedAt. |
inbox_threads | id (ibt_), mailboxId, contactId, channelAccountId, channel, subject, searchText (the subject folded for search), status, assigneeId, hiddenBelow, preview, lastMessageAt, anonymisedAt. |
inbox_messages | id (ibm_), threadId, direction (in, out, note), authorId, body, attachments, cc, channelAccountId, externalId (<channel>:<provider id>, unique per channelAccountId), contactId (the sender of an inbound message, indexed), authenticated, createdAtMs. |
inbox_audit | id (iba_), threadId, mailboxId and contactId (all indexed), actorId, action, data. |
inbox_tombstones | key (a SHA-256 of a channel account and a provider id that was removed), contactId (who sent it, indexed), permanent (written or kept by an erase: never pruned), createdAt. |
inbox_email_cursors | key (<driver>:<channel account id>), channelAccountId (deleted with the account), driver, state (the Gmail history id and watch expiry, or the IMAP UIDVALIDITY and last UID), updatedAt. |
Translations
Override any string in your app's i18n/locales/<code>.json, under the inbox key. Inbox ships Danish and English.
Next steps
- Record audiences – the grant lists that say who reads a mailbox.
- Teams – the teams whose leads read a team mailbox.
- Forms – the forms the contact form channel reads.
- Notify – the email driver replies go out through.