Communitygithub.com

Pranith-Jain/dfir-threat-intel-platform

建立完整的等待名單系統,包含電子郵件擷取、重複檢測、透過 Resend 發送確認信、Supabase 儲存、管理員檢視以及可選的推薦追蹤功能。適用於產品發布、建立受眾或限制早期存取權限。

dfir-threat-intel-platform 是什麼?

此技能會自動在你的專案中建立一個功能完整的等待名單系統。它會先讀取你的 `package.json` 來偵測你使用的資料庫(如 Supabase、Prisma、Drizzle)和郵件服務(Resend),然後根據你的技術棧生成對應的資料庫 Schema、API 路由、前端元件以及確認信範本。 這個技能特別適合 Next.js 專案,因為它會在你的 `app` 目錄下建立必要的檔案,並與現有架構無縫整合。你只需要回答幾個簡單的問題,例如:想收集哪些使用者資訊(僅 Email 或 Email + 姓名)、是否需要推薦連結功能、以及是否發送確認信。 使用這個技能的好處是極大節省開發時間,避免從頭撰寫等待名單相關的所有程式碼。它會處理郵件重複檢測、Email 標準化(轉小寫)、佇列位置自動遞增、以及透過秘密標頭(`x-admin-secret`)保護的管理員 API 端點。整個流程從偵測專案、詢問使用者需求、建立 Schema、寫入 API 路由、產生前端表單到發送確認信,都能一氣呵成。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Pranith-Jain/dfir-threat-intel-platform/tree/HEAD/.agents/skills/waitlist

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

建立完整的等待名單系統 — 電子郵件擷取、儲存、確認信以及管理員檢視。會先讀取專案內容,然後與現有技術棧整合。

第一階段:偵測專案

cat package.json | grep -E "next|supabase|prisma|drizzle|resend"

檢查以下項目:

  • 資料庫:Supabase / Prisma / Drizzle / 原生 Postgres?
  • 郵件服務:是否已安裝 Resend?
  • 身分驗證:是否有任何 Auth 提供者?(管理員檢視需要)
  • 是否已有等待名單資料表? 在 Schema 檔案中搜尋 waitlist

第二階段:詢問使用者

我將為 [產品名稱] 建立等待名單。

快速決定:

1. 你想收集哪些資訊?
   a) 僅 Email(預設 — 轉換率最高)
   b) Email + 姓名
   c) Email + 姓名 + "你在做什麼?"(選填欄位)

2. 需要推薦追蹤嗎?
   a) 不需要 — 簡單的清單
   b) 需要 — 每個註冊者獲得一個唯一的推薦連結,並追蹤被推薦人數

3. 需要確認信嗎?
   a) 需要 — 透過 Resend 發送「你已在名單上」的郵件(預設)
   b) 不需要

4. 你已經有 Resend 和經過驗證的寄件網域嗎?(有 / 需要設定)

第三階段:資料庫 Schema

根據偵測到的資料庫進行調整。建立一個 waitlist 資料表:

Supabase / 原生 SQL:

create table public.waitlist (
  id uuid primary key default gen_random_uuid(),
  email text not null unique,
  name text,
  note text,                              -- 選填的「你在做什麼?」欄位
  referral_code text unique,              -- 他們的分享碼(如果啟用推薦功能)
  referred_by text references public.waitlist(referral_code),  -- 誰推薦他們來的
  referral_count integer default 0,       -- 他們推薦了多少人
  position integer,                       -- 佇列位置(由觸發器設定)
  confirmed_at timestamptz,               -- null = 未確認
  created_at timestamptz default now()
);

-- 插入時自動遞增位置
create or replace function set_waitlist_position()
returns trigger as $$
begin
  new.position = (select coalesce(max(position), 0) + 1 from public.waitlist);
  return new;
end;
$$ language plpgsql;

create trigger waitlist_position_trigger
  before insert on public.waitlist
  for each row execute function set_waitlist_position();

如果不需要推薦追蹤,請移除 referral_code、referred_by、referral_count。

Prisma:

model Waitlist {
  id           String    @id @default(cuid())
  email        String    @unique
  name         String?
  note         String?
  referralCode String?   @unique
  referredBy   String?
  referralCount Int      @default(0)
  position     Int
  confirmedAt  DateTime?
  createdAt    DateTime  @default(now())
}

第四階段:註冊 API 路由

// app/api/waitlist/route.ts
import { NextResponse } from 'next/server';

