add a webapi and webhooks for a simple http/json-based api

for applications to compose/send messages, receive delivery feedback, and
maintain suppression lists.

this is an alternative to applications using a library to compose messages,
submitting those messages using smtp, and monitoring a mailbox with imap for
DSNs, which can be processed into the equivalent of suppression lists. but you
need to know about all these standards/protocols and find libraries. by using
the webapi & webhooks, you just need a http & json library.

unfortunately, there is no standard for these kinds of api, so mox has made up
yet another one...

matching incoming DSNs about deliveries to original outgoing messages requires
keeping history of "retired" messages (delivered from the queue, either
successfully or failed). this can be enabled per account. history is also
useful for debugging deliveries. we now also keep history of each delivery
attempt, accessible while still in the queue, and kept when a message is
retired. the queue webadmin pages now also have pagination, to show potentially
large history.

a queue of webhook calls is now managed too. failures are retried similar to
message deliveries. webhooks can also be saved to the retired list after
completing. also configurable per account.

messages can be sent with a "unique smtp mail from" address. this can only be
used if the domain is configured with a localpart catchall separator such as
"+". when enabled, a queued message gets assigned a random "fromid", which is
added after the separator when sending. when DSNs are returned, they can be
related to previously sent messages based on this fromid. in the future, we can
implement matching on the "envid" used in the smtp dsn extension, or on the
"message-id" of the message. using a fromid can be triggered by authenticating
with a login email address that is configured as enabling fromid.

suppression lists are automatically managed per account. if a delivery attempt
results in certain smtp errors, the destination address is added to the
suppression list. future messages queued for that recipient will immediately
fail without a delivery attempt. suppression lists protect your mail server
reputation.

submitted messages can carry "extra" data through the queue and webhooks for
outgoing deliveries. through webapi as a json object, through smtp submission
as message headers of the form "x-mox-extra-<key>: value".

to make it easy to test webapi/webhooks locally, the "localserve" mode actually
puts messages in the queue. when it's time to deliver, it still won't do a full
delivery attempt, but just delivers to the sender account. unless the recipient
address has a special form, simulating a failure to deliver.

admins now have more control over the queue. "hold rules" can be added to mark
newly queued messages as "on hold", pausing delivery. rules can be about
certain sender or recipient domains/addresses, or apply to all messages pausing
the entire queue. also useful for (local) testing.

new config options have been introduced. they are editable through the admin
and/or account web interfaces.

the webapi http endpoints are enabled for newly generated configs with the
quickstart, and in localserve. existing configurations must explicitly enable
the webapi in mox.conf.

gopherwatch.org was created to dogfood this code. it initially used just the
compose/smtpclient/imapclient mox packages to send messages and process
delivery feedback. it will get a config option to use the mox webapi/webhooks
instead. the gopherwatch code to use webapi/webhook is smaller and simpler, and
developing that shaped development of the mox webapi/webhooks.

for issue #31 by cuu508
This commit is contained in:
Mechiel Lukkien
2024-04-15 21:49:02 +02:00
parent 8bec5ef7d4
commit 09fcc49223
87 changed files with 15556 additions and 1306 deletions

View File

@ -5,6 +5,7 @@ package webaccount
import (
"archive/tar"
"archive/zip"
"bytes"
"compress/gzip"
"context"
cryptorand "crypto/rand"
@ -15,9 +16,11 @@ import (
"io"
"log/slog"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
_ "embed"
@ -30,8 +33,12 @@ import (
"github.com/mjl-/mox/mlog"
"github.com/mjl-/mox/mox-"
"github.com/mjl-/mox/moxvar"
"github.com/mjl-/mox/queue"
"github.com/mjl-/mox/smtp"
"github.com/mjl-/mox/store"
"github.com/mjl-/mox/webapi"
"github.com/mjl-/mox/webauth"
"github.com/mjl-/mox/webhook"
)
var pkglog = mlog.New("webaccount", nil)
@ -414,7 +421,7 @@ func (Account) SetPassword(ctx context.Context, password string) {
// Account returns information about the account.
// StorageUsed is the sum of the sizes of all messages, in bytes.
// StorageLimit is the maximum storage that can be used, or 0 if there is no limit.
func (Account) Account(ctx context.Context) (account config.Account, storageUsed, storageLimit int64) {
func (Account) Account(ctx context.Context) (account config.Account, storageUsed, storageLimit int64, suppressions []webapi.Suppression) {
log := pkglog.WithContext(ctx)
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
@ -439,16 +446,19 @@ func (Account) Account(ctx context.Context) (account config.Account, storageUsed
xcheckf(ctx, err, "get disk usage")
})
return accConf, storageUsed, storageLimit
suppressions, err = queue.SuppressionList(ctx, reqInfo.AccountName)
xcheckf(ctx, err, "list suppressions")
return accConf, storageUsed, storageLimit, suppressions
}
// AccountSaveFullName saves the full name (used as display name in email messages)
// for the account.
func (Account) AccountSaveFullName(ctx context.Context, fullName string) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
_, ok := mox.Conf.Account(reqInfo.AccountName)
if !ok {
xcheckf(ctx, errors.New("not found"), "looking up account")
}
err := mox.AccountFullNameSave(ctx, reqInfo.AccountName, fullName)
err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
acc.FullName = fullName
})
xcheckf(ctx, err, "saving account full name")
}
@ -457,25 +467,29 @@ func (Account) AccountSaveFullName(ctx context.Context, fullName string) {
// error is returned. Otherwise newDest is saved and the configuration reloaded.
func (Account) DestinationSave(ctx context.Context, destName string, oldDest, newDest config.Destination) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
accConf, ok := mox.Conf.Account(reqInfo.AccountName)
if !ok {
xcheckf(ctx, errors.New("not found"), "looking up account")
}
curDest, ok := accConf.Destinations[destName]
if !ok {
xcheckuserf(ctx, errors.New("not found"), "looking up destination")
}
if !curDest.Equal(oldDest) {
xcheckuserf(ctx, errors.New("modified"), "checking stored destination")
}
err := mox.AccountSave(ctx, reqInfo.AccountName, func(conf *config.Account) {
curDest, ok := conf.Destinations[destName]
if !ok {
xcheckuserf(ctx, errors.New("not found"), "looking up destination")
}
if !curDest.Equal(oldDest) {
xcheckuserf(ctx, errors.New("modified"), "checking stored destination")
}
// Keep fields we manage.
newDest.DMARCReports = curDest.DMARCReports
newDest.HostTLSReports = curDest.HostTLSReports
newDest.DomainTLSReports = curDest.DomainTLSReports
// Keep fields we manage.
newDest.DMARCReports = curDest.DMARCReports
newDest.HostTLSReports = curDest.HostTLSReports
newDest.DomainTLSReports = curDest.DomainTLSReports
err := mox.DestinationSave(ctx, reqInfo.AccountName, destName, newDest)
// Make copy of reference values.
nd := map[string]config.Destination{}
for dn, d := range conf.Destinations {
nd[dn] = d
}
nd[destName] = newDest
conf.Destinations = nd
})
xcheckf(ctx, err, "saving destination")
}
@ -491,3 +505,159 @@ func (Account) ImportAbort(ctx context.Context, importToken string) error {
func (Account) Types() (importProgress ImportProgress) {
return
}
// SuppressionList lists the addresses on the suppression list of this account.
func (Account) SuppressionList(ctx context.Context) (suppressions []webapi.Suppression) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
l, err := queue.SuppressionList(ctx, reqInfo.AccountName)
xcheckf(ctx, err, "list suppressions")
return l
}
// SuppressionAdd adds an email address to the suppression list.
func (Account) SuppressionAdd(ctx context.Context, address string, manual bool, reason string) (suppression webapi.Suppression) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
addr, err := smtp.ParseAddress(address)
xcheckuserf(ctx, err, "parsing address")
sup := webapi.Suppression{
Account: reqInfo.AccountName,
Manual: manual,
Reason: reason,
}
err = queue.SuppressionAdd(ctx, addr.Path(), &sup)
if err != nil && errors.Is(err, bstore.ErrUnique) {
xcheckuserf(ctx, err, "add suppression")
}
xcheckf(ctx, err, "add suppression")
return sup
}
// SuppressionRemove removes the email address from the suppression list.
func (Account) SuppressionRemove(ctx context.Context, address string) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
addr, err := smtp.ParseAddress(address)
xcheckuserf(ctx, err, "parsing address")
err = queue.SuppressionRemove(ctx, reqInfo.AccountName, addr.Path())
if err != nil && err == bstore.ErrAbsent {
xcheckuserf(ctx, err, "remove suppression")
}
xcheckf(ctx, err, "remove suppression")
}
// OutgoingWebhookSave saves a new webhook url for outgoing deliveries. If url
// is empty, the webhook is disabled. If authorization is non-empty it is used for
// the Authorization header in HTTP requests. Events specifies the outgoing events
// to be delivered, or all if empty/nil.
func (Account) OutgoingWebhookSave(ctx context.Context, url, authorization string, events []string) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
if url == "" {
acc.OutgoingWebhook = nil
} else {
acc.OutgoingWebhook = &config.OutgoingWebhook{URL: url, Authorization: authorization, Events: events}
}
})
if err != nil && errors.Is(err, mox.ErrConfig) {
xcheckuserf(ctx, err, "saving account outgoing webhook")
}
xcheckf(ctx, err, "saving account outgoing webhook")
}
// OutgoingWebhookTest makes a test webhook call to urlStr, with optional
// authorization. If the HTTP request is made this call will succeed also for
// non-2xx HTTP status codes.
func (Account) OutgoingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Outgoing) (code int, response string, errmsg string) {
log := pkglog.WithContext(ctx)
xvalidURL(ctx, urlStr)
log.Debug("making webhook test call for outgoing message", slog.String("url", urlStr))
var b bytes.Buffer
enc := json.NewEncoder(&b)
enc.SetIndent("", "\t")
enc.SetEscapeHTML(false)
err := enc.Encode(data)
xcheckf(ctx, err, "encoding outgoing webhook data")
code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
if err != nil {
errmsg = err.Error()
}
log.Debugx("result for webhook test call for outgoing message", err, slog.Int("code", code), slog.String("response", response))
return code, response, errmsg
}
// IncomingWebhookSave saves a new webhook url for incoming deliveries. If url is
// empty, the webhook is disabled. If authorization is not empty, it is used in
// the Authorization header in requests.
func (Account) IncomingWebhookSave(ctx context.Context, url, authorization string) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
if url == "" {
acc.IncomingWebhook = nil
} else {
acc.IncomingWebhook = &config.IncomingWebhook{URL: url, Authorization: authorization}
}
})
if err != nil && errors.Is(err, mox.ErrConfig) {
xcheckuserf(ctx, err, "saving account incoming webhook")
}
xcheckf(ctx, err, "saving account incoming webhook")
}
func xvalidURL(ctx context.Context, s string) {
u, err := url.Parse(s)
xcheckuserf(ctx, err, "parsing url")
if u.Scheme != "http" && u.Scheme != "https" {
xcheckuserf(ctx, errors.New("scheme must be http or https"), "parsing url")
}
}
// IncomingWebhookTest makes a test webhook HTTP delivery request to urlStr,
// with optional authorization header. If the HTTP call is made, this function
// returns non-error regardless of HTTP status code.
func (Account) IncomingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Incoming) (code int, response string, errmsg string) {
log := pkglog.WithContext(ctx)
xvalidURL(ctx, urlStr)
log.Debug("making webhook test call for incoming message", slog.String("url", urlStr))
var b bytes.Buffer
enc := json.NewEncoder(&b)
enc.SetEscapeHTML(false)
enc.SetIndent("", "\t")
err := enc.Encode(data)
xcheckf(ctx, err, "encoding incoming webhook data")
code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
if err != nil {
errmsg = err.Error()
}
log.Debugx("result for webhook test call for incoming message", err, slog.Int("code", code), slog.String("response", response))
return code, response, errmsg
}
// FromIDLoginAddressesSave saves new login addresses to enable unique SMTP
// MAIL FROM addresses ("fromid") for deliveries from the queue.
func (Account) FromIDLoginAddressesSave(ctx context.Context, loginAddresses []string) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
acc.FromIDLoginAddresses = loginAddresses
})
if err != nil && errors.Is(err, mox.ErrConfig) {
xcheckuserf(ctx, err, "saving account fromid login addresses")
}
xcheckf(ctx, err, "saving account fromid login addresses")
}
// KeepRetiredPeriodsSave save periods to save retired messages and webhooks.
func (Account) KeepRetiredPeriodsSave(ctx context.Context, keepRetiredMessagePeriod, keepRetiredWebhookPeriod time.Duration) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
acc.KeepRetiredMessagePeriod = keepRetiredMessagePeriod
acc.KeepRetiredWebhookPeriod = keepRetiredWebhookPeriod
})
if err != nil && errors.Is(err, mox.ErrConfig) {
xcheckuserf(ctx, err, "saving account keep retired periods")
}
xcheckf(ctx, err, "saving account keep retired periods")
}

View File

