mirror of
https://github.com/mjl-/mox.git
synced 2025-07-12 14:24:37 +03:00
replace http basic auth for web interfaces with session cookie & csrf-based auth
the http basic auth we had was very simple to reason about, and to implement. but it has a major downside: there is no way to logout, browsers keep sending credentials. ideally, browsers themselves would show a button to stop sending credentials. a related downside: the http auth mechanism doesn't indicate for which server paths the credentials are. another downside: the original password is sent to the server with each request. though sending original passwords to web servers seems to be considered normal. our new approach uses session cookies, along with csrf values when we can. the sessions are server-side managed, automatically extended on each use. this makes it easy to invalidate sessions and keeps the frontend simpler (than with long- vs short-term sessions and refreshing). the cookies are httponly, samesite=strict, scoped to the path of the web interface. cookies are set "secure" when set over https. the cookie is set by a successful call to Login. a call to Logout invalidates a session. changing a password invalidates all sessions for a user, but keeps the session with which the password was changed alive. the csrf value is also random, and associated with the session cookie. the csrf must be sent as header for api calls, or as parameter for direct form posts (where we cannot set a custom header). rest-like calls made directly by the browser, e.g. for images, don't have a csrf protection. the csrf value is returned by the Login api call and stored in localstorage. api calls without credentials return code "user:noAuth", and with bad credentials return "user:badAuth". the api client recognizes this and triggers a login. after a login, all auth-failed api calls are automatically retried. only for "user:badAuth" is an error message displayed in the login form (e.g. session expired). in an ideal world, browsers would take care of most session management. a server would indicate authentication is needed (like http basic auth), and the browsers uses trusted ui to request credentials for the server & path. the browser could use safer mechanism than sending original passwords to the server, such as scram, along with a standard way to create sessions. for now, web developers have to do authentication themselves: from showing the login prompt, ensuring the right session/csrf cookies/localstorage/headers/etc are sent with each request. webauthn is a newer way to do authentication, perhaps we'll implement it in the future. though hardware tokens aren't an attractive option for many users, and it may be overkill as long as we still do old-fashioned authentication in smtp & imap where passwords can be sent to the server. for issue #58
This commit is contained in:
@ -107,6 +107,7 @@ const zindexes = {
|
||||
popover: '5',
|
||||
attachments: '5',
|
||||
shortcut: '6',
|
||||
login: '7',
|
||||
}
|
||||
|
||||
// From HTML.
|
||||
@ -230,7 +231,89 @@ let rejectsMailbox: string = ''
|
||||
// Last known server version. For asking to reload.
|
||||
let lastServerVersion: string = ''
|
||||
|
||||
const client = new api.Client()
|
||||
const login = async (reason: string) => {
|
||||
return new Promise<string>((resolve: (v: string) => void, _) => {
|
||||
const origFocus = document.activeElement
|
||||
let reasonElem: HTMLElement
|
||||
let fieldset: HTMLFieldSetElement
|
||||
let username: HTMLInputElement
|
||||
let password: HTMLInputElement
|
||||
const root = dom.div(
|
||||
style({position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, backgroundColor: '#eee', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: zindexes.login, animation: 'fadein .15s ease-in'}),
|
||||
dom.div(
|
||||
reasonElem=reason ? dom.div(style({marginBottom: '2ex', textAlign: 'center'}), reason) : dom.div(),
|
||||
dom.div(
|
||||
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', marginBottom: '20vh'}),
|
||||
dom.form(
|
||||
async function submit(e: SubmitEvent) {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
|
||||
reasonElem.remove()
|
||||
|
||||
try {
|
||||
fieldset.disabled = true
|
||||
const loginToken = await client.LoginPrep()
|
||||
const token = await client.Login(loginToken, username.value, password.value)
|
||||
try {
|
||||
window.localStorage.setItem('webmailcsrftoken', token)
|
||||
} catch (err) {
|
||||
console.log('saving csrf token in localStorage', err)
|
||||
}
|
||||
root.remove()
|
||||
if (origFocus && origFocus instanceof HTMLElement && origFocus.parentNode) {
|
||||
origFocus.focus()
|
||||
}
|
||||
resolve(token)
|
||||
} catch (err) {
|
||||
console.log('login error', err)
|
||||
window.alert('Error: ' + errmsg(err))
|
||||
} finally {
|
||||
fieldset.disabled = false
|
||||
}
|
||||
},
|
||||
fieldset=dom.fieldset(
|
||||
dom.h1('Mail'),
|
||||
dom.label(
|
||||
style({display: 'block', marginBottom: '2ex'}),
|
||||
dom.div('Email address', style({marginBottom: '.5ex'})),
|
||||
username=dom.input(attr.required(''), attr.placeholder('jane@example.org')),
|
||||
),
|
||||
dom.label(
|
||||
style({display: 'block', marginBottom: '2ex'}),
|
||||
dom.div('Password', style({marginBottom: '.5ex'})),
|
||||
password=dom.input(attr.type('password'), attr.required('')),
|
||||
),
|
||||
dom.div(
|
||||
style({textAlign: 'center'}),
|
||||
dom.submitbutton('Login'),
|
||||
),
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
document.body.appendChild(root)
|
||||
username.focus()
|
||||
})
|
||||
}
|
||||
|
||||
const localStorageGet = (k: string): string | null => {
|
||||
try {
|
||||
return window.localStorage.getItem(k)
|
||||
} catch (err) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const localStorageRemove = (k: string) => {
|
||||
try {
|
||||
return window.localStorage.removeItem(k)
|
||||
} catch (err) {
|
||||
}
|
||||
}
|
||||
|
||||
const client = new api.Client().withOptions({csrfHeader: 'x-mox-csrf', login: login}).withAuthToken(localStorageGet('webmailcsrftoken') || '')
|
||||
|
||||
// Link returns a clickable link with rel="noopener noreferrer".
|
||||
const link = (href: string, anchorOpt?: string): HTMLElement => dom.a(attr.href(href), attr.rel('noopener noreferrer'), attr.target('_blank'), anchorOpt || href)
|
||||
@ -5350,6 +5433,7 @@ type listMailboxes = () => api.Mailbox[]
|
||||
const init = async () => {
|
||||
let connectionElem: HTMLElement // SSE connection status/error. Empty when connected.
|
||||
let layoutElem: HTMLSelectElement // Select dropdown for layout.
|
||||
let loginAddressElem: HTMLElement
|
||||
|
||||
let msglistscrollElem: HTMLElement
|
||||
let queryactivityElem: HTMLElement // We show ... when a query is active and data is forthcoming.
|
||||
@ -5915,7 +5999,18 @@ const init = async () => {
|
||||
' ',
|
||||
dom.clickbutton('Help', attr.title('Show popup with basic usage information and a keyboard shortcuts.'), clickCmd(cmdHelp, shortcuts)),
|
||||
' ',
|
||||
link('https://github.com/mjl-/mox', 'mox'),
|
||||
loginAddressElem=dom.span(),
|
||||
' ',
|
||||
dom.clickbutton('Logout', attr.title('Logout, invalidating this session.'), async function click(e: MouseEvent) {
|
||||
await withStatus('Logging out', client.Logout(), e.target! as HTMLButtonElement)
|
||||
localStorageRemove('webmailcsrftoken')
|
||||
if (eventSource) {
|
||||
eventSource.close()
|
||||
eventSource = null
|
||||
}
|
||||
// Reload so all state is cleared from memory.
|
||||
window.location.reload()
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
@ -6354,6 +6449,7 @@ const init = async () => {
|
||||
connecting = false
|
||||
sseID = start.SSEID
|
||||
loginAddress = start.LoginAddress
|
||||
dom._kids(loginAddressElem, loginAddress.User + '@' + (loginAddress.Domain.Unicode || loginAddress.Domain.ASCII))
|
||||
const loginAddr = formatEmailASCII(loginAddress)
|
||||
accountAddresses = start.Addresses || []
|
||||
accountAddresses.sort((a, b) => {
|
||||
|
Reference in New Issue
Block a user