Skip to content

Email for professionals and teams

add qr signin

Hieu Nguyen (Jack)cd8a5b4342bd
diff --git a/src/app/api/api-keys/route.ts b/src/app/api/api-keys/route.ts
index 0e05ef7..7443275 100644
--- a/src/app/api/api-keys/route.ts
+++ b/src/app/api/api-keys/route.ts
@@ -5,7 +5,7 @@ import { getEnv } from "@/lib/cloudflare";
import { getDb } from "@/db";
import { agentSendApprovals, apiKeys, mcpKeyMailboxes } from "@/db/schema";
import { requireUser } from "@/lib/auth/cookies";
-import { generateApiKey, parseScopes, scopesToJson } from "@/lib/api-keys";
+import { generateApiKey, generateAppPassword, parseScopes, scopesToJson } from "@/lib/api-keys";
import { API_KEY_SCOPES } from "@/lib/api/scopes";
import { newId } from "@/lib/ids";
import { ADMIN_API_KEY_SCOPES } from "@/lib/api/scopes";
@@ -49,7 +49,8 @@ export async function POST(request: Request) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
}
- const { fullKey, prefix, hash } = generateApiKey();
+ const isAppPassword = parsed.data.scopes.length === 1 && parsed.data.scopes[0] === "jmap";
+ const { fullKey, prefix, hash } = isAppPassword ? generateAppPassword() : generateApiKey();
const db = getDb(env);
const mailboxIds = [...new Set(parsed.data.mailboxIds)];
if (!mailboxIds.length && parsed.data.scopes.some((scope) => !scope.startsWith("calendar:"))) return NextResponse.json({ error: "Choose a mailbox for mail permissions" }, { status: 400 });
diff --git a/src/components/settings/email-clients-settings.tsx b/src/components/settings/email-clients-settings.tsx
index 508ef8c..5fc37ef 100644
--- a/src/components/settings/email-clients-settings.tsx
+++ b/src/components/settings/email-clients-settings.tsx
@@ -1,6 +1,7 @@
"use client";
-import { useState } from "react";
+import { useEffect, useState } from "react";
+import QRCode from "qrcode";
import Link from "next/link";
import { Copy, KeyRound } from "lucide-react";
import { useLanguage } from "@/components/language-provider";
@@ -10,6 +11,7 @@ import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { createJmapApiKey } from "./utils";
+import { buildSignInQrPayload } from "./sign-in-qr-utils";
/** Upper bound `POST /api/api-keys` places on `mailboxIds`. */
const MAX_KEY_MAILBOXES = 30;
@@ -30,17 +32,37 @@ export function EmailClientsSettings() {
const [chosenMailboxIds, setChosenMailboxIds] = useState<string[] | null>(null);
const mailboxIds = chosenMailboxIds ?? (mailboxes.length <= MAX_KEY_MAILBOXES ? mailboxes.map((mailbox) => mailbox.id) : [selectedMailbox?.id ?? mailboxes[0]?.id].filter((id): id is string => !!id));
const [key, setKey] = useState<string | null>(null);
+ const [username, setUsername] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [copied, setCopied] = useState<string | null>(null);
+ const [qr, setQr] = useState<string | null>(null);
const server = typeof window !== "undefined" ? window.location.origin : "";
+ // The mobile app scans this to fill in the sign-in form; it carries the key, so it is
+ // rendered in the browser and never leaves the page.
+ useEffect(() => {
+ if (!key) {
+ setQr(null);
+ return;
+ }
+ let cancelled = false;
+ QRCode.toDataURL(buildSignInQrPayload({ server, email: username, key }), { margin: 1, width: 240, errorCorrectionLevel: "M" })
+ .then((url) => { if (!cancelled) setQr(url); })
+ .catch(() => { if (!cancelled) setQr(null); });
+ return () => { cancelled = true; };
+ }, [key, server, username]);
+
async function submit(event: React.FormEvent) {
event.preventDefault();
setBusy(true);
setError(null);
try {
- setKey(await createJmapApiKey(name.trim() || t("emailClients.defaultName"), mailboxIds));
+ const created = await createJmapApiKey(name.trim() || t("emailClients.defaultName"), mailboxIds);
+ // The server ignores the username, but mail apps want an email address there.
+ const first = mailboxes.find((mailbox) => mailbox.id === mailboxIds[0]);
+ setUsername(first ? `${first.localPart}@${first.hostname}` : "");
+ setKey(created);
setName("");
} catch (err) {
setError(err instanceof Error ? err.message : t("emailClients.createFailed"));
@@ -61,7 +83,7 @@ export function EmailClientsSettings() {
{key ? (
<div className="space-y-3 rounded-2xl bg-neutral-50 p-4">
<Field label={t("emailClients.server")} value={server} onCopy={copy} copied={copied} />
- <Field label={t("emailClients.username")} value={t("emailClients.anyValue")} onCopy={copy} copied={copied} />
+ <Field label={t("emailClients.username")} value={username || t("emailClients.anyValue")} onCopy={copy} copied={copied} />
<Field label={t("emailClients.passwordApiKey")} value={key} onCopy={copy} copied={copied} mono />
<p className="text-xs text-neutral-500">
{t("emailClients.shownOnce", { link: "\u0001", url: "\u0002" }).split(/(\u0001|\u0002)/).map((part, index) => part === "\u0001" ? <Link key={index} href="/settings/api-keys" className="text-blue-700 underline">{t("settings.nav.apiKeys")}</Link> : part === "\u0002" ? <code key={index}>{server}/.well-known/jmap</code> : part)}
diff --git a/src/components/settings/sign-in-qr-utils.ts b/src/components/settings/sign-in-qr-utils.ts
new file mode 100644
index 0000000..9774138
--- /dev/null
+++ b/src/components/settings/sign-in-qr-utils.ts
@@ -0,0 +1,10 @@
+/**
+ * What the sign-in QR code encodes. The Mailflare mobile app scans it to fill in
+ * its sign-in form: `mailflare://signin?server=…&email=…&key=…`.
+ */
+export function buildSignInQrPayload({ server, email, key }: { server: string; email: string; key: string }): string {
+ const params = new URLSearchParams({ server });
+ if (email) params.set("email", email);
+ params.set("key", key);
+ return `mailflare://signin?${params.toString()}`;
+}
diff --git a/src/lib/api-keys.ts b/src/lib/api-keys.ts
index f0d0fb1..961d8ea 100644
--- a/src/lib/api-keys.ts
+++ b/src/lib/api-keys.ts
@@ -1,4 +1,5 @@
import bcrypt from "bcryptjs";
+import { customAlphabet } from "nanoid";
import { newId } from "@/lib/ids";
const KEY_PREFIX = "ep_";
@@ -11,6 +12,21 @@ export function generateApiKey(): { fullKey: string; prefix: string; hash: strin
return { fullKey, prefix, hash };
}
+const APP_PASSWORD_LENGTH = 16;
+const APP_PASSWORD_PREFIX_LENGTH = 6;
+const generateAppPasswordSecret = customAlphabet("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", APP_PASSWORD_LENGTH);
+
+/** Stored lookup prefix for a presented key: short app passwords keep fewer plaintext characters. */
+export function apiKeyLookupPrefix(key: string): string {
+ return key.slice(0, key.length <= APP_PASSWORD_LENGTH ? APP_PASSWORD_PREFIX_LENGTH : 12);
+}
+
+/** 16-character password for mail apps. Older, longer `ep_` keys keep working. */
+export function generateAppPassword(): { fullKey: string; prefix: string; hash: string } {
+ const fullKey = generateAppPasswordSecret();
+ return { fullKey, prefix: apiKeyLookupPrefix(fullKey), hash: bcrypt.hashSync(fullKey, 10) };
+}
+
export function verifyApiKey(fullKey: string, hash: string): boolean {
return bcrypt.compareSync(fullKey, hash);
}
diff --git a/src/lib/api/key-auth.ts b/src/lib/api/key-auth.ts
index 8b4aab0..d0ca2ad 100644
--- a/src/lib/api/key-auth.ts
+++ b/src/lib/api/key-auth.ts
@@ -1,7 +1,7 @@
import { and, eq, lt, or, isNull } from "drizzle-orm";
import { getDb } from "@/db";
import { apiKeys, mcpKeyMailboxes, users } from "@/db/schema";
-import { parseScopes, verifyApiKey } from "@/lib/api-keys";
+import { apiKeyLookupPrefix, parseScopes, verifyApiKey } from "@/lib/api-keys";
import type { ApiAuthResult } from "@/lib/api/key-auth-types";
import { ADMIN_API_KEY_SCOPES } from "@/lib/api/scopes";
@@ -16,7 +16,7 @@ const ADMIN_SCOPES = new Set<string>(ADMIN_API_KEY_SCOPES);
export async function authenticateApiKeyValue(env: CloudflareEnv, key: string): Promise<ApiAuthResult | null> {
const trimmed = key.trim();
if (!trimmed) return null;
- const prefix = trimmed.slice(0, 12);
+ const prefix = apiKeyLookupPrefix(trimmed);
const db = getDb(env);
const candidates = await db.select().from(apiKeys).where(eq(apiKeys.prefix, prefix));
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
index f8985bb..40dd59e 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -563,11 +563,13 @@
"common.copyLabel": "Copy {label}",
"emailClients.defaultName": "Mail app",
"emailClients.createFailed": "Could not create a key",
- "emailClients.description": "App Password for email clients that support JMAP. Point the app at this server and sign in with your email address and an API key as the password.",
+ "emailClients.description": "App Password for email clients that support JMAP. Point the app at this server and sign in with your email address and the app password.",
"emailClients.server": "Server",
"emailClients.username": "Username",
"emailClients.anyValue": "any value",
- "emailClients.passwordApiKey": "Password (API key)",
+ "emailClients.passwordApiKey": "Password",
+ "emailClients.qrAlt": "QR code for signing in to the Mailflare mobile app",
+ "emailClients.qrHint": "Scan with the Mailflare mobile app to sign in. Anyone who scans this can use the key.",
"emailClients.shownOnce": "This key is shown once. You can revoke it in {link}. Session discovery is at {url}.",
"emailClients.deviceName": "Device or app name",
"emailClients.devicePlaceholder": "Phone",