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)
216 isAPI := strings.HasPrefix(r.URL.Path, "/api/")
217 // Only allow POST for calls, they will not work cross-domain without CORS.
218 if isAPI && r.URL.Path != "/api/" && r.Method != "POST" {
219 http.Error(w, "405 - method not allowed - use post", http.StatusMethodNotAllowed)
223 var loginAddress, accName string
224 var sessionToken store.SessionToken
225 // All other URLs, except the login endpoint require some authentication.
226 if r.URL.Path != "/api/LoginPrep" && r.URL.Path != "/api/Login" {
228 isExport := r.URL.Path == "/export"
229 requireCSRF := isAPI || r.URL.Path == "/import" || isExport
230 accName, sessionToken, loginAddress, ok = webauth.Check(ctx, log, webauth.Accounts, "webaccount", isForwarded, w, r, isAPI, requireCSRF, isExport)
232 // Response has been written already.
238 reqInfo := requestInfo{loginAddress, accName, sessionToken, w, r}
239 ctx = context.WithValue(ctx, requestInfoCtxKey, reqInfo)
240 apiHandler.ServeHTTP(w, r.WithContext(ctx))
246 webops.Export(log, accName, w, r)
249 if r.Method != "POST" {
250 http.Error(w, "405 - method not allowed - post required", http.StatusMethodNotAllowed)
254 f, _, err := r.FormFile("file")
256 if errors.Is(err, http.ErrMissingFile) {
257 http.Error(w, "400 - bad request - missing file", http.StatusBadRequest)
259 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
265 log.Check(err, "closing form file")
267 skipMailboxPrefix := r.FormValue("skipMailboxPrefix")
268 tmpf, err := os.CreateTemp("", "mox-import")
270 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
275 store.CloseRemoveTempFile(log, tmpf, "upload")
278 if _, err := io.Copy(tmpf, f); err != nil {
279 log.Errorx("copying import to temporary file", err)
280 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
283 token, isUserError, err := importStart(log, accName, tmpf, skipMailboxPrefix)
285 log.Errorx("starting import", err, slog.Bool("usererror", isUserError))
287 http.Error(w, "400 - bad request - "+err.Error(), http.StatusBadRequest)
289 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
293 tmpf = nil // importStart is now responsible for cleanup.
295 w.Header().Set("Content-Type", "application/json")
296 _ = json.NewEncoder(w).Encode(ImportProgress{Token: token})
303// ImportProgress is returned after uploading a file to import.
304type ImportProgress struct {
305 // For fetching progress, or cancelling an import.
311var requestInfoCtxKey ctxKey = "requestInfo"
313type requestInfo struct {
316 SessionToken store.SessionToken
317 Response http.ResponseWriter
318 Request *http.Request // For Proto and TLS connection state during message submit.
321// LoginPrep returns a login token, and also sets it as cookie. Both must be
322// present in the call to Login.
323func (w Account) LoginPrep(ctx context.Context) string {
324 log := pkglog.WithContext(ctx)
325 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
328 _, err := cryptorand.Read(data[:])
329 xcheckf(ctx, err, "generate token")
330 loginToken := base64.RawURLEncoding.EncodeToString(data[:])
332 webauth.LoginPrep(ctx, log, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken)
337// Login returns a session token for the credentials, or fails with error code
338// "user:badLogin". Call LoginPrep to get a loginToken.
339func (w Account) Login(ctx context.Context, loginToken, username, password string) store.CSRFToken {
340 log := pkglog.WithContext(ctx)
341 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
343 csrfToken, err := webauth.Login(ctx, log, webauth.Accounts, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken, username, password)
344 if _, ok := err.(*sherpa.Error); ok {
347 xcheckf(ctx, err, "login")
351// Logout invalidates the session token.
352func (w Account) Logout(ctx context.Context) {
353 log := pkglog.WithContext(ctx)
354 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
356 err := webauth.Logout(ctx, log, webauth.Accounts, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, reqInfo.AccountName, reqInfo.SessionToken)
357 xcheckf(ctx, err, "logout")
360// SetPassword saves a new password for the account, invalidating the previous password.
361// Sessions are not interrupted, and will keep working. New login attempts must use the new password.
362// Password must be at least 8 characters.
363func (Account) SetPassword(ctx context.Context, password string) {
364 log := pkglog.WithContext(ctx)
365 if len(password) < 8 {
366 panic(&sherpa.Error{Code: "user:error", Message: "password must be at least 8 characters"})
369 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
370 acc, err := store.OpenAccount(log, reqInfo.AccountName)
371 xcheckf(ctx, err, "open account")
374 log.Check(err, "closing account")
377 // Retrieve session, resetting password invalidates it.
378 ls, err := store.SessionUse(ctx, log, reqInfo.AccountName, reqInfo.SessionToken, "")
379 xcheckf(ctx, err, "get session")
381 err = acc.SetPassword(log, password)
382 xcheckf(ctx, err, "setting password")
384 // Session has been invalidated. Add it again.
385 err = store.SessionAddToken(ctx, log, &ls)
386 xcheckf(ctx, err, "restoring session after password reset")
389// Account returns information about the account.
390// StorageUsed is the sum of the sizes of all messages, in bytes.
391// StorageLimit is the maximum storage that can be used, or 0 if there is no limit.
392func (Account) Account(ctx context.Context) (account config.Account, storageUsed, storageLimit int64, suppressions []webapi.Suppression) {
393 log := pkglog.WithContext(ctx)
394 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
396 acc, err := store.OpenAccount(log, reqInfo.AccountName)
397 xcheckf(ctx, err, "open account")
400 log.Check(err, "closing account")
403 var accConf config.Account
404 acc.WithRLock(func() {
405 accConf, _ = acc.Conf()
407 storageLimit = acc.QuotaMessageSize()
408 err := acc.DB.Read(ctx, func(tx *bstore.Tx) error {
409 du := store.DiskUsage{ID: 1}
411 storageUsed = du.MessageSize
414 xcheckf(ctx, err, "get disk usage")
417 suppressions, err = queue.SuppressionList(ctx, reqInfo.AccountName)
418 xcheckf(ctx, err, "list suppressions")
420 return accConf, storageUsed, storageLimit, suppressions
423// AccountSaveFullName saves the full name (used as display name in email messages)
425func (Account) AccountSaveFullName(ctx context.Context, fullName string) {
426 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
427 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
428 acc.FullName = fullName
430 xcheckf(ctx, err, "saving account full name")
433// DestinationSave updates a destination.
434// OldDest is compared against the current destination. If it does not match, an
435// error is returned. Otherwise newDest is saved and the configuration reloaded.
436func (Account) DestinationSave(ctx context.Context, destName string, oldDest, newDest config.Destination) {
437 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
439 err := mox.AccountSave(ctx, reqInfo.AccountName, func(conf *config.Account) {
440 curDest, ok := conf.Destinations[destName]
442 xcheckuserf(ctx, errors.New("not found"), "looking up destination")
444 if !curDest.Equal(oldDest) {
445 xcheckuserf(ctx, errors.New("modified"), "checking stored destination")
448 // Keep fields we manage.
449 newDest.DMARCReports = curDest.DMARCReports
450 newDest.HostTLSReports = curDest.HostTLSReports
451 newDest.DomainTLSReports = curDest.DomainTLSReports
453 // Make copy of reference values.
454 nd := map[string]config.Destination{}
455 for dn, d := range conf.Destinations {
458 nd[destName] = newDest
459 conf.Destinations = nd
461 xcheckf(ctx, err, "saving destination")
464// ImportAbort aborts an import that is in progress. If the import exists and isn't
465// finished, no changes will have been made by the import.
466func (Account) ImportAbort(ctx context.Context, importToken string) error {
467 req := importAbortRequest{importToken, make(chan error)}
468 importers.Abort <- req
469 return <-req.Response
472// Types exposes types not used in API method signatures, such as the import form upload.
473func (Account) Types() (importProgress ImportProgress) {
477// SuppressionList lists the addresses on the suppression list of this account.
478func (Account) SuppressionList(ctx context.Context) (suppressions []webapi.Suppression) {
479 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
480 l, err := queue.SuppressionList(ctx, reqInfo.AccountName)
481 xcheckf(ctx, err, "list suppressions")
485// SuppressionAdd adds an email address to the suppression list.
486func (Account) SuppressionAdd(ctx context.Context, address string, manual bool, reason string) (suppression webapi.Suppression) {
487 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
488 addr, err := smtp.ParseAddress(address)
489 xcheckuserf(ctx, err, "parsing address")
490 sup := webapi.Suppression{
491 Account: reqInfo.AccountName,
495 err = queue.SuppressionAdd(ctx, addr.Path(), &sup)
496 if err != nil && errors.Is(err, bstore.ErrUnique) {
497 xcheckuserf(ctx, err, "add suppression")
499 xcheckf(ctx, err, "add suppression")
503// SuppressionRemove removes the email address from the suppression list.
504func (Account) SuppressionRemove(ctx context.Context, address string) {
505 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
506 addr, err := smtp.ParseAddress(address)
507 xcheckuserf(ctx, err, "parsing address")
508 err = queue.SuppressionRemove(ctx, reqInfo.AccountName, addr.Path())
509 if err != nil && err == bstore.ErrAbsent {
510 xcheckuserf(ctx, err, "remove suppression")
512 xcheckf(ctx, err, "remove suppression")
515// OutgoingWebhookSave saves a new webhook url for outgoing deliveries. If url
516// is empty, the webhook is disabled. If authorization is non-empty it is used for
517// the Authorization header in HTTP requests. Events specifies the outgoing events
518// to be delivered, or all if empty/nil.
519func (Account) OutgoingWebhookSave(ctx context.Context, url, authorization string, events []string) {
520 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
521 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
523 acc.OutgoingWebhook = nil
525 acc.OutgoingWebhook = &config.OutgoingWebhook{URL: url, Authorization: authorization, Events: events}
528 xcheckf(ctx, err, "saving account outgoing webhook")
531// OutgoingWebhookTest makes a test webhook call to urlStr, with optional
532// authorization. If the HTTP request is made this call will succeed also for
533// non-2xx HTTP status codes.
534func (Account) OutgoingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Outgoing) (code int, response string, errmsg string) {
535 log := pkglog.WithContext(ctx)
537 xvalidURL(ctx, urlStr)
538 log.Debug("making webhook test call for outgoing message", slog.String("url", urlStr))
541 enc := json.NewEncoder(&b)
542 enc.SetIndent("", "\t")
543 enc.SetEscapeHTML(false)
544 err := enc.Encode(data)
545 xcheckf(ctx, err, "encoding outgoing webhook data")
547 code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
551 log.Debugx("result for webhook test call for outgoing message", err, slog.Int("code", code), slog.String("response", response))
552 return code, response, errmsg
555// IncomingWebhookSave saves a new webhook url for incoming deliveries. If url is
556// empty, the webhook is disabled. If authorization is not empty, it is used in
557// the Authorization header in requests.
558func (Account) IncomingWebhookSave(ctx context.Context, url, authorization string) {
559 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
560 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
562 acc.IncomingWebhook = nil
564 acc.IncomingWebhook = &config.IncomingWebhook{URL: url, Authorization: authorization}
567 xcheckf(ctx, err, "saving account incoming webhook")
570func xvalidURL(ctx context.Context, s string) {
571 u, err := url.Parse(s)
572 xcheckuserf(ctx, err, "parsing url")
573 if u.Scheme != "http" && u.Scheme != "https" {
574 xcheckuserf(ctx, errors.New("scheme must be http or https"), "parsing url")
578// IncomingWebhookTest makes a test webhook HTTP delivery request to urlStr,
579// with optional authorization header. If the HTTP call is made, this function
580// returns non-error regardless of HTTP status code.
581func (Account) IncomingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Incoming) (code int, response string, errmsg string) {
582 log := pkglog.WithContext(ctx)
584 xvalidURL(ctx, urlStr)
585 log.Debug("making webhook test call for incoming message", slog.String("url", urlStr))
588 enc := json.NewEncoder(&b)
589 enc.SetEscapeHTML(false)
590 enc.SetIndent("", "\t")
591 err := enc.Encode(data)
592 xcheckf(ctx, err, "encoding incoming webhook data")
593 code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
597 log.Debugx("result for webhook test call for incoming message", err, slog.Int("code", code), slog.String("response", response))
598 return code, response, errmsg
601// FromIDLoginAddressesSave saves new login addresses to enable unique SMTP
602// MAIL FROM addresses ("fromid") for deliveries from the queue.
603func (Account) FromIDLoginAddressesSave(ctx context.Context, loginAddresses []string) {
604 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
605 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
606 acc.FromIDLoginAddresses = loginAddresses
608 xcheckf(ctx, err, "saving account fromid login addresses")
611// KeepRetiredPeriodsSave saves periods to save retired messages and webhooks.
612func (Account) KeepRetiredPeriodsSave(ctx context.Context, keepRetiredMessagePeriod, keepRetiredWebhookPeriod time.Duration) {
613 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
614 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
615 acc.KeepRetiredMessagePeriod = keepRetiredMessagePeriod
616 acc.KeepRetiredWebhookPeriod = keepRetiredWebhookPeriod
618 xcheckf(ctx, err, "saving account keep retired periods")
621// AutomaticJunkFlagsSave saves settings for automatically marking messages as
622// junk/nonjunk when moved to mailboxes matching certain regular expressions.
623func (Account) AutomaticJunkFlagsSave(ctx context.Context, enabled bool, junkRegexp, neutralRegexp, notJunkRegexp string) {
624 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
625 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
626 acc.AutomaticJunkFlags = config.AutomaticJunkFlags{
628 JunkMailboxRegexp: junkRegexp,
629 NeutralMailboxRegexp: neutralRegexp,
630 NotJunkMailboxRegexp: notJunkRegexp,
633 xcheckf(ctx, err, "saving account automatic junk flags")
636// JunkFilterSave saves junk filter settings. If junkFilter is nil, the junk filter
637// is disabled. Otherwise all fields except Threegrams are stored.
638func (Account) JunkFilterSave(ctx context.Context, junkFilter *config.JunkFilter) {
639 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
640 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
641 if junkFilter == nil {
645 old := acc.JunkFilter
646 acc.JunkFilter = junkFilter
647 acc.JunkFilter.Params.Threegrams = false
649 acc.JunkFilter.Params.Threegrams = old.Params.Threegrams
652 xcheckf(ctx, err, "saving account junk filter settings")
655// RejectsSave saves the RejectsMailbox and KeepRejects settings.
656func (Account) RejectsSave(ctx context.Context, mailbox string, keep bool) {
657 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
658 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
659 acc.RejectsMailbox = mailbox
660 acc.KeepRejects = keep
662 xcheckf(ctx, err, "saving account rejects settings")