'; });
else box.innerHTML = '';
if (cfg.mailAdmin) mailAdminCard();
}
/** Choose a provider; Outlook.com signs in on Microsoft's page, Gmail and iCloud take an app password. */
function mailAddAccount(st) {
const choices = [['gmail', 'Gmail', 'App password'], ['icloud', 'iCloud Mail', 'App-specific password'], ...(st && st.outlook ? [['outlook', 'Outlook.com', 'Sign in with Microsoft']] : [])];
const el = openSheet('Add a mail account', '', `
${choices.map(([k, l, s]) => ``).join('')}
`);
el.querySelector('#sx').onclick = closeSheet;
el.querySelectorAll('[data-p]').forEach(b => b.onclick = async () => {
const k = b.dataset.p;
if (k === 'outlook') { try { const r = await jfetch('/api/mail/connect'); location.href = r.url; } catch (e) { toast(e.message); } return; }
mailPasswordForm(k);
});
}
function mailPasswordForm(type) {
const g = type === 'gmail';
const el = openSheet('Add ' + (g ? 'Gmail' : 'iCloud Mail'), '', ``);
el.querySelector('#sx').onclick = closeSheet;
el.querySelector('#paf').onsubmit = async e => {
e.preventDefault(); const btn = el.querySelector('#pab'); btn.disabled = true; btn.textContent = 'Checking…'; el.querySelector('#pax').textContent = '';
try { await jfetch('/api/mail/accounts', { method: 'POST', body: JSON.stringify({ type, address: el.querySelector('#pae').value, password: el.querySelector('#pap').value }) }); closeSheet(); toast('Connected'); mail.st = null; mail.items = []; mail.folders = []; mail.acct = ''; await mailPoll(); if (location.hash.startsWith('#/mail')) route(); else if ($('#mailst')) mailSettings(); }
catch (err) { btn.disabled = false; btn.textContent = 'Connect'; el.querySelector('#pax').textContent = err.message; }
};
setTimeout(() => el.querySelector('#pae').focus(), 60);
}
/** Admin: the Microsoft app behind Mail (client ID, secret, expiry), with the redirect address to register and a test button. */
async function mailAdminCard() {
let host = $('#mailadm');
if (!host) { $('#sec-mail').insertAdjacentHTML('beforeend', ''); host = $('#mailadm'); }
let a; try { a = await jfetch('/api/mail/admin'); } catch (e) { host.innerHTML = `
The client secret expired ${-a.days} day${a.days === -1 ? '' : 's'} ago. Mail cannot connect until you replace it.
`
: a.days <= 30 ? `
The client secret expires in ${a.days} day${a.days === 1 ? '' : 's'} (${esc(a.secretExpires)}). Make a new one in Microsoft Entra and paste it below.
` : '';
host.innerHTML = `
Microsoft app (admin)
Mail uses a free Microsoft app registration. ${a.source === 'env' ? 'This server gets it from its environment settings (MS_CLIENT_ID), so change it there.' : a.source === 'app' ? 'Saved here, encrypted on your server.' : 'Not set up yet: follow the steps below, then paste the values here.'}
${warn}
${a.verifiedAt ? '✓ Last successful connection: ' + esc(new Date(a.verifiedAt).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' })) : a.clientId ? 'Not proven yet. Open the Mail tab and press Connect: Microsoft checks everything then.' : ''}
It must match exactly, and be https (set PUBLIC_URL on the server if this shows the wrong address).
${a.source === 'env' ? `
Client secret: ${a.hasSecret ? 'set' : 'not set'}
` : ``}
How to register the app (about 5 minutes)
Go to entra.microsoft.com and sign in with any Microsoft account. Accept the free "Default Directory" if asked.
Entra ID → App registrations → New registration. Name it NE Hub, choose Personal Microsoft accounts only, set the redirect platform to Web, paste the redirect address above, press Register.
Copy the Application (client) ID from the Overview page into the first box above.
API permissions → Add a permission → Microsoft Graph → Delegated: Mail.ReadWrite, Mail.Send, User.Read, offline_access.
Certificates & secrets → New client secret (24 months). Copy its Value now (shown once) into the secret box, and set the expiry date.
Press Save, then open the Mail tab and press Connect. Microsoft checks the ID, secret and redirect address at that moment; if something is wrong it says what.
`;
$('#mcopy').onclick = async () => { try { await navigator.clipboard.writeText(a.redirect); toast('Copied'); } catch { $('#mredir').select(); toast('Press Ctrl/Cmd-C to copy'); } };
const f = $('#madm'); if (!f) return;
const res = (t, good) => { const el = $('#mres'); el.textContent = t; el.style.color = good ? 'var(--accent)' : ''; };
const save = async extra => jfetch('/api/mail/admin', { method: 'POST', body: JSON.stringify({ clientId: $('#mcid').value, clientSecret: $('#mcsec').value, secretExpires: $('#mcexp').value, ...(extra || {}) }) });
f.onsubmit = async e => { e.preventDefault(); res(''); try { await save(); const r = await jfetch('/api/config'); cfg = { ...cfg, ...r }; toast('Saved. Now open the Mail tab and press Connect.'); renderNav(); mailSettings(); } catch (err) { res(err.message); } };
if ($('#mclear')) $('#mclear').onclick = () => confirmSheet('Remove the Microsoft app settings?', 'Mail stops working for everyone until you set it up again. Connected mailboxes stay saved.', 'Remove', async () => { try { await jfetch('/api/mail/admin', { method: 'POST', body: JSON.stringify({ clientId: '', clearSecret: true, secretExpires: '' }) }); const c = await jfetch('/api/config'); cfg = { ...cfg, ...c }; renderNav(); mailSettings(); } catch (e) { toast(e.message); } });
}
// ---- the tab
async function viewMail(args = []) {
const v = $('#view');
if (!cfg.mail) { v.innerHTML = '
Mail
Mail is not available to you.
'; return; }
v.innerHTML = '
Mail
Loading…
';
let st; try { st = await jfetch('/api/mail/status'); } catch (e) { v.innerHTML = `
Read and send mail from your own accounts right here, all in one place. Passwords are checked with the provider and kept encrypted on your server; Outlook.com signs in on Microsoft's own page.
${st.expired ? '
Microsoft signed you out of mail. Connect again to continue.
' : ''}
${choices.map(([k, l, s, c]) => ``).join('')}
${st.outlook ? '' : '
Outlook.com needs a one-time Microsoft app set up by an admin (Settings → Microsoft app).