🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Implement API key creation with plan-based rate limits
Bill Yangc3d95355225e
diff --git a/client/messages/cs.json b/client/messages/cs.jsonindex 556580882..4062cfbf4 100644--- a/client/messages/cs.json+++ b/client/messages/cs.json@@ -725,6 +725,7 @@"jSp63j": "API klíče","wnSZSp": "Vytvořit API klíč","u4673k": "Vygeneruj API klíče pro přístup k analytickým endpointům z tvých aplikací",+ "1fe3VI": "","AkVL9j": "Název API klíče","mRL9Vh": "Vytvářím...","jDvHYJ": "Tvé API klíče",diff --git a/client/messages/de.json b/client/messages/de.jsonindex f4b47f2d6..e09aff217 100644--- a/client/messages/de.json+++ b/client/messages/de.json@@ -195,8 +195,8 @@"Zx7WPP": "Alle Event-Reihen ausgeblendet","AKRVhS": "Klicken Sie auf ein Legendenelement, um es anzuzeigen","NuhCPH": "Erfahren Sie, wie Sie Events verfolgen",- "/aq5/F": "Keine benutzerdefinierten Events gefunden","ES6IYH": "Versuchen Sie einen anderen Zeitraum oder Filter",+ "/aq5/F": "Keine benutzerdefinierten Events gefunden","j7BiRg": "Kein Event ausgewählt.","kF9XUo": "Zeitstempel","EwRIOm": "Benutzer",@@ -251,8 +251,8 @@"tHKpoN": "Keine Sitzungen wurden vor Erreichen dieses Schritts im ausgewählten Zeitraum abgebrochen.","5elgIe": "Fehler:","0hujDo": "Trichteranalyse fehlgeschlagen",- "gUKiFL": "Konfigurieren Sie Ihre Trichterschritte","cSzyIV": "Trichter wird analysiert...",+ "gUKiFL": "Konfigurieren Sie Ihre Trichterschritte","XFyfI5": "Gesamtkonversion","AFl3K6": "Konversion vom vorherigen Schritt","s+vZVl": "Trichtervorschau",@@ -725,6 +725,7 @@"jSp63j": "API-Schlüssel","wnSZSp": "API-Schlüssel erstellen","u4673k": "Generieren Sie API-Schlüssel für den Zugriff auf Analyse-Endpunkte aus Ihren Anwendungen",+ "1fe3VI": "","AkVL9j": "API-Schlüsselname","mRL9Vh": "Wird erstellt...","jDvHYJ": "Ihre API-Schlüssel",@@ -850,8 +851,8 @@"EjE0iv": "Team erfolgreich erstellt","hfiE8k": "Team konnte nicht aktualisiert werden","DswPK3": "Team konnte nicht erstellt werden",- "97DGta": "Team erstellen","U01dmA": "Team bearbeiten",+ "97DGta": "Team erstellen","03IKqU": "Teamname, Mitglieder und Website-Zuweisungen aktualisieren.","Ps71bZ": "Erstellen Sie ein neues Team, um Websites zu gruppieren und den Mitgliederzugriff zu steuern.","k+kHlN": "Teamname",diff --git a/client/messages/en.json b/client/messages/en.jsonindex 401d3d468..5cdb20fec 100644--- a/client/messages/en.json+++ b/client/messages/en.json@@ -195,8 +195,8 @@"Zx7WPP": "All event series hidden","AKRVhS": "Click a legend item to show it","NuhCPH": "Learn how to track events",- "/aq5/F": "No custom events found","ES6IYH": "Try a different date range or filter",+ "/aq5/F": "No custom events found","j7BiRg": "No event selected.","kF9XUo": "Timestamp","EwRIOm": "User",@@ -251,8 +251,8 @@"tHKpoN": "No sessions dropped off before reaching this step in the selected time period.","5elgIe": "Error:","0hujDo": "Failed to analyze funnel",- "gUKiFL": "Configure your funnel steps","cSzyIV": "Analyzing funnel...",+ "gUKiFL": "Configure your funnel steps","XFyfI5": "Overall conversion","AFl3K6": "Conversion from previous step","s+vZVl": "Funnel Preview",@@ -725,6 +725,7 @@"jSp63j": "API Keys","wnSZSp": "Create API Key","u4673k": "Generate API keys to access analytics endpoints from your applications",+ "1fe3VI": "API keys are available on Standard and Pro plans.","AkVL9j": "API Key Name","mRL9Vh": "Creating...","jDvHYJ": "Your API Keys",@@ -850,8 +851,8 @@"EjE0iv": "Team created successfully","hfiE8k": "Failed to update team","DswPK3": "Failed to create team",- "97DGta": "Create Team","U01dmA": "Edit Team",+ "97DGta": "Create Team","03IKqU": "Update team name, members, and site assignments.","Ps71bZ": "Create a new team to group sites and control member access.","k+kHlN": "Team Name",diff --git a/client/messages/es.json b/client/messages/es.jsonindex 7af387c5d..52b5e5d65 100644--- a/client/messages/es.json+++ b/client/messages/es.json@@ -195,8 +195,8 @@"Zx7WPP": "Todas las series de eventos ocultas","AKRVhS": "Haz clic en un elemento de la leyenda para mostrarlo","NuhCPH": "Aprende cómo rastrear eventos",- "/aq5/F": "No se encontraron eventos personalizados","ES6IYH": "Prueba un rango de fechas o filtro diferente",+ "/aq5/F": "No se encontraron eventos personalizados","j7BiRg": "Ningún evento seleccionado.","kF9XUo": "Marca de tiempo","EwRIOm": "Usuario",@@ -251,8 +251,8 @@"tHKpoN": "Ninguna sesión abandonó antes de alcanzar este paso en el periodo seleccionado.","5elgIe": "Error:","0hujDo": "Error al analizar el embudo",- "gUKiFL": "Configura los pasos de tu embudo","cSzyIV": "Analizando embudo...",+ "gUKiFL": "Configura los pasos de tu embudo","XFyfI5": "Conversión general","AFl3K6": "Conversión desde el paso anterior","s+vZVl": "Vista previa del embudo",@@ -725,6 +725,7 @@"jSp63j": "Claves de API","wnSZSp": "Crear clave de API","u4673k": "Genera claves de API para acceder a los endpoints de analíticas desde tus aplicaciones",+ "1fe3VI": "","AkVL9j": "Nombre de la clave de API","mRL9Vh": "Creando...","jDvHYJ": "Tus claves de API",@@ -850,8 +851,8 @@"EjE0iv": "Equipo creado correctamente","hfiE8k": "Error al actualizar el equipo","DswPK3": "Error al crear el equipo",- "97DGta": "Crear equipo","U01dmA": "Editar equipo",+ "97DGta": "Crear equipo","03IKqU": "Actualiza el nombre del equipo, los miembros y las asignaciones de sitios.","Ps71bZ": "Crea un nuevo equipo para agrupar sitios y controlar el acceso de los miembros.","k+kHlN": "Nombre del equipo",diff --git a/client/messages/fr.json b/client/messages/fr.jsonindex 3671f7d5f..64791d340 100644--- a/client/messages/fr.json+++ b/client/messages/fr.json@@ -195,8 +195,8 @@"Zx7WPP": "Toutes les séries d'événements masquées","AKRVhS": "Cliquez sur un élément de la légende pour l'afficher","NuhCPH": "Apprenez à suivre les événements",- "/aq5/F": "Aucun événement personnalisé trouvé","ES6IYH": "Essayez une autre période ou un autre filtre",+ "/aq5/F": "Aucun événement personnalisé trouvé","j7BiRg": "Aucun événement sélectionné.","kF9XUo": "Horodatage","EwRIOm": "Utilisateur",@@ -251,8 +251,8 @@"tHKpoN": "Aucune session n'a abandonné avant d'atteindre cette étape dans la période sélectionnée.","5elgIe": "Erreur :","0hujDo": "Échec de l'analyse de l'entonnoir",- "gUKiFL": "Configurez les étapes de votre entonnoir","cSzyIV": "Analyse de l'entonnoir en cours...",+ "gUKiFL": "Configurez les étapes de votre entonnoir","XFyfI5": "Conversion globale","AFl3K6": "Conversion depuis l'étape précédente","s+vZVl": "Aperçu de l'entonnoir",@@ -725,6 +725,7 @@"jSp63j": "Clés API","wnSZSp": "Créer une clé API","u4673k": "Générez des clés API pour accéder aux points d'accès analytiques depuis vos applications",+ "1fe3VI": "","AkVL9j": "Nom de la clé API","mRL9Vh": "Création en cours...","jDvHYJ": "Vos clés API",@@ -850,8 +851,8 @@"EjE0iv": "Équipe créée avec succès","hfiE8k": "Échec de la mise à jour de l'équipe","DswPK3": "Échec de la création de l'équipe",- "97DGta": "Créer une équipe","U01dmA": "Modifier l'équipe",+ "97DGta": "Créer une équipe","03IKqU": "Mettre à jour le nom de l'équipe, les membres et les affectations de sites.","Ps71bZ": "Créez une nouvelle équipe pour regrouper les sites et contrôler l'accès des membres.","k+kHlN": "Nom de l'équipe",diff --git a/client/messages/it.json b/client/messages/it.jsonindex c26bd786d..751ceec19 100644--- a/client/messages/it.json+++ b/client/messages/it.json@@ -195,8 +195,8 @@"Zx7WPP": "Tutte le serie di eventi nascoste","AKRVhS": "Clicca un elemento della legenda per mostrarlo","NuhCPH": "Scopri come tracciare gli eventi",- "/aq5/F": "Nessun evento personalizzato trovato","ES6IYH": "Prova un intervallo di date diverso o un filtro",+ "/aq5/F": "Nessun evento personalizzato trovato","j7BiRg": "Nessun evento selezionato.","kF9XUo": "Timestamp","EwRIOm": "Utente",@@ -251,8 +251,8 @@"tHKpoN": "Nessuna sessione è stata abbandonata prima di raggiungere questo passaggio nel periodo di tempo selezionato.","5elgIe": "Errore:","0hujDo": "Impossibile analizzare il funnel",- "gUKiFL": "Configura i passaggi del tuo funnel","cSzyIV": "Analisi del funnel in corso...",+ "gUKiFL": "Configura i passaggi del tuo funnel","XFyfI5": "Conversione complessiva","AFl3K6": "Conversione dal passaggio precedente","s+vZVl": "Anteprima Funnel",@@ -725,6 +725,7 @@"jSp63j": "Chiavi API","wnSZSp": "Crea Chiave API","u4673k": "Genera chiavi API per accedere agli endpoint di analisi dalle tue applicazioni",+ "1fe3VI": "","AkVL9j": "Nome Chiave API","mRL9Vh": "Creazione in corso...","jDvHYJ": "Le tue Chiavi API",@@ -850,8 +851,8 @@"EjE0iv": "Team creato con successo","hfiE8k": "Impossibile aggiornare il team","DswPK3": "Impossibile creare il team",- "97DGta": "Crea team","U01dmA": "Modifica team",+ "97DGta": "Crea team","03IKqU": "Aggiorna il nome del team, i membri e le assegnazioni dei siti.","Ps71bZ": "Crea un nuovo team per raggruppare i siti e controllare l'accesso dei membri.","k+kHlN": "Nome del team",diff --git a/client/messages/ja.json b/client/messages/ja.jsonindex 4e4f7f806..ee45cda44 100644--- a/client/messages/ja.json+++ b/client/messages/ja.json@@ -195,8 +195,8 @@"Zx7WPP": "すべてのイベント系列が非表示です","AKRVhS": "凡例の項目をクリックして表示します","NuhCPH": "イベントのトラッキング方法を学ぶ",- "/aq5/F": "カスタムイベントが見つかりません","ES6IYH": "別の日付範囲またはフィルターをお試しください",+ "/aq5/F": "カスタムイベントが見つかりません","j7BiRg": "イベントが選択されていません。","kF9XUo": "タイムスタンプ","EwRIOm": "ユーザー",@@ -251,8 +251,8 @@"tHKpoN": "選択した期間にこのステップの前に離脱したセッションはありません。","5elgIe": "エラー:","0hujDo": "ファネルの分析に失敗しました",- "gUKiFL": "ファネルのステップを設定","cSzyIV": "ファネルを分析中...",+ "gUKiFL": "ファネルのステップを設定","XFyfI5": "全体のコンバージョン","AFl3K6": "前のステップからのコンバージョン","s+vZVl": "ファネルプレビュー",@@ -725,6 +725,7 @@"jSp63j": "APIキー","wnSZSp": "APIキーを作成","u4673k": "アプリケーションからアナリティクスエンドポイントにアクセスするためのAPIキーを生成",+ "1fe3VI": "","AkVL9j": "APIキー名","mRL9Vh": "作成中...","jDvHYJ": "あなたのAPIキー",@@ -850,8 +851,8 @@"EjE0iv": "チームが正常に作成されました","hfiE8k": "チームの更新に失敗しました","DswPK3": "チームの作成に失敗しました",- "97DGta": "チームを作成","U01dmA": "チームを編集",+ "97DGta": "チームを作成","03IKqU": "チーム名、メンバー、サイト割り当てを更新します。","Ps71bZ": "サイトをグループ化してメンバーアクセスを制御する新しいチームを作成します。","k+kHlN": "チーム名",diff --git a/client/messages/ko.json b/client/messages/ko.jsonindex ebe3e3a27..db5313863 100644--- a/client/messages/ko.json+++ b/client/messages/ko.json@@ -195,8 +195,8 @@"Zx7WPP": "모든 이벤트 시리즈 숨김","AKRVhS": "범례 항목을 클릭하여 표시","NuhCPH": "이벤트 추적 방법 알아보기",- "/aq5/F": "사용자 정의 이벤트를 찾을 수 없음","ES6IYH": "다른 날짜 범위 또는 필터를 시도하세요",+ "/aq5/F": "사용자 정의 이벤트를 찾을 수 없음","j7BiRg": "이벤트가 선택되지 않았습니다.","kF9XUo": "타임스탬프","EwRIOm": "사용자",@@ -251,8 +251,8 @@"tHKpoN": "선택한 기간에 이 단계 전에 이탈한 세션이 없습니다.","5elgIe": "오류:","0hujDo": "퍼널 분석 실패",- "gUKiFL": "퍼널 단계를 구성하세요","cSzyIV": "퍼널 분석 중...",+ "gUKiFL": "퍼널 단계를 구성하세요","XFyfI5": "전체 전환율","AFl3K6": "이전 단계 대비 전환율","s+vZVl": "퍼널 미리보기",@@ -725,6 +725,7 @@"jSp63j": "API 키","wnSZSp": "API 키 생성","u4673k": "애플리케이션에서 분석 엔드포인트에 접근하기 위한 API 키 생성",+ "1fe3VI": "","AkVL9j": "API 키 이름","mRL9Vh": "생성 중...","jDvHYJ": "내 API 키",@@ -850,8 +851,8 @@"EjE0iv": "팀이 성공적으로 생성되었습니다","hfiE8k": "팀 업데이트에 실패했습니다","DswPK3": "팀 생성에 실패했습니다",- "97DGta": "팀 생성","U01dmA": "팀 편집",+ "97DGta": "팀 생성","03IKqU": "팀 이름, 멤버 및 사이트 할당을 업데이트합니다.","Ps71bZ": "사이트를 그룹화하고 멤버 액세스를 제어하는 새 팀을 만듭니다.","k+kHlN": "팀 이름",diff --git a/client/messages/pl.json b/client/messages/pl.jsonindex 8a9fed45d..96000898a 100644--- a/client/messages/pl.json+++ b/client/messages/pl.json@@ -195,8 +195,8 @@"Zx7WPP": "Wszystkie serie zdarzeń ukryte","AKRVhS": "Kliknij element legendy, aby go wyświetlić","NuhCPH": "Dowiedz się, jak śledzić zdarzenia",- "/aq5/F": "Nie znaleziono niestandardowych zdarzeń","ES6IYH": "Spróbuj innego zakresu dat lub filtra",+ "/aq5/F": "Nie znaleziono niestandardowych zdarzeń","j7BiRg": "Nie wybrano zdarzenia.","kF9XUo": "Znacznik czasu","EwRIOm": "Użytkownik",@@ -251,8 +251,8 @@"tHKpoN": "Żadna sesja nie porzuciła przed dotarciem do tego kroku w wybranym okresie.","5elgIe": "Błąd:","0hujDo": "Nie udało się przeanalizować lejka",- "gUKiFL": "Skonfiguruj kroki lejka","cSzyIV": "Analizowanie lejka...",+ "gUKiFL": "Skonfiguruj kroki lejka","XFyfI5": "Ogólna konwersja","AFl3K6": "Konwersja z poprzedniego kroku","s+vZVl": "Podgląd lejka",@@ -725,6 +725,7 @@"jSp63j": "Klucze API","wnSZSp": "Utwórz klucz API","u4673k": "Generuj klucze API, aby uzyskać dostęp do endpointów analitycznych z Twoich aplikacji",+ "1fe3VI": "","AkVL9j": "Nazwa klucza API","mRL9Vh": "Tworzenie...","jDvHYJ": "Twoje klucze API",@@ -850,8 +851,8 @@"EjE0iv": "Zespół został pomyślnie utworzony","hfiE8k": "Nie udało się zaktualizować zespołu","DswPK3": "Nie udało się utworzyć zespołu",- "97DGta": "Utwórz zespół","U01dmA": "Edytuj zespół",+ "97DGta": "Utwórz zespół","03IKqU": "Zaktualizuj nazwę zespołu, członków i przypisania witryn.","Ps71bZ": "Utwórz nowy zespół, aby grupować witryny i kontrolować dostęp członków.","k+kHlN": "Nazwa zespołu",diff --git a/client/messages/pt.json b/client/messages/pt.jsonindex 9abc9d5c0..8d1586c13 100644--- a/client/messages/pt.json+++ b/client/messages/pt.json@@ -195,8 +195,8 @@"Zx7WPP": "Todas as séries de eventos ocultas","AKRVhS": "Clique em um item da legenda para exibi-lo","NuhCPH": "Saiba como rastrear eventos",- "/aq5/F": "Nenhum evento personalizado encontrado","ES6IYH": "Tente um intervalo de datas diferente ou filtro",+ "/aq5/F": "Nenhum evento personalizado encontrado","j7BiRg": "Nenhum evento selecionado.","kF9XUo": "Data/Hora","EwRIOm": "Usuário",@@ -251,8 +251,8 @@"tHKpoN": "Nenhuma sessão abandonou antes de alcançar esta etapa no período selecionado.","5elgIe": "Erro:","0hujDo": "Falha ao analisar funil",- "gUKiFL": "Configure as etapas do seu funil","cSzyIV": "Analisando funil...",+ "gUKiFL": "Configure as etapas do seu funil","XFyfI5": "Conversão geral","AFl3K6": "Conversão da etapa anterior","s+vZVl": "Pré-visualização do Funil",@@ -725,6 +725,7 @@"jSp63j": "Chaves de API","wnSZSp": "Criar Chave de API","u4673k": "Gere chaves de API para acessar endpoints de análise das suas aplicações",+ "1fe3VI": "","AkVL9j": "Nome da Chave de API","mRL9Vh": "Criando...","jDvHYJ": "Suas Chaves de API",@@ -850,8 +851,8 @@"EjE0iv": "Time criado com sucesso","hfiE8k": "Falha ao atualizar time","DswPK3": "Falha ao criar time",- "97DGta": "Criar time","U01dmA": "Editar time",+ "97DGta": "Criar time","03IKqU": "Atualize o nome do time, membros e atribuições de sites.","Ps71bZ": "Crie um novo time para agrupar sites e controlar o acesso dos membros.","k+kHlN": "Nome do time",diff --git a/client/messages/zh.json b/client/messages/zh.jsonindex bbafeda6c..f81a8f448 100644--- a/client/messages/zh.json+++ b/client/messages/zh.json@@ -195,8 +195,8 @@"Zx7WPP": "所有事件系列已隐藏","AKRVhS": "点击图例项以显示它","NuhCPH": "了解如何追踪事件",- "/aq5/F": "未找到自定义事件","ES6IYH": "尝试不同的日期范围或过滤器",+ "/aq5/F": "未找到自定义事件","j7BiRg": "未选择事件。","kF9XUo": "时间戳","EwRIOm": "用户",@@ -251,8 +251,8 @@"tHKpoN": "在选定的时间段内,没有会话在到达此步骤之前流失。","5elgIe": "错误:","0hujDo": "分析漏斗失败",- "gUKiFL": "配置您的漏斗步骤","cSzyIV": "正在分析漏斗...",+ "gUKiFL": "配置您的漏斗步骤","XFyfI5": "整体转化率","AFl3K6": "较上一步的转化率","s+vZVl": "漏斗预览",@@ -725,6 +725,7 @@"jSp63j": "API 密钥","wnSZSp": "创建 API 密钥","u4673k": "生成 API 密钥以便从您的应用程序访问分析端点",+ "1fe3VI": "","AkVL9j": "API 密钥名称","mRL9Vh": "正在创建...","jDvHYJ": "您的 API 密钥",@@ -850,8 +851,8 @@"EjE0iv": "团队创建成功","hfiE8k": "更新团队失败","DswPK3": "创建团队失败",- "97DGta": "创建团队","U01dmA": "编辑团队",+ "97DGta": "创建团队","03IKqU": "更新团队名称、成员和站点分配。","Ps71bZ": "创建新团队以对站点进行分组并控制成员访问权限。","k+kHlN": "团队名称",diff --git a/client/src/api/admin/hooks/useUserApiKeys.ts b/client/src/api/admin/hooks/useUserApiKeys.tsindex e42224b6d..249fe397b 100644--- a/client/src/api/admin/hooks/useUserApiKeys.ts+++ b/client/src/api/admin/hooks/useUserApiKeys.ts@@ -1,5 +1,6 @@import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { authClient } from "../../../lib/auth";+import { authedFetch } from "../../utils";// List all API keys for the current userexport const useListApiKeys = () => {@@ -15,20 +16,16 @@ export const useListApiKeys = () => {});};-// Create a new API key+// Create a new API key (uses custom endpoint for plan-based rate limits)export const useCreateApiKey = () => {const queryClient = useQueryClient();return useMutation({mutationFn: async (data: { name: string; expiresIn?: number }) => {- const response = await authClient.apiKey.create({- name: data.name,- expiresIn: data.expiresIn,+ return authedFetch<{ key: string; id: string }>("/user/api-keys", undefined, {+ method: "POST",+ data,});- if (response.error) {- throw new Error(response.error.message);- }- return response.data;},onSuccess: () => {queryClient.invalidateQueries({ queryKey: ["userApiKeys"] });diff --git a/client/src/app/settings/account/components/ApiKeyManager.tsx b/client/src/app/settings/account/components/ApiKeyManager.tsxindex 8fc58b59c..bc25f0132 100644--- a/client/src/app/settings/account/components/ApiKeyManager.tsx+++ b/client/src/app/settings/account/components/ApiKeyManager.tsx@@ -11,6 +11,8 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from ".import { Label } from "../../../../components/ui/label";import { DateTime } from "luxon";import { useListApiKeys, useCreateApiKey, useDeleteApiKey } from "../../../../api/admin/hooks/useUserApiKeys";+import { useStripeSubscription } from "../../../../lib/subscription/useStripeSubscription";+import { IS_CLOUD } from "../../../../lib/const";export function ApiKeyManager() {const t = useExtracted();@@ -18,8 +20,13 @@ export function ApiKeyManager() {const [showApiKeyDialog, setShowApiKeyDialog] = useState(false);const [createdApiKey, setCreatedApiKey] = useState<string | null>(null);+ const { data: subscription } = useStripeSubscription();const { data: apiKeysData, isLoading: isLoadingApiKeys, isError, error, refetch } = useListApiKeys();+ const planName = subscription?.planName || "free";+ const isFreePlan = planName === "free" || planName.includes("basic");+ const isPlanGated = IS_CLOUD && isFreePlan;+const apiKeys = apiKeysData?.apiKeys;const createApiKey = useCreateApiKey();const deleteApiKey = useDeleteApiKey();@@ -73,27 +80,35 @@ export function ApiKeyManager() {<p className="text-xs text-neutral-500">{t("Generate API keys to access analytics endpoints from your applications")}</p>- <div className="flex space-x-2">- <Input- id="apiKeyName"- value={apiKeyName}- onChange={({ target }) => setApiKeyName(target.value)}- placeholder={t("API Key Name")}- onKeyDown={e => {- if (e.key === "Enter") {- e.preventDefault();- handleCreateApiKey();- }- }}- />- <Button- variant="outline"- onClick={handleCreateApiKey}- disabled={createApiKey.isPending || !apiKeyName.trim()}- >- {createApiKey.isPending ? t("Creating...") : t("Create")}- </Button>- </div>+ {isPlanGated ? (+ <div className="rounded-lg bg-neutral-50 dark:bg-neutral-900 p-3 border border-neutral-200 dark:border-neutral-800">+ <p className="text-xs text-neutral-600 dark:text-neutral-400">+ {t("API keys are available on Standard and Pro plans.")}+ </p>+ </div>+ ) : (+ <div className="flex space-x-2">+ <Input+ id="apiKeyName"+ value={apiKeyName}+ onChange={({ target }) => setApiKeyName(target.value)}+ placeholder={t("API Key Name")}+ onKeyDown={e => {+ if (e.key === "Enter") {+ e.preventDefault();+ handleCreateApiKey();+ }+ }}+ />+ <Button+ variant="outline"+ onClick={handleCreateApiKey}+ disabled={createApiKey.isPending || !apiKeyName.trim()}+ >+ {createApiKey.isPending ? t("Creating...") : t("Create")}+ </Button>+ </div>+ )}</div><div className="space-y-2">diff --git a/server/src/api/user/createApiKey.ts b/server/src/api/user/createApiKey.tsnew file mode 100644index 000000000..bd9a24102--- /dev/null+++ b/server/src/api/user/createApiKey.ts@@ -0,0 +1,69 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { auth } from "../../lib/auth.js";+import { getSessionFromReq } from "../../lib/auth-utils.js";+import { getSubscriptionInner } from "../stripe/getSubscription.js";+import {+ API_RATE_LIMIT_WINDOW,+ IS_CLOUD,+ PRO_API_RATE_LIMIT,+ STANDARD_API_RATE_LIMIT,+} from "../../lib/const.js";++/**+ * Creates an API key with plan-appropriate rate limits.+ * On cloud: blocks free/basic, sets standard or pro limits.+ * On self-hosted: uses standard limits as default.+ */+export async function createUserApiKey(+ request: FastifyRequest<{ Body: { name: string; expiresIn?: number } }>,+ reply: FastifyReply+) {+ const session = await getSessionFromReq(request);+ if (!session?.user?.id) {+ return reply.status(401).send({ error: "Unauthorized" });+ }++ const { name, expiresIn } = request.body;+ if (!name?.trim()) {+ return reply.status(400).send({ error: "Name is required" });+ }++ let rateLimitMax = STANDARD_API_RATE_LIMIT;++ if (IS_CLOUD) {+ const activeOrgId = (session.session as any).activeOrganizationId;+ if (!activeOrgId) {+ return reply.status(400).send({ error: "No active organization" });+ }++ const subscription = await getSubscriptionInner(activeOrgId);+ const planName = subscription?.planName || "free";++ if (planName === "free" || planName.includes("basic")) {+ return reply.status(403).send({+ error: "API keys require a Standard or Pro plan. Please upgrade to create API keys.",+ });+ }++ if (planName.includes("pro") || planName === "custom") {+ rateLimitMax = PRO_API_RATE_LIMIT;+ }+ }++ try {+ const result = await auth.api.createApiKey({+ body: {+ name,+ expiresIn: expiresIn ?? undefined,+ rateLimitEnabled: true,+ rateLimitTimeWindow: API_RATE_LIMIT_WINDOW,+ rateLimitMax,+ userId: session.user.id,+ },+ });++ return reply.send(result);+ } catch (error: any) {+ return reply.status(500).send({ error: error.message || "Failed to create API key" });+ }+}diff --git a/server/src/api/user/index.ts b/server/src/api/user/index.tsindex 2c245999a..8327589f5 100644--- a/server/src/api/user/index.ts+++ b/server/src/api/user/index.ts@@ -8,3 +8,6 @@ export { listOrganizationMembers } from "./listOrganizationMembers.js";export { updateAccountSettings } from "./updateAccountSettings.js";export { unsubscribeMarketing, oneClickUnsubscribeMarketing } from "./unsubscribeMarketing.js";+// API Keys+export { createUserApiKey } from "./createApiKey.js";+diff --git a/server/src/index.ts b/server/src/index.tsindex 9cc9f346c..14762384f 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -104,6 +104,7 @@ import {} from "./api/stripe/index.js";import {addUserToOrganization,+ createUserApiKey,getMyOrganizations,getUserOrganizations,listOrganizationMembers,@@ -343,6 +344,7 @@ async function userRoutes(fastify: FastifyInstance) {fastify.post("/user/unsubscribe-marketing", authOnly, unsubscribeMarketing);fastify.get("/user/unsubscribe-marketing-oneclick", oneClickUnsubscribeMarketing); // Public - for link clicksfastify.post("/user/unsubscribe-marketing-oneclick", oneClickUnsubscribeMarketing); // Public - for List-Unsubscribe header+ fastify.post("/user/api-keys", authOnly, createUserApiKey);}async function gscRoutes(fastify: FastifyInstance) {diff --git a/server/src/lib/auth.ts b/server/src/lib/auth.tsindex 90ae47db9..597dc1672 100644--- a/server/src/lib/auth.ts+++ b/server/src/lib/auth.ts@@ -10,7 +10,7 @@ import { apiKey } from "@better-auth/api-key"import { db } from "../db/postgres/postgres.js";import * as schema from "../db/postgres/schema.js";import { invitation, member, memberSiteAccess, user } from "../db/postgres/schema.js";-import { DISABLE_SIGNUP, IS_CLOUD } from "./const.js";+import { API_RATE_LIMIT_WINDOW, DISABLE_SIGNUP, IS_CLOUD, STANDARD_API_RATE_LIMIT } from "./const.js";import { addContactToAudience, sendInvitationEmail, sendOtpEmail, sendWelcomeEmail } from "./email/email.js";import { onboardingTipsService } from "../services/onboardingTips/onboardingTipsService.js";@@ -18,7 +18,13 @@ dotenv.config();const pluginList = [admin(),- apiKey(),+ apiKey({+ rateLimit: {+ enabled: true,+ timeWindow: API_RATE_LIMIT_WINDOW,+ maxRequests: STANDARD_API_RATE_LIMIT,+ },+ }),dash(),organization({allowUserToCreateOrganization: true,diff --git a/server/src/lib/const.ts b/server/src/lib/const.tsindex 36f3b104c..6152acbb7 100644--- a/server/src/lib/const.ts+++ b/server/src/lib/const.ts@@ -22,6 +22,11 @@ export const BASIC_MEMBER_LIMIT = 1;export const STANDARD_SITE_LIMIT = 5;export const STANDARD_MEMBER_LIMIT = 3;+// API key rate limits per plan (requests per window)+export const API_RATE_LIMIT_WINDOW = 60_000; // 1 minute+export const STANDARD_API_RATE_LIMIT = 20; // 20 req/min+export const PRO_API_RATE_LIMIT = 200; // 200 req/min+export const APPSUMO_SITE_LIMITS: Record<string, number | null> = {"1": 3, "2": 10, "3": 25, "4": 50, "5": 100, "6": null,};