Add embedded IMAP/SMTP mail for staff

Admins configure one mail server; each staff member gets their own mailbox
login. Read, reply and compose against real IMAP/SMTP.

IMAP and SMTP are raw TCP, so none of this can run in a browser — every
operation is a TanStack Start server function. mail.functions.ts ships to
the client bundle, so imapflow/nodemailer/mailparser and the crypto
helpers are imported inside handlers, never at the top level. Verified
that Nitro inlines all three into .output/server/_libs, since the Docker
runner stage copies only .output and has no node_modules.

Note this ties the app to the Node deployment: the default local build
targets Cloudflare Workers, which cannot open IMAP sockets.

Credential handling, since a mailbox password grants full read and send
access to someone's mail:

- user_mailboxes has RLS enabled, no policies, and SELECT revoked from
  anon and authenticated. Verified: teacher and admin both see zero rows
  and no ciphertext; only service_role can read it. The revoke is belt and
  braces — Supabase's default privileges had granted SELECT, leaving the
  table one stray policy away from leaking.
- Passwords are sealed with AES-256-GCM using MAIL_CRED_KEY from
  .env.secret, so a database dump alone opens nothing. GCM also makes
  tampering fail the auth tag instead of decrypting to garbage.
- Provisioning verifies credentials against the live IMAP server before
  storing them, so typos surface at setup rather than as a broken inbox.

Message bodies render as plain text; sender HTML is never injected, which
would execute sender-controlled markup and leak read receipts via
tracking pixels.

