Skip to content

Email for professionals and teams

Added Drive

Hieu Nguyen (Jack)9f66e13560b7
diff --git a/README.md b/README.md
index 9e1f379..d75ffaa 100644
--- a/README.md
+++ b/README.md
@@ -139,7 +139,7 @@ The Node/Docker runtime still uses Next.js with `build:node`, `start:node`, and
Everyone can switch language from the homepage or sign-in page, and signed-in users can set it under **Settings → Account → General**, next to their time zone. The choice is kept in a cookie, so server-rendered pages use it too.
-To add a language, create a catalog next to `src/lib/i18n/en.json` with the same keys, then register it in `src/lib/i18n/locales.ts` with its native name (add `dir: "rtl"` for right-to-left scripts). The selector, validation, and cookie handling pick it up from that registry. Missing keys fall back to English. English ships in the main bundle; other catalogs load on demand.
+To add a language, create `public/locales/<code>.json` with the same keys as `src/lib/i18n/en.json`, then register it in `src/lib/i18n/locales.ts` with its native name (add `dir: "rtl"` for right-to-left scripts). The selector, validation, and cookie handling pick it up from that registry. Missing keys fall back to English. English ships in the main bundle; other catalogs are static assets loaded on demand, outside the Worker size limit.
## Documentation
diff --git a/docs/localization.md b/docs/localization.md
index 27c4d0f..aafc770 100644
--- a/docs/localization.md
+++ b/docs/localization.md
@@ -22,19 +22,19 @@ The root layout reads the cookie with `await cookies()`, validates it against th
## Adding translations
-Catalogs are flat JSON objects in `src/lib/i18n/`. English (`en.json`) defines `TranslationKey` and `Messages`; registered catalogs must contain all English keys with string values (plural variants may add categories). Add new English keys and update registered translations together. `translate()` retains a per-key English fallback.
+Catalogs are flat JSON objects. English (`src/lib/i18n/en.json`) is bundled and defines `TranslationKey` and `Messages`; registered catalogs must contain all English keys with string values (plural variants may add categories). Add new English keys and update registered translations together. `translate()` retains a per-key English fallback.
To add another language:
-1. Copy `en.json` to a new catalog, for example `es.json`, and translate its values without changing the keys.
-2. Register it in `src/lib/i18n/locales.ts` with its BCP 47 locale code, native display name and a lazy loader:
+1. Copy `src/lib/i18n/en.json` to `public/locales/<code>.json`, for example `public/locales/es.json`, and translate its values without changing the keys.
+2. Register it in `src/lib/i18n/locales.ts` with its BCP 47 locale code and native display name:
```ts
// Inside locales:
- es: { label: "Español", load: async () => (await import("./es.json")).default },
+ es: { label: "Español" },
```
-That is the only registration point. The `Locale` type, supported-locale validation, cookie handling, server-rendered HTML and selector options all derive from it. No provider, layout, selector or utility changes are needed. English remains the default. For a right-to-left language add `dir: "rtl"` to the entry; the layout and provider then set `<html dir>`. English ships in the main bundle; every other catalog loads on demand. Locale-specific date formatting is not part of this system.
+That is the only registration point. The `Locale` type, supported-locale validation, cookie handling, server-rendered HTML and selector options all derive from it. No provider, layout, selector or utility changes are needed. English remains the default. For a right-to-left language add `dir: "rtl"` to the entry; the layout and provider then set `<html dir>`. English ships in the main bundle; every other catalog is a static asset loaded on demand (the browser fetches `/locales/<code>.json`, server rendering reads it through the `ASSETS` binding), so catalogs do not count toward the Worker's 3 MiB Free-plan size limit. Locale-specific date formatting is not part of this system.
Client components use `useLanguage().t(key, vars?)`; server code uses `createTranslator(locale)` from `src/lib/i18n/utils.ts`, which returns the same function. Strings interpolate `{name}` placeholders from `vars`. For plurals, add `key.one`, `key.other` (and any other CLDR categories the language needs, such as `few` for Polish, Ukrainian and Arabic) to the catalog, then call `t("key", { count })`; the variant is picked with `Intl.PluralRules`, falling back to the bare key. The dialog close button uses the translated `navigation.close` automatically.
diff --git a/drizzle/migrations/0055_add_drive.sql b/drizzle/migrations/0055_add_drive.sql
new file mode 100644
index 0000000..9c465ec
--- /dev/null
+++ b/drizzle/migrations/0055_add_drive.sql
@@ -0,0 +1,33 @@
+CREATE TABLE `drive_items` (
+ `id` text PRIMARY KEY NOT NULL,
+ `owner_id` text NOT NULL,
+ `parent_id` text,
+ `kind` text NOT NULL,
+ `name` text NOT NULL,
+ `r2_key` text,
+ `size` integer DEFAULT 0 NOT NULL,
+ `content_type` text DEFAULT 'application/octet-stream' NOT NULL,
+ `link_token` text,
+ `trashed_at` integer,
+ `created_at` integer NOT NULL,
+ `updated_at` integer NOT NULL,
+ FOREIGN KEY (`owner_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE INDEX `drive_items_owner_parent_idx` ON `drive_items` (`owner_id`,`parent_id`);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `drive_items_link_token_idx` ON `drive_items` (`link_token`);
+--> statement-breakpoint
+CREATE TABLE `drive_shares` (
+ `id` text PRIMARY KEY NOT NULL,
+ `item_id` text NOT NULL,
+ `user_id` text NOT NULL,
+ `role` text DEFAULT 'view' NOT NULL,
+ `created_at` integer NOT NULL,
+ FOREIGN KEY (`item_id`) REFERENCES `drive_items`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `drive_shares_item_user_idx` ON `drive_shares` (`item_id`,`user_id`);
+--> statement-breakpoint
+CREATE INDEX `drive_shares_user_idx` ON `drive_shares` (`user_id`);
diff --git a/drizzle/migrations/0056_add_drive_upload_id.sql b/drizzle/migrations/0056_add_drive_upload_id.sql
new file mode 100644
index 0000000..53a7561
--- /dev/null
+++ b/drizzle/migrations/0056_add_drive_upload_id.sql
@@ -0,0 +1 @@
+ALTER TABLE `drive_items` ADD `upload_id` text;
diff --git a/drizzle/migrations/0057_add_drive_resumable_uploads.sql b/drizzle/migrations/0057_add_drive_resumable_uploads.sql
new file mode 100644
index 0000000..551f4fc
--- /dev/null
+++ b/drizzle/migrations/0057_add_drive_resumable_uploads.sql
@@ -0,0 +1,12 @@
+ALTER TABLE `drive_items` ADD `upload_part_size` integer;
+--> statement-breakpoint
+ALTER TABLE `drive_items` ADD `upload_fingerprint` text;
+--> statement-breakpoint
+CREATE TABLE `drive_upload_parts` (
+ `item_id` text NOT NULL,
+ `part_number` integer NOT NULL,
+ `etag` text NOT NULL,
+ FOREIGN KEY (`item_id`) REFERENCES `drive_items`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `drive_upload_parts_idx` ON `drive_upload_parts` (`item_id`,`part_number`);
diff --git a/drizzle/migrations/0058_add_drive_storage_limit.sql b/drizzle/migrations/0058_add_drive_storage_limit.sql
new file mode 100644
index 0000000..f291542
--- /dev/null
+++ b/drizzle/migrations/0058_add_drive_storage_limit.sql
@@ -0,0 +1 @@
+ALTER TABLE `app_settings` ADD `drive_storage_limit_bytes` integer;
diff --git a/drizzle/migrations/0059_add_attachment_trash.sql b/drizzle/migrations/0059_add_attachment_trash.sql
new file mode 100644
index 0000000..f2f785b
--- /dev/null
+++ b/drizzle/migrations/0059_add_attachment_trash.sql
@@ -0,0 +1 @@
+ALTER TABLE `message_attachments` ADD `trashed_at` integer;
diff --git a/drizzle/migrations/0060_add_license_seat_limit.sql b/drizzle/migrations/0060_add_license_seat_limit.sql
new file mode 100644
index 0000000..47064cd
--- /dev/null
+++ b/drizzle/migrations/0060_add_license_seat_limit.sql
@@ -0,0 +1 @@
+ALTER TABLE `license_settings` ADD `seat_limit` integer DEFAULT 1;
diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.json
index aa06754..809aecb 100644
--- a/drizzle/migrations/meta/_journal.json
+++ b/drizzle/migrations/meta/_journal.json
@@ -330,6 +330,48 @@
"when": 1788850800018,
"tag": "0054_add_push_subscriptions",
"breakpoints": true
+ },
+ {
+ "idx": 47,
+ "version": "6",
+ "when": 1788850800019,
+ "tag": "0055_add_drive",
+ "breakpoints": true
+ },
+ {
+ "idx": 48,
+ "version": "6",
+ "when": 1788850800020,
+ "tag": "0056_add_drive_upload_id",
+ "breakpoints": true
+ },
+ {
+ "idx": 49,
+ "version": "6",
+ "when": 1788850800021,
+ "tag": "0057_add_drive_resumable_uploads",
+ "breakpoints": true
+ },
+ {
+ "idx": 50,
+ "version": "6",
+ "when": 1788850800022,
+ "tag": "0058_add_drive_storage_limit",
+ "breakpoints": true
+ },
+ {
+ "idx": 51,
+ "version": "6",
+ "when": 1788850800023,
+ "tag": "0059_add_attachment_trash",
+ "breakpoints": true
+ },
+ {
+ "idx": 52,
+ "version": "6",
+ "when": 1788850801023,
+ "tag": "0060_add_license_seat_limit",
+ "breakpoints": true
}
]
}
diff --git a/server/runtime/file-bucket.ts b/server/runtime/file-bucket.ts
index 7d78a9f..34ac6a4 100644
--- a/server/runtime/file-bucket.ts
+++ b/server/runtime/file-bucket.ts
@@ -1,12 +1,14 @@
-import { createReadStream } from "node:fs";
+import { randomUUID } from "node:crypto";
+import { createReadStream, createWriteStream } from "node:fs";
import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import { dirname, join, resolve, sep } from "node:path";
import { Readable } from "node:stream";
+import { pipeline } from "node:stream/promises";
/**
* The R2 bucket API over a directory. Objects are files under `root`; the
* HTTP and custom metadata R2 would keep ride in a `.meta.json` sidecar.
- * Covers what the app uses: get (with a byte range), put, delete, head.
+ * Covers what the app uses: get (with a byte range), put, delete, head, and multipart uploads.
*/
type StoredMeta = {
httpMetadata?: { contentType?: string; contentDisposition?: string; cacheControl?: string };
@@ -150,6 +152,50 @@ export class FileBucket {
return new FileObject(key, path, meta);
}
+ private multipartDirectory(uploadId: string) {
+ if (!/^[\w-]+$/.test(uploadId)) throw new Error("Invalid multipart upload id");
+ return join(this.root, ".multipart", uploadId);
+ }
+
+ async createMultipartUpload(key: string, options?: { httpMetadata?: StoredMeta["httpMetadata"] }) {
+ const uploadId = randomUUID();
+ await mkdir(this.multipartDirectory(uploadId), { recursive: true });
+ await writeFile(join(this.multipartDirectory(uploadId), "meta.json"), JSON.stringify(options?.httpMetadata ?? {}));
+ return this.resumeMultipartUpload(key, uploadId);
+ }
+
+ resumeMultipartUpload(key: string, uploadId: string) {
+ const directory = this.multipartDirectory(uploadId);
+ const partPath = (partNumber: number) => join(directory, `part-${partNumber}`);
+ return {
+ key,
+ uploadId,
+ uploadPart: async (partNumber: number, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | Blob) => {
+ if (!Number.isInteger(partNumber) || partNumber < 1) throw new Error("Invalid part number");
+ const source = value instanceof ReadableStream ? Readable.fromWeb(value as never) : Readable.from(Buffer.from(value instanceof Blob ? await value.arrayBuffer() : typeof value === "string" ? value : value instanceof ArrayBuffer ? value : (value as ArrayBufferView).buffer));
+ await pipeline(source, createWriteStream(partPath(partNumber)));
+ const { size } = await stat(partPath(partNumber));
+ return { partNumber, etag: `${partNumber}-${size.toString(16)}` };
+ },
+ abort: async () => { await rm(directory, { recursive: true, force: true }); },
+ complete: async (parts: { partNumber: number; etag: string }[]) => {
+ const path = this.pathFor(key);
+ await mkdir(dirname(path), { recursive: true });
+ const out = createWriteStream(path);
+ try {
+ for (const part of [...parts].sort((a, b) => a.partNumber - b.partNumber)) await pipeline(createReadStream(partPath(part.partNumber)), out, { end: false });
+ } finally { out.end(); }
+ await new Promise<void>((done) => out.once("close", () => done()));
+ const httpMetadata = JSON.parse(await readFile(join(directory, "meta.json"), "utf8")) as StoredMeta["httpMetadata"];
+ const { size } = await stat(path);
+ const meta: StoredMeta = { httpMetadata, size, uploaded: new Date().toISOString(), etag: `${Date.now().toString(16)}-${size.toString(16)}` };
+ await writeFile(`${path}.meta.json`, JSON.stringify(meta));
+ await rm(directory, { recursive: true, force: true });
+ return new FileObject(key, path, meta);
+ },
+ };
+ }
+
async delete(keys: string | string[]) {
for (const key of Array.isArray(keys) ? keys : [keys]) {
const path = this.pathFor(key);
diff --git a/server/runtime/scheduler.ts b/server/runtime/scheduler.ts
index f8232fc..dd72cfc 100644
--- a/server/runtime/scheduler.ts
+++ b/server/runtime/scheduler.ts
@@ -1,6 +1,7 @@
import { runScheduledDatabaseBackup } from "@/lib/backups/runner";
import { runAgentMaintenance } from "@/lib/agent/maintenance";
import { runTrashRetention } from "@/lib/email/trash-retention";
+import { runDriveTrashRetention } from "@/lib/drive/retention";
/** Fire the daily 02:00 UTC backup and the recurring maintenance jobs, matching the cron triggers in wrangler.jsonc. */
export function startScheduler(env: CloudflareEnv) {
@@ -13,6 +14,7 @@ export function startScheduler(env: CloudflareEnv) {
if (now.getUTCHours() !== 2 || lastRunDay === day) return;
lastRunDay = day;
runScheduledDatabaseBackup(env, now).catch((error) => console.error("Scheduled backup failed", error));
+ runDriveTrashRetention(env, now).catch((error) => console.error("Drive trash retention failed", error));
}, 60_000);
return () => clearInterval(timer);
}
diff --git a/src/app/(admin)/accounts/page.tsx b/src/app/(admin)/accounts/page.tsx
index 33a1f5b..6c00875 100644
--- a/src/app/(admin)/accounts/page.tsx
+++ b/src/app/(admin)/accounts/page.tsx
@@ -20,11 +20,11 @@ import { defaultTranslator } from "@/lib/i18n/utils";
import { AccountAliases } from "./account-aliases";
import type { Account, AccountAliasDraft, AccountResponse, Domain } from "./types";
-async function fetchAccounts(): Promise<Account[]> {
+async function fetchAccounts(): Promise<AccountResponse> {
const response = await authFetch("/api/accounts");
const data = (await response.json()) as AccountResponse;
if (!response.ok) throw new Error(data.error ?? defaultTranslator("accounts.loadFailed"));
- return data.accounts ?? [];
+ return data;
}
export default function AccountsPage() {
@@ -44,15 +44,19 @@ export default function AccountsPage() {
const [saving, setSaving] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
const [message, setMessage] = useState<string | null>(null);
+ const [seats, setSeats] = useState<AccountResponse["seats"] | null>(null);
const [teamRequired, setTeamRequired] = useState(false);
async function loadAccounts() {
- setAccounts(await fetchAccounts());
+ const data = await fetchAccounts();
+ setAccounts(data.accounts ?? []);
+ setSeats(data.seats ?? null);
}
useEffect(() => {
- fetchAccounts().then(async (accounts) => {
- setAccounts(accounts);
+ fetchAccounts().then(async (list) => {
+ setAccounts(list.accounts ?? []);
+ setSeats(list.seats ?? null);
const response = await authFetch("/api/domains");
const data = (await response.json()) as { domains?: Domain[]; error?: string };
if (!response.ok) throw new Error(data.error ?? t("accounts.domainsFailed"));
@@ -60,7 +64,7 @@ export default function AccountsPage() {
setDomainId(data.domains?.[0]?.id ?? "");
}).catch((error) => {
const text = error instanceof Error ? error.message : t("accounts.loadFailed");
- setTeamRequired(/team license/i.test(text));
+ setTeamRequired(/(pro|team) license/i.test(text) && !/seats/i.test(text));
setMessage(text);
}).finally(() => setLoading(false));
}, []);
@@ -90,9 +94,11 @@ export default function AccountsPage() {
}
}
+ const seatsFull = !!seats && seats.limit !== null && seats.used >= seats.limit;
+
return <div className="space-y-6">
- <div className="flex items-center justify-between gap-4"><div><h1 className="text-2xl md:text-3xl font-medium text-neutral-900">{t("accounts.title")}</h1><p className="mt-2 text-sm text-neutral-500">{t("accounts.description")}</p></div>{!teamRequired && canManage && <Button className={mobilePrimaryActionClass} onClick={() => setCreateOpen(true)}><Plus className="h-4 w-4" />{t("accounts.new")}</Button>}</div>
- <div className="relative">{teamRequired && <LicenseRequiredOverlay required="Team"><div className="min-h-48 rounded-3xl bg-white" /></LicenseRequiredOverlay>}<List>
+ <div className="flex items-center justify-between gap-4"><div><h1 className="text-2xl md:text-3xl font-medium text-neutral-900">{t("accounts.title")}</h1><p className="mt-2 text-sm text-neutral-500">{t("accounts.description")}</p>{seats && seats.limit !== null && <p className={`mt-1 text-sm ${seatsFull ? "text-amber-700" : "text-neutral-500"}`}>{t("accounts.seatsUsed", { used: seats.used, limit: seats.limit })}{seatsFull ? ` ${t("accounts.seatsFull")}` : ""}</p>}</div>{!teamRequired && canManage && <Button disabled={seatsFull} className={mobilePrimaryActionClass} onClick={() => setCreateOpen(true)}><Plus className="h-4 w-4" />{t("accounts.new")}</Button>}</div>
+ <div className="relative">{teamRequired && <LicenseRequiredOverlay required="Pro or Team"><div className="min-h-48 rounded-3xl bg-white" /></LicenseRequiredOverlay>}<List>
{loading && <p className="text-sm text-neutral-500">{t("common.loading")}</p>}
{accounts.map((account) => {
const locked = !currentUser?.isPrimaryAdmin && account.role === "admin" && account.id !== currentUser?.id;
diff --git a/src/app/(admin)/accounts/types.d.ts b/src/app/(admin)/accounts/types.d.ts
index ac36553..12f372c 100644
--- a/src/app/(admin)/accounts/types.d.ts
+++ b/src/app/(admin)/accounts/types.d.ts
@@ -40,6 +40,7 @@ export type Account = {
export type AccountResponse = {
accounts?: Account[];
+ seats?: { limit: number | null; used: number };
account?: Account;
error?: string;
};
diff --git a/src/app/(admin)/branding/page.tsx b/src/app/(admin)/branding/page.tsx
index 70458d6..18acead 100644
--- a/src/app/(admin)/branding/page.tsx
+++ b/src/app/(admin)/branding/page.tsx
@@ -1,7 +1,8 @@
"use client";
import { useEffect, useRef, useState } from "react";
-import { ExternalLink, ImagePlus, LockKeyhole, Palette } from "lucide-react";
+import Link from "next/link";
+import { ArrowRight, ExternalLink, ImagePlus, LockKeyhole, Palette } from "lucide-react";
import { useLanguage } from "@/components/language-provider";
import { useBranding } from "@/components/branding-provider";
import { Button } from "@/components/ui/button";
@@ -37,8 +38,9 @@ export default function BrandingPage() {
<CardDescription>{t("branding.originalNote")}</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3 pt-6 sm:flex-row">
- <Button asChild><a href="https://app.paymug.co/buy/mailflare-pro" target="_blank" rel="noopener noreferrer">{t("branding.buyPro")} <ExternalLink className="h-4 w-4" /></a></Button>
- <Button asChild variant="outline"><a href="https://app.paymug.co/buy/mailflare-team" target="_blank" rel="noopener noreferrer">{t("branding.buyTeam")} <ExternalLink className="h-4 w-4" /></a></Button>
+ <Button asChild>
+ <Link href="/licenses">{t("license.view")}</Link>
+ </Button>
</CardContent>
</Card>
</div>
diff --git a/src/app/(admin)/general/page.tsx b/src/app/(admin)/general/page.tsx
index 9a9b6ec..761abbe 100644
--- a/src/app/(admin)/general/page.tsx
+++ b/src/app/(admin)/general/page.tsx
@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { Switch } from "@/components/ui/switch";
import { loadGeneralSettings, saveGeneralSettings } from "./utils";
export default function GeneralSettingsPage() {
@@ -14,11 +15,15 @@ export default function GeneralSettingsPage() {
const [loaded, setLoaded] = useState(false);
const [saving, setSaving] = useState(false);
const [status, setStatus] = useState("");
+ const [unlimited, setUnlimited] = useState(true);
+ const [limitGb, setLimitGb] = useState(10);
+ const [driveSaving, setDriveSaving] = useState(false);
+ const [driveStatus, setDriveStatus] = useState("");
useEffect(() => {
let active = true;
void loadGeneralSettings().then((settings) => {
- if (active) { setMaxMb(settings.outboundAttachmentMaxMb); setLoaded(true); }
+ if (active) { setMaxMb(settings.outboundAttachmentMaxMb); setUnlimited(settings.driveStorageLimitGb === null); if (settings.driveStorageLimitGb !== null) setLimitGb(settings.driveStorageLimitGb); setLoaded(true); }
}).catch((error) => { if (active) setStatus(error instanceof Error ? error.message : t("general.loadFailed")); });
return () => { active = false; };
}, [t]);
@@ -28,7 +33,7 @@ export default function GeneralSettingsPage() {
setSaving(true);
setStatus("");
try {
- const settings = await saveGeneralSettings(maxMb);
+ const settings = await saveGeneralSettings({ outboundAttachmentMaxMb: maxMb });
setMaxMb(settings.outboundAttachmentMaxMb);
setStatus(t("general.saved"));
} catch (error) {
@@ -36,6 +41,20 @@ export default function GeneralSettingsPage() {
} finally { setSaving(false); }
}
+ async function saveDrive(event: React.FormEvent<HTMLFormElement>) {
+ event.preventDefault();
+ setDriveSaving(true);
+ setDriveStatus("");
+ try {
+ const settings = await saveGeneralSettings({ driveStorageLimitGb: unlimited ? null : limitGb });
+ setUnlimited(settings.driveStorageLimitGb === null);
+ if (settings.driveStorageLimitGb !== null) setLimitGb(settings.driveStorageLimitGb);
+ setDriveStatus(t("general.driveSaved"));
+ } catch (error) {
+ setDriveStatus(error instanceof Error ? error.message : t("general.saveFailed"));
+ } finally { setDriveSaving(false); }
+ }
+
return <div className="space-y-6">
<div><h1 className="text-2xl md:text-3xl font-medium text-neutral-900">{t("general.title")}</h1><p className="mt-2 text-sm text-neutral-500">{t("general.description")}</p></div>
<Card className="rounded-3xl border-0 bg-white p-6">
@@ -47,5 +66,15 @@ export default function GeneralSettingsPage() {
<Button type="submit" disabled={!loaded || saving || !Number.isInteger(maxMb) || maxMb < 1 || maxMb > 25}>{saving ? t("common.saving") : t("general.save")}</Button>
</form></CardContent>
</Card>
+ <Card className="rounded-3xl border-0 bg-white p-6">
+ <CardHeader className="py-0"><CardTitle>{t("general.drive")}</CardTitle></CardHeader>
+ <CardContent className="pt-6"><form onSubmit={saveDrive} className="space-y-4">
+ <div className="flex items-center gap-3"><Switch id="drive-unlimited" checked={unlimited} onCheckedChange={setUnlimited} disabled={!loaded || driveSaving} /><Label htmlFor="drive-unlimited">{t("general.driveUnlimited")}</Label></div>
+ {!unlimited && <div className="space-y-2"><Label htmlFor="drive-limit">{t("general.driveLimit")}</Label><Input id="drive-limit" type="number" min="0.01" max="1000000" step="any" value={limitGb} onChange={(event) => setLimitGb(Number(event.target.value))} disabled={!loaded || driveSaving} className="max-w-40" required /></div>}
+ <p className="text-sm text-neutral-500">{t("general.driveHint")}</p>
+ {driveStatus && <p role="status" className="text-sm text-neutral-700">{driveStatus}</p>}
+ <Button type="submit" disabled={!loaded || driveSaving || (!unlimited && !(limitGb > 0))}>{driveSaving ? t("common.saving") : t("general.save")}</Button>
+ </form></CardContent>
+ </Card>
</div>;
}
diff --git a/src/app/(admin)/general/types.d.ts b/src/app/(admin)/general/types.d.ts
index fd8fb06..928df51 100644
--- a/src/app/(admin)/general/types.d.ts
+++ b/src/app/(admin)/general/types.d.ts
@@ -1,3 +1,5 @@
export interface GeneralSettings {
outboundAttachmentMaxMb: number;
+ /** Per-user Drive cap in GB; null when unlimited. */
+ driveStorageLimitGb: number | null;
}
diff --git a/src/app/(admin)/general/utils.ts b/src/app/(admin)/general/utils.ts
index e0e39cc..8a49722 100644
--- a/src/app/(admin)/general/utils.ts
+++ b/src/app/(admin)/general/utils.ts
@@ -8,11 +8,11 @@ export async function loadGeneralSettings(): Promise<GeneralSettings> {
return data as GeneralSettings;
}
-export async function saveGeneralSettings(outboundAttachmentMaxMb: number): Promise<GeneralSettings> {
+export async function saveGeneralSettings(changes: Partial<GeneralSettings>): Promise<GeneralSettings> {
const response = await authFetch("/api/admin/general", {
method: "PUT",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ outboundAttachmentMaxMb }),
+ body: JSON.stringify(changes),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error ?? "Could not save general settings");
diff --git a/src/app/(admin)/licenses/license-activation.tsx b/src/app/(admin)/licenses/license-activation.tsx
index 5a8e38e..e6fc06f 100644
--- a/src/app/(admin)/licenses/license-activation.tsx
+++ b/src/app/(admin)/licenses/license-activation.tsx
@@ -84,6 +84,7 @@ export function LicenseActivation({ children }: { children?: ReactNode }) {
<p className="mt-2 text-sm leading-6 text-neutral-600">
{t("licenses.activatedBody", { plan: formatLicensePlan(license.plan, t) })}
</p>
+ <p className="mt-1 text-sm text-neutral-500">{license.seatLimit === null ? t("licenses.seatsUnlimited") : t("licenses.seats", { limit: license.seatLimit })}</p>
<Button type="button" variant="outline" className="mt-5" onClick={() => void submit("deactivate")} disabled={action !== null}>
{action === "deactivate" ? t("licenses.deactivating") : t("licenses.deactivate")}
</Button>
diff --git a/src/app/(calendar)/booking/page.tsx b/src/app/(calendar)/booking/page.tsx
index 3b9ee8b..1ee2b26 100644
--- a/src/app/(calendar)/booking/page.tsx
+++ b/src/app/(calendar)/booking/page.tsx
@@ -112,7 +112,7 @@ export default function BookingsPage() {
}
return <div className={clsx("flex h-full min-h-0 flex-col bg-[#f6f8fc] pl-3 max-md:pl-0 transition-[gap] duration-200 ease-in-out motion-reduce:transition-none lg:flex-row", minimal ? "gap-0" : "gap-3")}>
- <Toaster position="bottom-right" />
+ <Toaster position="bottom-left" />
{loading && <RouteLoadingBarPortal />}
<UpcomingSidebar />
<section className="min-h-0 min-w-0 flex-1 overflow-hidden overscroll-contain max-md:rounded-t-3xl max-md:bg-white">
diff --git a/src/app/(calendar)/calendar/page.tsx b/src/app/(calendar)/calendar/page.tsx
index 5c4a14f..6fa9504 100644
--- a/src/app/(calendar)/calendar/page.tsx
+++ b/src/app/(calendar)/calendar/page.tsx
@@ -384,7 +384,7 @@ export default function CalendarPage() {
return (
<div className={clsx("flex h-full min-h-0 flex-col bg-[#f6f8fc] pl-3 max-md:pl-0 lg:flex-row transition-[gap] duration-200 ease-in-out motion-reduce:transition-none", minimal ? "gap-0" : "gap-3")}>
- <Toaster position="bottom-right" />
+ <Toaster position="bottom-left" />
{loading && <RouteLoadingBarPortal />}
{headerTarget && createPortal(
<div className="flex min-w-0 flex-1 items-center justify-between gap-3 ">
diff --git a/src/app/(drive)/drive-bulk-actions.tsx b/src/app/(drive)/drive-bulk-actions.tsx
new file mode 100644
index 0000000..e0a4d7c
--- /dev/null
+++ b/src/app/(drive)/drive-bulk-actions.tsx
@@ -0,0 +1,169 @@
+"use client";
+
+import { useMemo, useRef, useState } from "react";
+import toast from "react-hot-toast";
+import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
+import clsx from "clsx";
+import { Folder, FolderInput, FolderPlus, HardDrive, RotateCcw, Trash2, X } from "lucide-react";
+import { useLanguage } from "@/components/language-provider";
+import { Button } from "@/components/ui/button";
+import { authFetch } from "@/lib/auth/client";
+import type { DriveItemDto } from "@/lib/drive/types";
+
+type FolderNode = { id: string; name: string; parentId: string | null };
+type FolderRow = FolderNode & { depth: number; disabled: boolean };
+
+export async function bulk(body: Record<string, unknown>, fallback: string): Promise<number | null> {
+ try {
+ const response = await authFetch("/api/drive/items/bulk", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+ const data = await response.json().catch(() => ({})) as { count?: number; error?: string };
+ if (!response.ok) throw new Error(data.error);
+ return data.count ?? 0;
+ } catch (error) {
+ toast.error(error instanceof Error && error.message ? error.message : fallback);
+ return null;
+ }
+}
+
+export async function attachmentAction(action: "trash" | "restore" | "delete", ids: string[], fallback: string): Promise<number | null> {
+ try {
+ const response = await authFetch("/api/drive/attachments", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action, ids }) });
+ const data = await response.json().catch(() => ({})) as { count?: number; error?: string };
+ if (!response.ok) throw new Error(data.error);
+ return data.count ?? 0;
+ } catch (error) {
+ toast.error(error instanceof Error && error.message ? error.message : fallback);
+ return null;
+ }
+}
+
+/** Flattens the folder list depth-first. Folders being moved, and everything beneath them, cannot be targets. */
+function buildRows(folders: FolderNode[], moving: Set<string>): FolderRow[] {
+ const children = new Map<string | null, FolderNode[]>();
+ const known = new Set(folders.map((folder) => folder.id));
+ for (const folder of folders) {
+ const key = folder.parentId && known.has(folder.parentId) ? folder.parentId : null;
+ children.set(key, [...(children.get(key) ?? []), folder]);
+ }
+ const rows: FolderRow[] = [];
+ const visit = (parent: string | null, depth: number, blocked: boolean) => {
+ for (const folder of (children.get(parent) ?? []).sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }))) {
+ const disabled = blocked || moving.has(folder.id);
+ rows.push({ ...folder, depth, disabled });
+ visit(folder.id, depth + 1, disabled);
+ }
+ };
+ visit(null, 0, false);
+ return rows;
+}
+
+export function DriveBulkActions({ selected, trashView, onDone }: { selected: DriveItemDto[]; trashView: boolean; onDone: () => void }) {
+ const { t } = useLanguage();
+ const [folders, setFolders] = useState<FolderNode[] | null>(null);
+ const [name, setName] = useState("");
+ const [busy, setBusy] = useState(false);
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const ids = useMemo(() => selected.map((item) => item.id), [selected]);
+ const rows = useMemo(() => buildRows(folders ?? [], new Set(ids)), [folders, ids]);
+ const driveIds = useMemo(() => selected.filter((item) => !item.source).map((item) => item.id), [selected]);
+ const attachmentIds = useMemo(() => selected.filter((item) => item.source).map((item) => item.id), [selected]);
+ // Editors can trash what is shared with them; moving, restoring and deleting forever are for the owner.
+ const driveItems = selected.filter((item) => !item.source);
+ const ownsAll = driveItems.every((item) => item.role === "owner");
+ const canTrash = driveItems.every((item) => item.role === "owner" || item.role === "edit");
+ const count = selected.length;
+
+ async function run(task: () => Promise<number | null>, message: (count: number) => string) {
+ setBusy(true);
+ const done = await task();
+ setBusy(false);
+ if (done === null) return;
+ toast.success(message(done));
+ onDone();
+ }
+
+ /** Applies a trash action to the Drive items and the email attachments in the selection. */
+ async function act(action: "trash" | "restore" | "delete"): Promise<number | null> {
+ let total = 0;
+ if (driveIds.length) {
+ const done = await bulk({ action, ids: driveIds }, t("drive.actionFailed"));
+ if (done === null) return null;
+ total += done;
+ }
+ if (attachmentIds.length) {
+ const done = await attachmentAction(action, attachmentIds, t("drive.actionFailed"));
+ if (done === null) return null;
+ total += done;
+ }
+ return total;
+ }
+
+ async function loadFolders(open: boolean) {
+ if (!open) return;
+ setName("");
+ try {
+ const response = await authFetch("/api/drive/folders");
+ if (!response.ok) throw new Error();
+ setFolders((await response.json() as { folders: FolderNode[] }).folders);
+ } catch { toast.error(t("drive.loadFailed")); }
+ }
+
+ const move = (parentId: string | null) => run(() => bulk({ action: "move", ids, parentId }, t("drive.actionFailed")), (done) => t("drive.bulkMoved", { count: done }));
+
+ async function createAndMove(event: React.FormEvent) {
+ event.preventDefault();
+ const folderName = name.trim();
+ if (!folderName) return;
+ setBusy(true);
+ try {
+ const response = await authFetch("/api/drive/items", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: folderName }) });
+ const data = await response.json().catch(() => ({})) as { item?: { id: string }; error?: string };
+ if (!response.ok || !data.item) throw new Error(data.error);
+ setBusy(false);
+ await move(data.item.id);
+ } catch (error) {
+ setBusy(false);
+ toast.error(error instanceof Error && error.message ? error.message : t("drive.actionFailed"));
+ }
+ }
+
+ const buttonClass = "h-9 gap-2 rounded-full px-3 text-sm";
+ return (
+ <div className="flex flex-wrap items-center justify-end gap-1 text-sm">
+ {!trashView && canTrash && (
+ <>
+ <Button type="button" variant="ghost" className={buttonClass} disabled={busy} onClick={() => void run(() => act("trash"), (done) => t("drive.bulkTrashed", { count: done }))}><Trash2 size={16} />{t("drive.moveToTrash")}</Button>
+ {attachmentIds.length === 0 && ownsAll && <DropdownMenu.Root onOpenChange={(open) => void loadFolders(open)}>
+ <DropdownMenu.Trigger asChild>
+ <Button type="button" variant="ghost" className={buttonClass} disabled={busy}><FolderInput size={16} />{t("drive.moveToFolder")}</Button>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Portal>
+ <DropdownMenu.Content align="end" sideOffset={6} onCloseAutoFocus={(event) => event.preventDefault()} className="z-[200] w-72 rounded-xl border border-neutral-200 bg-white p-1.5 shadow-xl">
+ <form onSubmit={(event) => void createAndMove(event)} onKeyDown={(event) => event.stopPropagation()} className="flex items-center gap-1 border-b border-neutral-100 p-1.5 pb-2">
+ <FolderPlus size={16} className="shrink-0 text-neutral-500" />
+ <input ref={inputRef} value={name} onChange={(event) => setName(event.target.value)} maxLength={255} placeholder={t("drive.newFolderPlaceholder")} aria-label={t("drive.newFolderPlaceholder")} className="h-8 min-w-0 flex-1 rounded-md border border-neutral-200 bg-transparent px-2 text-sm placeholder:text-neutral-500 focus:border-blue-600 focus:outline-none" />
+ <Button type="submit" size="sm" disabled={busy || !name.trim()} title={t("drive.createAndMove")}>{t("drive.create")}</Button>
+ </form>
+ <div className="max-h-64 overflow-y-auto pt-1">
+ <DropdownMenu.Item onSelect={() => void move(null)} className="flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-2 text-sm text-neutral-700 outline-none data-[highlighted]:bg-neutral-100"><HardDrive size={16} className="shrink-0" />{t("drive.myDrive")}</DropdownMenu.Item>
+ {rows.map((folder) => (
+ <DropdownMenu.Item key={folder.id} disabled={folder.disabled} onSelect={() => void move(folder.id)} style={{ paddingLeft: 10 + folder.depth * 14 }} className={clsx("flex cursor-pointer items-center gap-2 rounded-lg py-2 pr-2.5 text-sm text-neutral-700 outline-none data-[disabled]:cursor-default data-[disabled]:opacity-40 data-[highlighted]:bg-neutral-100")}>
+ <Folder size={16} className="shrink-0 text-amber-500" /><span className="truncate">{folder.name}</span>
+ </DropdownMenu.Item>
+ ))}
+ {folders && rows.length === 0 && <p className="px-2.5 py-2 text-xs text-neutral-500">{t("drive.noFolders")}</p>}
+ </div>
+ </DropdownMenu.Content>
+ </DropdownMenu.Portal>
+ </DropdownMenu.Root>}
+ </>
+ )}
+ {ownsAll && trashView && (
+ <>
+ <Button type="button" variant="ghost" className={buttonClass} disabled={busy} onClick={() => void run(() => act("restore"), (done) => t("drive.bulkRestored", { count: done }))}><RotateCcw size={16} />{t("drive.restore")}</Button>
+ <Button type="button" variant="ghost" className={clsx(buttonClass, "text-red-600")} disabled={busy} onClick={() => { if (window.confirm(t("drive.confirmBulkDelete", { count }))) void run(() => act("delete"), (done) => t("drive.bulkDeleted", { count: done })); }}><X size={16} />{t("drive.deleteForever")}</Button>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/src/app/(drive)/drive-columns.tsx b/src/app/(drive)/drive-columns.tsx
new file mode 100644
index 0000000..138d238
--- /dev/null
+++ b/src/app/(drive)/drive-columns.tsx
@@ -0,0 +1,101 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import clsx from "clsx";
+import type { KeyboardEvent, PointerEvent } from "react";
+import { useLanguage } from "@/components/language-provider";
+
+export type DriveColumn = "owner" | "updatedAt" | "size";
+
+const STORAGE_KEY = "mailflare-drive-columns";
+const DEFAULT_WIDTHS: Record<DriveColumn, number> = { owner: 160, updatedAt: 144, size: 96 };
+const MIN_WIDTH = 72;
+const MAX_WIDTH = 480;
+const clamp = (value: number) => Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, Math.round(value)));
+
+/** Widths of the resizable columns; the name column takes whatever is left. Remembered per browser. */
+export function useDriveColumns() {
+ const [widths, setWidths] = useState(DEFAULT_WIDTHS);
+
+ useEffect(() => {
+ try {
+ const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "null") as Partial<Record<DriveColumn, number>> | null;
+ if (saved) setWidths((current) => ({ owner: clamp(saved.owner ?? current.owner), updatedAt: clamp(saved.updatedAt ?? current.updatedAt), size: clamp(saved.size ?? current.size) }));
+ } catch { /* storage unavailable: keep defaults */ }
+ }, []);
+
+ const resize = useCallback((column: DriveColumn, width: number, persist = false) => {
+ setWidths((current) => {
+ const next = { ...current, [column]: clamp(width) };
+ if (persist) { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); } catch { /* ignore */ } }
+ return next;
+ });
+ }, []);
+
+ const template = `2rem minmax(0,1fr) ${widths.owner}px ${widths.updatedAt}px ${widths.size}px 2.5rem`;
+ return { widths, resize, template };
+}
+
+/**
+ * Drag handle on the left edge of a column header: dragging left makes the column wider. The drag is tracked on
+ * `window` from the width it started with, so it ends cleanly wherever the pointer is released and never leaves a
+ * listener behind on the handle.
+ */
+export function ColumnResizeHandle({ column, width, onResize, label }: { column: DriveColumn; width: number; onResize: (column: DriveColumn, width: number, persist?: boolean) => void; label: string }) {
+ const { t } = useLanguage();
+ const [dragging, setDragging] = useState(false);
+ const cleanup = useRef<(() => void) | null>(null);
+ useEffect(() => () => cleanup.current?.(), []);
+
+ function onPointerDown(event: PointerEvent<HTMLDivElement>) {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ cleanup.current?.();
+ const startX = event.clientX;
+ const startWidth = width;
+ let latest = startWidth;
+ const move = (moveEvent: globalThis.PointerEvent) => { latest = startWidth + (startX - moveEvent.clientX); onResize(column, latest); };
+ const end = (endEvent?: globalThis.PointerEvent) => {
+ if (endEvent && endEvent.type === "pointerup") latest = startWidth + (startX - endEvent.clientX);
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", end);
+ window.removeEventListener("pointercancel", end);
+ window.removeEventListener("blur", cancel);
+ document.body.style.removeProperty("cursor");
+ document.body.style.removeProperty("user-select");
+ cleanup.current = null;
+ setDragging(false);
+ onResize(column, latest, true);
+ };
+ const cancel = () => end();
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", end);
+ window.addEventListener("pointercancel", end);
+ window.addEventListener("blur", cancel);
+ document.body.style.cursor = "col-resize";
+ document.body.style.userSelect = "none";
+ cleanup.current = cancel;
+ setDragging(true);
+ }
+ function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
+ const step = event.shiftKey ? 40 : 10;
+ if (event.key === "ArrowLeft") { event.preventDefault(); onResize(column, width + step, true); }
+ if (event.key === "ArrowRight") { event.preventDefault(); onResize(column, width - step, true); }
+ }
+ return (
+ <div
+ role="separator"
+ aria-orientation="vertical"
+ aria-label={t("drive.resizeColumn", { name: label })}
+ aria-valuenow={width}
+ aria-valuemin={MIN_WIDTH}
+ aria-valuemax={MAX_WIDTH}
+ tabIndex={0}
+ onPointerDown={onPointerDown}
+ onKeyDown={onKeyDown}
+ className="group/handle absolute -left-2 top-0 flex h-full w-4 cursor-col-resize touch-none items-center justify-center outline-none"
+ >
+ <span className={clsx("h-5 w-0.5 rounded-full transition-colors", dragging ? "bg-blue-500" : "bg-transparent group-hover/handle:bg-blue-500 group-focus-visible/handle:bg-blue-500")} />
+ </div>
+ );
+}
diff --git a/src/app/(drive)/drive-drag.ts b/src/app/(drive)/drive-drag.ts
new file mode 100644
index 0000000..48437da
--- /dev/null
+++ b/src/app/(drive)/drive-drag.ts
@@ -0,0 +1,122 @@
+"use client";
+
+import type { DragEvent } from "react";
+import toast from "react-hot-toast";
+import type { Translator } from "@/lib/i18n/utils";
+import type { DriveItemDto } from "@/lib/drive/types";
+import { canEditDrive } from "@/lib/drive/utils";
+import { attachmentAction, bulk } from "./drive-bulk-actions";
+import { DRIVE_REFRESH_EVENT } from "./drive-events";
+
+/** Marks a drag as Drive items being moved, so drop targets ignore files dragged in from the desktop. */
+export const DRIVE_DRAG_TYPE = "application/x-mailflare-drive";
+
+type DraggedItem = Pick<DriveItemDto, "id" | "kind" | "role"> & { attachment: boolean; trashed: boolean };
+/**
+ * Where items are dropped: a folder (`null` is the root of My Drive), the trash, or the attachments list, which only
+ * takes trashed attachments back.
+ */
+export type DriveDropTarget = { kind: "folder"; id: string | null } | { kind: "trash" } | { kind: "attachments" };
+
+// `dataTransfer` cannot be read until the drop, so targets decide whether to accept from this instead.
+let dragged: DraggedItem[] = [];
+
+/**
+ * Items that can be picked up: attachments the user may delete, and Drive items they can edit. From the trash, only what
+ * the user may restore: their own items and deletable attachments.
+ */
+export function isDriveDraggable(item: DriveItemDto): boolean {
+ if (item.source) return item.source.canDelete;
+ return item.trashedAt ? item.role === "owner" : canEditDrive(item.role);
+}
+
+export function startDriveDrag(event: DragEvent, items: DriveItemDto[], label: string) {
+ dragged = items.map((item) => ({ id: item.id, kind: item.kind, role: item.role, attachment: !!item.source, trashed: !!item.trashedAt }));
+ event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.setData(DRIVE_DRAG_TYPE, JSON.stringify(dragged.map((item) => item.id)));
+ if (items.length > 1) {
+ // A small "3 selected" chip instead of the browser's snapshot of a single row.
+ const chip = document.createElement("div");
+ chip.textContent = label;
+ chip.style.cssText = "position:fixed;top:-100px;left:0;padding:6px 12px;border-radius:9999px;background:#1d4ed8;color:#fff;font:500 13px system-ui,sans-serif;white-space:nowrap";
+ document.body.appendChild(chip);
+ event.dataTransfer.setDragImage(chip, 12, 16);
+ setTimeout(() => chip.remove(), 0);
+ }
+}
+
+export function endDriveDrag() {
+ dragged = [];
+}
+
+export function draggedDriveIds(): Set<string> {
+ return new Set(dragged.map((item) => item.id));
+}
+
+/**
+ * Whether the current drag may land on a target. Anything not yet trashed may go to the trash, and trashed attachments
+ * may go back to the attachments list. Moving (which also restores from the trash) is for the owner's own Drive items,
+ * never attachments, and never into a folder being dragged or one inside it (`isInside` walks up from the target, for
+ * callers that know the folder tree).
+ */
+export function canDropDrive(target: DriveDropTarget, isInside?: (folderId: string, ancestorIds: Set<string>) => boolean): boolean {
+ if (!dragged.length) return false;
+ if (target.kind === "trash") return dragged.some((item) => !item.trashed);
+ if (target.kind === "attachments") return dragged.every((item) => item.attachment && item.trashed);
+ if (dragged.some((item) => item.attachment || item.role !== "owner")) return false;
+ if (target.id === null) return true;
+ const folders = new Set(dragged.filter((item) => item.kind === "folder").map((item) => item.id));
+ if (folders.has(target.id)) return false;
+ return !isInside?.(target.id, folders);
+}
+
+/** Moves or trashes the dragged items, reports the result and asks the listing to reload. */
+export async function dropDrive(target: DriveDropTarget, t: Translator): Promise<void> {
+ const items = dragged;
+ endDriveDrag();
+ if (!items.length) return;
+ const fallback = t("drive.actionFailed");
+ let count: number | null = 0;
+ if (target.kind === "attachments") {
+ count = await attachmentAction("restore", items.map((item) => item.id), fallback);
+ if (count) toast.success(t("drive.bulkRestored", { count }));
+ } else if (target.kind === "trash") {
+ const live = items.filter((item) => !item.trashed);
+ const attachments = live.filter((item) => item.attachment).map((item) => item.id);
+ const driveIds = live.filter((item) => !item.attachment).map((item) => item.id);
+ for (const done of [attachments.length ? await attachmentAction("trash", attachments, fallback) : 0, driveIds.length ? await bulk({ action: "trash", ids: driveIds }, fallback) : 0]) {
+ count = count === null || done === null ? null : count + done;
+ }
+ if (count) toast.success(t("drive.bulkTrashed", { count }));
+ } else {
+ count = await bulk({ action: "move", ids: items.map((item) => item.id), parentId: target.id }, fallback);
+ if (count) toast.success(t(items.every((item) => item.trashed) ? "drive.bulkRestored" : "drive.bulkMoved", { count }));
+ }
+ window.dispatchEvent(new Event(DRIVE_REFRESH_EVENT));
+}
+
+/**
+ * Drop handlers for one target; `setOver` drives its highlight. `accepts` runs on every dragover, so keep it cheap.
+ * A drop that is handled stops propagating, so the page's file-upload drop zone never sees it.
+ */
+export function driveDropHandlers(target: DriveDropTarget, accepts: () => boolean, t: Translator, setOver: (over: boolean) => void) {
+ return {
+ onDragOver(event: DragEvent) {
+ if (!event.dataTransfer.types.includes(DRIVE_DRAG_TYPE) || !accepts()) return;
+ event.preventDefault();
+ event.stopPropagation();
+ event.dataTransfer.dropEffect = "move";
+ setOver(true);
+ },
+ onDragLeave(event: DragEvent) {
+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setOver(false);
+ },
+ onDrop(event: DragEvent) {
+ if (!event.dataTransfer.types.includes(DRIVE_DRAG_TYPE)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ setOver(false);
+ if (accepts()) void dropDrive(target, t);
+ },
+ };
+}
diff --git a/src/app/(drive)/drive-events.ts b/src/app/(drive)/drive-events.ts
new file mode 100644
index 0000000..945dafd
--- /dev/null
+++ b/src/app/(drive)/drive-events.ts
@@ -0,0 +1,11 @@
+export const DRIVE_UPLOAD_EVENT = "mailflare:drive-upload";
+export const DRIVE_NEW_FOLDER_EVENT = "mailflare:drive-new-folder";
+/** Detail: `DriveStorageDetail`. Sent by the page whenever a listing loads. */
+export const DRIVE_STORAGE_EVENT = "mailflare:drive-storage";
+/** Sent after a listing loads so the sidebar can refresh its folder list. */
+export const DRIVE_FOLDERS_EVENT = "mailflare:drive-folders";
+
+/** Asks the open listing to reload, e.g. after the sidebar created a folder. */
+export const DRIVE_REFRESH_EVENT = "mailflare:drive-refresh";
+
+export type DriveStorageDetail = { used: number; limit: number | null };
diff --git a/src/app/(drive)/drive-nav.tsx b/src/app/(drive)/drive-nav.tsx
new file mode 100644
index 0000000..a165587
--- /dev/null
+++ b/src/app/(drive)/drive-nav.tsx
@@ -0,0 +1,215 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import Link from "next/link";
+import { usePathname, useSearchParams } from "next/navigation";
+import clsx from "clsx";
+import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
+import toast from "react-hot-toast";
+import { ChevronRight, Folder, FolderPlus, HardDrive, Paperclip, Plus, Trash2, UploadCloud, UsersRound } from "lucide-react";
+import { useLanguage } from "@/components/language-provider";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { PoweredBy } from "@/components/sidebar-footer";
+import { useSidebar } from "@/components/sidebar-state";
+import { authFetch } from "@/lib/auth/client";
+import { formatDriveSize } from "@/lib/drive/utils";
+import { DRIVE_FOLDERS_EVENT, DRIVE_NEW_FOLDER_EVENT, DRIVE_REFRESH_EVENT, DRIVE_STORAGE_EVENT, DRIVE_UPLOAD_EVENT } from "./drive-events";
+import type { DriveStorageDetail } from "./drive-events";
+import { canDropDrive, driveDropHandlers } from "./drive-drag";
+import type { DriveDropTarget } from "./drive-drag";
+
+const itemClass = "flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2 text-sm text-neutral-700 outline-none data-[highlighted]:bg-neutral-100";
+const FOLDERS_OPEN_KEY = "mailflare-drive-folders-open";
+
+type FolderNode = { id: string; name: string; parentId: string | null };
+
+function flattenFolders(folders: FolderNode[]): (FolderNode & { depth: number })[] {
+ const known = new Set(folders.map((folder) => folder.id));
+ const children = new Map<string | null, FolderNode[]>();
+ for (const folder of folders) {
+ const key = folder.parentId && known.has(folder.parentId) ? folder.parentId : null;
+ children.set(key, [...(children.get(key) ?? []), folder]);
+ }
+ const rows: (FolderNode & { depth: number })[] = [];
+ const visit = (parent: string | null, depth: number) => {
+ for (const folder of (children.get(parent) ?? []).sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }))) {
+ rows.push({ ...folder, depth });
+ visit(folder.id, depth + 1);
+ }
+ };
+ visit(null, 0);
+ return rows;
+}
+
+export function DriveNav({ onNavigate }: { onNavigate?: () => void }) {
+ const { t } = useLanguage();
+ const { minimal, mobile } = useSidebar();
+ const pathname = usePathname();
+ const params = useSearchParams();
+ const view = params.get("view") ?? "my";
+ const activeFolder = params.get("folder");
+ const [storage, setStorage] = useState<DriveStorageDetail | null>(null);
+ const [foldersOpen, setFoldersOpen] = useState(false);
+ const [folders, setFolders] = useState<FolderNode[]>([]);
+ const compact = minimal && !mobile;
+ const [creating, setCreating] = useState(false);
+ const [folderName, setFolderName] = useState("");
+ const [saving, setSaving] = useState(false);
+ // The sidebar entry items are being dragged over: "my", "trash" or a folder id.
+ const [dropKey, setDropKey] = useState<string | null>(null);
+
+ useEffect(() => {
+ const onStorage = (event: Event) => setStorage((event as CustomEvent<DriveStorageDetail>).detail);
+ window.addEventListener(DRIVE_STORAGE_EVENT, onStorage);
+ return () => window.removeEventListener(DRIVE_STORAGE_EVENT, onStorage);
+ }, []);
+
+ useEffect(() => {
+ try { setFoldersOpen(localStorage.getItem(FOLDERS_OPEN_KEY) === "1"); } catch { /* storage unavailable */ }
+ }, []);
+
+ const loadFolders = useCallback(async () => {
+ try {
+ const response = await authFetch("/api/drive/folders", { redirectOnUnauthorized: false });
+ if (response.ok) setFolders((await response.json() as { folders: FolderNode[] }).folders);
+ } catch { /* the list stays as it was */ }
+ }, []);
+
+ useEffect(() => {
+ if (!foldersOpen) return;
+ void loadFolders();
+ window.addEventListener(DRIVE_FOLDERS_EVENT, loadFolders);
+ return () => window.removeEventListener(DRIVE_FOLDERS_EVENT, loadFolders);
+ }, [foldersOpen, loadFolders]);
+
+ function toggleFolders() {
+ setFoldersOpen((open) => {
+ try { localStorage.setItem(FOLDERS_OPEN_KEY, open ? "0" : "1"); } catch { /* ignore */ }
+ return !open;
+ });
+ }
+
+ async function createFolder(event: React.FormEvent) {
+ event.preventDefault();
+ const name = folderName.trim();
+ if (!name || saving) return;
+ setSaving(true);
+ try {
+ const response = await authFetch("/api/drive/items", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) });
+ const data = await response.json().catch(() => ({})) as { error?: string };
+ if (!response.ok) throw new Error(data.error);
+ toast.success(t("drive.folderCreated"));
+ setCreating(false);
+ setFolderName("");
+ if (!foldersOpen) toggleFolders();
+ void loadFolders();
+ window.dispatchEvent(new Event(DRIVE_REFRESH_EVENT));
+ } catch (error) {
+ toast.error(error instanceof Error && error.message ? error.message : t("drive.actionFailed"));
+ } finally { setSaving(false); }
+ }
+
+ const rows = useMemo(() => flattenFolders(folders), [folders]);
+ const parents = useMemo(() => new Map(folders.map((folder) => [folder.id, folder.parentId])), [folders]);
+ // True when `folderId` is one of `ancestorIds` or sits somewhere beneath one of them.
+ const isInside = useCallback((folderId: string, ancestorIds: Set<string>) => {
+ for (let current: string | null | undefined = folderId, steps = 0; current && steps < 1000; current = parents.get(current), steps += 1) {
+ if (ancestorIds.has(current)) return true;
+ }
+ return false;
+ }, [parents]);
+ const dropProps = (key: string, target: DriveDropTarget) => driveDropHandlers(target, () => canDropDrive(target, isInside), t, (over) => setDropKey((current) => (over ? key : current === key ? null : current)));
+ const dropHighlight = "bg-blue-100 text-blue-900 ring-2 ring-inset ring-blue-500";
+ const links = [
+ { key: "my", href: "/drive", label: t("drive.myDrive"), icon: HardDrive },
+ { key: "attachments", href: "/drive?view=attachments", label: t("drive.attachments"), icon: Paperclip },
+ { key: "shared", href: "/drive?view=shared", label: t("drive.sharedWithMe"), icon: UsersRound },
+ { key: "trash", href: "/drive?view=trash", label: t("drive.trash"), icon: Trash2 },
+ ];
+ const percent = storage?.limit ? Math.min(100, Math.round((storage.used / storage.limit) * 100)) : 0;
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="min-h-0 flex-1 overflow-y-auto px-3 pt-1">
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger asChild>
+ <button type="button" aria-label={t("drive.new")} className={clsx("mb-4 flex h-14 items-center gap-3 rounded-2xl bg-white text-sm font-medium text-neutral-800 shadow-md transition-shadow hover:shadow-lg", compact ? "w-14 justify-center" : "w-fit px-5")}>
+ <Plus size={22} />{!compact && t("drive.new")}
+ </button>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Portal>
+ <DropdownMenu.Content align="start" sideOffset={6} className="z-[200] min-w-52 rounded-xl border border-neutral-200 bg-white p-1.5 shadow-xl">
+ <DropdownMenu.Item className={itemClass} onSelect={() => { window.dispatchEvent(new Event(DRIVE_NEW_FOLDER_EVENT)); onNavigate?.(); }}><FolderPlus size={18} />{t("drive.newFolder")}</DropdownMenu.Item>
+ <DropdownMenu.Separator className="my-1 h-px bg-neutral-100" />
+ <DropdownMenu.Item className={itemClass} onSelect={() => { window.dispatchEvent(new Event(DRIVE_UPLOAD_EVENT)); onNavigate?.(); }}><UploadCloud size={18} />{t("drive.fileUpload")}</DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Portal>
+ </DropdownMenu.Root>
+ <nav aria-label={t("drive.sections")} className="space-y-0.5">
+ {links.map(({ key, href, label, icon: Icon }) => {
+ const active = pathname === "/drive" && view === key && !activeFolder;
+ // My Drive takes items to its root (restoring them from the trash), Trash trashes them, and
+ // Attachments takes trashed attachments back.
+ const target: DriveDropTarget | null = key === "my" ? { kind: "folder", id: null } : key === "trash" ? { kind: "trash" } : key === "attachments" ? { kind: "attachments" } : null;
+ return (
+ <Link key={key} href={href} onClick={onNavigate} {...(target ? dropProps(key, target) : {})} aria-current={active ? "page" : undefined} title={compact ? label : undefined} className={clsx("flex h-10 items-center gap-3 rounded-full text-sm", compact ? "w-10 justify-center" : "px-4", dropKey === key ? dropHighlight : active ? "bg-blue-100 font-medium text-blue-900" : "text-neutral-700 hover:bg-neutral-200/60")}>
+ <Icon size={16} />{!compact && label}
+ </Link>
+ );
+ })}
+ </nav>
+ {!compact && (
+ <div className="mt-3">
+ <div className="flex items-center gap-1">
+ <button type="button" onClick={toggleFolders} aria-expanded={foldersOpen} aria-label={t("drive.foldersToggle")} className="flex h-9 min-w-0 flex-1 items-center gap-2 rounded-full px-4 text-xs font-semibold uppercase tracking-wide text-neutral-500 hover:bg-neutral-200/60">
+ <ChevronRight size={14} className={clsx("transition-transform", foldersOpen && "rotate-90")} />{t("drive.folders")}
+ </button>
+ <button type="button" onClick={() => { setFolderName(""); setCreating(true); }} aria-label={t("drive.newFolder")} title={t("drive.newFolder")} className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-neutral-500 hover:bg-neutral-200/60 hover:text-neutral-800"><Plus size={16} /></button>
+ </div>
+ {foldersOpen && (
+ <ul className="mt-0.5 space-y-0.5">
+ {rows.length === 0 && <li className="px-4 py-1.5 text-xs text-neutral-500">{t("drive.noFolders")}</li>}
+ {rows.map((folder) => (
+ <li key={folder.id}>
+ <Link href={`/drive?folder=${encodeURIComponent(folder.id)}`} onClick={onNavigate} {...dropProps(folder.id, { kind: "folder", id: folder.id })} aria-current={activeFolder === folder.id ? "page" : undefined} style={{ paddingLeft: 16 + folder.depth * 14 }} className={clsx("flex h-8 items-center gap-2 rounded-full pr-3 text-sm", dropKey === folder.id ? dropHighlight : activeFolder === folder.id ? "bg-blue-100 font-medium text-blue-900" : "text-neutral-700 hover:bg-neutral-200/60")}>
+ <Folder size={14} className="shrink-0 text-amber-500" /><span className="truncate">{folder.name}</span>
+ </Link>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+ </div>
+ {!compact && (
+ <div className="shrink-0 border-t border-neutral-200/70 px-4 py-3">
+ {storage && (
+ storage.limit ? (
+ <div className="mb-2">
+ <div role="progressbar" aria-label={t("drive.storageBar")} aria-valuemin={0} aria-valuemax={100} aria-valuenow={percent} className="mb-1.5 h-1.5 overflow-hidden rounded-full bg-neutral-200">
+ <div className={clsx("h-full rounded-full transition-[width]", percent >= 90 ? "bg-red-500" : "bg-blue-600")} style={{ width: `${percent}%` }} />
+ </div>
+ <p className="text-xs text-neutral-600">{t("drive.storageOf", { used: formatDriveSize(storage.used), total: formatDriveSize(storage.limit) })}</p>
+ </div>
+ ) : <p className="mb-2 text-xs text-neutral-600">{t("drive.storageUsed", { size: formatDriveSize(storage.used) })}</p>
+ )}
+ <PoweredBy className="" />
+ </div>
+ )}
+ <Dialog open={creating} onOpenChange={(open) => { if (!saving) setCreating(open); }}>
+ <DialogContent>
+ <DialogHeader><DialogTitle>{t("drive.newFolder")}</DialogTitle></DialogHeader>
+ <form onSubmit={(event) => void createFolder(event)} className="space-y-5">
+ <Input autoFocus value={folderName} onChange={(event) => setFolderName(event.target.value)} placeholder={t("drive.folderName")} aria-label={t("drive.folderName")} maxLength={255} />
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="ghost" onClick={() => setCreating(false)} disabled={saving}>{t("common.cancel")}</Button>
+ <Button type="submit" disabled={saving || !folderName.trim()}>{t("drive.create")}</Button>
+ </div>
+ </form>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
diff --git a/src/app/(drive)/drive-owner-avatar.tsx b/src/app/(drive)/drive-owner-avatar.tsx
new file mode 100644
index 0000000..f982f77
--- /dev/null
+++ b/src/app/(drive)/drive-owner-avatar.tsx
@@ -0,0 +1,22 @@
+"use client";
+
+import { useState } from "react";
+import { useLanguage } from "@/components/language-provider";
+import { Tooltip } from "@/components/ui/tooltip";
+import { getAvatarColorStyle } from "@/lib/avatar-colors";
+import type { DriveItemDto } from "@/lib/drive/types";
+
+/** Owner's profile picture (or a coloured initial), with "me" or their name on hover. */
+export function DriveOwnerAvatar({ item }: { item: Pick<DriveItemDto, "ownerId" | "ownerName" | "ownerHasAvatar" | "role"> }) {
+ const { t } = useLanguage();
+ const [failed, setFailed] = useState(false);
+ const label = item.role === "owner" ? t("drive.me") : item.ownerName;
+ const className = "h-6 w-6 shrink-0 rounded-full";
+ return (
+ <Tooltip label={label}>
+ {item.ownerHasAvatar && !failed
+ ? <img src={`/api/drive/owners/${encodeURIComponent(item.ownerId)}/avatar`} alt={label} onError={() => setFailed(true)} className={`${className} object-cover`} />
+ : <span role="img" aria-label={label} className={`${className} flex items-center justify-center text-xs font-semibold`} style={getAvatarColorStyle(item.ownerName || item.ownerId)}>{(item.ownerName.trim().slice(0, 1) || "?").toUpperCase()}</span>}
+ </Tooltip>
+ );
+}
diff --git a/src/app/(drive)/drive-preview.tsx b/src/app/(drive)/drive-preview.tsx
new file mode 100644
index 0000000..fab86d1
--- /dev/null
+++ b/src/app/(drive)/drive-preview.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import { Download } from "lucide-react";
+import { useLanguage } from "@/components/language-provider";
+import { canPreview } from "./drive-utils";
+
+export function DrivePreviewBody({ src, downloadHref, contentType, name }: { src: string; downloadHref: string; contentType: string; name: string }) {
+ const { t } = useLanguage();
+ if (!canPreview(contentType)) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-4 text-sm text-[#e8eaed]">
+ <p>{t("drive.noPreview")}</p>
+ <a href={downloadHref} className="inline-flex items-center gap-2 rounded-full bg-[#e8eaed] px-4 py-2 font-medium text-[#202124]"><Download size={16} />{t("drive.download")}</a>
+ </div>
+ );
+ }
+ if (contentType.startsWith("image/")) return <img src={src} alt={name} className="mx-auto max-h-full max-w-full object-contain" />;
+ if (contentType.startsWith("video/")) return <video src={src} controls className="mx-auto max-h-full max-w-full" />;
+ if (contentType.startsWith("audio/")) return <div className="flex h-full items-center justify-center"><audio src={src} controls /></div>;
+ return <iframe src={src} title={name} className="h-full w-full rounded-lg" style={{ background: "#fff", colorScheme: "light" }} />;
+}
diff --git a/src/app/(drive)/drive-share-dialog.tsx b/src/app/(drive)/drive-share-dialog.tsx
new file mode 100644
index 0000000..f43e7e7
--- /dev/null
+++ b/src/app/(drive)/drive-share-dialog.tsx
@@ -0,0 +1,109 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import toast from "react-hot-toast";
+import { Copy, Link2, X } from "lucide-react";
+import { useLanguage } from "@/components/language-provider";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { authFetch } from "@/lib/auth/client";
+import type { DriveItemDto, DriveShareDto, DriveShareRole } from "@/lib/drive/types";
+
+const selectClass = "h-10 rounded-md border border-neutral-200 bg-white px-2 text-sm";
+
+export function DriveShareDialog({ item, onClose, onChanged }: { item: DriveItemDto | null; onClose: () => void; onChanged: () => void }) {
+ const { t } = useLanguage();
+ const [shares, setShares] = useState<DriveShareDto[]>([]);
+ const [linkToken, setLinkToken] = useState<string | null>(null);
+ const [email, setEmail] = useState("");
+ const [role, setRole] = useState<DriveShareRole>("view");
+ const [busy, setBusy] = useState(false);
+ const id = item?.id;
+
+ const load = useCallback(async () => {
+ if (!id) return;
+ const response = await authFetch(`/api/drive/items/${id}/shares`);
+ if (!response.ok) return toast.error(t("drive.shareFailed"));
+ const data = await response.json() as { shares: DriveShareDto[]; linkToken: string | null };
+ setShares(data.shares);
+ setLinkToken(data.linkToken);
+ }, [id, t]);
+
+ useEffect(() => {
+ setShares([]); setLinkToken(null); setEmail("");
+ void load();
+ }, [load]);
+
+ async function request(input: string, init: RequestInit) {
+ setBusy(true);
+ try {
+ const response = await authFetch(input, init);
+ const data = await response.json().catch(() => ({})) as { shares?: DriveShareDto[]; linkToken?: string | null; error?: string };
+ if (!response.ok) { toast.error(data.error ?? t("drive.shareFailed")); return null; }
+ onChanged();
+ return data;
+ } finally { setBusy(false); }
+ }
+
+ async function addPerson(event: React.FormEvent) {
+ event.preventDefault();
+ if (!item || !email.trim()) return;
+ const data = await request(`/api/drive/items/${item.id}/shares`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, role }) });
+ if (data?.shares) { setShares(data.shares); setEmail(""); }
+ }
+
+ async function removePerson(shareId: string) {
+ if (!item) return;
+ const data = await request(`/api/drive/items/${item.id}/shares?shareId=${encodeURIComponent(shareId)}`, { method: "DELETE" });
+ if (data?.shares) setShares(data.shares);
+ }
+
+ async function toggleLink() {
+ if (!item) return;
+ const data = await request(`/api/drive/items/${item.id}/link`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ enabled: !linkToken }) });
+ if (data) setLinkToken(data.linkToken ?? null);
+ }
+
+ const linkUrl = linkToken ? `${window.location.origin}/d/${linkToken}` : "";
+
+ return (
+ <Dialog open={!!item} onOpenChange={(open) => { if (!open) onClose(); }}>
+ <DialogContent className="max-h-[calc(100vh-4rem)] overflow-y-auto">
+ <DialogHeader><DialogTitle className="pr-6 truncate">{t("drive.shareTitle", { name: item?.name ?? "" })}</DialogTitle></DialogHeader>
+ <form onSubmit={addPerson} className="flex gap-2">
+ <Input type="email" value={email} onChange={(event) => setEmail(event.target.value)} placeholder={t("drive.shareEmail")} aria-label={t("drive.shareEmail")} />
+ <select value={role} onChange={(event) => setRole(event.target.value as DriveShareRole)} className={selectClass} aria-label={t("drive.peopleWithAccess")}>
+ <option value="view">{t("drive.canView")}</option>
+ <option value="edit">{t("drive.canEdit")}</option>
+ </select>
+ <Button type="submit" disabled={busy || !email.trim()}>{t("drive.shareAdd")}</Button>
+ </form>
+ <h3 className="mb-2 mt-6 text-sm font-medium text-neutral-900">{t("drive.peopleWithAccess")}</h3>
+ {shares.length === 0 ? <p className="text-sm text-neutral-500">{t("drive.noPeople")}</p> : (
+ <ul className="space-y-1">
+ {shares.map((share) => (
+ <li key={share.id} className="flex items-center gap-2 rounded-lg px-2 py-1.5 text-sm hover:bg-neutral-50">
+ <span className="min-w-0 flex-1"><span className="block truncate text-neutral-900">{share.name}</span><span className="block truncate text-xs text-neutral-500">{share.email}</span></span>
+ <span className="shrink-0 text-xs text-neutral-500">{share.role === "edit" ? t("drive.canEdit") : t("drive.canView")}</span>
+ <button type="button" onClick={() => void removePerson(share.id)} disabled={busy} aria-label={t("drive.remove")} className="rounded-full p-1 text-neutral-500 hover:bg-neutral-200"><X size={14} /></button>
+ </li>
+ ))}
+ </ul>
+ )}
+ <h3 className="mb-2 mt-6 text-sm font-medium text-neutral-900">{t("drive.generalAccess")}</h3>
+ <div className="flex items-center gap-3 rounded-lg border border-neutral-200 p-3 text-sm">
+ <Link2 size={18} className="shrink-0 text-neutral-500" />
+ <span className="min-w-0 flex-1 text-neutral-700">{linkToken ? t("drive.linkOn") : t("drive.linkOff")}</span>
+ <Button type="button" variant="outline" size="sm" disabled={busy} onClick={() => void toggleLink()}>{linkToken ? t("drive.linkDisable") : t("drive.linkEnable")}</Button>
+ </div>
+ {linkToken && (
+ <div className="mt-2 flex gap-2">
+ <Input readOnly value={linkUrl} onFocus={(event) => event.currentTarget.select()} aria-label={t("drive.copyLink")} />
+ <Button type="button" variant="outline" onClick={() => { void navigator.clipboard.writeText(linkUrl).then(() => toast.success(t("drive.linkCopied"))); }}><Copy size={16} />{t("drive.copyLink")}</Button>
+ </div>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/app/(drive)/drive-type-filter.tsx b/src/app/(drive)/drive-type-filter.tsx
new file mode 100644
index 0000000..2952e06
--- /dev/null
+++ b/src/app/(drive)/drive-type-filter.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
+import clsx from "clsx";
+import { Check, ListFilter } from "lucide-react";
+import { useLanguage } from "@/components/language-provider";
+import { DRIVE_CATEGORIES } from "@/lib/drive/category-names";
+import type { DriveCategory } from "@/lib/drive/category-names";
+
+/** Multi-select filter by kind of file (photos, videos, documents, others). */
+export function DriveTypeFilter({ value: applied, onChange }: { value: DriveCategory[]; onChange: (next: DriveCategory[]) => void }) {
+ const { t } = useLanguage();
+ // Local copy so quick successive clicks build on each other while the URL update is still in flight.
+ const [value, setValue] = useState(applied);
+ const appliedKey = applied.join(",");
+ useEffect(() => { setValue(appliedKey ? (appliedKey.split(",") as DriveCategory[]) : []); }, [appliedKey]);
+ const update = (next: DriveCategory[]) => { setValue(next); onChange(next); };
+ const labels: Record<DriveCategory, string> = { photos: t("drive.photos"), videos: t("drive.videos"), documents: t("drive.documents"), others: t("drive.others") };
+ const active = value.length > 0;
+ return (
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger asChild>
+ <button type="button" aria-label={t("drive.typeFilter")} className={clsx("flex h-9 shrink-0 items-center gap-2 rounded-full border px-3 text-sm", active ? "border-blue-200 bg-blue-50 text-blue-800" : "border-neutral-200 text-neutral-700 hover:bg-neutral-100")}>
+ <ListFilter size={16} />{t("drive.typeFilter")}{active && <span className="rounded-full bg-blue-600 px-1.5 text-xs text-white">{value.length}</span>}
+ </button>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Portal>
+ <DropdownMenu.Content align="end" sideOffset={6} className="z-[200] min-w-48 rounded-xl border border-neutral-200 bg-white p-1.5 shadow-xl">
+ {DRIVE_CATEGORIES.map((category) => (
+ <DropdownMenu.CheckboxItem
+ key={category}
+ checked={value.includes(category)}
+ onCheckedChange={(checked) => update(checked ? [...value, category] : value.filter((entry) => entry !== category))}
+ onSelect={(event) => event.preventDefault()}
+ className="relative flex cursor-pointer items-center rounded-lg py-2 pl-8 pr-3 text-sm text-neutral-700 outline-none data-[highlighted]:bg-neutral-100"
+ >
+ <DropdownMenu.ItemIndicator className="absolute left-2.5"><Check size={14} className="text-blue-600" /></DropdownMenu.ItemIndicator>
+ {labels[category]}
+ </DropdownMenu.CheckboxItem>
+ ))}
+ {active && (
+ <>
+ <DropdownMenu.Separator className="my-1 h-px bg-neutral-100" />
+ <DropdownMenu.Item onSelect={() => update([])} className="cursor-pointer rounded-lg px-3 py-2 text-sm text-neutral-700 outline-none data-[highlighted]:bg-neutral-100">{t("drive.clearFilter")}</DropdownMenu.Item>
+ </>
+ )}
+ </DropdownMenu.Content>
+ </DropdownMenu.Portal>
+ </DropdownMenu.Root>
+ );
+}
diff --git a/src/app/(drive)/drive-upload.ts b/src/app/(drive)/drive-upload.ts
new file mode 100644
index 0000000..299ac2f
--- /dev/null
+++ b/src/app/(drive)/drive-upload.ts
@@ -0,0 +1,48 @@
+import { authFetch } from "@/lib/auth/client";
+
+const PART_RETRIES = 3;
+
+async function readError(response: Response): Promise<Error> {
+ const data = await response.json().catch(() => null) as { error?: string } | null;
+ return new Error(data?.error ?? `Upload failed (${response.status})`);
+}
+
+/**
+ * Uploads a file in parts, each sent as a raw request body. Not multipart/form-data: the runtime treats every
+ * multipart POST as a server action and rejects anything over 1 MB.
+ *
+ * The server remembers which parts arrived. Interrupted uploads (lost connection, closed tab) are not discarded:
+ * picking the same file again, same name, size and modified time, into the same folder continues after the last stored part.
+ */
+export async function uploadDriveFile(file: File, parentId: string | null, onProgress: (percent: number, resumed: boolean) => void): Promise<void> {
+ const start = await authFetch("/api/drive/upload", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name: file.name, size: file.size, contentType: file.type || "application/octet-stream", parentId, fingerprint: String(file.lastModified) }),
+ });
+ if (!start.ok) throw await readError(start);
+ const session = await start.json() as { id?: string; partSize?: number; parts?: number; uploaded?: number[]; resumed?: boolean; complete?: boolean };
+ if (session.complete) return;
+ const { id, partSize, parts } = session as { id: string; partSize: number; parts: number };
+ const stored = new Set(session.uploaded ?? []);
+ const resumed = !!session.resumed;
+ let finished = stored.size;
+ onProgress(Math.round((finished / parts) * 100), resumed);
+ for (let index = 0; index < parts; index += 1) {
+ if (stored.has(index + 1)) continue;
+ const chunk = file.slice(index * partSize, (index + 1) * partSize);
+ for (let attempt = 1; ; attempt += 1) {
+ try {
+ const response = await authFetch(`/api/drive/upload/${id}?part=${index + 1}`, { method: "PUT", headers: { "Content-Type": "application/octet-stream" }, body: chunk });
+ if (!response.ok) throw await readError(response);
+ break;
+ } catch (error) {
+ if (attempt >= PART_RETRIES) throw error;
+ }
+ }
+ finished += 1;
+ onProgress(Math.round((finished / parts) * 100), resumed);
+ }
+ const finish = await authFetch(`/api/drive/upload/${id}`, { method: "POST" });
+ if (!finish.ok) throw await readError(finish);
+}
diff --git a/src/app/(drive)/drive-utils.ts b/src/app/(drive)/drive-utils.ts
new file mode 100644
index 0000000..64dff91
--- /dev/null
+++ b/src/app/(drive)/drive-utils.ts
@@ -0,0 +1,62 @@
+import { File as FileIcon, FileArchive, FileAudio, FileCode, FileImage, FileSpreadsheet, FileText, FileVideo, Folder, Presentation } from "lucide-react";
+import type { DriveItemDto } from "@/lib/drive/types";
+
+const extensionOf = (name: string) => name.slice(name.lastIndexOf(".") + 1).toLowerCase();
+const SPREADSHEET = /spreadsheet|ms-excel|csv/;
+const PRESENTATION = /presentation|ms-powerpoint/;
+const ARCHIVE = /zip|compressed|x-tar|gzip|rar|7z/;
+const CODE_EXTENSIONS = new Set(["js", "ts", "tsx", "jsx", "json", "html", "css", "py", "rb", "go", "rs", "java", "c", "cpp", "h", "sh", "sql", "yml", "yaml", "xml"]);
+
+// One colour per kind of file. Palette classes, not hex, so the dark theme remaps them.
+export function driveIconFor(item: Pick<DriveItemDto, "kind" | "contentType" | "name">) {
+ if (item.kind === "folder") return { Icon: Folder, className: "text-amber-500" };
+ const type = item.contentType;
+ const extension = extensionOf(item.name);
+ if (type.startsWith("image/")) return { Icon: FileImage, className: "text-rose-500" };
+ if (type.startsWith("video/")) return { Icon: FileVideo, className: "text-purple-500" };
+ if (type.startsWith("audio/")) return { Icon: FileAudio, className: "text-orange-500" };
+ if (type === "application/pdf" || extension === "pdf") return { Icon: FileText, className: "text-red-600" };
+ if (SPREADSHEET.test(type) || ["xls", "xlsx", "ods", "csv", "numbers"].includes(extension)) return { Icon: FileSpreadsheet, className: "text-green-600" };
+ if (PRESENTATION.test(type) || ["ppt", "pptx", "odp", "key"].includes(extension)) return { Icon: Presentation, className: "text-orange-600" };
+ if (ARCHIVE.test(type) || ["zip", "rar", "7z", "tar", "gz"].includes(extension)) return { Icon: FileArchive, className: "text-yellow-700" };
+ if (CODE_EXTENSIONS.has(extension) || type === "application/json" || type.includes("javascript") || type.includes("xml")) return { Icon: FileCode, className: "text-teal-500" };
+ if (type.startsWith("text/") || type.includes("word") || type.includes("opendocument.text") || ["doc", "docx", "odt", "rtf", "txt", "md", "pages"].includes(extension)) return { Icon: FileText, className: "text-blue-500" };
+ return { Icon: FileIcon, className: "text-neutral-500" };
+}
+
+export type DriveSortKey = "name" | "owner" | "updatedAt" | "size";
+
+export function sortDriveItems<T extends Pick<DriveItemDto, "kind" | "name" | "updatedAt"> & { ownerName?: string; role?: string; size?: number }>(items: T[], key: DriveSortKey, ascending: boolean): T[] {
+ const direction = ascending ? 1 : -1;
+ const text = (a: string, b: string) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" });
+ return [...items].sort((a, b) => {
+ if (a.kind !== b.kind) return a.kind === "folder" ? -1 : 1;
+ let compared: number;
+ if (key === "updatedAt") compared = a.updatedAt.localeCompare(b.updatedAt);
+ else if (key === "size") compared = (a.size ?? 0) - (b.size ?? 0);
+ else if (key === "owner") compared = text(a.role === "owner" ? "" : a.ownerName ?? "", b.role === "owner" ? "" : b.ownerName ?? "");
+ else compared = 0;
+ return (compared || text(a.name, b.name)) * direction;
+ });
+}
+
+/** URL of a file's bytes: a Drive file, or an email attachment when the item comes from mail. */
+export function driveFileUrl(item: Pick<DriveItemDto, "id" | "source">, download = false): string {
+ return item.source ? `/api/drive/attachments/${encodeURIComponent(item.id)}/content${download ? "?download=1" : ""}` : contentUrl(item.id, download);
+}
+
+export function emailUrl(source: NonNullable<DriveItemDto["source"]>): string {
+ return `/${source.direction === "outbound" ? "sent" : "inbox"}/${encodeURIComponent(source.messageId)}`;
+}
+
+export function contentUrl(id: string, download = false): string {
+ return `/api/drive/items/${encodeURIComponent(id)}/content${download ? "?download=1" : ""}`;
+}
+
+export function publicContentUrl(token: string, itemId: string, download = false): string {
+ return `/api/drive/public/${encodeURIComponent(token)}?item=${encodeURIComponent(itemId)}&${download ? "download=1" : "content=1"}`;
+}
+
+export function canPreview(contentType: string): boolean {
+ return contentType.startsWith("image/") && contentType !== "image/svg+xml" || contentType.startsWith("video/") || contentType.startsWith("audio/") || contentType === "application/pdf" || contentType === "text/plain" || contentType === "text/csv" || contentType === "application/json";
+}
diff --git a/src/app/(drive)/drive/page.tsx b/src/app/(drive)/drive/page.tsx
new file mode 100644
index 0000000..bdcb1f1
--- /dev/null
+++ b/src/app/(drive)/drive/page.tsx
@@ -0,0 +1,351 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import type { DragEvent } from "react";
+import { createPortal } from "react-dom";
+import { HeaderSearch } from "@/components/header-search";
+import { useRouter, useSearchParams } from "next/navigation";
+import toast, { Toaster } from "react-hot-toast";
+import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
+import clsx from "clsx";
+import { ArrowDown, ArrowUp, ChevronRight, Download, ExternalLink, Mail, MoreVertical, Pencil, RotateCcw, Share2, Trash2, UploadCloud, X } from "lucide-react";
+import { useLanguage } from "@/components/language-provider";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { authFetch } from "@/lib/auth/client";
+import { canEditDrive, DRIVE_MAX_FILE_BYTES, formatDriveSize } from "@/lib/drive/utils";
+import type { DriveCrumb, DriveItemDto, DriveRole } from "@/lib/drive/types";
+import { DRIVE_FOLDERS_EVENT, DRIVE_NEW_FOLDER_EVENT, DRIVE_REFRESH_EVENT, DRIVE_STORAGE_EVENT, DRIVE_UPLOAD_EVENT } from "../drive-events";
+import { DrivePreviewBody } from "../drive-preview";
+import { DriveShareDialog } from "../drive-share-dialog";
+import { driveFileUrl, driveIconFor, emailUrl, sortDriveItems } from "../drive-utils";
+import type { DriveSortKey } from "../drive-utils";
+import { DriveBulkActions } from "../drive-bulk-actions";
+import { Checkbox } from "@/components/ui/checkbox";
+import { DriveOwnerAvatar } from "../drive-owner-avatar";
+import { ColumnResizeHandle, useDriveColumns } from "../drive-columns";
+import { DriveTypeFilter } from "../drive-type-filter";
+import { isDriveCategory } from "@/lib/drive/category-names";
+import type { DriveCategory } from "@/lib/drive/category-names";
+import { uploadDriveFile } from "../drive-upload";
+import { canDropDrive, driveDropHandlers, endDriveDrag, isDriveDraggable, startDriveDrag } from "../drive-drag";
+
+const menuItemClass = "flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2 text-sm text-neutral-700 outline-none data-[highlighted]:bg-neutral-100";
+const dateFormat = new Intl.DateTimeFormat(undefined, { year: "numeric", month: "short", day: "numeric" });
+
+type ListResponse = { items: DriveItemDto[]; path: DriveCrumb[]; role: DriveRole; storageUsed: number; storageLimit: number | null };
+
+export default function DrivePage() {
+ const { t } = useLanguage();
+ const router = useRouter();
+ const params = useSearchParams();
+ const view = params.get("view") ?? "my";
+ const folder = params.get("folder");
+ const query = params.get("q") ?? "";
+ const typesParam = params.get("types") ?? "";
+ const types = useMemo(() => typesParam.split(",").filter((entry): entry is DriveCategory => isDriveCategory(entry)), [typesParam]);
+ const [items, setItems] = useState<DriveItemDto[]>([]);
+ const [path, setPath] = useState<DriveCrumb[]>([]);
+ const [role, setRole] = useState<DriveRole>("owner");
+ const [loading, setLoading] = useState(true);
+ const [failed, setFailed] = useState(false);
+ const [sortKey, setSortKey] = useState<DriveSortKey>("name");
+ const columns = useDriveColumns();
+ const [ascending, setAscending] = useState(true);
+ const [dragging, setDragging] = useState(false);
+ const [search, setSearch] = useState(query);
+ const [headerTarget, setHeaderTarget] = useState<HTMLElement | null>(null);
+ const [preview, setPreview] = useState<DriveItemDto | null>(null);
+ const [sharing, setSharing] = useState<DriveItemDto | null>(null);
+ const [naming, setNaming] = useState<{ mode: "create" | "rename"; item?: DriveItemDto; value: string } | null>(null);
+ const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
+ const selectAllRef = useRef<HTMLInputElement | null>(null);
+ const fileInput = useRef<HTMLInputElement | null>(null);
+ const dragDepth = useRef(0);
+ // Rows being dragged to another folder or the trash, and the folder row under the pointer.
+ const [movingIds, setMovingIds] = useState<Set<string>>(new Set());
+ const [dropFolder, setDropFolder] = useState<string | null>(null);
+
+ const canWrite = view !== "trash" && (folder ? canEditDrive(role) : view === "my");
+ const requestKey = `${view}|${folder ?? ""}|${query}|${typesParam}`;
+ // The key of the listing the page currently wants, so a slow response for a folder we already left is dropped.
+ const requestRef = useRef(requestKey);
+ useEffect(() => { requestRef.current = requestKey; }, [requestKey]);
+
+ const load = useCallback(async () => {
+ const key = requestKey;
+ const search = new URLSearchParams({ view });
+ if (folder) search.set("parent", folder);
+ if (query) search.set("q", query);
+ if (typesParam) search.set("types", typesParam);
+ try {
+ const response = await authFetch(`/api/drive/items?${search}`);
+ if (!response.ok) throw new Error();
+ const data = await response.json() as ListResponse;
+ if (key !== requestRef.current) return;
+ setItems(data.items); setPath(data.path); setRole(data.role); setFailed(false);
+ window.dispatchEvent(new CustomEvent(DRIVE_STORAGE_EVENT, { detail: { used: data.storageUsed, limit: data.storageLimit } }));
+ window.dispatchEvent(new Event(DRIVE_FOLDERS_EVENT));
+ } catch {
+ if (key === requestRef.current) setFailed(true);
+ } finally {
+ if (key === requestRef.current) setLoading(false);
+ }
+ }, [view, folder, query, typesParam, requestKey]);
+
+ useEffect(() => { setLoading(true); void load(); }, [load]);
+ useEffect(() => { setSearch(query); }, [query]);
+ useEffect(() => {
+ const refresh = () => void load();
+ window.addEventListener(DRIVE_REFRESH_EVENT, refresh);
+ return () => window.removeEventListener(DRIVE_REFRESH_EVENT, refresh);
+ }, [load]);
+ useEffect(() => { setSelectedIds(new Set()); }, [requestKey]);
+ // Keep only selected items that are still listed (after a move, trash, upload or reload).
+ useEffect(() => { setSelectedIds((current) => { const present = new Set(items.map((item) => item.id)); const next = new Set([...current].filter((id) => present.has(id))); return next.size === current.size ? current : next; }); }, [items]);
+ useEffect(() => { setHeaderTarget(document.getElementById("drive-header-slot")); }, []);
+
+ const upload = useCallback(async (files: File[]) => {
+ if (!canWrite || !files.length) return;
+ let done = 0;
+ for (const file of files) {
+ if (file.size > DRIVE_MAX_FILE_BYTES) { toast.error(t("drive.tooLarge", { name: file.name, size: formatDriveSize(DRIVE_MAX_FILE_BYTES) })); continue; }
+ const toastId = toast.loading(t("drive.uploading", { name: file.name }));
+ try {
+ await uploadDriveFile(file, folder, (percent, resumed) => toast.loading(`${resumed ? t("drive.resuming", { name: file.name }) : t("drive.uploading", { name: file.name })} ${percent}%`, { id: toastId }));
+ done += 1;
+ toast.dismiss(toastId);
+ } catch (error) {
+ toast.error(error instanceof Error && error.message ? error.message : t("drive.uploadFailed", { name: file.name }), { id: toastId });
+ }
+ }
+ if (done) { toast.success(t("drive.uploaded", { count: done })); await load(); }
+ }, [canWrite, folder, load, t]);
+
+ const canWriteRef = useRef(canWrite);
+ useEffect(() => { canWriteRef.current = canWrite; }, [canWrite]);
+ useEffect(() => {
+ const onUpload = () => { if (canWriteRef.current) fileInput.current?.click(); };
+ const onFolder = () => { if (canWriteRef.current) setNaming({ mode: "create", value: t("drive.untitledFolder") }); };
+ window.addEventListener(DRIVE_UPLOAD_EVENT, onUpload);
+ window.addEventListener(DRIVE_NEW_FOLDER_EVENT, onFolder);
+ return () => { window.removeEventListener(DRIVE_UPLOAD_EVENT, onUpload); window.removeEventListener(DRIVE_NEW_FOLDER_EVENT, onFolder); };
+ }, [t]);
+
+ async function mutate(url: string, init: RequestInit, successMessage?: string) {
+ try {
+ const response = await authFetch(url, init);
+ if (!response.ok) {
+ const data = await response.json().catch(() => ({})) as { error?: string };
+ throw new Error(data.error);
+ }
+ if (successMessage) toast.success(successMessage);
+ await load();
+ return true;
+ } catch (error) {
+ toast.error(error instanceof Error && error.message ? error.message : t("drive.actionFailed"));
+ return false;
+ }
+ }
+
+ const json = (method: string, body: unknown): RequestInit => ({ method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+
+ async function submitName(event: React.FormEvent) {
+ event.preventDefault();
+ if (!naming || !naming.value.trim()) return;
+ const ok = naming.mode === "create"
+ ? await mutate("/api/drive/items", json("POST", { name: naming.value, parentId: folder }))
+ : await mutate(`/api/drive/items/${naming.item!.id}`, json("PATCH", { name: naming.value }));
+ if (ok) setNaming(null);
+ }
+
+ function open(item: DriveItemDto) {
+ if (item.trashedAt) return;
+ if (item.kind === "folder") router.push(`/drive?folder=${encodeURIComponent(item.id)}${view === "shared" ? "&view=shared" : ""}`);
+ else setPreview(item);
+ }
+
+ function onDragEnter(event: DragEvent) {
+ if (!canWrite || !event.dataTransfer.types.includes("Files")) return;
+ event.preventDefault();
+ dragDepth.current += 1;
+ setDragging(true);
+ }
+ function onDragLeave() {
+ dragDepth.current = Math.max(0, dragDepth.current - 1);
+ if (dragDepth.current === 0) setDragging(false);
+ }
+ function onDrop(event: DragEvent) {
+ if (!canWrite || !event.dataTransfer.types.includes("Files")) return;
+ event.preventDefault();
+ dragDepth.current = 0;
+ setDragging(false);
+ void upload([...event.dataTransfer.files]);
+ }
+
+ // Dragging a selected row carries the whole selection; any other row goes alone.
+ function onItemDragStart(event: DragEvent, item: DriveItemDto) {
+ const group = selectedIds.has(item.id) ? selectedItems.filter(isDriveDraggable) : [item];
+ startDriveDrag(event, group, t("drive.selected", { count: group.length }));
+ setMovingIds(new Set(group.map((entry) => entry.id)));
+ }
+ function onItemDragEnd() {
+ endDriveDrag();
+ setMovingIds(new Set());
+ setDropFolder(null);
+ }
+
+ function setTypes(next: DriveCategory[]) {
+ const search = new URLSearchParams(params.toString());
+ if (next.length) search.set("types", next.join(",")); else search.delete("types");
+ router.push(`/drive${search.size ? `?${search}` : ""}`);
+ }
+
+ const sorted = useMemo(() => sortDriveItems(items, sortKey, ascending), [items, sortKey, ascending]);
+ // Attachments can only be selected when the user may delete them.
+ const selectable = sorted.filter((item) => (item.source ? item.source.canDelete : canEditDrive(item.role)));
+ const selectedItems = selectable.filter((item) => selectedIds.has(item.id));
+ const allSelected = selectable.length > 0 && selectedItems.length === selectable.length;
+ useEffect(() => { if (selectAllRef.current) selectAllRef.current.indeterminate = selectedItems.length > 0 && !allSelected; }, [selectedItems.length, allSelected]);
+ const toggleItem = (id: string) => setSelectedIds((current) => { const next = new Set(current); if (!next.delete(id)) next.add(id); return next; });
+ const attachmentsView = view === "attachments" && !folder;
+ const title = view === "attachments" ? t("drive.attachments") : view === "trash" ? t("drive.trash") : view === "shared" ? t("drive.sharedWithMe") : query ? t("drive.search") : t("drive.myDrive");
+ const rootHref = view === "shared" ? "/drive?view=shared" : "/drive";
+ const emptyText = view === "attachments" ? t("drive.emptyAttachments") : view === "trash" ? t("drive.emptyTrash") : view === "shared" ? t("drive.emptyShared") : query ? t("drive.emptySearch") : t("drive.empty");
+
+ function toggleSort(key: DriveSortKey) {
+ if (key === sortKey) setAscending((value) => !value);
+ else { setSortKey(key); setAscending(true); }
+ }
+ const SortIcon = ascending ? ArrowUp : ArrowDown;
+ const headerButton = (key: DriveSortKey, label: string) => (
+ <button type="button" onClick={() => toggleSort(key)} aria-sort={sortKey === key ? (ascending ? "ascending" : "descending") : "none"} className="flex min-w-0 items-center gap-1 font-medium text-neutral-600 hover:text-neutral-900"><span className="truncate">{label}</span>{sortKey === key && <SortIcon size={12} className="shrink-0" />}</button>
+ );
+ const gridStyle = { "--drive-columns": columns.template } as React.CSSProperties;
+
+ return (
+ <div className="relative flex h-full min-h-0 flex-col" onDragEnter={onDragEnter} onDragOver={(event) => { if (canWrite && event.dataTransfer.types.includes("Files")) event.preventDefault(); }} onDragLeave={onDragLeave} onDrop={onDrop}>
+ <Toaster position="bottom-left" containerClassName="text-sm" />
+
+ {headerTarget && createPortal(
+ <HeaderSearch value={search} onChange={setSearch} label={t("drive.search")} onSubmit={() => router.push(search.trim() ? `/drive?q=${encodeURIComponent(search.trim())}` : "/drive")} />,
+ headerTarget,
+ )}
+ <input ref={fileInput} type="file" multiple hidden onChange={(event) => { void upload([...(event.target.files ?? [])]); event.target.value = ""; }} />
+ <div className="flex min-h-0 flex-1 flex-col rounded-t-3xl bg-white">
+ <div className="flex min-h-[4.25rem] shrink-0 items-center justify-between gap-3 border-b border-neutral-200 px-5 py-3">
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-3 gap-y-1">
+ <nav aria-label={title} className="flex min-w-0 flex-wrap items-center gap-1 text-xl text-neutral-800 max-md:text-lg">
+ {path.length === 0 ? <h1 className="font-normal">{title}</h1> : (
+ <>
+ <button type="button" onClick={() => router.push(rootHref)} className="rounded-full px-2 py-1 hover:bg-neutral-100">{view === "shared" || role !== "owner" ? t("drive.sharedWithMe") : t("drive.myDrive")}</button>
+ {path.map((crumb, index) => (
+ <span key={crumb.id} className="flex items-center gap-1">
+ <ChevronRight size={18} className="text-neutral-500" />
+ {index === path.length - 1 ? <h1 className="px-2 py-1 font-normal">{crumb.name}</h1> : <button type="button" onClick={() => router.push(`/drive?folder=${encodeURIComponent(crumb.id)}${view === "shared" ? "&view=shared" : ""}`)} className="rounded-full px-2 py-1 hover:bg-neutral-100">{crumb.name}</button>}
+ </span>
+ ))}
+ </>
+ )}
+ </nav>
+ {selectedItems.length > 0 && (
+ <span className="flex shrink-0 items-center gap-1 text-sm text-neutral-600">
+ <button type="button" onClick={() => setSelectedIds(new Set())} aria-label={t("navigation.close")} className="flex h-8 w-8 items-center justify-center rounded-full hover:bg-neutral-100"><X size={16} /></button>
+ {t("drive.selected", { count: selectedItems.length })}
+ </span>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ {selectedItems.length > 0 && <DriveBulkActions selected={selectedItems} trashView={view === "trash"} onDone={() => { setSelectedIds(new Set()); void load(); }} />}
+ <DriveTypeFilter value={types} onChange={setTypes} />
+ </div>
+ </div>
+ {view === "trash" && !folder && <p className="shrink-0 border-b border-neutral-200 bg-neutral-50 px-5 py-2 text-xs text-neutral-600">{t("drive.trashNotice", { days: 30 })}</p>}
+ <div style={gridStyle} className="grid shrink-0 grid-cols-[2rem_minmax(0,1fr)_2.5rem] items-center gap-x-4 border-b border-neutral-200 px-5 py-2 text-sm md:grid-cols-[var(--drive-columns)]">
+ <Checkbox ref={selectAllRef} checked={allSelected} onChange={() => setSelectedIds(allSelected ? new Set() : new Set(selectable.map((item) => item.id)))} disabled={selectable.length === 0} aria-label={t("drive.selectAll")} className="ml-1" />
+ <span className="min-w-0 pl-7">{headerButton("name", t("drive.name"))}</span>
+ <span className="relative hidden min-w-0 md:block">{headerButton("owner", attachmentsView ? t("drive.from") : t("drive.owner"))}<ColumnResizeHandle column="owner" width={columns.widths.owner} onResize={columns.resize} label={t("drive.owner")} /></span>
+ <span className="relative hidden min-w-0 md:block">{headerButton("updatedAt", t("drive.modified"))}<ColumnResizeHandle column="updatedAt" width={columns.widths.updatedAt} onResize={columns.resize} label={t("drive.modified")} /></span>
+ <span className="relative hidden min-w-0 md:block">{headerButton("size", t("drive.fileSize"))}<ColumnResizeHandle column="size" width={columns.widths.size} onResize={columns.resize} label={t("drive.fileSize")} /></span>
+ <span />
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-2 space-y-px pt-px">
+ {failed ? <p className="p-8 text-center text-sm text-neutral-500">{t("drive.loadFailed")}</p>
+ : !loading && sorted.length === 0 ? <p className="p-12 text-center text-sm text-neutral-500">{emptyText}</p>
+ : sorted.map((item) => {
+ const { Icon, className } = driveIconFor(item);
+ // Only the owner's own folders take drops, matching what the move endpoint allows.
+ const dropTarget = item.kind === "folder" && item.role === "owner" && !item.trashedAt && !item.source
+ ? driveDropHandlers({ kind: "folder", id: item.id }, () => canDropDrive({ kind: "folder", id: item.id }), t, (over) => setDropFolder((current) => (over ? item.id : current === item.id ? null : current)))
+ : {};
+ return (
+ <div key={item.id} role="row" style={gridStyle} draggable={isDriveDraggable(item)} onDragStart={(event) => onItemDragStart(event, item)} onDragEnd={onItemDragEnd} {...dropTarget} className={clsx("group grid grid-cols-[2rem_minmax(0,1fr)_2.5rem] items-center gap-x-4 rounded-lg px-3 text-sm md:grid-cols-[var(--drive-columns)]", dropFolder === item.id ? "bg-blue-100 ring-2 ring-inset ring-blue-500" : selectedIds.has(item.id) ? "bg-blue-50" : "hover:bg-neutral-50", movingIds.has(item.id) && "opacity-50")}>
+ <Checkbox checked={selectedIds.has(item.id)} onChange={() => toggleItem(item.id)} disabled={!selectable.includes(item)} aria-label={t("drive.selectItem", { name: item.name })} className={clsx("ml-1", !selectable.includes(item) && "invisible")} />
+ <button type="button" onClick={() => open(item)} aria-disabled={item.trashedAt ? true : undefined} className="flex min-w-0 items-center gap-3 py-3 text-left aria-disabled:cursor-default">
+ <Icon size={16} className={clsx("shrink-0", className)} fill={item.kind === "folder" ? "currentColor" : "none"} />
+ <span className="truncate text-neutral-900">{item.name}</span>
+ {item.shared && item.role === "owner" && <Share2 size={12} className="shrink-0 text-neutral-400" aria-label={t("drive.share")} />}
+ </button>
+ <span className="hidden md:block"><DriveOwnerAvatar item={item} /></span>
+ <span className="hidden text-neutral-600 md:block">{dateFormat.format(new Date(item.updatedAt))}</span>
+ <span className="hidden text-neutral-600 md:block">{item.kind === "file" ? formatDriveSize(item.size) : "—"}</span>
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger asChild>
+ <button type="button" aria-label={t("drive.actions")} className="flex h-9 w-9 items-center justify-center rounded-full text-neutral-600 hover:bg-neutral-200"><MoreVertical size={16} /></button>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Portal>
+ <DropdownMenu.Content align="end" sideOffset={4} className="z-[200] min-w-52 rounded-xl border border-neutral-200 bg-white p-1.5 shadow-xl">
+ {!item.trashedAt && <DropdownMenu.Item className={menuItemClass} onSelect={() => open(item)}>{t("drive.open")}</DropdownMenu.Item>}
+ {item.kind === "file" && !(item.source && item.trashedAt) && <DropdownMenu.Item asChild className={menuItemClass}><a href={driveFileUrl(item, true)}><Download size={16} />{t("drive.download")}</a></DropdownMenu.Item>}
+ {item.source && !item.trashedAt && <DropdownMenu.Item asChild className={menuItemClass}><a href={emailUrl(item.source)} target="_blank" rel="noopener noreferrer"><Mail size={16} />{t("drive.openEmail")}</a></DropdownMenu.Item>}
+ {item.role === "owner" && !item.trashedAt && <DropdownMenu.Item className={menuItemClass} onSelect={() => setSharing(item)}><Share2 size={16} />{t("drive.share")}</DropdownMenu.Item>}
+ {canEditDrive(item.role) && !item.trashedAt && <DropdownMenu.Item className={menuItemClass} onSelect={() => setNaming({ mode: "rename", item, value: item.name })}><Pencil size={16} />{t("drive.rename")}</DropdownMenu.Item>}
+ {item.source?.canDelete && !item.trashedAt && <DropdownMenu.Item className={menuItemClass} onSelect={() => void mutate("/api/drive/attachments", json("POST", { action: "trash", ids: [item.id] }), t("drive.trashed"))}><Trash2 size={16} />{t("drive.moveToTrash")}</DropdownMenu.Item>}
+ {canEditDrive(item.role) && !item.source && !item.trashedAt && <DropdownMenu.Item className={menuItemClass} onSelect={() => void mutate(`/api/drive/items/${item.id}`, json("PATCH", { trashed: true }), t("drive.trashed"))}><Trash2 size={16} />{t("drive.moveToTrash")}</DropdownMenu.Item>}
+ {item.trashedAt && <DropdownMenu.Item className={menuItemClass} onSelect={() => void (item.source ? mutate("/api/drive/attachments", json("POST", { action: "restore", ids: [item.id] }), t("drive.restored")) : mutate(`/api/drive/items/${item.id}`, json("PATCH", { trashed: false }), t("drive.restored")))}><RotateCcw size={16} />{t("drive.restore")}</DropdownMenu.Item>}
+ {item.trashedAt && <DropdownMenu.Item className={clsx(menuItemClass, "text-red-600")} onSelect={() => { if (window.confirm(t("drive.confirmDelete", { name: item.name }))) void (item.source ? mutate("/api/drive/attachments", json("POST", { action: "delete", ids: [item.id] }), t("drive.deleted")) : mutate(`/api/drive/items/${item.id}`, { method: "DELETE" }, t("drive.deleted"))); }}><X size={16} />{t("drive.deleteForever")}</DropdownMenu.Item>}
+ </DropdownMenu.Content>
+ </DropdownMenu.Portal>
+ </DropdownMenu.Root>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ {dragging && <div className="pointer-events-none absolute inset-2 z-20 flex items-center justify-center rounded-2xl border-2 border-dashed border-blue-500 bg-blue-50/80 text-blue-700"><UploadCloud size={28} /><span className="ml-3 text-base font-medium">{t("drive.fileUpload")}</span></div>}
+
+ <Dialog open={!!naming} onOpenChange={(openState) => { if (!openState) setNaming(null); }}>
+ <DialogContent>
+ <DialogHeader><DialogTitle>{naming?.mode === "create" ? t("drive.newFolder") : t("drive.renameTitle")}</DialogTitle></DialogHeader>
+ <form onSubmit={submitName} className="space-y-5">
+ <Input autoFocus value={naming?.value ?? ""} onChange={(event) => setNaming((current) => current && { ...current, value: event.target.value })} onFocus={(event) => event.currentTarget.select()} aria-label={t("drive.folderName")} maxLength={255} />
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="ghost" onClick={() => setNaming(null)}>{t("common.cancel")}</Button>
+ <Button type="submit" disabled={!naming?.value.trim()}>{naming?.mode === "create" ? t("drive.create") : t("drive.save")}</Button>
+ </div>
+ </form>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog open={!!preview} onOpenChange={(openState) => { if (!openState) setPreview(null); }}>
+ <DialogContent overlayClassName="bg-black/65 backdrop-blur-sm" closeClassName="text-white hover:bg-[rgb(255_255_255/0.15)] hover:text-white" className="h-[min(85vh,900px)] w-[min(1100px,calc(100vw-32px))] max-w-none overflow-hidden bg-transparent p-0 shadow-none">
+ {preview && (
+ <div className="flex h-full flex-col">
+ <DialogTitle className="flex h-14 shrink-0 items-center justify-between gap-3 pl-5 pr-14 text-white">
+ <span className="truncate text-base font-medium">{preview.name}</span>
+ <span className="flex shrink-0 items-center gap-1">
+ {preview.source && <a href={emailUrl(preview.source)} target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 rounded-full px-3 py-2 text-sm hover:bg-[rgb(255_255_255/0.15)]"><Mail size={16} />{t("drive.openEmail")}<ExternalLink size={12} /></a>}
+ <a href={driveFileUrl(preview, true)} aria-label={t("drive.download")} className="rounded-full p-2 hover:bg-[rgb(255_255_255/0.15)]"><Download size={18} /></a>
+ </span>
+ </DialogTitle>
+ <div className="min-h-0 flex-1 p-3 pt-0"><DrivePreviewBody src={driveFileUrl(preview)} downloadHref={driveFileUrl(preview, true)} contentType={preview.contentType} name={preview.name} /></div>
+ </div>
+ )}
+ </DialogContent>
+ </Dialog>
+
+ <DriveShareDialog item={sharing} onClose={() => setSharing(null)} onChanged={() => void load()} />
+ </div>
+ );
+}
diff --git a/src/app/(drive)/layout.tsx b/src/app/(drive)/layout.tsx
new file mode 100644
index 0000000..3b4dafa
--- /dev/null
+++ b/src/app/(drive)/layout.tsx
@@ -0,0 +1,58 @@
+"use client";
+
+import { Suspense } from "react";
+import { AuthGuard } from "@/components/auth/auth-guard";
+import { ComposeProvider } from "@/components/compose/compose-context";
+import { LicenseIndicator } from "@/components/license-indicator";
+import { MailSearchProvider } from "@/components/mail-search/mail-search-context";
+import { MailboxProvider } from "@/components/mailbox-provider";
+import { MailboxSelector } from "@/components/mailbox-selector";
+import { SidebarAside, MobileMenuButton } from "@/components/sidebar-aside";
+import { SidebarHeader } from "@/components/sidebar-header";
+import { SidebarResizeBoundary } from "@/components/sidebar-resize-boundary";
+import { SidebarProvider, useSidebar } from "@/components/sidebar-state";
+import { ShortcutsProvider } from "@/components/shortcuts";
+import { DriveNav } from "./drive-nav";
+
+function DriveFrame({ children }: { children: React.ReactNode }) {
+ const { mobile, toggle } = useSidebar();
+ // Same grid and sidebar width as the dashboard, so the menu and the search line up and resizing carries over.
+ return (
+ <div className="grid h-dvh grid-cols-[minmax(0,1fr)] overflow-hidden bg-[#f6f8fc] transition-[grid-template-columns] md:grid-cols-[var(--sidebar-width)_minmax(0,1fr)]" style={{ transitionDuration: "var(--sidebar-transition-duration)" }}>
+ <SidebarAside>
+ <div className="flex h-full min-h-0 flex-col">
+ <div className="shrink-0 px-3 pt-4"><SidebarHeader href="/inbox" /></div>
+ <Suspense fallback={null}><DriveNav onNavigate={mobile ? toggle : undefined} /></Suspense>
+ </div>
+ <SidebarResizeBoundary />
+ </SidebarAside>
+ <div className="flex min-h-0 min-w-0 flex-col">
+ <header className="flex h-16 w-full shrink-0 items-center gap-3 pr-4 text-sm">
+ <MobileMenuButton className="ml-2" />
+ <div id="drive-header-slot" className="flex min-w-0 flex-1 items-center" />
+ <LicenseIndicator />
+ <MailboxSelector />
+ </header>
+ <main className="min-h-0 min-w-0 flex-1 overflow-hidden md:pr-4">{children}</main>
+ </div>
+ </div>
+ );
+}
+
+export default function DriveLayout({ children }: { children: React.ReactNode }) {
+ return (
+ <AuthGuard>
+ <SidebarProvider mobileOverlay>
+ <MailboxProvider>
+ <ComposeProvider>
+ <MailSearchProvider>
+ <ShortcutsProvider>
+ <DriveFrame>{children}</DriveFrame>
+ </ShortcutsProvider>
+ </MailSearchProvider>
+ </ComposeProvider>
+ </MailboxProvider>
+ </SidebarProvider>
+ </AuthGuard>
+ );
+}
diff --git a/src/app/api/accounts/[id]/route.ts b/src/app/api/accounts/[id]/route.ts
index fe6f917..d038d59 100644
--- a/src/app/api/accounts/[id]/route.ts
+++ b/src/app/api/accounts/[id]/route.ts
@@ -4,6 +4,7 @@ import { getDb } from "@/db";
import { users } from "@/db/schema";
import { updateManagedAccountSchema } from "@/lib/validators";
import { requireTeamAdmin } from "../utils";
+import { getAccountSeatError } from "@/lib/licenses/seats";
import { getLicenseEntitlements } from "@/lib/licenses/service";
import { canManageUsers, isPrimaryAdmin } from "@/lib/auth/admin";
import type { AccountRouteParams } from "./types";
@@ -67,6 +68,10 @@ export async function PATCH(request: Request, { params }: AccountRouteParams) {
if (!canForwardEmail && parsed.data.forwardingEmail && parsed.data.forwardingEmail !== account.forwardingEmail) {
return NextResponse.json({ error: "A Pro or Team license is required for email forwarding" }, { status: 403 });
}
+ if (account.disabled && !parsed.data.disabled) {
+ const seatError = await getAccountSeatError(access.env);
+ if (seatError) return NextResponse.json({ error: seatError }, { status: 403 });
+ }
await updateAccountCredentials(db, id, { name: parsed.data.name, password: parsed.data.password ?? null });
// A password set by an admin is a reset: whoever held the old one is signed out.
if (parsed.data.password) await deleteUserSessions(access.env, id);
diff --git a/src/app/api/accounts/create.ts b/src/app/api/accounts/create.ts
index a38de2e..6569cd2 100644
--- a/src/app/api/accounts/create.ts
+++ b/src/app/api/accounts/create.ts
@@ -8,12 +8,15 @@ import { rollbackEmailRoutingRuleChanges } from "@/lib/cloudflare-api";
import type { CfEmailRoutingRuleChange } from "@/lib/cloudflare-api.types";
import { normalizeRecipientLocalPart } from "@/lib/email/recipient-address";
import { newId } from "@/lib/ids";
+import { getAccountSeatError } from "@/lib/licenses/seats";
import { ensureMailboxDomainRouting } from "@/lib/mailboxes/domain-addresses";
import type { CreateUserAccountInput } from "./types";
import { accountListItemFromUser, getDomainForAdmin } from "./utils";
/** Shared by dashboard and admin API/MCP account creation. */
export async function createAccountResponse(env: CloudflareEnv, adminUserId: string, input: CreateUserAccountInput) {
+ const seatError = await getAccountSeatError(env);
+ if (seatError) return NextResponse.json({ error: seatError }, { status: 403 });
const db = getDb(env);
const primaryDomain = await getDomainForAdmin(db, adminUserId, input.domainId);
if (!primaryDomain) return NextResponse.json({ error: "Domain not found" }, { status: 404 });
diff --git a/src/app/api/accounts/route.ts b/src/app/api/accounts/route.ts
index 556b5bc..7a0269f 100644
--- a/src/app/api/accounts/route.ts
+++ b/src/app/api/accounts/route.ts
@@ -2,6 +2,8 @@ import { NextResponse } from "next/server";
import { getDb } from "@/db";
import { createUserAccountSchema } from "@/lib/validators";
import { canManageUsers, isPrimaryAdmin } from "@/lib/auth/admin";
+import { getLicenseEntitlements } from "@/lib/licenses/service";
+import { countUsedAccountSeats } from "@/lib/licenses/seats";
import { createAccountResponse } from "./create";
import { accountListItemFromUser, listAccountsForAdmin, requireTeamAdmin } from "./utils";
@@ -9,8 +11,10 @@ export async function GET(request: Request) {
const access = await requireTeamAdmin(request);
if (access.error) return access.error;
const rows = await listAccountsForAdmin(getDb(access.env));
+ const [{ accountSeatLimit }, seatsUsed] = await Promise.all([getLicenseEntitlements(access.env), countUsedAccountSeats(access.env)]);
return NextResponse.json({
accounts: rows.map((row) => accountListItemFromUser(row)),
+ seats: { limit: accountSeatLimit, used: seatsUsed },
});
}
diff --git a/src/app/api/accounts/utils.ts b/src/app/api/accounts/utils.ts
index d1c9703..d42503d 100644
--- a/src/app/api/accounts/utils.ts
+++ b/src/app/api/accounts/utils.ts
@@ -77,6 +77,16 @@ export function accountListItemFromUser(user: {
};
}
+/** Admin session on an installation licensed for Team-only mailbox sharing. */
+export async function requireTeamSharingAdmin(request: Request) {
+ const access = await requireTeamAdmin(request);
+ if (access.error) return access;
+ if (!(await getLicenseEntitlements(access.env)).canShareMailboxes) {
+ return { ...access, error: NextResponse.json({ error: "A Team license is required to share inboxes" }, { status: 403 }) };
+ }
+ return access;
+}
+
export async function requireTeamAdmin(request: Request) {
const env = getEnv();
try {
@@ -86,7 +96,7 @@ export async function requireTeamAdmin(request: Request) {
return {
env,
user,
- error: NextResponse.json({ error: "A Team license is required to manage accounts" }, { status: 403 }),
+ error: NextResponse.json({ error: "A Pro or Team license is required to manage accounts" }, { status: 403 }),
};
}
return { env, user, error: null };
diff --git a/src/app/api/admin/general/utils.ts b/src/app/api/admin/general/utils.ts
index 4cad9ed..17e9949 100644
--- a/src/app/api/admin/general/utils.ts
+++ b/src/app/api/admin/general/utils.ts
@@ -6,15 +6,27 @@ import { requireSessionUser } from "@/lib/api/auth";
import { isPrimaryAdmin } from "@/lib/auth/admin";
import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";
import { getOutboundAttachmentMaxMb, MAX_OUTBOUND_ATTACHMENT_MAX_MB } from "@/lib/email/attachment-policy";
+import { getDriveStorageLimit } from "@/lib/drive/storage";
-const schema = z.object({ outboundAttachmentMaxMb: z.number().int().min(1).max(MAX_OUTBOUND_ATTACHMENT_MAX_MB) });
+const GIB = 1024 ** 3;
+
+const schema = z.object({
+ outboundAttachmentMaxMb: z.number().int().min(1).max(MAX_OUTBOUND_ATTACHMENT_MAX_MB).optional(),
+ /** Per-user Drive limit in GB; null removes the limit. */
+ driveStorageLimitGb: z.number().positive().max(1_000_000).nullable().optional(),
+});
+
+async function readSettings(env: CloudflareEnv) {
+ const limit = await getDriveStorageLimit(env);
+ return { outboundAttachmentMaxMb: await getOutboundAttachmentMaxMb(env), driveStorageLimitGb: limit === null ? null : Math.round((limit / GIB) * 100) / 100 };
+}
export async function GET(request: Request) {
const env = getEnv();
const auth = await requireSessionUser(env, request);
if (auth.error) return auth.error;
if (!isPrimaryAdmin(auth.user)) return Response.json({ error: "Forbidden" }, { status: 403 });
- return Response.json({ outboundAttachmentMaxMb: await getOutboundAttachmentMaxMb(env) }, { headers: { "Cache-Control": "no-store" } });
+ return Response.json(await readSettings(env), { headers: { "Cache-Control": "no-store" } });
}
export async function PUT(request: Request) {
@@ -24,8 +36,10 @@ export async function PUT(request: Request) {
if (!isPrimaryAdmin(auth.user)) return Response.json({ error: "Forbidden" }, { status: 403 });
if (!hasValidSessionMutationOrigin(request)) return Response.json({ error: "Invalid origin" }, { status: 403 });
const parsed = schema.safeParse(await request.json().catch(() => null));
- if (!parsed.success) return Response.json({ error: "Choose a whole number from 1 to 25 MB" }, { status: 400 });
- const values = { outboundAttachmentMaxMb: parsed.data.outboundAttachmentMaxMb, updatedAt: new Date() };
+ if (!parsed.success || (parsed.data.outboundAttachmentMaxMb === undefined && parsed.data.driveStorageLimitGb === undefined)) return Response.json({ error: "Enter a valid attachment limit (1 to 25 MB) or Drive storage limit" }, { status: 400 });
+ const values: Partial<typeof appSettings.$inferInsert> = { updatedAt: new Date() };
+ if (parsed.data.outboundAttachmentMaxMb !== undefined) values.outboundAttachmentMaxMb = parsed.data.outboundAttachmentMaxMb;
+ if (parsed.data.driveStorageLimitGb !== undefined) values.driveStorageLimitBytes = parsed.data.driveStorageLimitGb === null ? null : Math.round(parsed.data.driveStorageLimitGb * GIB);
await getDb(env).insert(appSettings).values({ id: "default", ...values }).onConflictDoUpdate({ target: appSettings.id, set: values });
- return Response.json(values, { headers: { "Cache-Control": "no-store" } });
+ return Response.json(await readSettings(env), { headers: { "Cache-Control": "no-store" } });
}
diff --git a/src/app/api/booking/[eventId]/route.ts b/src/app/api/booking/[eventId]/route.ts
index 71843cf..f32dc12 100644
--- a/src/app/api/booking/[eventId]/route.ts
+++ b/src/app/api/booking/[eventId]/route.ts
@@ -19,7 +19,7 @@ export async function PATCH(request: Request, { params }: BookingEventRouteConte
if (!input) return NextResponse.json({ error: "Enter valid booking details and availability." }, { status: 400 });
const { eventId } = await params;
const db = getDb(env);
- const canManageHosts = user.role === "admin" && (await getLicenseEntitlements(env)).canManageAccounts;
+ const canManageHosts = user.role === "admin" && (await getLicenseEntitlements(env)).canShareMailboxes;
const hostIds = await validBookingHostIds(db, user.id, input.hostIds, canManageHosts);
if (!hostIds) return NextResponse.json({ error: "Choose users from the host list." }, { status: 400 });
const [taken] = await db.select({ id: bookingEvents.id }).from(bookingEvents).where(and(eq(bookingEvents.userId, user.id), eq(bookingEvents.slug, input.slug))).limit(1);
diff --git a/src/app/api/booking/route.ts b/src/app/api/booking/route.ts
index a10f7f0..91e5a67 100644
--- a/src/app/api/booking/route.ts
+++ b/src/app/api/booking/route.ts
@@ -19,7 +19,7 @@ export async function GET(request: Request) {
const db = getDb(env);
const events = await db.select().from(bookingEvents).where(eq(bookingEvents.userId, user.id)).orderBy(bookingEvents.createdAt);
const [currentUser] = await db.select({ avatarKey: users.avatarKey }).from(users).where(eq(users.id, user.id)).limit(1);
- const canManageHosts = user.role === "admin" && (await getLicenseEntitlements(env)).canManageAccounts;
+ const canManageHosts = user.role === "admin" && (await getLicenseEntitlements(env)).canShareMailboxes;
return NextResponse.json({ events, username, currentUser: { id: user.id, name: user.name, email: user.email, hasAvatar: !!currentUser?.avatarKey }, canManageHosts });
}
@@ -31,7 +31,7 @@ export async function POST(request: Request) {
const input = parseBookingEventInput(await request.json().catch(() => null));
if (!input) return NextResponse.json({ error: "Enter valid booking details and availability." }, { status: 400 });
const db = getDb(env);
- const canManageHosts = user.role === "admin" && (await getLicenseEntitlements(env)).canManageAccounts;
+ const canManageHosts = user.role === "admin" && (await getLicenseEntitlements(env)).canShareMailboxes;
const hostIds = await validBookingHostIds(db, user.id, input.hostIds, canManageHosts);
if (!hostIds) return NextResponse.json({ error: "Choose users from the host list." }, { status: 400 });
const [taken] = await db.select({ id: bookingEvents.id }).from(bookingEvents).where(and(eq(bookingEvents.userId, user.id), eq(bookingEvents.slug, input.slug))).limit(1);
diff --git a/src/app/api/drive/attachments/[id]/content/route.ts b/src/app/api/drive/attachments/[id]/content/route.ts
new file mode 100644
index 0000000..65fbb8e
--- /dev/null
+++ b/src/app/api/drive/attachments/[id]/content/route.ts
@@ -0,0 +1,23 @@
+import { eq } from "drizzle-orm";
+import { getDb } from "@/db";
+import { messageAttachments } from "@/db/schema";
+import { getEnv } from "@/lib/cloudflare";
+import { requireSessionUser } from "@/lib/api/auth";
+import { getAttachmentForUser } from "@/lib/email/attachments";
+import { streamDriveFile } from "@/lib/drive/content";
+import type { DriveRow } from "@/lib/drive/types";
+import type { DriveItemParams } from "../../../items/[id]/types";
+
+/** Streams an email attachment for the Drive preview, with range support and a CSP that lets PDFs render. */
+export async function GET(request: Request, { params }: DriveItemParams) {
+ const { id } = await params;
+ const env = getEnv();
+ const { user, error } = await requireSessionUser(env, request);
+ if (error) return error;
+ const [row] = await getDb(env).select({ messageId: messageAttachments.messageId }).from(messageAttachments).where(eq(messageAttachments.id, id)).limit(1);
+ const result = row ? await getAttachmentForUser(env, user, row.messageId, id) : null;
+ if (!result) return new Response("Not found", { status: 404 });
+ const { attachment } = result;
+ const file: DriveRow = { id: attachment.id, ownerId: row.messageId, parentId: null, kind: "file", name: attachment.filename, r2Key: attachment.r2Key, size: attachment.size, contentType: attachment.contentType, uploadId: null, uploadPartSize: null, uploadFingerprint: null, linkToken: null, trashedAt: null, createdAt: attachment.createdAt, updatedAt: attachment.createdAt };
+ return streamDriveFile(env, request, file, new URL(request.url).searchParams.get("download") === "1");
+}
diff --git a/src/app/api/drive/attachments/route.ts b/src/app/api/drive/attachments/route.ts
new file mode 100644
index 0000000..c3bfd81
--- /dev/null
+++ b/src/app/api/drive/attachments/route.ts
@@ -0,0 +1,65 @@
+import { eq, inArray } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { getDb } from "@/db";
+import { messageAttachments, messages } from "@/db/schema";
+import { authorizeDrive } from "@/lib/drive/auth";
+import { getMailboxAccessLevel, hasMailboxPermission } from "@/lib/mailboxes/access";
+
+const MAX_BULK = 200;
+
+/**
+ * Trash, restore or permanently delete email attachments.
+ *
+ * - `trash` hides the attachment from the email and lists it in the Drive trash; it is purged after 30 days.
+ * - `restore` puts it back on the email.
+ * - `delete` removes the database row and the stored file for good, and only works on trashed attachments.
+ *
+ * The message itself is never touched. Read-only mailbox access is not enough for any of these.
+ */
+export async function POST(request: Request) {
+ const auth = await authorizeDrive(request, true);
+ if (auth.error) return auth.error;
+ const { env, user } = auth;
+ const db = getDb(env);
+ const body = await request.json().catch(() => ({})) as { action?: unknown; ids?: unknown };
+ const ids = Array.isArray(body.ids) ? [...new Set(body.ids.filter((id): id is string => typeof id === "string"))] : [];
+ if (body.action !== "trash" && body.action !== "restore" && body.action !== "delete") return NextResponse.json({ error: "Unknown action" }, { status: 400 });
+ if (!ids.length || ids.length > MAX_BULK) return NextResponse.json({ error: "Select between 1 and 200 attachments" }, { status: 400 });
+
+ const permitted: { id: string; r2Key: string; trashedAt: Date | null }[] = [];
+ const accessCache = new Map<string, boolean>();
+ let denied = 0;
+ for (let index = 0; index < ids.length; index += 50) {
+ const rows = await db
+ .select({ id: messageAttachments.id, r2Key: messageAttachments.r2Key, trashedAt: messageAttachments.trashedAt, mailboxId: messages.mailboxId, userId: messages.userId })
+ .from(messageAttachments)
+ .innerJoin(messages, eq(messageAttachments.messageId, messages.id))
+ .where(inArray(messageAttachments.id, ids.slice(index, index + 50)));
+ for (const row of rows) {
+ let allowed: boolean;
+ if (!row.mailboxId) allowed = row.userId === user.id;
+ else {
+ if (!accessCache.has(row.mailboxId)) {
+ const access = await getMailboxAccessLevel(db, user, row.mailboxId);
+ accessCache.set(row.mailboxId, !!access && hasMailboxPermission(access.permission, "send_on_behalf"));
+ }
+ allowed = accessCache.get(row.mailboxId)!;
+ }
+ if (allowed) permitted.push({ id: row.id, r2Key: row.r2Key, trashedAt: row.trashedAt }); else denied += 1;
+ }
+ }
+ if (denied && !permitted.length) return NextResponse.json({ error: "You cannot change these attachments" }, { status: 403 });
+
+ let targets = permitted;
+ if (body.action === "trash") targets = permitted.filter((row) => !row.trashedAt);
+ else targets = permitted.filter((row) => row.trashedAt);
+ const targetIds = targets.map((row) => row.id);
+
+ for (let index = 0; index < targetIds.length; index += 50) {
+ const slice = targetIds.slice(index, index + 50);
+ if (body.action === "delete") await db.delete(messageAttachments).where(inArray(messageAttachments.id, slice));
+ else await db.update(messageAttachments).set({ trashedAt: body.action === "trash" ? new Date() : null }).where(inArray(messageAttachments.id, slice));
+ }
+ if (body.action === "delete" && targets.length) await env.BUCKET.delete(targets.map((row) => row.r2Key));
+ return NextResponse.json({ count: targets.length, denied });
+}
diff --git a/src/app/api/drive/folders/route.ts b/src/app/api/drive/folders/route.ts
new file mode 100644
index 0000000..e3f7534
--- /dev/null
+++ b/src/app/api/drive/folders/route.ts
@@ -0,0 +1,15 @@
+import { and, eq, isNull } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { driveItems } from "@/db/schema";
+import { authorizeDrive } from "@/lib/drive/auth";
+import { withoutTrashedAncestors } from "@/lib/drive/access";
+
+/** Every folder the user owns (not trashed), flat; the client builds the tree for the "Move to folder" menu. */
+export async function GET(request: Request) {
+ const auth = await authorizeDrive(request);
+ if (auth.error) return auth.error;
+ const { db, user } = auth;
+ const rows = await db.select().from(driveItems).where(and(eq(driveItems.ownerId, user.id), eq(driveItems.kind, "folder"), isNull(driveItems.trashedAt))).limit(2000);
+ const folders = await withoutTrashedAncestors(db, rows);
+ return NextResponse.json({ folders: folders.map((folder) => ({ id: folder.id, name: folder.name, parentId: folder.parentId })) });
+}
diff --git a/src/app/api/drive/items/[id]/content/route.ts b/src/app/api/drive/items/[id]/content/route.ts
new file mode 100644
index 0000000..b2788ee
--- /dev/null
+++ b/src/app/api/drive/items/[id]/content/route.ts
@@ -0,0 +1,14 @@
+import { authorizeDrive } from "@/lib/drive/auth";
+import { getDriveItem, getDriveRole } from "@/lib/drive/access";
+import { streamDriveFile } from "@/lib/drive/content";
+import type { DriveItemParams } from "../types";
+
+export async function GET(request: Request, { params }: DriveItemParams) {
+ const { id } = await params;
+ const auth = await authorizeDrive(request);
+ if (auth.error) return auth.error;
+ const { env, db, user } = auth;
+ const item = await getDriveItem(db, id);
+ if (!item || !(await getDriveRole(db, user.id, item))) return new Response("Not found", { status: 404 });
+ return streamDriveFile(env, request, item, new URL(request.url).searchParams.get("download") === "1");
+}
diff --git a/src/app/api/drive/items/[id]/link/route.ts b/src/app/api/drive/items/[id]/link/route.ts
new file mode 100644
index 0000000..3729d0b
--- /dev/null
+++ b/src/app/api/drive/items/[id]/link/route.ts
@@ -0,0 +1,20 @@
+import { eq } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { driveItems } from "@/db/schema";
+import { newId } from "@/lib/ids";
+import { authorizeDrive } from "@/lib/drive/auth";
+import { getDriveItem } from "@/lib/drive/access";
+import type { DriveItemParams } from "../types";
+
+/** Turns the "anyone with the link can view" URL on or off. Turning it off invalidates the old token. */
+export async function POST(request: Request, { params }: DriveItemParams) {
+ const { id } = await params;
+ const auth = await authorizeDrive(request, true);
+ if (auth.error) return auth.error;
+ const item = await getDriveItem(auth.db, id);
+ if (!item || item.ownerId !== auth.user.id || item.trashedAt) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ const body = await request.json().catch(() => ({})) as { enabled?: unknown };
+ const linkToken = body.enabled ? item.linkToken ?? `${newId()}${newId()}`.replace(/[^A-Za-z0-9]/g, "").slice(0, 32) : null;
+ await auth.db.update(driveItems).set({ linkToken }).where(eq(driveItems.id, id));
+ return NextResponse.json({ linkToken });
+}
diff --git a/src/app/api/drive/items/[id]/route.ts b/src/app/api/drive/items/[id]/route.ts
new file mode 100644
index 0000000..41c4516
--- /dev/null
+++ b/src/app/api/drive/items/[id]/route.ts
@@ -0,0 +1,46 @@
+import { eq } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { driveItems } from "@/db/schema";
+import { authorizeDrive } from "@/lib/drive/auth";
+import { deleteDriveItems, getDriveItem, getDriveRole, toDriveItemDtos } from "@/lib/drive/access";
+import { canEditDrive, normalizeDriveName } from "@/lib/drive/utils";
+import type { DriveItemParams } from "./types";
+
+/** Rename, move to trash or restore. */
+export async function PATCH(request: Request, { params }: DriveItemParams) {
+ const { id } = await params;
+ const auth = await authorizeDrive(request, true);
+ if (auth.error) return auth.error;
+ const { db, user } = auth;
+ const item = await getDriveItem(db, id);
+ if (!item) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ const body = await request.json().catch(() => ({})) as { name?: unknown; trashed?: unknown };
+ const restoring = body.trashed === false && !!item.trashedAt;
+ const role = await getDriveRole(db, user.id, item, restoring);
+ if (!canEditDrive(role)) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ // Editors may move an item to the trash; only the owner can bring it back.
+ if (body.trashed === false && role !== "owner") return NextResponse.json({ error: "Only the owner can do that" }, { status: 403 });
+ const patch: Partial<typeof driveItems.$inferInsert> = { updatedAt: new Date() };
+ if (body.name !== undefined) {
+ const name = normalizeDriveName(body.name);
+ if (!name) return NextResponse.json({ error: "Enter a name" }, { status: 400 });
+ patch.name = name;
+ }
+ if (typeof body.trashed === "boolean") patch.trashedAt = body.trashed ? new Date() : null;
+ await db.update(driveItems).set(patch).where(eq(driveItems.id, id));
+ const [updated] = await toDriveItemDtos(db, [{ ...item, ...patch } as typeof item], user.id, () => role!);
+ return NextResponse.json({ item: updated });
+}
+
+/** Permanently deletes an item the owner has already moved to the trash. */
+export async function DELETE(request: Request, { params }: DriveItemParams) {
+ const { id } = await params;
+ const auth = await authorizeDrive(request, true);
+ if (auth.error) return auth.error;
+ const { env, db, user } = auth;
+ const item = await getDriveItem(db, id);
+ if (!item || item.ownerId !== user.id) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ if (!item.trashedAt) return NextResponse.json({ error: "Move the item to trash first" }, { status: 409 });
+ await deleteDriveItems(env, [item]);
+ return NextResponse.json({ ok: true });
+}
diff --git a/src/app/api/drive/items/[id]/shares/route.ts b/src/app/api/drive/items/[id]/shares/route.ts
new file mode 100644
index 0000000..982bf6c
--- /dev/null
+++ b/src/app/api/drive/items/[id]/shares/route.ts
@@ -0,0 +1,55 @@
+import { and, eq } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { driveShares, users } from "@/db/schema";
+import { newId } from "@/lib/ids";
+import { authorizeDrive } from "@/lib/drive/auth";
+import { getDriveItem } from "@/lib/drive/access";
+import type { DriveItemParams } from "../types";
+
+async function loadOwnedItem(request: Request, params: DriveItemParams["params"], mutation: boolean) {
+ const { id } = await params;
+ const auth = await authorizeDrive(request, mutation);
+ if (auth.error) return { error: auth.error } as const;
+ const item = await getDriveItem(auth.db, id);
+ if (!item || item.ownerId !== auth.user.id || item.trashedAt) return { error: NextResponse.json({ error: "Not found" }, { status: 404 }) } as const;
+ return { ...auth, item } as const;
+}
+
+async function listShares(db: Parameters<typeof getDriveItem>[0], itemId: string) {
+ return db
+ .select({ id: driveShares.id, userId: driveShares.userId, name: users.name, email: users.email, role: driveShares.role })
+ .from(driveShares)
+ .innerJoin(users, eq(driveShares.userId, users.id))
+ .where(eq(driveShares.itemId, itemId))
+ .orderBy(driveShares.createdAt);
+}
+
+export async function GET(request: Request, { params }: DriveItemParams) {
+ const ctx = await loadOwnedItem(request, params, false);
+ if (ctx.error) return ctx.error;
+ return NextResponse.json({ shares: await listShares(ctx.db, ctx.item.id), linkToken: ctx.item.linkToken });
+}
+
+export async function POST(request: Request, { params }: DriveItemParams) {
+ const ctx = await loadOwnedItem(request, params, true);
+ if (ctx.error) return ctx.error;
+ const { db, user, item } = ctx;
+ const body = await request.json().catch(() => ({})) as { email?: unknown; role?: unknown };
+ const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
+ const role = body.role === "edit" ? "edit" : "view";
+ if (!email) return NextResponse.json({ error: "Enter an email address" }, { status: 400 });
+ const [target] = await db.select({ id: users.id }).from(users).where(eq(users.email, email)).limit(1);
+ if (!target) return NextResponse.json({ error: "No account uses that email address" }, { status: 404 });
+ if (target.id === user.id) return NextResponse.json({ error: "You already own this item" }, { status: 400 });
+ await db.insert(driveShares).values({ id: newId("dshr"), itemId: item.id, userId: target.id, role }).onConflictDoUpdate({ target: [driveShares.itemId, driveShares.userId], set: { role } });
+ return NextResponse.json({ shares: await listShares(db, item.id) });
+}
+
+export async function DELETE(request: Request, { params }: DriveItemParams) {
+ const ctx = await loadOwnedItem(request, params, true);
+ if (ctx.error) return ctx.error;
+ const shareId = new URL(request.url).searchParams.get("shareId");
+ if (!shareId) return NextResponse.json({ error: "Missing share" }, { status: 400 });
+ await ctx.db.delete(driveShares).where(and(eq(driveShares.id, shareId), eq(driveShares.itemId, ctx.item.id)));
+ return NextResponse.json({ shares: await listShares(ctx.db, ctx.item.id) });
+}
diff --git a/src/app/api/drive/items/[id]/types.d.ts b/src/app/api/drive/items/[id]/types.d.ts
new file mode 100644
index 0000000..4c304cb
--- /dev/null
+++ b/src/app/api/drive/items/[id]/types.d.ts
@@ -0,0 +1 @@
+export type DriveItemParams = { params: Promise<{ id: string }> };
diff --git a/src/app/api/drive/items/bulk/route.ts b/src/app/api/drive/items/bulk/route.ts
new file mode 100644
index 0000000..c89036d
--- /dev/null
+++ b/src/app/api/drive/items/bulk/route.ts
@@ -0,0 +1,59 @@
+import { inArray } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { driveItems } from "@/db/schema";
+import { authorizeDrive } from "@/lib/drive/auth";
+import { deleteDriveItems, getDriveChain, getDriveItem, getDriveRole } from "@/lib/drive/access";
+import { canEditDrive } from "@/lib/drive/utils";
+import type { DriveRow } from "@/lib/drive/types";
+
+const MAX_BULK_ITEMS = 200;
+
+/**
+ * Applies one action to several items: trash, restore, move or delete (forever, trashed items only). Anyone who can edit
+ * an item may move it to the trash; restoring, moving and deleting forever are for the owner. Moving a trashed item
+ * also takes it out of the trash, so it can be dragged from Trash straight into a folder.
+ */
+export async function POST(request: Request) {
+ const auth = await authorizeDrive(request, true);
+ if (auth.error) return auth.error;
+ const { env, db, user } = auth;
+ const body = await request.json().catch(() => ({})) as { action?: unknown; ids?: unknown; parentId?: unknown };
+ const ids = Array.isArray(body.ids) ? [...new Set(body.ids.filter((id): id is string => typeof id === "string"))] : [];
+ if (!ids.length || ids.length > MAX_BULK_ITEMS) return NextResponse.json({ error: "Select between 1 and 200 items" }, { status: 400 });
+
+ const owned: DriveRow[] = [];
+ for (let index = 0; index < ids.length; index += 50) {
+ owned.push(...await db.select().from(driveItems).where(inArray(driveItems.id, ids.slice(index, index + 50))));
+ }
+ if (owned.length !== ids.length) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ for (const row of owned) {
+ const allowed = row.ownerId === user.id || (body.action === "trash" && canEditDrive(await getDriveRole(db, user.id, row)));
+ if (!allowed) return NextResponse.json({ error: "Only the owner can change these items" }, { status: 403 });
+ }
+ const update = async (rows: DriveRow[], set: Partial<typeof driveItems.$inferInsert>) => {
+ const targets = rows.map((row) => row.id);
+ for (let index = 0; index < targets.length; index += 50) await db.update(driveItems).set({ ...set, updatedAt: new Date() }).where(inArray(driveItems.id, targets.slice(index, index + 50)));
+ return targets.length;
+ };
+
+ if (body.action === "trash") return NextResponse.json({ count: await update(owned.filter((row) => !row.trashedAt), { trashedAt: new Date() }) });
+ if (body.action === "restore") return NextResponse.json({ count: await update(owned.filter((row) => row.trashedAt), { trashedAt: null }) });
+ if (body.action === "delete") {
+ const trashed = owned.filter((row) => row.trashedAt);
+ if (trashed.length) await deleteDriveItems(env, trashed);
+ return NextResponse.json({ count: trashed.length });
+ }
+ if (body.action === "move") {
+ let parentId: string | null = null;
+ if (typeof body.parentId === "string" && body.parentId) {
+ const destination = await getDriveItem(db, body.parentId);
+ if (!destination || destination.ownerId !== user.id || destination.kind !== "folder" || destination.trashedAt || destination.uploadId) return NextResponse.json({ error: "Folder not found" }, { status: 404 });
+ // A folder cannot move into itself or anything beneath it.
+ const chain = new Set((await getDriveChain(db, destination)).map((row) => row.id));
+ if (owned.some((row) => chain.has(row.id))) return NextResponse.json({ error: "Cannot move a folder into itself" }, { status: 400 });
+ parentId = destination.id;
+ }
+ return NextResponse.json({ count: await update(owned.filter((row) => row.parentId !== parentId || row.trashedAt), { parentId, trashedAt: null }) });
+ }
+ return NextResponse.json({ error: "Unknown action" }, { status: 400 });
+}
diff --git a/src/app/api/drive/items/route.ts b/src/app/api/drive/items/route.ts
new file mode 100644
index 0000000..9ce4a73
--- /dev/null
+++ b/src/app/api/drive/items/route.ts
@@ -0,0 +1,102 @@
+import { and, desc, eq, isNotNull, isNull, or, sql } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { driveItems, driveShares } from "@/db/schema";
+import { newId } from "@/lib/ids";
+import { authorizeDrive } from "@/lib/drive/auth";
+import { getDriveChain, getDriveItem, getDriveRole, toDriveItemDtos, withoutTrashedAncestors } from "@/lib/drive/access";
+import { canEditDrive, normalizeDriveName, toDriveCrumbs } from "@/lib/drive/utils";
+import { driveTypesCondition, parseDriveCategories } from "@/lib/drive/categories";
+import { listDriveAttachments } from "@/lib/drive/attachments";
+import { getDriveStorageLimit, getDriveStorageUsed } from "@/lib/drive/storage";
+import type { DriveRole } from "@/lib/drive/types";
+
+export async function GET(request: Request) {
+ const auth = await authorizeDrive(request);
+ if (auth.error) return auth.error;
+ const { env, db, user } = auth;
+ const url = new URL(request.url);
+ const view = url.searchParams.get("view") ?? "my";
+ const parentId = url.searchParams.get("parent");
+ const query = url.searchParams.get("q")?.trim();
+ const types = parseDriveCategories(url.searchParams.get("types"));
+ // With a type filter, files must match but folders stay listed so you can still browse into them.
+ const typeFilter = types.length ? or(eq(driveItems.kind, "folder"), driveTypesCondition(types))! : undefined;
+
+ const meta = { storageUsed: await getDriveStorageUsed(db, user.id), storageLimit: await getDriveStorageLimit(env) };
+ const respond = (items: Awaited<ReturnType<typeof toDriveItemDtos>>, extra: { path?: ReturnType<typeof toDriveCrumbs>; role: DriveRole }) => NextResponse.json({ items, path: extra.path ?? [], role: extra.role, ...meta });
+
+ if (parentId) {
+ const folder = await getDriveItem(db, parentId);
+ const role = folder?.kind === "folder" ? await getDriveRole(db, user.id, folder) : null;
+ if (!folder || !role) return NextResponse.json({ error: "Folder not found" }, { status: 404 });
+ const rows = await db.select().from(driveItems).where(and(eq(driveItems.parentId, folder.id), isNull(driveItems.trashedAt), isNull(driveItems.uploadId), typeFilter));
+ const chain = await getDriveChain(db, folder);
+ // For shared folders the breadcrumb starts at the folder the user was given access to.
+ const visibleChain = role === "owner" ? chain : await trimToSharedRoot(db, user.id, chain);
+ return respond(await toDriveItemDtos(db, rows, user.id, () => role), { path: toDriveCrumbs(visibleChain), role });
+ }
+
+ if (view === "attachments") return respond(await listDriveAttachments(db, user, types), { role: "view" });
+
+ if (view === "shared") {
+ const rows = await db
+ .select({ item: driveItems, role: driveShares.role })
+ .from(driveShares)
+ .innerJoin(driveItems, eq(driveShares.itemId, driveItems.id))
+ .where(and(eq(driveShares.userId, user.id), isNull(driveItems.trashedAt), isNull(driveItems.uploadId), typeFilter))
+ .orderBy(desc(driveShares.createdAt));
+ const roles = new Map(rows.map((row) => [row.item.id, row.role as DriveRole]));
+ return respond(await toDriveItemDtos(db, rows.map((row) => row.item), user.id, (row) => roles.get(row.id) ?? "view"), { role: "view" });
+ }
+
+ if (view === "trash") {
+ const rows = await db.select().from(driveItems).where(and(eq(driveItems.ownerId, user.id), isNotNull(driveItems.trashedAt), typeFilter)).orderBy(desc(driveItems.trashedAt));
+ const trashedAttachments = await listDriveAttachments(db, user, types, true);
+ const merged = [...await toDriveItemDtos(db, rows, user.id), ...trashedAttachments].sort((a, b) => (b.trashedAt ?? "").localeCompare(a.trashedAt ?? ""));
+ return respond(merged, { role: "owner" });
+ }
+
+ // My Drive. A type filter, like a search, looks through every folder instead of only the top level.
+ if (types.length && !query) {
+ const rows = await db.select().from(driveItems).where(and(eq(driveItems.ownerId, user.id), eq(driveItems.kind, "file"), isNull(driveItems.trashedAt), isNull(driveItems.uploadId), driveTypesCondition(types))).orderBy(desc(driveItems.updatedAt)).limit(1000);
+ return respond(await toDriveItemDtos(db, await withoutTrashedAncestors(db, rows), user.id), { role: "owner" });
+ }
+ const conditions = [eq(driveItems.ownerId, user.id), isNull(driveItems.trashedAt), isNull(driveItems.uploadId)];
+ if (query) conditions.push(sql`${driveItems.name} like ${`%${query.replace(/[\\%_]/g, "\\$&")}%`} escape '\\'`);
+ else conditions.push(isNull(driveItems.parentId));
+ if (typeFilter) conditions.push(typeFilter);
+ const rows = await db.select().from(driveItems).where(and(...conditions)).orderBy(desc(driveItems.updatedAt)).limit(query ? 200 : 1000);
+ return respond(await toDriveItemDtos(db, rows, user.id), { role: "owner" });
+}
+
+async function trimToSharedRoot(db: Parameters<typeof getDriveRole>[0], userId: string, chain: Awaited<ReturnType<typeof getDriveChain>>) {
+ for (let index = 0; index < chain.length; index += 1) {
+ const [share] = await db.select({ id: driveShares.id }).from(driveShares).where(and(eq(driveShares.itemId, chain[index].id), eq(driveShares.userId, userId))).limit(1);
+ if (share) return chain.slice(index);
+ }
+ return chain;
+}
+
+/** Creates a folder. */
+export async function POST(request: Request) {
+ const auth = await authorizeDrive(request, true);
+ if (auth.error) return auth.error;
+ const { db, user } = auth;
+ const body = await request.json().catch(() => ({})) as { name?: unknown; parentId?: unknown };
+ const name = normalizeDriveName(body.name);
+ if (!name) return NextResponse.json({ error: "Enter a folder name" }, { status: 400 });
+ let ownerId = user.id;
+ let parentId: string | null = null;
+ if (typeof body.parentId === "string" && body.parentId) {
+ const parent = await getDriveItem(db, body.parentId);
+ const role = parent?.kind === "folder" ? await getDriveRole(db, user.id, parent) : null;
+ if (!parent || !canEditDrive(role)) return NextResponse.json({ error: "Folder not found" }, { status: 404 });
+ parentId = parent.id;
+ ownerId = parent.ownerId;
+ }
+ const now = new Date();
+ const row = { id: newId("drv"), ownerId, parentId, kind: "folder" as const, name, r2Key: null, size: 0, contentType: "application/x-directory", uploadId: null, uploadPartSize: null, uploadFingerprint: null, linkToken: null, trashedAt: null, createdAt: now, updatedAt: now };
+ await db.insert(driveItems).values(row);
+ const [item] = await toDriveItemDtos(db, [row], user.id, () => (ownerId === user.id ? "owner" : "edit"));
+ return NextResponse.json({ item });
+}
diff --git a/src/app/api/drive/owners/[id]/avatar/route.ts b/src/app/api/drive/owners/[id]/avatar/route.ts
new file mode 100644
index 0000000..929f253
--- /dev/null
+++ b/src/app/api/drive/owners/[id]/avatar/route.ts
@@ -0,0 +1,23 @@
+import { and, eq } from "drizzle-orm";
+import { getDb } from "@/db";
+import { driveItems, driveShares, users } from "@/db/schema";
+import { getEnv } from "@/lib/cloudflare";
+import { requireSessionUser } from "@/lib/api/auth";
+import { getAvatarImageResponse } from "@/lib/avatar-images";
+import type { DriveItemParams } from "../../../items/[id]/types";
+
+/** Avatar of a Drive owner. Only yourself, or someone who shared something with you, is visible. */
+export async function GET(request: Request, { params }: DriveItemParams) {
+ const { id } = await params;
+ const env = getEnv();
+ const { user, error } = await requireSessionUser(env, request);
+ if (error) return error;
+ const db = getDb(env);
+ if (id !== user.id) {
+ const [shared] = await db.select({ id: driveShares.id }).from(driveShares).innerJoin(driveItems, eq(driveShares.itemId, driveItems.id)).where(and(eq(driveShares.userId, user.id), eq(driveItems.ownerId, id))).limit(1);
+ if (!shared) return new Response("Not found", { status: 404 });
+ }
+ const [owner] = await db.select({ avatarKey: users.avatarKey }).from(users).where(eq(users.id, id)).limit(1);
+ if (!owner?.avatarKey) return new Response("Not found", { status: 404 });
+ return getAvatarImageResponse(request, env.BUCKET, owner.avatarKey);
+}
diff --git a/src/app/api/drive/public/[token]/route.ts b/src/app/api/drive/public/[token]/route.ts
new file mode 100644
index 0000000..0529372
--- /dev/null
+++ b/src/app/api/drive/public/[token]/route.ts
@@ -0,0 +1,29 @@
+import { and, eq, isNull } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { getDb } from "@/db";
+import { driveItems } from "@/db/schema";
+import { getEnv } from "@/lib/cloudflare";
+import { getDriveChain, getPublicDriveItem } from "@/lib/drive/access";
+import { streamDriveFile } from "@/lib/drive/content";
+import type { DriveTokenParams } from "./types";
+
+const publicItem = (row: typeof driveItems.$inferSelect) => ({ id: row.id, kind: row.kind, name: row.name, size: row.size, contentType: row.contentType, updatedAt: row.updatedAt.toISOString() });
+
+/** Public, unauthenticated access to an item (and its subtree) shared by link. */
+export async function GET(request: Request, { params }: DriveTokenParams) {
+ const { token } = await params;
+ const env = getEnv();
+ const db = getDb(env);
+ const url = new URL(request.url);
+ const target = url.searchParams.get("item");
+ const resolved = await getPublicDriveItem(db, token, target);
+ if (!resolved) return NextResponse.json({ error: "Link not found" }, { status: 404 });
+ const { root, item } = resolved;
+ if (url.searchParams.get("content") === "1" || url.searchParams.get("download") === "1") {
+ return streamDriveFile(env, request, item, url.searchParams.get("download") === "1");
+ }
+ const children = item.kind === "folder" ? await db.select().from(driveItems).where(and(eq(driveItems.parentId, item.id), isNull(driveItems.trashedAt), isNull(driveItems.uploadId))) : [];
+ const chain = await getDriveChain(db, item);
+ const path = chain.slice(chain.findIndex((entry) => entry.id === root.id)).map((entry) => ({ id: entry.id, name: entry.name }));
+ return NextResponse.json({ item: publicItem(item), items: children.map(publicItem), path });
+}
diff --git a/src/app/api/drive/public/[token]/types.d.ts b/src/app/api/drive/public/[token]/types.d.ts
new file mode 100644
index 0000000..8b9428e
--- /dev/null
+++ b/src/app/api/drive/public/[token]/types.d.ts
@@ -0,0 +1 @@
+export type DriveTokenParams = { params: Promise<{ token: string }> };
diff --git a/src/app/api/drive/upload/[id]/route.ts b/src/app/api/drive/upload/[id]/route.ts
new file mode 100644
index 0000000..9a2a12a
--- /dev/null
+++ b/src/app/api/drive/upload/[id]/route.ts
@@ -0,0 +1,63 @@
+import { eq } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { driveItems, driveUploadParts } from "@/db/schema";
+import { authorizeDrive } from "@/lib/drive/auth";
+import { getDriveItem, getDriveRole, toDriveItemDtos } from "@/lib/drive/access";
+import { canEditDrive, DRIVE_MAX_PARTS, driveObjectKey } from "@/lib/drive/utils";
+import type { DriveItemParams } from "../../items/[id]/types";
+
+async function loadPending(request: Request, params: DriveItemParams["params"]) {
+ const { id } = await params;
+ const auth = await authorizeDrive(request, true);
+ if (auth.error) return { error: auth.error } as const;
+ const item = await getDriveItem(auth.db, id);
+ const role = item ? await getDriveRole(auth.db, auth.user.id, item) : null;
+ if (!item || !item.uploadId || !canEditDrive(role)) return { error: NextResponse.json({ error: "Upload not found" }, { status: 404 }) } as const;
+ const upload = auth.env.BUCKET.resumeMultipartUpload(item.r2Key ?? driveObjectKey(item.ownerId, item.id), item.uploadId);
+ return { ...auth, item, upload, role: role! } as const;
+}
+
+/** Uploads one part. The body is the raw bytes of the part. */
+export async function PUT(request: Request, { params }: DriveItemParams) {
+ const ctx = await loadPending(request, params);
+ if (ctx.error) return ctx.error;
+ const partNumber = Number(new URL(request.url).searchParams.get("part"));
+ const length = Number(request.headers.get("content-length"));
+ const partSize = ctx.item.uploadPartSize ?? 0;
+ const total = partSize ? Math.ceil(ctx.item.size / partSize) : 0;
+ if (!Number.isInteger(partNumber) || partNumber < 1 || partNumber > Math.min(total, DRIVE_MAX_PARTS)) return NextResponse.json({ error: "Invalid part number" }, { status: 400 });
+ // R2 needs every part but the last to be the same size, and the size the client declared must add up.
+ const expected = partNumber < total ? partSize : ctx.item.size - (total - 1) * partSize;
+ if (!request.body || length !== expected) return NextResponse.json({ error: "Invalid part size" }, { status: 400 });
+ const part = await ctx.upload.uploadPart(partNumber, request.body);
+ await ctx.db.insert(driveUploadParts).values({ itemId: ctx.item.id, partNumber, etag: part.etag }).onConflictDoUpdate({ target: [driveUploadParts.itemId, driveUploadParts.partNumber], set: { etag: part.etag } });
+ await ctx.db.update(driveItems).set({ updatedAt: new Date() }).where(eq(driveItems.id, ctx.item.id));
+ return NextResponse.json({ partNumber, etag: part.etag });
+}
+
+/** Finishes the upload from the recorded parts and makes the file visible. */
+export async function POST(request: Request, { params }: DriveItemParams) {
+ const ctx = await loadPending(request, params);
+ if (ctx.error) return ctx.error;
+ const parts = await ctx.db.select({ partNumber: driveUploadParts.partNumber, etag: driveUploadParts.etag }).from(driveUploadParts).where(eq(driveUploadParts.itemId, ctx.item.id));
+ const total = ctx.item.uploadPartSize ? Math.ceil(ctx.item.size / ctx.item.uploadPartSize) : 0;
+ if (!total || parts.length !== total) return NextResponse.json({ error: "Some parts are missing" }, { status: 409 });
+ let object;
+ try { object = await ctx.upload.complete(parts); }
+ catch { return NextResponse.json({ error: "Could not complete the upload" }, { status: 400 }); }
+ const row = { ...ctx.item, size: object.size, uploadId: null, uploadPartSize: null, uploadFingerprint: null, updatedAt: new Date() };
+ await ctx.db.update(driveItems).set({ size: row.size, uploadId: null, uploadPartSize: null, uploadFingerprint: null, updatedAt: row.updatedAt }).where(eq(driveItems.id, ctx.item.id));
+ await ctx.db.delete(driveUploadParts).where(eq(driveUploadParts.itemId, ctx.item.id));
+ const [item] = await toDriveItemDtos(ctx.db, [row], ctx.user.id, () => ctx.role);
+ return NextResponse.json({ item });
+}
+
+/** Abandons an upload and discards what was sent. */
+export async function DELETE(request: Request, { params }: DriveItemParams) {
+ const ctx = await loadPending(request, params);
+ if (ctx.error) return ctx.error;
+ await ctx.upload.abort().catch(() => undefined);
+ await ctx.db.delete(driveUploadParts).where(eq(driveUploadParts.itemId, ctx.item.id));
+ await ctx.db.delete(driveItems).where(eq(driveItems.id, ctx.item.id));
+ return NextResponse.json({ ok: true });
+}
diff --git a/src/app/api/drive/upload/route.ts b/src/app/api/drive/upload/route.ts
new file mode 100644
index 0000000..ee46676
--- /dev/null
+++ b/src/app/api/drive/upload/route.ts
@@ -0,0 +1,80 @@
+import { NextResponse } from "next/server";
+import { and, eq, isNotNull, isNull, lt } from "drizzle-orm";
+import { driveItems, driveUploadParts } from "@/db/schema";
+import { newId } from "@/lib/ids";
+import { authorizeDrive } from "@/lib/drive/auth";
+import { getDriveItem, getDriveRole, toDriveItemDtos } from "@/lib/drive/access";
+import { getDriveStorageLimit, getDriveStorageUsed } from "@/lib/drive/storage";
+import { canEditDrive, DRIVE_MAX_FILE_BYTES, DRIVE_PART_BYTES, DRIVE_UPLOAD_RESUME_MS, driveObjectKey, normalizeDriveName } from "@/lib/drive/utils";
+
+/**
+ * Starts an upload. The file itself is then sent as raw (non multipart/form-data) PUT requests, because the runtime
+ * treats every multipart POST as a server action and rejects bodies over 1 MB.
+ */
+export async function POST(request: Request) {
+ const auth = await authorizeDrive(request, true);
+ if (auth.error) return auth.error;
+ const { env, db, user } = auth;
+ const body = await request.json().catch(() => ({})) as { name?: unknown; size?: unknown; contentType?: unknown; parentId?: unknown; fingerprint?: unknown };
+ const size = typeof body.size === "number" && Number.isInteger(body.size) && body.size >= 0 ? body.size : null;
+ const name = normalizeDriveName(body.name) ?? "Untitled";
+ if (size === null) return NextResponse.json({ error: "Invalid file size" }, { status: 400 });
+ if (size > DRIVE_MAX_FILE_BYTES) return NextResponse.json({ error: "File is too large" }, { status: 413 });
+
+ let ownerId = user.id;
+ let parentId: string | null = null;
+ if (typeof body.parentId === "string" && body.parentId) {
+ const parent = await getDriveItem(db, body.parentId);
+ const role = parent?.kind === "folder" ? await getDriveRole(db, user.id, parent) : null;
+ if (!parent || !canEditDrive(role)) return NextResponse.json({ error: "Folder not found" }, { status: 404 });
+ parentId = parent.id;
+ ownerId = parent.ownerId;
+ }
+
+ const fingerprint = typeof body.fingerprint === "string" ? body.fingerprint.slice(0, 100) : "";
+
+ // Uploads nobody came back to are discarded so they do not pile up.
+ const stale = await db.select().from(driveItems).where(and(eq(driveItems.ownerId, ownerId), isNotNull(driveItems.uploadId), lt(driveItems.updatedAt, new Date(Date.now() - DRIVE_UPLOAD_RESUME_MS)))).limit(20);
+ for (const old of stale) {
+ await env.BUCKET.resumeMultipartUpload(old.r2Key ?? driveObjectKey(old.ownerId, old.id), old.uploadId!).abort().catch(() => undefined);
+ await db.delete(driveUploadParts).where(eq(driveUploadParts.itemId, old.id));
+ await db.delete(driveItems).where(eq(driveItems.id, old.id));
+ }
+
+ // The same file picked again continues the upload that was interrupted.
+ if (fingerprint && size > 0) {
+ const [pending] = await db.select().from(driveItems).where(and(eq(driveItems.ownerId, ownerId), parentId ? eq(driveItems.parentId, parentId) : isNull(driveItems.parentId), eq(driveItems.name, name), eq(driveItems.size, size), eq(driveItems.uploadFingerprint, fingerprint), isNotNull(driveItems.uploadId))).limit(1);
+ if (pending?.uploadPartSize) {
+ const done = await db.select({ partNumber: driveUploadParts.partNumber }).from(driveUploadParts).where(eq(driveUploadParts.itemId, pending.id));
+ await db.update(driveItems).set({ updatedAt: new Date() }).where(eq(driveItems.id, pending.id));
+ return NextResponse.json({ id: pending.id, partSize: pending.uploadPartSize, parts: Math.ceil(size / pending.uploadPartSize), uploaded: done.map((part) => part.partNumber), resumed: true });
+ }
+ }
+
+ const limit = await getDriveStorageLimit(env);
+ if (limit !== null && (await getDriveStorageUsed(db, ownerId)) + size > limit) return NextResponse.json({ error: "Not enough Drive storage left for this file" }, { status: 413 });
+
+ const id = newId("drv");
+ const key = driveObjectKey(ownerId, id);
+ const contentType = typeof body.contentType === "string" && body.contentType ? body.contentType.slice(0, 255) : "application/octet-stream";
+ const now = new Date();
+ const row: typeof driveItems.$inferSelect = { id, ownerId, parentId, kind: "file", name, r2Key: key, size, contentType, uploadId: null, uploadPartSize: null, uploadFingerprint: null, linkToken: null, trashedAt: null, createdAt: now, updatedAt: now };
+ const role = ownerId === user.id ? "owner" : "edit";
+
+ // Multipart uploads need at least one part, so an empty file is simply stored.
+ if (size === 0) {
+ await env.BUCKET.put(key, new Uint8Array(0), { httpMetadata: { contentType } });
+ try { await db.insert(driveItems).values(row); }
+ catch (error) { await env.BUCKET.delete(key); throw error; }
+ const [item] = await toDriveItemDtos(db, [row], user.id, () => role);
+ return NextResponse.json({ item, complete: true });
+ }
+
+ const upload = await env.BUCKET.createMultipartUpload(key, { httpMetadata: { contentType } });
+ row.uploadId = upload.uploadId;
+ row.uploadPartSize = DRIVE_PART_BYTES;
+ row.uploadFingerprint = fingerprint || null;
+ try { await db.insert(driveItems).values(row); }
+ catch (error) { await upload.abort(); throw error; }
+ return NextResponse.json({ id, partSize: DRIVE_PART_BYTES, parts: Math.ceil(size / DRIVE_PART_BYTES), uploaded: [] });
+}
diff --git a/src/app/api/mailboxes/[id]/access/route.ts b/src/app/api/mailboxes/[id]/access/route.ts
index e6e5669..2cf1074 100644
--- a/src/app/api/mailboxes/[id]/access/route.ts
+++ b/src/app/api/mailboxes/[id]/access/route.ts
@@ -2,14 +2,14 @@ import { and, eq } from "drizzle-orm";
import { NextResponse } from "next/server";
import { getDb } from "@/db";
import { mailboxAccess, users } from "@/db/schema";
-import { requireTeamAdmin } from "@/app/api/accounts/utils";
+import { requireTeamSharingAdmin } from "@/app/api/accounts/utils";
import { newId } from "@/lib/ids";
import { mailboxAccessSchema } from "@/lib/validators";
import type { MailboxAccessRouteParams } from "./types";
import { getSharedMailboxForAdmin } from "./utils";
export async function GET(request: Request, { params }: MailboxAccessRouteParams) {
- const access = await requireTeamAdmin(request);
+ const access = await requireTeamSharingAdmin(request);
if (access.error) return access.error;
const { id } = await params;
const db = getDb(access.env);
@@ -39,7 +39,7 @@ export async function GET(request: Request, { params }: MailboxAccessRouteParams
}
export async function POST(request: Request, { params }: MailboxAccessRouteParams) {
- const access = await requireTeamAdmin(request);
+ const access = await requireTeamSharingAdmin(request);
if (access.error) return access.error;
const parsed = mailboxAccessSchema.safeParse(await request.json());
if (!parsed.success) return NextResponse.json({ error: "Choose a valid account" }, { status: 400 });
@@ -71,7 +71,7 @@ export async function POST(request: Request, { params }: MailboxAccessRouteParam
}
export async function DELETE(request: Request, { params }: MailboxAccessRouteParams) {
- const access = await requireTeamAdmin(request);
+ const access = await requireTeamSharingAdmin(request);
if (access.error) return access.error;
const { id } = await params;
const userId = new URL(request.url).searchParams.get("userId");
diff --git a/src/app/api/mailboxes/route.ts b/src/app/api/mailboxes/route.ts
index 10fcbaf..47ac011 100644
--- a/src/app/api/mailboxes/route.ts
+++ b/src/app/api/mailboxes/route.ts
@@ -25,7 +25,7 @@ export async function GET(request: Request) {
: {}),
senderAddresses: await getMailboxDomainAddresses(db, mailbox),
}))),
- canCreateShared: user.role === "admin" && entitlements.canManageAccounts,
+ canCreateShared: user.role === "admin" && entitlements.canShareMailboxes,
});
}
@@ -41,7 +41,7 @@ export async function POST(request: Request) {
const mailboxType = parsed.data.type ?? "personal";
if (mailboxType === "shared") {
const entitlements = await getLicenseEntitlements(env);
- if (user.role !== "admin" || !entitlements.canManageAccounts) {
+ if (user.role !== "admin" || !entitlements.canShareMailboxes) {
return NextResponse.json({ error: "A Team license is required to create shared inboxes" }, { status: 403 });
}
}
diff --git a/src/app/api/v1/accounts/[id]/utils.ts b/src/app/api/v1/accounts/[id]/utils.ts
index a3e8119..4675825 100644
--- a/src/app/api/v1/accounts/[id]/utils.ts
+++ b/src/app/api/v1/accounts/[id]/utils.ts
@@ -15,7 +15,7 @@ export async function GET(request: Request, { params }: AdminAccountRouteParams)
const env = getEnv();
const auth = await authenticateAdminApiKey(env, request, "accounts");
if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
- if (!(await canManageAdminAccounts(env))) return NextResponse.json({ error: "A Team license is required to manage accounts" }, { status: 403 });
+ if (!(await canManageAdminAccounts(env))) return NextResponse.json({ error: "A Pro or Team license is required to manage accounts" }, { status: 403 });
const { id } = await params;
const account = await selectAccountById(getDb(env), id);
if (!account || (account.id !== auth.userId && account.createdByUserId !== auth.userId)) return NextResponse.json({ error: "Account not found" }, { status: 404 });
@@ -30,7 +30,7 @@ export async function PATCH(request: Request, { params }: AdminAccountRouteParam
const env = getEnv();
const auth = await authenticateAdminApiKey(env, request, "accounts");
if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
- if (!(await canManageAdminAccounts(env))) return NextResponse.json({ error: "A Team license is required to manage accounts" }, { status: 403 });
+ if (!(await canManageAdminAccounts(env))) return NextResponse.json({ error: "A Pro or Team license is required to manage accounts" }, { status: 403 });
const { id } = await params;
const db = getDb(env);
const account = await selectAccountById(db, id);
diff --git a/src/app/api/v1/accounts/utils.ts b/src/app/api/v1/accounts/utils.ts
index bd05b07..87b608c 100644
--- a/src/app/api/v1/accounts/utils.ts
+++ b/src/app/api/v1/accounts/utils.ts
@@ -13,7 +13,7 @@ export async function GET(request: Request) {
const env = getEnv();
const auth = await authenticateAdminApiKey(env, request, "accounts");
if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
- if (!(await canManageAdminAccounts(env))) return NextResponse.json({ error: "A Team license is required to manage accounts" }, { status: 403 });
+ if (!(await canManageAdminAccounts(env))) return NextResponse.json({ error: "A Pro or Team license is required to manage accounts" }, { status: 403 });
const rows = await getDb(env).select().from(users).where(or(eq(users.id, auth.userId), eq(users.createdByUserId, auth.userId)));
return NextResponse.json({ accounts: rows.map(accountListItemFromUser) });
}
@@ -22,7 +22,7 @@ export async function POST(request: Request) {
const env = getEnv();
const auth = await authenticateAdminApiKey(env, request, "accounts");
if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
- if (!(await canManageAdminAccounts(env))) return NextResponse.json({ error: "A Team license is required to manage accounts" }, { status: 403 });
+ if (!(await canManageAdminAccounts(env))) return NextResponse.json({ error: "A Pro or Team license is required to manage accounts" }, { status: 403 });
const parsed = createUserAccountSchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
if (parsed.data.role === "admin" && !isPrimaryAdmin(auth.user)) {
diff --git a/src/app/api/v1/mailboxes/utils.ts b/src/app/api/v1/mailboxes/utils.ts
index 25f8642..a1120d0 100644
--- a/src/app/api/v1/mailboxes/utils.ts
+++ b/src/app/api/v1/mailboxes/utils.ts
@@ -3,7 +3,7 @@ import { and, eq, or } from "drizzle-orm";
import { getEnv } from "@/lib/cloudflare";
import { getDb } from "@/db";
import { domains, mailboxAliases, mailboxes, users } from "@/db/schema";
-import { authenticateAdminApiKey, canManageAdminAccounts } from "@/lib/api/admin-auth";
+import { authenticateAdminApiKey, canShareAdminMailboxes } from "@/lib/api/admin-auth";
import { newId } from "@/lib/ids";
import { mailboxSchema } from "@/lib/validators";
import { ensureMailboxDomainRouting } from "@/lib/mailboxes/domain-addresses";
@@ -30,7 +30,7 @@ export async function POST(request: Request) {
if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
const db = getDb(env);
const mailboxType = parsed.data.type ?? "personal";
- if (mailboxType === "shared" && !(await canManageAdminAccounts(env))) return NextResponse.json({ error: "A Team license is required to create shared inboxes" }, { status: 403 });
+ if (mailboxType === "shared" && !(await canShareAdminMailboxes(env))) return NextResponse.json({ error: "A Team license is required to create shared inboxes" }, { status: 403 });
const ownerUserId = mailboxType === "shared" ? auth.userId : parsed.data.ownerUserId ?? auth.userId;
if (ownerUserId !== auth.userId) {
const [owner] = await db.select({ id: users.id }).from(users).where(and(eq(users.id, ownerUserId), eq(users.createdByUserId, auth.userId))).limit(1);
diff --git a/src/app/d/[token]/page.tsx b/src/app/d/[token]/page.tsx
new file mode 100644
index 0000000..2054b4f
--- /dev/null
+++ b/src/app/d/[token]/page.tsx
@@ -0,0 +1,70 @@
+"use client";
+
+import { use, useEffect, useState } from "react";
+import { ChevronRight, Download } from "lucide-react";
+import { useLanguage } from "@/components/language-provider";
+import { formatDriveSize } from "@/lib/drive/utils";
+import { DrivePreviewBody } from "@/app/(drive)/drive-preview";
+import { driveIconFor, publicContentUrl, sortDriveItems } from "@/app/(drive)/drive-utils";
+import type { PublicDriveItem, PublicDriveListing } from "./types";
+
+export default function PublicDrivePage({ params }: { params: Promise<{ token: string }> }) {
+ const { token } = use(params);
+ const { t } = useLanguage();
+ const [itemId, setItemId] = useState<string | null>(null);
+ const [data, setData] = useState<PublicDriveListing | null>(null);
+ const [missing, setMissing] = useState(false);
+
+ useEffect(() => {
+ let active = true;
+ const search = itemId ? `?item=${encodeURIComponent(itemId)}` : "";
+ void fetch(`/api/drive/public/${encodeURIComponent(token)}${search}`)
+ .then(async (response) => {
+ if (!response.ok) throw new Error();
+ return response.json() as Promise<PublicDriveListing>;
+ })
+ .then((listing) => { if (active) { setData(listing); setMissing(false); } })
+ .catch(() => { if (active) setMissing(true); });
+ return () => { active = false; };
+ }, [token, itemId]);
+
+ if (missing) return <main className="flex min-h-dvh items-center justify-center bg-[#f6f8fc] p-6 text-center text-neutral-600">{t("drive.publicNotFound")}</main>;
+ if (!data) return <main className="min-h-dvh bg-[#f6f8fc]" aria-busy="true" />;
+ const { item, items, path } = data;
+ const isFile = item.kind === "file";
+
+ return (
+ <main className="mx-auto flex min-h-dvh max-w-5xl flex-col bg-[#f6f8fc] p-4 md:p-8">
+ <nav className="mb-4 flex flex-wrap items-center gap-1 text-lg text-neutral-800">
+ {path.map((crumb, index) => (
+ <span key={crumb.id} className="flex items-center gap-1">
+ {index > 0 && <ChevronRight size={18} className="text-neutral-500" />}
+ {index === path.length - 1 ? <h1 className="px-2 py-1">{crumb.name}</h1> : <button type="button" onClick={() => setItemId(crumb.id)} className="rounded-full px-2 py-1 hover:bg-neutral-200/60">{crumb.name}</button>}
+ </span>
+ ))}
+ {isFile && <a href={publicContentUrl(token, item.id, true)} className="ml-auto inline-flex items-center gap-2 rounded-full bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"><Download size={16} />{t("drive.download")}</a>}
+ </nav>
+ {isFile ? (
+ <div className="min-h-[70vh] flex-1 rounded-2xl bg-[#202124] p-3"><DrivePreviewBody src={publicContentUrl(token, item.id)} downloadHref={publicContentUrl(token, item.id, true)} contentType={item.contentType} name={item.name} /></div>
+ ) : (
+ <div className="rounded-2xl bg-white p-2">
+ {items.length === 0 ? <p className="p-10 text-center text-sm text-neutral-500">{t("drive.empty")}</p> : sortDriveItems(items, "name", true).map((entry) => <PublicRow key={entry.id} entry={entry} token={token} onOpen={setItemId} />)}
+ </div>
+ )}
+ </main>
+ );
+}
+
+function PublicRow({ entry, token, onOpen }: { entry: PublicDriveItem; token: string; onOpen: (id: string) => void }) {
+ const { Icon, className } = driveIconFor(entry);
+ return (
+ <div className="flex items-center gap-4 rounded-lg px-3 text-sm hover:bg-neutral-50">
+ <button type="button" onClick={() => onOpen(entry.id)} className="flex min-w-0 flex-1 items-center gap-4 py-3 text-left">
+ <Icon size={16} className={className} fill={entry.kind === "folder" ? "currentColor" : "none"} />
+ <span className="truncate text-neutral-900">{entry.name}</span>
+ </button>
+ {entry.kind === "file" && <span className="hidden shrink-0 text-neutral-500 sm:block">{formatDriveSize(entry.size)}</span>}
+ {entry.kind === "file" && <a href={publicContentUrl(token, entry.id, true)} aria-label={entry.name} className="shrink-0 rounded-full p-2 text-neutral-600 hover:bg-neutral-200"><Download size={16} /></a>}
+ </div>
+ );
+}
diff --git a/src/app/d/[token]/types.d.ts b/src/app/d/[token]/types.d.ts
new file mode 100644
index 0000000..b3ede7f
--- /dev/null
+++ b/src/app/d/[token]/types.d.ts
@@ -0,0 +1,2 @@
+export type PublicDriveItem = { id: string; kind: "file" | "folder"; name: string; size: number; contentType: string; updatedAt: string };
+export type PublicDriveListing = { item: PublicDriveItem; items: PublicDriveItem[]; path: { id: string; name: string }[] };
diff --git a/src/app/layout.tsx b/src/app/layout.tsx
index da3ac6a..adbb7cc 100644
--- a/src/app/layout.tsx
+++ b/src/app/layout.tsx
@@ -1,9 +1,9 @@
import type { Metadata } from "next";
-import { cookies } from "next/headers";
import { Geist, Geist_Mono } from "next/font/google";
import { Providers } from "@/components/providers";
import { LanguageProvider } from "@/components/language-provider";
-import { DEFAULT_LOCALE, LOCALE_COOKIE, getDirection, loadMessages, resolveLocale } from "@/lib/i18n/utils";
+import { DEFAULT_LOCALE, getDirection } from "@/lib/i18n/utils";
+import { getRequestLocale, loadServerMessages } from "@/lib/i18n/server";
import { sidebarBootstrapScript } from "@/components/sidebar-state-utils";
import { themeBootstrapScript } from "@/components/theme-utils";
import "./globals.css";
@@ -44,8 +44,8 @@ export const metadata: Metadata = {
};
export default async function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
- const locale = resolveLocale((await cookies()).get(LOCALE_COOKIE)?.value);
- const messages = locale === DEFAULT_LOCALE ? undefined : await loadMessages(locale);
+ const locale = await getRequestLocale();
+ const messages = locale === DEFAULT_LOCALE ? undefined : await loadServerMessages(locale);
return (
<html lang={locale} dir={getDirection(locale)} suppressHydrationWarning>
<head>
diff --git a/src/components/dashboard-nav.tsx b/src/components/dashboard-nav.tsx
index eb41cd1..4c0434a 100644
--- a/src/components/dashboard-nav.tsx
+++ b/src/components/dashboard-nav.tsx
@@ -314,8 +314,9 @@ export function DashboardNav({ className }: { className?: string }) {
)}
</NavSectionHeader>
)}
+
{!minimal && foldersSectionOpen && folders.length === 0 && (
- <div className="mx-6 rounded-lg border border-dashed border-neutral-200 px-3 py-3 text-xs text-neutral-400">
+ <div className="px-4 py-1.5 text-xs text-neutral-500">
{t("navigation.noFolders")}
</div>
)}
diff --git a/src/components/header-search-types.d.ts b/src/components/header-search-types.d.ts
new file mode 100644
index 0000000..15fc138
--- /dev/null
+++ b/src/components/header-search-types.d.ts
@@ -0,0 +1,11 @@
+import type { ReactNode } from "react";
+
+export type HeaderSearchProps = {
+ value: string;
+ onChange: (value: string) => void;
+ label: string;
+ placeholder?: string;
+ onSubmit?: () => void;
+ trailing?: ReactNode;
+ inputProps?: Record<string, string>;
+};
diff --git a/src/components/header-search.tsx b/src/components/header-search.tsx
new file mode 100644
index 0000000..ff45c44
--- /dev/null
+++ b/src/components/header-search.tsx
@@ -0,0 +1,50 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import clsx from "clsx";
+import { Search } from "lucide-react";
+import { Input } from "@/components/ui/input";
+import type { HeaderSearchProps } from "./header-search-types";
+
+// The header search shared by every layout. On phones it is an icon beside the menu button
+// until tapped, then covers the header at full width; the wrapper still fills the row so
+// whatever follows it stays pushed to the right.
+export function HeaderSearch({ value, onChange, label, placeholder, onSubmit, trailing, inputProps }: HeaderSearchProps) {
+ const [expanded, setExpanded] = useState(false);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ if (expanded) inputRef.current?.focus();
+ }, [expanded]);
+
+ return (
+ <div className="flex min-w-0 flex-1 items-center">
+ <button
+ type="button"
+ onClick={() => setExpanded(true)}
+ aria-label={label}
+ className={clsx("flex h-10 w-10 shrink-0 items-center justify-center rounded-full hover:bg-neutral-200 md:hidden", value ? "bg-blue-100 text-blue-700" : "text-neutral-600", expanded && "hidden")}
+ >
+ <Search className="h-5 w-5" />
+ </button>
+ <form
+ role="search"
+ onSubmit={(event) => { event.preventDefault(); onSubmit?.(); }}
+ className={clsx("h-12 min-w-0 flex-1 items-center gap-2.5 rounded-full bg-[#eaf1fb] px-4 text-neutral-600 focus-within:ring-2 focus-within:ring-blue-500/30 transition-all md:flex", expanded ? "flex max-md:fixed max-md:inset-x-2 max-md:top-2 max-md:z-[60] max-md:shadow-md" : "max-md:hidden")}
+ >
+ <Search className="h-5 w-5 shrink-0" />
+ <Input
+ ref={inputRef}
+ {...inputProps}
+ onBlur={() => setExpanded(false)}
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ aria-label={label}
+ placeholder={placeholder ?? label}
+ className="h-full min-w-0 flex-1 bg-transparent text-[15px] text-neutral-800 outline-none! shadow-none! border-none! placeholder:text-neutral-500"
+ />
+ {trailing}
+ </form>
+ </div>
+ );
+}
diff --git a/src/components/license-required-overlay-types.d.ts b/src/components/license-required-overlay-types.d.ts
index 47c7856..94da136 100644
--- a/src/components/license-required-overlay-types.d.ts
+++ b/src/components/license-required-overlay-types.d.ts
@@ -1,6 +1,6 @@
import type { ReactNode } from "react";
export type LicenseRequiredOverlayProps = {
- required: "Pro" | "Team";
+ required: "Pro" | "Team" | "Pro or Team";
children: ReactNode;
};
diff --git a/src/components/mail-search/mail-search-input.tsx b/src/components/mail-search/mail-search-input.tsx
index d50b540..44f9aa7 100644
--- a/src/components/mail-search/mail-search-input.tsx
+++ b/src/components/mail-search/mail-search-input.tsx
@@ -1,10 +1,8 @@
"use client";
-import { useEffect, useRef, useState } from "react";
-import clsx from "clsx";
-import { Search, X } from "lucide-react";
+import { X } from "lucide-react";
import { useLanguage } from "@/components/language-provider";
-import { Input } from "@/components/ui/input";
+import { HeaderSearch } from "@/components/header-search";
import { useMailSearch } from "./mail-search-context";
import { useShortcuts } from "@/components/shortcuts";
@@ -13,36 +11,15 @@ export function MailSearchInput() {
const { input: query, setQuery } = useMailSearch();
const { openCommandPalette, shortcutsEnabled, shortcutsPreferenceLoading } = useShortcuts();
const showShortcutHints = shortcutsEnabled && !shortcutsPreferenceLoading;
- // On phones the field is an icon until tapped, then covers the header at full width.
- const [expanded, setExpanded] = useState(false);
- const inputRef = useRef<HTMLInputElement>(null);
-
- useEffect(() => {
- if (expanded) inputRef.current?.focus();
- }, [expanded]);
return (
- <>
- <button
- type="button"
- onClick={() => setExpanded(true)}
- aria-label={t("search.mail")}
- className={clsx("ml-auto flex h-10 w-10 shrink-0 items-center justify-center rounded-full hover:bg-neutral-200 md:hidden", query ? "bg-blue-100 text-blue-700" : "text-neutral-600", expanded && "hidden")}
- >
- <Search className="h-5 w-5" />
- </button>
- <div className={clsx("h-12 flex-1 items-center gap-2.5 rounded-full bg-[#eaf1fb] px-4 text-neutral-600 focus-within:ring-2 focus-within:ring-blue-500/30 transition-all md:flex", expanded ? "flex max-md:fixed max-md:inset-x-2 max-md:top-2 max-md:z-[60] max-md:shadow-md" : "max-md:hidden")}>
- <Search className="h-5 w-5 shrink-0" />
- <Input
- ref={inputRef}
- data-mail-search-input=""
- onBlur={() => setExpanded(false)}
- value={query}
- onChange={(event) => setQuery(event.target.value)}
- placeholder={showShortcutHints ? t("search.mailHint") : t("search.mail")}
- className="h-full min-w-0 flex-1 bg-transparent text-[15px] text-neutral-800 outline-none! shadow-none! border-none! placeholder:text-neutral-500"
- />
- {query ? (
+ <HeaderSearch
+ value={query}
+ onChange={setQuery}
+ label={t("search.mail")}
+ placeholder={showShortcutHints ? t("search.mailHint") : t("search.mail")}
+ inputProps={{ "data-mail-search-input": "" }}
+ trailing={query ? (
<button
type="button"
onMouseDown={(event) => event.preventDefault()}
@@ -62,7 +39,6 @@ export function MailSearchInput() {
<span className="text-[11px] font-mono">⌘K</span>
</button>
) : null}
- </div>
- </>
+ />
);
}
diff --git a/src/components/mailbox-selector.tsx b/src/components/mailbox-selector.tsx
index 2e894a5..ae1a619 100644
--- a/src/components/mailbox-selector.tsx
+++ b/src/components/mailbox-selector.tsx
@@ -2,7 +2,7 @@
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
-import { CalendarDays, Check, ChevronDown, Inbox, LogOut, Settings, ShieldCheck, UserPlus, UserRound, UsersRound } from "lucide-react";
+import { CalendarDays, Check, HardDrive, ChevronDown, Inbox, LogOut, Settings, ShieldCheck, UserPlus, UserRound, UsersRound } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useLanguage } from "@/components/language-provider";
import { useSelectedMailbox } from "@/components/mailbox-provider";
@@ -310,6 +310,14 @@ export function MailboxSelector({ initialUser }: MailboxSelectorProps = {}) {
<CalendarDays size={18} className="text-neutral-600" />
{t("account.calendar")}
</Link>
+ <Link
+ href="/drive"
+ onClick={() => setOpen(false)}
+ className="mt-1 flex items-center gap-3 rounded-xl px-3 py-2 text-sm font-medium text-neutral-700 hover:bg-[#f2f6fc]"
+ >
+ <HardDrive size={18} className="text-neutral-600" />
+ {t("account.drive")}
+ </Link>
<Link
href="/settings/account"
onClick={() => setOpen(false)}
diff --git a/src/components/nav-section-header.tsx b/src/components/nav-section-header.tsx
index 93f6b24..e932ade 100644
--- a/src/components/nav-section-header.tsx
+++ b/src/components/nav-section-header.tsx
@@ -2,7 +2,7 @@
import { useEffect, useState } from "react";
import type { ReactNode } from "react";
-import { ChevronDown } from "lucide-react";
+import { ChevronRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { readStorage, writeStorage } from "./reorderable-list-utils";
@@ -17,12 +17,13 @@ export function useSectionOpen(storageKey: string): [boolean, () => void] {
return [open, toggle];
}
+/** Collapsible section label: small uppercase text behind a chevron that turns when the section opens. */
export function NavSectionHeader({ label, open, onToggle, children }: { label: string; open: boolean; onToggle: () => void; children?: ReactNode }) {
return (
- <div className="mt-2 flex h-8 shrink-0 items-center justify-between px-6">
- <button type="button" onClick={onToggle} aria-expanded={open} className="flex items-center gap-1 text-sm font-medium tracking-wide text-neutral-900 max-md:text-base">
- {label}
- <ChevronDown className={cn("h-4 w-4 text-neutral-500 transition-transform", !open && "-rotate-90")} />
+ <div className="mt-2 flex h-9 shrink-0 items-center justify-between gap-1 ml-3 mr-2 hover:bg-neutral-200/60 rounded-full pr-2">
+ <button type="button" onClick={onToggle} aria-expanded={open} className="flex h-9 min-w-0 flex-1 items-center gap-2 pl-3 pr-3 text-left text-xs font-semibold uppercase tracking-wide text-neutral-500 max-md:text-sm">
+ <ChevronRight className={cn("h-3.5 w-3.5 shrink-0 transition-transform", open && "rotate-90")} />
+ <span className="truncate">{label}</span>
</button>
{children}
</div>
diff --git a/src/components/sidebar-footer.tsx b/src/components/sidebar-footer.tsx
index d7f0c2b..c5b11f1 100644
--- a/src/components/sidebar-footer.tsx
+++ b/src/components/sidebar-footer.tsx
@@ -29,7 +29,16 @@ export function SidebarFooter() {
</kbd>
</button>
)}
- <p className="px-1 text-[11px] text-neutral-400">
+ <PoweredBy />
+ </div>
+ );
+}
+
+/** The "Powered by Mailflare vX" credit, shared by the mail and Drive sidebars. */
+export function PoweredBy({ className = "px-1" }: { className?: string }) {
+ const { t } = useLanguage();
+ return (
+ <p className={`${className} text-[11px] text-neutral-400`}>
{t("navigation.poweredBy")}{" "}
<a
href={`https://mailflare.co/?ref=${typeof window !== "undefined" ? location.hostname : ""}&v=${packageJson.version}`}
@@ -40,6 +49,5 @@ export function SidebarFooter() {
Mailflare v{packageJson.version}
</a>
</p>
- </div>
- );
+ );
}
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx
index d08c9ac..5cd147c 100644
--- a/src/components/ui/dialog.tsx
+++ b/src/components/ui/dialog.tsx
@@ -14,12 +14,14 @@ export function DialogContent({
className,
children,
closeLabel,
+ overlayClassName,
+ closeClassName,
...props
-}: React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & { closeLabel?: string }) {
+}: React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & { closeLabel?: string; overlayClassName?: string; closeClassName?: string }) {
const { t } = useLanguage();
return (
<DialogPrimitive.Portal>
- <DialogPrimitive.Overlay className="dialog-overlay fixed inset-0 z-50 bg-black/35" />
+ <DialogPrimitive.Overlay className={cn("dialog-overlay fixed inset-0 z-50 bg-black/35", overlayClassName)} />
<DialogPrimitive.Content
className={cn(
"dialog-content fixed left-1/2 top-1/2 z-50 w-[min(520px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 rounded-2xl bg-white p-6 shadow-xl",
@@ -28,7 +30,7 @@ export function DialogContent({
{...props}
>
{children}
- <DialogPrimitive.Close className="absolute right-4 top-4 rounded-full p-1 text-neutral-500 hover:bg-neutral-100 hover:text-neutral-900">
+ <DialogPrimitive.Close className={cn("absolute right-4 top-4 rounded-full p-1 text-neutral-500 hover:bg-neutral-100 hover:text-neutral-900", closeClassName)}>
<X className="h-4 w-4" />
<span className="sr-only">{closeLabel ?? t("navigation.close")}</span>
</DialogPrimitive.Close>
diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts
index ddbba90..e2f784a 100644
--- a/src/db/schema/index.ts
+++ b/src/db/schema/index.ts
@@ -356,6 +356,8 @@ export const messageAttachments = sqliteTable(
.default("attachment"),
contentId: text("content_id"),
r2Key: text("r2_key").notNull().unique(),
+ /** Set when the attachment is moved to the Drive trash; hidden from the email until restored, purged after 30 days. */
+ trashedAt: integer("trashed_at", { mode: "timestamp" }),
createdAt: integer("created_at", { mode: "timestamp" })
.notNull()
.$defaultFn(() => new Date()),
@@ -673,6 +675,8 @@ export const appSettings = sqliteTable("app_settings", {
id: text("id").primaryKey(),
appName: text("app_name").notNull().default("Mailflare"),
outboundAttachmentMaxMb: integer("outbound_attachment_max_mb").notNull().default(25),
+ /** Per-user Drive storage cap in bytes; null means unlimited. */
+ driveStorageLimitBytes: integer("drive_storage_limit_bytes"),
resendApiKey: text("resend_api_key"),
/** JSON: AWS access key, secret and region (see src/lib/aws/config.ts). */
awsConfig: text("aws_config"),
@@ -703,6 +707,8 @@ export const licenseSettings = sqliteTable("license_settings", {
.notNull()
.default("inactive"),
features: text("features").notNull().default("[]"),
+ // Account seats from Paymug's seatLimit; null is unlimited. Rows predating seats keep one.
+ seatLimit: integer("seat_limit").default(1),
activatedAt: integer("activated_at", { mode: "timestamp" }),
validatedAt: integer("validated_at", { mode: "timestamp" }),
updatedAt: integer("updated_at", { mode: "timestamp" })
@@ -823,6 +829,45 @@ export const mcpKeyMailboxes = sqliteTable("mcp_key_mailboxes", {
mailboxId: text("mailbox_id").notNull().references(() => mailboxes.id, { onDelete: "cascade" }),
}, (t) => [uniqueIndex("mcp_key_mailbox_idx").on(t.keyId, t.mailboxId)]);
+export const driveItems = sqliteTable("drive_items", {
+ id: text("id").primaryKey(),
+ ownerId: text("owner_id").notNull().references(() => users.id, { onDelete: "cascade" }),
+ parentId: text("parent_id"),
+ kind: text("kind", { enum: ["file", "folder"] }).notNull(),
+ name: text("name").notNull(),
+ r2Key: text("r2_key"),
+ size: integer("size").notNull().default(0),
+ contentType: text("content_type").notNull().default("application/octet-stream"),
+ // Set while a multipart upload is in flight; such rows stay hidden until the upload completes.
+ uploadId: text("upload_id"),
+ uploadPartSize: integer("upload_part_size"),
+ uploadFingerprint: text("upload_fingerprint"),
+ linkToken: text("link_token"),
+ trashedAt: integer("trashed_at", { mode: "timestamp" }),
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),
+ updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),
+}, (t) => [
+ index("drive_items_owner_parent_idx").on(t.ownerId, t.parentId),
+ uniqueIndex("drive_items_link_token_idx").on(t.linkToken),
+]);
+
+export const driveUploadParts = sqliteTable("drive_upload_parts", {
+ itemId: text("item_id").notNull().references(() => driveItems.id, { onDelete: "cascade" }),
+ partNumber: integer("part_number").notNull(),
+ etag: text("etag").notNull(),
+}, (t) => [uniqueIndex("drive_upload_parts_idx").on(t.itemId, t.partNumber)]);
+
+export const driveShares = sqliteTable("drive_shares", {
+ id: text("id").primaryKey(),
+ itemId: text("item_id").notNull().references(() => driveItems.id, { onDelete: "cascade" }),
+ userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
+ role: text("role", { enum: ["view", "edit"] }).notNull().default("view"),
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),
+}, (t) => [
+ uniqueIndex("drive_shares_item_user_idx").on(t.itemId, t.userId),
+ index("drive_shares_user_idx").on(t.userId),
+]);
+
export const schema = {
users,
domains,
@@ -848,6 +893,9 @@ export const schema = {
webhookDeliveries,
sessions,
pushSubscriptions,
+ driveItems,
+ driveUploadParts,
+ driveShares,
auditLogs,
backupSettings,
backups,
diff --git a/src/lib/api/admin-auth.ts b/src/lib/api/admin-auth.ts
index 74bd3fe..5088d7f 100644
--- a/src/lib/api/admin-auth.ts
+++ b/src/lib/api/admin-auth.ts
@@ -8,6 +8,10 @@ export async function authenticateAdminApiKey(env: CloudflareEnv, request: Reque
return auth?.user.role === "admin" && auth.scopes.includes(scope) ? auth : null;
}
+export async function canShareAdminMailboxes(env: CloudflareEnv): Promise<boolean> {
+ return (await getLicenseEntitlements(env)).canShareMailboxes;
+}
+
export async function canManageAdminAccounts(env: CloudflareEnv): Promise<boolean> {
return (await getLicenseEntitlements(env)).canManageAccounts;
}
diff --git a/src/lib/drive/access.ts b/src/lib/drive/access.ts
new file mode 100644
index 0000000..a599bca
--- /dev/null
+++ b/src/lib/drive/access.ts
@@ -0,0 +1,135 @@
+import { and, eq, inArray } from "drizzle-orm";
+import { getDb } from "@/db";
+import { driveItems, driveShares, driveUploadParts, users } from "@/db/schema";
+import { DRIVE_MAX_DEPTH, driveObjectKey } from "./utils";
+import type { DriveItemDto, DriveRole, DriveRow } from "./types";
+
+type Db = ReturnType<typeof getDb>;
+
+export async function getDriveItem(db: Db, id: string): Promise<DriveRow | null> {
+ const [item] = await db.select().from(driveItems).where(eq(driveItems.id, id)).limit(1);
+ return item ?? null;
+}
+
+/** Ancestors from the root down to (and including) the item. Stops early at a missing parent. */
+export async function getDriveChain(db: Db, item: DriveRow): Promise<DriveRow[]> {
+ const chain: DriveRow[] = [item];
+ let current = item;
+ while (current.parentId && chain.length < DRIVE_MAX_DEPTH) {
+ const parent = await getDriveItem(db, current.parentId);
+ if (!parent) break;
+ chain.unshift(parent);
+ current = parent;
+ }
+ return chain;
+}
+
+/**
+ * Effective role for a user. Shares on any ancestor apply to everything beneath it. A trashed item or
+ * trashed ancestor is invisible unless `allowTrashed` (used by the owner's Trash view).
+ */
+export async function getDriveRole(db: Db, userId: string, item: DriveRow, allowTrashed = false): Promise<DriveRole | null> {
+ const chain = await getDriveChain(db, item);
+ if (!allowTrashed && chain.some((entry) => entry.trashedAt)) return null;
+ if (item.ownerId === userId) return "owner";
+ const shares = await db.select({ role: driveShares.role }).from(driveShares).where(and(eq(driveShares.userId, userId), inArray(driveShares.itemId, chain.map((entry) => entry.id))));
+ if (shares.some((share) => share.role === "edit")) return "edit";
+ return shares.length ? "view" : null;
+}
+
+/** Resolves a public link token to its root item, optionally narrowed to a descendant file. */
+export async function getPublicDriveItem(db: Db, token: string, itemId?: string | null): Promise<{ root: DriveRow; item: DriveRow } | null> {
+ const [root] = await db.select().from(driveItems).where(eq(driveItems.linkToken, token)).limit(1);
+ if (!root || root.trashedAt) return null;
+ if (!itemId || itemId === root.id) return { root, item: root };
+ const item = await getDriveItem(db, itemId);
+ if (!item) return null;
+ const chain = await getDriveChain(db, item);
+ if (chain.some((entry) => entry.trashedAt) || !chain.some((entry) => entry.id === root.id)) return null;
+ return { root, item };
+}
+
+export async function toDriveItemDtos(db: Db, rows: DriveRow[], userId: string, roleFor?: (row: DriveRow) => DriveRole): Promise<DriveItemDto[]> {
+ if (!rows.length) return [];
+ const ownerIds = [...new Set(rows.map((row) => row.ownerId))];
+ const owners = await db.select({ id: users.id, name: users.name, email: users.email, avatarKey: users.avatarKey }).from(users).where(inArray(users.id, ownerIds));
+ const ownerNames = new Map(owners.map((owner) => [owner.id, owner.name || owner.email]));
+ const ownerAvatars = new Map(owners.map((owner) => [owner.id, !!owner.avatarKey]));
+ const sharedIds = new Set<string>();
+ for (let index = 0; index < rows.length; index += 50) {
+ const slice = rows.slice(index, index + 50).map((row) => row.id);
+ const shares = await db.select({ itemId: driveShares.itemId }).from(driveShares).where(inArray(driveShares.itemId, slice));
+ for (const share of shares) sharedIds.add(share.itemId);
+ }
+ return rows.map((row) => ({
+ id: row.id,
+ kind: row.kind,
+ name: row.name,
+ size: row.size,
+ contentType: row.contentType,
+ parentId: row.parentId,
+ ownerId: row.ownerId,
+ ownerName: ownerNames.get(row.ownerId) ?? "",
+ ownerHasAvatar: ownerAvatars.get(row.ownerId) ?? false,
+ role: roleFor ? roleFor(row) : row.ownerId === userId ? "owner" : "view",
+ shared: sharedIds.has(row.id) || !!row.linkToken,
+ linkToken: row.ownerId === userId ? row.linkToken : null,
+ trashedAt: row.trashedAt?.toISOString() ?? null,
+ updatedAt: row.updatedAt.toISOString(),
+ }));
+}
+
+/** Every descendant of the given folders (breadth first), without the roots themselves. */
+export async function collectDriveDescendants(db: Db, rootIds: string[]): Promise<DriveRow[]> {
+ const found: DriveRow[] = [];
+ let level = rootIds;
+ for (let depth = 0; level.length && depth < DRIVE_MAX_DEPTH; depth += 1) {
+ const next: DriveRow[] = [];
+ for (let index = 0; index < level.length; index += 50) {
+ next.push(...await db.select().from(driveItems).where(inArray(driveItems.parentId, level.slice(index, index + 50))));
+ }
+ found.push(...next);
+ level = next.filter((row) => row.kind === "folder").map((row) => row.id);
+ }
+ return found;
+}
+
+/** Permanently removes items, their descendants and the stored objects. */
+export async function deleteDriveItems(env: CloudflareEnv, roots: DriveRow[]): Promise<void> {
+ const db = getDb(env);
+ const descendants = await collectDriveDescendants(db, roots.filter((row) => row.kind === "folder").map((row) => row.id));
+ const all = [...roots, ...descendants];
+ const keys = all.filter((row) => row.kind === "file").map((row) => row.r2Key ?? driveObjectKey(row.ownerId, row.id));
+ for (let index = 0; index < keys.length; index += 500) await env.BUCKET.delete(keys.slice(index, index + 500));
+ const ids = all.map((row) => row.id);
+ for (let index = 0; index < ids.length; index += 50) {
+ const slice = ids.slice(index, index + 50);
+ await db.delete(driveShares).where(inArray(driveShares.itemId, slice));
+ await db.delete(driveUploadParts).where(inArray(driveUploadParts.itemId, slice));
+ await db.delete(driveItems).where(inArray(driveItems.id, slice));
+ }
+}
+
+/** Drops rows that sit under a trashed folder; only the folder itself carries `trashedAt`. */
+export async function withoutTrashedAncestors(db: Db, rows: DriveRow[]): Promise<DriveRow[]> {
+ const trashedByFolder = new Map<string, boolean>();
+ async function isHidden(folderId: string | null): Promise<boolean> {
+ const path: string[] = [];
+ let current = folderId;
+ let hidden = false;
+ while (current && path.length < DRIVE_MAX_DEPTH) {
+ const known = trashedByFolder.get(current);
+ if (known !== undefined) { hidden = known; break; }
+ const folder = await getDriveItem(db, current);
+ path.push(current);
+ if (!folder) break;
+ if (folder.trashedAt) { hidden = true; break; }
+ current = folder.parentId;
+ }
+ for (const id of path) trashedByFolder.set(id, hidden);
+ return hidden;
+ }
+ const kept: DriveRow[] = [];
+ for (const row of rows) if (!(await isHidden(row.parentId))) kept.push(row);
+ return kept;
+}
diff --git a/src/lib/drive/attachments.ts b/src/lib/drive/attachments.ts
new file mode 100644
index 0000000..4a028c6
--- /dev/null
+++ b/src/lib/drive/attachments.ts
@@ -0,0 +1,59 @@
+import { and, desc, eq, inArray, isNotNull, isNull, notInArray } from "drizzle-orm";
+import { getDb } from "@/db";
+import { messageAttachments, messages } from "@/db/schema";
+import { hasMailboxPermission, listAccessibleMailboxes } from "@/lib/mailboxes/access";
+import { driveTypesCondition } from "./categories";
+import type { DriveCategory } from "./categories";
+import type { DriveItemDto } from "./types";
+
+type Db = ReturnType<typeof getDb>;
+const MAX_ATTACHMENTS = 500;
+const MAILBOX_CHUNK = 80;
+
+function senderName(from: string): string {
+ const named = from.match(/^\s*"?([^"<]+?)"?\s*<[^>]+>\s*$/)?.[1];
+ return (named ?? from).trim();
+}
+
+/**
+ * Files attached to mail the user can read, received or sent. Inline images, drafts, trash and spam are left out. With `trashed`, lists the attachments in the Drive trash instead.
+ * Deleting needs more than read-only access to the mailbox. The attachment's own id is the item id; it is opened through `/api/drive/attachments/<id>/content`.
+ */
+export async function listDriveAttachments(db: Db, user: Parameters<typeof listAccessibleMailboxes>[1], categories: DriveCategory[], trashed = false): Promise<DriveItemDto[]> {
+ const accessible = await listAccessibleMailboxes(db, user);
+ const mailboxIds = accessible.map((mailbox) => mailbox.id);
+ const permissions = new Map(accessible.map((mailbox) => [mailbox.id, mailbox.permission]));
+ const scopes = [and(isNull(messages.mailboxId), eq(messages.userId, user.id))];
+ for (let index = 0; index < mailboxIds.length; index += MAILBOX_CHUNK) scopes.push(inArray(messages.mailboxId, mailboxIds.slice(index, index + MAILBOX_CHUNK)));
+ const typeFilter = categories.length ? [driveTypesCondition(categories, { contentType: messageAttachments.contentType, name: messageAttachments.filename })] : [];
+
+ const fetchScope = (scope: ReturnType<typeof and>) => db
+ .select({ attachment: messageAttachments, messageId: messages.id, subject: messages.subject, from: messages.fromAddr, direction: messages.direction, mailboxId: messages.mailboxId, date: messages.createdAt })
+ .from(messageAttachments)
+ .innerJoin(messages, eq(messageAttachments.messageId, messages.id))
+ .where(and(scope, eq(messageAttachments.disposition, "attachment"), trashed ? isNotNull(messageAttachments.trashedAt) : isNull(messageAttachments.trashedAt), notInArray(messages.status, ["draft", "trash", "spam"]), ...typeFilter))
+ .orderBy(desc(messages.createdAt))
+ .limit(MAX_ATTACHMENTS);
+ const rows: Awaited<ReturnType<typeof fetchScope>> = [];
+ for (const scope of scopes) rows.push(...await fetchScope(scope));
+ return rows
+ .sort((a, b) => b.date.getTime() - a.date.getTime())
+ .slice(0, MAX_ATTACHMENTS)
+ .map((row) => ({
+ id: row.attachment.id,
+ kind: "file" as const,
+ name: row.attachment.filename,
+ size: row.attachment.size,
+ contentType: row.attachment.contentType,
+ parentId: null,
+ ownerId: row.messageId,
+ ownerName: senderName(row.from),
+ ownerHasAvatar: false,
+ role: "view" as const,
+ shared: false,
+ linkToken: null,
+ trashedAt: row.attachment.trashedAt?.toISOString() ?? null,
+ updatedAt: row.date.toISOString(),
+ source: { messageId: row.messageId, subject: row.subject ?? "", direction: row.direction, canDelete: !row.mailboxId || hasMailboxPermission(permissions.get(row.mailboxId) ?? "read_only", "send_on_behalf") },
+ }));
+}
diff --git a/src/lib/drive/auth.ts b/src/lib/drive/auth.ts
new file mode 100644
index 0000000..eb8363e
--- /dev/null
+++ b/src/lib/drive/auth.ts
@@ -0,0 +1,13 @@
+import { NextResponse } from "next/server";
+import { getDb } from "@/db";
+import { getEnv } from "@/lib/cloudflare";
+import { requireSessionUser } from "@/lib/api/auth";
+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";
+
+export async function authorizeDrive(request: Request, mutation = false) {
+ const env = getEnv();
+ const { user, error } = await requireSessionUser(env, request);
+ if (error) return { error } as const;
+ if (mutation && !hasValidSessionMutationOrigin(request)) return { error: NextResponse.json({ error: "Invalid origin" }, { status: 403 }) } as const;
+ return { env, db: getDb(env), user, error: null } as const;
+}
diff --git a/src/lib/drive/categories.ts b/src/lib/drive/categories.ts
new file mode 100644
index 0000000..f50c083
--- /dev/null
+++ b/src/lib/drive/categories.ts
@@ -0,0 +1,50 @@
+import { like, or, sql } from "drizzle-orm";
+import type { AnyColumn, SQL } from "drizzle-orm";
+import { driveItems } from "@/db/schema";
+
+import { isDriveCategory } from "./category-names";
+import type { DriveCategory } from "./category-names";
+
+export { DRIVE_CATEGORIES, isDriveCategory } from "./category-names";
+export type { DriveCategory } from "./category-names";
+
+// Browsers leave the type empty for formats they do not know (HEIC, Markdown, Office files on some systems),
+// so the file extension is checked as well.
+const PHOTO_EXTENSIONS = ["jpg", "jpeg", "png", "gif", "webp", "avif", "heic", "heif", "bmp", "tif", "tiff", "svg", "raw", "dng"];
+const VIDEO_EXTENSIONS = ["mp4", "mov", "m4v", "mkv", "webm", "avi", "wmv", "mpg", "mpeg", "3gp"];
+const DOCUMENT_EXTENSIONS = ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "md", "csv", "rtf", "odt", "ods", "odp", "pages", "numbers", "key", "epub"];
+
+export type DriveTypeColumns = { contentType: AnyColumn; name: AnyColumn };
+const driveColumns: DriveTypeColumns = { contentType: driveItems.contentType, name: driveItems.name };
+
+/** Parses `?types=photos,videos` into known categories. */
+export function parseDriveCategories(value: string | null): DriveCategory[] {
+ return [...new Set((value ?? "").split(",").filter(isDriveCategory))];
+}
+
+function build(columns: DriveTypeColumns) {
+ const byExtension = (extensions: string[]) => extensions.map((extension) => sql`lower(${columns.name}) like ${`%.${extension}`}`);
+ const photo = or(like(columns.contentType, "image/%"), ...byExtension(PHOTO_EXTENSIONS))!;
+ const video = or(like(columns.contentType, "video/%"), ...byExtension(VIDEO_EXTENSIONS))!;
+ const document = or(
+ like(columns.contentType, "text/%"),
+ like(columns.contentType, "application/vnd.%"),
+ sql`${columns.contentType} in ('application/pdf', 'application/msword', 'application/rtf', 'application/json', 'application/epub+zip')`,
+ ...byExtension(DOCUMENT_EXTENSIONS),
+ )!;
+ return { photo, video, document };
+}
+
+/** WHERE condition selecting the files of a category. Photos and videos win over documents, e.g. for an .svg. */
+export function driveCategoryCondition(category: DriveCategory, columns: DriveTypeColumns = driveColumns): SQL {
+ const { photo, video, document } = build(columns);
+ if (category === "photos") return photo;
+ if (category === "videos") return video;
+ if (category === "documents") return sql`((${document}) and not (${photo}) and not (${video}))`;
+ return sql`(not (${photo}) and not (${video}) and not (${document}))`;
+}
+
+/** Files matching any of the chosen categories. */
+export function driveTypesCondition(categories: DriveCategory[], columns: DriveTypeColumns = driveColumns): SQL {
+ return or(...categories.map((category) => driveCategoryCondition(category, columns)))!;
+}
diff --git a/src/lib/drive/category-names.ts b/src/lib/drive/category-names.ts
new file mode 100644
index 0000000..526a11c
--- /dev/null
+++ b/src/lib/drive/category-names.ts
@@ -0,0 +1,6 @@
+export const DRIVE_CATEGORIES = ["photos", "videos", "documents", "others"] as const;
+export type DriveCategory = (typeof DRIVE_CATEGORIES)[number];
+
+export function isDriveCategory(value: string | null): value is DriveCategory {
+ return !!value && (DRIVE_CATEGORIES as readonly string[]).includes(value);
+}
diff --git a/src/lib/drive/content.ts b/src/lib/drive/content.ts
new file mode 100644
index 0000000..dc24a3a
--- /dev/null
+++ b/src/lib/drive/content.ts
@@ -0,0 +1,57 @@
+import { driveContentDisposition, driveObjectKey, isDriveInlineSafe } from "./utils";
+import type { DriveRow } from "./types";
+
+/** Parses a single `bytes=` range. Returns null when absent or unusable (multi-range is served whole), "invalid" when unsatisfiable. */
+export function parseByteRange(header: string | null, size: number): { start: number; end: number } | "invalid" | null {
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header?.trim() ?? "");
+ if (!match || (match[1] === "" && match[2] === "")) return null;
+ let start: number;
+ let end: number;
+ if (match[1] === "") {
+ const suffix = Number(match[2]);
+ if (suffix === 0) return "invalid";
+ start = Math.max(size - suffix, 0);
+ end = size - 1;
+ } else {
+ start = Number(match[1]);
+ end = match[2] === "" ? size - 1 : Math.min(Number(match[2]), size - 1);
+ }
+ return start >= size || start > end ? "invalid" : { start, end };
+}
+
+/** Streams a stored file with support for resumable downloads and seeking (`Range` / `If-Range`). */
+export async function streamDriveFile(env: CloudflareEnv, request: Request, item: DriveRow, download: boolean): Promise<Response> {
+ if (item.kind !== "file") return new Response("Not a file", { status: 400 });
+ const inline = !download && isDriveInlineSafe(item.contentType);
+ const etag = `"${item.id}-${item.updatedAt.getTime().toString(36)}-${item.size.toString(36)}"`;
+ const headers = new Headers();
+ headers.set("Content-Type", inline ? item.contentType : "application/octet-stream");
+ headers.set("Content-Disposition", driveContentDisposition(item.name, inline));
+ headers.set("Accept-Ranges", "bytes");
+ headers.set("ETag", etag);
+ headers.set("X-Content-Type-Options", "nosniff");
+ // Chrome's PDF viewer is blocked by a sandbox or a restrictive default-src (it needs object/plugin loads), and a
+ // PDF served with nosniff cannot run script, so it only gets the framing rule.
+ headers.set("Content-Security-Policy", inline && item.contentType === "application/pdf" ? "frame-ancestors 'self'" : "default-src 'none'; style-src 'unsafe-inline'; sandbox");
+ headers.set("Referrer-Policy", "no-referrer");
+ headers.set("Cache-Control", "private, no-store");
+
+ // A client resuming against a file that changed since must start over, which If-Range expresses.
+ const ifRange = request.headers.get("If-Range");
+ const range = ifRange && ifRange !== etag ? null : parseByteRange(request.headers.get("Range"), item.size);
+ if (range === "invalid") {
+ headers.set("Content-Range", `bytes */${item.size}`);
+ return new Response(null, { status: 416, headers });
+ }
+
+ const key = item.r2Key ?? driveObjectKey(item.ownerId, item.id);
+ const object = range ? await env.BUCKET.get(key, { range: { offset: range.start, length: range.end - range.start + 1 } }) : await env.BUCKET.get(key);
+ if (!object) return new Response("File not found", { status: 404 });
+ if (!range) {
+ headers.set("Content-Length", String(item.size));
+ return new Response(request.method === "HEAD" ? null : object.body, { headers });
+ }
+ headers.set("Content-Range", `bytes ${range.start}-${range.end}/${item.size}`);
+ headers.set("Content-Length", String(range.end - range.start + 1));
+ return new Response(request.method === "HEAD" ? null : object.body, { status: 206, headers });
+}
diff --git a/src/lib/drive/retention.ts b/src/lib/drive/retention.ts
new file mode 100644
index 0000000..d250a51
--- /dev/null
+++ b/src/lib/drive/retention.ts
@@ -0,0 +1,38 @@
+import { and, inArray, isNotNull, lte } from "drizzle-orm";
+import { getDb } from "@/db";
+import { driveItems, messageAttachments } from "@/db/schema";
+import { deleteDriveItems } from "./access";
+
+export const DRIVE_TRASH_RETENTION_DAYS = 30;
+const BATCH_SIZE = 100;
+const MAX_PASSES = 20;
+
+/**
+ * Permanently deletes Drive items and email attachments that have been in the trash for 30 days or more: database
+ * rows and stored objects both. Runs once a day from the scheduled handler. Each pass handles one batch of each kind
+ * and passes repeat until nothing is left (up to a cap), so a large backlog is cleared in a single daily run.
+ */
+export async function runDriveTrashRetention(env: CloudflareEnv, now = new Date()): Promise<number> {
+ const db = getDb(env);
+ const cutoff = new Date(now.getTime() - DRIVE_TRASH_RETENTION_DAYS * 24 * 60 * 60_000);
+ let removed = 0;
+
+ for (let pass = 0; pass < MAX_PASSES; pass += 1) {
+ const expiredItems = await db.select().from(driveItems).where(and(isNotNull(driveItems.trashedAt), lte(driveItems.trashedAt, cutoff))).limit(BATCH_SIZE);
+ if (expiredItems.length) await deleteDriveItems(env, expiredItems);
+
+ const expiredAttachments = await db
+ .select({ id: messageAttachments.id, r2Key: messageAttachments.r2Key })
+ .from(messageAttachments)
+ .where(and(isNotNull(messageAttachments.trashedAt), lte(messageAttachments.trashedAt, cutoff)))
+ .limit(BATCH_SIZE);
+ if (expiredAttachments.length) {
+ await env.BUCKET.delete(expiredAttachments.map((row) => row.r2Key));
+ await db.delete(messageAttachments).where(inArray(messageAttachments.id, expiredAttachments.map((row) => row.id)));
+ }
+
+ removed += expiredItems.length + expiredAttachments.length;
+ if (expiredItems.length < BATCH_SIZE && expiredAttachments.length < BATCH_SIZE) break;
+ }
+ return removed;
+}
diff --git a/src/lib/drive/storage.ts b/src/lib/drive/storage.ts
new file mode 100644
index 0000000..6b24958
--- /dev/null
+++ b/src/lib/drive/storage.ts
@@ -0,0 +1,14 @@
+import { eq, sql } from "drizzle-orm";
+import { getDb } from "@/db";
+import { appSettings, driveItems } from "@/db/schema";
+
+/** Per-user Drive cap in bytes, or null for unlimited. Set by the admin on the General page. */
+export async function getDriveStorageLimit(env: CloudflareEnv): Promise<number | null> {
+ const [settings] = await getDb(env).select({ limit: appSettings.driveStorageLimitBytes }).from(appSettings).where(eq(appSettings.id, "default")).limit(1);
+ return settings?.limit && settings.limit > 0 ? settings.limit : null;
+}
+
+export async function getDriveStorageUsed(db: ReturnType<typeof getDb>, ownerId: string): Promise<number> {
+ const [usage] = await db.select({ total: sql<number>`coalesce(sum(${driveItems.size}), 0)` }).from(driveItems).where(eq(driveItems.ownerId, ownerId));
+ return Number(usage?.total ?? 0);
+}
diff --git a/src/lib/drive/types.d.ts b/src/lib/drive/types.d.ts
new file mode 100644
index 0000000..9985031
--- /dev/null
+++ b/src/lib/drive/types.d.ts
@@ -0,0 +1,28 @@
+import type { driveItems } from "@/db/schema";
+
+export type DriveRow = typeof driveItems.$inferSelect;
+export type DriveRole = "owner" | "edit" | "view";
+export type DriveShareRole = "view" | "edit";
+
+export type DriveItemDto = {
+ id: string;
+ kind: "file" | "folder";
+ name: string;
+ size: number;
+ contentType: string;
+ parentId: string | null;
+ ownerId: string;
+ ownerName: string;
+ ownerHasAvatar: boolean;
+ role: DriveRole;
+ shared: boolean;
+ linkToken: string | null;
+ trashedAt: string | null;
+ updatedAt: string;
+ /** Set for files that come from an email rather than from Drive. */
+ source?: { messageId: string; subject: string; direction: "inbound" | "outbound"; canDelete: boolean };
+};
+
+export type DriveCrumb = { id: string; name: string };
+
+export type DriveShareDto = { id: string; userId: string; name: string; email: string; role: DriveShareRole };
diff --git a/src/lib/drive/utils.ts b/src/lib/drive/utils.ts
new file mode 100644
index 0000000..fd018b9
--- /dev/null
+++ b/src/lib/drive/utils.ts
@@ -0,0 +1,59 @@
+import type { DriveCrumb, DriveRole, DriveRow } from "./types";
+
+/**
+ * Files upload in parts straight into an R2 multipart upload, so no file is ever buffered in the Worker. A part must stay
+ * under the 100 MB request limit of Cloudflare's Free and Pro plans, and R2 allows 10,000 parts per object, which caps a
+ * file at about 640 GB. Lowering the part size shrinks that cap; raising it needs a plan with larger request bodies.
+ */
+export const DRIVE_PART_BYTES = 64 * 1024 * 1024;
+/** How long an interrupted upload can be resumed. R2 should be set to abort incomplete multipart uploads after about as long. */
+export const DRIVE_UPLOAD_RESUME_MS = 3 * 24 * 60 * 60 * 1000;
+export const DRIVE_MAX_PARTS = 10_000;
+export const DRIVE_MAX_FILE_BYTES = DRIVE_PART_BYTES * DRIVE_MAX_PARTS;
+export const DRIVE_MAX_NAME_LENGTH = 255;
+export const DRIVE_MAX_DEPTH = 64;
+
+export function normalizeDriveName(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const name = value.replace(/[\u0000-\u001f/\\]/g, " ").replace(/\s+/g, " ").trim().slice(0, DRIVE_MAX_NAME_LENGTH);
+ return name && name !== "." && name !== ".." ? name : null;
+}
+
+export function canEditDrive(role: DriveRole | null): boolean {
+ return role === "owner" || role === "edit";
+}
+
+export function driveObjectKey(ownerId: string, itemId: string): string {
+ return `drive/${ownerId}/${itemId}`;
+}
+
+export function toDriveCrumbs(chain: DriveRow[]): DriveCrumb[] {
+ return chain.map((item) => ({ id: item.id, name: item.name }));
+}
+
+export function formatDriveSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ const units = ["KB", "MB", "GB", "TB"];
+ let value = bytes / 1024;
+ let unit = 0;
+ while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit += 1; }
+ return `${value >= 10 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`;
+}
+
+export function driveContentDisposition(filename: string, inline: boolean): string {
+ const ascii = filename.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
+ return `${inline ? "inline" : "attachment"}; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
+}
+
+/** Types that are safe to render in the browser; everything else (HTML, SVG, scripts) is forced to download. */
+export function isDriveInlineSafe(contentType: string): boolean {
+ return (
+ contentType === "application/pdf" ||
+ contentType.startsWith("audio/") ||
+ contentType.startsWith("video/") ||
+ (contentType.startsWith("image/") && contentType !== "image/svg+xml") ||
+ contentType === "text/plain" ||
+ contentType === "text/csv" ||
+ contentType === "application/json"
+ );
+}
diff --git a/src/lib/email/attachments.ts b/src/lib/email/attachments.ts
index 19c291e..5e892b8 100644
--- a/src/lib/email/attachments.ts
+++ b/src/lib/email/attachments.ts
@@ -1,4 +1,4 @@
-import { and, eq } from "drizzle-orm";
+import { and, eq, isNull } from "drizzle-orm";
import { getDb } from "@/db";
import { messageAttachments, messages } from "@/db/schema";
import { newId } from "@/lib/ids";
@@ -120,7 +120,7 @@ export async function copyMessageAttachments(
toMessageId: string,
): Promise<AttachmentMetadata[]> {
const db = getDb(env);
- const rows = await db.select().from(messageAttachments).where(eq(messageAttachments.messageId, fromMessageId));
+ const rows = await db.select().from(messageAttachments).where(and(eq(messageAttachments.messageId, fromMessageId), isNull(messageAttachments.trashedAt)));
const copied: AttachmentMetadata[] = [];
for (const row of rows) {
const object = await env.BUCKET.get(row.r2Key);
@@ -160,7 +160,7 @@ export async function loadMessageAttachmentContents(
messageId: string,
): Promise<AttachmentContent[]> {
const db = getDb(env);
- const rows = await db.select().from(messageAttachments).where(eq(messageAttachments.messageId, messageId));
+ const rows = await db.select().from(messageAttachments).where(and(eq(messageAttachments.messageId, messageId), isNull(messageAttachments.trashedAt)));
const result: AttachmentContent[] = [];
for (const row of rows) {
const object = await env.BUCKET.get(row.r2Key);
@@ -213,7 +213,7 @@ export async function listMessageAttachments(
const rows = await db
.select()
.from(messageAttachments)
- .where(eq(messageAttachments.messageId, messageId));
+ .where(and(eq(messageAttachments.messageId, messageId), isNull(messageAttachments.trashedAt)));
return rows.map((attachment) => ({
id: attachment.id,
@@ -250,6 +250,7 @@ export async function getAttachmentForUser(
and(
eq(messageAttachments.id, attachmentId),
eq(messageAttachments.messageId, messageId),
+ isNull(messageAttachments.trashedAt),
),
)
.limit(1);
diff --git a/src/lib/email/thread-view.ts b/src/lib/email/thread-view.ts
index 98a4602..12e94b3 100644
--- a/src/lib/email/thread-view.ts
+++ b/src/lib/email/thread-view.ts
@@ -1,4 +1,4 @@
-import { and, asc, eq, inArray, notInArray } from "drizzle-orm";
+import { and, asc, eq, inArray, isNull, notInArray } from "drizzle-orm";
import { getDb } from "@/db";
import { messageAttachments, messages } from "@/db/schema";
import { getContactAvatarMap, getContactDisplayNameMap } from "@/lib/contacts/service";
@@ -58,7 +58,7 @@ export async function getMessageThreadForUser(env: CloudflareEnv, user: SessionU
contentId: messageAttachments.contentId,
})
.from(messageAttachments)
- .where(inArray(messageAttachments.messageId, ids))
+ .where(and(inArray(messageAttachments.messageId, ids), isNull(messageAttachments.trashedAt)))
: [];
const attachmentsByMessage = new Map<string, typeof attachmentRows>();
for (const attachment of attachmentRows) {
diff --git a/src/lib/jmap/blobs.ts b/src/lib/jmap/blobs.ts
index be06af1..c35af84 100644
--- a/src/lib/jmap/blobs.ts
+++ b/src/lib/jmap/blobs.ts
@@ -1,4 +1,4 @@
-import { and, eq } from "drizzle-orm";
+import { and, eq, isNull } from "drizzle-orm";
import { messageAttachments, messages } from "@/db/schema";
import { newId } from "@/lib/ids";
import { LIMITS } from "./constants";
@@ -67,7 +67,7 @@ export async function readBlob(ctx: JmapContext, blobId: string): Promise<{ body
.select({ r2Key: messageAttachments.r2Key, filename: messageAttachments.filename, type: messageAttachments.contentType, size: messageAttachments.size, mailboxId: messages.mailboxId })
.from(messageAttachments)
.innerJoin(messages, eq(messageAttachments.messageId, messages.id))
- .where(eq(messageAttachments.id, decoded.id))
+ .where(and(eq(messageAttachments.id, decoded.id), isNull(messageAttachments.trashedAt)))
.limit(1);
if (!row || !row.mailboxId || !accessible.has(row.mailboxId)) return null;
const object = await ctx.env.BUCKET.get(row.r2Key);
diff --git a/src/lib/jmap/email-objects.ts b/src/lib/jmap/email-objects.ts
index 774cc60..e367eee 100644
--- a/src/lib/jmap/email-objects.ts
+++ b/src/lib/jmap/email-objects.ts
@@ -1,4 +1,4 @@
-import { inArray } from "drizzle-orm";
+import { and, inArray, isNull } from "drizzle-orm";
import { messageAttachments, messages } from "@/db/schema";
import { parseEmailAddressParts, splitEmailAddressList } from "@/lib/email/address";
import { htmlToReadableText } from "@/lib/email/reply-content-utils";
@@ -139,7 +139,7 @@ export function buildEmailObject(row: MessageRow, attachments: AttachmentRow[],
export async function loadAttachmentsByMessage(ctx: JmapContext, messageIds: string[]): Promise<Map<string, AttachmentRow[]>> {
const result = new Map<string, AttachmentRow[]>();
if (messageIds.length === 0) return result;
- const rows = await ctx.db.select().from(messageAttachments).where(inArray(messageAttachments.messageId, messageIds));
+ const rows = await ctx.db.select().from(messageAttachments).where(and(inArray(messageAttachments.messageId, messageIds), isNull(messageAttachments.trashedAt)));
for (const row of rows) {
const list = result.get(row.messageId) ?? [];
list.push(row);
diff --git a/src/lib/licenses/seats.ts b/src/lib/licenses/seats.ts
new file mode 100644
index 0000000..cd654d5
--- /dev/null
+++ b/src/lib/licenses/seats.ts
@@ -0,0 +1,20 @@
+import { and, count, eq } from "drizzle-orm";
+import { getDb } from "@/db";
+import { users } from "@/db/schema";
+import { getLicenseEntitlements } from "./service";
+
+/** Enabled accounts occupy a seat; the primary admin is one of them. */
+export async function countUsedAccountSeats(env: CloudflareEnv): Promise<number> {
+ const [row] = await getDb(env).select({ total: count() }).from(users).where(eq(users.disabled, false));
+ return row?.total ?? 0;
+}
+
+/** Returns an error message when no seat is free for one more enabled account, otherwise null. */
+export async function getAccountSeatError(env: CloudflareEnv): Promise<string | null> {
+ const { accountSeatLimit } = await getLicenseEntitlements(env);
+ if (accountSeatLimit === null) return null;
+ const used = await countUsedAccountSeats(env);
+ return used >= accountSeatLimit
+ ? `All ${accountSeatLimit} account seats of this license are in use. Disable an account or add seats to your license`
+ : null;
+}
diff --git a/src/lib/licenses/service.ts b/src/lib/licenses/service.ts
index 5c4446f..0b796bd 100644
--- a/src/lib/licenses/service.ts
+++ b/src/lib/licenses/service.ts
@@ -30,6 +30,7 @@ function toLicenseStatus(settings: typeof licenseSettings.$inferSelect): License
plan: active ? settings.plan : "community",
state: settings.state,
features: parseFeatures(settings.features),
+ seatLimit: active && settings.plan === "pro" ? settings.seatLimit : null,
instanceId: settings.instanceId,
instanceUrl: settings.instanceUrl,
active,
@@ -45,15 +46,17 @@ export async function getLicenseStatus(env: CloudflareEnv): Promise<LicenseStatu
export async function getLicenseEntitlements(env: CloudflareEnv): Promise<LicenseEntitlements> {
try {
const status = await getLicenseStatus(env);
- // TODO: confirm Paymug's exact feature identifiers when they are documented; plan is authoritative meanwhile.
+ // Pro adds accounts up to its seat limit; Team is unlimited and also unlocks shared mailboxes.
return {
plan: status.plan,
- canCustomizeBranding: status.active && (status.plan === "pro" || status.plan === "team"),
- canManageAccounts: status.active && status.plan === "team",
- canForwardEmail: status.active && (status.plan === "pro" || status.plan === "team"),
+ canCustomizeBranding: status.active,
+ canManageAccounts: status.active,
+ canShareMailboxes: status.active && status.plan === "team",
+ accountSeatLimit: status.seatLimit,
+ canForwardEmail: status.active,
};
} catch {
- return { plan: "community", canCustomizeBranding: false, canManageAccounts: false, canForwardEmail: false };
+ return { plan: "community", canCustomizeBranding: false, canManageAccounts: false, canShareMailboxes: false, accountSeatLimit: 0, canForwardEmail: false };
}
}
@@ -102,6 +105,7 @@ async function updateLicenseFromPaymug(
plan: "community",
state: "deactivated",
features: "[]",
+ seatLimit: 1,
validatedAt: now,
updatedAt: now,
})
@@ -132,6 +136,7 @@ async function updateLicenseFromPaymug(
plan,
state: "active",
features: JSON.stringify(result.features ?? []),
+ seatLimit: result.seatLimit === undefined ? settings.seatLimit : result.seatLimit,
activatedAt: action === "activate" ? now : settings.activatedAt,
validatedAt: now,
updatedAt: now,
diff --git a/src/lib/licenses/types.d.ts b/src/lib/licenses/types.d.ts
index 4a7b866..48bb7eb 100644
--- a/src/lib/licenses/types.d.ts
+++ b/src/lib/licenses/types.d.ts
@@ -11,12 +11,15 @@ export type PaymugLicenseResponse = {
productId?: string;
plan?: string;
features?: string[];
+ seatLimit?: number | null;
};
export type LicenseStatus = {
plan: LicensePlan;
state: LicenseState;
features: string[];
+ /** Account seats; null is unlimited. */
+ seatLimit: number | null;
instanceId: string;
instanceUrl: string | null;
active: boolean;
@@ -41,5 +44,9 @@ export type LicenseEntitlements = {
plan: LicensePlan;
canCustomizeBranding: boolean;
canManageAccounts: boolean;
+ /** Shared inboxes, mailbox sharing and booking hosts: Team only. */
+ canShareMailboxes: boolean;
+ /** Maximum enabled accounts; null is unlimited. */
+ accountSeatLimit: number | null;
canForwardEmail: boolean;
};
diff --git a/src/lib/licenses/utils.ts b/src/lib/licenses/utils.ts
index 713ebc1..938f880 100644
--- a/src/lib/licenses/utils.ts
+++ b/src/lib/licenses/utils.ts
@@ -35,6 +35,7 @@ export function parsePaymugLicenseResponse(value: unknown): PaymugLicenseRespons
features: Array.isArray(response.features)
? response.features.filter((feature): feature is string => typeof feature === "string")
: undefined,
+ seatLimit: response.seatLimit === null ? null : typeof response.seatLimit === "number" && Number.isInteger(response.seatLimit) && response.seatLimit >= 0 ? response.seatLimit : undefined,
};
}
diff --git a/src/lib/mcp/admin-tools.ts b/src/lib/mcp/admin-tools.ts
index 40024b8..63b3211 100644
--- a/src/lib/mcp/admin-tools.ts
+++ b/src/lib/mcp/admin-tools.ts
@@ -55,7 +55,7 @@ export function registerAdminMcpTools(server: McpServer, principal: McpPrincipal
});
if (principal.scopes.includes("accounts")) server.registerTool("manage_accounts", {
- description: "List, inspect, create, or update managed accounts. Actions: list, get, create, update. Pass id for get or update and data for create or update. For create, data accepts username, domainId, password, role?, useAllDomains? (defaults to true for compatibility), and aliases?: [{ domainId, localPart }]. Set useAllDomains to false to assign only the primary address and explicit aliases. Requires a Team license.",
+ description: "List, inspect, create, or update managed accounts. Actions: list, get, create, update. Pass id for get or update and data for create or update. For create, data accepts username, domainId, password, role?, useAllDomains? (defaults to true for compatibility), and aliases?: [{ domainId, localPart }]. Set useAllDomains to false to assign only the primary address and explicit aliases. Requires a Pro or Team license; Pro is limited to its account seats.",
inputSchema: adminInput,
}, async ({ action, id, data }) => {
if (!principal.scopes.includes("accounts")) return result({ error: "Permission denied" }, true);
diff --git a/src/lib/security/headers.ts b/src/lib/security/headers.ts
index f1913e0..19669a7 100644
--- a/src/lib/security/headers.ts
+++ b/src/lib/security/headers.ts
@@ -5,7 +5,8 @@ const csp = [
"img-src 'self' data: blob: https:",
"font-src 'self' data:",
"connect-src 'self' ws: wss: https://challenges.cloudflare.com",
- "frame-src https://challenges.cloudflare.com",
+ // 'self' lets the Drive preview show PDFs and text files in an iframe.
+ "frame-src 'self' https://challenges.cloudflare.com",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
diff --git a/tests/account-alias-selection.test.mjs b/tests/account-alias-selection.test.mjs
index 16550ac..144e578 100644
--- a/tests/account-alias-selection.test.mjs
+++ b/tests/account-alias-selection.test.mjs
@@ -242,6 +242,20 @@ test("account creation still enforces admin authorization and the Team license",
assert.equal(f.calls.length, 0);
});
+test("a Pro license creates accounts only while seats remain; Team and unlimited Pro have no limit", async (t) => {
+ const f = await fixture(t);
+ const users = () => f.database.db.prepare("SELECT count(*) AS count FROM users WHERE disabled = 0").get().count;
+ f.database.db.exec(`UPDATE license_settings SET plan = 'pro', seat_limit = ${users()}`);
+ assert.equal((await f.post("api")).status, 403, "no seat left");
+ f.database.db.exec(`UPDATE license_settings SET seat_limit = ${users() + 1}`);
+ assert.equal((await f.post("api", { username: "seat-one" })).status, 201);
+ assert.equal((await f.post("api", { username: "seat-two" })).status, 403, "seat just used");
+ f.database.db.exec("UPDATE license_settings SET seat_limit = NULL");
+ assert.equal((await f.post("api", { username: "seat-three" })).status, 201);
+ f.database.db.exec("UPDATE license_settings SET plan = 'team', seat_limit = 1");
+ assert.equal((await f.post("api", { username: "seat-four" })).status, 201);
+});
+
for (const separateDomains of [false, true]) {
test(`more than 50 aliases on ${separateDomains ? "separate domains" : "one domain"} stay within database parameter limits`, async (t) => {
const f = await fixture(t);
diff --git a/tests/i18n.test.mjs b/tests/i18n.test.mjs
index 5fe6492..3cafa27 100644
--- a/tests/i18n.test.mjs
+++ b/tests/i18n.test.mjs
@@ -11,6 +11,18 @@ const outDir = mkdtempSync(join(tmpdir(), "mailflare-i18n-"));
after(() => rmSync(outDir, { recursive: true, force: true }));
const outfile = join(outDir, "i18n.mjs");
+// Catalogs other than English are static assets; tests serve them from public/ for both the browser
+// `fetch` and the server's ASSETS binding. `testCatalogs` adds in-memory catalogs for an isolated locale.
+globalThis.testCatalogs = {};
+globalThis.readTestAsset = async (input) => {
+ const path = new URL(String(input), "https://mailflare.local").pathname;
+ const code = path.match(/^\/locales\/([\w-]+)\.json$/)?.[1];
+ if (code && globalThis.testCatalogs[code]) return Response.json(globalThis.testCatalogs[code]);
+ const file = join(root, "public", path);
+ return existsSync(file) ? new Response(readFileSync(file)) : new Response("Not found", { status: 404 });
+};
+globalThis.fetch = globalThis.readTestAsset;
+
async function bundleI18n(outfile, extraLocale = false) {
await build({
stdin: {
@@ -49,15 +61,17 @@ async function bundleI18n(outfile, extraLocale = false) {
setup(builder) {
if (extraLocale) builder.onLoad({ filter: /\/i18n\/locales\.ts$/ }, ({ path }) => ({
contents: readFileSync(path, "utf8").replace("export const locales = {", `export const locales = {
- xx: { label: "Testlandic", dir: "rtl", load: async () => ({ ...en, "navigation.inbox": "Entrada", "navigation.inbox.one": "{count} entrada", "navigation.inbox.other": "{count} entradas", "language.label": "Idioma" }) },`),
+ xx: { label: "Testlandic", dir: "rtl" },`),
loader: "ts",
}));
- builder.onResolve({ filter: /^(next\/headers|next\/font\/google|@\/components\/providers)$/ }, (args) => ({ path: args.path, namespace: "stub" }));
+ builder.onResolve({ filter: /^(next\/headers|next\/font\/google|@\/components\/providers|@\/lib\/cloudflare)$/ }, (args) => ({ path: args.path, namespace: "stub" }));
builder.onLoad({ filter: /.*/, namespace: "stub" }, ({ path }) => ({ contents: path === "next/headers"
? 'export async function cookies() { return { get(name) { return name === "mailflare-locale" && globalThis.testLocaleCookie !== undefined ? { value: globalThis.testLocaleCookie } : undefined; } }; }'
: path === "next/font/google"
? 'export const Geist = () => ({ variable: "sans" }); export const Geist_Mono = () => ({ variable: "mono" });'
- : 'export function Providers({ children }) { return children; }' }));
+ : path === "@/lib/cloudflare"
+ ? "export function getEnv() { return { ASSETS: { fetch: globalThis.readTestAsset } }; }"
+ : 'export function Providers({ children }) { return children; }' }));
builder.onLoad({ filter: /\.css$/ }, () => ({ contents: "", loader: "js" }));
},
}],
@@ -77,8 +91,8 @@ const pluralBases = new Set(Object.keys(en).filter((key) => key.endsWith(".other
const isPluralKey = (key) => categoryOf(key) && pluralBases.has(baseOf(key));
test("every registered catalog has the English keys and nonempty messages and label", async () => {
- for (const [code, { load, label }] of Object.entries(i18n.locales)) {
- const catalog = await load();
+ for (const [code, { label }] of Object.entries(i18n.locales)) {
+ const catalog = await i18n.loadMessages(code);
assert.ok(label.trim().length > 0, code);
const plain = (keys) => keys.filter((key) => !isPluralKey(key)).sort();
assert.deepEqual(plain(Object.keys(catalog)), plain(Object.keys(en)), `${code}: keys differ from English`);
@@ -136,6 +150,7 @@ test("root layout passes the same cookie locale to HTML and provider on first re
test("a locale registered once reaches resolution, translation, cookie, selector and SSR", async () => {
assert.ok(existsSync(join(root, "src/lib/i18n/locales.ts")), "locales must have one shared registry");
+ globalThis.testCatalogs.xx = { ...en, "navigation.inbox": "Entrada", "navigation.inbox.one": "{count} entrada", "navigation.inbox.other": "{count} entradas", "language.label": "Idioma" };
const extraFile = join(outDir, "with-spanish.mjs");
await bundleI18n(extraFile, true);
const extended = await import(pathToFileURL(extraFile).href);
diff --git a/worker.ts b/worker.ts
index 4ecdd36..2f22697 100644
--- a/worker.ts
+++ b/worker.ts
@@ -20,6 +20,7 @@ import { runScheduledDatabaseBackup } from "./src/lib/backups/runner";
import { processAgentDraftJob } from "./src/lib/agent/jobs/utils";
import { runAgentMaintenance } from "./src/lib/agent/maintenance";
import { runTrashRetention } from "./src/lib/email/trash-retention";
+import { runDriveTrashRetention } from "./src/lib/drive/retention";
export { RealtimeHub } from "./src/lib/realtime/hub";
export default {
@@ -126,5 +127,7 @@ export default {
if (controller.cron === "0 2 * * *") ctx.waitUntil(runScheduledDatabaseBackup(env, new Date(controller.scheduledTime)));
ctx.waitUntil(runAgentMaintenance(env));
ctx.waitUntil(runTrashRetention(env, new Date(controller.scheduledTime)));
+ // Drive trash is emptied once a day, with the 02:00 UTC cron; the 5-minute cron is for queue-like upkeep.
+ if (controller.cron === "0 2 * * *") ctx.waitUntil(runDriveTrashRetention(env, new Date(controller.scheduledTime)));
},
} satisfies ExportedHandler<CloudflareEnv>;