mirror of
https://github.com/wekan/wekan.git
synced 2026-11-24 09:59:47 -05:00
An audit of every environment variable the code reads found 30 that are new since v12.00. Eleven were already Admin Panel settings and on every platform the release workflows build. Of the rest: Now Admin Panel settings, through models/lib/authConfigCatalog.js (a value there wins, an empty field falls back to the variable): - Email to card limits, beside its own Admin Panel settings: INBOUND_IMAP_POLL_SECONDS, INBOUND_EMAIL_PER_ADDRESS_PER_HOUR, INBOUND_EMAIL_MAX_BYTES, INBOUND_EMAIL_MAX_ATTACHMENT_BYTES and EMAIL_VIEW_SENDS_PER_HOUR. They were module-level constants, read before the Admin Panel values loaded; they are read when used now. createRateLimiter takes a limit function, and a changed poll interval restarts the IMAP poller. - ACCOUNTS_COOKIE_REFRESH_RATE_LIMIT in People / Login, like the login expiry beside it, applied from the next start. - Windows SSO (WINDOWS_SSO_ENABLED, _DOMAINS, _ACTIVE_DIRECTORY, _MERGE_EXISTING_USERS) in People / Login. It was already read through authEnv but had no form. Being Windows-only, its catalog section names start-wekan.bat as its one platform. Listed on every platform (Dockerfile, the docker-compose files, start-wekan.sh and .bat, the snap config and help), where none of these had been: the variables above, INBOUND_EMAIL_WEBHOOK_SECRET (its own Admin Panel page already has it), and the per-process switches that stay environment only - INBOUND_IMAP_DISABLED (one pod of a multi-pod deployment), WEKAN_DISK_MONITOR, WEKAN_DISK_WATCH_PATHS, WEKAN_RAM_MONITOR and WEKAN_IMPORT_RUN_STALE_MS. Left unlisted on purpose: NEXTCLOUD_EXAPP, NEXTCLOUD_URL and WEKAN_NEXTCLOUD_PROXY_KEY (set by Nextcloud's AppAPI), SANDSTORM_MAILDIR (set by Sandstorm). DEFAULT_AVATAR_URL keeps no Admin Panel UI, as decided in #824. tests/envVarCoverage.test.cjs keeps it so. It fails for a variable that is in no Admin Panel catalog, OWN_PANE or ENV_ONLY with its reason; the variables read before v12.00 are a frozen LEGACY list that can only shrink. An environment-only or own-page setting a user sets must be on every platform, and stale entries fail. tests/authConfigCatalog.test.cjs honours a section's platform list. tests/adminPanelNewSettings.test.cjs pins the reads and the forms. tests/cookieRefreshRateLimit.test.cjs's guard now expects the Admin Panel value, and says why. tests/playwright/specs/admin-new-env-settings.e2e.js opens the forms. Thanks to xet7 !
276 lines
12 KiB
JavaScript
276 lines
12 KiB
JavaScript
'use strict';
|
|
|
|
// Email to card (#794, #3948): an email sent to a member's personal board
|
|
// address becomes a card on that board, the way Trello's email-to-board does.
|
|
//
|
|
// Pure (no Meteor, no Mongo), so it is shared by the client (the settings UI)
|
|
// and the server (the inbound paths), and tested with plain Node
|
|
// (tests/emailToCard.test.cjs).
|
|
//
|
|
// Where it is configured - Notification Settings, at three levels:
|
|
// - Admin Panel: whether inbound email is on at all, the address domain, and
|
|
// the mail servers (IMAP accounts) with their passwords - server-side only.
|
|
// The admin switch is a hard gate: nothing below can turn on what the
|
|
// administrator has off.
|
|
// - Board Settings: whether this board accepts email, which list and
|
|
// swimlane new cards go to, and which parts of an email are used.
|
|
// - Member Settings: whether the member's own addresses work, and the parts
|
|
// they want (overriding the board's).
|
|
// Member over board over admin, as for the other notification settings
|
|
// (models/lib/notificationSettings.js); an unset value falls through.
|
|
|
|
// What an email can contribute to a card. `title` is always the subject.
|
|
const EMAIL_PARTS = Object.freeze({
|
|
// The card description: 'text' (the plain-text body, or the HTML body as
|
|
// text) or 'none'.
|
|
description: Object.freeze(['text', 'none']),
|
|
// Drop the quoted earlier messages ("On ... wrote:", "> ...").
|
|
stripQuoted: 'boolean',
|
|
// Attach the email's attachments to the card.
|
|
attachments: 'boolean',
|
|
// Start the description with "From: Name <address>" - the card's author is
|
|
// the address's member, so this keeps who actually wrote a forwarded email.
|
|
senderLine: 'boolean',
|
|
});
|
|
|
|
const DEFAULT_PARTS = Object.freeze({
|
|
description: 'text',
|
|
stripQuoted: true,
|
|
attachments: true,
|
|
senderLine: true,
|
|
});
|
|
|
|
const MAX_TITLE = 255;
|
|
const MAX_DESCRIPTION = 100000;
|
|
|
|
function validPart(name, value) {
|
|
const kind = EMAIL_PARTS[name];
|
|
if (Array.isArray(kind)) return kind.includes(value);
|
|
return kind === 'boolean' && (value === true || value === false);
|
|
}
|
|
|
|
// Only known parts with valid values; anything else is dropped, so a stored
|
|
// or submitted object can never add a field the resolver does not know.
|
|
function cleanParts(parts) {
|
|
const out = {};
|
|
if (!parts || typeof parts !== 'object') return out;
|
|
for (const name of Object.keys(EMAIL_PARTS)) {
|
|
if (validPart(name, parts[name])) out[name] = parts[name];
|
|
}
|
|
return out;
|
|
}
|
|
|
|
const bool = value => (value === true || value === false ? value : undefined);
|
|
|
|
// The effective settings for one member on one board.
|
|
// admin { enabled, domain } Settings.inboundMail
|
|
// board { enabled, listId, swimlaneId, parts } board.emailToCard
|
|
// member { enabled, parts } user.profile.emailToCard
|
|
function resolveEmailToCard({ admin = {}, board = {}, member = {} } = {}) {
|
|
const adminOn = bool(admin.enabled) === true && typeof admin.domain === 'string' && admin.domain.trim() !== '';
|
|
// Off on a board until its admin turns it on; on for a member unless they
|
|
// turn their own addresses off.
|
|
const boardOn = bool(board.enabled) === true;
|
|
const memberOn = bool(member.enabled) !== false;
|
|
return {
|
|
enabled: adminOn && boardOn && memberOn,
|
|
reason: !adminOn ? 'admin-off' : !boardOn ? 'board-off' : !memberOn ? 'member-off' : null,
|
|
listId: typeof board.listId === 'string' ? board.listId : null,
|
|
swimlaneId: typeof board.swimlaneId === 'string' ? board.swimlaneId : null,
|
|
parts: { ...DEFAULT_PARTS, ...cleanParts(board.parts), ...cleanParts(member.parts) },
|
|
};
|
|
}
|
|
|
|
// "Name <address>" or "address", for the sender line.
|
|
function formatSender(from) {
|
|
if (!from || !from.address) return '';
|
|
return from.name ? `${from.name} <${from.address}>` : from.address;
|
|
}
|
|
|
|
// The HTML body as plain text, when an email has no text part: tags removed,
|
|
// block ends kept as line breaks, the common entities decoded. Good enough for
|
|
// a card description; nothing here is ever rendered as HTML.
|
|
// Tags are removed by ONE pass over the characters, not by regular
|
|
// expressions: a scanner never puts back together what it took apart, so text
|
|
// around a removed tag cannot become a tag ("<scr<script>ipt>"), and a
|
|
// <script>, <style> or <head> element goes with everything inside it. CodeQL
|
|
// alerts #570, #571, #581 and #582 were the regular-expression versions.
|
|
const SKIP_CONTENT = new Set(['script', 'style', 'head']);
|
|
const LINE_ENDS = new Set(['br', '/p', '/div', '/li', '/tr', '/h1', '/h2', '/h3', '/h4', '/h5', '/h6', '/blockquote']);
|
|
|
|
function isNameChar(ch) {
|
|
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9');
|
|
}
|
|
|
|
function stripTags(html) {
|
|
const out = [];
|
|
let i = 0;
|
|
while (i < html.length) {
|
|
const ch = html[i];
|
|
const next = html[i + 1] || '';
|
|
const isLetter = (next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z');
|
|
// "<" that does not start a tag ("2 < 3") is text, as in a browser - but
|
|
// not one right before another "<", which with the tag after it removed
|
|
// would read as a tag again ("<<b>script>" -> "<script>").
|
|
if (ch !== '<' || !(isLetter || next === '/' || next === '!' || next === '?')) {
|
|
if (!(ch === '<' && next === '<')) out.push(ch);
|
|
i += 1;
|
|
continue;
|
|
}
|
|
let j = i + 1;
|
|
let name = html[j] === '/' ? '/' : '';
|
|
if (name) j += 1;
|
|
while (j < html.length && isNameChar(html[j])) name += html[j++];
|
|
name = name.toLowerCase();
|
|
const close = html.indexOf('>', j);
|
|
if (close < 0) break; // an unfinished tag: the rest is part of it
|
|
i = close + 1;
|
|
if (SKIP_CONTENT.has(name)) {
|
|
// Everything up to the element's end tag, or to the end if it has none.
|
|
const end = html.toLowerCase().indexOf(`</${name}`, i);
|
|
const endClose = end < 0 ? -1 : html.indexOf('>', end);
|
|
i = endClose < 0 ? html.length : endClose + 1;
|
|
} else if (LINE_ENDS.has(name)) {
|
|
out.push('\n');
|
|
}
|
|
}
|
|
return out.join('');
|
|
}
|
|
|
|
function htmlToText(html) {
|
|
return stripTags(String(html || ''))
|
|
.replace(/ /g, ' ').replace(/</g, '<').replace(/>/g, '>')
|
|
.replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&')
|
|
.replace(/\n{3,}/g, '\n\n')
|
|
.trim();
|
|
}
|
|
|
|
// Card fields from one parsed email, by the resolved parts.
|
|
// message { subject, text, html, from: { name, address }, attachments }
|
|
// options.stripQuoted the quote stripper (server/lib/inboundEmailQuoteStrip.js),
|
|
// passed in so this module stays dependency-free
|
|
// Returns { title, description, attachments }.
|
|
function cardFromEmail(message = {}, parts = DEFAULT_PARTS, { stripQuoted = text => text } = {}) {
|
|
const resolved = { ...DEFAULT_PARTS, ...cleanParts(parts) };
|
|
let body = typeof message.text === 'string' && message.text.trim()
|
|
? message.text : htmlToText(message.html);
|
|
body = String(body || '').replace(/\r\n?/g, '\n');
|
|
if (resolved.stripQuoted) body = stripQuoted(body) || '';
|
|
body = body.trim();
|
|
|
|
const firstLine = body.split('\n').find(line => line.trim()) || '';
|
|
const subject = String(message.subject || '').replace(/\s+/g, ' ').trim();
|
|
const title = (subject || firstLine.trim() || 'Email').slice(0, MAX_TITLE);
|
|
|
|
const lines = [];
|
|
if (resolved.senderLine && formatSender(message.from)) lines.push(`From: ${formatSender(message.from)}`);
|
|
if (resolved.description === 'text' && body) {
|
|
if (lines.length) lines.push('');
|
|
lines.push(body);
|
|
}
|
|
const description = lines.join('\n').slice(0, MAX_DESCRIPTION);
|
|
|
|
const attachments = resolved.attachments && Array.isArray(message.attachments)
|
|
? message.attachments.filter(a => a && a.content && a.filename) : [];
|
|
return { title, description, attachments };
|
|
}
|
|
|
|
// --- Admin Panel: the inbound side, servers and passwords ------------------
|
|
//
|
|
// Settings.inboundMail:
|
|
// enabled, domain the hard gate and the board-address domain
|
|
// webhookSecret / webhookSecretSet the provider webhook's shared secret
|
|
// accounts: [{ id, label, host, port, secure, username, mailbox,
|
|
// after: 'seen'|'delete', enabled }] IMAP mailboxes polled
|
|
// passwords: { <id>: password } / passwordSet: { <id>: true }
|
|
// The secret and the passwords are written only when one is typed, and never
|
|
// leave the server (inboundMailAdminView).
|
|
|
|
const HOST = /^(?=.{1,253}$)([A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
|
|
const ACCOUNT_ID = /^[A-Za-z0-9_-]{1,40}$/;
|
|
const MAX_ACCOUNTS = 20;
|
|
|
|
const isHost = value => typeof value === 'string' && HOST.test(value);
|
|
|
|
function cleanAccount(account) {
|
|
if (!account || typeof account !== 'object' || !ACCOUNT_ID.test(String(account.id || ''))) return null;
|
|
const host = String(account.host || '').trim().toLowerCase();
|
|
if (!isHost(host)) return null;
|
|
const port = Number(account.port);
|
|
return {
|
|
id: String(account.id),
|
|
label: String(account.label || '').trim().slice(0, 100),
|
|
host,
|
|
port: Number.isInteger(port) && port > 0 && port < 65536 ? port : (account.secure === false ? 143 : 993),
|
|
secure: account.secure !== false,
|
|
username: String(account.username || '').trim().slice(0, 320),
|
|
mailbox: String(account.mailbox || 'INBOX').trim().slice(0, 200) || 'INBOX',
|
|
after: account.after === 'delete' ? 'delete' : 'seen',
|
|
enabled: account.enabled === true,
|
|
};
|
|
}
|
|
|
|
// The non-secret part of a submitted admin form. Throws a string error code
|
|
// for what cannot be saved.
|
|
function cleanInboundAdmin(input = {}) {
|
|
const domain = String(input.domain || '').trim().toLowerCase();
|
|
if (domain && !isHost(domain)) throw new Error('inbound-domain-invalid');
|
|
if (input.enabled === true && !domain) throw new Error('inbound-domain-required');
|
|
const accounts = [];
|
|
for (const raw of Array.isArray(input.accounts) ? input.accounts.slice(0, MAX_ACCOUNTS) : []) {
|
|
const account = cleanAccount(raw);
|
|
if (!account) throw new Error('inbound-account-invalid');
|
|
if (accounts.some(a => a.id === account.id)) throw new Error('inbound-account-invalid');
|
|
accounts.push(account);
|
|
}
|
|
return { enabled: input.enabled === true, domain, accounts };
|
|
}
|
|
|
|
// What the Admin Panel form is shown: everything but the secrets.
|
|
function inboundMailAdminView(inboundMail = {}) {
|
|
const accounts = Array.isArray(inboundMail.accounts) ? inboundMail.accounts : [];
|
|
const passwordSet = inboundMail.passwordSet || {};
|
|
return {
|
|
enabled: inboundMail.enabled === true,
|
|
domain: typeof inboundMail.domain === 'string' ? inboundMail.domain : '',
|
|
webhookSecretSet: inboundMail.webhookSecretSet === true,
|
|
accounts: accounts.map(a => ({ ...a, passwordSet: passwordSet[a.id] === true })),
|
|
sandstormBoard: inboundMail.sandstormBoard && inboundMail.sandstormBoard.boardId
|
|
? { boardId: inboundMail.sandstormBoard.boardId } : null,
|
|
};
|
|
}
|
|
|
|
// A sliding-window limit per key (a board address): `limit` emails per
|
|
// `windowMs`. In memory, per server process - a flood is stopped where it
|
|
// arrives, and a restart forgetting the window costs at most one more window.
|
|
//
|
|
// `limit` is a number, or a function read at every call, so a limit set in
|
|
// Admin Panel applies at once (models/lib/authConfigCatalog.js).
|
|
function createRateLimiter({ limit = 30, windowMs = 60 * 60 * 1000, now = Date.now } = {}) {
|
|
const hits = new Map();
|
|
return function allow(key) {
|
|
const t = now();
|
|
const max = typeof limit === 'function' ? limit() : limit;
|
|
const recent = (hits.get(key) || []).filter(at => t - at < windowMs);
|
|
if (recent.length >= max) { hits.set(key, recent); return false; }
|
|
recent.push(t);
|
|
hits.set(key, recent);
|
|
if (hits.size > 10000) hits.delete(hits.keys().next().value);
|
|
return true;
|
|
};
|
|
}
|
|
|
|
module.exports = {
|
|
cleanInboundAdmin,
|
|
inboundMailAdminView,
|
|
createRateLimiter,
|
|
EMAIL_PARTS,
|
|
DEFAULT_PARTS,
|
|
MAX_TITLE,
|
|
cleanParts,
|
|
resolveEmailToCard,
|
|
cardFromEmail,
|
|
htmlToText,
|
|
formatSender,
|
|
};
|