Mailboxes are limited to admins and teachers. Students are excluded
deliberately — external mail for minors carries archiving, monitoring and
consent obligations that should be chosen, not inherited.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-26 10:46:47 -04:00
co-authored by Claude Opus 5
parent 53ab6b92b5
commit d2d4e49fa6
9 changed files with 1444 additions and 1 deletions
+72
View File
@@ -531,6 +531,42 @@ export type Database = {
},
]
}
mail_server_settings: {
Row: {
id: boolean
imap_host: string
imap_port: number
imap_secure: boolean
smtp_host: string
smtp_port: number
smtp_secure: boolean
updated_at: string
updated_by: string | null
}
Insert: {
id?: boolean
imap_host: string
imap_port?: number
imap_secure?: boolean
smtp_host: string
smtp_port?: number
smtp_secure?: boolean
updated_at?: string
updated_by?: string | null
}
Update: {
id?: boolean
imap_host?: string
imap_port?: number
imap_secure?: boolean
smtp_host?: string
smtp_port?: number
smtp_secure?: boolean
updated_at?: string
updated_by?: string | null
}
Relationships: []
}
message_threads: {
Row: {
created_at: string
@@ -1298,6 +1334,42 @@ export type Database = {
},
]
}
user_mailboxes: {
Row: {
created_at: string
created_by: string | null
email: string
last_verified_at: string | null
secret_ciphertext: string
secret_iv: string
secret_tag: string
updated_at: string
user_id: string
}
Insert: {
created_at?: string
created_by?: string | null
email: string
last_verified_at?: string | null
secret_ciphertext: string
secret_iv: string
secret_tag: string
updated_at?: string
user_id: string
}
Update: {
created_at?: string
created_by?: string | null
email?: string
last_verified_at?: string | null
secret_ciphertext?: string
secret_iv?: string
secret_tag?: string
updated_at?: string
user_id?: string
}
Relationships: []
}
user_roles: {
Row: {
created_at: string
+55
View File
@@ -0,0 +1,55 @@
// Sealing for mailbox passwords. Server-only: never import from a route or a
// *.functions.ts top level, both of which ship to the client bundle.
//
// AES-256-GCM so the stored value is both encrypted and tamper-evident — a
// modified ciphertext fails the auth tag rather than decrypting to garbage that
// then gets sent to an IMAP server.
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
export type Sealed = { ciphertext: string; iv: string; tag: string };
const KEY_ENV = "MAIL_CRED_KEY";
// 32 bytes, supplied base64 or hex. Generate with:
// openssl rand -base64 32
function key(): Buffer {
const raw = process.env[KEY_ENV];
if (!raw) {
throw new Error(
`${KEY_ENV} is not set. Add a 32-byte key to .env.secret (openssl rand -base64 32) before using mail.`,
);
}
const buf = /^[0-9a-fA-F]{64}$/.test(raw.trim())
? Buffer.from(raw.trim(), "hex")
: Buffer.from(raw.trim(), "base64");
if (buf.length !== 32) {
throw new Error(`${KEY_ENV} must decode to exactly 32 bytes (got ${buf.length}).`);
}
return buf;
}
export function seal(plaintext: string): Sealed {
const iv = randomBytes(12); // 96-bit nonce, the GCM standard
const c = createCipheriv("aes-256-gcm", key(), iv);
const ct = Buffer.concat([c.update(plaintext, "utf8"), c.final()]);
return {
ciphertext: ct.toString("base64"),
iv: iv.toString("base64"),
tag: c.getAuthTag().toString("base64"),
};
}
export function open(s: Sealed): string {
const d = createDecipheriv("aes-256-gcm", key(), Buffer.from(s.iv, "base64"));
d.setAuthTag(Buffer.from(s.tag, "base64"));
return Buffer.concat([d.update(Buffer.from(s.ciphertext, "base64")), d.final()]).toString("utf8");
}
export function mailKeyConfigured(): boolean {
try {
key();
return true;
} catch {
return false;
}
}
+430
View File
@@ -0,0 +1,430 @@
// Embedded mail. IMAP and SMTP are raw TCP protocols, so every one of these
// runs server-side; the browser only ever sees parsed results.
//
// This file ships to the client bundle, so imapflow / nodemailer / mailparser /
// the crypto helpers are imported *inside* handlers, never at the top level.
import { createServerFn } from "@tanstack/react-start";
import { requireSupabaseAuth } from "@/integrations/supabase/auth-middleware";
export type MailSettings = {
imap_host: string;
imap_port: number;
imap_secure: boolean;
smtp_host: string;
smtp_port: number;
smtp_secure: boolean;
};
export type MailboxSummary = {
user_id: string;
email: string;
full_name: string | null;
last_verified_at: string | null;
};
export type MessageHeader = {
uid: number;
subject: string;
from: string;
to: string;
date: string | null;
seen: boolean;
flagged: boolean;
hasAttachments: boolean;
};
export type MessageBody = {
uid: number;
subject: string;
from: string;
to: string;
cc: string;
date: string | null;
text: string;
html: string | null;
messageId: string | null;
references: string | null;
attachments: { filename: string; size: number; contentType: string }[];
};
const callerId = (context: unknown) => (context as { userId: string }).userId;
async function assertAdmin(uid: string) {
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { data } = await supabaseAdmin
.from("user_roles")
.select("role")
.eq("user_id", uid)
.eq("role", "admin")
.maybeSingle();
if (!data) throw new Error("Only admins can manage mail settings.");
}
async function loadSettings(): Promise<MailSettings> {
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { data } = await supabaseAdmin.from("mail_server_settings").select("*").maybeSingle();
if (!data) throw new Error("Mail server is not configured yet. An admin must set it up first.");
return data as MailSettings;
}
// Resolves the caller's own mailbox credentials. Nothing here is ever returned
// to the client — only used to open a connection.
async function credentialsFor(userId: string) {
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { open } = await import("@/lib/mail-crypto.server");
const { data } = await supabaseAdmin
.from("user_mailboxes")
.select("email, secret_ciphertext, secret_iv, secret_tag")
.eq("user_id", userId)
.maybeSingle();
if (!data) throw new Error("You do not have a mailbox yet. Ask an administrator to set one up.");
const settings = await loadSettings();
return {
settings,
email: data.email,
password: open({
ciphertext: data.secret_ciphertext,
iv: data.secret_iv,
tag: data.secret_tag,
}),
};
}
async function withImap<T>(
userId: string,
fn: (client: import("imapflow").ImapFlow) => Promise<T>,
): Promise<T> {
const { ImapFlow } = await import("imapflow");
const { settings, email, password } = await credentialsFor(userId);
const client = new ImapFlow({
host: settings.imap_host,
port: settings.imap_port,
secure: settings.imap_secure,
auth: { user: email, pass: password },
logger: false,
// Fail fast rather than hanging a request behind a dead mail host.
socketTimeout: 20_000,
greetingTimeout: 10_000,
});
await client.connect();
try {
return await fn(client);
} finally {
await client.logout().catch(() => client.close());
}
}
const addr = (a: unknown): string => {
const list = (a as { address?: string; name?: string }[] | undefined) ?? [];
return list.map((x) => (x.name ? `${x.name} <${x.address}>` : (x.address ?? ""))).join(", ");
};
// ── Admin: setup ────────────────────────────────────────────────────────────
export const getMailSetup = createServerFn({ method: "POST" })
.middleware([requireSupabaseAuth])
.handler(async ({ context }) => {
const uid = callerId(context);
await assertAdmin(uid);
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { mailKeyConfigured } = await import("@/lib/mail-crypto.server");
const { data: settings } = await supabaseAdmin
.from("mail_server_settings")
.select("*")
.maybeSingle();
const { data: boxes } = await supabaseAdmin
.from("user_mailboxes")
.select("user_id, email, last_verified_at");
const ids = (boxes ?? []).map((b) => b.user_id);
const { data: profs } = ids.length
? await supabaseAdmin.from("profiles").select("id, full_name").in("id", ids)
: { data: [] as { id: string; full_name: string | null }[] };
const nameOf = Object.fromEntries((profs ?? []).map((p) => [p.id, p.full_name]));
// Staff eligible for a mailbox. Students are deliberately excluded from this
// rollout; widening it is a policy decision, not a code change.
const { data: staffRoles } = await supabaseAdmin
.from("user_roles")
.select("user_id, role")
.in("role", ["admin", "teacher"]);
const staffIds = [...new Set((staffRoles ?? []).map((r) => r.user_id))];
const { data: staffProfiles } = staffIds.length
? await supabaseAdmin.from("profiles").select("id, full_name, email").in("id", staffIds)
: { data: [] as { id: string; full_name: string | null; email: string | null }[] };
return {
settings: (settings ?? null) as MailSettings | null,
keyConfigured: mailKeyConfigured(),
mailboxes: (boxes ?? []).map((b) => ({
user_id: b.user_id,
email: b.email,
full_name: nameOf[b.user_id] ?? null,
last_verified_at: b.last_verified_at,
})) as MailboxSummary[],
staff: (staffProfiles ?? []) as {
id: string;
full_name: string | null;
email: string | null;
}[],
};
});
export const saveMailSettings = createServerFn({ method: "POST" })
.middleware([requireSupabaseAuth])
.validator((d: MailSettings) => d)
.handler(async ({ data, context }) => {
const uid = callerId(context);
await assertAdmin(uid);
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { error } = await supabaseAdmin.from("mail_server_settings").upsert(
{
id: true,
imap_host: data.imap_host.trim(),
imap_port: Number(data.imap_port),
imap_secure: !!data.imap_secure,
smtp_host: data.smtp_host.trim(),
smtp_port: Number(data.smtp_port),
smtp_secure: !!data.smtp_secure,
updated_by: uid,
},
{ onConflict: "id" },
);
if (error) throw new Error(error.message);
return { ok: true };
});
// Provisioning verifies the credentials against the live IMAP server before
// storing them, so a typo surfaces here instead of as a broken inbox later.
export const setUserMailbox = createServerFn({ method: "POST" })
.middleware([requireSupabaseAuth])
.validator((d: { userId: string; email: string; password: string }) => d)
.handler(async ({ data, context }) => {
const uid = callerId(context);
await assertAdmin(uid);
if (!data.email.trim() || !data.password)
throw new Error("Email and password are both required.");
const settings = await loadSettings();
const { ImapFlow } = await import("imapflow");
const probe = new ImapFlow({
host: settings.imap_host,
port: settings.imap_port,
secure: settings.imap_secure,
auth: { user: data.email.trim(), pass: data.password },
logger: false,
socketTimeout: 20_000,
greetingTimeout: 10_000,
});
try {
await probe.connect();
await probe.logout();
} catch (e) {
throw new Error(`IMAP login failed: ${(e as Error).message}`);
}
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { seal } = await import("@/lib/mail-crypto.server");
const s = seal(data.password);
const { error } = await supabaseAdmin.from("user_mailboxes").upsert(
{
user_id: data.userId,
email: data.email.trim(),
secret_ciphertext: s.ciphertext,
secret_iv: s.iv,
secret_tag: s.tag,
last_verified_at: new Date().toISOString(),
created_by: uid,
},
{ onConflict: "user_id" },
);
if (error) throw new Error(error.message);
return { ok: true };
});
export const removeUserMailbox = createServerFn({ method: "POST" })
.middleware([requireSupabaseAuth])
.validator((d: { userId: string }) => d)
.handler(async ({ data, context }) => {
const uid = callerId(context);
await assertAdmin(uid);
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { error } = await supabaseAdmin
.from("user_mailboxes")
.delete()
.eq("user_id", data.userId);
if (error) throw new Error(error.message);
return { ok: true };
});
// ── Own mailbox ─────────────────────────────────────────────────────────────
export const myMailboxStatus = createServerFn({ method: "POST" })
.middleware([requireSupabaseAuth])
.handler(async ({ context }) => {
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { data: box } = await supabaseAdmin
.from("user_mailboxes")
.select("email")
.eq("user_id", callerId(context))
.maybeSingle();
const { data: settings } = await supabaseAdmin
.from("mail_server_settings")
.select("id")
.maybeSingle();
return { email: box?.email ?? null, serverConfigured: !!settings };
});
export const listFolders = createServerFn({ method: "POST" })
.middleware([requireSupabaseAuth])
.handler(async ({ context }) =>
withImap(callerId(context), async (client) => {
const list = await client.list();
return list
.filter((f) => !f.flags.has("\\Noselect"))
.map((f) => ({ path: f.path, name: f.name, specialUse: f.specialUse ?? null }));
}),
);
export const listMessages = createServerFn({ method: "POST" })
.middleware([requireSupabaseAuth])
.validator((d: { folder?: string; limit?: number }) => d)
.handler(async ({ data, context }) =>
withImap(callerId(context), async (client) => {
const folder = data.folder || "INBOX";
const limit = Math.min(Math.max(data.limit ?? 40, 1), 100);
const lock = await client.getMailboxLock(folder);
try {
const total = typeof client.mailbox === "object" ? client.mailbox.exists : 0;
if (!total) return { folder, total: 0, messages: [] as MessageHeader[] };
// Newest `limit` by sequence number, then reversed for display.
const start = Math.max(1, total - limit + 1);
const out: MessageHeader[] = [];
for await (const m of client.fetch(`${start}:${total}`, {
uid: true,
envelope: true,
flags: true,
bodyStructure: true,
})) {
const bs = m.bodyStructure as { childNodes?: { disposition?: string }[] } | undefined;
out.push({
uid: m.uid,
subject: m.envelope?.subject ?? "(no subject)",
from: addr(m.envelope?.from),
to: addr(m.envelope?.to),
date: m.envelope?.date ? new Date(m.envelope.date).toISOString() : null,
seen: m.flags?.has("\\Seen") ?? false,
flagged: m.flags?.has("\\Flagged") ?? false,
hasAttachments: !!bs?.childNodes?.some((c) => c.disposition === "attachment"),
});
}
return { folder, total, messages: out.reverse() };
} finally {
lock.release();
}
}),
);
export const getMessage = createServerFn({ method: "POST" })
.middleware([requireSupabaseAuth])
.validator((d: { folder: string; uid: number }) => d)
.handler(async ({ data, context }) =>
withImap(callerId(context), async (client) => {
const lock = await client.getMailboxLock(data.folder || "INBOX");
try {
const msg = await client.fetchOne(String(data.uid), { source: true }, { uid: true });
if (!msg || !msg.source) throw new Error("Message not found.");
const { simpleParser } = await import("mailparser");
const p = await simpleParser(msg.source);
// Opening a message marks it read, matching every other mail client.
await client.messageFlagsAdd(String(data.uid), ["\\Seen"], { uid: true }).catch(() => {});
return {
uid: data.uid,
subject: p.subject ?? "(no subject)",
from: p.from?.text ?? "",
to: Array.isArray(p.to) ? p.to.map((t) => t.text).join(", ") : (p.to?.text ?? ""),
cc: Array.isArray(p.cc) ? p.cc.map((t) => t.text).join(", ") : (p.cc?.text ?? ""),
date: p.date ? p.date.toISOString() : null,
text: p.text ?? "",
html: typeof p.html === "string" ? p.html : null,
messageId: p.messageId ?? null,
references: Array.isArray(p.references) ? p.references.join(" ") : (p.references ?? null),
attachments: (p.attachments ?? []).map((a) => ({
filename: a.filename ?? "attachment",
size: a.size ?? 0,
contentType: a.contentType ?? "application/octet-stream",
})),
} as MessageBody;
} finally {
lock.release();
}
}),
);
export const getAttachment = createServerFn({ method: "POST" })
.middleware([requireSupabaseAuth])
.validator((d: { folder: string; uid: number; filename: string }) => d)
.handler(async ({ data, context }) =>
withImap(callerId(context), async (client) => {
const lock = await client.getMailboxLock(data.folder || "INBOX");
try {
const msg = await client.fetchOne(String(data.uid), { source: true }, { uid: true });
if (!msg || !msg.source) throw new Error("Message not found.");
const { simpleParser } = await import("mailparser");
const p = await simpleParser(msg.source);
const found = (p.attachments ?? []).find(
(a) => (a.filename ?? "attachment") === data.filename,
);
if (!found) throw new Error("Attachment not found.");
return {
filename: data.filename,
contentType: found.contentType ?? "application/octet-stream",
base64: Buffer.from(found.content).toString("base64"),
};
} finally {
lock.release();
}
}),
);
export const sendMail = createServerFn({ method: "POST" })
.middleware([requireSupabaseAuth])
.validator(
(d: {
to: string;
cc?: string;
subject: string;
body: string;
inReplyTo?: string | null;
references?: string | null;
}) => d,
)
.handler(async ({ data, context }) => {
const uid = callerId(context);
const { settings, email, password } = await credentialsFor(uid);
if (!data.to.trim()) throw new Error("At least one recipient is required.");
const nodemailer = await import("nodemailer");
const transport = nodemailer.createTransport({
host: settings.smtp_host,
port: settings.smtp_port,
secure: settings.smtp_secure, // false = STARTTLS on 587
auth: { user: email, pass: password },
connectionTimeout: 20_000,
});
const info = await transport.sendMail({
from: email,
to: data.to,
cc: data.cc || undefined,
subject: data.subject,
text: data.body,
// Threading headers so replies land in the original conversation.
inReplyTo: data.inReplyTo || undefined,
references: data.references || undefined,
});
// Deliberately not appending a copy to the Sent folder. Hosted providers
// (Migadu, Zoho, Google, Fastmail) file SMTP-submitted mail into Sent
// themselves, so appending would show every sent message twice. If the
// chosen provider turns out not to file sent mail, add an IMAP append here.
return { ok: true, messageId: info.messageId };
});
+21
View File
@@ -17,6 +17,7 @@ import { Route as AuthenticatedStudentsRouteImport } from './routes/_authenticat
import { Route as AuthenticatedReportsRouteImport } from './routes/_authenticated/reports'
import { Route as AuthenticatedPlansRouteImport } from './routes/_authenticated/plans'
import { Route as AuthenticatedMessagesRouteImport } from './routes/_authenticated/messages'
import { Route as AuthenticatedMailRouteImport } from './routes/_authenticated/mail'
import { Route as AuthenticatedLedgerRouteImport } from './routes/_authenticated/ledger'
import { Route as AuthenticatedFormsRouteImport } from './routes/_authenticated/forms'
import { Route as AuthenticatedDashboardRouteImport } from './routes/_authenticated/dashboard'
@@ -70,6 +71,11 @@ const AuthenticatedMessagesRoute = AuthenticatedMessagesRouteImport.update({
path: '/messages',
getParentRoute: () => AuthenticatedRouteRoute,
} as any)
const AuthenticatedMailRoute = AuthenticatedMailRouteImport.update({
id: '/mail',
path: '/mail',
getParentRoute: () => AuthenticatedRouteRoute,
} as any)
const AuthenticatedLedgerRoute = AuthenticatedLedgerRouteImport.update({
id: '/ledger',
path: '/ledger',
@@ -149,6 +155,7 @@ export interface FileRoutesByFullPath {
'/dashboard': typeof AuthenticatedDashboardRoute
'/forms': typeof AuthenticatedFormsRoute
'/ledger': typeof AuthenticatedLedgerRoute
'/mail': typeof AuthenticatedMailRoute
'/messages': typeof AuthenticatedMessagesRoute
'/plans': typeof AuthenticatedPlansRoute
'/reports': typeof AuthenticatedReportsRoute
@@ -170,6 +177,7 @@ export interface FileRoutesByTo {
'/dashboard': typeof AuthenticatedDashboardRoute
'/forms': typeof AuthenticatedFormsRoute
'/ledger': typeof AuthenticatedLedgerRoute
'/mail': typeof AuthenticatedMailRoute
'/messages': typeof AuthenticatedMessagesRoute
'/plans': typeof AuthenticatedPlansRoute
'/reports': typeof AuthenticatedReportsRoute
@@ -193,6 +201,7 @@ export interface FileRoutesById {
'/_authenticated/dashboard': typeof AuthenticatedDashboardRoute
'/_authenticated/forms': typeof AuthenticatedFormsRoute
'/_authenticated/ledger': typeof AuthenticatedLedgerRoute
'/_authenticated/mail': typeof AuthenticatedMailRoute
'/_authenticated/messages': typeof AuthenticatedMessagesRoute
'/_authenticated/plans': typeof AuthenticatedPlansRoute
'/_authenticated/reports': typeof AuthenticatedReportsRoute
@@ -217,6 +226,7 @@ export interface FileRouteTypes {
| '/dashboard'
| '/forms'
| '/ledger'
| '/mail'
| '/messages'
| '/plans'
| '/reports'
@@ -238,6 +248,7 @@ export interface FileRouteTypes {
| '/dashboard'
| '/forms'
| '/ledger'
| '/mail'
| '/messages'
| '/plans'
| '/reports'
@@ -260,6 +271,7 @@ export interface FileRouteTypes {
| '/_authenticated/dashboard'
| '/_authenticated/forms'
| '/_authenticated/ledger'
| '/_authenticated/mail'
| '/_authenticated/messages'
| '/_authenticated/plans'
| '/_authenticated/reports'
@@ -338,6 +350,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedMessagesRouteImport
parentRoute: typeof AuthenticatedRouteRoute
}
'/_authenticated/mail': {
id: '/_authenticated/mail'
path: '/mail'
fullPath: '/mail'
preLoaderRoute: typeof AuthenticatedMailRouteImport
parentRoute: typeof AuthenticatedRouteRoute
}
'/_authenticated/ledger': {
id: '/_authenticated/ledger'
path: '/ledger'
@@ -470,6 +489,7 @@ interface AuthenticatedRouteRouteChildren {
AuthenticatedDashboardRoute: typeof AuthenticatedDashboardRoute
AuthenticatedFormsRoute: typeof AuthenticatedFormsRoute
AuthenticatedLedgerRoute: typeof AuthenticatedLedgerRoute
AuthenticatedMailRoute: typeof AuthenticatedMailRoute
AuthenticatedMessagesRoute: typeof AuthenticatedMessagesRoute
AuthenticatedPlansRoute: typeof AuthenticatedPlansRoute
AuthenticatedReportsRoute: typeof AuthenticatedReportsRoute
@@ -485,6 +505,7 @@ const AuthenticatedRouteRouteChildren: AuthenticatedRouteRouteChildren = {
AuthenticatedDashboardRoute: AuthenticatedDashboardRoute,
AuthenticatedFormsRoute: AuthenticatedFormsRoute,
AuthenticatedLedgerRoute: AuthenticatedLedgerRoute,
AuthenticatedMailRoute: AuthenticatedMailRoute,
AuthenticatedMessagesRoute: AuthenticatedMessagesRoute,
AuthenticatedPlansRoute: AuthenticatedPlansRoute,
AuthenticatedReportsRoute: AuthenticatedReportsRoute,
+689
View File
@@ -0,0 +1,689 @@
import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
} from "@/components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Mail,
Inbox,
Loader2,
Paperclip,
RefreshCw,
Reply,
Send,
Settings,
Trash2,
AlertTriangle,
} from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import {
getMailSetup,
getAttachment,
getMessage,
listFolders,
listMessages,
myMailboxStatus,
removeUserMailbox,
saveMailSettings,
sendMail,
setUserMailbox,
type MailSettings,
} from "@/lib/mail.functions";
export const Route = createFileRoute("/_authenticated/mail")({
head: () => ({ meta: [{ title: "Mail — School Portal" }] }),
component: MailPage,
});
const fmt = (iso: string | null) =>
iso ? new Date(iso).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" }) : "—";
function MailPage() {
const { roles } = useAuth();
const isAdmin = roles.includes("admin");
const qc = useQueryClient();
const [folder, setFolder] = useState("INBOX");
const [openUid, setOpenUid] = useState<number | null>(null);
const [composing, setComposing] = useState<null | {
to: string;
subject: string;
inReplyTo: string | null;
references: string | null;
}>(null);
const [setupOpen, setSetupOpen] = useState(false);
const status = useQuery({
queryKey: ["mail-status"],
queryFn: () => myMailboxStatus({}),
});
const folders = useQuery({
queryKey: ["mail-folders"],
enabled: !!status.data?.email,
queryFn: () => listFolders({}),
retry: false,
});
const messages = useQuery({
queryKey: ["mail-messages", folder],
enabled: !!status.data?.email,
queryFn: () => listMessages({ data: { folder, limit: 40 } }),
retry: false,
});
if (status.isLoading) {
return (
<div className="p-8 flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> Loading mail…
</div>
);
}
// Nothing set up yet: tell the admin what to do, and tell everyone else who to ask.
if (!status.data?.email) {
return (
<div className="p-8 max-w-2xl">
<h1 className="text-2xl font-semibold flex items-center gap-2">
<Mail className="h-6 w-6 text-primary" /> Mail
</h1>
<div className="bg-card border rounded-lg p-6 mt-6 space-y-3">
{!status.data?.serverConfigured ? (
<>
<div className="font-medium">The mail server isn't configured yet.</div>
<p className="text-sm text-muted-foreground">
{isAdmin
? "Enter your provider's IMAP and SMTP details, then give each staff member their mailbox login."
: "An administrator needs to set up the school mail server before you can use this page."}
</p>
</>
) : (
<>
<div className="font-medium">You don't have a mailbox yet.</div>
<p className="text-sm text-muted-foreground">
The mail server is configured, but no mailbox has been assigned to your account.
{isAdmin ? " Assign one below." : " Ask an administrator to set one up."}
</p>
</>
)}
{isAdmin && (
<Button onClick={() => setSetupOpen(true)}>
<Settings className="h-4 w-4 mr-1" /> Mail setup
</Button>
)}
</div>
{setupOpen && (
<MailSetupDialog
onClose={() => {
setSetupOpen(false);
qc.invalidateQueries({ queryKey: ["mail-status"] });
}}
/>
)}
</div>
);
}
const err = (messages.error ?? folders.error) as Error | undefined;
return (
<div className="p-6 md:p-8">
<div className="flex items-center justify-between flex-wrap gap-2">
<div>
<h1 className="text-2xl font-semibold flex items-center gap-2">
<Mail className="h-6 w-6 text-primary" /> Mail
</h1>
<p className="text-muted-foreground text-sm mt-1">{status.data.email}</p>
</div>
<div className="flex gap-2">
<Button
size="sm"
variant="outline"
onClick={() => qc.invalidateQueries({ queryKey: ["mail-messages", folder] })}
disabled={messages.isFetching}
>
<RefreshCw className={`h-4 w-4 mr-1 ${messages.isFetching ? "animate-spin" : ""}`} />{" "}
Refresh
</Button>
<Button
size="sm"
onClick={() => setComposing({ to: "", subject: "", inReplyTo: null, references: null })}
>
<Send className="h-4 w-4 mr-1" /> Compose
</Button>
{isAdmin && (
<Button size="sm" variant="ghost" onClick={() => setSetupOpen(true)}>
<Settings className="h-4 w-4" />
</Button>
)}
</div>
</div>
{err && (
<div className="mt-4 border rounded-md p-3 flex items-start gap-2 text-sm">
<AlertTriangle className="h-4 w-4 text-destructive shrink-0 mt-0.5" />
<div>
<div className="font-medium">Couldn't reach the mail server</div>
<div className="text-muted-foreground text-xs mt-0.5">{err.message}</div>
</div>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-[200px_1fr] gap-4 mt-6">
<div className="bg-card border rounded-lg p-2 h-fit">
{(folders.data ?? [{ path: "INBOX", name: "Inbox", specialUse: null }]).map((f) => (
<button
key={f.path}
onClick={() => {
setFolder(f.path);
setOpenUid(null);
}}
className={`w-full text-left px-3 py-1.5 rounded-md text-sm flex items-center gap-2 ${
folder === f.path ? "bg-primary text-primary-foreground" : "hover:bg-muted"
}`}
>
<Inbox className="h-3.5 w-3.5 shrink-0" />
<span className="truncate">{f.name}</span>
</button>
))}
</div>
<div className="min-w-0">
{messages.isLoading ? (
<div className="bg-card border rounded-lg p-6 flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> Loading messages…
</div>
) : (messages.data?.messages ?? []).length === 0 ? (
<div className="bg-card border rounded-lg p-6 text-sm text-muted-foreground">
No messages in this folder.
</div>
) : (
<div className="bg-card border rounded-lg divide-y">
{(messages.data?.messages ?? []).map((m) => (
<button
key={m.uid}
onClick={() => setOpenUid(m.uid)}
className="w-full text-left p-3 hover:bg-muted/40 flex gap-3 items-start"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className={`truncate text-sm ${m.seen ? "" : "font-semibold"}`}>
{m.from || "(unknown sender)"}
</span>
{!m.seen && (
<Badge variant="default" className="h-4 px-1 text-[10px]">
New
</Badge>
)}
{m.hasAttachments && (
<Paperclip className="h-3 w-3 text-muted-foreground shrink-0" />
)}
</div>
<div className={`truncate text-sm ${m.seen ? "text-muted-foreground" : ""}`}>
{m.subject}
</div>
</div>
<span className="text-xs text-muted-foreground shrink-0">{fmt(m.date)}</span>
</button>
))}
</div>
)}
{messages.data ? (
<p className="text-xs text-muted-foreground mt-2">
Showing {messages.data.messages.length} of {messages.data.total} in{" "}
{messages.data.folder}.
</p>
) : null}
</div>
</div>
{openUid !== null && (
<MessageDialog
folder={folder}
uid={openUid}
onClose={() => {
setOpenUid(null);
qc.invalidateQueries({ queryKey: ["mail-messages", folder] });
}}
onReply={(c) => {
setOpenUid(null);
setComposing(c);
}}
/>
)}
{composing && <ComposeDialog initial={composing} onClose={() => setComposing(null)} />}
{setupOpen && (
<MailSetupDialog
onClose={() => {
setSetupOpen(false);
qc.invalidateQueries({ queryKey: ["mail-status"] });
}}
/>
)}
</div>
);
}
function MessageDialog({
folder,
uid,
onClose,
onReply,
}: {
folder: string;
uid: number;
onClose: () => void;
onReply: (c: {
to: string;
subject: string;
inReplyTo: string | null;
references: string | null;
}) => void;
}) {
const { data, isLoading, error } = useQuery({
queryKey: ["mail-message", folder, uid],
queryFn: () => getMessage({ data: { folder, uid } }),
retry: false,
});
const download = async (filename: string) => {
try {
const a = await getAttachment({ data: { folder, uid, filename } });
const bytes = Uint8Array.from(atob(a.base64), (ch) => ch.charCodeAt(0));
const url = URL.createObjectURL(new Blob([bytes], { type: a.contentType }));
const el = document.createElement("a");
el.href = url;
el.download = a.filename;
el.click();
URL.revokeObjectURL(url);
} catch (e) {
toast.error((e as Error).message);
}
};
return (
<Dialog open onOpenChange={(o) => !o && onClose()}>
<DialogContent className="max-w-3xl max-h-[85vh] overflow-auto">
<DialogHeader>
<DialogTitle className="pr-8">{data?.subject ?? "Message"}</DialogTitle>
</DialogHeader>
{isLoading && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> Loading…
</div>
)}
{error && <p className="text-sm text-destructive">{(error as Error).message}</p>}
{data && (
<div className="space-y-3">
<div className="text-sm space-y-0.5 border-b pb-2">
<div>
<span className="text-muted-foreground">From:</span> {data.from}
</div>
<div>
<span className="text-muted-foreground">To:</span> {data.to}
</div>
{data.cc && (
<div>
<span className="text-muted-foreground">Cc:</span> {data.cc}
</div>
)}
<div className="text-xs text-muted-foreground">{fmt(data.date)}</div>
</div>
{data.attachments.length > 0 && (
<div className="flex flex-wrap gap-2">
{data.attachments.map((a) => (
<Button
key={a.filename}
size="sm"
variant="outline"
onClick={() => download(a.filename)}
>
<Paperclip className="h-3.5 w-3.5 mr-1" /> {a.filename}
<span className="text-xs text-muted-foreground ml-1">
{(a.size / 1024).toFixed(0)} KB
</span>
</Button>
))}
</div>
)}
{/* Remote HTML is deliberately not rendered — an <iframe> or
dangerouslySetInnerHTML here would execute sender-controlled
markup and leak read receipts via tracking pixels. */}
<pre className="text-sm whitespace-pre-wrap break-words font-sans">
{data.text || "(no plain-text body)"}
</pre>
{!data.text && data.html && (
<p className="text-xs text-muted-foreground">
This message is HTML-only. It is shown as text for safety.
</p>
)}
<Button
size="sm"
onClick={() =>
onReply({
to: data.from,
subject: data.subject.startsWith("Re:") ? data.subject : `Re: ${data.subject}`,
inReplyTo: data.messageId,
references: [data.references, data.messageId].filter(Boolean).join(" ") || null,
})
}
>
<Reply className="h-4 w-4 mr-1" /> Reply
</Button>
</div>
)}
</DialogContent>
</Dialog>
);
}
function ComposeDialog({
initial,
onClose,
}: {
initial: { to: string; subject: string; inReplyTo: string | null; references: string | null };
onClose: () => void;
}) {
const [to, setTo] = useState(initial.to);
const [cc, setCc] = useState("");
const [subject, setSubject] = useState(initial.subject);
const [body, setBody] = useState("");
const send = useMutation({
mutationFn: () =>
sendMail({
data: {
to,
cc,
subject,
body,
inReplyTo: initial.inReplyTo,
references: initial.references,
},
}),
onSuccess: () => {
toast.success("Message sent");
onClose();
},
onError: (e: Error) => toast.error(e.message),
});
return (
<Dialog open onOpenChange={(o) => !o && onClose()}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>{initial.inReplyTo ? "Reply" : "New message"}</DialogTitle>
</DialogHeader>
<div className="space-y-3">
<div>
<Label className="text-xs">To</Label>
<Input
value={to}
onChange={(e) => setTo(e.target.value)}
placeholder="name@example.com"
/>
</div>
<div>
<Label className="text-xs">Cc</Label>
<Input value={cc} onChange={(e) => setCc(e.target.value)} />
</div>
<div>
<Label className="text-xs">Subject</Label>
<Input value={subject} onChange={(e) => setSubject(e.target.value)} />
</div>
<div>
<Label className="text-xs">Message</Label>
<Textarea rows={10} value={body} onChange={(e) => setBody(e.target.value)} />
</div>
<div className="flex gap-2">
<Button onClick={() => send.mutate()} disabled={!to || send.isPending}>
{send.isPending ? "Sending…" : "Send"}
</Button>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
</div>
</div>
</DialogContent>
</Dialog>
);
}
// ── Admin setup: server details + per-user mailbox provisioning ──────────────
function MailSetupDialog({ onClose }: { onClose: () => void }) {
const qc = useQueryClient();
const setup = useQuery({
queryKey: ["mail-setup"],
queryFn: () => getMailSetup({}),
retry: false,
});
const [s, setS] = useState<MailSettings | null>(null);
const current: MailSettings = s ??
setup.data?.settings ?? {
imap_host: "",
imap_port: 993,
imap_secure: true,
smtp_host: "",
smtp_port: 587,
smtp_secure: false,
};
const [box, setBox] = useState({ userId: "", email: "", password: "" });
const saveSettings = useMutation({
mutationFn: () => saveMailSettings({ data: current }),
onSuccess: () => {
toast.success("Mail server saved");
qc.invalidateQueries({ queryKey: ["mail-setup"] });
qc.invalidateQueries({ queryKey: ["mail-status"] });
},
onError: (e: Error) => toast.error(e.message),
});
const assign = useMutation({
mutationFn: () => setUserMailbox({ data: box }),
onSuccess: () => {
toast.success("Mailbox verified and saved");
setBox({ userId: "", email: "", password: "" });
qc.invalidateQueries({ queryKey: ["mail-setup"] });
qc.invalidateQueries({ queryKey: ["mail-status"] });
},
onError: (e: Error) => toast.error(e.message),
});
const remove = useMutation({
mutationFn: (userId: string) => removeUserMailbox({ data: { userId } }),
onSuccess: () => {
toast.success("Mailbox removed");
qc.invalidateQueries({ queryKey: ["mail-setup"] });
qc.invalidateQueries({ queryKey: ["mail-status"] });
},
onError: (e: Error) => toast.error(e.message),
});
return (
<Dialog open onOpenChange={(o) => !o && onClose()}>
<DialogContent className="max-w-2xl max-h-[85vh] overflow-auto">
<DialogHeader>
<DialogTitle>Mail setup</DialogTitle>
<DialogDescription>
One mail server for the school, with a separate mailbox login per staff member.
</DialogDescription>
</DialogHeader>
{setup.error && (
<p className="text-sm text-destructive">{(setup.error as Error).message}</p>
)}
{setup.data && !setup.data.keyConfigured && (
<div className="border rounded-md p-3 flex items-start gap-2 text-xs">
<AlertTriangle className="h-4 w-4 text-destructive shrink-0 mt-0.5" />
<span>
<strong>MAIL_CRED_KEY is not set on the server.</strong> Mailbox passwords are sealed
with it, so assigning a mailbox will fail until it exists. Generate one with{" "}
<code>openssl rand -base64 32</code> and add it to <code>.env.secret</code>.
</span>
</div>
)}
<div className="space-y-3">
<div className="font-medium text-sm">Server</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
<div className="md:col-span-2">
<Label className="text-xs">IMAP host</Label>
<Input
value={current.imap_host}
onChange={(e) => setS({ ...current, imap_host: e.target.value })}
placeholder="imap.provider.com"
/>
</div>
<div>
<Label className="text-xs">IMAP port</Label>
<Input
inputMode="numeric"
value={String(current.imap_port)}
onChange={(e) => setS({ ...current, imap_port: Number(e.target.value) || 0 })}
/>
</div>
</div>
<div className="flex items-center justify-between max-w-sm">
<Label className="text-xs">IMAP uses TLS on connect (port 993)</Label>
<Switch
checked={current.imap_secure}
onCheckedChange={(v) => setS({ ...current, imap_secure: v })}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
<div className="md:col-span-2">
<Label className="text-xs">SMTP host</Label>
<Input
value={current.smtp_host}
onChange={(e) => setS({ ...current, smtp_host: e.target.value })}
placeholder="smtp.provider.com"
/>
</div>
<div>
<Label className="text-xs">SMTP port</Label>
<Input
inputMode="numeric"
value={String(current.smtp_port)}
onChange={(e) => setS({ ...current, smtp_port: Number(e.target.value) || 0 })}
/>
</div>
</div>
<div className="flex items-center justify-between max-w-sm">
<Label className="text-xs">SMTP uses TLS on connect (465; off = STARTTLS on 587)</Label>
<Switch
checked={current.smtp_secure}
onCheckedChange={(v) => setS({ ...current, smtp_secure: v })}
/>
</div>
<Button
size="sm"
onClick={() => saveSettings.mutate()}
disabled={!current.imap_host || !current.smtp_host || saveSettings.isPending}
>
{saveSettings.isPending ? "Saving…" : "Save server settings"}
</Button>
</div>
<div className="border-t pt-4 space-y-3">
<div className="font-medium text-sm">Mailboxes</div>
<div className="border rounded-lg divide-y">
{(setup.data?.mailboxes ?? []).map((m) => (
<div key={m.user_id} className="p-3 flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="text-sm font-medium truncate">{m.full_name || m.email}</div>
<div className="text-xs text-muted-foreground truncate">
{m.email}
{m.last_verified_at ? ` · verified ${fmt(m.last_verified_at)}` : ""}
</div>
</div>
<Button
size="sm"
variant="ghost"
onClick={() => {
if (
confirm(
`Remove the mailbox for ${m.email}? Their mail is not deleted — the portal just stops connecting to it.`,
)
)
remove.mutate(m.user_id);
}}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
))}
{(setup.data?.mailboxes ?? []).length === 0 && (
<div className="p-3 text-sm text-muted-foreground">No mailboxes assigned yet.</div>
)}
</div>
<div className="border rounded-md p-3 space-y-2">
<div className="text-sm font-medium">Assign a mailbox</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-2">
<Select value={box.userId} onValueChange={(v) => setBox({ ...box, userId: v })}>
<SelectTrigger>
<SelectValue placeholder="Staff member" />
</SelectTrigger>
<SelectContent>
{(setup.data?.staff ?? []).map((u) => (
<SelectItem key={u.id} value={u.id}>
{u.full_name || u.email}
</SelectItem>
))}
</SelectContent>
</Select>
<Input
placeholder="mailbox@school.org"
value={box.email}
onChange={(e) => setBox({ ...box, email: e.target.value })}
/>
<Input
type="password"
placeholder="Mailbox password"
value={box.password}
onChange={(e) => setBox({ ...box, password: e.target.value })}
/>
</div>
<p className="text-xs text-muted-foreground">
The password is checked against the IMAP server before it is stored, then sealed with
AES-256-GCM. It is never sent back to any browser, including yours.
</p>
<Button
size="sm"
onClick={() => assign.mutate()}
disabled={!box.userId || !box.email || !box.password || assign.isPending}
>
{assign.isPending ? "Verifying…" : "Verify & save mailbox"}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
);
}
+2 -1
View File
@@ -4,7 +4,7 @@ import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import {
GraduationCap, LayoutDashboard, Users, ClipboardCheck, Receipt,
MessageSquare, FileText, CalendarDays, Settings, LogOut, Loader2, BookOpen, ClipboardList, Printer
MessageSquare, FileText, CalendarDays, Settings, LogOut, Loader2, BookOpen, ClipboardList, Printer, Mail
} from "lucide-react";
import { useEffect } from "react";
@@ -38,6 +38,7 @@ function ProtectedLayout() {
{ to: "/reports", label: "Reports", icon: Printer, show: isAdmin || roles.includes("teacher") },
{ to: "/ledger", label: "Tuition", icon: Receipt, show: true },
{ to: "/messages", label: "Messages", icon: MessageSquare, show: true },
{ to: "/mail", label: "Mail", icon: Mail, show: isAdmin || roles.includes("teacher") },
{ to: "/forms", label: "Forms", icon: FileText, show: true },
{ to: "/calendar", label: "Calendar", icon: CalendarDays, show: true },
{ to: "/admin", label: "Admin", icon: Settings, show: isAdmin },