🛡️ Supabase Auth 이메일 게이트웨이

Supabase Auth 이메일에 발송 전 게이트웨이 검사 추가

주소 형식과 수신자 도메인 MX를 검사합니다. tempmail.com을 명시적으로 추가한 오프라인 MIT 라이선스 정적 일회용 도메인 목록의 정확한/하위 도메인 일치, 제한 도메인, 기존 수신자 도메인 위협 시그니처와 일치하는 항목을 차단합니다. MX 조회 실패와 스팸 트랩/평판 휴리스틱 HIGH 경고는 통과하며 실시간 트랩 조회는 하지 않습니다.

이메일 인증 · 월 100건 무료 요청(검증과 발송에 공유) · 카드 불필요

delivery-path.trace사전 검사 활성화

인증 이메일 / 제어된 전송

01
Supabase Auth가입 · OTP · 계정 복구
02
SentriSend 사전 검사 게이트웨이수신자 검증 · 대기 시간 제한 · 장애 시 전송 계속
03
설정된 이메일 제공업체서명이 확인된 훅이 자체 제공업체를 통해 전송
✓Supabase Auth → SentriSend 사전 검사 게이트웨이 → 설정된 이메일 제공업체

01 / 문제가 발생하는 방식

형식이 올바른 주소도 배달되지 않을 수 있습니다.

Supabase Auth가 이메일 전송을 시작합니다. SentriSend는 주소 형식을 검사하고 수신자 도메인의 MX를 조회합니다. MX가 없거나 잘못되었거나 일시적으로 조회되지 않으면 경고만 남기고 통과하며 사서함 존재를 확인하지 않습니다. tempmail.com을 명시적으로 추가한 오프라인 MIT 라이선스 정적 일회용 도메인 목록의 정확한/하위 도메인 일치, 제한 도메인, 기존 수신자 도메인 위협 시그니처와 일치하는 항목은 차단합니다. 스팸 트랩/평판 휴리스틱 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을 활성화하세요. 자동화 테스트에서는 훅 요청을 시뮬레이션합니다. 이 예제는 실제 Supabase 프로젝트에서 엔드투엔드 검증을 거치지 않았습니다.
pages/api/auth/supabase-hook.ts
// 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) => ({
    "&": "&amp;", "<": "&lt;", ">": "&gt;",
    '"': "&quot;", "'": "&#39;",
  })[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건까지 발송
  • 무료 키는 소유자 본인의 인증된 이메일 주소로만 발송할 수 있습니다.

보안 확인 로딩 중…