accounts.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. package email
  2. /*
  3. accounts.go
  4. Adding, testing, updating and removing mail accounts. An account is only
  5. stored after its IMAP login (and, unless skipped, its SMTP login) worked,
  6. so the sidebar never fills up with half-configured accounts.
  7. */
  8. import (
  9. "context"
  10. "errors"
  11. "fmt"
  12. "net/mail"
  13. "sort"
  14. "strings"
  15. "imuslab.com/arozos/mod/info/logger"
  16. )
  17. // accountColors cycle for new accounts (dot in the sidebar, avatar ring).
  18. var accountColors = []string{"#3b82f6", "#8b5cf6", "#10b981", "#f59e0b", "#ef4444", "#06b6d4", "#ec4899", "#64748b"}
  19. // TestResult reports the outcome of a connection test.
  20. type TestResult struct {
  21. IMAPOK bool `json:"imapOk"`
  22. SMTPOK bool `json:"smtpOk"`
  23. Error string `json:"error,omitempty"`
  24. AuthFailed bool `json:"authFailed"`
  25. Hint string `json:"hint,omitempty"`
  26. Stage string `json:"stage,omitempty"` //imap | smtp
  27. }
  28. func (a *Account) info() AccountInfo {
  29. return AccountInfo{
  30. ID: a.ID,
  31. Email: a.Email,
  32. DisplayName: a.DisplayName,
  33. Provider: a.Provider,
  34. Color: a.Color,
  35. IMAP: a.IMAP,
  36. SMTP: a.SMTP,
  37. Auth: a.Auth,
  38. OAuthProvider: a.OAuthProvider,
  39. Signature: a.Signature,
  40. ReplyTo: a.ReplyTo,
  41. SaveSent: a.SaveSent,
  42. Order: a.Order,
  43. HasSecret: a.Secret != "",
  44. SeparateSMTPKey: a.SMTPSecret != "",
  45. AuthError: a.AuthError,
  46. }
  47. }
  48. // ListAccounts returns a user's accounts in sidebar order.
  49. func (m *Manager) ListAccounts(p Principal) ([]AccountInfo, error) {
  50. accounts, err := m.store.listAccounts(p.Username)
  51. if err != nil {
  52. return nil, err
  53. }
  54. results := make([]AccountInfo, 0, len(accounts))
  55. for _, account := range accounts {
  56. results = append(results, account.info())
  57. }
  58. return results, nil
  59. }
  60. // account loads one of p's accounts.
  61. func (m *Manager) account(p Principal, id string) (*Account, error) {
  62. return m.store.getAccount(p.Username, strings.TrimSpace(id))
  63. }
  64. // GetAccount returns the browser view of one account.
  65. func (m *Manager) GetAccount(p Principal, id string) (*AccountInfo, error) {
  66. account, err := m.account(p, id)
  67. if err != nil {
  68. return nil, err
  69. }
  70. info := account.info()
  71. return &info, nil
  72. }
  73. // normaliseInput validates an account form and fills preset defaults.
  74. func (m *Manager) normaliseInput(p Principal, input *AccountInput) error {
  75. input.Email = strings.TrimSpace(input.Email)
  76. parsed, err := mail.ParseAddress(input.Email)
  77. if err != nil || !strings.Contains(parsed.Address, "@") {
  78. return errors.New("please enter a valid email address")
  79. }
  80. input.Email = parsed.Address
  81. if input.DisplayName == "" && parsed.Name != "" {
  82. input.DisplayName = parsed.Name
  83. }
  84. input.DisplayName = strings.TrimSpace(input.DisplayName)
  85. preset, known := PresetByID(input.Provider)
  86. if !known {
  87. if detected, ok := presetForDomain(domainOf(input.Email)); ok {
  88. preset = detected
  89. } else {
  90. preset = customPreset
  91. }
  92. input.Provider = preset.ID
  93. }
  94. fill := func(server *ServerConfig, defaults ServerConfig, label string) error {
  95. server.Host = strings.ToLower(strings.TrimSpace(server.Host))
  96. if server.Host == "" {
  97. server.Host = defaults.Host
  98. }
  99. if server.Port == 0 {
  100. server.Port = defaults.Port
  101. }
  102. if server.Security == "" {
  103. server.Security = defaults.Security
  104. }
  105. server.Username = strings.TrimSpace(server.Username)
  106. if server.Username == "" {
  107. server.Username = usernameFor(preset.UsernameStyle, input.Email)
  108. }
  109. if server.Host == "" {
  110. return fmt.Errorf("%s server is required", label)
  111. }
  112. if strings.ContainsAny(server.Host, " /\\@") {
  113. return fmt.Errorf("%s server name is not valid", label)
  114. }
  115. if server.Port <= 0 || server.Port > 65535 {
  116. return fmt.Errorf("%s port is not valid", label)
  117. }
  118. if !oneOf(server.Security, SecuritySSL, SecuritySTARTTLS, SecurityNone) {
  119. return fmt.Errorf("%s security must be ssl, starttls or none", label)
  120. }
  121. if server.Security == SecurityNone && !m.allowInsecure(p) {
  122. return ErrInsecureBlocked
  123. }
  124. return nil
  125. }
  126. if err := fill(&input.IMAP, preset.IMAP, "IMAP"); err != nil {
  127. return err
  128. }
  129. if err := fill(&input.SMTP, preset.SMTP, "SMTP"); err != nil {
  130. return err
  131. }
  132. if input.Auth == "" {
  133. input.Auth = AuthPassword
  134. }
  135. if !oneOf(input.Auth, AuthPassword, AuthOAuth2) {
  136. return errors.New("unknown authentication method")
  137. }
  138. if !oneOf(input.SaveSent, "auto", "always", "never") {
  139. input.SaveSent = "auto"
  140. }
  141. input.ReplyTo = strings.TrimSpace(input.ReplyTo)
  142. if input.ReplyTo != "" {
  143. if _, err := mail.ParseAddress(input.ReplyTo); err != nil {
  144. return errors.New("the reply-to address is not valid")
  145. }
  146. }
  147. if len(input.Signature) > 256*1024 {
  148. return errors.New("the signature is too large")
  149. }
  150. return nil
  151. }
  152. // TestAccount checks the IMAP and SMTP settings without storing anything.
  153. // Only password accounts can be tested this way; OAuth accounts are tested
  154. // as part of AddAccount, where the pending token is consumed.
  155. func (m *Manager) TestAccount(ctx context.Context, p Principal, input AccountInput) TestResult {
  156. if err := m.normaliseInput(p, &input); err != nil {
  157. return TestResult{Error: err.Error()}
  158. }
  159. if input.Auth == AuthOAuth2 {
  160. return TestResult{Error: "OAuth accounts are verified when they are added"}
  161. }
  162. account, err := m.accountFromInput(p, input, nil)
  163. if err != nil {
  164. return TestResult{Error: err.Error()}
  165. }
  166. return m.verifyAccount(ctx, p, account, input.SkipSMTPCheck)
  167. }
  168. // verifyAccount logs in to both servers of an unsaved account.
  169. func (m *Manager) verifyAccount(ctx context.Context, p Principal, account *Account, skipSMTP bool) TestResult {
  170. result := TestResult{}
  171. client, err := m.dialIMAP(ctx, p, account)
  172. if err != nil {
  173. result.Stage = "imap"
  174. result.Error = err.Error()
  175. result.AuthFailed = IsAuthError(err)
  176. result.Hint = AuthHint(err)
  177. return result
  178. }
  179. logoutAndClose(client)
  180. result.IMAPOK = true
  181. if skipSMTP {
  182. return result
  183. }
  184. if err := m.checkSMTP(ctx, p, account); err != nil {
  185. result.Stage = "smtp"
  186. result.Error = err.Error()
  187. result.AuthFailed = IsAuthError(err)
  188. result.Hint = AuthHint(err)
  189. return result
  190. }
  191. result.SMTPOK = true
  192. return result
  193. }
  194. // accountFromInput builds an Account (with sealed secrets) from a form.
  195. // existing supplies kept secrets on update.
  196. func (m *Manager) accountFromInput(p Principal, input AccountInput, existing *Account) (*Account, error) {
  197. account := &Account{
  198. Owner: p.Username,
  199. Email: input.Email,
  200. DisplayName: input.DisplayName,
  201. Provider: input.Provider,
  202. Color: input.Color,
  203. IMAP: input.IMAP,
  204. SMTP: input.SMTP,
  205. Auth: input.Auth,
  206. Signature: input.Signature,
  207. ReplyTo: input.ReplyTo,
  208. SaveSent: input.SaveSent,
  209. }
  210. if existing != nil {
  211. account.ID = existing.ID
  212. account.Order = existing.Order
  213. account.Created = existing.Created
  214. account.OAuthProvider = existing.OAuthProvider
  215. account.OAuthFlow = existing.OAuthFlow
  216. if account.Color == "" {
  217. account.Color = existing.Color
  218. }
  219. }
  220. switch input.Auth {
  221. case AuthPassword:
  222. account.OAuthProvider = ""
  223. account.OAuthFlow = ""
  224. if input.Password != "" {
  225. sealed, err := m.box.Seal(input.Password)
  226. if err != nil {
  227. return nil, err
  228. }
  229. account.Secret = sealed
  230. } else if existing != nil && existing.Auth == AuthPassword {
  231. account.Secret = existing.Secret
  232. } else {
  233. return nil, errors.New("please enter the password")
  234. }
  235. if input.SMTPPassword != "" {
  236. sealed, err := m.box.Seal(input.SMTPPassword)
  237. if err != nil {
  238. return nil, err
  239. }
  240. account.SMTPSecret = sealed
  241. } else if existing != nil && existing.Auth == AuthPassword {
  242. account.SMTPSecret = existing.SMTPSecret
  243. }
  244. case AuthOAuth2:
  245. if input.OAuthState != "" {
  246. pending, err := m.oauth.take(input.OAuthState, p.Username)
  247. if err != nil {
  248. return nil, err
  249. }
  250. if pending.token.RefreshToken == "" {
  251. return nil, errors.New("the provider did not grant offline access, please sign in again and accept all permissions")
  252. }
  253. sealed, err := m.box.Seal(pending.token.RefreshToken)
  254. if err != nil {
  255. return nil, err
  256. }
  257. account.Secret = sealed
  258. account.OAuthProvider = pending.provider
  259. account.OAuthFlow = pending.flow
  260. account.freshAccessToken = pending.token.AccessToken
  261. if !pending.token.Expiry.IsZero() {
  262. account.freshTokenExpiry = pending.token.Expiry.Unix()
  263. }
  264. if pending.idEmail != "" && !strings.EqualFold(pending.idEmail, account.Email) {
  265. //The mailbox is whatever the user actually signed in to
  266. account.Email = pending.idEmail
  267. if strings.EqualFold(account.IMAP.Username, input.Email) {
  268. account.IMAP.Username = pending.idEmail
  269. }
  270. if strings.EqualFold(account.SMTP.Username, input.Email) {
  271. account.SMTP.Username = pending.idEmail
  272. }
  273. }
  274. } else if existing != nil && existing.Auth == AuthOAuth2 {
  275. account.Secret = existing.Secret
  276. } else {
  277. return nil, errors.New("please sign in with your provider first")
  278. }
  279. account.SMTPSecret = ""
  280. }
  281. return account, nil
  282. }
  283. // AddAccount verifies and stores a new account.
  284. func (m *Manager) AddAccount(ctx context.Context, p Principal, input AccountInput) (*AccountInfo, TestResult, error) {
  285. if err := m.normaliseInput(p, &input); err != nil {
  286. return nil, TestResult{Error: err.Error()}, err
  287. }
  288. existing, err := m.store.listAccounts(p.Username)
  289. if err != nil {
  290. return nil, TestResult{}, err
  291. }
  292. config := m.store.getAdminConfig()
  293. if config.MaxAccounts > 0 && len(existing) >= config.MaxAccounts {
  294. err := fmt.Errorf("you can add at most %d mail accounts", config.MaxAccounts)
  295. return nil, TestResult{Error: err.Error()}, err
  296. }
  297. account, err := m.accountFromInput(p, input, nil)
  298. if err != nil {
  299. return nil, TestResult{Error: err.Error()}, err
  300. }
  301. for _, other := range existing {
  302. if strings.EqualFold(other.Email, account.Email) && strings.EqualFold(other.IMAP.Host, account.IMAP.Host) {
  303. err := errors.New(account.Email + " is already added")
  304. return nil, TestResult{Error: err.Error()}, err
  305. }
  306. }
  307. account.ID = randomID(8)
  308. account.Created = m.now().Unix()
  309. account.Updated = account.Created
  310. maxOrder := -1
  311. for _, other := range existing {
  312. if other.Order > maxOrder {
  313. maxOrder = other.Order
  314. }
  315. }
  316. account.Order = maxOrder + 1
  317. if account.Color == "" {
  318. account.Color = accountColors[len(existing)%len(accountColors)]
  319. }
  320. m.oauth.seed(account)
  321. result := m.verifyAccount(ctx, p, account, input.SkipSMTPCheck)
  322. if result.Error != "" {
  323. m.oauth.forget(account)
  324. return nil, result, errors.New(result.Error)
  325. }
  326. if err := m.store.saveAccount(account); err != nil {
  327. return nil, result, err
  328. }
  329. logger.PrintAndLog("Email", "Mail account "+account.Email+" added by "+p.Username, nil)
  330. info := account.info()
  331. return &info, result, nil
  332. }
  333. // UpdateAccount changes an account. Connection settings and credentials are
  334. // re-verified before anything is stored.
  335. func (m *Manager) UpdateAccount(ctx context.Context, p Principal, id string, input AccountInput) (*AccountInfo, TestResult, error) {
  336. existing, err := m.account(p, id)
  337. if err != nil {
  338. return nil, TestResult{Error: err.Error()}, err
  339. }
  340. if err := m.normaliseInput(p, &input); err != nil {
  341. return nil, TestResult{Error: err.Error()}, err
  342. }
  343. account, err := m.accountFromInput(p, input, existing)
  344. if err != nil {
  345. return nil, TestResult{Error: err.Error()}, err
  346. }
  347. connectionChanged := account.IMAP != existing.IMAP || account.SMTP != existing.SMTP ||
  348. account.Auth != existing.Auth || account.Secret != existing.Secret ||
  349. account.SMTPSecret != existing.SMTPSecret || !strings.EqualFold(account.Email, existing.Email)
  350. result := TestResult{IMAPOK: true, SMTPOK: true}
  351. if connectionChanged {
  352. m.oauth.forget(account)
  353. m.oauth.seed(account)
  354. result = m.verifyAccount(ctx, p, account, input.SkipSMTPCheck)
  355. if result.Error != "" {
  356. return nil, result, errors.New(result.Error)
  357. }
  358. account.AuthError = ""
  359. } else {
  360. account.AuthError = existing.AuthError
  361. }
  362. account.Updated = m.now().Unix()
  363. if err := m.store.saveAccount(account); err != nil {
  364. return nil, result, err
  365. }
  366. if connectionChanged {
  367. m.pool.invalidate(poolKey(p.Username, account.ID))
  368. }
  369. info := account.info()
  370. return &info, result, nil
  371. }
  372. // RemoveAccount deletes an account and everything stored locally for it.
  373. func (m *Manager) RemoveAccount(p Principal, id string) error {
  374. account, err := m.account(p, id)
  375. if err != nil {
  376. return err
  377. }
  378. if err := m.store.deleteAccount(p.Username, account.ID); err != nil {
  379. return err
  380. }
  381. m.pool.invalidate(poolKey(p.Username, account.ID))
  382. m.oauth.forget(account)
  383. m.previews.dropAccount(p.Username, account.ID)
  384. prefix := account.ID + ":"
  385. m.store.deleteOwnedWithPrefix(tableSnooze, p.Username, prefix)
  386. m.store.deleteOwnedWithPrefix(tableLabelMap, p.Username, prefix)
  387. m.outbox.dropAccount(p.Username, account.ID)
  388. logger.PrintAndLog("Email", "Mail account "+account.Email+" removed by "+p.Username, nil)
  389. return nil
  390. }
  391. // ReorderAccounts stores a new sidebar order.
  392. func (m *Manager) ReorderAccounts(p Principal, ids []string) error {
  393. accounts, err := m.store.listAccounts(p.Username)
  394. if err != nil {
  395. return err
  396. }
  397. position := map[string]int{}
  398. for index, id := range ids {
  399. position[id] = index
  400. }
  401. sort.SliceStable(accounts, func(i, j int) bool {
  402. pi, iok := position[accounts[i].ID]
  403. pj, jok := position[accounts[j].ID]
  404. if iok && jok {
  405. return pi < pj
  406. }
  407. return iok && !jok
  408. })
  409. for index, account := range accounts {
  410. if account.Order != index {
  411. account.Order = index
  412. if err := m.store.saveAccount(account); err != nil {
  413. return err
  414. }
  415. }
  416. }
  417. return nil
  418. }