export async function POST(req: Request) {
  const { email, name, note, referredBy } = await req.json();

  // 驗證 Email
  if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    return NextResponse.json({ error: '需要有效的 Email' }, { status: 400 });
  }

  // 標準化
  const normalizedEmail = email.toLowerCase().trim();

  // 檢查重複
  const existing = await db.query.waitlist.findFirst({
    where: eq(waitlist.email, normalizedEmail),
  });

  if (existing) {
    // 回傳成功 — 不要告訴垃圾郵件發送者哪些 Email 已註冊
    return NextResponse.json({
      success: true,
      position: existing.position,
      alreadyRegistered: true,
    });
  }

  // 如果啟用推薦功能,產生推薦碼
  const referralCode = generateReferralCode(normalizedEmail); // 例如:Email 雜湊的前 8 個字元

  // 插入
  const entry = await db
    .insert(waitlistTable)
    .values({
      email: normalizedEmail,
      name: name?.trim() || null,
      note: note?.trim() || null,
      referralCode,
      referredBy: referredBy || null,
    })
    .returning();

  // 增加推薦者的計數
  if (referredBy) {
    await db
      .update(waitlistTable)
      .set({ referralCount: sql`referral_count + 1` })
      .where(eq(waitlistTable.referralCode, referredBy));
  }

  // 發送確認信(如果已設定 Resend)
  if (process.env.RESEND_API_KEY) {
    await sendWaitlistConfirmation({
      email: normalizedEmail,
      name: name || '使用者',
      position: entry[0].position,
      referralCode,
    });
  }

  return NextResponse.json({
    success: true,
    position: entry[0].position,
    referralCode,
  });
}

function generateReferralCode(email: string): string {
  const { createHash } = require('crypto');
  return createHash('sha256').update(email).digest('hex').slice(0, 8);
}

第五階段:確認信

// lib/emails/waitlist-confirmation.ts
import { Resend } from 'resend';

const resend = new Resend(process.env.RESEND_API_KEY);

export async function sendWaitlistConfirmation({
  email,
  name,
  position,
  referralCode,
}: {
  email: string;
  name: string;
  position: number;
  referralCode?: string;
}) {
  const referralUrl = referralCode ? `${process.env.NEXT_PUBLIC_APP_URL}/?ref=${referralCode}` : null;

  await resend.emails.send({
    from: `[產品名稱] <[email protected]>`,
    to: email,
    subject: `你是名單上的第 #${position} 位`,
    html: `
      <div style="font-family: sans-serif; max-width: 520px; margin: 0 auto; padding: 40px 20px; color: #111;">
        <p>嘿 ${name},</p>
        <p>你是名單上的第 <strong>#${position}</strong> 位。輪到你時,我們會與你聯繫。</p>
        ${
          referralUrl
            ? `
        <p style="margin-top: 24px;">
          往前移動 — 分享你的連結:<br>
          <a href="${referralUrl}" style="color: #000; font-weight: bold;">${referralUrl}</a>
        </p>
        `
            : ''
        }
        <p style="color: #666; font-size: 13px; margin-top: 40px;">— [你的名字]</p>
      </div>
    `,
  });
}

第六階段:註冊表單元件

// components/waitlist-form.tsx
'use client';
import { useState } from 'react';

export function WaitlistForm({ referralCode }: { referralCode?: string }) {
  const [email, setEmail] = useState('');
  const [state, setState] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [position, setPosition] = useState<number | null>(null);
  const [userReferralCode, setUserReferralCode] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setState('loading');

    const res = await fetch('/api/waitlist', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, referredBy: referralCode }),
    });

    const data = await res.json();

    if (data.success) {
      setState('success');
      setPosition(data.position);
      setUserReferralCode(data.referralCode);
    } else {
      setState('error');
    }
  }

  if (state === 'success') {
    return (
      <div>
        <p>你是名單上的第 #{position} 位。</p>
        {userReferralCode && (
          <p>
            分享你的連結來往前移動: <code>{`${window.location.origin}/?ref=${userReferralCode}`}</code>
          </p>
        )}
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="[email protected]"
        required
        disabled={state === 'loading'}
      />
      <button type="submit" disabled={state === 'loading'}>
        {state === 'loading' ? '加入中...' : '加入等待名單'}
      </button>
      {state === 'error' && <p>發生錯誤,請再試一次。</p>}
    </form>
  );
}

從頁面的 URL 參數中讀取推薦碼:

// app/page.tsx
export default function Page({ searchParams }: { searchParams: { ref?: string } }) {
  return <WaitlistForm referralCode={searchParams.ref} />;
}

第七階段:管理員檢視

一個需要秘密標頭的簡單路由 — 等待名單的管理員不需要完整的身分驗證:

// app/api/admin/waitlist/route.ts
export async function GET(req: Request) {
  if (req.headers.get('x-admin-secret') !== process.env.ADMIN_SECRET) {
    return Response.json({ error: '未經授權' }, { status: 401 });
  }

  const signups = await db.select().from(waitlistTable).orderBy(asc(waitlistTable.position));

  return Response.json({
    total: signups.length,
    signups,
  });
}

使用以下指令擷取資料:curl -H "x-admin-secret: $ADMIN_SECRET" https://yoursite.com/api/admin/waitlist

驗證

[ ] 重複的 Email 回傳成功並帶有 alreadyRegistered: true(不顯示錯誤,也不洩漏資訊)
[ ] Email 在儲存前標準化為小寫
[ ] 位置正確遞增 — 第一位註冊者是 #1
[ ] 確認信送達收件匣,而不是垃圾郵件
[ ] URL 中的推薦碼 (?ref=) 被擷取並儲存
[ ] 當被推薦者完成註冊時,推薦者的計數會增加
[ ] 管理員路由需要 x-admin-secret 標頭
[ ] ADMIN_SECRET 和 RESEND_API_KEY 存在於 .env.example 中
[ ] 提交時表單輸入框被停用
[ ] 成功狀態顯示位置和推薦連結

相關技能