1// Package webaccount provides a web app for users to view and change their account
2// settings, and to import/export email.
8 cryptorand "crypto/rand"
24 "github.com/mjl-/bstore"
25 "github.com/mjl-/sherpa"
26 "github.com/mjl-/sherpadoc"
27 "github.com/mjl-/sherpaprom"
29 "github.com/mjl-/mox/config"
30 "github.com/mjl-/mox/mlog"
31 "github.com/mjl-/mox/mox-"
32 "github.com/mjl-/mox/moxvar"
33 "github.com/mjl-/mox/queue"
34 "github.com/mjl-/mox/smtp"
35 "github.com/mjl-/mox/store"
36 "github.com/mjl-/mox/webapi"
37 "github.com/mjl-/mox/webauth"
38 "github.com/mjl-/mox/webhook"
39 "github.com/mjl-/mox/webops"
42var pkglog = mlog.New("webaccount", nil)
45var accountapiJSON []byte
47//go:embed account.html
53var webaccountFile = &mox.WebappFile{
56 HTMLPath: filepath.FromSlash("webaccount/account.html"),
57 JSPath: filepath.FromSlash("webaccount/account.js"),
60var accountDoc = mustParseAPI("account", accountapiJSON)
62func mustParseAPI(api string, buf []byte) (doc sherpadoc.Section) {
63 err := json.Unmarshal(buf, &doc)
65 pkglog.Fatalx("parsing webaccount api docs", err, slog.String("api", api))
70var sherpaHandlerOpts *sherpa.HandlerOpts
72func makeSherpaHandler(cookiePath string, isForwarded bool) (http.Handler, error) {
73 return sherpa.NewHandler("/api/", moxvar.Version, Account{cookiePath, isForwarded}, &accountDoc, sherpaHandlerOpts)
77 collector, err := sherpaprom.NewCollector("moxaccount", nil)
79 pkglog.Fatalx("creating sherpa prometheus collector", err)
82 sherpaHandlerOpts = &sherpa.HandlerOpts{Collector: collector, AdjustFunctionNames: "none", NoCORS: true}
84 _, err = makeSherpaHandler("", false)
86 pkglog.Fatalx("sherpa handler", err)
89 mox.NewWebaccountHandler = func(basePath string, isForwarded bool) http.Handler {
90 return http.HandlerFunc(Handler(basePath, isForwarded))
94// Handler returns a handler for the webaccount endpoints, customized for the
96func Handler(cookiePath string, isForwarded bool) func(w http.ResponseWriter, r *http.Request) {
97 sh, err := makeSherpaHandler(cookiePath, isForwarded)
98 return func(w http.ResponseWriter, r *http.Request) {
100 http.Error(w, "500 - internal server error - cannot handle requests", http.StatusInternalServerError)
103 handle(sh, isForwarded, w, r)
107func xcheckf(ctx context.Context, err error, format string, args ...any) {
111 // If caller tried saving a config that is invalid, or because of a bad request, cause a user error.
112 if errors.Is(err, mox.ErrConfig) || errors.Is(err, mox.ErrRequest) {
113 xcheckuserf(ctx, err, format, args...)
116 msg := fmt.Sprintf(format, args...)
117 errmsg := fmt.Sprintf("%s: %s", msg, err)
118 pkglog.WithContext(ctx).Errorx(msg, err)
119 code := "server:error"
120 if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
123 panic(&sherpa.Error{Code: code, Message: errmsg})
126func xcheckuserf(ctx context.Context, err error, format string, args ...any) {
130 msg := fmt.Sprintf(format, args...)
131 errmsg := fmt.Sprintf("%s: %s", msg, err)
132 pkglog.WithContext(ctx).Errorx(msg, err)
133 panic(&sherpa.Error{Code: "user:error", Message: errmsg})
136// Account exports web API functions for the account web interface. All its
137// methods are exported under api/. Function calls require valid HTTP
138// Authentication credentials of a user.
140 cookiePath string // From listener, for setting authentication cookies.
141 isForwarded bool // From listener, whether we look at X-Forwarded-* headers.
144func handle(apiHandler http.Handler, isForwarded bool, w http.ResponseWriter, r *http.Request) {
145 ctx := context.WithValue(r.Context(), mlog.CidKey, mox.Cid())
146 log := pkglog.WithContext(ctx).With(slog.String("userauth", ""))
148 // Without authentication. The token is unguessable.
149 if r.URL.Path == "/importprogress" {
150 if r.Method != "GET" {
151 http.Error(w, "405 - method not allowed - get required", http.StatusMethodNotAllowed)
156 token := q.Get("token")
158 http.Error(w, "400 - bad request - missing token", http.StatusBadRequest)
162 flusher, ok := w.(http.Flusher)
164 log.Error("internal error: ResponseWriter not a http.Flusher")
165 http.Error(w, "500 - internal error - cannot access underlying connection", 500)
169 l := importListener{token, make(chan importEvent, 100), make(chan bool, 1)}
170 importers.Register <- &l
173 http.Error(w, "400 - bad request - unknown token, import may have finished more than a minute ago", http.StatusBadRequest)
177 importers.Unregister <- &l
181 h.Set("Content-Type", "text/event-stream")
182 h.Set("Cache-Control", "no-cache")
183 _, err := w.Write([]byte(": keepalive\n\n"))
192 case e := <-l.Events:
193 _, err := w.Write(e.SSEMsg)
205 // HTML/JS can be retrieved without authentication.
206 if r.URL.Path == "/" {
209 webaccountFile.Serve(ctx, log, w, r)
211 http.Error(w, "405 - method not allowed - use get", http.StatusMethodNotAllowed)
214 } else if r.URL.Path == "/licenses.txt" {
219 http.Error(w, "405 - method not allowed - use get", http.StatusMethodNotAllowed)
224 isAPI := strings.HasPrefix(r.URL.Path, "/api/")
225 // Only allow POST for calls, they will not work cross-domain without CORS.
226 if isAPI && r.URL.Path != "/api/" && r.Method != "POST" {
227 http.Error(w, "405 - method not allowed - use post", http.StatusMethodNotAllowed)
231 var loginAddress, accName string
232 var sessionToken store.SessionToken
233 // All other URLs, except the login endpoint require some authentication.
234 if r.URL.Path != "/api/LoginPrep" && r.URL.Path != "/api/Login" {
236 isExport := r.URL.Path == "/export"
237 requireCSRF := isAPI || r.URL.Path == "/import" || isExport
238 accName, sessionToken, loginAddress, ok = webauth.Check(ctx, log, webauth.Accounts, "webaccount", isForwarded, w, r, isAPI, requireCSRF, isExport)
240 // Response has been written already.
246 reqInfo := requestInfo{loginAddress, accName, sessionToken, w, r}
247 ctx = context.WithValue(ctx, requestInfoCtxKey, reqInfo)
248 apiHandler.ServeHTTP(w, r.WithContext(ctx))
254 webops.Export(log, accName, w, r)
257 if r.Method != "POST" {
258 http.Error(w, "405 - method not allowed - post required", http.StatusMethodNotAllowed)
262 f, _, err := r.FormFile("file")
264 if errors.Is(err, http.ErrMissingFile) {
265 http.Error(w, "400 - bad request - missing file", http.StatusBadRequest)
267 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
273 log.Check(err, "closing form file")
275 skipMailboxPrefix := r.FormValue("skipMailboxPrefix")
276 tmpf, err := os.CreateTemp("", "mox-import")
278 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
283 store.CloseRemoveTempFile(log, tmpf, "upload")
286 if _, err := io.Copy(tmpf, f); err != nil {
287 log.Errorx("copying import to temporary file", err)
288 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
291 token, isUserError, err := importStart(log, accName, tmpf, skipMailboxPrefix)
293 log.Errorx("starting import", err, slog.Bool("usererror", isUserError))
295 http.Error(w, "400 - bad request - "+err.Error(), http.StatusBadRequest)
297 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
301 tmpf = nil // importStart is now responsible for cleanup.
303 w.Header().Set("Content-Type", "application/json")
304 _ = json.NewEncoder(w).Encode(ImportProgress{Token: token})
311// ImportProgress is returned after uploading a file to import.
312type ImportProgress struct {
313 // For fetching progress, or cancelling an import.
319var requestInfoCtxKey ctxKey = "requestInfo"
321type requestInfo struct {
324 SessionToken store.SessionToken
325 Response http.ResponseWriter
326 Request *http.Request // For Proto and TLS connection state during message submit.
329// LoginPrep returns a login token, and also sets it as cookie. Both must be
330// present in the call to Login.
331func (w Account) LoginPrep(ctx context.Context) string {
332 log := pkglog.WithContext(ctx)
333 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
336 _, err := cryptorand.Read(data[:])
337 xcheckf(ctx, err, "generate token")
338 loginToken := base64.RawURLEncoding.EncodeToString(data[:])
340 webauth.LoginPrep(ctx, log, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken)
345// Login returns a session token for the credentials, or fails with error code
346// "user:badLogin". Call LoginPrep to get a loginToken.
347func (w Account) Login(ctx context.Context, loginToken, username, password string) store.CSRFToken {
348 log := pkglog.WithContext(ctx)
349 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
351 csrfToken, err := webauth.Login(ctx, log, webauth.Accounts, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken, username, password)
352 if _, ok := err.(*sherpa.Error); ok {
355 xcheckf(ctx, err, "login")
359// Logout invalidates the session token.
360func (w Account) Logout(ctx context.Context) {
361 log := pkglog.WithContext(ctx)
362 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
364 err := webauth.Logout(ctx, log, webauth.Accounts, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, reqInfo.AccountName, reqInfo.SessionToken)
365 xcheckf(ctx, err, "logout")
368// SetPassword saves a new password for the account, invalidating the previous password.
369// Sessions are not interrupted, and will keep working. New login attempts must use the new password.
370// Password must be at least 8 characters.
371func (Account) SetPassword(ctx context.Context, password string) {
372 log := pkglog.WithContext(ctx)
373 if len(password) < 8 {
374 panic(&sherpa.Error{Code: "user:error", Message: "password must be at least 8 characters"})
377 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
378 acc, err := store.OpenAccount(log, reqInfo.AccountName)
379 xcheckf(ctx, err, "open account")
382 log.Check(err, "closing account")
385 // Retrieve session, resetting password invalidates it.
386 ls, err := store.SessionUse(ctx, log, reqInfo.AccountName, reqInfo.SessionToken, "")
387 xcheckf(ctx, err, "get session")
389 err = acc.SetPassword(log, password)
390 xcheckf(ctx, err, "setting password")
392 // Session has been invalidated. Add it again.
393 err = store.SessionAddToken(ctx, log, &ls)
394 xcheckf(ctx, err, "restoring session after password reset")
397// Account returns information about the account.
398// StorageUsed is the sum of the sizes of all messages, in bytes.
399// StorageLimit is the maximum storage that can be used, or 0 if there is no limit.
400func (Account) Account(ctx context.Context) (account config.Account, storageUsed, storageLimit int64, suppressions []webapi.Suppression) {
401 log := pkglog.WithContext(ctx)
402 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
404 acc, err := store.OpenAccount(log, reqInfo.AccountName)
405 xcheckf(ctx, err, "open account")
408 log.Check(err, "closing account")
411 var accConf config.Account
412 acc.WithRLock(func() {
413 accConf, _ = acc.Conf()
415 storageLimit = acc.QuotaMessageSize()
416 err := acc.DB.Read(ctx, func(tx *bstore.Tx) error {
417 du := store.DiskUsage{ID: 1}
419 storageUsed = du.MessageSize
422 xcheckf(ctx, err, "get disk usage")
425 suppressions, err = queue.SuppressionList(ctx, reqInfo.AccountName)
426 xcheckf(ctx, err, "list suppressions")
428 return accConf, storageUsed, storageLimit, suppressions
431// AccountSaveFullName saves the full name (used as display name in email messages)
433func (Account) AccountSaveFullName(ctx context.Context, fullName string) {
434 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
435 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
436 acc.FullName = fullName
438 xcheckf(ctx, err, "saving account full name")
441// DestinationSave updates a destination.
442// OldDest is compared against the current destination. If it does not match, an
443// error is returned. Otherwise newDest is saved and the configuration reloaded.
444func (Account) DestinationSave(ctx context.Context, destName string, oldDest, newDest config.Destination) {
445 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
447 err := mox.AccountSave(ctx, reqInfo.AccountName, func(conf *config.Account) {
448 curDest, ok := conf.Destinations[destName]
450 xcheckuserf(ctx, errors.New("not found"), "looking up destination")
452 if !curDest.Equal(oldDest) {
453 xcheckuserf(ctx, errors.New("modified"), "checking stored destination")
456 // Keep fields we manage.
457 newDest.DMARCReports = curDest.DMARCReports
458 newDest.HostTLSReports = curDest.HostTLSReports
459 newDest.DomainTLSReports = curDest.DomainTLSReports
461 // Make copy of reference values.
462 nd := map[string]config.Destination{}
463 for dn, d := range conf.Destinations {
466 nd[destName] = newDest
467 conf.Destinations = nd
469 xcheckf(ctx, err, "saving destination")
472// ImportAbort aborts an import that is in progress. If the import exists and isn't
473// finished, no changes will have been made by the import.
474func (Account) ImportAbort(ctx context.Context, importToken string) error {
475 req := importAbortRequest{importToken, make(chan error)}
476 importers.Abort <- req
477 return <-req.Response
480// Types exposes types not used in API method signatures, such as the import form upload.
481func (Account) Types() (importProgress ImportProgress) {
485// SuppressionList lists the addresses on the suppression list of this account.
486func (Account) SuppressionList(ctx context.Context) (suppressions []webapi.Suppression) {
487 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
488 l, err := queue.SuppressionList(ctx, reqInfo.AccountName)
489 xcheckf(ctx, err, "list suppressions")
493// SuppressionAdd adds an email address to the suppression list.
494func (Account) SuppressionAdd(ctx context.Context, address string, manual bool, reason string) (suppression webapi.Suppression) {
495 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
496 addr, err := smtp.ParseAddress(address)
497 xcheckuserf(ctx, err, "parsing address")
498 sup := webapi.Suppression{
499 Account: reqInfo.AccountName,
503 err = queue.SuppressionAdd(ctx, addr.Path(), &sup)
504 if err != nil && errors.Is(err, bstore.ErrUnique) {
505 xcheckuserf(ctx, err, "add suppression")
507 xcheckf(ctx, err, "add suppression")
511// SuppressionRemove removes the email address from the suppression list.
512func (Account) SuppressionRemove(ctx context.Context, address string) {
513 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
514 addr, err := smtp.ParseAddress(address)
515 xcheckuserf(ctx, err, "parsing address")
516 err = queue.SuppressionRemove(ctx, reqInfo.AccountName, addr.Path())
517 if err != nil && err == bstore.ErrAbsent {
518 xcheckuserf(ctx, err, "remove suppression")
520 xcheckf(ctx, err, "remove suppression")
523// OutgoingWebhookSave saves a new webhook url for outgoing deliveries. If url
524// is empty, the webhook is disabled. If authorization is non-empty it is used for
525// the Authorization header in HTTP requests. Events specifies the outgoing events
526// to be delivered, or all if empty/nil.
527func (Account) OutgoingWebhookSave(ctx context.Context, url, authorization string, events []string) {
528 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
529 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
531 acc.OutgoingWebhook = nil
533 acc.OutgoingWebhook = &config.OutgoingWebhook{URL: url, Authorization: authorization, Events: events}
536 xcheckf(ctx, err, "saving account outgoing webhook")
539// OutgoingWebhookTest makes a test webhook call to urlStr, with optional
540// authorization. If the HTTP request is made this call will succeed also for
541// non-2xx HTTP status codes.
542func (Account) OutgoingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Outgoing) (code int, response string, errmsg string) {
543 log := pkglog.WithContext(ctx)
545 xvalidURL(ctx, urlStr)
546 log.Debug("making webhook test call for outgoing message", slog.String("url", urlStr))
549 enc := json.NewEncoder(&b)
550 enc.SetIndent("", "\t")
551 enc.SetEscapeHTML(false)
552 err := enc.Encode(data)
553 xcheckf(ctx, err, "encoding outgoing webhook data")
555 code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
559 log.Debugx("result for webhook test call for outgoing message", err, slog.Int("code", code), slog.String("response", response))
560 return code, response, errmsg
563// IncomingWebhookSave saves a new webhook url for incoming deliveries. If url is
564// empty, the webhook is disabled. If authorization is not empty, it is used in
565// the Authorization header in requests.
566func (Account) IncomingWebhookSave(ctx context.Context, url, authorization string) {
567 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
568 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
570 acc.IncomingWebhook = nil
572 acc.IncomingWebhook = &config.IncomingWebhook{URL: url, Authorization: authorization}
575 xcheckf(ctx, err, "saving account incoming webhook")
578func xvalidURL(ctx context.Context, s string) {
579 u, err := url.Parse(s)
580 xcheckuserf(ctx, err, "parsing url")
581 if u.Scheme != "http" && u.Scheme != "https" {
582 xcheckuserf(ctx, errors.New("scheme must be http or https"), "parsing url")
586// IncomingWebhookTest makes a test webhook HTTP delivery request to urlStr,
587// with optional authorization header. If the HTTP call is made, this function
588// returns non-error regardless of HTTP status code.
589func (Account) IncomingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Incoming) (code int, response string, errmsg string) {
590 log := pkglog.WithContext(ctx)
592 xvalidURL(ctx, urlStr)
593 log.Debug("making webhook test call for incoming message", slog.String("url", urlStr))
596 enc := json.NewEncoder(&b)
597 enc.SetEscapeHTML(false)
598 enc.SetIndent("", "\t")
599 err := enc.Encode(data)
600 xcheckf(ctx, err, "encoding incoming webhook data")
601 code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
605 log.Debugx("result for webhook test call for incoming message", err, slog.Int("code", code), slog.String("response", response))
606 return code, response, errmsg
609// FromIDLoginAddressesSave saves new login addresses to enable unique SMTP
610// MAIL FROM addresses ("fromid") for deliveries from the queue.
611func (Account) FromIDLoginAddressesSave(ctx context.Context, loginAddresses []string) {
612 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
613 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
614 acc.FromIDLoginAddresses = loginAddresses
616 xcheckf(ctx, err, "saving account fromid login addresses")
619// KeepRetiredPeriodsSave saves periods to save retired messages and webhooks.
620func (Account) KeepRetiredPeriodsSave(ctx context.Context, keepRetiredMessagePeriod, keepRetiredWebhookPeriod time.Duration) {
621 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
622 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
623 acc.KeepRetiredMessagePeriod = keepRetiredMessagePeriod
624 acc.KeepRetiredWebhookPeriod = keepRetiredWebhookPeriod
626 xcheckf(ctx, err, "saving account keep retired periods")
629// AutomaticJunkFlagsSave saves settings for automatically marking messages as
630// junk/nonjunk when moved to mailboxes matching certain regular expressions.
631func (Account) AutomaticJunkFlagsSave(ctx context.Context, enabled bool, junkRegexp, neutralRegexp, notJunkRegexp string) {
632 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
633 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
634 acc.AutomaticJunkFlags = config.AutomaticJunkFlags{
636 JunkMailboxRegexp: junkRegexp,
637 NeutralMailboxRegexp: neutralRegexp,
638 NotJunkMailboxRegexp: notJunkRegexp,
641 xcheckf(ctx, err, "saving account automatic junk flags")
644// JunkFilterSave saves junk filter settings. If junkFilter is nil, the junk filter
645// is disabled. Otherwise all fields except Threegrams are stored.
646func (Account) JunkFilterSave(ctx context.Context, junkFilter *config.JunkFilter) {
647 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
648 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
649 if junkFilter == nil {
653 old := acc.JunkFilter
654 acc.JunkFilter = junkFilter
655 acc.JunkFilter.Params.Threegrams = false
657 acc.JunkFilter.Params.Threegrams = old.Params.Threegrams
660 xcheckf(ctx, err, "saving account junk filter settings")
663// RejectsSave saves the RejectsMailbox and KeepRejects settings.
664func (Account) RejectsSave(ctx context.Context, mailbox string, keep bool) {
665 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
666 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
667 acc.RejectsMailbox = mailbox
668 acc.KeepRejects = keep
670 xcheckf(ctx, err, "saving account rejects settings")