🛡️ Supabase Auth 電郵閘道
為 Supabase Auth 電郵加入 寄送前閘道檢查
檢查地址格式並查詢收件者網域 MX。離線 MIT 授權靜態一次性網域清單(明確加入 tempmail.com)中的完整/子網域比對、受限網域,以及與現有收件者網域威脅特徵的比對會被硬性封鎖。MX 查詢失敗和垃圾郵件陷阱/信譽啟發式 HIGH 警告只會提示並放行;不會進行即時陷阱查詢。
電郵驗證 · 每月 100 次免費請求(驗證與寄送共用)· 毋須信用卡
身份驗證電郵 / 受控寄送
01 / 故障情況
格式正確的地址仍可能無法投遞。
Supabase Auth 會觸發電郵寄送。SentriSend 會檢查地址格式並查詢收件者網域 MX。MX 缺失、無效或暫時無法查詢時只會提示並放行,不會驗證郵箱是否存在。離線 MIT 授權靜態一次性網域清單(明確加入 tempmail.com)中的完整/子網域比對、受限網域,以及與現有收件者網域威脅特徵的比對會被硬性封鎖。垃圾郵件陷阱/信譽啟發式 HIGH 警告只會提示並放行;不會進行即時陷阱查詢或探測 SMTP 收件者。實際投遞情況請在服務商查看。
- 檢查地址格式並查詢收件者網域 MX(不會驗證郵箱)。
- 硬性封鎖離線一次性網域清單(明確加入 tempmail.com)中的完整/子網域比對、受限網域,以及與現有收件者網域威脅特徵的比對。
- 垃圾郵件陷阱/信譽啟發式 HIGH 警告會放行;不會進行即時陷阱查詢或探測 SMTP 收件者。
02 / 整合
驗證掛鈎簽署,檢查收件者,只傳送一次。
這個 Next.js 電郵傳送掛鈎先用 standardwebhooks 驗證 Supabase 原始請求的簽署,再呼叫 POST /api/v1/validate。AbortSignal 限制驗證等候時間,但不保證回應時間。驗證 API 會區分即棄網域、不存在的網域,以及既沒有 MX 亦沒有可用 A 紀錄的網域。A 紀錄後備路徑只會檢查 DNS;Null MX(明確宣告不接收電郵)會被拒絕,暫時性 DNS 故障則以 DNS_INCONCLUSIVE 及 MEDIUM 風險放行。掛鈎只會在明確的驗證回應中 allowed === false 時拒絕;輸入錯誤、配額耗盡、伺服器錯誤、無效 JSON 及逾時均繼續交由電郵服務商傳送。服務商會傳送包含 token_hash 連結、token 驗證碼或兩者的電郵,不會探測 SMTP 伺服器或郵箱。
standardwebhooks,並將此路由設定為 Supabase Send Email Hook。在伺服器端設定 SEND_EMAIL_HOOK_SECRET、SENTRISEND_API_KEY 及 RESEND_API_KEY,設定連結所需的 NEXT_PUBLIC_SUPABASE_URL 與 NEXT_PUBLIC_SITE_URL。將範例寄件者改為已驗證的網域。秘密資料切勿使用 NEXT_PUBLIC_ 前綴。請啟用 Supabase 原生速率限制及 Cloudflare Turnstile。自動化測試使用模擬的 Hook 請求。此範例尚未在真實的 Supabase 專案中進行端到端驗證。// pages/api/auth/supabase-hook.ts
import type { NextApiRequest, NextApiResponse } from "next";
import { Webhook } from "standardwebhooks";
// Preserve the raw body for signature verification.
// App Router equivalent: await req.text().
export const config = { api: { bodyParser: false } };
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const SUBJECT_MAP: Record<string, string> = {
signup: "Verify your account",
recovery: "Reset your password",
magiclink: "Your magic login link",
reauthentication: "Confirm your identity",
};
const SUPPORTED_TYPES = new Set(Object.keys(SUBJECT_MAP));
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
if (req.method !== "POST") return res.status(405).end();
// Authenticate Supabase before any validation or email delivery.
let payload: any;
try {
const rawBody = (await getRawBody(req)).toString("utf8");
const secret = (process.env.SEND_EMAIL_HOOK_SECRET || "")
.replace(/^v1,whsec_/, "");
payload = new Webhook(secret).verify(
rawBody, req.headers as Record<string, string>,
);
} catch {
return res.status(401).json({
error: { http_code: 401, message: "Invalid webhook signature" },
});
}
const { user, email_data } = payload;
const email = user?.email;
const token = email_data?.token;
const tokenHash = email_data?.token_hash;
const redirectTo = email_data?.redirect_to
|| process.env.NEXT_PUBLIC_SITE_URL || "";
const type = email_data?.email_action_type || "signup";
if (typeof email !== "string"
|| !EMAIL_REGEX.test(email) || email.length > 254) {
return res.status(400).json({
error: { http_code: 400, message: "Invalid recipient address" },
});
}
if (!SUPPORTED_TYPES.has(type)) {
return res.status(400).json({
error: { http_code: 400, message: "Unsupported auth action type" },
});
}
// Validation only: delivery stays with your upstream provider.
// Enable Supabase native rate limits and Cloudflare Turnstile.
try {
const check = await fetch(
"https://sentrisend.com/api/v1/validate",
{
method: "POST",
signal: AbortSignal.timeout(600),
headers: {
Authorization: `Bearer ${process.env.SENTRISEND_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ email }),
},
);
// 429, 5xx, malformed JSON, and timeouts fail open.
// Only a validation response can intentionally reject the user.
if (check.ok || check.status === 400) {
const data = await check.json().catch(() => ({}));
if (data.allowed === false) {
return res.status(400).json({
error: {
http_code: 400,
message: "Unsupported or high-risk email address rejected.",
},
});
}
}
if (check.status === 401) {
console.error("[SentriSend] Invalid SENTRISEND_API_KEY");
}
} catch {
console.warn("[SentriSend] Validation unavailable; failing open");
}
try {
const result = await sendEmailViaProvider({
email, token, tokenHash, type, redirectTo,
subject: SUBJECT_MAP[type],
});
if (!result.ok) {
return res.status(502).json({
error: { http_code: 502, message: "Upstream delivery failed" },
});
}
// Supabase expects an empty JSON object on hook success.
return res.status(200).json({});
} catch {
return res.status(500).json({
error: { http_code: 500, message: "Internal delivery failure" },
});
}
}
function escapeHtml(value: string): string {
return value.replace(/[&<>"']/g, (char) => ({
"&": "&", "<": "<", ">": ">",
'"': """, "'": "'",
})[char]!);
}
async function sendEmailViaProvider({
email, token, tokenHash, type, redirectTo, subject,
}: any) {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || "";
let htmlContent = "";
if (typeof tokenHash === "string" && tokenHash) {
const params = new URLSearchParams({
token: tokenHash, type, redirect_to: redirectTo,
});
const verifyUrl = `${supabaseUrl}/auth/v1/verify?${params}`;
htmlContent += `<p><a href="${escapeHtml(verifyUrl)}">Click here to complete authentication</a></p>`;
}
if (typeof token === "string" && token) {
htmlContent += `<p>Or enter this verification code: <strong>${escapeHtml(token)}</strong></p>`;
}
if (!htmlContent) return { ok: false };
const response = await fetch("https://api.resend.com/emails", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.RESEND_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
from: "Your App <auth@yourdomain.com>",
to: email, subject, html: htmlContent,
}),
});
return { ok: response.ok };
}
async function getRawBody(req: NextApiRequest): Promise<Buffer> {
const chunks: Buffer[] = [];
for await (const chunk of req) {
chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
}
return Buffer.concat(chunks);
}03 / 開始防護
由真正的金鑰開始,毋須銷售洽談。
驗證你的電郵,並使用自己的身份驗證電郵流量測試閘道。
免費金鑰
產生免費 SentriSend API 金鑰
每個電郵地址只可領取一個免費金鑰。所有網域的 + 標籤均視為同一地址;只有 Gmail 及 Googlemail 的句點亦視為相同。
驗證電郵後即可領取金鑰。毋須信用卡。
使用上限
- 每月 100 次請求,驗證與寄送共用
- 每個 UTC 日最多寄送 10 封
- 免費金鑰只可寄送至金鑰擁有者本人已驗證的電郵地址。