mirror of
https://github.com/mjl-/mox.git
synced 2024-12-27 08:53:48 +03:00
849b4ec9e9
it was far down on the roadmap, but implemented earlier, because it's interesting, and to help prepare for a jmap implementation. for jmap we need to implement more client-like functionality than with just imap. internal data structures need to change. jmap has lots of other requirements, so it's already a big project. by implementing a webmail now, some of the required data structure changes become clear and can be made now, so the later jmap implementation can do things similarly to the webmail code. the webmail frontend and webmail are written together, making their interface/api much smaller and simpler than jmap. one of the internal changes is that we now keep track of per-mailbox total/unread/unseen/deleted message counts and mailbox sizes. keeping this data consistent after any change to the stored messages (through the code base) is tricky, so mox now has a consistency check that verifies the counts are correct, which runs only during tests, each time an internal account reference is closed. we have a few more internal "changes" that are propagated for the webmail frontend (that imap doesn't have a way to propagate on a connection), like changes to the special-use flags on mailboxes, and used keywords in a mailbox. more changes that will be required have revealed themselves while implementing the webmail, and will be implemented next. the webmail user interface is modeled after the mail clients i use or have used: thunderbird, macos mail, mutt; and webmails i normally only use for testing: gmail, proton, yahoo, outlook. a somewhat technical user is assumed, but still the goal is to make this webmail client easy to use for everyone. the user interface looks like most other mail clients: a list of mailboxes, a search bar, a message list view, and message details. there is a top/bottom and a left/right layout for the list/message view, default is automatic based on screen size. the panes can be resized by the user. buttons for actions are just text, not icons. clicking a button briefly shows the shortcut for the action in the bottom right, helping with learning to operate quickly. any text that is underdotted has a title attribute that causes more information to be displayed, e.g. what a button does or a field is about. to highlight potential phishing attempts, any text (anywhere in the webclient) that switches unicode "blocks" (a rough approximation to (language) scripts) within a word is underlined orange. multiple messages can be selected with familiar ui interaction: clicking while holding control and/or shift keys. keyboard navigation works with arrows/page up/down and home/end keys, and also with a few basic vi-like keys for list/message navigation. we prefer showing the text instead of html (with inlined images only) version of a message. html messages are shown in an iframe served from an endpoint with CSP headers to prevent dangerous resources (scripts, external images) from being loaded. the html is also sanitized, with javascript removed. a user can choose to load external resources (e.g. images for tracking purposes). the frontend is just (strict) typescript, no external frameworks. all incoming/outgoing data is typechecked, both the api request parameters and response types, and the data coming in over SSE. the types and checking code are generated with sherpats, which uses the api definitions generated by sherpadoc based on the Go code. so types from the backend are automatically propagated to the frontend. since there is no framework to automatically propagate properties and rerender components, changes coming in over the SSE connection are propagated explicitly with regular function calls. the ui is separated into "views", each with a "root" dom element that is added to the visible document. these views have additional functions for getting changes propagated, often resulting in the view updating its (internal) ui state (dom). we keep the frontend compilation simple, it's just a few typescript files that get compiled (combined and types stripped) into a single js file, no additional runtime code needed or complicated build processes used. the webmail is served is served from a compressed, cachable html file that includes style and the javascript, currently just over 225kb uncompressed, under 60kb compressed (not minified, including comments). we include the generated js files in the repository, to keep Go's easily buildable self-contained binaries. authentication is basic http, as with the account and admin pages. most data comes in over one long-term SSE connection to the backend. api requests signal which mailbox/search/messages are requested over the SSE connection. fetching individual messages, and making changes, are done through api calls. the operations are similar to imap, so some code has been moved from package imapserver to package store. the future jmap implementation will benefit from these changes too. more functionality will probably be moved to the store package in the future. the quickstart enables webmail on the internal listener by default (for new installs). users can enable it on the public listener if they want to. mox localserve enables it too. to enable webmail on existing installs, add settings like the following to the listeners in mox.conf, similar to AccountHTTP(S): WebmailHTTP: Enabled: true WebmailHTTPS: Enabled: true special thanks to liesbeth, gerben, andrii for early user feedback. there is plenty still to do, see the list at the top of webmail/webmail.ts. feedback welcome as always.
713 lines
23 KiB
HTML
713 lines
23 KiB
HTML
<!doctype html>
|
|
<html>
|
|
<head>
|
|
<title>Mox Account</title>
|
|
<meta charset="utf-8" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
<link rel="icon" href="noNeedlessFaviconRequestsPlease:" />
|
|
<style>
|
|
body, html { padding: 1em; font-size: 16px; }
|
|
* { font-size: inherit; font-family: ubuntu, lato, sans-serif; margin: 0; padding: 0; box-sizing: border-box; }
|
|
h1, h2, h3, h4 { margin-bottom: 1ex; }
|
|
h1 { font-size: 1.2rem; }
|
|
h2 { font-size: 1.1rem; }
|
|
h3, h4 { font-size: 1rem; }
|
|
ul { padding-left: 1rem; }
|
|
.literal { background-color: #fdfdfd; padding: .5em 1em; border: 1px solid #eee; border-radius: 4px; white-space: pre-wrap; font-family: monospace; font-size: 15px; tab-size: 4; }
|
|
table td, table th { padding: .2em .5em; }
|
|
table > tbody > tr:nth-child(odd) { background-color: #f8f8f8; }
|
|
.text { max-width: 50em; }
|
|
p { margin-bottom: 1em; max-width: 50em; }
|
|
[title] { text-decoration: underline; text-decoration-style: dotted; }
|
|
fieldset { border: 0; }
|
|
#page { opacity: 1; animation: fadein 0.15s ease-in; }
|
|
#page.loading { 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 } }
|
|
</style>
|
|
<script src="api/sherpa.js"></script>
|
|
<script>api._sherpa.baseurl = 'api/'</script>
|
|
</head>
|
|
<body>
|
|
<div id="page">Loading...</div>
|
|
|
|
<script>
|
|
const [dom, style, attr, prop] = (function() {
|
|
function _domKids(e, ...kl) {
|
|
kl.forEach(k => {
|
|
if (typeof k === 'string' || k instanceof String) {
|
|
e.appendChild(document.createTextNode(k))
|
|
} else if (k instanceof Node) {
|
|
e.appendChild(k)
|
|
} else if (Array.isArray(k)) {
|
|
_domKids(e, ...k)
|
|
} else if (typeof k === 'function') {
|
|
if (!k.name) {
|
|
throw new Error('function without name', k)
|
|
}
|
|
e.addEventListener(k.name, k)
|
|
} else if (typeof k === 'object' && k !== null) {
|
|
if (k.root) {
|
|
e.appendChild(k.root)
|
|
return
|
|
}
|
|
for (const key in k) {
|
|
const value = k[key]
|
|
if (key === '_prop') {
|
|
for (const prop in value) {
|
|
e[prop] = value[prop]
|
|
}
|
|
} else if (key === '_attr') {
|
|
for (const prop in value) {
|
|
e.setAttribute(prop, value[prop])
|
|
}
|
|
} else if (key === '_listen') {
|
|
e.addEventListener(...value)
|
|
} else {
|
|
e.style[key] = value
|
|
}
|
|
}
|
|
} else {
|
|
console.log('bad kid', k)
|
|
throw new Error('bad kid')
|
|
}
|
|
})
|
|
}
|
|
const _dom = (kind, ...kl) => {
|
|
const t = kind.split('.')
|
|
const e = document.createElement(t[0])
|
|
for (let i = 1; i < t.length; i++) {
|
|
e.classList.add(t[i])
|
|
}
|
|
_domKids(e, kl)
|
|
return e
|
|
}
|
|
_dom._kids = function(e, ...kl) {
|
|
while(e.firstChild) {
|
|
e.removeChild(e.firstChild)
|
|
}
|
|
_domKids(e, kl)
|
|
}
|
|
const dom = new Proxy(_dom, {
|
|
get: function(dom, prop) {
|
|
if (prop in dom) {
|
|
return dom[prop]
|
|
}
|
|
const fn = (...kl) => _dom(prop, kl)
|
|
dom[prop] = fn
|
|
return fn
|
|
},
|
|
apply: function(target, that, args) {
|
|
if (args.length === 1 && typeof args[0] === 'object' && !Array.isArray(args[0])) {
|
|
return {_attr: args[0]}
|
|
}
|
|
return _dom(...args)
|
|
},
|
|
})
|
|
const style = x => x
|
|
const attr = x => { return {_attr: x} }
|
|
const prop = x => { return {_prop: x} }
|
|
return [dom, style, attr, prop]
|
|
})()
|
|
|
|
const link = (href, anchorOpt) => dom.a(attr({href: href, rel: 'noopener noreferrer'}), anchorOpt || href)
|
|
|
|
const crumblink = (text, link) => dom.a(text, attr({href: link}))
|
|
const crumbs = (...l) => [dom.h1(l.map((e, index) => index === 0 ? e : [' / ', e])), dom.br()]
|
|
|
|
const footer = dom.div(
|
|
style({marginTop: '6ex', opacity: 0.75}),
|
|
link('https://github.com/mjl-/mox', 'mox'),
|
|
' ',
|
|
api._sherpa.version,
|
|
)
|
|
|
|
const domainName = d => {
|
|
return d.Unicode || d.ASCII
|
|
}
|
|
|
|
const domainString = d => {
|
|
if (d.Unicode) {
|
|
return d.Unicode+" ("+d.ASCII+")"
|
|
}
|
|
return d.ASCII
|
|
}
|
|
|
|
const box = (color, ...l) => [
|
|
dom.div(
|
|
style({
|
|
display: 'inline-block',
|
|
padding: '.25em .5em',
|
|
backgroundColor: color,
|
|
borderRadius: '3px',
|
|
margin: '.5ex 0',
|
|
}),
|
|
l,
|
|
),
|
|
dom.br(),
|
|
]
|
|
|
|
const green = '#1dea20'
|
|
const yellow = '#ffe400'
|
|
const red = '#ff7443'
|
|
const blue = '#8bc8ff'
|
|
|
|
const index = async () => {
|
|
const [accountFullName, domain, destinations] = await api.Account()
|
|
|
|
let fullNameForm, fullNameFieldset, fullName
|
|
let passwordForm, passwordFieldset, password1, password2, passwordHint
|
|
|
|
let importForm, importFieldset, mailboxFile, mailboxFileHint, mailboxPrefix, mailboxPrefixHint, importProgress, importAbortBox, importAbort
|
|
|
|
const importTrack = async (token) => {
|
|
const importConnection = dom.div('Waiting for updates...')
|
|
importProgress.appendChild(importConnection)
|
|
|
|
let countsTbody
|
|
let counts = {} // mailbox -> elem
|
|
|
|
let problems // element
|
|
|
|
await new Promise((resolve, reject) => {
|
|
const eventSource = new window.EventSource('importprogress?token=' + encodeURIComponent(token))
|
|
eventSource.addEventListener('open', function(e) {
|
|
console.log('eventsource open', {e})
|
|
dom._kids(importConnection, dom.div('Waiting for updates, connected...'))
|
|
|
|
dom._kids(importAbortBox,
|
|
importAbort=dom.button('Abort import', attr({title: 'If the import is not yet finished, it can be aborted and no messages will have been imported.'}), async function click(e) {
|
|
try {
|
|
await api.ImportAbort(token)
|
|
} catch (err) {
|
|
console.log({err})
|
|
window.alert('Error: ' + err.message)
|
|
}
|
|
// On success, the event source will get an aborted notification and shutdown the connection.
|
|
})
|
|
)
|
|
})
|
|
eventSource.addEventListener('error', function(e) {
|
|
console.log('eventsource error', {e})
|
|
dom._kids(importConnection, box(red, 'Connection error'))
|
|
reject({message: 'Connection error'})
|
|
})
|
|
eventSource.addEventListener('count', (e) => {
|
|
const data = JSON.parse(e.data) // {Mailbox: ..., Count: ...}
|
|
console.log('import count event', {e, data})
|
|
if (!countsTbody) {
|
|
importProgress.appendChild(
|
|
dom.div(
|
|
dom.br(),
|
|
dom.h3('Importing mailboxes and messages...'),
|
|
dom.table(
|
|
dom.thead(
|
|
dom.tr(dom.th('Mailbox'), dom.th('Messages')),
|
|
),
|
|
countsTbody=dom.tbody(),
|
|
),
|
|
)
|
|
)
|
|
}
|
|
let elem = counts[data.Mailbox]
|
|
if (!elem) {
|
|
countsTbody.appendChild(
|
|
dom.tr(
|
|
dom.td(data.Mailbox),
|
|
elem=dom.td(style({textAlign: 'right'}), ''+data.Count),
|
|
),
|
|
)
|
|
counts[data.Mailbox] = elem
|
|
}
|
|
dom._kids(elem, ''+data.Count)
|
|
})
|
|
eventSource.addEventListener('problem', (e) => {
|
|
const data = JSON.parse(e.data) // {Message: ...}
|
|
console.log('import problem event', {e, data})
|
|
if (!problems) {
|
|
importProgress.appendChild(
|
|
dom.div(
|
|
dom.br(),
|
|
dom.h3('Problems during import'),
|
|
problems=dom.div(),
|
|
),
|
|
)
|
|
}
|
|
problems.appendChild(dom.div(box(yellow, data.Message)))
|
|
})
|
|
eventSource.addEventListener('done', (e) => {
|
|
console.log('import done event', {e})
|
|
importProgress.appendChild(dom.div(dom.br(), box(blue, 'Import finished')))
|
|
|
|
eventSource.close()
|
|
dom._kids(importConnection)
|
|
dom._kids(importAbortBox)
|
|
window.sessionStorage.removeItem('ImportToken')
|
|
|
|
resolve()
|
|
})
|
|
eventSource.addEventListener('aborted', function(e) {
|
|
console.log('import aborted event', {e})
|
|
|
|
importProgress.appendChild(dom.div(dom.br(), box(red, 'Import aborted, no message imported')))
|
|
|
|
eventSource.close()
|
|
dom._kids(importConnection)
|
|
dom._kids(importAbortBox)
|
|
window.sessionStorage.removeItem('ImportToken')
|
|
|
|
reject({message: 'Import aborted'})
|
|
})
|
|
})
|
|
}
|
|
|
|
const page = document.getElementById('page')
|
|
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: ',
|
|
domain.ASCII ? domainString(domain) : '(none)',
|
|
),
|
|
dom.br(),
|
|
|
|
fullNameForm=dom.form(
|
|
fullNameFieldset=dom.fieldset(
|
|
dom.label(
|
|
style({display: 'inline-block'}),
|
|
'Full name',
|
|
dom.br(),
|
|
fullName=dom.input(attr({value: accountFullName, title: 'Name to use in From header when composing messages. Can be overridden per configured address.'})),
|
|
|
|
),
|
|
' ',
|
|
dom.button('Save'),
|
|
),
|
|
async function submit(e) {
|
|
e.preventDefault()
|
|
fullNameFieldset.disabled = true
|
|
try {
|
|
await api.AccountSaveFullName(fullName.value)
|
|
fullName.setAttribute('value', fullName.value)
|
|
fullNameForm.reset()
|
|
window.alert('Full name has been changed.')
|
|
} catch (err) {
|
|
console.log({err})
|
|
window.alert('Error: ' + err.message)
|
|
} finally {
|
|
fullNameFieldset.disabled = false
|
|
}
|
|
},
|
|
),
|
|
dom.br(),
|
|
|
|
dom.h2('Addresses'),
|
|
dom.ul(
|
|
Object.entries(destinations).sort().map(t =>
|
|
dom.li(
|
|
dom.a(t[0], attr({href: '#destinations/'+t[0]})),
|
|
t[0].startsWith('@') ? ' (catchall)' : [],
|
|
),
|
|
),
|
|
),
|
|
dom.br(),
|
|
dom.h2('Change password'),
|
|
passwordForm=dom.form(
|
|
passwordFieldset=dom.fieldset(
|
|
dom.label(
|
|
style({display: 'inline-block'}),
|
|
'New password',
|
|
dom.br(),
|
|
password1=dom.input(attr({type: 'password', required: ''}), function focus() {
|
|
passwordHint.style.display = ''
|
|
}),
|
|
),
|
|
' ',
|
|
dom.label(
|
|
style({display: 'inline-block'}),
|
|
'New password repeat',
|
|
dom.br(),
|
|
password2=dom.input(attr({type: 'password', required: ''})),
|
|
),
|
|
' ',
|
|
dom.button('Change password'),
|
|
),
|
|
passwordHint=dom.div(
|
|
style({display: 'none', marginTop: '.5ex'}),
|
|
dom.button('Generate random password', attr({type: 'button'}), function click(e) {
|
|
e.preventDefault()
|
|
let b = new Uint8Array(1)
|
|
let s = ''
|
|
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*-_;:,<.>/'
|
|
while (s.length < 12) {
|
|
self.crypto.getRandomValues(b)
|
|
if (Math.ceil(b[0]/chars.length)*chars.length > 255) {
|
|
continue // Prevent bias.
|
|
}
|
|
s += chars[b[0]%chars.length]
|
|
}
|
|
password1.type = 'text'
|
|
password2.type = 'text'
|
|
password1.value = s
|
|
password2.value = s
|
|
}),
|
|
dom('div.text',
|
|
box(yellow, 'Important: Bots will try to bruteforce your password. Connections with failed authentication attempts will be rate limited but attackers WILL find weak passwords. If your account is compromised, spammers are likely to abuse your system, spamming your address and the wider internet in your name. So please pick a random, unguessable password, preferrably at least 12 characters.'),
|
|
),
|
|
),
|
|
async function submit(e) {
|
|
e.stopPropagation()
|
|
e.preventDefault()
|
|
if (!password1.value || password1.value !== password2.value) {
|
|
window.alert('Passwords do not match.')
|
|
return
|
|
}
|
|
passwordFieldset.disabled = true
|
|
try {
|
|
await api.SetPassword(password1.value)
|
|
window.alert('Password has been changed.')
|
|
passwordForm.reset()
|
|
} catch (err) {
|
|
console.log({err})
|
|
window.alert('Error: ' + err.message)
|
|
} finally {
|
|
passwordFieldset.disabled = false
|
|
}
|
|
},
|
|
),
|
|
dom.br(),
|
|
dom.h2('Export'),
|
|
dom.p('Export all messages in all mailboxes. In maildir or mbox format, as .zip or .tgz file.'),
|
|
dom.ul(
|
|
dom.li(dom.a('mail-export-maildir.tgz', attr({href: 'mail-export-maildir.tgz'}))),
|
|
dom.li(dom.a('mail-export-maildir.zip', attr({href: 'mail-export-maildir.zip'}))),
|
|
dom.li(dom.a('mail-export-mbox.tgz', attr({href: 'mail-export-mbox.tgz'}))),
|
|
dom.li(dom.a('mail-export-mbox.zip', attr({href: '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 = () => {
|
|
return new Promise((resolve, reject) => {
|
|
// Browsers can do everything. Except show a progress bar while uploading...
|
|
let progressBox, progressPercentage, progressBar
|
|
dom._kids(importProgress,
|
|
progressBox=dom.div(
|
|
dom.div('Uploading... ', progressPercentage=dom.span()),
|
|
),
|
|
)
|
|
importProgress.style.display = ''
|
|
|
|
const xhr = new window.XMLHttpRequest()
|
|
xhr.open('POST', 'import', true)
|
|
xhr.upload.addEventListener('progress', (e) => {
|
|
if (!e.lengthComputable) {
|
|
return
|
|
}
|
|
const pct = Math.floor(100*e.loaded/e.total)
|
|
dom._kids(progressPercentage, pct+'%')
|
|
})
|
|
xhr.addEventListener('load', () => {
|
|
console.log('upload done', {xhr: xhr, status: xhr.status})
|
|
if (xhr.status !== 200) {
|
|
reject({message: 'status '+xhr.status})
|
|
return
|
|
}
|
|
let resp
|
|
try {
|
|
resp = JSON.parse(xhr.responseText)
|
|
} catch (err) {
|
|
reject({message: 'parsing resonse json: '+err.message})
|
|
return
|
|
}
|
|
resolve(resp)
|
|
})
|
|
xhr.addEventListener('error', (e) => reject({message: 'upload error', event: e}))
|
|
xhr.addEventListener('abort', (e) => reject({message: 'upload aborted', event: e}))
|
|
xhr.send(new window.FormData(importForm))
|
|
})
|
|
}
|
|
try {
|
|
const p = request()
|
|
importFieldset.disabled = true
|
|
const result = await p
|
|
|
|
try {
|
|
window.sessionStorage.setItem('ImportToken', result.ImportToken)
|
|
} catch (err) {
|
|
console.log('storing import token in session storage', {err})
|
|
// Ignore error, could be some browser security thing like private browsing.
|
|
}
|
|
|
|
await importTrack(result.ImportToken)
|
|
} catch (err) {
|
|
console.log({err})
|
|
window.alert('Error: '+err.message)
|
|
} finally {
|
|
importFieldset.disabled = false
|
|
}
|
|
},
|
|
importFieldset=dom.fieldset(
|
|
dom.div(
|
|
style({marginBottom: '1ex'}),
|
|
dom.label(
|
|
dom.div(style({marginBottom: '.5ex'}), 'File'),
|
|
mailboxFile=dom.input(attr({type: 'file', required: '', name: 'file'}), function focus() {
|
|
mailboxFileHint.style.display = ''
|
|
}),
|
|
),
|
|
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)'),
|
|
mailboxPrefix=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.button('Upload and import'),
|
|
dom.p(style({fontStyle: 'italic', marginTop: '.5ex'}), 'The file is uploaded first, then its messages are imported. 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,
|
|
)
|
|
|
|
// Try to show the progress of an earlier import session. The user may have just
|
|
// refreshed the browser.
|
|
let importToken
|
|
try {
|
|
importToken = window.sessionStorage.getItem('ImportToken')
|
|
} catch (err) {
|
|
console.log('looking up ImportToken in session storage', {err})
|
|
return
|
|
}
|
|
if (!importToken) {
|
|
return
|
|
}
|
|
importFieldset.disabled = true
|
|
dom._kids(importProgress,
|
|
dom.div(
|
|
dom.div('Reconnecting to import...'),
|
|
),
|
|
)
|
|
importProgress.style.display = ''
|
|
importTrack(importToken)
|
|
.catch((err) => {
|
|
if (window.confirm('Error reconnecting to import. Remove this import session?')) {
|
|
window.sessionStorage.removeItem('ImportToken')
|
|
dom._kids(importProgress)
|
|
importProgress.style.display = 'none'
|
|
}
|
|
})
|
|
.finally(() => {
|
|
importFieldset.disabled = false
|
|
})
|
|
}
|
|
|
|
const destination = async (name) => {
|
|
const [_, domain, destinations] = await api.Account()
|
|
let dest = destinations[name]
|
|
if (!dest) {
|
|
throw new Error('destination not found')
|
|
}
|
|
|
|
let rulesetsTbody = dom.tbody()
|
|
let rulesetsRows = []
|
|
|
|
const addRulesetsRow = (rs) => {
|
|
let headersCell = dom.td()
|
|
let headers = [] // Holds objects: {key, value, root}
|
|
const addHeader = (k, v) => {
|
|
let h = {}
|
|
h.root = dom.div(
|
|
h.key=dom.input(attr({value: k})),
|
|
' ',
|
|
h.value=dom.input(attr({value: v})),
|
|
' ',
|
|
dom.button('-', style({width: '1.5em'}), function click(e) {
|
|
h.root.remove()
|
|
headers = headers.filter(x => x !== h)
|
|
if (headers.length === 0) {
|
|
const b = dom.button('+', style({width: '1.5em'}), function click(e) {
|
|
e.target.remove()
|
|
addHeader('', '')
|
|
})
|
|
headersCell.appendChild(dom.div(style({textAlign: 'right'}), b))
|
|
}
|
|
}),
|
|
' ',
|
|
dom.button('+', style({width: '1.5em'}), function click(e) {
|
|
addHeader('', '')
|
|
}),
|
|
)
|
|
headers.push(h)
|
|
headersCell.appendChild(h.root)
|
|
}
|
|
Object.entries(rs.HeadersRegexp || {}).sort().forEach(t =>
|
|
addHeader(t[0], t[1])
|
|
)
|
|
if (Object.entries(rs.HeadersRegexp || {}).length === 0) {
|
|
const b = dom.button('+', style({width: '1.5em'}), function click(e) {
|
|
e.target.remove()
|
|
addHeader('', '')
|
|
})
|
|
headersCell.appendChild(dom.div(style({textAlign: 'right'}), b))
|
|
}
|
|
|
|
let row = {headers}
|
|
row.root=dom.tr(
|
|
dom.td(row.SMTPMailFromRegexp=dom.input(attr({value: rs.SMTPMailFromRegexp || ''}))),
|
|
dom.td(row.VerifiedDomain=dom.input(attr({value: rs.VerifiedDomain || ''}))),
|
|
headersCell,
|
|
dom.td(row.ListAllowDomain=dom.input(attr({value: rs.ListAllowDomain || ''}))),
|
|
dom.td(row.Mailbox=dom.input(attr({value: rs.Mailbox || ''}))),
|
|
dom.td(
|
|
dom.button('Remove ruleset', function click(e) {
|
|
row.root.remove()
|
|
rulesetsRows = rulesetsRows.filter(e => e !== row)
|
|
}),
|
|
),
|
|
)
|
|
rulesetsRows.push(row)
|
|
rulesetsTbody.appendChild(row.root)
|
|
}
|
|
|
|
(dest.Rulesets || []).forEach(rs => {
|
|
addRulesetsRow(rs)
|
|
})
|
|
|
|
let defaultMailbox
|
|
let fullName
|
|
let saveButton
|
|
|
|
const page = document.getElementById('page')
|
|
dom._kids(page,
|
|
crumbs(
|
|
crumblink('Mox Account', '#'),
|
|
'Destination ' + name,
|
|
),
|
|
dom.div(
|
|
dom.span('Default mailbox', attr({title: 'Default mailbox where email for this recipient is delivered to if it does not match any ruleset. Default is Inbox.'})),
|
|
dom.br(),
|
|
defaultMailbox=dom.input(attr({value: dest.Mailbox, placeholder: 'Inbox'})),
|
|
),
|
|
dom.br(),
|
|
dom.div(
|
|
dom.span('Full name', attr({title: 'Name to use in From header when composing messages. If not set, the account default full name is used.'})),
|
|
dom.br(),
|
|
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('The "List allow domain" does not affect the matching, but skips the regular spam checks if one of the verified domains is a (sub)domain of the domain mentioned here.'),
|
|
dom.table(
|
|
dom.thead(
|
|
dom.tr(
|
|
dom.th('SMTP "MAIL FROM" regexp', attr({title: 'Matches if this regular expression matches (a substring of) the SMTP MAIL FROM address (not the message From-header). E.g. user@example.org.'})),
|
|
dom.th('Verified domain', attr({title: 'Matches if this domain matches an SPF- and/or DKIM-verified (sub)domain.'})),
|
|
dom.th('Headers regexp', attr({title: 'Matches if these header field/value regular expressions all match (substrings of) the message headers. Header fields and valuees are converted to lower case before matching. Whitespace is trimmed from the value before matching. A header field can occur multiple times in a message, only one instance has to match. For mailing lists, you could match on ^list-id$ with the value typically the mailing list address in angled brackets with @ replaced with a dot, e.g. <name\\.lists\\.example\\.org>.'})),
|
|
dom.th('List allow domain', attr({title: "Influence the spam filtering, this does not change whether this ruleset applies to a message. If this domain matches an SPF- and/or DKIM-verified (sub)domain, the message is accepted without further spam checks, such as a junk filter or DMARC reject evaluation. DMARC rejects should not apply for mailing lists that are not configured to rewrite the From-header of messages that don't have a passing DKIM signature of the From-domain. Otherwise, by rejecting messages, you may be automatically unsubscribed from the mailing list. The assumption is that mailing lists do their own spam filtering/moderation."})),
|
|
dom.th('Mailbox', attr({title: 'Mailbox to deliver to if this ruleset matches.'})),
|
|
dom.th('Action'),
|
|
)
|
|
),
|
|
rulesetsTbody,
|
|
dom.tfoot(
|
|
dom.tr(
|
|
dom.td(attr({colspan: '5'})),
|
|
dom.td(
|
|
dom.button('Add ruleset', function click(e) {
|
|
addRulesetsRow({})
|
|
}),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
dom.br(),
|
|
saveButton=dom.button('Save', async function click(e) {
|
|
saveButton.disabled = true
|
|
try {
|
|
const newDest = {
|
|
Mailbox: defaultMailbox.value,
|
|
FullName: fullName.value,
|
|
Rulesets: rulesetsRows.map(row => {
|
|
return {
|
|
SMTPMailFromRegexp: row.SMTPMailFromRegexp.value,
|
|
VerifiedDomain: row.VerifiedDomain.value,
|
|
HeadersRegexp: Object.fromEntries(row.headers.map(h => [h.key.value, h.value.value])),
|
|
ListAllowDomain: row.ListAllowDomain.value,
|
|
Mailbox: row.Mailbox.value,
|
|
}
|
|
}),
|
|
}
|
|
page.classList.add('loading')
|
|
await api.DestinationSave(name, dest, newDest)
|
|
dest = newDest // Set new dest, for if user edits again. Without this, they would get an error that the config has been modified.
|
|
} catch (err) {
|
|
console.log({err})
|
|
window.alert('Error: '+err.message)
|
|
return
|
|
} finally {
|
|
saveButton.disabled = false
|
|
page.classList.remove('loading')
|
|
}
|
|
}),
|
|
)
|
|
}
|
|
|
|
const init = async () => {
|
|
let curhash
|
|
|
|
const page = document.getElementById('page')
|
|
|
|
const hashChange = async () => {
|
|
if (curhash === window.location.hash) {
|
|
return
|
|
}
|
|
let h = decodeURIComponent(window.location.hash)
|
|
if (h !== '' && h.substring(0, 1) == '#') {
|
|
h = h.substring(1)
|
|
}
|
|
const t = h.split('/')
|
|
page.classList.add('loading')
|
|
try {
|
|
if (h === '') {
|
|
await index()
|
|
} else if (t[0] === 'destinations' && t.length === 2) {
|
|
await destination(t[1])
|
|
} else {
|
|
dom._kids(page, 'page not found')
|
|
}
|
|
} catch (err) {
|
|
console.log({err})
|
|
window.alert('Error: ' + err.message)
|
|
window.location.hash = curhash
|
|
curhash = window.location.hash
|
|
return
|
|
}
|
|
curhash = window.location.hash
|
|
page.classList.remove('loading')
|
|
}
|
|
window.addEventListener('hashchange', hashChange)
|
|
hashChange()
|
|
}
|
|
|
|
window.addEventListener('load', init)
|
|
</script>
|
|
</body>
|
|
</html>
|