Filters on a shared mailbox: its own rules, sort-only for members #156
No files matched your search
@@ -296,6 +296,9 @@ function AuthedApp() {
|
||||
void useCalendar.getState().init();
|
||||
void useContacts.getState().init();
|
||||
void useFiles.getState().init();
|
||||
// And a shared mailbox's filters, which sort its mail rather than the
|
||||
// reader's (#155); a locked account keeps the reader's own.
|
||||
void useSieve.getState().init();
|
||||
if (!viewing) return;
|
||||
const poll = window.setInterval(() => {
|
||||
if (document.visibilityState === "visible") {
|
||||
|
||||
@@ -74,6 +74,15 @@ export function hasAdministration(perms: Permissions): boolean {
|
||||
return adminSections(perms).length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the server treats the account as an administrator when it acts in
|
||||
* another account, as it does for a shared mailbox's filters. The mail server
|
||||
* asks for `impersonate` there, not for any of the directory permissions.
|
||||
*/
|
||||
export function actsAsAdministrator(perms: Permissions): boolean {
|
||||
return perms.has("impersonate");
|
||||
}
|
||||
|
||||
/**
|
||||
* What an administrator holds, at the least: Stalwart's built-in Tenant
|
||||
* Administrator role, for the parts of it that manage people and domains.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { newRule, reorderRules, rulesToSieve, sieveToRules, testToSieve, sieveString, upsertRule, type SieveRule } from "../sieve";
|
||||
import { needsAdministrator, newRule, reorderRules, rulesToSieve, sieveToRules, SORTING_ACTIONS, testToSieve, sieveString, upsertRule, type SieveRule } from "../sieve";
|
||||
|
||||
describe("sieve codec", () => {
|
||||
it("escapes strings", () => {
|
||||
@@ -55,3 +55,59 @@ describe("reordering rules", () => {
|
||||
expect(ids(list)).toEqual(["a", "b", "c", "d"]);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* #155: on a shared mailbox a member who isn't an administrator may only save
|
||||
* rules that sort. A rule an administrator saved there, one that forwards or
|
||||
* rejects, is shown read-only -- and because saving rewrites the whole script
|
||||
* from the rules, it has to come back out byte for byte when the others change.
|
||||
*/
|
||||
describe("rules only an administrator may change on a shared mailbox", () => {
|
||||
const forward: SieveRule = {
|
||||
id: "radmin",
|
||||
name: "Escalate to on-call",
|
||||
enabled: true,
|
||||
join: "anyof",
|
||||
tests: [{ type: "header", header: "subject", op: "contains", value: "outage" }],
|
||||
actions: [{ type: "redirect", address: "[email protected]", copy: true }, { type: "stop" }],
|
||||
};
|
||||
const bounce: SieveRule = { ...newRule({ id: "rreject", name: "Refuse spam" }), actions: [{ type: "reject", reason: "No thanks" }] };
|
||||
const sort = newRule({ id: "rsort", name: "Invoices", actions: [{ type: "fileinto", mailbox: "Invoices" }, { type: "markread" }] });
|
||||
|
||||
it("counts forwarding and rejecting, and nothing that only sorts", () => {
|
||||
expect(needsAdministrator(forward)).toBe(true);
|
||||
expect(needsAdministrator(bounce)).toBe(true);
|
||||
expect(needsAdministrator(sort)).toBe(false);
|
||||
for (const type of ["discard", "stop", "flag", "keep"] as const) {
|
||||
expect(needsAdministrator(newRule({ actions: [{ type }] }))).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("counts an action it doesn't know, so a newer client's rule is left alone", () => {
|
||||
const future = { ...sort, actions: [{ type: "vacation", days: 7 }] } as unknown as SieveRule;
|
||||
expect(needsAdministrator(future)).toBe(true);
|
||||
expect(SORTING_ACTIONS.has("redirect")).toBe(false);
|
||||
});
|
||||
|
||||
it("writes an administrator's rule back unchanged when the others are edited", () => {
|
||||
const script = rulesToSieve([sort, forward, bounce]);
|
||||
const blockOf = (text: string, id: string) => {
|
||||
const lines = text.split("\n");
|
||||
const at = lines.findIndex((l) => l.startsWith("# rule:") && l.includes(`"id":"${id}"`));
|
||||
const end = lines.indexOf("", at);
|
||||
return lines.slice(at, end).join("\n");
|
||||
};
|
||||
|
||||
// What a member does: edit their own rule, add one, reorder around the others.
|
||||
const parsed = sieveToRules(script)!;
|
||||
const edited = parsed.map((r) => (r.id === "rsort" ? { ...r, name: "Invoices (paid)" } : r));
|
||||
const next = rulesToSieve([...reorderRules(edited, "rsort", "rreject", true), newRule({ id: "rnew", name: "Flag the boss" })]);
|
||||
|
||||
expect(blockOf(next, "radmin")).toBe(blockOf(script, "radmin"));
|
||||
expect(blockOf(next, "rreject")).toBe(blockOf(script, "rreject"));
|
||||
expect(blockOf(next, "radmin")).toContain('redirect :copy "[email protected]";');
|
||||
// The extensions those rules need stay required.
|
||||
expect(next).toMatch(/^require \[.*"copy".*"reject".*\];$/m);
|
||||
expect(sieveToRules(next)!.find((r) => r.id === "radmin")).toEqual(forward);
|
||||
});
|
||||
});
|
||||
@@ -287,6 +287,24 @@ export function sieveToRules(script: string): SieveRule[] | null {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a member of a shared mailbox may save in its filters without an
|
||||
* administrator: actions that sort the mail and send nothing anywhere. The
|
||||
* server refuses the rest (forwarding, rejecting, automatic replies) from
|
||||
* anyone who isn't one, so the editor doesn't offer them.
|
||||
*
|
||||
* An allowlist, so an action this version doesn't know counts as one only an
|
||||
* administrator may change.
|
||||
*/
|
||||
export const SORTING_ACTIONS: ReadonlySet<SieveAction["type"]> = new Set<SieveAction["type"]>([
|
||||
"fileinto", "markread", "flag", "addflag", "setflag", "removeflag", "keep", "discard", "stop",
|
||||
]);
|
||||
|
||||
/** Whether only an administrator may change this rule on a shared mailbox. */
|
||||
export function needsAdministrator(r: SieveRule): boolean {
|
||||
return r.actions.some((a) => !SORTING_ACTIONS.has(a.type));
|
||||
}
|
||||
|
||||
export function newRule(partial: Partial<SieveRule> = {}): SieveRule {
|
||||
return {
|
||||
id: `r${Math.random().toString(36).slice(2, 9)}`,
|
||||
|
||||
@@ -1816,6 +1816,13 @@ export const catalog: Catalog = {
|
||||
"Unread in the Inbox: {count}": "Ungelesen im Posteingang: {count}",
|
||||
"Sign out of all accounts": "Von allen Konten abmelden",
|
||||
"Shared mailbox:": "Gemeinsames Postfach:",
|
||||
// Added 2026-11-25 (a shared mailbox's filters, #155): generated by AI,
|
||||
// not yet read by a native speaker.
|
||||
"Filters for {name}": "Filter für {name}",
|
||||
"You need full access to this mailbox to change its filters.": "Sie benötigen vollen Zugriff auf dieses Postfach, um seine Filter zu ändern.",
|
||||
"Rules here only apply to mail delivered to you. To sort a shared mailbox's mail, switch to it first.": "Die Regeln hier gelten nur für E-Mails, die an Sie zugestellt werden. Um die E-Mails eines gemeinsamen Postfachs zu sortieren, wechseln Sie zuerst zu diesem Postfach.",
|
||||
"Saved by an administrator; only an administrator can change it": "Von einem Administrator gespeichert; nur ein Administrator kann sie ändern",
|
||||
"Create a rule to move newsletters to a folder or flag important senders.": "Erstellen Sie eine Regel, um Newsletter in einen Ordner zu verschieben oder wichtige Absender zu markieren.",
|
||||
"New mail for {name}": "Neue E-Mail für {name}",
|
||||
"This webmail works with the inbuxa mail server, and sign-in refuses a server that doesn't offer what it needs.": "Dieses Webmail arbeitet mit dem inbuxa-Mailserver, und die Anmeldung verweigert einen Server, der nicht bietet, was es braucht.",
|
||||
"{app} test": "{app}-Test",
|
||||
|
||||
@@ -1789,6 +1789,13 @@ export const catalog: Catalog = {
|
||||
"Unread in the Inbox: {count}": "No leídos en la bandeja de entrada: {count}",
|
||||
"Sign out of all accounts": "Cerrar sesión en todas las cuentas",
|
||||
"Shared mailbox:": "Buzón compartido:",
|
||||
// Added 2026-11-25 (a shared mailbox's filters, #155): generated by AI,
|
||||
// not yet read by a native speaker.
|
||||
"Filters for {name}": "Filtros de {name}",
|
||||
"You need full access to this mailbox to change its filters.": "Necesita acceso completo a este buzón para cambiar sus filtros.",
|
||||
"Rules here only apply to mail delivered to you. To sort a shared mailbox's mail, switch to it first.": "Estas reglas solo se aplican al correo que se le entrega a usted. Para ordenar el correo de un buzón compartido, cambie primero a ese buzón.",
|
||||
"Saved by an administrator; only an administrator can change it": "Guardada por un administrador; solo un administrador puede cambiarla",
|
||||
"Create a rule to move newsletters to a folder or flag important senders.": "Cree una regla para mover boletines a una carpeta o marcar remitentes importantes.",
|
||||
"New mail for {name}": "Correo nuevo para {name}",
|
||||
"This webmail works with the inbuxa mail server, and sign-in refuses a server that doesn't offer what it needs.": "Este correo web funciona con el servidor de correo inbuxa, y el inicio de sesión rechaza un servidor que no ofrezca lo que necesita.",
|
||||
"{app} test": "Prueba de {app}",
|
||||
|
||||
@@ -1794,6 +1794,13 @@ export const catalog: Catalog = {
|
||||
"Unread in the Inbox: {count}": "Non lus dans la boîte de réception : {count}",
|
||||
"Sign out of all accounts": "Se déconnecter de tous les comptes",
|
||||
"Shared mailbox:": "Boîte partagée :",
|
||||
// Added 2026-11-25 (a shared mailbox's filters, #155): generated by AI,
|
||||
// not yet read by a native speaker.
|
||||
"Filters for {name}": "Filtres de {name}",
|
||||
"You need full access to this mailbox to change its filters.": "Vous devez disposer d'un accès complet à cette boîte pour modifier ses filtres.",
|
||||
"Rules here only apply to mail delivered to you. To sort a shared mailbox's mail, switch to it first.": "Les règles définies ici ne s'appliquent qu'au courrier qui vous est distribué. Pour trier le courrier d'une boîte partagée, passez d'abord à celle-ci.",
|
||||
"Saved by an administrator; only an administrator can change it": "Enregistrée par un administrateur ; seul un administrateur peut la modifier",
|
||||
"Create a rule to move newsletters to a folder or flag important senders.": "Créez une règle pour classer les newsletters dans un dossier ou signaler les expéditeurs importants.",
|
||||
"New mail for {name}": "Nouveau courrier pour {name}",
|
||||
"This webmail works with the inbuxa mail server, and sign-in refuses a server that doesn't offer what it needs.": "Ce webmail fonctionne avec le serveur de messagerie inbuxa, et la connexion refuse un serveur qui n'offre pas ce dont il a besoin.",
|
||||
"{app} test": "Test de {app}",
|
||||
|
||||
@@ -1797,6 +1797,13 @@ export const catalog: Catalog = {
|
||||
"Unread in the Inbox: {count}": "受信トレイの未読: {count}",
|
||||
"Sign out of all accounts": "すべてのアカウントからサインアウト",
|
||||
"Shared mailbox:": "共有メールボックス:",
|
||||
// Added 2026-11-25 (a shared mailbox's filters, #155): generated by AI,
|
||||
// not yet read by a native speaker.
|
||||
"Filters for {name}": "{name} のフィルター",
|
||||
"You need full access to this mailbox to change its filters.": "このメールボックスのフィルターを変更するには、フルアクセスが必要です。",
|
||||
"Rules here only apply to mail delivered to you. To sort a shared mailbox's mail, switch to it first.": "ここのルールは、あなた宛てに配信されたメールにのみ適用されます。共有メールボックスのメールを振り分けるには、先にそのメールボックスに切り替えてください。",
|
||||
"Saved by an administrator; only an administrator can change it": "管理者が保存したルールです。変更できるのは管理者だけです",
|
||||
"Create a rule to move newsletters to a folder or flag important senders.": "ルールを作成すると、メールマガジンをフォルダーへ移動したり、重要な差出人に印を付けたりできます。",
|
||||
"New mail for {name}": "{name} に新着メール",
|
||||
"This webmail works with the inbuxa mail server, and sign-in refuses a server that doesn't offer what it needs.": "このウェブメールは inbuxa メールサーバーで動作します。必要な機能を提供しないサーバーへのサインインは拒否されます。",
|
||||
"{app} test": "{app} のテスト",
|
||||
|
||||
@@ -1789,6 +1789,13 @@ export const catalog: Catalog = {
|
||||
"Unread in the Inbox: {count}": "Ongelezen in Postvak IN: {count}",
|
||||
"Sign out of all accounts": "Uitloggen bij alle accounts",
|
||||
"Shared mailbox:": "Gedeeld postvak:",
|
||||
// Added 2026-11-25 (a shared mailbox's filters, #155): generated by AI,
|
||||
// not yet read by a native speaker.
|
||||
"Filters for {name}": "Filters voor {name}",
|
||||
"You need full access to this mailbox to change its filters.": "U hebt volledige toegang tot dit postvak nodig om de filters ervan te wijzigen.",
|
||||
"Rules here only apply to mail delivered to you. To sort a shared mailbox's mail, switch to it first.": "Filterregels hier gelden alleen voor e-mail die aan u wordt bezorgd. Wilt u de e-mail van een gedeeld postvak sorteren, schakel dan eerst over naar dat postvak.",
|
||||
"Saved by an administrator; only an administrator can change it": "Opgeslagen door een beheerder; alleen een beheerder kan deze filterregel wijzigen",
|
||||
"Create a rule to move newsletters to a folder or flag important senders.": "Maak een filterregel om nieuwsbrieven naar een map te verplaatsen of belangrijke afzenders te markeren.",
|
||||
"New mail for {name}": "Nieuwe mail voor {name}",
|
||||
"This webmail works with the inbuxa mail server, and sign-in refuses a server that doesn't offer what it needs.": "Deze webmail werkt met de inbuxa-mailserver, en inloggen weigert een server die niet biedt wat de webmail nodig heeft.",
|
||||
"{app} test": "{app}-test",
|
||||
|
||||
@@ -1792,6 +1792,13 @@ export const catalog: Catalog = {
|
||||
"Unread in the Inbox: {count}": "Não lidas na Caixa de entrada: {count}",
|
||||
"Sign out of all accounts": "Sair de todas as contas",
|
||||
"Shared mailbox:": "Caixa postal compartilhada:",
|
||||
// Added 2026-11-25 (a shared mailbox's filters, #155): generated by AI,
|
||||
// not yet read by a native speaker.
|
||||
"Filters for {name}": "Filtros de {name}",
|
||||
"You need full access to this mailbox to change its filters.": "Você precisa de acesso total a esta caixa postal para alterar os filtros dela.",
|
||||
"Rules here only apply to mail delivered to you. To sort a shared mailbox's mail, switch to it first.": "Estas regras só se aplicam às mensagens entregues a você. Para organizar as mensagens de uma caixa postal compartilhada, mude para ela primeiro.",
|
||||
"Saved by an administrator; only an administrator can change it": "Salva por um administrador; só um administrador pode alterá-la",
|
||||
"Create a rule to move newsletters to a folder or flag important senders.": "Crie uma regra para mover newsletters para uma pasta ou sinalizar remetentes importantes.",
|
||||
"New mail for {name}": "E-mail novo para {name}",
|
||||
"This webmail works with the inbuxa mail server, and sign-in refuses a server that doesn't offer what it needs.": "Este webmail funciona com o servidor de e-mail inbuxa, e o login recusa um servidor que não ofereça o que ele precisa.",
|
||||
"{app} test": "Teste do {app}",
|
||||
|
||||
@@ -1791,6 +1791,13 @@ export const catalog: Catalog = {
|
||||
"Unread in the Inbox: {count}": "Непрочитанных во «Входящих»: {count}",
|
||||
"Sign out of all accounts": "Выйти из всех учётных записей",
|
||||
"Shared mailbox:": "Общий почтовый ящик:",
|
||||
// Added 2026-11-25 (a shared mailbox's filters, #155): generated by AI,
|
||||
// not yet read by a native speaker.
|
||||
"Filters for {name}": "Фильтры для {name}",
|
||||
"You need full access to this mailbox to change its filters.": "Чтобы изменить фильтры этого почтового ящика, нужен полный доступ к нему.",
|
||||
"Rules here only apply to mail delivered to you. To sort a shared mailbox's mail, switch to it first.": "Эти правила применяются только к почте, доставленной вам. Чтобы сортировать почту общего почтового ящика, сначала переключитесь на него.",
|
||||
"Saved by an administrator; only an administrator can change it": "Сохранено администратором; изменить его может только администратор",
|
||||
"Create a rule to move newsletters to a folder or flag important senders.": "Создайте правило, чтобы складывать рассылки в папку или отмечать важных отправителей.",
|
||||
"New mail for {name}": "Новое письмо для {name}",
|
||||
"This webmail works with the inbuxa mail server, and sign-in refuses a server that doesn't offer what it needs.": "Этот веб-клиент работает с почтовым сервером inbuxa, а вход на сервер, который не предоставляет нужного, не выполняется.",
|
||||
"{app} test": "Тест {app}",
|
||||
|
||||
@@ -1694,6 +1694,13 @@ export const catalog: Catalog = {
|
||||
"Unread in the Inbox: {count}": "Gelen Kutusu'nda okunmamış: {count}",
|
||||
"Sign out of all accounts": "Tüm hesaplardan çıkış yap",
|
||||
"Shared mailbox:": "Paylaşılan posta kutusu:",
|
||||
// Added 2026-11-25 (a shared mailbox's filters, #155): generated by AI,
|
||||
// not yet read by a native speaker.
|
||||
"Filters for {name}": "{name} için filtreler",
|
||||
"You need full access to this mailbox to change its filters.": "Bu posta kutusunun filtrelerini değiştirmek için tam erişiminizin olması gerekir.",
|
||||
"Rules here only apply to mail delivered to you. To sort a shared mailbox's mail, switch to it first.": "Buradaki kurallar yalnızca size teslim edilen postalara uygulanır. Paylaşılan bir posta kutusunun postalarını sıralamak için önce o posta kutusuna geçin.",
|
||||
"Saved by an administrator; only an administrator can change it": "Bir yönetici tarafından kaydedildi; yalnızca bir yönetici değiştirebilir",
|
||||
"Create a rule to move newsletters to a folder or flag important senders.": "Bültenleri bir klasöre taşımak veya önemli gönderenleri işaretlemek için bir kural oluşturun.",
|
||||
"New mail for {name}": "{name} için yeni posta",
|
||||
// ── Passkeys (inbuxa #334) ──
|
||||
"Remove “{name}”?": "“{name}” kaldırılsın mı?",
|
||||
|
||||
@@ -1785,6 +1785,13 @@ export const catalog: Catalog = {
|
||||
"Unread in the Inbox: {count}": "Непрочитаних у «Вхідних»: {count}",
|
||||
"Sign out of all accounts": "Вийти з усіх облікових записів",
|
||||
"Shared mailbox:": "Спільна поштова скринька:",
|
||||
// Added 2026-11-25 (a shared mailbox's filters, #155): generated by AI,
|
||||
// not yet read by a native speaker.
|
||||
"Filters for {name}": "Фільтри для {name}",
|
||||
"You need full access to this mailbox to change its filters.": "Щоб змінити фільтри цієї поштової скриньки, потрібен повний доступ до неї.",
|
||||
"Rules here only apply to mail delivered to you. To sort a shared mailbox's mail, switch to it first.": "Ці правила застосовуються лише до пошти, доставленої вам. Щоб сортувати пошту спільної поштової скриньки, спершу перейдіть до неї.",
|
||||
"Saved by an administrator; only an administrator can change it": "Збережено адміністратором; змінити його може лише адміністратор",
|
||||
"Create a rule to move newsletters to a folder or flag important senders.": "Створіть правило, щоб складати розсилки до теки або позначати важливих відправників.",
|
||||
"New mail for {name}": "Новий лист для {name}",
|
||||
"This webmail works with the inbuxa mail server, and sign-in refuses a server that doesn't offer what it needs.": "Цей вебклієнт працює з поштовим сервером inbuxa, а вхід на сервер, який не надає потрібного, не виконується.",
|
||||
"{app} test": "Тест {app}",
|
||||
|
||||
@@ -1796,6 +1796,13 @@ export const catalog: Catalog = {
|
||||
"Unread in the Inbox: {count}": "收件箱中的未读邮件:{count}",
|
||||
"Sign out of all accounts": "退出所有账户",
|
||||
"Shared mailbox:": "共享邮箱:",
|
||||
// Added 2026-11-25 (a shared mailbox's filters, #155): generated by AI,
|
||||
// not yet read by a native speaker.
|
||||
"Filters for {name}": "{name} 的过滤器",
|
||||
"You need full access to this mailbox to change its filters.": "您需要对此邮箱拥有完全访问权限才能更改其过滤器。",
|
||||
"Rules here only apply to mail delivered to you. To sort a shared mailbox's mail, switch to it first.": "此处的规则只适用于投递给您的邮件。要整理共享邮箱的邮件,请先切换到该邮箱。",
|
||||
"Saved by an administrator; only an administrator can change it": "由管理员保存;只有管理员可以更改",
|
||||
"Create a rule to move newsletters to a folder or flag important senders.": "创建规则,把订阅邮件移入文件夹或标记重要发件人。",
|
||||
"New mail for {name}": "{name} 有新邮件",
|
||||
"This webmail works with the inbuxa mail server, and sign-in refuses a server that doesn't offer what it needs.": "此网页邮箱与 inbuxa 邮件服务器配合使用;若服务器未提供所需功能,将拒绝登录。",
|
||||
"{app} test": "{app} 测试",
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { CAP, client, JmapMethodError } from "@/jmap/client";
|
||||
import type { JmapSession } from "@/jmap/types";
|
||||
import { useSession } from "@/store/session";
|
||||
import { filtersTarget, refusal, useSieve } from "@/store/sieve";
|
||||
import { newRule, rulesToSieve } from "@/lib/sieve/sieve";
|
||||
|
||||
/**
|
||||
* #155: a shared mailbox's mail is sorted by its own script, so with one in
|
||||
* view the Filters page edits that, on the terms the server sets (inbuxa-server
|
||||
* #643): full access to manage them at all, and an administrator to make them
|
||||
* forward, reject or answer mail.
|
||||
*/
|
||||
|
||||
const INBUXA = "urn:inbuxa:jmap";
|
||||
const shared = (access: "read" | "organize" | "full") => ({
|
||||
name: "[email protected]",
|
||||
isPersonal: false,
|
||||
accountCapabilities: { [CAP.mail]: {}, [CAP.sieve]: {}, [INBUXA]: { delegation: { locked: true, kind: "sharedMailbox", access } } },
|
||||
});
|
||||
const session = (access: "read" | "organize" | "full", permissions: string[] = []): JmapSession =>
|
||||
({
|
||||
capabilities: { [CAP.core]: {}, [CAP.mail]: {}, [CAP.sieve]: {} },
|
||||
accounts: {
|
||||
me: { name: "[email protected]", isPersonal: true, accountCapabilities: { [CAP.mail]: {}, [CAP.sieve]: {} } },
|
||||
ops: shared(access),
|
||||
},
|
||||
primaryAccounts: { [CAP.mail]: "me", [CAP.sieve]: "me" },
|
||||
ihasmail: { permissions },
|
||||
}) as unknown as JmapSession;
|
||||
const OPS = [{ id: "ops", name: "[email protected]" }];
|
||||
|
||||
const show = (s: JmapSession, viewing: string | null) => {
|
||||
client.session = s;
|
||||
useSession.setState({ session: s, accountId: "me", viewing, sharedMail: OPS });
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
useSieve.setState({ accountId: null, shared: null, forbidden: false, sortOnly: false, available: false, scripts: [], contents: {}, loading: false, error: null });
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
client.session = null;
|
||||
});
|
||||
|
||||
describe("whose filters the page edits", () => {
|
||||
it("is the reader's own with no shared mailbox in view", () => {
|
||||
expect(filtersTarget(session("full"), null, OPS, "me")).toEqual({ accountId: "me", shared: null, forbidden: false, sortOnly: false });
|
||||
});
|
||||
|
||||
it("is the shared mailbox's when it is in view, sorting only for a member", () => {
|
||||
expect(filtersTarget(session("full"), "ops", OPS, "me")).toEqual({ accountId: "ops", shared: { name: "[email protected]" }, forbidden: false, sortOnly: true });
|
||||
});
|
||||
|
||||
it("is refused without asking for Read and Organize members", () => {
|
||||
expect(filtersTarget(session("read"), "ops", OPS, "me").forbidden).toBe(true);
|
||||
expect(filtersTarget(session("organize"), "ops", OPS, "me").forbidden).toBe(true);
|
||||
});
|
||||
|
||||
it("lets an administrator save anything, whatever their delegation says", () => {
|
||||
const t = filtersTarget(session("read", ["impersonate"]), "ops", OPS, "me");
|
||||
expect(t.forbidden).toBe(false);
|
||||
expect(t.sortOnly).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the reader's own for an account that isn't shared mail", () => {
|
||||
// A locked account handed to the reader (AL-7) is not in sharedMail.
|
||||
expect(filtersTarget(session("full"), "locked", OPS, "me").accountId).toBe("me");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the sieve store on a shared mailbox", () => {
|
||||
it("loads the shared mailbox's scripts and drops the reader's own", async () => {
|
||||
useSieve.setState({ accountId: "me", scripts: [{ id: "mine", name: "ihasmail", blobId: "b0", isActive: true }], contents: { mine: "x" } });
|
||||
show(session("full"), "ops");
|
||||
const call = vi.spyOn(client, "call").mockResolvedValue({ list: [] } as never);
|
||||
await useSieve.getState().init();
|
||||
expect(call).toHaveBeenCalledWith("SieveScript/get", { accountId: "ops", ids: null });
|
||||
expect(useSieve.getState()).toMatchObject({ accountId: "ops", scripts: [], contents: {}, sortOnly: true, forbidden: false });
|
||||
});
|
||||
|
||||
it("does not ask when the delegation already says no", async () => {
|
||||
show(session("organize"), "ops");
|
||||
const call = vi.spyOn(client, "call");
|
||||
await useSieve.getState().init();
|
||||
expect(call).not.toHaveBeenCalled();
|
||||
expect(useSieve.getState().forbidden).toBe(true);
|
||||
});
|
||||
|
||||
it("reads the server's Forbidden as no full access, not as an error", async () => {
|
||||
show(session("full"), "ops");
|
||||
vi.spyOn(client, "call").mockRejectedValue(new JmapMethodError("SieveScript/get", { type: "forbidden" }));
|
||||
await useSieve.getState().init();
|
||||
expect(useSieve.getState().forbidden).toBe(true);
|
||||
expect(useSieve.getState().error).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a Forbidden on the reader's own account an ordinary error", async () => {
|
||||
show(session("full"), null);
|
||||
vi.spyOn(client, "call").mockRejectedValue(new JmapMethodError("SieveScript/get", { type: "forbidden" }));
|
||||
await useSieve.getState().init();
|
||||
expect(useSieve.getState().forbidden).toBe(false);
|
||||
expect(useSieve.getState().error).toMatch(/forbidden/);
|
||||
});
|
||||
|
||||
it("shows the server's words when it refuses a save", async () => {
|
||||
show(session("full"), "ops");
|
||||
const words = "Forwarding and automatic replies on a shared mailbox can only be saved by an administrator.";
|
||||
vi.spyOn(client, "call").mockResolvedValue({ list: [] } as never);
|
||||
await useSieve.getState().init();
|
||||
vi.spyOn(client, "upload").mockResolvedValue({ blobId: "up1" } as never);
|
||||
vi.spyOn(client, "call").mockResolvedValue({ notCreated: { s: { type: "forbidden", description: words } } } as never);
|
||||
await expect(useSieve.getState().saveRules([newRule()])).rejects.toThrow(words);
|
||||
});
|
||||
|
||||
it("turns a Forbidden on save into the no-access page", async () => {
|
||||
show(session("full"), "ops");
|
||||
vi.spyOn(client, "call").mockResolvedValue({ list: [] } as never);
|
||||
await useSieve.getState().init();
|
||||
vi.spyOn(client, "upload").mockRejectedValue(new JmapMethodError("upload", { type: "forbidden" }));
|
||||
await expect(useSieve.getState().saveScript(null, "ihasmail", rulesToSieve([]), true)).rejects.toThrow(/full access/);
|
||||
expect(useSieve.getState().forbidden).toBe(true);
|
||||
});
|
||||
|
||||
it("throws away an answer for a mailbox no longer in view", async () => {
|
||||
show(session("full"), "ops");
|
||||
let answer!: (v: unknown) => void;
|
||||
vi.spyOn(client, "call").mockImplementation(() => new Promise((r) => { answer = r; }) as never);
|
||||
const loading = useSieve.getState().init();
|
||||
useSieve.setState({ accountId: "me" });
|
||||
answer({ list: [{ id: "theirs", name: "ihasmail", blobId: "b", isActive: true }] });
|
||||
await loading;
|
||||
expect(useSieve.getState().scripts).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("refusal", () => {
|
||||
it("prefers the server's description", () => {
|
||||
expect(refusal({ type: "forbidden", description: "Only an administrator." }, true)).toBe("Only an administrator.");
|
||||
});
|
||||
it("explains a bare forbidden on a shared mailbox", () => {
|
||||
expect(refusal({ type: "forbidden" }, true)).toMatch(/full access/);
|
||||
expect(refusal({ type: "forbidden" }, false)).toBe("forbidden");
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,8 @@ interface SessionState {
|
||||
* Another account whose mail the app shows instead of the reader's own:
|
||||
* a locked account handed to them (inbuxa AL-7), whose calendar, contacts
|
||||
* and files follow, or a shared or group mailbox (MA-A), which is mail
|
||||
* only. The reader's settings, filters, signatures and push stay their own.
|
||||
* only. The reader's settings, signatures and push stay their own; a shared
|
||||
* mailbox's filters are its own, since they sort its mail (#155).
|
||||
*/
|
||||
viewing: Id | null;
|
||||
/** Shared and group mailboxes the reader can open (MA-A); see lib/sharedMail. */
|
||||
|
||||
+95
-16
@@ -1,13 +1,67 @@
|
||||
import { create } from "zustand";
|
||||
import { CAP, client, setErrorMessage } from "@/jmap/client";
|
||||
import type { GetResponse, Id, SetResponse, SieveScript } from "@/jmap/types";
|
||||
import { CAP, client, JmapMethodError, setErrorMessage } from "@/jmap/client";
|
||||
import type { GetResponse, Id, JmapSession, SetError, SetResponse, SieveScript } from "@/jmap/types";
|
||||
import { rulesToSieve, scriptDamage, sieveToRules, type SieveRule } from "@/lib/sieve/sieve";
|
||||
import { actsAsAdministrator, permissionSet } from "@/lib/admin/adminAccess";
|
||||
import { delegationOf } from "@/lib/delegation";
|
||||
import type { SharedMailAccount } from "@/lib/sharedMail";
|
||||
import { t } from "@/lib/i18n";
|
||||
import { useSession } from "./session";
|
||||
|
||||
export const IHASMAIL_SCRIPT = "ihasmail";
|
||||
|
||||
interface SieveState {
|
||||
/**
|
||||
* Whose filters the page edits, and on what terms.
|
||||
*
|
||||
* The reader's own, unless a shared mailbox is in view (MA-S): its mail is
|
||||
* sorted by its own script, so that is the one to edit. Rules written into the
|
||||
* reader's own script for a shared address never ran on its mail, and filed
|
||||
* into the reader's Inbox when they named its folders. A locked account handed
|
||||
* to the reader (AL-7) keeps the reader's own filters, as before.
|
||||
*
|
||||
* Only a member with full access may manage a shared mailbox's filters, and
|
||||
* only an administrator may make them forward, reject or answer mail. The
|
||||
* server enforces both; this only decides what the page offers.
|
||||
*/
|
||||
export interface FiltersTarget {
|
||||
accountId: Id | null;
|
||||
/** The shared mailbox, or null for the reader's own filters. */
|
||||
shared: { name: string } | null;
|
||||
/** Known without asking: the reader's access to the shared mailbox isn't full. */
|
||||
forbidden: boolean;
|
||||
/** Only sorting actions may be saved: a shared mailbox, and the reader isn't an administrator. */
|
||||
sortOnly: boolean;
|
||||
}
|
||||
|
||||
export function filtersTarget(session: JmapSession | null, viewing: Id | null, sharedMail: readonly SharedMailAccount[], own: Id | null): FiltersTarget {
|
||||
const shared = viewing ? sharedMail.find((a) => a.id === viewing) : undefined;
|
||||
if (!shared) return { accountId: own, shared: null, forbidden: false, sortOnly: false };
|
||||
// An installation with administration off sends no permissions, so nobody
|
||||
// counts as an administrator here; the server still lets one save anything.
|
||||
const perms = permissionSet(session?.ihasmail?.administration === false ? [] : session?.ihasmail?.permissions);
|
||||
const admin = actsAsAdministrator(perms);
|
||||
const delegation = delegationOf(session, shared.id);
|
||||
return {
|
||||
accountId: shared.id,
|
||||
shared: { name: shared.name },
|
||||
forbidden: !admin && delegation !== null && delegation.access !== "full",
|
||||
sortOnly: !admin,
|
||||
};
|
||||
}
|
||||
|
||||
const isForbidden = (err: unknown): boolean => err instanceof JmapMethodError && err.type === "forbidden";
|
||||
|
||||
/**
|
||||
* Why a save was refused. The server's own words when it gave some: on a
|
||||
* shared mailbox they say what only an administrator may save, which is the
|
||||
* whole answer. A bare `forbidden` there means the access isn't full.
|
||||
*/
|
||||
export function refusal(err: SetError, shared: boolean): string {
|
||||
if (shared && err.type === "forbidden" && !err.description) return t("You need full access to this mailbox to change its filters.");
|
||||
return setErrorMessage(err);
|
||||
}
|
||||
|
||||
interface SieveState extends FiltersTarget {
|
||||
available: boolean;
|
||||
scripts: SieveScript[];
|
||||
/** Content of each script by id. */
|
||||
@@ -30,6 +84,9 @@ interface SieveState {
|
||||
|
||||
export const useSieve = create<SieveState>((set, get) => ({
|
||||
accountId: null,
|
||||
shared: null,
|
||||
forbidden: false,
|
||||
sortOnly: false,
|
||||
available: false,
|
||||
scripts: [],
|
||||
contents: {},
|
||||
@@ -37,19 +94,26 @@ export const useSieve = create<SieveState>((set, get) => ({
|
||||
error: null,
|
||||
|
||||
async init() {
|
||||
const accountId = useSession.getState().accountFor(CAP.sieve);
|
||||
const available = Boolean(accountId && client.hasCapability(CAP.sieve));
|
||||
set({ accountId, available });
|
||||
if (available) await get().load();
|
||||
const s = useSession.getState();
|
||||
const target = filtersTarget(s.session, s.viewing, s.sharedMail, s.accountFor(CAP.sieve));
|
||||
const available = Boolean(target.accountId && client.hasCapability(CAP.sieve));
|
||||
// Another account's scripts are not this one's: never show them, or save
|
||||
// over them, while the new account's are on their way.
|
||||
const moved = target.accountId !== get().accountId;
|
||||
set({ ...target, available, ...(moved ? { scripts: [], contents: {}, error: null, loading: false } : {}) });
|
||||
if (available && !target.forbidden) await get().load();
|
||||
},
|
||||
|
||||
async load() {
|
||||
const accountId = get().accountId;
|
||||
if (!accountId) return;
|
||||
// Already answered: init() asks again when the mailbox or the session changes.
|
||||
if (!accountId || get().forbidden) return;
|
||||
set({ loading: true });
|
||||
try {
|
||||
const res = await client.call<GetResponse<SieveScript>>("SieveScript/get", { accountId, ids: null });
|
||||
set({ scripts: res.list, loading: false, error: null });
|
||||
// The reader switched mailboxes while this was asking.
|
||||
if (get().accountId !== accountId) return;
|
||||
set({ scripts: res.list, loading: false, error: null, forbidden: false });
|
||||
// Preload contents.
|
||||
//
|
||||
// A fetch that fails must not be recorded as "". An empty script parses
|
||||
@@ -72,9 +136,14 @@ export const useSieve = create<SieveState>((set, get) => ({
|
||||
);
|
||||
// Merged, not replaced: saveScript caches the content it just wrote, and
|
||||
// a reload whose fetch failed must not throw that away.
|
||||
if (get().accountId !== accountId) return;
|
||||
set((st) => ({ contents: { ...st.contents, ...fetched } }));
|
||||
} catch (err) {
|
||||
set({ loading: false, error: (err as Error).message });
|
||||
if (get().accountId !== accountId) return;
|
||||
// A shared mailbox's filters, and the reader's access isn't full. That
|
||||
// is an answer, not a failure, and the page says it as one.
|
||||
if (get().shared && isForbidden(err)) set({ loading: false, forbidden: true, scripts: [], contents: {}, error: null });
|
||||
else set({ loading: false, error: (err as Error).message });
|
||||
}
|
||||
},
|
||||
|
||||
@@ -129,14 +198,24 @@ export const useSieve = create<SieveState>((set, get) => ({
|
||||
|
||||
async saveScript(id, name, content, activate) {
|
||||
const accountId = get().accountId!;
|
||||
const up = await client.upload(accountId, new Blob([content], { type: "application/sieve" }), { type: "application/sieve" });
|
||||
const args: Record<string, unknown> = { accountId };
|
||||
if (id) args.update = { [id]: { name, blobId: up.blobId } };
|
||||
else args.create = { s: { name, blobId: up.blobId } };
|
||||
if (activate) args.onSuccessActivateScript = id ?? "#s";
|
||||
const res = await client.call<SetResponse<SieveScript>>("SieveScript/set", args);
|
||||
let res: SetResponse<SieveScript>;
|
||||
try {
|
||||
const up = await client.upload(accountId, new Blob([content], { type: "application/sieve" }), { type: "application/sieve" });
|
||||
if (id) args.update = { [id]: { name, blobId: up.blobId } };
|
||||
else args.create = { s: { name, blobId: up.blobId } };
|
||||
if (activate) args.onSuccessActivateScript = id ?? "#s";
|
||||
res = await client.call<SetResponse<SieveScript>>("SieveScript/set", args);
|
||||
} catch (err) {
|
||||
// Access taken away since the page opened: show the page that says so.
|
||||
if (get().shared && isForbidden(err)) {
|
||||
set({ forbidden: true });
|
||||
throw new Error(t("You need full access to this mailbox to change its filters."));
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
const err = id ? res.notUpdated?.[id] : res.notCreated?.s;
|
||||
if (err) throw new Error(setErrorMessage(err));
|
||||
if (err) throw new Error(refusal(err, get().shared !== null));
|
||||
const newId = id ?? res.created!.s!.id;
|
||||
set((s) => ({ contents: { ...s.contents, [newId]: content } }));
|
||||
await get().load();
|
||||
|
||||
@@ -1790,6 +1790,8 @@ select optgroup { background-color: var(--bg-elev); color: var(--fg); }
|
||||
.rule-card.drop-below { box-shadow: inset 0 -3px 0 0 var(--accent); }
|
||||
.rule-card .drag-handle { display: flex; align-items: center; padding: 2px; margin-left: -4px; color: var(--fg-faint); cursor: grab; touch-action: none; }
|
||||
.rule-card .drag-handle:active { cursor: grabbing; }
|
||||
/* A rule only an administrator may change (#155): nothing to grab. */
|
||||
.rule-card .drag-handle.locked { cursor: default; }
|
||||
|
||||
/* The bar that says whether there is unsaved work, kept where it can be read.
|
||||
Unpinned it sat after the rules, which on a full list means off the bottom of
|
||||
|
||||
@@ -19,7 +19,7 @@ export function FilterFromMessageDialog({ email, mailboxId, onClose }: { email:
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
if (sieve.available && !sieve.scripts.length && !sieve.loading) await sieve.load();
|
||||
if (sieve.available && !sieve.forbidden && !sieve.scripts.length && !sieve.loading) await sieve.load();
|
||||
setReady(true);
|
||||
})();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
@@ -33,6 +33,13 @@ export function FilterFromMessageDialog({ email, mailboxId, onClose }: { email:
|
||||
);
|
||||
}
|
||||
if (!ready) return <Dialog open onClose={onClose} title={t("Create filter")} size="sm"><Spinner /></Dialog>;
|
||||
if (sieve.forbidden) {
|
||||
return (
|
||||
<Dialog open onClose={onClose} title={t("Create filter")} size="sm" footer={<button className="btn" onClick={onClose}>{t("Close")}</button>}>
|
||||
<p>{t("You need full access to this mailbox to change its filters.")}</p>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
const { rules, loaded, damage } = sieve.rules();
|
||||
if (rules === null) {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { ArrowDown, ArrowUp, Code, GripVertical, Plus, Trash2, Wand2, Play, AlertTriangle, Power } from "lucide-react";
|
||||
import { ArrowDown, ArrowUp, Code, GripVertical, Lock, Plus, Trash2, Wand2, Play, AlertTriangle, Power } from "lucide-react";
|
||||
import { useSieve } from "@/store/sieve";
|
||||
import { useMail } from "@/store/mail";
|
||||
import { describeRule, newRule, reorderRules, rulesToSieve, upsertRule, type SieveRule } from "@/lib/sieve/sieve";
|
||||
import { useSession } from "@/store/session";
|
||||
import { describeRule, needsAdministrator, newRule, reorderRules, rulesToSieve, upsertRule, type SieveRule } from "@/lib/sieve/sieve";
|
||||
import { RuleDialog } from "./RuleDialog";
|
||||
import { saveAndApply } from "../mail/FilterFromMessage";
|
||||
import { confirmDialog, promptDialog } from "@/ui/dialog";
|
||||
@@ -26,24 +27,42 @@ export function FiltersSettings() {
|
||||
if (ok) setTab(next);
|
||||
});
|
||||
};
|
||||
/** Whether there is a shared mailbox whose mail these rules will never see. */
|
||||
const hasSharedMail = useSession((s) => s.sharedMail.length > 0);
|
||||
useEffect(() => {
|
||||
if (sieve.available && !sieve.scripts.length && !sieve.loading) void sieve.load();
|
||||
if (sieve.available && !sieve.forbidden && !sieve.scripts.length && !sieve.loading) void sieve.load();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [sieve.available]);
|
||||
}, [sieve.available, sieve.accountId]);
|
||||
|
||||
// On a shared mailbox, say whose filters these are: rules written here sort
|
||||
// its mail, not the reader's, and rules for it written anywhere else never run.
|
||||
const heading = <h1>{sieve.shared ? t("Filters for {name}", { name: sieve.shared.name }) : t("Filters & rules")}</h1>;
|
||||
|
||||
if (!sieve.available) {
|
||||
return (
|
||||
<div>
|
||||
<h1>{t("Filters & rules")}</h1>
|
||||
{heading}
|
||||
<p className="lead">{t("Sieve filtering is not available for this account.")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Read or Organize access to a shared mailbox. Nothing here would work, so
|
||||
// nothing here is offered.
|
||||
if (sieve.forbidden) {
|
||||
return (
|
||||
<div>
|
||||
{heading}
|
||||
<p className="lead">{t("You need full access to this mailbox to change its filters.")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>{t("Filters & rules")}</h1>
|
||||
{heading}
|
||||
<p className="lead">{t("Sort incoming mail automatically. Rules run on the server (Sieve), so they work for every client you use.")}</p>
|
||||
{!sieve.shared && hasSharedMail && <p className="hint mb-16">{t("Rules here only apply to mail delivered to you. To sort a shared mailbox's mail, switch to it first.")}</p>}
|
||||
<div className="view-switch" style={{ marginBottom: 16 }}>
|
||||
<button className={tab === "rules" ? "active" : ""} onClick={() => switchTab("rules")}><Wand2 size={15} /> {t("Rules")}</button>
|
||||
<button className={tab === "scripts" ? "active" : ""} onClick={() => switchTab("scripts")}><Code size={15} /> {t("Scripts (advanced)")}</button>
|
||||
@@ -130,48 +149,59 @@ function RulesEditor() {
|
||||
return (
|
||||
<div>
|
||||
{activeIsOther && <div className="warn-box mb-16">{t("Another script (“{name}”) is active. Saving rules here will activate the “ihasmail” script instead.", { name: script?.name ?? "" })}</div>}
|
||||
{list.length === 0 && <div className="empty" style={{ padding: 32 }}><Wand2 size={32} /><h3>{t("No filters yet")}</h3><p>{t("Create a rule to move newsletters to a folder, flag important senders, or forward mail.")}</p></div>}
|
||||
{list.map((r, i) => (
|
||||
<div
|
||||
key={r.id}
|
||||
className={`rule-card ${r.enabled ? "" : "disabled"} ${dragId === r.id ? "dragging" : ""} ${over?.id === r.id ? (over.below ? "drop-below" : "drop-above") : ""}`}
|
||||
draggable={armed === r.id}
|
||||
onDragStart={(e) => { e.dataTransfer.setData(RULE_MIME, r.id); e.dataTransfer.effectAllowed = "move"; dragging.current = r.id; setDragId(r.id); }}
|
||||
onDragEnd={endDrag}
|
||||
onDragOver={(e) => {
|
||||
if (!e.dataTransfer.types.includes(RULE_MIME) || dragging.current === r.id) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = "move";
|
||||
const below = isBelow(e.currentTarget, e.clientY);
|
||||
if (over?.id !== r.id || over.below !== below) setOver({ id: r.id, below });
|
||||
}}
|
||||
onDragLeave={() => setOver((o) => (o?.id === r.id ? null : o))}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
const from = e.dataTransfer.getData(RULE_MIME);
|
||||
if (from) setLocal(reorderRules(list, from, r.id, isBelow(e.currentTarget, e.clientY)));
|
||||
endDrag();
|
||||
}}
|
||||
>
|
||||
<div className="row">
|
||||
<span
|
||||
className="drag-handle"
|
||||
title={t("Drag to reorder")}
|
||||
aria-hidden="true"
|
||||
onPointerDown={() => setArmed(r.id)}
|
||||
onPointerUp={() => setArmed(null)}
|
||||
><GripVertical size={16} /></span>
|
||||
<Switch checked={r.enabled} onChange={(v) => setLocal(list.map((x) => (x.id === r.id ? { ...x, enabled: v } : x)))} />
|
||||
<div className="grow" style={{ cursor: "pointer", minWidth: 0 }} onClick={() => setEditing(r)}>
|
||||
<div style={{ fontWeight: 600 }}>{r.name}</div>
|
||||
<div className="hint truncate">{describeRule(r)}</div>
|
||||
{list.length === 0 && <div className="empty" style={{ padding: 32 }}><Wand2 size={32} /><h3>{t("No filters yet")}</h3><p>{sieve.sortOnly ? t("Create a rule to move newsletters to a folder or flag important senders.") : t("Create a rule to move newsletters to a folder, flag important senders, or forward mail.")}</p></div>}
|
||||
{list.map((r, i) => {
|
||||
// Forwards, rejects or does something else only an administrator may
|
||||
// save here. Shown, so the list is the whole of what runs, but kept
|
||||
// exactly as it is: saving the other rules writes it back unchanged.
|
||||
const locked = sieve.sortOnly && needsAdministrator(r);
|
||||
return (
|
||||
<div
|
||||
key={r.id}
|
||||
className={`rule-card ${r.enabled ? "" : "disabled"} ${dragId === r.id ? "dragging" : ""} ${over?.id === r.id ? (over.below ? "drop-below" : "drop-above") : ""}`}
|
||||
draggable={!locked && armed === r.id}
|
||||
onDragStart={(e) => { e.dataTransfer.setData(RULE_MIME, r.id); e.dataTransfer.effectAllowed = "move"; dragging.current = r.id; setDragId(r.id); }}
|
||||
onDragEnd={endDrag}
|
||||
onDragOver={(e) => {
|
||||
if (!e.dataTransfer.types.includes(RULE_MIME) || dragging.current === r.id) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = "move";
|
||||
const below = isBelow(e.currentTarget, e.clientY);
|
||||
if (over?.id !== r.id || over.below !== below) setOver({ id: r.id, below });
|
||||
}}
|
||||
onDragLeave={() => setOver((o) => (o?.id === r.id ? null : o))}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
const from = e.dataTransfer.getData(RULE_MIME);
|
||||
if (from) setLocal(reorderRules(list, from, r.id, isBelow(e.currentTarget, e.clientY)));
|
||||
endDrag();
|
||||
}}
|
||||
>
|
||||
<div className="row">
|
||||
{locked ? (
|
||||
<span className="drag-handle locked" aria-hidden="true"><Lock size={16} /></span>
|
||||
) : (
|
||||
<span
|
||||
className="drag-handle"
|
||||
title={t("Drag to reorder")}
|
||||
aria-hidden="true"
|
||||
onPointerDown={() => setArmed(r.id)}
|
||||
onPointerUp={() => setArmed(null)}
|
||||
><GripVertical size={16} /></span>
|
||||
)}
|
||||
<Switch checked={r.enabled} locked={locked} onChange={(v) => setLocal(list.map((x) => (x.id === r.id ? { ...x, enabled: v } : x)))} />
|
||||
<div className="grow" style={{ cursor: locked ? "default" : "pointer", minWidth: 0 }} onClick={locked ? undefined : () => setEditing(r)}>
|
||||
<div style={{ fontWeight: 600 }}>{r.name}</div>
|
||||
<div className="hint truncate">{describeRule(r)}</div>
|
||||
{locked && <div className="hint">{t("Saved by an administrator; only an administrator can change it")}</div>}
|
||||
</div>
|
||||
<button className="icon-btn sm" disabled={locked || i === 0} aria-label={t("Move up")} onClick={() => { const n = [...list]; [n[i - 1], n[i]] = [n[i]!, n[i - 1]!]; setLocal(n); }}><ArrowUp size={16} /></button>
|
||||
<button className="icon-btn sm" disabled={locked || i === list.length - 1} aria-label={t("Move down")} onClick={() => { const n = [...list]; [n[i + 1], n[i]] = [n[i]!, n[i + 1]!]; setLocal(n); }}><ArrowDown size={16} /></button>
|
||||
<button className="icon-btn sm danger" disabled={locked} aria-label={t("Delete rule")} onClick={() => setLocal(list.filter((x) => x.id !== r.id))}><Trash2 size={16} /></button>
|
||||
</div>
|
||||
<button className="icon-btn sm" disabled={i === 0} aria-label={t("Move up")} onClick={() => { const n = [...list]; [n[i - 1], n[i]] = [n[i]!, n[i - 1]!]; setLocal(n); }}><ArrowUp size={16} /></button>
|
||||
<button className="icon-btn sm" disabled={i === list.length - 1} aria-label={t("Move down")} onClick={() => { const n = [...list]; [n[i + 1], n[i]] = [n[i]!, n[i + 1]!]; setLocal(n); }}><ArrowDown size={16} /></button>
|
||||
<button className="icon-btn sm danger" aria-label={t("Delete rule")} onClick={() => setLocal(list.filter((x) => x.id !== r.id))}><Trash2 size={16} /></button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
{/*
|
||||
* Pinned, because with more than a screenful of rules this bar was the
|
||||
* only thing saying there was unsaved work and it sat below the fold.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { Plus, Trash2 } from "lucide-react";
|
||||
import { useMail } from "@/store/mail";
|
||||
import { useSieve } from "@/store/sieve";
|
||||
import { HEADER_CHOICES, HEADER_OPS, type SieveAction, type SieveRule, type SieveTest } from "@/lib/sieve/sieve";
|
||||
import { Dialog, promptDialog } from "@/ui/dialog";
|
||||
import { toast } from "@/ui/toast";
|
||||
@@ -23,6 +24,9 @@ export interface RuleDialogProps {
|
||||
export function RuleDialog({ rule, onClose, onSave, applyMailbox, applyByDefault, title, saveLabel }: RuleDialogProps) {
|
||||
const [r, setR] = useState<SieveRule>(rule);
|
||||
const [applyNow, setApplyNow] = useState(Boolean(applyMailbox && applyByDefault));
|
||||
// A shared mailbox, and the reader isn't an administrator: the server takes
|
||||
// sorting from them and nothing that sends mail anywhere (#155).
|
||||
const sortOnly = useSieve((s) => s.sortOnly);
|
||||
const mailboxes = useMail((s) => s.mailboxes);
|
||||
const mailboxPath = useMail((s) => s.mailboxPath);
|
||||
const folders = useMemo(() => Object.values(mailboxes).map((m) => ({ id: m.id, path: mailboxPath(m.id) })).sort((a, b) => a.path.localeCompare(b.path)), [mailboxes, mailboxPath]);
|
||||
@@ -101,10 +105,10 @@ export function RuleDialog({ rule, onClose, onSave, applyMailbox, applyByDefault
|
||||
<option value="markread">{translate("Mark as read")}</option>
|
||||
<option value="flag">{translate("Star")}</option>
|
||||
<option value="addflag">{translate("Add label / keyword")}</option>
|
||||
<option value="redirect">{translate("Forward to")}</option>
|
||||
{(!sortOnly || a.type === "redirect") && <option value="redirect">{translate("Forward to")}</option>}
|
||||
<option value="keep">{translate("Keep in Inbox")}</option>
|
||||
<option value="discard">{translate("Delete")}</option>
|
||||
<option value="reject">{translate("Reject with message")}</option>
|
||||
{(!sortOnly || a.type === "reject") && <option value="reject">{translate("Reject with message")}</option>}
|
||||
<option value="stop">{translate("Stop processing more rules")}</option>
|
||||
</select>
|
||||
{a.type === "fileinto" ? (
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { FiltersSettings } from "../FiltersSettings";
|
||||
import { RuleDialog } from "../RuleDialog";
|
||||
import { ConfirmHost } from "@/ui/dialog";
|
||||
import { useSieve } from "@/store/sieve";
|
||||
import { useSession } from "@/store/session";
|
||||
import { newRule, rulesToSieve, type SieveRule } from "@/lib/sieve/sieve";
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
/**
|
||||
* #155: Settings › Filters with a shared mailbox in view. It says whose filters
|
||||
* they are, explains a refusal instead of failing, and keeps a member who isn't
|
||||
* an administrator to rules that sort.
|
||||
*/
|
||||
|
||||
const sorting = newRule({ id: "r1", name: "Invoices", actions: [{ type: "fileinto", mailbox: "Invoices" }] });
|
||||
const forwarding: SieveRule = { ...newRule({ id: "r2", name: "Escalate" }), actions: [{ type: "redirect", address: "[email protected]" }] };
|
||||
|
||||
describe("Filters on a shared mailbox", () => {
|
||||
let host: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
const text = () => document.body.textContent ?? "";
|
||||
const button = (label: string) => Array.from(document.querySelectorAll("button")).find((b) => b.textContent?.includes(label));
|
||||
const card = (name: string) => Array.from(document.querySelectorAll(".rule-card")).find((c) => c.textContent?.includes(name))!;
|
||||
|
||||
const state = (over: Partial<ReturnType<typeof useSieve.getState>>) =>
|
||||
useSieve.setState({
|
||||
accountId: "ops", shared: { name: "[email protected]" }, forbidden: false, sortOnly: true,
|
||||
available: true, loading: false, error: null,
|
||||
scripts: [{ id: "s1", name: "ihasmail", blobId: "b1", isActive: true }],
|
||||
contents: { s1: rulesToSieve([sorting, forwarding]) },
|
||||
...over,
|
||||
});
|
||||
const render = (el: React.ReactNode) => act(() => root.render(<>{el}<ConfirmHost /></>));
|
||||
|
||||
beforeEach(() => {
|
||||
useSession.setState({ sharedMail: [{ id: "ops", name: "[email protected]" }] });
|
||||
host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
root = createRoot(host);
|
||||
});
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
host.remove();
|
||||
useSession.setState({ sharedMail: [] });
|
||||
});
|
||||
|
||||
it("says whose filters these are", () => {
|
||||
state({});
|
||||
render(<FiltersSettings />);
|
||||
expect(document.querySelector("h1")?.textContent).toBe("Filters for [email protected]");
|
||||
// The hint is for the reader's own page, not this one.
|
||||
expect(text()).not.toContain("only apply to mail delivered to you");
|
||||
});
|
||||
|
||||
it("explains a refusal, and offers nothing that would fail", () => {
|
||||
state({ forbidden: true, scripts: [], contents: {} });
|
||||
render(<FiltersSettings />);
|
||||
expect(text()).toContain("You need full access to this mailbox to change its filters.");
|
||||
expect(button("New rule")).toBeUndefined();
|
||||
expect(document.querySelector(".view-switch")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows an administrator's forwarding rule read-only", () => {
|
||||
state({});
|
||||
render(<FiltersSettings />);
|
||||
const locked = card("Escalate");
|
||||
expect(locked.textContent).toContain("Saved by an administrator; only an administrator can change it");
|
||||
expect(locked.querySelector(".switch")?.hasAttribute("disabled")).toBe(true);
|
||||
expect((locked.querySelector('[aria-label="Delete rule"]') as HTMLButtonElement).disabled).toBe(true);
|
||||
const open = card("Invoices");
|
||||
expect(open.textContent).not.toContain("Saved by an administrator");
|
||||
expect((open.querySelector('[aria-label="Delete rule"]') as HTMLButtonElement).disabled).toBe(false);
|
||||
});
|
||||
|
||||
it("leaves an administrator's rule editable for an administrator", () => {
|
||||
state({ sortOnly: false });
|
||||
render(<FiltersSettings />);
|
||||
expect(card("Escalate").textContent).not.toContain("Saved by an administrator");
|
||||
});
|
||||
|
||||
it("offers a member only actions that sort", () => {
|
||||
state({});
|
||||
render(<RuleDialog rule={sorting} onClose={() => undefined} onSave={() => undefined} />);
|
||||
const offered = Array.from(document.querySelectorAll<HTMLOptionElement>(".rule-row.actions select option")).map((o) => o.value);
|
||||
expect(offered).toEqual(expect.arrayContaining(["fileinto", "markread", "flag", "discard", "stop"]));
|
||||
expect(offered).not.toContain("redirect");
|
||||
expect(offered).not.toContain("reject");
|
||||
});
|
||||
|
||||
it("offers forwarding again on the reader's own filters", () => {
|
||||
state({ shared: null, sortOnly: false, accountId: "me" });
|
||||
render(<RuleDialog rule={sorting} onClose={() => undefined} onSave={() => undefined} />);
|
||||
const offered = Array.from(document.querySelectorAll<HTMLOptionElement>(".rule-row.actions select option")).map((o) => o.value);
|
||||
expect(offered).toContain("redirect");
|
||||
expect(offered).toContain("reject");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the reader's own Filters page", () => {
|
||||
let host: HTMLDivElement;
|
||||
let root: Root;
|
||||
beforeEach(() => {
|
||||
useSieve.setState({
|
||||
accountId: "me", shared: null, forbidden: false, sortOnly: false, available: true, loading: false, error: null,
|
||||
scripts: [{ id: "s1", name: "ihasmail", blobId: "b1", isActive: true }], contents: { s1: rulesToSieve([sorting]) },
|
||||
});
|
||||
host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
root = createRoot(host);
|
||||
});
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
host.remove();
|
||||
useSession.setState({ sharedMail: [] });
|
||||
});
|
||||
|
||||
const hint = "Rules here only apply to mail delivered to you. To sort a shared mailbox's mail, switch to it first.";
|
||||
|
||||
it("says where a shared mailbox's rules go, when there is one", () => {
|
||||
useSession.setState({ sharedMail: [{ id: "ops", name: "[email protected]" }] });
|
||||
act(() => root.render(<FiltersSettings />));
|
||||
expect(document.querySelector("h1")?.textContent).toBe("Filters & rules");
|
||||
expect(document.body.textContent).toContain(hint);
|
||||
});
|
||||
|
||||
it("says nothing about it to someone with none", () => {
|
||||
act(() => root.render(<FiltersSettings />));
|
||||
expect(document.body.textContent).not.toContain(hint);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user