@ -14,6 +14,7 @@ h2 { font-size: 1.1rem; }
h3, h4 { font-size: 1rem; }
ul { padding-left: 1rem; }
.literal { background-color: #eee; padding: .5em 1em; border: 1px solid #eee; border-radius: 4px; white-space: pre-wrap; font-family: monospace; font-size: 15px; tab-size: 4; }
table { border-spacing: 0; }
table td, table th { padding: .2em .5em; }
table > tbody > tr:nth-child(odd) { background-color: #f8f8f8; }
table.slim td, table.slim th { padding: 0; }
@ -23,8 +24,8 @@ p { margin-bottom: 1em; max-width: 50em; }
fieldset { border: 0; }
.scriptswitch { text-decoration: underline #dca053 2px; }
thead { position: sticky; top: 0; background-color: white; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1); }
#page { opacity: 1; animation: fadein 0.15s ease-in; }
#page.loading { opacity: 0.1; animation: fadeout 1s ease-out; }
#page, .loadend { opacity: 1; animation: fadein 0.15s ease-in; }
#page.loading, .loadstart { opacity: 0.1; animation: fadeout 1s ease-out; }
@keyframes fadein { 0% { opacity: 0 } 100% { opacity: 1 } }
@keyframes fadeout { 0% { opacity: 1 } 100% { opacity: 0.1 } }
.autosize { display: inline-grid; max-width: 90vw; }

View File

@ -220,6 +220,7 @@ const [dom, style, attr, prop] = (function () {
autocomplete: (s) => _attr('autocomplete', s),
list: (s) => _attr('list', s),
form: (s) => _attr('form', s),
size: (s) => _attr('size', s),
};
const style = (x) => { return { _styles: x }; };
const prop = (x) => { return { _props: x }; };
@ -228,11 +229,39 @@ const [dom, style, attr, prop] = (function () {
// NOTE: GENERATED by github.com/mjl-/sherpats, DO NOT MODIFY
var api;
(function (api) {
api.structTypes = { "Account": true, "AutomaticJunkFlags": true, "Destination": true, "Domain": true, "ImportProgress": true, "JunkFilter": true, "Route": true, "Ruleset": true, "SubjectPass": true };
api.stringsTypes = { "CSRFToken": true };
// OutgoingEvent is an activity for an outgoing delivery. Either generated by the
// queue, or through an incoming DSN (delivery status notification) message.
let OutgoingEvent;
(function (OutgoingEvent) {
// Message was accepted by a next-hop server. This does not necessarily mean the
// message has been delivered in the mailbox of the user.
OutgoingEvent["EventDelivered"] = "delivered";
// Outbound delivery was suppressed because the recipient address is on the
// suppression list of the account, or a simplified/base variant of the address is.
OutgoingEvent["EventSuppressed"] = "suppressed";
OutgoingEvent["EventDelayed"] = "delayed";
// Delivery of the message failed and will not be tried again. Also see the
// "Suppressing" field of [Outgoing].
OutgoingEvent["EventFailed"] = "failed";
// Message was relayed into a system that does not generate DSNs. Should only
// happen when explicitly requested.
OutgoingEvent["EventRelayed"] = "relayed";
// Message was accepted and is being delivered to multiple recipients (e.g. the
// address was an alias/list), which may generate more DSNs.
OutgoingEvent["EventExpanded"] = "expanded";
OutgoingEvent["EventCanceled"] = "canceled";
// An incoming message was received that was either a DSN with an unknown event
// type ("action"), or an incoming non-DSN-message was received for the unique
// per-outgoing-message address used for sending.
OutgoingEvent["EventUnrecognized"] = "unrecognized";
})(OutgoingEvent = api.OutgoingEvent || (api.OutgoingEvent = {}));
api.structTypes = { "Account": true, "AutomaticJunkFlags": true, "Destination": true, "Domain": true, "ImportProgress": true, "Incoming": true, "IncomingMeta": true, "IncomingWebhook": true, "JunkFilter": true, "NameAddress": true, "Outgoing": true, "OutgoingWebhook": true, "Route": true, "Ruleset": true, "Structure": true, "SubjectPass": true, "Suppression": true };
api.stringsTypes = { "CSRFToken": true, "OutgoingEvent": true };
api.intsTypes = {};
api.types = {
"Account": { "Name": "Account", "Docs": "", "Fields": [{ "Name": "Domain", "Docs": "", "Typewords": ["string"] }, { "Name": "Description", "Docs": "", "Typewords": ["string"] }, { "Name": "FullName", "Docs": "", "Typewords": ["string"] }, { "Name": "Destinations", "Docs": "", "Typewords": ["{}", "Destination"] }, { "Name": "SubjectPass", "Docs": "", "Typewords": ["SubjectPass"] }, { "Name": "QuotaMessageSize", "Docs": "", "Typewords": ["int64"] }, { "Name": "RejectsMailbox", "Docs": "", "Typewords": ["string"] }, { "Name": "KeepRejects", "Docs": "", "Typewords": ["bool"] }, { "Name": "AutomaticJunkFlags", "Docs": "", "Typewords": ["AutomaticJunkFlags"] }, { "Name": "JunkFilter", "Docs": "", "Typewords": ["nullable", "JunkFilter"] }, { "Name": "MaxOutgoingMessagesPerDay", "Docs": "", "Typewords": ["int32"] }, { "Name": "MaxFirstTimeRecipientsPerDay", "Docs": "", "Typewords": ["int32"] }, { "Name": "NoFirstTimeSenderDelay", "Docs": "", "Typewords": ["bool"] }, { "Name": "Routes", "Docs": "", "Typewords": ["[]", "Route"] }, { "Name": "DNSDomain", "Docs": "", "Typewords": ["Domain"] }] },
"Account": { "Name": "Account", "Docs": "", "Fields": [{ "Name": "OutgoingWebhook", "Docs": "", "Typewords": ["nullable", "OutgoingWebhook"] }, { "Name": "IncomingWebhook", "Docs": "", "Typewords": ["nullable", "IncomingWebhook"] }, { "Name": "FromIDLoginAddresses", "Docs": "", "Typewords": ["[]", "string"] }, { "Name": "KeepRetiredMessagePeriod", "Docs": "", "Typewords": ["int64"] }, { "Name": "KeepRetiredWebhookPeriod", "Docs": "", "Typewords": ["int64"] }, { "Name": "Domain", "Docs": "", "Typewords": ["string"] }, { "Name": "Description", "Docs": "", "Typewords": ["string"] }, { "Name": "FullName", "Docs": "", "Typewords": ["string"] }, { "Name": "Destinations", "Docs": "", "Typewords": ["{}", "Destination"] }, { "Name": "SubjectPass", "Docs": "", "Typewords": ["SubjectPass"] }, { "Name": "QuotaMessageSize", "Docs": "", "Typewords": ["int64"] }, { "Name": "RejectsMailbox", "Docs": "", "Typewords": ["string"] }, { "Name": "KeepRejects", "Docs": "", "Typewords": ["bool"] }, { "Name": "AutomaticJunkFlags", "Docs": "", "Typewords": ["AutomaticJunkFlags"] }, { "Name": "JunkFilter", "Docs": "", "Typewords": ["nullable", "JunkFilter"] }, { "Name": "MaxOutgoingMessagesPerDay", "Docs": "", "Typewords": ["int32"] }, { "Name": "MaxFirstTimeRecipientsPerDay", "Docs": "", "Typewords": ["int32"] }, { "Name": "NoFirstTimeSenderDelay", "Docs": "", "Typewords": ["bool"] }, { "Name": "Routes", "Docs": "", "Typewords": ["[]", "Route"] }, { "Name": "DNSDomain", "Docs": "", "Typewords": ["Domain"] }] },
"OutgoingWebhook": { "Name": "OutgoingWebhook", "Docs": "", "Fields": [{ "Name": "URL", "Docs": "", "Typewords": ["string"] }, { "Name": "Authorization", "Docs": "", "Typewords": ["string"] }, { "Name": "Events", "Docs": "", "Typewords": ["[]", "string"] }] },
"IncomingWebhook": { "Name": "IncomingWebhook", "Docs": "", "Fields": [{ "Name": "URL", "Docs": "", "Typewords": ["string"] }, { "Name": "Authorization", "Docs": "", "Typewords": ["string"] }] },
"Destination": { "Name": "Destination", "Docs": "", "Fields": [{ "Name": "Mailbox", "Docs": "", "Typewords": ["string"] }, { "Name": "Rulesets", "Docs": "", "Typewords": ["[]", "Ruleset"] }, { "Name": "FullName", "Docs": "", "Typewords": ["string"] }] },
"Ruleset": { "Name": "Ruleset", "Docs": "", "Fields": [{ "Name": "SMTPMailFromRegexp", "Docs": "", "Typewords": ["string"] }, { "Name": "VerifiedDomain", "Docs": "", "Typewords": ["string"] }, { "Name": "HeadersRegexp", "Docs": "", "Typewords": ["{}", "string"] }, { "Name": "IsForward", "Docs": "", "Typewords": ["bool"] }, { "Name": "ListAllowDomain", "Docs": "", "Typewords": ["string"] }, { "Name": "AcceptRejectsToMailbox", "Docs": "", "Typewords": ["string"] }, { "Name": "Mailbox", "Docs": "", "Typewords": ["string"] }, { "Name": "VerifiedDNSDomain", "Docs": "", "Typewords": ["Domain"] }, { "Name": "ListAllowDNSDomain", "Docs": "", "Typewords": ["Domain"] }] },
"Domain": { "Name": "Domain", "Docs": "", "Fields": [{ "Name": "ASCII", "Docs": "", "Typewords": ["string"] }, { "Name": "Unicode", "Docs": "", "Typewords": ["string"] }] },
@ -240,11 +269,20 @@ var api;
"AutomaticJunkFlags": { "Name": "AutomaticJunkFlags", "Docs": "", "Fields": [{ "Name": "Enabled", "Docs": "", "Typewords": ["bool"] }, { "Name": "JunkMailboxRegexp", "Docs": "", "Typewords": ["string"] }, { "Name": "NeutralMailboxRegexp", "Docs": "", "Typewords": ["string"] }, { "Name": "NotJunkMailboxRegexp", "Docs": "", "Typewords": ["string"] }] },
"JunkFilter": { "Name": "JunkFilter", "Docs": "", "Fields": [{ "Name": "Threshold", "Docs": "", "Typewords": ["float64"] }, { "Name": "Onegrams", "Docs": "", "Typewords": ["bool"] }, { "Name": "Twograms", "Docs": "", "Typewords": ["bool"] }, { "Name": "Threegrams", "Docs": "", "Typewords": ["bool"] }, { "Name": "MaxPower", "Docs": "", "Typewords": ["float64"] }, { "Name": "TopWords", "Docs": "", "Typewords": ["int32"] }, { "Name": "IgnoreWords", "Docs": "", "Typewords": ["float64"] }, { "Name": "RareWords", "Docs": "", "Typewords": ["int32"] }] },
"Route": { "Name": "Route", "Docs": "", "Fields": [{ "Name": "FromDomain", "Docs": "", "Typewords": ["[]", "string"] }, { "Name": "ToDomain", "Docs": "", "Typewords": ["[]", "string"] }, { "Name": "MinimumAttempts", "Docs": "", "Typewords": ["int32"] }, { "Name": "Transport", "Docs": "", "Typewords": ["string"] }, { "Name": "FromDomainASCII", "Docs": "", "Typewords": ["[]", "string"] }, { "Name": "ToDomainASCII", "Docs": "", "Typewords": ["[]", "string"] }] },
"Suppression": { "Name": "Suppression", "Docs": "", "Fields": [{ "Name": "ID", "Docs": "", "Typewords": ["int64"] }, { "Name": "Created", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "Account", "Docs": "", "Typewords": ["string"] }, { "Name": "BaseAddress", "Docs": "", "Typewords": ["string"] }, { "Name": "OriginalAddress", "Docs": "", "Typewords": ["string"] }, { "Name": "Manual", "Docs": "", "Typewords": ["bool"] }, { "Name": "Reason", "Docs": "", "Typewords": ["string"] }] },
"ImportProgress": { "Name": "ImportProgress", "Docs": "", "Fields": [{ "Name": "Token", "Docs": "", "Typewords": ["string"] }] },
"Outgoing": { "Name": "Outgoing", "Docs": "", "Fields": [{ "Name": "Version", "Docs": "", "Typewords": ["int32"] }, { "Name": "Event", "Docs": "", "Typewords": ["OutgoingEvent"] }, { "Name": "DSN", "Docs": "", "Typewords": ["bool"] }, { "Name": "Suppressing", "Docs": "", "Typewords": ["bool"] }, { "Name": "QueueMsgID", "Docs": "", "Typewords": ["int64"] }, { "Name": "FromID", "Docs": "", "Typewords": ["string"] }, { "Name": "MessageID", "Docs": "", "Typewords": ["string"] }, { "Name": "Subject", "Docs": "", "Typewords": ["string"] }, { "Name": "WebhookQueued", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "SMTPCode", "Docs": "", "Typewords": ["int32"] }, { "Name": "SMTPEnhancedCode", "Docs": "", "Typewords": ["string"] }, { "Name": "Error", "Docs": "", "Typewords": ["string"] }, { "Name": "Extra", "Docs": "", "Typewords": ["{}", "string"] }] },
"Incoming": { "Name": "Incoming", "Docs": "", "Fields": [{ "Name": "Version", "Docs": "", "Typewords": ["int32"] }, { "Name": "From", "Docs": "", "Typewords": ["[]", "NameAddress"] }, { "Name": "To", "Docs": "", "Typewords": ["[]", "NameAddress"] }, { "Name": "CC", "Docs": "", "Typewords": ["[]", "NameAddress"] }, { "Name": "BCC", "Docs": "", "Typewords": ["[]", "NameAddress"] }, { "Name": "ReplyTo", "Docs": "", "Typewords": ["[]", "NameAddress"] }, { "Name": "Subject", "Docs": "", "Typewords": ["string"] }, { "Name": "MessageID", "Docs": "", "Typewords": ["string"] }, { "Name": "InReplyTo", "Docs": "", "Typewords": ["string"] }, { "Name": "References", "Docs": "", "Typewords": ["[]", "string"] }, { "Name": "Date", "Docs": "", "Typewords": ["nullable", "timestamp"] }, { "Name": "Text", "Docs": "", "Typewords": ["string"] }, { "Name": "HTML", "Docs": "", "Typewords": ["string"] }, { "Name": "Structure", "Docs": "", "Typewords": ["Structure"] }, { "Name": "Meta", "Docs": "", "Typewords": ["IncomingMeta"] }] },
"NameAddress": { "Name": "NameAddress", "Docs": "", "Fields": [{ "Name": "Name", "Docs": "", "Typewords": ["string"] }, { "Name": "Address", "Docs": "", "Typewords": ["string"] }] },
"Structure": { "Name": "Structure", "Docs": "", "Fields": [{ "Name": "ContentType", "Docs": "", "Typewords": ["string"] }, { "Name": "ContentTypeParams", "Docs": "", "Typewords": ["{}", "string"] }, { "Name": "ContentID", "Docs": "", "Typewords": ["string"] }, { "Name": "DecodedSize", "Docs": "", "Typewords": ["int64"] }, { "Name": "Parts", "Docs": "", "Typewords": ["[]", "Structure"] }] },
"IncomingMeta": { "Name": "IncomingMeta", "Docs": "", "Fields": [{ "Name": "MsgID", "Docs": "", "Typewords": ["int64"] }, { "Name": "MailFrom", "Docs": "", "Typewords": ["string"] }, { "Name": "MailFromValidated", "Docs": "", "Typewords": ["bool"] }, { "Name": "MsgFromValidated", "Docs": "", "Typewords": ["bool"] }, { "Name": "RcptTo", "Docs": "", "Typewords": ["string"] }, { "Name": "DKIMVerifiedDomains", "Docs": "", "Typewords": ["[]", "string"] }, { "Name": "RemoteIP", "Docs": "", "Typewords": ["string"] }, { "Name": "Received", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "MailboxName", "Docs": "", "Typewords": ["string"] }, { "Name": "Automated", "Docs": "", "Typewords": ["bool"] }] },
"CSRFToken": { "Name": "CSRFToken", "Docs": "", "Values": null },
"OutgoingEvent": { "Name": "OutgoingEvent", "Docs": "", "Values": [{ "Name": "EventDelivered", "Value": "delivered", "Docs": "" }, { "Name": "EventSuppressed", "Value": "suppressed", "Docs": "" }, { "Name": "EventDelayed", "Value": "delayed", "Docs": "" }, { "Name": "EventFailed", "Value": "failed", "Docs": "" }, { "Name": "EventRelayed", "Value": "relayed", "Docs": "" }, { "Name": "EventExpanded", "Value": "expanded", "Docs": "" }, { "Name": "EventCanceled", "Value": "canceled", "Docs": "" }, { "Name": "EventUnrecognized", "Value": "unrecognized", "Docs": "" }] },
};
api.parser = {
Account: (v) => api.parse("Account", v),
OutgoingWebhook: (v) => api.parse("OutgoingWebhook", v),
IncomingWebhook: (v) => api.parse("IncomingWebhook", v),
Destination: (v) => api.parse("Destination", v),
Ruleset: (v) => api.parse("Ruleset", v),
Domain: (v) => api.parse("Domain", v),
@ -252,8 +290,15 @@ var api;
AutomaticJunkFlags: (v) => api.parse("AutomaticJunkFlags", v),
JunkFilter: (v) => api.parse("JunkFilter", v),
Route: (v) => api.parse("Route", v),
Suppression: (v) => api.parse("Suppression", v),
ImportProgress: (v) => api.parse("ImportProgress", v),
Outgoing: (v) => api.parse("Outgoing", v),
Incoming: (v) => api.parse("Incoming", v),
NameAddress: (v) => api.parse("NameAddress", v),
Structure: (v) => api.parse("Structure", v),
IncomingMeta: (v) => api.parse("IncomingMeta", v),
CSRFToken: (v) => api.parse("CSRFToken", v),
OutgoingEvent: (v) => api.parse("OutgoingEvent", v),
};
// Account exports web API functions for the account web interface. All its
// methods are exported under api/. Function calls require valid HTTP
@ -322,10 +367,12 @@ var api;
async Account() {
const fn = "Account";
const paramTypes = [];
const returnTypes = [["Account"], ["int64"], ["int64"]];
const returnTypes = [["Account"], ["int64"], ["int64"], ["[]", "Suppression"]];
const params = [];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// AccountSaveFullName saves the full name (used as display name in email messages)
// for the account.
async AccountSaveFullName(fullName) {
const fn = "AccountSaveFullName";
const paramTypes = [["string"]];
@ -360,6 +407,88 @@ var api;
const params = [];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// SuppressionList lists the addresses on the suppression list of this account.
async SuppressionList() {
const fn = "SuppressionList";
const paramTypes = [];
const returnTypes = [["[]", "Suppression"]];
const params = [];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// SuppressionAdd adds an email address to the suppression list.
async SuppressionAdd(address, manual, reason) {
const fn = "SuppressionAdd";
const paramTypes = [["string"], ["bool"], ["string"]];
const returnTypes = [["Suppression"]];
const params = [address, manual, reason];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// SuppressionRemove removes the email address from the suppression list.
async SuppressionRemove(address) {
const fn = "SuppressionRemove";
const paramTypes = [["string"]];
const returnTypes = [];
const params = [address];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// OutgoingWebhookSave saves a new webhook url for outgoing deliveries. If url
// is empty, the webhook is disabled. If authorization is non-empty it is used for
// the Authorization header in HTTP requests. Events specifies the outgoing events
// to be delivered, or all if empty/nil.
async OutgoingWebhookSave(url, authorization, events) {
const fn = "OutgoingWebhookSave";
const paramTypes = [["string"], ["string"], ["[]", "string"]];
const returnTypes = [];
const params = [url, authorization, events];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// OutgoingWebhookTest makes a test webhook call to urlStr, with optional
// authorization. If the HTTP request is made this call will succeed also for
// non-2xx HTTP status codes.
async OutgoingWebhookTest(urlStr, authorization, data) {
const fn = "OutgoingWebhookTest";
const paramTypes = [["string"], ["string"], ["Outgoing"]];
const returnTypes = [["int32"], ["string"], ["string"]];
const params = [urlStr, authorization, data];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// IncomingWebhookSave saves a new webhook url for incoming deliveries. If url is
// empty, the webhook is disabled. If authorization is not empty, it is used in
// the Authorization header in requests.
async IncomingWebhookSave(url, authorization) {
const fn = "IncomingWebhookSave";
const paramTypes = [["string"], ["string"]];
const returnTypes = [];
const params = [url, authorization];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// IncomingWebhookTest makes a test webhook HTTP delivery request to urlStr,
// with optional authorization header. If the HTTP call is made, this function
// returns non-error regardless of HTTP status code.
async IncomingWebhookTest(urlStr, authorization, data) {
const fn = "IncomingWebhookTest";
const paramTypes = [["string"], ["string"], ["Incoming"]];
const returnTypes = [["int32"], ["string"], ["string"]];
const params = [urlStr, authorization, data];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// FromIDLoginAddressesSave saves new login addresses to enable unique SMTP
// MAIL FROM addresses ("fromid") for deliveries from the queue.
async FromIDLoginAddressesSave(loginAddresses) {
const fn = "FromIDLoginAddressesSave";
const paramTypes = [["[]", "string"]];
const returnTypes = [];
const params = [loginAddresses];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// KeepRetiredPeriodsSave save periods to save retired messages and webhooks.
async KeepRetiredPeriodsSave(keepRetiredMessagePeriod, keepRetiredWebhookPeriod) {
const fn = "KeepRetiredPeriodsSave";
const paramTypes = [["int64"], ["int64"]];
const returnTypes = [];
const params = [keepRetiredMessagePeriod, keepRetiredWebhookPeriod];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
}
api.Client = Client;
api.defaultBaseURL = (function () {
@ -753,6 +882,37 @@ const login = async (reason) => {
username.focus();
});
};
// Popup shows kids in a centered div with white background on top of a
// transparent overlay on top of the window. Clicking the overlay or hitting
// Escape closes the popup. Scrollbars are automatically added to the div with
// kids. Returns a function that removes the popup.
const popup = (...kids) => {
const origFocus = document.activeElement;
const close = () => {
if (!root.parentNode) {
return;
}
root.remove();
if (origFocus && origFocus instanceof HTMLElement && origFocus.parentNode) {
origFocus.focus();
}
};
let content;
const root = dom.div(style({ position: 'fixed', top: 0, right: 0, bottom: 0, left: 0, backgroundColor: 'rgba(0, 0, 0, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: '1' }), function keydown(e) {
if (e.key === 'Escape') {
e.stopPropagation();
close();
}
}, function click(e) {
e.stopPropagation();
close();
}, content = dom.div(attr.tabindex('0'), style({ backgroundColor: 'white', borderRadius: '.25em', padding: '1em', boxShadow: '0 0 20px rgba(0, 0, 0, 0.1)', border: '1px solid #ddd', maxWidth: '95vw', overflowX: 'auto', maxHeight: '95vh', overflowY: 'auto' }), function click(e) {
e.stopPropagation();
}, kids));
document.body.appendChild(root);
content.focus();
return close;
};
const localStorageGet = (k) => {
try {
return window.localStorage.getItem(k);
@ -842,6 +1002,39 @@ const green = '#1dea20';
const yellow = '#ffe400';
const red = '#ff7443';
const blue = '#8bc8ff';
const age = (date) => {
const r = dom.span(dom._class('notooltip'), attr.title(date.toString()));
const nowSecs = new Date().getTime() / 1000;
let t = nowSecs - date.getTime() / 1000;
let negative = '';
if (t < 0) {
negative = '-';
t = -t;
}
const minute = 60;
const hour = 60 * minute;
const day = 24 * hour;
const month = 30 * day;
const year = 365 * day;
const periods = [year, month, day, hour, minute];
const suffix = ['y', 'mo', 'd', 'h', 'min'];
let s;
for (let i = 0; i < periods.length; i++) {
const p = periods[i];
if (t >= 2 * p || i === periods.length - 1) {
const n = Math.round(t / p);
s = '' + n + suffix[i];
break;
}
}
if (t < 60) {
s = '<1min';
// Prevent showing '-<1min' when browser and server have relatively small time drift of max 1 minute.
negative = '';
}
dom._kids(r, negative + s);
return r;
};
const formatQuotaSize = (v) => {
if (v === 0) {
return '0';
@ -861,7 +1054,7 @@ const formatQuotaSize = (v) => {
return '' + v;
};
const index = async () => {
const [acc, storageUsed, storageLimit] = await client.Account();
const [acc, storageUsed, storageLimit, suppressions] = await client.Account();
let fullNameForm;
let fullNameFieldset;
let fullName;
@ -870,12 +1063,78 @@ const index = async () => {
let password1;
let password2;
let passwordHint;
let outgoingWebhookFieldset;
let outgoingWebhookURL;
let outgoingWebhookAuthorization;
let outgoingWebhookEvents;
let incomingWebhookFieldset;
let incomingWebhookURL;
let incomingWebhookAuthorization;
let keepRetiredPeriodsFieldset;
let keepRetiredMessagePeriod;
let keepRetiredWebhookPeriod;
let fromIDLoginAddressesFieldset;
const second = 1000 * 1000 * 1000;
const minute = 60 * second;
const hour = 60 * minute;
const day = 24 * hour;
const week = 7 * day;
const parseDuration = (s) => {
if (!s) {
return 0;
}
const xparseint = () => {
const v = parseInt(s.substring(0, s.length - 1));
if (isNaN(v) || Math.round(v) !== v) {
throw new Error('bad number in duration');
}
return v;
};
if (s.endsWith('w')) {
return xparseint() * week;
}
if (s.endsWith('d')) {
return xparseint() * day;
}
if (s.endsWith('h')) {
return xparseint() * hour;
}
if (s.endsWith('m')) {
return xparseint() * minute;
}
if (s.endsWith('s')) {
return xparseint() * second;
}
throw new Error('bad duration ' + s);
};
const formatDuration = (v) => {
if (v === 0) {
return '';
}
const is = (period) => v > 0 && Math.round(v / period) === v / period;
const format = (period, s) => '' + (v / period) + s;
if (is(week)) {
return format(week, 'w');
}
if (is(day)) {
return format(day, 'd');
}
if (is(hour)) {
return format(hour, 'h');
}
if (is(minute)) {
return format(minute, 'm');
}
return format(second, 's');
};
let importForm;
let importFieldset;
let mailboxFileHint;
let mailboxPrefixHint;
let importProgress;
let importAbortBox;
let suppressionAddress;
let suppressionReason;
const importTrack = async (token) => {
const importConnection = dom.div('Waiting for updates...');
importProgress.appendChild(importConnection);
@ -952,6 +1211,139 @@ const index = async () => {
const exportForm = (filename) => {
return dom.form(attr.target('_blank'), attr.method('POST'), attr.action('export/' + filename), dom.input(attr.type('hidden'), attr.name('csrf'), attr.value(localStorageGet('webaccountcsrftoken') || '')), dom.submitbutton('Export'));
};
const authorizationPopup = (dest) => {
let username;
let password;
const close = popup(dom.form(function submit(e) {
e.preventDefault();
e.stopPropagation();
dest.value = 'Basic ' + window.btoa(username.value + ':' + password.value);
close();
}, dom.p('Compose HTTP Basic authentication header'), dom.div(style({ marginBottom: '1ex' }), dom.div(dom.label('Username')), username = dom.input(attr.required(''))), dom.div(style({ marginBottom: '1ex' }), dom.div(dom.label('Password (shown in clear)')), password = dom.input(attr.required(''))), dom.div(style({ marginBottom: '1ex' }), dom.submitbutton('Set')), dom.div('A HTTP Basic authorization header contains the password in plain text, as base64.')));
username.focus();
};
const popupTestOutgoing = () => {
let fieldset;
let event;
let dsn;
let suppressing;
let queueMsgID;
let fromID;
let messageID;
let error;
let extra;
let body;
let curl;
let result;
let data = {
Version: 0,
Event: api.OutgoingEvent.EventDelivered,
DSN: false,
Suppressing: false,
QueueMsgID: 123,
FromID: 'MDEyMzQ1Njc4OWFiY2RlZg',
MessageID: '<QnxzgulZK51utga6agH_rg@mox.example>',
Subject: 'test from mox web pages',
WebhookQueued: new Date(),
SMTPCode: 0,
SMTPEnhancedCode: '',
Error: '',
Extra: {},
};
const onchange = function change() {
data = {
Version: 0,
Event: event.value,
DSN: dsn.checked,
Suppressing: suppressing.checked,
QueueMsgID: parseInt(queueMsgID.value),
FromID: fromID.value,
MessageID: messageID.value,
Subject: 'test from mox web pages',
WebhookQueued: new Date(),
SMTPCode: 0,
SMTPEnhancedCode: '',
Error: error.value,
Extra: JSON.parse(extra.value),
};
const curlStr = "curl " + (outgoingWebhookAuthorization.value ? "-H 'Authorization: " + outgoingWebhookAuthorization.value + "' " : "") + "-H 'X-Mox-Webhook-ID: 1' -H 'X-Mox-Webhook-Attempt: 1' --json '" + JSON.stringify(data) + "' '" + outgoingWebhookURL.value + "'";
dom._kids(curl, style({ maxWidth: '45em', wordBreak: 'break-all' }), curlStr);
body.value = JSON.stringify(data, undefined, "\t");
};
popup(dom.h1('Test webhook for outgoing delivery'), dom.form(async function submit(e) {
e.preventDefault();
e.stopPropagation();
result.classList.add('loadstart');
const [code, response, errmsg] = await check(fieldset, client.OutgoingWebhookTest(outgoingWebhookURL.value, outgoingWebhookAuthorization.value, data));
const nresult = dom.div(dom._class('loadend'), dom.table(dom.tr(dom.td('HTTP status code'), dom.td('' + code)), dom.tr(dom.td('Error message'), dom.td(errmsg)), dom.tr(dom.td('Response'), dom.td(response))));
result.replaceWith(nresult);
result = nresult;
}, fieldset = dom.fieldset(dom.p('Make a test call to ', dom.b(outgoingWebhookURL.value), '.'), dom.div(style({ display: 'flex', gap: '1em' }), dom.div(dom.h2('Parameters'), dom.div(style({ marginBottom: '.5ex' }), dom.label('Event', dom.div(event = dom.select(onchange, ["delivered", "suppressed", "delayed", "failed", "relayed", "expanded", "canceled", "unrecognized"].map(s => dom.option(s.substring(0, 1).toUpperCase() + s.substring(1), attr.value(s))))))), dom.div(style({ marginBottom: '.5ex' }), dom.label(dsn = dom.input(attr.type('checkbox')), ' DSN', onchange)), dom.div(style({ marginBottom: '.5ex' }), dom.label(suppressing = dom.input(attr.type('checkbox')), ' Suppressing', onchange)), dom.div(style({ marginBottom: '.5ex' }), dom.label('Queue message ID ', dom.div(queueMsgID = dom.input(attr.required(''), attr.type('number'), attr.value('123'), onchange)))), dom.div(style({ marginBottom: '.5ex' }), dom.label('From ID ', dom.div(fromID = dom.input(attr.required(''), attr.value(data.FromID), onchange)))), dom.div(style({ marginBottom: '.5ex' }), dom.label('MessageID', dom.div(messageID = dom.input(attr.required(''), attr.value(data.MessageID), onchange)))), dom.div(style({ marginBottom: '.5ex' }), dom.label('Error', dom.div(error = dom.input(onchange)))), dom.div(style({ marginBottom: '.5ex' }), dom.label('Extra', dom.div(extra = dom.input(attr.required(''), attr.value('{}'), onchange))))), dom.div(dom.h2('Headers'), dom.pre('X-Mox-Webhook-ID: 1\nX-Mox-Webhook-Attempt: 1'), dom.br(), dom.h2('JSON'), body = dom.textarea(attr.disabled(''), attr.rows('15'), style({ width: '30em' })), dom.br(), dom.h2('curl'), curl = dom.div(dom._class('literal')))), dom.br(), dom.div(style({ textAlign: 'right' }), dom.submitbutton('Post')), dom.br(), result = dom.div())));
onchange();
};
const popupTestIncoming = () => {
let fieldset;
let body;
let curl;
let result;
let data = {
Version: 0,
From: [{ Name: 'remote', Address: 'remote@remote.example' }],
To: [{ Name: 'mox', Address: 'mox@mox.example' }],
CC: [],
BCC: [],
ReplyTo: [],
Subject: 'test webhook for incoming message',
MessageID: '<QnxzgulZK51utga6agH_rg@mox.example>',
InReplyTo: '',
References: [],
Date: new Date(),
Text: 'hi ☺\n',
HTML: '',
Structure: {
ContentType: 'text/plain',
ContentTypeParams: { charset: 'utf-8' },
ContentID: '',
DecodedSize: 8,
Parts: [],
},
Meta: {
MsgID: 1,
MailFrom: 'remote@remote.example',
MailFromValidated: true,
MsgFromValidated: true,
RcptTo: 'mox@localhost',
DKIMVerifiedDomains: ['remote.example'],
RemoteIP: '127.0.0.1',
Received: new Date(),
MailboxName: 'Inbox',
Automated: false,
},
};
const onchange = function change() {
try {
api.parser.Incoming(JSON.parse(body.value));
}
catch (err) {
console.log({ err });
window.alert('Error parsing data: ' + errmsg(err));
}
const curlStr = "curl " + (incomingWebhookAuthorization.value ? "-H 'Authorization: " + incomingWebhookAuthorization.value + "' " : "") + "-H 'X-Mox-Webhook-ID: 1' -H 'X-Mox-Webhook-Attempt: 1' --json '" + JSON.stringify(data) + "' '" + incomingWebhookURL.value + "'";
dom._kids(curl, style({ maxWidth: '45em', wordBreak: 'break-all' }), curlStr);
};
popup(dom.h1('Test webhook for incoming delivery'), dom.form(async function submit(e) {
e.preventDefault();
e.stopPropagation();
result.classList.add('loadstart');
const [code, response, errmsg] = await check(fieldset, (async () => await client.IncomingWebhookTest(incomingWebhookURL.value, incomingWebhookAuthorization.value, api.parser.Incoming(JSON.parse(body.value))))());
const nresult = dom.div(dom._class('loadend'), dom.table(dom.tr(dom.td('HTTP status code'), dom.td('' + code)), dom.tr(dom.td('Error message'), dom.td(errmsg)), dom.tr(dom.td('Response'), dom.td(response))));
result.replaceWith(nresult);
result = nresult;
}, fieldset = dom.fieldset(dom.p('Make a test call to ', dom.b(incomingWebhookURL.value), '.'), dom.div(style({ display: 'flex', gap: '1em' }), dom.div(dom.h2('JSON'), body = dom.textarea(style({ maxHeight: '90vh' }), style({ width: '30em' }), onchange)), dom.div(dom.h2('Headers'), dom.pre('X-Mox-Webhook-ID: 1\nX-Mox-Webhook-Attempt: 1'), dom.br(), dom.h2('curl'), curl = dom.div(dom._class('literal')))), dom.br(), dom.div(style({ textAlign: 'right' }), dom.submitbutton('Post')), dom.br(), result = dom.div())));
body.value = JSON.stringify(data, undefined, '\t');
body.setAttribute('rows', '' + Math.min(40, (body.value.split('\n').length + 1)));
onchange();
};
dom._kids(page, crumbs('Mox Account'), dom.p('NOTE: Not all account settings can be configured through these pages yet. See the configuration file for more options.'), dom.div('Default domain: ', acc.DNSDomain.ASCII ? domainString(acc.DNSDomain) : '(none)'), dom.br(), fullNameForm = dom.form(fullNameFieldset = dom.fieldset(dom.label(style({ display: 'inline-block' }), 'Full name', dom.br(), fullName = dom.input(attr.value(acc.FullName), attr.title('Name to use in From header when composing messages. Can be overridden per configured address.'))), ' ', dom.submitbutton('Save')), async function submit(e) {
e.preventDefault();
await check(fullNameFieldset, client.AccountSaveFullName(fullName.value));
@ -989,7 +1381,67 @@ const index = async () => {
' (',
'' + Math.floor(100 * storageUsed / storageLimit),
'%).',
] : [', no explicit limit is configured.']), dom.h2('Export'), dom.p('Export all messages in all mailboxes. In maildir or mbox format, as .zip or .tgz file.'), dom.table(dom._class('slim'), dom.tr(dom.td('Maildirs in .tgz'), dom.td(exportForm('mail-export-maildir.tgz'))), dom.tr(dom.td('Maildirs in .zip'), dom.td(exportForm('mail-export-maildir.zip'))), dom.tr(dom.td('Mbox files in .tgz'), dom.td(exportForm('mail-export-mbox.tgz'))), dom.tr(dom.td('Mbox files in .zip'), dom.td(exportForm('mail-export-mbox.zip')))), dom.br(), dom.h2('Import'), dom.p('Import messages from a .zip or .tgz file with maildirs and/or mbox files.'), importForm = dom.form(async function submit(e) {
] : [', no explicit limit is configured.']), dom.h2('Webhooks'), dom.h3('Outgoing', attr.title('Webhooks for outgoing messages are called for each attempt to deliver a message in the outgoing queue, e.g. when the queue has delivered a message to the next hop, when a single attempt failed with a temporary error, when delivery permanently failed, or when DSN (delivery status notification) messages were received about a previously sent message.')), dom.form(async function submit(e) {
e.preventDefault();
e.stopPropagation();
await check(outgoingWebhookFieldset, client.OutgoingWebhookSave(outgoingWebhookURL.value, outgoingWebhookAuthorization.value, [...outgoingWebhookEvents.selectedOptions].map(o => o.value)));
}, outgoingWebhookFieldset = dom.fieldset(dom.div(style({ display: 'flex', gap: '1em' }), dom.div(dom.label(dom.div('URL', attr.title('URL to do an HTTP POST to for each event. Webhooks are disabled if empty.')), outgoingWebhookURL = dom.input(attr.value(acc.OutgoingWebhook?.URL || ''), style({ width: '30em' })))), dom.div(dom.label(dom.div('Authorization header ', dom.a('Basic', attr.href(''), function click(e) {
e.preventDefault();
authorizationPopup(outgoingWebhookAuthorization);
}), attr.title('If non-empty, HTTP requests have this value as Authorization header, e.g. Basic <base64-encoded-username-password>.')), outgoingWebhookAuthorization = dom.input(attr.value(acc.OutgoingWebhook?.Authorization || '')))), dom.div(dom.label(style({ verticalAlign: 'top' }), dom.div('Events', attr.title('Either limit to specific events, or receive all events (default).')), outgoingWebhookEvents = dom.select(style({ verticalAlign: 'bottom' }), attr.multiple(''), attr.size('8'), // Number of options.
["delivered", "suppressed", "delayed", "failed", "relayed", "expanded", "canceled", "unrecognized"].map(s => dom.option(s.substring(0, 1).toUpperCase() + s.substring(1), attr.value(s), acc.OutgoingWebhook?.Events?.includes(s) ? attr.selected('') : []))))), dom.div(dom.div(dom.label('\u00a0')), dom.submitbutton('Save'), ' ', dom.clickbutton('Test', function click() {
popupTestOutgoing();
}))))), dom.br(), dom.h3('Incoming', attr.title('Webhooks for incoming messages are called for each message received over SMTP, excluding DSN messages about previous deliveries.')), dom.form(async function submit(e) {
e.preventDefault();
e.stopPropagation();
await check(incomingWebhookFieldset, client.IncomingWebhookSave(incomingWebhookURL.value, incomingWebhookAuthorization.value));
}, incomingWebhookFieldset = dom.fieldset(dom.div(style({ display: 'flex', gap: '1em' }), dom.div(dom.label(dom.div('URL'), incomingWebhookURL = dom.input(attr.value(acc.IncomingWebhook?.URL || ''), style({ width: '30em' })))), dom.div(dom.label(dom.div('Authorization header ', dom.a('Basic', attr.href(''), function click(e) {
e.preventDefault();
authorizationPopup(incomingWebhookAuthorization);
}), attr.title('If non-empty, HTTP requests have this value as Authorization header, e.g. Basic <base64-encoded-username-password>.')), incomingWebhookAuthorization = dom.input(attr.value(acc.IncomingWebhook?.Authorization || '')))), dom.div(dom.div(dom.label('\u00a0')), dom.submitbutton('Save'), ' ', dom.clickbutton('Test', function click() {
popupTestIncoming();
}))))), dom.br(), dom.h2('Keep messages/webhooks retired from queue', attr.title('After delivering a message or webhook from the queue it is removed by default. But you can also keep these "retired" messages/webhooks around for a while. With unique SMTP MAIL FROM addresses configured below, this allows relating incoming delivery status notification messages (DSNs) to previously sent messages and their original recipients, which is needed for automatic management of recipient suppression lists, which is important for managing the reputation of your mail server. For both messages and webhooks, this can be useful for debugging. Use values like "3d" for 3 days, or units "s" for second, "m" for minute, "h" for hour, "w" for week.')), dom.form(async function submit(e) {
e.preventDefault();
e.stopPropagation();
await check(keepRetiredPeriodsFieldset, (async () => await client.KeepRetiredPeriodsSave(parseDuration(keepRetiredMessagePeriod.value), parseDuration(keepRetiredWebhookPeriod.value)))());
}, keepRetiredPeriodsFieldset = dom.fieldset(dom.div(style({ display: 'flex', gap: '1em', alignItems: 'flex-end' }), dom.div(dom.label('Messages deliveries', dom.br(), keepRetiredMessagePeriod = dom.input(attr.value(formatDuration(acc.KeepRetiredMessagePeriod))))), dom.div(dom.label('Webhook deliveries', dom.br(), keepRetiredWebhookPeriod = dom.input(attr.value(formatDuration(acc.KeepRetiredWebhookPeriod))))), dom.div(dom.submitbutton('Save'))))), dom.br(), dom.h2('Unique SMTP MAIL FROM login addresses', attr.title('Outgoing messages are normally sent using your email address in the SMTP MAIL FROM command. By using unique addresses (by using the localpart catchall separator, e.g. addresses of the form "localpart+<uniquefromid>@domain"), future incoming DSNs can be related to the original outgoing messages and recipients, which allows for automatic management of recipient suppression lists when keeping retired messages for as long as you expect DSNs to come in as configured above. Configure the addresses used for logging in with SMTP submission, the webapi or webmail for which unique SMTP MAIL FROM addesses should be enabled. Note: These are addresses used for authenticating, not the address in the message "From" header.')), (() => {
let inputs = [];
let elem;
const render = () => {
inputs = [];
const e = dom.form(async function submit(e) {
e.preventDefault();
e.stopPropagation();
await check(fromIDLoginAddressesFieldset, client.FromIDLoginAddressesSave(inputs.map(e => e.value)));
}, fromIDLoginAddressesFieldset = dom.fieldset(dom.table(dom.tbody((acc.FromIDLoginAddresses || []).length === 0 ? dom.tr(dom.td('(None)'), dom.td()) : [], (acc.FromIDLoginAddresses || []).map((s, index) => {
const input = dom.input(attr.required(''), attr.value(s));
inputs.push(input);
const x = dom.tr(dom.td(input), dom.td(dom.clickbutton('Remove', function click() {
acc.FromIDLoginAddresses.splice(index, 1);
render();
})));
return x;
})), dom.tfoot(dom.tr(dom.td(), dom.td(dom.clickbutton('Add', function click() {
acc.FromIDLoginAddresses = (acc.FromIDLoginAddresses || []).concat(['']);
render();
}))), dom.tr(dom.td(attr.colspan('2'), dom.submitbutton('Save')))))));
if (elem) {
elem.replaceWith(e);
elem = e;
}
return e;
};
elem = render();
return elem;
})(), dom.br(), dom.h2('Suppression list'), dom.p('Messages queued for delivery to recipients on the suppression list will immediately fail. If delivery to a recipient fails repeatedly, it can be added to the suppression list automatically. Repeated rejected delivery attempts can have a negative influence of mail server reputation. Applications sending email can implement their own handling of delivery failure notifications, but not all do.'), dom.form(attr.id('suppressionAdd'), async function submit(e) {
e.preventDefault();
e.stopPropagation();
await check(e.target, client.SuppressionAdd(suppressionAddress.value, true, suppressionReason.value));
window.location.reload(); // todo: reload less
}), dom.table(dom.thead(dom.tr(dom.th('Address', attr.title('Address that caused this entry to be added to the list. The title (shown on hover) displays an address with a fictional simplified localpart, with lower-cased, dots removed, only first part before "+" or "-" (typicaly catchall separators). When checking if an address is on the suppression list, it is checked against this address.')), dom.th('Manual', attr.title('Whether suppression was added manually, instead of automatically based on bounces.')), dom.th('Reason'), dom.th('Since'), dom.th('Action'))), dom.tbody((suppressions || []).length === 0 ? dom.tr(dom.td(attr.colspan('5'), '(None)')) : [], (suppressions || []).map(s => dom.tr(dom.td(s.OriginalAddress, attr.title(s.BaseAddress)), dom.td(s.Manual ? '✓' : ''), dom.td(s.Reason), dom.td(age(s.Created)), dom.td(dom.clickbutton('Remove', async function click(e) {
await check(e.target, client.SuppressionRemove(s.OriginalAddress));
window.location.reload(); // todo: reload less
}))))), dom.tfoot(dom.tr(dom.td(suppressionAddress = dom.input(attr.type('required'), attr.form('suppressionAdd'))), dom.td(), dom.td(suppressionReason = dom.input(style({ width: '100%' }), attr.form('suppressionAdd'))), dom.td(), dom.td(dom.submitbutton('Add suppression', attr.form('suppressionAdd')))))), dom.br(), dom.h2('Export'), dom.p('Export all messages in all mailboxes. In maildir or mbox format, as .zip or .tgz file.'), dom.table(dom._class('slim'), dom.tr(dom.td('Maildirs in .tgz'), dom.td(exportForm('mail-export-maildir.tgz'))), dom.tr(dom.td('Maildirs in .zip'), dom.td(exportForm('mail-export-maildir.zip'))), dom.tr(dom.td('Mbox files in .tgz'), dom.td(exportForm('mail-export-mbox.tgz'))), dom.tr(dom.td('Mbox files in .zip'), dom.td(exportForm('mail-export-mbox.zip')))), dom.br(), dom.h2('Import'), dom.p('Import messages from a .zip or .tgz file with maildirs and/or mbox files.'), importForm = dom.form(async function submit(e) {
e.preventDefault();
e.stopPropagation();
const request = async () => {
@ -1054,7 +1506,7 @@ const index = async () => {
})), mailboxFileHint = dom.p(style({ display: 'none', fontStyle: 'italic', marginTop: '.5ex' }), 'This file must either be a zip file or a gzipped tar file with mbox and/or maildir mailboxes. For maildirs, an optional file "dovecot-keywords" is read additional keywords, like Forwarded/Junk/NotJunk. If an imported mailbox already exists by name, messages are added to the existing mailbox. If a mailbox does not yet exist it will be created.')), dom.div(style({ marginBottom: '1ex' }), dom.label(dom.div(style({ marginBottom: '.5ex' }), 'Skip mailbox prefix (optional)'), dom.input(attr.name('skipMailboxPrefix'), function focus() {
mailboxPrefixHint.style.display = '';
})), mailboxPrefixHint = dom.p(style({ display: 'none', fontStyle: 'italic', marginTop: '.5ex' }), 'If set, any mbox/maildir path with this prefix will have it stripped before importing. For example, if all mailboxes are in a directory "Takeout", specify that path in the field above so mailboxes like "Takeout/Inbox.mbox" are imported into a mailbox called "Inbox" instead of "Takeout/Inbox".')), dom.div(dom.submitbutton('Upload and import'), dom.p(style({ fontStyle: 'italic', marginTop: '.5ex' }), 'The file is uploaded first, then its messages are imported, finally messages are matched for threading. Importing is done in a transaction, you can abort the entire import before it is finished.')))), importAbortBox = dom.div(), // Outside fieldset because it gets disabled, above progress because may be scrolling it down quickly with problems.
importProgress = dom.div(style({ display: 'none' })), footer);
importProgress = dom.div(style({ display: 'none' })), dom.br(), footer);
// Try to show the progress of an earlier import session. The user may have just
// refreshed the browser.
let importToken;

View File

@ -84,6 +84,48 @@ const login = async (reason: string) => {
})
}
// Popup shows kids in a centered div with white background on top of a
// transparent overlay on top of the window. Clicking the overlay or hitting
// Escape closes the popup. Scrollbars are automatically added to the div with
// kids. Returns a function that removes the popup.
const popup = (...kids: ElemArg[]) => {
const origFocus = document.activeElement
const close = () => {
if (!root.parentNode) {
return
}
root.remove()
if (origFocus && origFocus instanceof HTMLElement && origFocus.parentNode) {
origFocus.focus()
}
}
let content: HTMLElement
const root = dom.div(
style({position: 'fixed', top: 0, right: 0, bottom: 0, left: 0, backgroundColor: 'rgba(0, 0, 0, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: '1'}),
function keydown(e: KeyboardEvent) {
if (e.key === 'Escape') {
e.stopPropagation()
close()
}
},
function click(e: MouseEvent) {
e.stopPropagation()
close()
},
content=dom.div(
attr.tabindex('0'),
style({backgroundColor: 'white', borderRadius: '.25em', padding: '1em', boxShadow: '0 0 20px rgba(0, 0, 0, 0.1)', border: '1px solid #ddd', maxWidth: '95vw', overflowX: 'auto', maxHeight: '95vh', overflowY: 'auto'}),
function click(e: MouseEvent) {
e.stopPropagation()
},
kids,
)
)
document.body.appendChild(root)
content.focus()
return close
}
const localStorageGet = (k: string): string | null => {
try {
return window.localStorage.getItem(k)
@ -195,6 +237,42 @@ const yellow = '#ffe400'
const red = '#ff7443'
const blue = '#8bc8ff'
const age = (date: Date) => {
const r = dom.span(dom._class('notooltip'), attr.title(date.toString()))
const nowSecs = new Date().getTime()/1000
let t = nowSecs - date.getTime()/1000
let negative = ''
if (t < 0) {
negative = '-'
t = -t
}
const minute = 60
const hour = 60*minute
const day = 24*hour
const month = 30*day
const year = 365*day
const periods = [year, month, day, hour, minute]
const suffix = ['y', 'mo', 'd', 'h', 'min']
let s
for (let i = 0; i < periods.length; i++) {
const p = periods[i]
if (t >= 2*p || i === periods.length-1) {
const n = Math.round(t/p)
s = '' + n + suffix[i]
break
}
}
if (t < 60) {
s = '<1min'
// Prevent showing '-<1min' when browser and server have relatively small time drift of max 1 minute.
negative = ''
}
dom._kids(r, negative+s)
return r
}
const formatQuotaSize = (v: number) => {
if (v === 0) {
return '0'
@ -213,7 +291,7 @@ const formatQuotaSize = (v: number) => {
}
const index = async () => {
const [acc, storageUsed, storageLimit] = await client.Account()
const [acc, storageUsed, storageLimit, suppressions] = await client.Account()
let fullNameForm: HTMLFormElement
let fullNameFieldset: HTMLFieldSetElement
@ -224,6 +302,55 @@ const index = async () => {
let password2: HTMLInputElement
let passwordHint: HTMLElement
let outgoingWebhookFieldset: HTMLFieldSetElement
let outgoingWebhookURL: HTMLInputElement
let outgoingWebhookAuthorization: HTMLInputElement
let outgoingWebhookEvents: HTMLSelectElement
let incomingWebhookFieldset: HTMLFieldSetElement
let incomingWebhookURL: HTMLInputElement
let incomingWebhookAuthorization: HTMLInputElement
let keepRetiredPeriodsFieldset: HTMLFieldSetElement
let keepRetiredMessagePeriod: HTMLInputElement
let keepRetiredWebhookPeriod: HTMLInputElement
let fromIDLoginAddressesFieldset: HTMLFieldSetElement
const second = 1000*1000*1000
const minute = 60*second
const hour = 60*minute
const day = 24*hour
const week = 7*day
const parseDuration = (s: string) => {
if (!s) { return 0 }
const xparseint = () => {
const v = parseInt(s.substring(0, s.length-1))
if (isNaN(v) || Math.round(v) !== v) {
throw new Error('bad number in duration')
}
return v
}
if (s.endsWith('w')) { return xparseint()*week }
if (s.endsWith('d')) { return xparseint()*day }
if (s.endsWith('h')) { return xparseint()*hour }
if (s.endsWith('m')) { return xparseint()*minute }
if (s.endsWith('s')) { return xparseint()*second }
throw new Error('bad duration '+s)
}
const formatDuration = (v: number) => {
if (v === 0) {
return ''
}
const is = (period: number) => v > 0 && Math.round(v/period) === v/period
const format = (period: number, s: string) => ''+(v/period)+s
if (is(week)) { return format(week, 'w') }
if (is(day)) { return format(day, 'd') }
if (is(hour)) { return format(hour, 'h') }
if (is(minute)) { return format(minute, 'm') }
return format(second, 's')
}
let importForm: HTMLFormElement
let importFieldset: HTMLFieldSetElement
let mailboxFileHint: HTMLElement
@ -231,6 +358,9 @@ const index = async () => {
let importProgress: HTMLElement
let importAbortBox: HTMLElement
let suppressionAddress: HTMLInputElement
let suppressionReason: HTMLInputElement
const importTrack = async (token: string) => {
const importConnection = dom.div('Waiting for updates...')
importProgress.appendChild(importConnection)
@ -345,6 +475,252 @@ const index = async () => {
)
}
const authorizationPopup = (dest: HTMLInputElement) => {
let username: HTMLInputElement
let password: HTMLInputElement
const close = popup(
dom.form(
function submit(e: SubmitEvent) {
e.preventDefault()
e.stopPropagation()
dest.value = 'Basic '+window.btoa(username.value+':'+password.value)
close()
},
dom.p('Compose HTTP Basic authentication header'),
dom.div(
style({marginBottom: '1ex'}),
dom.div(dom.label('Username')),
username=dom.input(attr.required('')),
),
dom.div(
style({marginBottom: '1ex'}),
dom.div(dom.label('Password (shown in clear)')),
password=dom.input(attr.required('')),
),
dom.div(
style({marginBottom: '1ex'}),
dom.submitbutton('Set'),
),
dom.div('A HTTP Basic authorization header contains the password in plain text, as base64.'),
),
)
username.focus()
}
const popupTestOutgoing = () => {
let fieldset: HTMLFieldSetElement
let event: HTMLSelectElement
let dsn: HTMLInputElement
let suppressing: HTMLInputElement
let queueMsgID: HTMLInputElement
let fromID: HTMLInputElement
let messageID: HTMLInputElement
let error: HTMLInputElement
let extra: HTMLInputElement
let body: HTMLTextAreaElement
let curl: HTMLElement
let result: HTMLElement
let data: api.Outgoing = {
Version: 0,
Event: api.OutgoingEvent.EventDelivered,
DSN: false,
Suppressing: false,
QueueMsgID: 123,
FromID: 'MDEyMzQ1Njc4OWFiY2RlZg',
MessageID: '<QnxzgulZK51utga6agH_rg@mox.example>',
Subject: 'test from mox web pages',
WebhookQueued: new Date(),
SMTPCode: 0,
SMTPEnhancedCode: '',
Error: '',
Extra: {},
}
const onchange = function change() {
data = {
Version: 0,
Event: event.value as api.OutgoingEvent,
DSN: dsn.checked,
Suppressing: suppressing.checked,
QueueMsgID: parseInt(queueMsgID.value),
FromID: fromID.value,
MessageID: messageID.value,
Subject: 'test from mox web pages',
WebhookQueued: new Date(),
SMTPCode: 0,
SMTPEnhancedCode: '',
Error: error.value,
Extra: JSON.parse(extra.value),
}
const curlStr = "curl " + (outgoingWebhookAuthorization.value ? "-H 'Authorization: "+outgoingWebhookAuthorization.value+"' " : "") + "-H 'X-Mox-Webhook-ID: 1' -H 'X-Mox-Webhook-Attempt: 1' --json '"+JSON.stringify(data)+"' '"+outgoingWebhookURL.value+"'"
dom._kids(curl, style({maxWidth: '45em', wordBreak: 'break-all'}), curlStr)
body.value = JSON.stringify(data, undefined, "\t")
}
popup(
dom.h1('Test webhook for outgoing delivery'),
dom.form(
async function submit(e: SubmitEvent) {
e.preventDefault()
e.stopPropagation()
result.classList.add('loadstart')
const [code, response, errmsg] = await check(fieldset, client.OutgoingWebhookTest(outgoingWebhookURL.value, outgoingWebhookAuthorization.value, data))
const nresult = dom.div(
dom._class('loadend'),
dom.table(
dom.tr(dom.td('HTTP status code'), dom.td(''+code)),
dom.tr(dom.td('Error message'), dom.td(errmsg)),
dom.tr(dom.td('Response'), dom.td(response)),
),
)
result.replaceWith(nresult)
result = nresult
},
fieldset=dom.fieldset(
dom.p('Make a test call to ', dom.b(outgoingWebhookURL.value), '.'),
dom.div(style({display: 'flex', gap: '1em'}),
dom.div(
dom.h2('Parameters'),
dom.div(
style({marginBottom: '.5ex'}),
dom.label(
'Event',
dom.div(
event=dom.select(onchange,
["delivered", "suppressed", "delayed", "failed", "relayed", "expanded", "canceled", "unrecognized"].map(s => dom.option(s.substring(0, 1).toUpperCase()+s.substring(1), attr.value(s))),
),
),
),
),
dom.div(style({marginBottom: '.5ex'}), dom.label(dsn=dom.input(attr.type('checkbox')), ' DSN', onchange)),
dom.div(style({marginBottom: '.5ex'}), dom.label(suppressing=dom.input(attr.type('checkbox')), ' Suppressing', onchange)),
dom.div(style({marginBottom: '.5ex'}), dom.label('Queue message ID ', dom.div(queueMsgID=dom.input(attr.required(''), attr.type('number'), attr.value('123'), onchange)))),
dom.div(style({marginBottom: '.5ex'}), dom.label('From ID ', dom.div(fromID=dom.input(attr.required(''), attr.value(data.FromID), onchange)))),
dom.div(style({marginBottom: '.5ex'}), dom.label('MessageID', dom.div(messageID=dom.input(attr.required(''), attr.value(data.MessageID), onchange)))),
dom.div(style({marginBottom: '.5ex'}), dom.label('Error', dom.div(error=dom.input(onchange)))),
dom.div(style({marginBottom: '.5ex'}), dom.label('Extra', dom.div(extra=dom.input(attr.required(''), attr.value('{}'), onchange)))),
),
dom.div(
dom.h2('Headers'),
dom.pre('X-Mox-Webhook-ID: 1\nX-Mox-Webhook-Attempt: 1'),
dom.br(),
dom.h2('JSON'),
body=dom.textarea(attr.disabled(''), attr.rows('15'), style({width: '30em'})),
dom.br(),
dom.h2('curl'),
curl=dom.div(dom._class('literal')),
),
),
dom.br(),
dom.div(style({textAlign: 'right'}), dom.submitbutton('Post')),
dom.br(),
result=dom.div(),
),
),
)
onchange()
}
const popupTestIncoming = () => {
let fieldset: HTMLFieldSetElement
let body: HTMLTextAreaElement
let curl: HTMLElement
let result: HTMLElement
let data: api.Incoming = {
Version: 0,
From: [{Name: 'remote', Address: 'remote@remote.example'}],
To: [{Name: 'mox', Address: 'mox@mox.example'}],
CC: [],
BCC: [],
ReplyTo: [],
Subject: 'test webhook for incoming message',
MessageID: '<QnxzgulZK51utga6agH_rg@mox.example>',
InReplyTo: '',
References: [],
Date: new Date(),
Text: 'hi ☺\n',
HTML: '',
Structure: {
ContentType: 'text/plain',
ContentTypeParams: {charset: 'utf-8'},
ContentID: '',
DecodedSize: 8,
Parts: [],
},
Meta: {
MsgID: 1,
MailFrom: 'remote@remote.example',
MailFromValidated: true,
MsgFromValidated: true,
RcptTo: 'mox@localhost',
DKIMVerifiedDomains: ['remote.example'],
RemoteIP: '127.0.0.1',
Received: new Date(),
MailboxName: 'Inbox',
Automated: false,
},
}
const onchange = function change() {
try {
api.parser.Incoming(JSON.parse(body.value))
} catch (err) {
console.log({err})
window.alert('Error parsing data: '+errmsg(err))
}
const curlStr = "curl " + (incomingWebhookAuthorization.value ? "-H 'Authorization: "+incomingWebhookAuthorization.value+"' " : "") + "-H 'X-Mox-Webhook-ID: 1' -H 'X-Mox-Webhook-Attempt: 1' --json '"+JSON.stringify(data)+"' '"+incomingWebhookURL.value+"'"
dom._kids(curl, style({maxWidth: '45em', wordBreak: 'break-all'}), curlStr)
}
popup(
dom.h1('Test webhook for incoming delivery'),
dom.form(
async function submit(e: SubmitEvent) {
e.preventDefault()
e.stopPropagation()
result.classList.add('loadstart')
const [code, response, errmsg] = await check(fieldset, (async () => await client.IncomingWebhookTest(incomingWebhookURL.value, incomingWebhookAuthorization.value, api.parser.Incoming(JSON.parse(body.value))))())
const nresult = dom.div(
dom._class('loadend'),
dom.table(
dom.tr(dom.td('HTTP status code'), dom.td(''+code)),
dom.tr(dom.td('Error message'), dom.td(errmsg)),
dom.tr(dom.td('Response'), dom.td(response)),
),
)
result.replaceWith(nresult)
result = nresult
},
fieldset=dom.fieldset(
dom.p('Make a test call to ', dom.b(incomingWebhookURL.value), '.'),
dom.div(style({display: 'flex', gap: '1em'}),
dom.div(
dom.h2('JSON'),
body=dom.textarea(style({maxHeight: '90vh'}), style({width: '30em'}), onchange),
),
dom.div(
dom.h2('Headers'),
dom.pre('X-Mox-Webhook-ID: 1\nX-Mox-Webhook-Attempt: 1'),
dom.br(),
dom.h2('curl'),
curl=dom.div(dom._class('literal')),
),
),
dom.br(),
dom.div(style({textAlign: 'right'}), dom.submitbutton('Post')),
dom.br(),
result=dom.div(),
),
),
)
body.value = JSON.stringify(data, undefined, '\t')
body.setAttribute('rows', ''+Math.min(40, (body.value.split('\n').length+1)))
onchange()
}
dom._kids(page,
crumbs('Mox Account'),
dom.p('NOTE: Not all account settings can be configured through these pages yet. See the configuration file for more options.'),
@ -386,6 +762,7 @@ const index = async () => {
),
),
dom.br(),
dom.h2('Change password'),
passwordForm=dom.form(
passwordFieldset=dom.fieldset(
@ -442,6 +819,7 @@ const index = async () => {
},
),
dom.br(),
dom.h2('Disk usage'),
dom.p('Storage used is ', dom.b(formatQuotaSize(Math.floor(storageUsed/(1024*1024))*1024*1024)),
storageLimit > 0 ? [
@ -450,6 +828,256 @@ const index = async () => {
''+Math.floor(100*storageUsed/storageLimit),
'%).',
] : [', no explicit limit is configured.']),
dom.h2('Webhooks'),
dom.h3('Outgoing', attr.title('Webhooks for outgoing messages are called for each attempt to deliver a message in the outgoing queue, e.g. when the queue has delivered a message to the next hop, when a single attempt failed with a temporary error, when delivery permanently failed, or when DSN (delivery status notification) messages were received about a previously sent message.')),
dom.form(
async function submit(e: SubmitEvent) {
e.preventDefault()
e.stopPropagation()
await check(outgoingWebhookFieldset, client.OutgoingWebhookSave(outgoingWebhookURL.value, outgoingWebhookAuthorization.value, [...outgoingWebhookEvents.selectedOptions].map(o => o.value)))
},
outgoingWebhookFieldset=dom.fieldset(
dom.div(style({display: 'flex', gap: '1em'}),
dom.div(
dom.label(
dom.div('URL', attr.title('URL to do an HTTP POST to for each event. Webhooks are disabled if empty.')),
outgoingWebhookURL=dom.input(attr.value(acc.OutgoingWebhook?.URL || ''), style({width: '30em'})),
),
),
dom.div(
dom.label(
dom.div(
'Authorization header ',
dom.a(
'Basic',
attr.href(''),
function click(e: MouseEvent) {
e.preventDefault()
authorizationPopup(outgoingWebhookAuthorization)
},
),
attr.title('If non-empty, HTTP requests have this value as Authorization header, e.g. Basic <base64-encoded-username-password>.'),
),
outgoingWebhookAuthorization=dom.input(attr.value(acc.OutgoingWebhook?.Authorization || '')),
),
),
dom.div(
dom.label(
style({verticalAlign: 'top'}),
dom.div('Events', attr.title('Either limit to specific events, or receive all events (default).')),
outgoingWebhookEvents=dom.select(
style({verticalAlign: 'bottom'}),
attr.multiple(''),
attr.size('8'), // Number of options.
["delivered", "suppressed", "delayed", "failed", "relayed", "expanded", "canceled", "unrecognized"].map(s => dom.option(s.substring(0, 1).toUpperCase()+s.substring(1), attr.value(s), acc.OutgoingWebhook?.Events?.includes(s) ? attr.selected('') : [])),
),
),
),
dom.div(
dom.div(dom.label('\u00a0')),
dom.submitbutton('Save'), ' ',
dom.clickbutton('Test', function click() {
popupTestOutgoing()
}),
),
),
),
),
dom.br(),
dom.h3('Incoming', attr.title('Webhooks for incoming messages are called for each message received over SMTP, excluding DSN messages about previous deliveries.')),
dom.form(
async function submit(e: SubmitEvent) {
e.preventDefault()
e.stopPropagation()
await check(incomingWebhookFieldset, client.IncomingWebhookSave(incomingWebhookURL.value, incomingWebhookAuthorization.value))
},
incomingWebhookFieldset=dom.fieldset(
dom.div(
style({display: 'flex', gap: '1em'}),
dom.div(
dom.label(
dom.div('URL'),
incomingWebhookURL=dom.input(attr.value(acc.IncomingWebhook?.URL || ''), style({width: '30em'})),
),
),
dom.div(
dom.label(
dom.div(
'Authorization header ',
dom.a(
'Basic',
attr.href(''),
function click(e: MouseEvent) {
e.preventDefault()
authorizationPopup(incomingWebhookAuthorization)
},
),
attr.title('If non-empty, HTTP requests have this value as Authorization header, e.g. Basic <base64-encoded-username-password>.'),
),
incomingWebhookAuthorization=dom.input(attr.value(acc.IncomingWebhook?.Authorization || '')),
),
),
dom.div(
dom.div(dom.label('\u00a0')),
dom.submitbutton('Save'), ' ',
dom.clickbutton('Test', function click() {
popupTestIncoming()
}),
),
),
),
),
dom.br(),
dom.h2('Keep messages/webhooks retired from queue', attr.title('After delivering a message or webhook from the queue it is removed by default. But you can also keep these "retired" messages/webhooks around for a while. With unique SMTP MAIL FROM addresses configured below, this allows relating incoming delivery status notification messages (DSNs) to previously sent messages and their original recipients, which is needed for automatic management of recipient suppression lists, which is important for managing the reputation of your mail server. For both messages and webhooks, this can be useful for debugging. Use values like "3d" for 3 days, or units "s" for second, "m" for minute, "h" for hour, "w" for week.')),
dom.form(
async function submit(e: SubmitEvent) {
e.preventDefault()
e.stopPropagation()
await check(keepRetiredPeriodsFieldset, (async () => await client.KeepRetiredPeriodsSave(parseDuration(keepRetiredMessagePeriod.value), parseDuration(keepRetiredWebhookPeriod.value)))())
},
keepRetiredPeriodsFieldset=dom.fieldset(
dom.div(
style({display: 'flex', gap: '1em', alignItems: 'flex-end'}),
dom.div(
dom.label(
'Messages deliveries',
dom.br(),
keepRetiredMessagePeriod=dom.input(attr.value(formatDuration(acc.KeepRetiredMessagePeriod))),
),
),
dom.div(
dom.label(
'Webhook deliveries',
dom.br(),
keepRetiredWebhookPeriod=dom.input(attr.value(formatDuration(acc.KeepRetiredWebhookPeriod))),
),
),
dom.div(
dom.submitbutton('Save'),
),
),
),
),
dom.br(),
dom.h2('Unique SMTP MAIL FROM login addresses', attr.title('Outgoing messages are normally sent using your email address in the SMTP MAIL FROM command. By using unique addresses (by using the localpart catchall separator, e.g. addresses of the form "localpart+<uniquefromid>@domain"), future incoming DSNs can be related to the original outgoing messages and recipients, which allows for automatic management of recipient suppression lists when keeping retired messages for as long as you expect DSNs to come in as configured above. Configure the addresses used for logging in with SMTP submission, the webapi or webmail for which unique SMTP MAIL FROM addesses should be enabled. Note: These are addresses used for authenticating, not the address in the message "From" header.')),
(() => {
let inputs: HTMLInputElement[] = []
let elem: HTMLElement
const render = () => {
inputs = []
const e = dom.form(
async function submit(e: SubmitEvent) {
e.preventDefault()
e.stopPropagation()
await check(fromIDLoginAddressesFieldset, client.FromIDLoginAddressesSave(inputs.map(e => e.value)))
},
fromIDLoginAddressesFieldset=dom.fieldset(
dom.table(
dom.tbody(
(acc.FromIDLoginAddresses || []).length === 0 ? dom.tr(dom.td('(None)'), dom.td()) : [],
(acc.FromIDLoginAddresses || []).map((s, index) => {
const input = dom.input(attr.required(''), attr.value(s))
inputs.push(input)
const x = dom.tr(
dom.td(input),
dom.td(
dom.clickbutton('Remove', function click() {
acc.FromIDLoginAddresses!.splice(index, 1)
render()
}),
),
)
return x
}),
),
dom.tfoot(
dom.tr(
dom.td(),
dom.td(
dom.clickbutton('Add', function click() {
acc.FromIDLoginAddresses = (acc.FromIDLoginAddresses || []).concat([''])
render()
}),
),
),
dom.tr(
dom.td(attr.colspan('2'), dom.submitbutton('Save')),
),
),
),
),
)
if (elem) {
elem.replaceWith(e)
elem = e
}
return e
}
elem = render()
return elem
})(),
dom.br(),
dom.h2('Suppression list'),
dom.p('Messages queued for delivery to recipients on the suppression list will immediately fail. If delivery to a recipient fails repeatedly, it can be added to the suppression list automatically. Repeated rejected delivery attempts can have a negative influence of mail server reputation. Applications sending email can implement their own handling of delivery failure notifications, but not all do.'),
dom.form(
attr.id('suppressionAdd'),
async function submit(e: SubmitEvent) {
e.preventDefault()
e.stopPropagation()
await check(e.target! as HTMLButtonElement, client.SuppressionAdd(suppressionAddress.value, true, suppressionReason.value))
window.location.reload() // todo: reload less
},
),
dom.table(
dom.thead(
dom.tr(
dom.th('Address', attr.title('Address that caused this entry to be added to the list. The title (shown on hover) displays an address with a fictional simplified localpart, with lower-cased, dots removed, only first part before "+" or "-" (typicaly catchall separators). When checking if an address is on the suppression list, it is checked against this address.')),
dom.th('Manual', attr.title('Whether suppression was added manually, instead of automatically based on bounces.')),
dom.th('Reason'),
dom.th('Since'),
dom.th('Action'),
),
),
dom.tbody(
(suppressions || []).length === 0 ? dom.tr(dom.td(attr.colspan('5'), '(None)')) : [],
(suppressions || []).map(s =>
dom.tr(
dom.td(s.OriginalAddress, attr.title(s.BaseAddress)),
dom.td(s.Manual ? '✓' : ''),
dom.td(s.Reason),
dom.td(age(s.Created)),
dom.td(
dom.clickbutton('Remove', async function click(e: MouseEvent) {
await check(e.target! as HTMLButtonElement, client.SuppressionRemove(s.OriginalAddress))
window.location.reload() // todo: reload less
})
),
),
),
),
dom.tfoot(
dom.tr(
dom.td(suppressionAddress=dom.input(attr.type('required'), attr.form('suppressionAdd'))),
dom.td(),
dom.td(suppressionReason=dom.input(style({width: '100%'}), attr.form('suppressionAdd'))),
dom.td(),
dom.td(dom.submitbutton('Add suppression', attr.form('suppressionAdd'))),
),
),
),
dom.br(),
dom.h2('Export'),
dom.p('Export all messages in all mailboxes. In maildir or mbox format, as .zip or .tgz file.'),
dom.table(dom._class('slim'),
@ -471,6 +1099,7 @@ const index = async () => {
),
),
dom.br(),
dom.h2('Import'),
dom.p('Import messages from a .zip or .tgz file with maildirs and/or mbox files.'),
importForm=dom.form(
@ -570,6 +1199,8 @@ const index = async () => {
importProgress=dom.div(
style({display: 'none'}),
),
dom.br(),
footer,
)
@ -744,6 +1375,7 @@ const destination = async (name: string) => {
fullName=dom.input(attr.value(dest.FullName)),
),
dom.br(),
dom.h2('Rulesets'),
dom.p('Incoming messages are checked against the rulesets. If a ruleset matches, the message is delivered to the mailbox configured for the ruleset instead of to the default mailbox.'),
dom.p('"Is Forward" does not affect matching, but changes prevents the sending mail server from being included in future junk classifications by clearing fields related to the forwarding email server (IP address, EHLO domain, MAIL FROM domain and a matching DKIM domain), and prevents DMARC rejects for forwarded messages.'),

View File

@ -16,18 +16,22 @@ import (
"os"
"path"
"path/filepath"
"reflect"
"runtime/debug"
"sort"
"strings"
"testing"
"time"
"github.com/mjl-/bstore"
"github.com/mjl-/sherpa"
"github.com/mjl-/mox/mlog"
"github.com/mjl-/mox/mox-"
"github.com/mjl-/mox/queue"
"github.com/mjl-/mox/store"
"github.com/mjl-/mox/webauth"
"github.com/mjl-/mox/webhook"
)
var ctxbg = context.Background()
@ -73,6 +77,13 @@ func tneedErrorCode(t *testing.T, code string, fn func()) {
fn()
}
func tcompare(t *testing.T, got, expect any) {
t.Helper()
if !reflect.DeepEqual(got, expect) {
t.Fatalf("got:\n%#v\nexpected:\n%#v", got, expect)
}
}
func TestAccount(t *testing.T) {
os.RemoveAll("../testdata/httpaccount/data")
mox.ConfigStaticPath = filepath.FromSlash("../testdata/httpaccount/mox.conf")
@ -216,7 +227,9 @@ func TestAccount(t *testing.T) {
api.SetPassword(ctx, "test1234")
account, _, _ := api.Account(ctx)
err = queue.Init() // For DB.
tcheck(t, err, "queue init")
account, _, _, _ := api.Account(ctx)
api.DestinationSave(ctx, "mjl☺@mox.example", account.Destinations["mjl☺@mox.example"], account.Destinations["mjl☺@mox.example"]) // todo: save modified value and compare it afterwards
api.AccountSaveFullName(ctx, account.FullName+" changed") // todo: check if value was changed
@ -371,6 +384,59 @@ func TestAccount(t *testing.T) {
testExport("/export/mail-export-mbox.tgz", false, 2)
testExport("/export/mail-export-mbox.zip", true, 2)
sl := api.SuppressionList(ctx)
tcompare(t, len(sl), 0)
api.SuppressionAdd(ctx, "mjl@mox.example", true, "testing")
tneedErrorCode(t, "user:error", func() { api.SuppressionAdd(ctx, "mjl@mox.example", true, "testing") }) // Duplicate.
tneedErrorCode(t, "user:error", func() { api.SuppressionAdd(ctx, "bogus", true, "testing") }) // Bad address.
sl = api.SuppressionList(ctx)
tcompare(t, len(sl), 1)
api.SuppressionRemove(ctx, "mjl@mox.example")
tneedErrorCode(t, "user:error", func() { api.SuppressionRemove(ctx, "mjl@mox.example") }) // Absent.
tneedErrorCode(t, "user:error", func() { api.SuppressionRemove(ctx, "bogus") }) // Not an address.
var hooks int
hookServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "ok")
hooks++
}))
defer hookServer.Close()
api.OutgoingWebhookSave(ctx, "http://localhost:1234", "Basic base64", []string{"delivered"})
api.OutgoingWebhookSave(ctx, "http://localhost:1234", "Basic base64", []string{})
tneedErrorCode(t, "user:error", func() {
api.OutgoingWebhookSave(ctx, "http://localhost:1234/outgoing", "Basic base64", []string{"bogus"})
})
tneedErrorCode(t, "user:error", func() { api.OutgoingWebhookSave(ctx, "invalid", "Basic base64", nil) })
api.OutgoingWebhookSave(ctx, "", "", nil) // Restore.
code, response, errmsg := api.OutgoingWebhookTest(ctx, hookServer.URL, "", webhook.Outgoing{})
tcompare(t, code, 200)
tcompare(t, response, "ok\n")
tcompare(t, errmsg, "")
tneedErrorCode(t, "user:error", func() { api.OutgoingWebhookTest(ctx, "bogus", "", webhook.Outgoing{}) })
api.IncomingWebhookSave(ctx, "http://localhost:1234", "Basic base64")
tneedErrorCode(t, "user:error", func() { api.IncomingWebhookSave(ctx, "invalid", "Basic base64") })
api.IncomingWebhookSave(ctx, "", "") // Restore.
code, response, errmsg = api.IncomingWebhookTest(ctx, hookServer.URL, "", webhook.Incoming{})
tcompare(t, code, 200)
tcompare(t, response, "ok\n")
tcompare(t, errmsg, "")
tneedErrorCode(t, "user:error", func() { api.IncomingWebhookTest(ctx, "bogus", "", webhook.Incoming{}) })
api.FromIDLoginAddressesSave(ctx, []string{"mjl☺@mox.example"})
api.FromIDLoginAddressesSave(ctx, []string{"mjl☺@mox.example", "mjl☺+fromid@mox.example"})
api.FromIDLoginAddressesSave(ctx, []string{})
tneedErrorCode(t, "user:error", func() { api.FromIDLoginAddressesSave(ctx, []string{"bogus@other.example"}) })
api.KeepRetiredPeriodsSave(ctx, time.Minute, time.Minute)
api.KeepRetiredPeriodsSave(ctx, 0, 0) // Restore.
api.Logout(ctx)
tneedErrorCode(t, "server:error", func() { api.Logout(ctx) })
}

View File

@ -88,12 +88,19 @@
"Typewords": [
"int64"
]
},
{
"Name": "suppressions",
"Typewords": [
"[]",
"Suppression"
]
}
]
},
{
"Name": "AccountSaveFullName",
"Docs": "",
"Docs": "AccountSaveFullName saves the full name (used as display name in email messages)\nfor the account.",
"Params": [
{
"Name": "fullName",
@ -154,6 +161,231 @@
]
}
]
},
{
"Name": "SuppressionList",
"Docs": "SuppressionList lists the addresses on the suppression list of this account.",
"Params": [],
"Returns": [
{
"Name": "suppressions",
"Typewords": [
"[]",
"Suppression"
]
}
]
},
{
"Name": "SuppressionAdd",
"Docs": "SuppressionAdd adds an email address to the suppression list.",
"Params": [
{
"Name": "address",
"Typewords": [
"string"
]
},
{
"Name": "manual",
"Typewords": [
"bool"
]
},
{
"Name": "reason",
"Typewords": [
"string"
]
}
],
"Returns": [
{
"Name": "suppression",
"Typewords": [
"Suppression"
]
}
]
},
{
"Name": "SuppressionRemove",
"Docs": "SuppressionRemove removes the email address from the suppression list.",
"Params": [
{
"Name": "address",
"Typewords": [
"string"
]
}
],
"Returns": []
},
{
"Name": "OutgoingWebhookSave",
"Docs": "OutgoingWebhookSave saves a new webhook url for outgoing deliveries. If url\nis empty, the webhook is disabled. If authorization is non-empty it is used for\nthe Authorization header in HTTP requests. Events specifies the outgoing events\nto be delivered, or all if empty/nil.",
"Params": [
{
"Name": "url",
"Typewords": [
"string"
]
},
{
"Name": "authorization",
"Typewords": [
"string"
]
},
{
"Name": "events",
"Typewords": [
"[]",
"string"
]
}
],
"Returns": []
},
{
"Name": "OutgoingWebhookTest",
"Docs": "OutgoingWebhookTest makes a test webhook call to urlStr, with optional\nauthorization. If the HTTP request is made this call will succeed also for\nnon-2xx HTTP status codes.",
"Params": [
{
"Name": "urlStr",
"Typewords": [
"string"
]
},
{
"Name": "authorization",
"Typewords": [
"string"
]
},
{
"Name": "data",
"Typewords": [
"Outgoing"
]
}
],
"Returns": [
{
"Name": "code",
"Typewords": [
"int32"
]
},
{
"Name": "response",
"Typewords": [
"string"
]
},
{
"Name": "errmsg",
"Typewords": [
"string"
]
}
]
},
{
"Name": "IncomingWebhookSave",
"Docs": "IncomingWebhookSave saves a new webhook url for incoming deliveries. If url is\nempty, the webhook is disabled. If authorization is not empty, it is used in\nthe Authorization header in requests.",
"Params": [
{
"Name": "url",
"Typewords": [
"string"
]
},
{
"Name": "authorization",
"Typewords": [
"string"
]
}
],
"Returns": []
},
{
"Name": "IncomingWebhookTest",
"Docs": "IncomingWebhookTest makes a test webhook HTTP delivery request to urlStr,\nwith optional authorization header. If the HTTP call is made, this function\nreturns non-error regardless of HTTP status code.",
"Params": [
{
"Name": "urlStr",
"Typewords": [
"string"
]
},
{
"Name": "authorization",
"Typewords": [
"string"
]
},
{
"Name": "data",
"Typewords": [
"Incoming"
]
}
],
"Returns": [
{
"Name": "code",
"Typewords": [
"int32"
]
},
{
"Name": "response",
"Typewords": [
"string"
]
},
{
"Name": "errmsg",
"Typewords": [
"string"
]
}
]
},
{
"Name": "FromIDLoginAddressesSave",
"Docs": "FromIDLoginAddressesSave saves new login addresses to enable unique SMTP\nMAIL FROM addresses (\"fromid\") for deliveries from the queue.",
"Params": [
{
"Name": "loginAddresses",
"Typewords": [
"[]",
"string"
]
}
],
"Returns": []
},
{
"Name": "KeepRetiredPeriodsSave",
"Docs": "KeepRetiredPeriodsSave save periods to save retired messages and webhooks.",
"Params": [
{
"Name": "keepRetiredMessagePeriod",
"Typewords": [
"int64"
]
},
{
"Name": "keepRetiredWebhookPeriod",
"Typewords": [
"int64"
]
}
],
"Returns": []
}
],
"Sections": [],
@ -162,6 +394,44 @@
"Name": "Account",
"Docs": "",
"Fields": [
{
"Name": "OutgoingWebhook",
"Docs": "",
"Typewords": [
"nullable",
"OutgoingWebhook"
]
},
{
"Name": "IncomingWebhook",
"Docs": "",
"Typewords": [
"nullable",
"IncomingWebhook"
]
},
{
"Name": "FromIDLoginAddresses",
"Docs": "",
"Typewords": [
"[]",
"string"
]
},
{
"Name": "KeepRetiredMessagePeriod",
"Docs": "",
"Typewords": [
"int64"
]
},
{
"Name": "KeepRetiredWebhookPeriod",
"Docs": "",
"Typewords": [
"int64"
]
},
{
"Name": "Domain",
"Docs": "",
@ -272,6 +542,54 @@
}
]
},
{
"Name": "OutgoingWebhook",
"Docs": "",
"Fields": [
{
"Name": "URL",
"Docs": "",
"Typewords": [
"string"
]
},
{
"Name": "Authorization",
"Docs": "",
"Typewords": [
"string"
]
},
{
"Name": "Events",
"Docs": "",
"Typewords": [
"[]",
"string"
]
}
]
},
{
"Name": "IncomingWebhook",
"Docs": "",
"Fields": [
{
"Name": "URL",
"Docs": "",
"Typewords": [
"string"
]
},
{
"Name": "Authorization",
"Docs": "",
"Typewords": [
"string"
]
}
]
},
{
"Name": "Destination",
"Docs": "",
@ -551,6 +869,61 @@
}
]
},
{
"Name": "Suppression",
"Docs": "Suppression is an address to which messages will not be delivered. Attempts to\ndeliver or queue will result in an immediate permanent failure to deliver.",
"Fields": [
{
"Name": "ID",
"Docs": "",
"Typewords": [
"int64"
]
},
{
"Name": "Created",
"Docs": "",
"Typewords": [
"timestamp"
]
},
{
"Name": "Account",
"Docs": "Suppression applies to this account only.",
"Typewords": [
"string"
]
},
{
"Name": "BaseAddress",
"Docs": "Unicode. Address with fictional simplified localpart: lowercase, dots removed (gmail), first token before any \"-\" or \"+\" (typical catchall separator).",
"Typewords": [
"string"
]
},
{
"Name": "OriginalAddress",
"Docs": "Unicode. Address that caused this suppression.",
"Typewords": [
"string"
]
},
{
"Name": "Manual",
"Docs": "",
"Typewords": [
"bool"
]
},
{
"Name": "Reason",
"Docs": "",
"Typewords": [
"string"
]
}
]
},
{
"Name": "ImportProgress",
"Docs": "ImportProgress is returned after uploading a file to import.",
@ -563,6 +936,362 @@
]
}
]
},
{
"Name": "Outgoing",
"Docs": "Outgoing is the payload sent to webhook URLs for events about outgoing deliveries.",
"Fields": [
{
"Name": "Version",
"Docs": "Format of hook, currently 0.",
"Typewords": [
"int32"
]
},
{
"Name": "Event",
"Docs": "Type of outgoing delivery event.",
"Typewords": [
"OutgoingEvent"
]
},
{
"Name": "DSN",
"Docs": "If this event was triggered by a delivery status notification message (DSN).",
"Typewords": [
"bool"
]
},
{
"Name": "Suppressing",
"Docs": "If true, this failure caused the address to be added to the suppression list.",
"Typewords": [
"bool"
]
},
{
"Name": "QueueMsgID",
"Docs": "ID of message in queue.",
"Typewords": [
"int64"
]
},
{
"Name": "FromID",
"Docs": "As used in MAIL FROM, can be empty, for incoming messages.",
"Typewords": [
"string"
]
},
{
"Name": "MessageID",
"Docs": "From Message-Id header, as set by submitter or us, with enclosing \u003c\u003e.",
"Typewords": [
"string"
]
},
{
"Name": "Subject",
"Docs": "Of original message.",
"Typewords": [
"string"
]
},
{
"Name": "WebhookQueued",
"Docs": "When webhook was first queued for delivery.",
"Typewords": [
"timestamp"
]
},
{
"Name": "SMTPCode",
"Docs": "Optional, for errors only, e.g. 451, 550. See package smtp for definitions.",
"Typewords": [
"int32"
]
},
{
"Name": "SMTPEnhancedCode",
"Docs": "Optional, for errors only, e.g. 5.1.1.",
"Typewords": [
"string"
]
},
{
"Name": "Error",
"Docs": "Error message while delivering, or from DSN from remote, if any.",
"Typewords": [
"string"
]
},
{
"Name": "Extra",
"Docs": "Extra fields set for message during submit, through webapi call or through X-Mox-Extra-* headers during SMTP submission.",
"Typewords": [
"{}",
"string"
]
}
]
},
{
"Name": "Incoming",
"Docs": "Incoming is the data sent to a webhook for incoming deliveries over SMTP.",
"Fields": [
{
"Name": "Version",
"Docs": "Format of hook, currently 0.",
"Typewords": [
"int32"
]
},
{
"Name": "From",
"Docs": "Message \"From\" header, typically has one address.",
"Typewords": [
"[]",
"NameAddress"
]
},
{
"Name": "To",
"Docs": "",
"Typewords": [
"[]",
"NameAddress"
]
},
{
"Name": "CC",
"Docs": "",
"Typewords": [
"[]",
"NameAddress"
]
},
{
"Name": "BCC",
"Docs": "Often empty, even if you were a BCC recipient.",
"Typewords": [
"[]",
"NameAddress"
]
},
{
"Name": "ReplyTo",
"Docs": "Optional Reply-To header, typically absent or with one address.",
"Typewords": [
"[]",
"NameAddress"
]
},
{
"Name": "Subject",
"Docs": "",
"Typewords": [
"string"
]
},
{
"Name": "MessageID",
"Docs": "Of Message-Id header, typically of the form \"\u003crandom@hostname\u003e\", includes \u003c\u003e.",
"Typewords": [
"string"
]
},
{
"Name": "InReplyTo",
"Docs": "Optional, the message-id this message is a reply to. Includes \u003c\u003e.",
"Typewords": [
"string"
]
},
{
"Name": "References",
"Docs": "Optional, zero or more message-ids this message is a reply/forward/related to. The last entry is the most recent/immediate message this is a reply to. Earlier entries are the parents in a thread. Values include \u003c\u003e.",
"Typewords": [
"[]",
"string"
]
},
{
"Name": "Date",
"Docs": "Time in \"Date\" message header, can be different from time received.",
"Typewords": [
"nullable",
"timestamp"
]
},
{
"Name": "Text",
"Docs": "Contents of text/plain and/or text/html part (if any), with \"\\n\" line-endings, converted from \"\\r\\n\". Values are truncated to 1MB (1024*1024 bytes). Use webapi MessagePartGet to retrieve the full part data.",
"Typewords": [
"string"
]
},
{
"Name": "HTML",
"Docs": "",
"Typewords": [
"string"
]
},
{
"Name": "Structure",
"Docs": "Parsed form of MIME message.",
"Typewords": [
"Structure"
]
},
{
"Name": "Meta",
"Docs": "Details about message in storage, and SMTP transaction details.",
"Typewords": [
"IncomingMeta"
]
}
]
},
{
"Name": "NameAddress",
"Docs": "",
"Fields": [
{
"Name": "Name",
"Docs": "Optional, human-readable \"display name\" of the addressee.",
"Typewords": [
"string"
]
},
{
"Name": "Address",
"Docs": "Required, email address.",
"Typewords": [
"string"
]
}
]
},
{
"Name": "Structure",
"Docs": "",
"Fields": [
{
"Name": "ContentType",
"Docs": "Lower case, e.g. text/plain.",
"Typewords": [
"string"
]
},
{
"Name": "ContentTypeParams",
"Docs": "Lower case keys, original case values, e.g. {\"charset\": \"UTF-8\"}.",
"Typewords": [
"{}",
"string"
]
},
{
"Name": "ContentID",
"Docs": "Can be empty. Otherwise, should be a value wrapped in \u003c\u003e's. For use in HTML, referenced as URI `cid:...`.",
"Typewords": [
"string"
]
},
{
"Name": "DecodedSize",
"Docs": "Size of content after decoding content-transfer-encoding. For text and HTML parts, this can be larger than the data returned since this size includes \\r\\n line endings.",
"Typewords": [
"int64"
]
},
{
"Name": "Parts",
"Docs": "Subparts of a multipart message, possibly recursive.",
"Typewords": [
"[]",
"Structure"
]
}
]
},
{
"Name": "IncomingMeta",
"Docs": "",
"Fields": [
{
"Name": "MsgID",
"Docs": "ID of message in storage, and to use in webapi calls like MessageGet.",
"Typewords": [
"int64"
]
},
{
"Name": "MailFrom",
"Docs": "Address used during SMTP \"MAIL FROM\" command.",
"Typewords": [
"string"
]
},
{
"Name": "MailFromValidated",
"Docs": "Whether SMTP MAIL FROM address was SPF-validated.",
"Typewords": [
"bool"
]
},
{
"Name": "MsgFromValidated",
"Docs": "Whether address in message \"From\"-header was DMARC(-like) validated.",
"Typewords": [
"bool"
]
},
{
"Name": "RcptTo",
"Docs": "SMTP RCPT TO address used in SMTP.",
"Typewords": [
"string"
]
},
{
"Name": "DKIMVerifiedDomains",
"Docs": "Verified domains from DKIM-signature in message. Can be different domain than used in addresses.",
"Typewords": [
"[]",
"string"
]
},
{
"Name": "RemoteIP",
"Docs": "Where the message was delivered from.",
"Typewords": [
"string"
]
},
{
"Name": "Received",
"Docs": "When message was received, may be different from the Date header.",
"Typewords": [
"timestamp"
]
},
{
"Name": "MailboxName",
"Docs": "Mailbox where message was delivered to, based on configured rules. Defaults to \"Inbox\".",
"Typewords": [
"string"
]
},
{
"Name": "Automated",
"Docs": "Whether this message was automated and should not receive automated replies. E.g. out of office or mailing list messages.",
"Typewords": [
"bool"
]
}
]
}
],
"Ints": [],
@ -571,6 +1300,52 @@
"Name": "CSRFToken",
"Docs": "",
"Values": null
},
{
"Name": "OutgoingEvent",
"Docs": "OutgoingEvent is an activity for an outgoing delivery. Either generated by the\nqueue, or through an incoming DSN (delivery status notification) message.",
"Values": [
{
"Name": "EventDelivered",
"Value": "delivered",
"Docs": "Message was accepted by a next-hop server. This does not necessarily mean the\nmessage has been delivered in the mailbox of the user."
},
{
"Name": "EventSuppressed",
"Value": "suppressed",
"Docs": "Outbound delivery was suppressed because the recipient address is on the\nsuppression list of the account, or a simplified/base variant of the address is."
},
{
"Name": "EventDelayed",
"Value": "delayed",
"Docs": "A delivery attempt failed but delivery will be retried again later."
},
{
"Name": "EventFailed",
"Value": "failed",
"Docs": "Delivery of the message failed and will not be tried again. Also see the\n\"Suppressing\" field of [Outgoing]."
},
{
"Name": "EventRelayed",
"Value": "relayed",
"Docs": "Message was relayed into a system that does not generate DSNs. Should only\nhappen when explicitly requested."
},
{
"Name": "EventExpanded",
"Value": "expanded",
"Docs": "Message was accepted and is being delivered to multiple recipients (e.g. the\naddress was an alias/list), which may generate more DSNs."
},
{
"Name": "EventCanceled",
"Value": "canceled",
"Docs": "Message was removed from the queue, e.g. canceled by admin/user."
},
{
"Name": "EventUnrecognized",
"Value": "unrecognized",
"Docs": "An incoming message was received that was either a DSN with an unknown event\ntype (\"action\"), or an incoming non-DSN-message was received for the unique\nper-outgoing-message address used for sending."
}
]
}
],
"SherpaVersion": 0,

View File

@ -3,6 +3,11 @@
namespace api {
export interface Account {
OutgoingWebhook?: OutgoingWebhook | null
IncomingWebhook?: IncomingWebhook | null
FromIDLoginAddresses?: string[] | null
KeepRetiredMessagePeriod: number
KeepRetiredWebhookPeriod: number
Domain: string
Description: string
FullName: string
@ -20,6 +25,17 @@ export interface Account {
DNSDomain: Domain // Parsed form of Domain.
}
export interface OutgoingWebhook {
URL: string
Authorization: string
Events?: string[] | null
}
export interface IncomingWebhook {
URL: string
Authorization: string
}
export interface Destination {
Mailbox: string
Rulesets?: Ruleset[] | null
@ -78,18 +94,120 @@ export interface Route {
ToDomainASCII?: string[] | null
}
// Suppression is an address to which messages will not be delivered. Attempts to
// deliver or queue will result in an immediate permanent failure to deliver.
export interface Suppression {
ID: number
Created: Date
Account: string // Suppression applies to this account only.
BaseAddress: string // Unicode. Address with fictional simplified localpart: lowercase, dots removed (gmail), first token before any "-" or "+" (typical catchall separator).
OriginalAddress: string // Unicode. Address that caused this suppression.
Manual: boolean
Reason: string
}
// ImportProgress is returned after uploading a file to import.
export interface ImportProgress {
Token: string // For fetching progress, or cancelling an import.
}
// Outgoing is the payload sent to webhook URLs for events about outgoing deliveries.
export interface Outgoing {
Version: number // Format of hook, currently 0.
Event: OutgoingEvent // Type of outgoing delivery event.
DSN: boolean // If this event was triggered by a delivery status notification message (DSN).
Suppressing: boolean // If true, this failure caused the address to be added to the suppression list.
QueueMsgID: number // ID of message in queue.
FromID: string // As used in MAIL FROM, can be empty, for incoming messages.
MessageID: string // From Message-Id header, as set by submitter or us, with enclosing <>.
Subject: string // Of original message.
WebhookQueued: Date // When webhook was first queued for delivery.
SMTPCode: number // Optional, for errors only, e.g. 451, 550. See package smtp for definitions.
SMTPEnhancedCode: string // Optional, for errors only, e.g. 5.1.1.
Error: string // Error message while delivering, or from DSN from remote, if any.
Extra?: { [key: string]: string } // Extra fields set for message during submit, through webapi call or through X-Mox-Extra-* headers during SMTP submission.
}
// Incoming is the data sent to a webhook for incoming deliveries over SMTP.
export interface Incoming {
Version: number // Format of hook, currently 0.
From?: NameAddress[] | null // Message "From" header, typically has one address.
To?: NameAddress[] | null
CC?: NameAddress[] | null
BCC?: NameAddress[] | null // Often empty, even if you were a BCC recipient.
ReplyTo?: NameAddress[] | null // Optional Reply-To header, typically absent or with one address.
Subject: string
MessageID: string // Of Message-Id header, typically of the form "<random@hostname>", includes <>.
InReplyTo: string // Optional, the message-id this message is a reply to. Includes <>.
References?: string[] | null // Optional, zero or more message-ids this message is a reply/forward/related to. The last entry is the most recent/immediate message this is a reply to. Earlier entries are the parents in a thread. Values include <>.
Date?: Date | null // Time in "Date" message header, can be different from time received.
Text: string // Contents of text/plain and/or text/html part (if any), with "\n" line-endings, converted from "\r\n". Values are truncated to 1MB (1024*1024 bytes). Use webapi MessagePartGet to retrieve the full part data.
HTML: string
Structure: Structure // Parsed form of MIME message.
Meta: IncomingMeta // Details about message in storage, and SMTP transaction details.
}
export interface NameAddress {
Name: string // Optional, human-readable "display name" of the addressee.
Address: string // Required, email address.
}
export interface Structure {
ContentType: string // Lower case, e.g. text/plain.
ContentTypeParams?: { [key: string]: string } // Lower case keys, original case values, e.g. {"charset": "UTF-8"}.
ContentID: string // Can be empty. Otherwise, should be a value wrapped in <>'s. For use in HTML, referenced as URI `cid:...`.
DecodedSize: number // Size of content after decoding content-transfer-encoding. For text and HTML parts, this can be larger than the data returned since this size includes \r\n line endings.
Parts?: Structure[] | null // Subparts of a multipart message, possibly recursive.
}
export interface IncomingMeta {
MsgID: number // ID of message in storage, and to use in webapi calls like MessageGet.
MailFrom: string // Address used during SMTP "MAIL FROM" command.
MailFromValidated: boolean // Whether SMTP MAIL FROM address was SPF-validated.
MsgFromValidated: boolean // Whether address in message "From"-header was DMARC(-like) validated.
RcptTo: string // SMTP RCPT TO address used in SMTP.
DKIMVerifiedDomains?: string[] | null // Verified domains from DKIM-signature in message. Can be different domain than used in addresses.
RemoteIP: string // Where the message was delivered from.
Received: Date // When message was received, may be different from the Date header.
MailboxName: string // Mailbox where message was delivered to, based on configured rules. Defaults to "Inbox".
Automated: boolean // Whether this message was automated and should not receive automated replies. E.g. out of office or mailing list messages.
}
export type CSRFToken = string
export const structTypes: {[typename: string]: boolean} = {"Account":true,"AutomaticJunkFlags":true,"Destination":true,"Domain":true,"ImportProgress":true,"JunkFilter":true,"Route":true,"Ruleset":true,"SubjectPass":true}
export const stringsTypes: {[typename: string]: boolean} = {"CSRFToken":true}
// OutgoingEvent is an activity for an outgoing delivery. Either generated by the
// queue, or through an incoming DSN (delivery status notification) message.
export enum OutgoingEvent {
// Message was accepted by a next-hop server. This does not necessarily mean the
// message has been delivered in the mailbox of the user.
EventDelivered = "delivered",
// Outbound delivery was suppressed because the recipient address is on the
// suppression list of the account, or a simplified/base variant of the address is.
EventSuppressed = "suppressed",
EventDelayed = "delayed", // A delivery attempt failed but delivery will be retried again later.
// Delivery of the message failed and will not be tried again. Also see the
// "Suppressing" field of [Outgoing].
EventFailed = "failed",
// Message was relayed into a system that does not generate DSNs. Should only
// happen when explicitly requested.
EventRelayed = "relayed",
// Message was accepted and is being delivered to multiple recipients (e.g. the
// address was an alias/list), which may generate more DSNs.
EventExpanded = "expanded",
EventCanceled = "canceled", // Message was removed from the queue, e.g. canceled by admin/user.
// An incoming message was received that was either a DSN with an unknown event
// type ("action"), or an incoming non-DSN-message was received for the unique
// per-outgoing-message address used for sending.
EventUnrecognized = "unrecognized",
}
export const structTypes: {[typename: string]: boolean} = {"Account":true,"AutomaticJunkFlags":true,"Destination":true,"Domain":true,"ImportProgress":true,"Incoming":true,"IncomingMeta":true,"IncomingWebhook":true,"JunkFilter":true,"NameAddress":true,"Outgoing":true,"OutgoingWebhook":true,"Route":true,"Ruleset":true,"Structure":true,"SubjectPass":true,"Suppression":true}
export const stringsTypes: {[typename: string]: boolean} = {"CSRFToken":true,"OutgoingEvent":true}
export const intsTypes: {[typename: string]: boolean} = {}
export const types: TypenameMap = {
"Account": {"Name":"Account","Docs":"","Fields":[{"Name":"Domain","Docs":"","Typewords":["string"]},{"Name":"Description","Docs":"","Typewords":["string"]},{"Name":"FullName","Docs":"","Typewords":["string"]},{"Name":"Destinations","Docs":"","Typewords":["{}","Destination"]},{"Name":"SubjectPass","Docs":"","Typewords":["SubjectPass"]},{"Name":"QuotaMessageSize","Docs":"","Typewords":["int64"]},{"Name":"RejectsMailbox","Docs":"","Typewords":["string"]},{"Name":"KeepRejects","Docs":"","Typewords":["bool"]},{"Name":"AutomaticJunkFlags","Docs":"","Typewords":["AutomaticJunkFlags"]},{"Name":"JunkFilter","Docs":"","Typewords":["nullable","JunkFilter"]},{"Name":"MaxOutgoingMessagesPerDay","Docs":"","Typewords":["int32"]},{"Name":"MaxFirstTimeRecipientsPerDay","Docs":"","Typewords":["int32"]},{"Name":"NoFirstTimeSenderDelay","Docs":"","Typewords":["bool"]},{"Name":"Routes","Docs":"","Typewords":["[]","Route"]},{"Name":"DNSDomain","Docs":"","Typewords":["Domain"]}]},
"Account": {"Name":"Account","Docs":"","Fields":[{"Name":"OutgoingWebhook","Docs":"","Typewords":["nullable","OutgoingWebhook"]},{"Name":"IncomingWebhook","Docs":"","Typewords":["nullable","IncomingWebhook"]},{"Name":"FromIDLoginAddresses","Docs":"","Typewords":["[]","string"]},{"Name":"KeepRetiredMessagePeriod","Docs":"","Typewords":["int64"]},{"Name":"KeepRetiredWebhookPeriod","Docs":"","Typewords":["int64"]},{"Name":"Domain","Docs":"","Typewords":["string"]},{"Name":"Description","Docs":"","Typewords":["string"]},{"Name":"FullName","Docs":"","Typewords":["string"]},{"Name":"Destinations","Docs":"","Typewords":["{}","Destination"]},{"Name":"SubjectPass","Docs":"","Typewords":["SubjectPass"]},{"Name":"QuotaMessageSize","Docs":"","Typewords":["int64"]},{"Name":"RejectsMailbox","Docs":"","Typewords":["string"]},{"Name":"KeepRejects","Docs":"","Typewords":["bool"]},{"Name":"AutomaticJunkFlags","Docs":"","Typewords":["AutomaticJunkFlags"]},{"Name":"JunkFilter","Docs":"","Typewords":["nullable","JunkFilter"]},{"Name":"MaxOutgoingMessagesPerDay","Docs":"","Typewords":["int32"]},{"Name":"MaxFirstTimeRecipientsPerDay","Docs":"","Typewords":["int32"]},{"Name":"NoFirstTimeSenderDelay","Docs":"","Typewords":["bool"]},{"Name":"Routes","Docs":"","Typewords":["[]","Route"]},{"Name":"DNSDomain","Docs":"","Typewords":["Domain"]}]},
"OutgoingWebhook": {"Name":"OutgoingWebhook","Docs":"","Fields":[{"Name":"URL","Docs":"","Typewords":["string"]},{"Name":"Authorization","Docs":"","Typewords":["string"]},{"Name":"Events","Docs":"","Typewords":["[]","string"]}]},
"IncomingWebhook": {"Name":"IncomingWebhook","Docs":"","Fields":[{"Name":"URL","Docs":"","Typewords":["string"]},{"Name":"Authorization","Docs":"","Typewords":["string"]}]},
"Destination": {"Name":"Destination","Docs":"","Fields":[{"Name":"Mailbox","Docs":"","Typewords":["string"]},{"Name":"Rulesets","Docs":"","Typewords":["[]","Ruleset"]},{"Name":"FullName","Docs":"","Typewords":["string"]}]},
"Ruleset": {"Name":"Ruleset","Docs":"","Fields":[{"Name":"SMTPMailFromRegexp","Docs":"","Typewords":["string"]},{"Name":"VerifiedDomain","Docs":"","Typewords":["string"]},{"Name":"HeadersRegexp","Docs":"","Typewords":["{}","string"]},{"Name":"IsForward","Docs":"","Typewords":["bool"]},{"Name":"ListAllowDomain","Docs":"","Typewords":["string"]},{"Name":"AcceptRejectsToMailbox","Docs":"","Typewords":["string"]},{"Name":"Mailbox","Docs":"","Typewords":["string"]},{"Name":"VerifiedDNSDomain","Docs":"","Typewords":["Domain"]},{"Name":"ListAllowDNSDomain","Docs":"","Typewords":["Domain"]}]},
"Domain": {"Name":"Domain","Docs":"","Fields":[{"Name":"ASCII","Docs":"","Typewords":["string"]},{"Name":"Unicode","Docs":"","Typewords":["string"]}]},
@ -97,12 +215,21 @@ export const types: TypenameMap = {
"AutomaticJunkFlags": {"Name":"AutomaticJunkFlags","Docs":"","Fields":[{"Name":"Enabled","Docs":"","Typewords":["bool"]},{"Name":"JunkMailboxRegexp","Docs":"","Typewords":["string"]},{"Name":"NeutralMailboxRegexp","Docs":"","Typewords":["string"]},{"Name":"NotJunkMailboxRegexp","Docs":"","Typewords":["string"]}]},
"JunkFilter": {"Name":"JunkFilter","Docs":"","Fields":[{"Name":"Threshold","Docs":"","Typewords":["float64"]},{"Name":"Onegrams","Docs":"","Typewords":["bool"]},{"Name":"Twograms","Docs":"","Typewords":["bool"]},{"Name":"Threegrams","Docs":"","Typewords":["bool"]},{"Name":"MaxPower","Docs":"","Typewords":["float64"]},{"Name":"TopWords","Docs":"","Typewords":["int32"]},{"Name":"IgnoreWords","Docs":"","Typewords":["float64"]},{"Name":"RareWords","Docs":"","Typewords":["int32"]}]},
"Route": {"Name":"Route","Docs":"","Fields":[{"Name":"FromDomain","Docs":"","Typewords":["[]","string"]},{"Name":"ToDomain","Docs":"","Typewords":["[]","string"]},{"Name":"MinimumAttempts","Docs":"","Typewords":["int32"]},{"Name":"Transport","Docs":"","Typewords":["string"]},{"Name":"FromDomainASCII","Docs":"","Typewords":["[]","string"]},{"Name":"ToDomainASCII","Docs":"","Typewords":["[]","string"]}]},
"Suppression": {"Name":"Suppression","Docs":"","Fields":[{"Name":"ID","Docs":"","Typewords":["int64"]},{"Name":"Created","Docs":"","Typewords":["timestamp"]},{"Name":"Account","Docs":"","Typewords":["string"]},{"Name":"BaseAddress","Docs":"","Typewords":["string"]},{"Name":"OriginalAddress","Docs":"","Typewords":["string"]},{"Name":"Manual","Docs":"","Typewords":["bool"]},{"Name":"Reason","Docs":"","Typewords":["string"]}]},
"ImportProgress": {"Name":"ImportProgress","Docs":"","Fields":[{"Name":"Token","Docs":"","Typewords":["string"]}]},
"Outgoing": {"Name":"Outgoing","Docs":"","Fields":[{"Name":"Version","Docs":"","Typewords":["int32"]},{"Name":"Event","Docs":"","Typewords":["OutgoingEvent"]},{"Name":"DSN","Docs":"","Typewords":["bool"]},{"Name":"Suppressing","Docs":"","Typewords":["bool"]},{"Name":"QueueMsgID","Docs":"","Typewords":["int64"]},{"Name":"FromID","Docs":"","Typewords":["string"]},{"Name":"MessageID","Docs":"","Typewords":["string"]},{"Name":"Subject","Docs":"","Typewords":["string"]},{"Name":"WebhookQueued","Docs":"","Typewords":["timestamp"]},{"Name":"SMTPCode","Docs":"","Typewords":["int32"]},{"Name":"SMTPEnhancedCode","Docs":"","Typewords":["string"]},{"Name":"Error","Docs":"","Typewords":["string"]},{"Name":"Extra","Docs":"","Typewords":["{}","string"]}]},
"Incoming": {"Name":"Incoming","Docs":"","Fields":[{"Name":"Version","Docs":"","Typewords":["int32"]},{"Name":"From","Docs":"","Typewords":["[]","NameAddress"]},{"Name":"To","Docs":"","Typewords":["[]","NameAddress"]},{"Name":"CC","Docs":"","Typewords":["[]","NameAddress"]},{"Name":"BCC","Docs":"","Typewords":["[]","NameAddress"]},{"Name":"ReplyTo","Docs":"","Typewords":["[]","NameAddress"]},{"Name":"Subject","Docs":"","Typewords":["string"]},{"Name":"MessageID","Docs":"","Typewords":["string"]},{"Name":"InReplyTo","Docs":"","Typewords":["string"]},{"Name":"References","Docs":"","Typewords":["[]","string"]},{"Name":"Date","Docs":"","Typewords":["nullable","timestamp"]},{"Name":"Text","Docs":"","Typewords":["string"]},{"Name":"HTML","Docs":"","Typewords":["string"]},{"Name":"Structure","Docs":"","Typewords":["Structure"]},{"Name":"Meta","Docs":"","Typewords":["IncomingMeta"]}]},
"NameAddress": {"Name":"NameAddress","Docs":"","Fields":[{"Name":"Name","Docs":"","Typewords":["string"]},{"Name":"Address","Docs":"","Typewords":["string"]}]},
"Structure": {"Name":"Structure","Docs":"","Fields":[{"Name":"ContentType","Docs":"","Typewords":["string"]},{"Name":"ContentTypeParams","Docs":"","Typewords":["{}","string"]},{"Name":"ContentID","Docs":"","Typewords":["string"]},{"Name":"DecodedSize","Docs":"","Typewords":["int64"]},{"Name":"Parts","Docs":"","Typewords":["[]","Structure"]}]},
"IncomingMeta": {"Name":"IncomingMeta","Docs":"","Fields":[{"Name":"MsgID","Docs":"","Typewords":["int64"]},{"Name":"MailFrom","Docs":"","Typewords":["string"]},{"Name":"MailFromValidated","Docs":"","Typewords":["bool"]},{"Name":"MsgFromValidated","Docs":"","Typewords":["bool"]},{"Name":"RcptTo","Docs":"","Typewords":["string"]},{"Name":"DKIMVerifiedDomains","Docs":"","Typewords":["[]","string"]},{"Name":"RemoteIP","Docs":"","Typewords":["string"]},{"Name":"Received","Docs":"","Typewords":["timestamp"]},{"Name":"MailboxName","Docs":"","Typewords":["string"]},{"Name":"Automated","Docs":"","Typewords":["bool"]}]},
"CSRFToken": {"Name":"CSRFToken","Docs":"","Values":null},
"OutgoingEvent": {"Name":"OutgoingEvent","Docs":"","Values":[{"Name":"EventDelivered","Value":"delivered","Docs":""},{"Name":"EventSuppressed","Value":"suppressed","Docs":""},{"Name":"EventDelayed","Value":"delayed","Docs":""},{"Name":"EventFailed","Value":"failed","Docs":""},{"Name":"EventRelayed","Value":"relayed","Docs":""},{"Name":"EventExpanded","Value":"expanded","Docs":""},{"Name":"EventCanceled","Value":"canceled","Docs":""},{"Name":"EventUnrecognized","Value":"unrecognized","Docs":""}]},
}
export const parser = {
Account: (v: any) => parse("Account", v) as Account,
OutgoingWebhook: (v: any) => parse("OutgoingWebhook", v) as OutgoingWebhook,
IncomingWebhook: (v: any) => parse("IncomingWebhook", v) as IncomingWebhook,
Destination: (v: any) => parse("Destination", v) as Destination,
Ruleset: (v: any) => parse("Ruleset", v) as Ruleset,
Domain: (v: any) => parse("Domain", v) as Domain,
@ -110,8 +237,15 @@ export const parser = {
AutomaticJunkFlags: (v: any) => parse("AutomaticJunkFlags", v) as AutomaticJunkFlags,
JunkFilter: (v: any) => parse("JunkFilter", v) as JunkFilter,
Route: (v: any) => parse("Route", v) as Route,
Suppression: (v: any) => parse("Suppression", v) as Suppression,
ImportProgress: (v: any) => parse("ImportProgress", v) as ImportProgress,
Outgoing: (v: any) => parse("Outgoing", v) as Outgoing,
Incoming: (v: any) => parse("Incoming", v) as Incoming,
NameAddress: (v: any) => parse("NameAddress", v) as NameAddress,
Structure: (v: any) => parse("Structure", v) as Structure,
IncomingMeta: (v: any) => parse("IncomingMeta", v) as IncomingMeta,
CSRFToken: (v: any) => parse("CSRFToken", v) as CSRFToken,
OutgoingEvent: (v: any) => parse("OutgoingEvent", v) as OutgoingEvent,
}
// Account exports web API functions for the account web interface. All its
@ -187,14 +321,16 @@ export class Client {
// Account returns information about the account.
// StorageUsed is the sum of the sizes of all messages, in bytes.
// StorageLimit is the maximum storage that can be used, or 0 if there is no limit.
async Account(): Promise<[Account, number, number]> {
async Account(): Promise<[Account, number, number, Suppression[] | null]> {
const fn: string = "Account"
const paramTypes: string[][] = []
const returnTypes: string[][] = [["Account"],["int64"],["int64"]]
const returnTypes: string[][] = [["Account"],["int64"],["int64"],["[]","Suppression"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as [Account, number, number]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as [Account, number, number, Suppression[] | null]
}
// AccountSaveFullName saves the full name (used as display name in email messages)
// for the account.
async AccountSaveFullName(fullName: string): Promise<void> {
const fn: string = "AccountSaveFullName"
const paramTypes: string[][] = [["string"]]
@ -232,6 +368,97 @@ export class Client {
const params: any[] = []
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as ImportProgress
}
// SuppressionList lists the addresses on the suppression list of this account.
async SuppressionList(): Promise<Suppression[] | null> {
const fn: string = "SuppressionList"
const paramTypes: string[][] = []
const returnTypes: string[][] = [["[]","Suppression"]]
const params: any[] = []
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Suppression[] | null
}
// SuppressionAdd adds an email address to the suppression list.
async SuppressionAdd(address: string, manual: boolean, reason: string): Promise<Suppression> {
const fn: string = "SuppressionAdd"
const paramTypes: string[][] = [["string"],["bool"],["string"]]
const returnTypes: string[][] = [["Suppression"]]
const params: any[] = [address, manual, reason]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as Suppression
}
// SuppressionRemove removes the email address from the suppression list.
async SuppressionRemove(address: string): Promise<void> {
const fn: string = "SuppressionRemove"
const paramTypes: string[][] = [["string"]]
const returnTypes: string[][] = []
const params: any[] = [address]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// OutgoingWebhookSave saves a new webhook url for outgoing deliveries. If url
// is empty, the webhook is disabled. If authorization is non-empty it is used for
// the Authorization header in HTTP requests. Events specifies the outgoing events
// to be delivered, or all if empty/nil.
async OutgoingWebhookSave(url: string, authorization: string, events: string[] | null): Promise<void> {
const fn: string = "OutgoingWebhookSave"
const paramTypes: string[][] = [["string"],["string"],["[]","string"]]
const returnTypes: string[][] = []
const params: any[] = [url, authorization, events]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// OutgoingWebhookTest makes a test webhook call to urlStr, with optional
// authorization. If the HTTP request is made this call will succeed also for
// non-2xx HTTP status codes.
async OutgoingWebhookTest(urlStr: string, authorization: string, data: Outgoing): Promise<[number, string, string]> {
const fn: string = "OutgoingWebhookTest"
const paramTypes: string[][] = [["string"],["string"],["Outgoing"]]
const returnTypes: string[][] = [["int32"],["string"],["string"]]
const params: any[] = [urlStr, authorization, data]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as [number, string, string]
}
// IncomingWebhookSave saves a new webhook url for incoming deliveries. If url is
// empty, the webhook is disabled. If authorization is not empty, it is used in
// the Authorization header in requests.
async IncomingWebhookSave(url: string, authorization: string): Promise<void> {
const fn: string = "IncomingWebhookSave"
const paramTypes: string[][] = [["string"],["string"]]
const returnTypes: string[][] = []
const params: any[] = [url, authorization]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// IncomingWebhookTest makes a test webhook HTTP delivery request to urlStr,
// with optional authorization header. If the HTTP call is made, this function
// returns non-error regardless of HTTP status code.
async IncomingWebhookTest(urlStr: string, authorization: string, data: Incoming): Promise<[number, string, string]> {
const fn: string = "IncomingWebhookTest"
const paramTypes: string[][] = [["string"],["string"],["Incoming"]]
const returnTypes: string[][] = [["int32"],["string"],["string"]]
const params: any[] = [urlStr, authorization, data]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as [number, string, string]
}
// FromIDLoginAddressesSave saves new login addresses to enable unique SMTP
// MAIL FROM addresses ("fromid") for deliveries from the queue.
async FromIDLoginAddressesSave(loginAddresses: string[] | null): Promise<void> {
const fn: string = "FromIDLoginAddressesSave"
const paramTypes: string[][] = [["[]","string"]]
const returnTypes: string[][] = []
const params: any[] = [loginAddresses]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
// KeepRetiredPeriodsSave save periods to save retired messages and webhooks.
async KeepRetiredPeriodsSave(keepRetiredMessagePeriod: number, keepRetiredWebhookPeriod: number): Promise<void> {
const fn: string = "KeepRetiredPeriodsSave"
const paramTypes: string[][] = [["int64"],["int64"]]
const returnTypes: string[][] = []
const params: any[] = [keepRetiredMessagePeriod, keepRetiredWebhookPeriod]
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params) as void
}
}
export const defaultBaseURL = (function() {