🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
app (#657)
Bill Yang1ea917a945fd
diff --git a/.claude/settings.local.json b/.claude/settings.local.jsonindex d5c3e079a..f831cbb88 100644--- a/.claude/settings.local.json+++ b/.claude/settings.local.json@@ -12,7 +12,8 @@"WebFetch(domain:github.com)","Bash(npm install @marsidev/react-turnstile)","Bash(npm install @marsidev/react-turnstile --legacy-peer-deps)",- "WebFetch(domain:clickhouse.com)"+ "WebFetch(domain:clickhouse.com)",+ "WebFetch(domain:docs.licensing.appsumo.com)"],"deny": [],"ask": []diff --git a/.gitignore b/.gitignoreindex 2a4f52090..7245dc5f0 100644--- a/.gitignore+++ b/.gitignore@@ -43,4 +43,6 @@ coverage/# Production.env.production-.cursor/\ No newline at end of file+.cursor/++.claude/\ No newline at end of filediff --git a/client/src/app/as/callback/page.tsx b/client/src/app/as/callback/page.tsxnew file mode 100644index 000000000..6dcb07a8f--- /dev/null+++ b/client/src/app/as/callback/page.tsx@@ -0,0 +1,451 @@+"use client";++import { AuthButton } from "@/components/auth/AuthButton";+import { AuthError } from "@/components/auth/AuthError";+import { AuthInput } from "@/components/auth/AuthInput";+import { Turnstile } from "@/components/auth/Turnstile";+import { Button } from "@/components/ui/button";+import { Card } from "@/components/ui/card";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { motion } from "framer-motion";+import { ArrowRight, Check } from "lucide-react";+import Image from "next/image";+import Link from "next/link";+import { useRouter, useSearchParams } from "next/navigation";+import React, { Suspense, useEffect, useState } from "react";+import { addSite } from "../../../api/admin/sites";+import { useSetPageTitle } from "../../../hooks/useSetPageTitle";+import { authClient } from "../../../lib/auth";+import { IS_CLOUD } from "../../../lib/const";+import { userStore } from "../../../lib/userStore";+import { cn, isValidDomain, normalizeDomain } from "../../../lib/utils";++// Animation variants for step transitions+const contentVariants = {+ hidden: { opacity: 0, x: 20 },+ visible: { opacity: 1, x: 0, transition: { duration: 0.3 } },+};++// Client component to handle AppSumo code from URL params+function AppSumoCodeHandler({+ onSetCode,+ onSetStep,+}: {+ onSetCode: (code: string) => void;+ onSetStep: (step: number) => void;+}) {+ const searchParams = useSearchParams();++ useEffect(() => {+ const code = searchParams.get("code");+ if (code) {+ onSetCode(code);+ }++ // Handle step override for testing+ const step = searchParams.get("step");+ if (step && !isNaN(Number(step))) {+ onSetStep(Number(step));+ }+ }, [searchParams, onSetCode, onSetStep]);++ return null;+}++export default function AppSumoSignupPage() {+ useSetPageTitle("Rybbit · AppSumo Signup");++ const [currentStep, setCurrentStep] = useState(1);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<string>("");+ const [appsumoCode, setAppsumoCode] = useState<string>("");+ const router = useRouter();++ // Step 1: Account creation+ const [email, setEmail] = useState("");+ const [password, setPassword] = useState("");+ const [turnstileToken, setTurnstileToken] = useState<string>("");++ // Step 2: Organization creation+ const [orgName, setOrgName] = useState("");+ const [orgSlug, setOrgSlug] = useState("");++ // Step 3: Website addition+ const [organizationId, setOrganizationId] = useState("");+ const [domain, setDomain] = useState("");++ // Handle organization name change and generate slug+ const handleOrgNameChange = (value: string) => {+ setOrgName(value);+ if (value) {+ const generatedSlug = value+ .toLowerCase()+ .replace(/\s+/g, "-")+ .replace(/[^a-z0-9-]/g, "");+ setOrgSlug(generatedSlug);+ }+ };++ // Step 1: Account creation submission+ const handleAccountSubmit = async () => {+ setIsLoading(true);+ setError("");++ try {+ // Validate Turnstile token if in cloud mode+ if (IS_CLOUD && !turnstileToken) {+ setError("Please complete the captcha verification");+ setIsLoading(false);+ return;+ }++ const { data, error } = await authClient.signUp.email(+ {+ email,+ name: email.split("@")[0], // Use email prefix as default name+ password,+ },+ {+ onRequest: context => {+ if (IS_CLOUD && turnstileToken) {+ context.headers.set("x-captcha-response", turnstileToken);+ }+ },+ }+ );++ if (data?.user) {+ userStore.setState({+ user: data.user,+ });+ setCurrentStep(2);+ }++ if (error) {+ setError(error.message ?? "");+ }+ } catch (error) {+ setError(String(error));+ } finally {+ setIsLoading(false);+ }+ };++ // Step 2: Organization creation and AppSumo license activation+ const handleOrganizationSubmit = async () => {+ setIsLoading(true);+ setError("");++ try {+ // Create organization+ const { data, error } = await authClient.organization.create({+ name: orgName,+ slug: orgSlug,+ });++ if (error) {+ throw new Error(error.message || "Failed to create organization");+ }++ if (!data?.id) {+ throw new Error("No organization ID returned");+ }++ // Set as active organization+ await authClient.organization.setActive({+ organizationId: data.id,+ });++ setOrganizationId(data.id);++ // Activate AppSumo license if code is present+ if (appsumoCode) {+ try {+ const response = await fetch("/api/as/activate", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ credentials: "include",+ body: JSON.stringify({+ code: appsumoCode,+ organizationId: data.id,+ }),+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || "Failed to activate AppSumo license");+ }++ const licenseData = await response.json();+ console.log("AppSumo license activated:", licenseData);+ } catch (licenseError) {+ console.error("Error activating AppSumo license:", licenseError);+ setError(+ "Organization created, but license activation failed. Please contact support with your license key."+ );+ // Continue to next step even if license activation fails+ }+ }++ setCurrentStep(3);+ } catch (error) {+ setError(String(error));+ } finally {+ setIsLoading(false);+ }+ };++ // Step 3: Website addition submission+ const handleWebsiteSubmit = async () => {+ setIsLoading(true);+ setError("");++ try {+ // Validate domain+ if (!isValidDomain(domain)) {+ setError("Invalid domain format. Must be a valid domain like example.com or sub.example.com");+ setIsLoading(false);+ return;+ }++ try {+ const normalizedDomain = normalizeDomain(domain);+ const response = await addSite(normalizedDomain, normalizedDomain, organizationId);+ // Navigate directly to dashboard after adding website+ router.push(`/${response.siteId}`);+ } catch (error) {+ setError(String(error));+ }+ } catch (error) {+ setError(String(error));+ } finally {+ setIsLoading(false);+ }+ };++ // Skip website step and go to dashboard+ const handleSkipWebsite = () => {+ router.push("/");+ };++ // Render the content based on current step+ const renderStepContent = () => {+ switch (currentStep) {+ case 1:+ return (+ <motion.div initial="hidden" animate="visible" variants={contentVariants}>+ <h2 className="text-2xl font-semibold mb-2">Welcome to Rybbit!</h2>+ <p className="text-sm text-muted-foreground mb-6">Activate your AppSumo license by creating an account</p>+ <div className="space-y-4">+ <AuthInput+ id="email"+ label="Email"+ type="email"+ placeholder="[email protected]"+ required+ value={email}+ onChange={e => setEmail(e.target.value)}+ />++ <AuthInput+ id="password"+ label="Password"+ type="password"+ placeholder="••••••••"+ required+ value={password}+ onChange={e => setPassword(e.target.value)}+ />++ {IS_CLOUD && (+ <Turnstile+ onSuccess={token => setTurnstileToken(token)}+ onError={() => setTurnstileToken("")}+ onExpire={() => setTurnstileToken("")}+ className="flex justify-center"+ />+ )}++ <AuthButton+ isLoading={isLoading}+ loadingText="Creating account..."+ onClick={handleAccountSubmit}+ type="button"+ className="mt-6 transition-all duration-300 h-11"+ disabled={IS_CLOUD ? !turnstileToken || isLoading : isLoading}+ >+ Continue+ <ArrowRight className="ml-2 h-4 w-4" />+ </AuthButton>++ <div className="text-center text-sm">+ Already have an account?{" "}+ <Link+ href="/login"+ className="underline underline-offset-4 hover:text-emerald-400 transition-colors duration-300"+ >+ Log in+ </Link>+ </div>+ </div>+ </motion.div>+ );+ case 2:+ return (+ <motion.div initial="hidden" animate="visible" variants={contentVariants}>+ <h2 className="text-2xl font-semibold mb-2">Create your organization</h2>+ <p className="text-sm text-muted-foreground mb-6">+ Your AppSumo license will be activated for this organization+ </p>+ <div className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="orgName">Organization Name</Label>+ <Input+ id="orgName"+ type="text"+ placeholder="Acme Inc."+ value={orgName}+ onChange={e => handleOrgNameChange(e.target.value)}+ required+ className="h-10 transition-all bg-neutral-800/50 border-neutral-700"+ />+ </div>++ <Button+ className="w-full transition-all duration-300 h-11 bg-emerald-600 hover:bg-emerald-500 text-white"+ onClick={handleOrganizationSubmit}+ disabled={isLoading || !orgName || !orgSlug}+ variant="success"+ >+ Continue & Activate License+ <ArrowRight className="ml-2 h-4 w-4" />+ </Button>+ </div>+ </motion.div>+ );+ case 3:+ return (+ <motion.div initial="hidden" animate="visible" variants={contentVariants}>+ <h2 className="text-2xl font-semibold mb-2">Add your site (optional)</h2>+ <p className="text-sm text-muted-foreground mb-6">+ You can always add sites later from your dashboard+ </p>+ <div className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="domain">Website Domain</Label>+ <Input+ id="domain"+ type="text"+ placeholder="example.com or sub.example.com"+ value={domain}+ onChange={e => setDomain(e.target.value.toLowerCase())}+ className="h-10 transition-all bg-neutral-800/50 border-neutral-700"+ />+ <p className="text-xs text-muted-foreground">Enter the domain of the website you want to track</p>+ </div>++ <div className="flex flex-col gap-3">+ <Button+ className="w-full transition-all duration-300 h-11 bg-emerald-600 hover:bg-emerald-500 text-white"+ onClick={handleWebsiteSubmit}+ disabled={isLoading || !domain || !isValidDomain(domain)}+ variant="success"+ >+ Add Site & Continue+ <ArrowRight className="ml-2 h-4 w-4" />+ </Button>+ <Button+ className="w-full transition-all duration-300 h-11"+ onClick={handleSkipWebsite}+ disabled={isLoading}+ variant="outline"+ >+ Skip for now+ </Button>+ </div>+ </div>+ </motion.div>+ );+ default:+ return null;+ }+ };++ return (+ <div className="flex justify-center items-center h-dvh w-full p-4 ">+ <div className="flex flex-col items-center bg-background relative">+ {/* Suspense boundary for the URL parameter handler */}+ <Suspense fallback={null}>+ <AppSumoCodeHandler onSetCode={setAppsumoCode} onSetStep={setCurrentStep} />+ </Suspense>++ {/* Background gradients similar to docs page */}+ <div className="absolute top-0 left-0 w-[550px] h-[550px] bg-emerald-500/40 rounded-full blur-[80px] opacity-40"></div>+ <div className="absolute top-20 left-20 w-[400px] h-[400px] bg-emerald-600/30 rounded-full blur-[70px] opacity-30"></div>++ <div className="absolute bottom-0 right-0 w-[500px] h-[500px] bg-blue-500/40 rounded-full blur-[80px] opacity-30"></div>+ <div className="absolute bottom-40 right-20 w-[350px] h-[350px] bg-indigo-500/30 rounded-full blur-[75px] opacity-30"></div>++ <div className="absolute top-1/4 right-0 w-[320px] h-[320px] bg-purple-500/40 rounded-full blur-[70px] opacity-20"></div>++ {/* Logo and title above the card */}+ <div className="relative z-10 mb-6 text-center">+ <a href="https://rybbit.com" target="_blank" className="inline-block mb-2">+ <Image src="/rybbit-text.svg" alt="Rybbit" width={150} height={34} />+ </a>+ <h1 className="text-lg text-neutral-300">AppSumo License Activation</h1>+ </div>++ <Card className="w-full md:w-[500px] p-0 overflow-hidden shadow-2xl border-neutral-700/50 backdrop-blur-sm bg-neutral-800/20 z-10 p-8">+ {/* Horizontal step indicator */}+ <div className="flex items-center w-full mb-4">+ {[1, 2, 3].map((step, index) => (+ <React.Fragment key={step}>+ <div+ className={cn(+ "flex items-center justify-center w-10 h-10 rounded-full text-sm font-semibold transition-all duration-300",+ currentStep === step+ ? "bg-emerald-600 text-primary-foreground"+ : currentStep > step+ ? "bg-emerald-600/20 text-emerald-400 border-2 border-emerald-600/40"+ : "bg-muted-foreground/20 text-muted-foreground border-2 border-muted-foreground/40"+ )}+ >+ {currentStep > step ? <Check className="h-5 w-5" /> : step}+ </div>+ {index < 2 && (+ <div+ className={cn(+ "flex-1 h-0.5 transition-all duration-300",+ currentStep > step ? "bg-emerald-600" : "bg-muted-foreground/40"+ )}+ />+ )}+ </React.Fragment>+ ))}+ </div>++ {/* Content area */}+ <div className="flex flex-col gap-4">+ {renderStepContent()}+ <AuthError error={error} />+ </div>+ </Card>++ <div className="text-xs text-muted-foreground relative z-10 mt-8">+ <a+ href="https://rybbit.com"+ target="_blank"+ rel="noopener"+ title="Rybbit - Open Source Privacy-Focused Web Analytics"+ >+ Open source web analytics powered by Rybbit+ </a>+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/app/settings/organization/subscription/page.tsx b/client/src/app/settings/organization/subscription/page.tsxindex e37017ff1..5a8c9bcdd 100644--- a/client/src/app/settings/organization/subscription/page.tsx+++ b/client/src/app/settings/organization/subscription/page.tsx@@ -64,7 +64,7 @@ export default function OrganizationSubscriptionPage() {return <TrialPlan />;}- if (activeSubscription.appSumoPlan) {+ if (activeSubscription.planName.startsWith("appsumo")) {return <AppSumoPlan />;}diff --git a/client/src/components/AuthenticationGuard.tsx b/client/src/components/AuthenticationGuard.tsxindex e38bc5ca8..f0eeb0ade 100644--- a/client/src/components/AuthenticationGuard.tsx+++ b/client/src/components/AuthenticationGuard.tsx@@ -5,7 +5,7 @@ import { redirect, usePathname } from "next/navigation";import { userStore } from "../lib/userStore";import { useGetSiteIsPublic } from "../api/admin/sites";-const publicRoutes = ["/login", "/signup", "/invitation", "/reset-password"];+const PUBLIC_ROUTES = ["/login", "/signup", "/invitation", "/reset-password", "/as/callback"];export function AuthenticationGuard() {const { user, isPending } = userStore();@@ -28,7 +28,14 @@ export function AuthenticationGuard() {// 3. Not on a public route// 4. Not on a public site// 5. Not using a private link key- if (!isPending && !isCheckingPublic && !user && !publicRoutes.includes(pathname) && !isPublicSite && !hasPrivateKey) {+ if (+ !isPending &&+ !isCheckingPublic &&+ !user &&+ !PUBLIC_ROUTES.includes(pathname) &&+ !isPublicSite &&+ !hasPrivateKey+ ) {redirect("/login");}}, [isPending, user, pathname, isCheckingPublic, isPublicSite, hasPrivateKey]);diff --git a/client/src/components/subscription/AppSumoPlan.tsx b/client/src/components/subscription/AppSumoPlan.tsxindex 8718583ae..a4d9a15d7 100644--- a/client/src/components/subscription/AppSumoPlan.tsx+++ b/client/src/components/subscription/AppSumoPlan.tsx@@ -36,7 +36,7 @@ export function AppSumoPlan() {<div className="space-y-6"><Card><CardHeader>- <CardTitle className="flex items-center">AppSumo Plan</CardTitle>+ <CardTitle className="flex items-center">AppSumo Plan Tier {subscription.planName.split("-")[1]}</CardTitle><CardDescription>You are on the AppSumo lifetime plan with up to {subscription?.eventLimit.toLocaleString()} events permonth.diff --git a/client/src/lib/subscription/useStripeSubscription.ts b/client/src/lib/subscription/useStripeSubscription.tsindex 45c6f0720..9eb0a2f01 100644--- a/client/src/lib/subscription/useStripeSubscription.ts+++ b/client/src/lib/subscription/useStripeSubscription.ts@@ -17,7 +17,6 @@ interface SubscriptionData {trialDaysRemaining?: number;message?: string; // For expired trial messageisPro?: boolean;- appSumoPlan?: string;}export function useStripeSubscription() {diff --git a/client/src/middleware.ts b/client/src/middleware.tsindex c1891abe6..6ec3bb26d 100644--- a/client/src/middleware.ts+++ b/client/src/middleware.ts@@ -39,6 +39,7 @@ export async function middleware(request: NextRequest) {"account","uptime","settings",+ "as","_next","api",];diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.ymlindex 48b51b0e3..5cae27622 100644--- a/docker-compose.cloud.yml+++ b/docker-compose.cloud.yml@@ -102,6 +102,9 @@ services:- CLOUD=${CLOUD}- STRIPE_SECRET_KEY=${STRIPE_SECRET_KEY}- STRIPE_WEBHOOK_SECRET=${STRIPE_WEBHOOK_SECRET}+ # AppSumo configuration+ - APPSUMO_CLIENT_ID=${APPSUMO_CLIENT_ID}+ - APPSUMO_CLIENT_SECRET=${APPSUMO_CLIENT_SECRET}- GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID}- GOOGLE_CLIENT_SECRET=${GOOGLE_CLIENT_SECRET}- GITHUB_CLIENT_ID=${GITHUB_CLIENT_ID}diff --git a/docs-v2/.next/trace b/docs-v2/.next/tracedeleted file mode 100644index 4ba27b042..000000000--- a/docs-v2/.next/trace+++ /dev/null@@ -1 +0,0 @@-[{"name":"next-dev","duration":180048258510,"timestamp":91226093941,"id":1,"tags":{},"startTime":1760674837548,"traceId":"bf9cf7461a50f1da"}]diff --git a/server/.env.example b/server/.env.exampleindex 729da28d8..01e7cf702 100644--- a/server/.env.example+++ b/server/.env.example@@ -27,6 +27,10 @@ BETTER_AUTH_SECRET=your-secret-key-hereSTRIPE_SECRET_KEY=STRIPE_WEBHOOK_SECRET=+# AppSumo (optional - cloud only)+APPSUMO_CLIENT_ID=+APPSUMO_CLIENT_SECRET=+# R2 Storage (optional)R2_ACCOUNT_ID=R2_ACCESS_KEY_ID=diff --git a/server/drizzle.config.ts b/server/drizzle.config.tsindex c4cc08897..56dcdd319 100644--- a/server/drizzle.config.ts+++ b/server/drizzle.config.ts@@ -16,5 +16,5 @@ export default defineConfig({ssl: false,},verbose: true,- tablesFilter: ['!pg_*'],+ tablesFilter: ['!pg_*', '!as_*'],});diff --git a/server/src/api/as/activate.ts b/server/src/api/as/activate.tsnew file mode 100644index 000000000..6f40d655a--- /dev/null+++ b/server/src/api/as/activate.ts@@ -0,0 +1,213 @@+import { eq, sql } from "drizzle-orm";+import { FastifyReply, FastifyRequest } from "fastify";+import { db } from "../../db/postgres/postgres.js";+import { asLicenses } from "../../db/postgres/schema-appsumo.js";+import { getSessionFromReq } from "../../lib/auth-utils.js";+import { IS_CLOUD } from "../../lib/const.js";++/**+ * Check if AppSumo integration is enabled+ */+function isAppSumoEnabled(): boolean {+ return (+ IS_CLOUD &&+ !!process.env.APPSUMO_CLIENT_ID &&+ !!process.env.APPSUMO_CLIENT_SECRET+ );+}++/**+ * Exchange authorization code for access token+ */+async function exchangeCodeForToken(code: string) {+ const tokenUrl = "https://appsumo.com/openid/token/";++ const params = new URLSearchParams({+ client_id: process.env.APPSUMO_CLIENT_ID!,+ client_secret: process.env.APPSUMO_CLIENT_SECRET!,+ redirect_uri: "https://app.rybbit.io/as/callback",+ code: code,+ grant_type: "authorization_code",+ });++ const response = await fetch(tokenUrl, {+ method: "POST",+ headers: {+ "Content-Type": "application/x-www-form-urlencoded",+ },+ body: params.toString(),+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`Failed to exchange code for token: ${response.status} - ${errorText}`);+ }++ const data = await response.json();++ return {+ accessToken: data.access_token,+ };+}++/**+ * Fetch license key using access token+ */+async function fetchLicenseKey(accessToken: string) {+ const licenseUrl = "https://appsumo.com/openid/license_key/";++ const response = await fetch(licenseUrl, {+ method: "GET",+ headers: {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`Failed to fetch license key: ${response.status} - ${errorText}`);+ }++ const data = await response.json();++ return {+ licenseKey: data.license_key,+ tier: data.tier?.toString() || "1",+ };+}++export async function activateAppSumoLicense(+ request: FastifyRequest<{+ Body: {+ code: string;+ organizationId: string;+ };+ }>,+ reply: FastifyReply+) {+ if (!isAppSumoEnabled()) {+ return reply.status(503).send({+ error: "AppSumo integration is not available",+ });+ }++ const { code, organizationId } = request.body;++ if (!code || !organizationId) {+ return reply.status(400).send({+ error: "Missing required fields: code and organizationId",+ });+ }++ try {+ const session = await getSessionFromReq(request);++ if (!session?.user?.id) {+ return reply.status(401).send({+ error: "Unauthorized",+ message: "You must be logged in to activate a license",+ });+ }++ // Verify user is a member of the organization+ const member = await db.query.member.findFirst({+ where: (member, { and, eq }) =>+ and(eq(member.userId, session.user.id), eq(member.organizationId, organizationId)),+ });++ if (!member) {+ return reply.status(403).send({+ error: "You are not a member of this organization",+ });+ }++ // Step 1: Exchange authorization code for access token+ let tokenData;+ try {+ tokenData = await exchangeCodeForToken(code);+ } catch (error) {+ console.error("Error exchanging code for token:", error);+ return reply.status(400).send({+ error: "Failed to exchange authorization code",+ message: error instanceof Error ? error.message : "Unknown error",+ });+ }++ // Step 2: Fetch license key using access token+ let licenseData;+ try {+ licenseData = await fetchLicenseKey(tokenData.accessToken);+ } catch (error) {+ console.error("Error fetching license key:", error);+ return reply.status(400).send({+ error: "Failed to fetch license key",+ message: error instanceof Error ? error.message : "Unknown error",+ });+ }++ // Step 3: Check if license already exists+ const existingLicense = await db.execute(+ sql`SELECT organization_id FROM as_licenses WHERE license_key = ${licenseData.licenseKey} LIMIT 1`+ );++ if (Array.isArray(existingLicense) && existingLicense.length > 0) {+ const existing = existingLicense[0] as any;+ // If organization_id is already set, license is already activated+ if (existing.organization_id !== null) {+ return reply.status(409).send({+ error: "License already activated",+ message: "This license key has already been activated for another organization",+ });+ }++ // License exists as placeholder (from purchase webhook) - update it+ await db.execute(sql`+ UPDATE as_licenses+ SET+ organization_id = ${organizationId},+ tier = ${licenseData.tier},+ status = 'active',+ activated_at = NOW(),+ updated_at = NOW()+ WHERE license_key = ${licenseData.licenseKey}+ `);+ } else {+ // Step 4: License doesn't exist - create new record+ await db.execute(sql`+ INSERT INTO as_licenses (+ organization_id,+ license_key,+ tier,+ status,+ activated_at,+ created_at,+ updated_at+ ) VALUES (+ ${organizationId},+ ${licenseData.licenseKey},+ ${licenseData.tier},+ 'active',+ NOW(),+ NOW(),+ NOW()+ )+ `);+ }++ return reply.status(200).send({+ success: true,+ license: {+ licenseKey: licenseData.licenseKey,+ tier: licenseData.tier,+ status: "active",+ },+ });+ } catch (error) {+ console.error("Error activating AppSumo license:", error);+ return reply.status(500).send({+ error: "Internal server error",+ message: error instanceof Error ? error.message : "Unknown error",+ });+ }+}diff --git a/server/src/api/as/webhook.ts b/server/src/api/as/webhook.tsnew file mode 100644index 000000000..5c5d8144e--- /dev/null+++ b/server/src/api/as/webhook.ts@@ -0,0 +1,533 @@+import { sql } from "drizzle-orm";+import { FastifyReply, FastifyRequest } from "fastify";+import { db } from "../../db/postgres/postgres.js";+import { IS_CLOUD } from "../../lib/const.js";++interface AppSumoWebhookPayload {+ test?: boolean;+ event: string;+ license_key: string;+ prev_license_key?: string; // Used in upgrade/downgrade events+ event_timestamp?: number; // Unix timestamp in milliseconds+ created_at?: number; // Unix timestamp in seconds+ license_status?: string;+ tier?: string | number;+ extra?: {+ reason?: string;+ };+ // Deal add-on specific fields+ partner_plan_name?: string;+ parent_license_key?: string;+ unit_quantity?: number;+}++/**+ * Check if AppSumo integration is enabled+ */+function isAppSumoEnabled(): boolean {+ return (+ IS_CLOUD &&+ !!process.env.APPSUMO_CLIENT_ID &&+ !!process.env.APPSUMO_CLIENT_SECRET+ );+}++/**+ * Validate webhook payload+ */+function validateWebhookPayload(payload: AppSumoWebhookPayload): boolean {+ if (!payload.license_key) {+ throw new Error("Missing license_key in webhook payload");+ }++ if (!payload.event) {+ throw new Error("Missing event in webhook payload");+ }++ const validEvents = ["purchase", "activate", "upgrade", "downgrade", "deactivate", "migrate", "test"];+ if (!validEvents.includes(payload.event)) {+ throw new Error(`Invalid event type: ${payload.event}`);+ }++ return true;+}++export async function handleAppSumoWebhook(+ request: FastifyRequest<{+ Body: AppSumoWebhookPayload;+ }>,+ reply: FastifyReply+) {+ if (!isAppSumoEnabled()) {+ console.log("[AppSumo] Integration not enabled");+ return reply.status(503).send({+ error: "AppSumo integration is not available",+ });+ }++ const payload = request.body;+ console.log("[AppSumo] Received webhook:", JSON.stringify(payload, null, 2));++ // Handle test webhook for AppSumo validation+ if (payload.test === true || payload.event === "test") {+ console.log("[AppSumo] Test webhook received");+ return reply.status(200).send({+ event: "test",+ success: true,+ });+ }++ try {+ // Validate webhook payload+ validateWebhookPayload(payload);++ const {+ license_key,+ event,+ tier,+ parent_license_key,+ prev_license_key,+ license_status,+ event_timestamp,+ extra,+ } = payload;++ console.log(`[AppSumo] Processing ${event} event for license ${license_key}`);++ // Log webhook event for audit trail+ await db.execute(sql`+ INSERT INTO as_webhook_events (+ license_key,+ event,+ payload,+ processed_at,+ created_at+ ) VALUES (+ ${license_key},+ ${event},+ ${JSON.stringify(payload)},+ NOW(),+ NOW()+ )+ `);++ // Process the webhook based on event type+ switch (event) {+ case "purchase":+ // License purchased - create placeholder record+ // Note: license_status will be "inactive" until user activates+ console.log(`[AppSumo] Handling purchase event for license ${license_key}, tier ${tier}`);+ await handlePurchaseEvent(license_key, tier, parent_license_key);+ break;++ case "activate":+ // License activated by user+ // Note: license_status is "inactive" in webhook, becomes active after our 200 response+ console.log(`[AppSumo] Handling activate event for license ${license_key}, tier ${tier}`);+ await handleActivateEvent(license_key, tier);+ break;++ case "upgrade":+ // License upgraded to higher tier+ // Note: Creates NEW license_key with prev_license_key pointing to old one+ // AppSumo sends simultaneous deactivate event for old license (we skip it)+ console.log(`[AppSumo] Handling upgrade event: ${prev_license_key} -> ${license_key}, tier ${tier}`);+ await handleUpgradeEvent(license_key, tier, prev_license_key);+ break;++ case "downgrade":+ // License downgraded to lower tier+ // Note: Creates NEW license_key with prev_license_key pointing to old one+ // AppSumo sends simultaneous deactivate event for old license (we skip it)+ console.log(`[AppSumo] Handling downgrade event: ${prev_license_key} -> ${license_key}, tier ${tier}`);+ await handleDowngradeEvent(license_key, tier, prev_license_key);+ break;++ case "deactivate":+ // License refunded or canceled+ // Note: license_status is "active" in webhook (for refunds), becomes deactivated after our 200 response+ // For upgrade/downgrade, license_status is already "deactivated" - we skip these+ const isUpgradeOrDowngradeDeactivation =+ extra?.reason === "Upgraded by customer" || extra?.reason === "Downgraded by customer";+ console.log(`[AppSumo] Deactivate event for ${license_key}, reason: ${extra?.reason}, skipping: ${isUpgradeOrDowngradeDeactivation}`);+ if (!isUpgradeOrDowngradeDeactivation) {+ await handleDeactivateEvent(license_key);+ }+ break;++ case "migrate":+ // Add-on migration when parent license is upgraded/downgraded+ // Note: parent_license_key is updated to point to new parent license+ console.log(`[AppSumo] Handling migrate event for ${license_key}, parent: ${parent_license_key}`);+ await handleMigrateEvent(license_key, tier, parent_license_key);+ break;++ default:+ console.warn(`[AppSumo] Unknown AppSumo webhook event: ${event}`);+ }++ // Return success response as required by AppSumo+ console.log(`[AppSumo] Successfully processed ${event} event for ${license_key}`);+ return reply.status(200).send({+ event: event,+ success: true,+ });+ } catch (error) {+ console.error("[AppSumo] Error processing AppSumo webhook:", error);++ // Still return 200 to acknowledge receipt, but log the error+ return reply.status(200).send({+ event: payload.event || "unknown",+ success: false,+ error: error instanceof Error ? error.message : "Unknown error",+ });+ }+}++/**+ * Handle purchase event - create placeholder license record+ */+async function handlePurchaseEvent(+ licenseKey: string,+ tier: any,+ parentLicenseKey?: string+) {+ const tierValue = tier?.toString() || "1";+ console.log(`[AppSumo] handlePurchaseEvent - license: ${licenseKey}, tier: ${tierValue}, parent: ${parentLicenseKey}`);++ // Check if license already exists+ const existing = await db.execute(+ sql`SELECT id FROM as_licenses WHERE license_key = ${licenseKey} LIMIT 1`+ );++ if (Array.isArray(existing) && existing.length === 0) {+ // Create placeholder - will be linked to org when user activates+ console.log(`[AppSumo] Creating new pending license ${licenseKey}`);+ await db.execute(sql`+ INSERT INTO as_licenses (+ organization_id,+ license_key,+ tier,+ status,+ parent_license_key,+ created_at,+ updated_at+ ) VALUES (+ NULL,+ ${licenseKey},+ ${tierValue},+ 'pending',+ ${parentLicenseKey || null},+ NOW(),+ NOW()+ )+ ON CONFLICT (license_key) DO NOTHING+ `);+ console.log(`[AppSumo] Successfully created pending license ${licenseKey}`);+ } else {+ console.log(`[AppSumo] License ${licenseKey} already exists, skipping`);+ }+}++/**+ * Handle activate event - update license status+ */+async function handleActivateEvent(licenseKey: string, tier: any) {+ const tierValue = tier?.toString() || "1";+ console.log(`[AppSumo] handleActivateEvent - license: ${licenseKey}, tier: ${tierValue}`);++ await db.execute(sql`+ UPDATE as_licenses+ SET+ status = 'active',+ tier = ${tierValue},+ activated_at = NOW(),+ updated_at = NOW()+ WHERE license_key = ${licenseKey}+ `);+ console.log(`[AppSumo] Successfully activated license ${licenseKey}`);+}++/**+ * Handle upgrade event - create new license and transfer organization+ */+async function handleUpgradeEvent(licenseKey: string, tier: any, prevLicenseKey?: string) {+ const tierValue = tier?.toString() || "1";+ console.log(`[AppSumo] handleUpgradeEvent - new license: ${licenseKey}, prev license: ${prevLicenseKey}, tier: ${tierValue}`);++ if (!prevLicenseKey) {+ console.warn("[AppSumo] No prev_license_key provided for upgrade event");+ return;+ }++ // Get the old license to find the organization+ console.log(`[AppSumo] Querying old license: ${prevLicenseKey}`);+ let oldLicenseResult = await db.execute(+ sql`SELECT organization_id FROM as_licenses WHERE license_key = ${prevLicenseKey} LIMIT 1`+ );++ console.log(`[AppSumo] Old license query result:`, JSON.stringify(oldLicenseResult, null, 2));++ // If previous license not found, try to find ANY license with an organization (fallback for missed webhooks)+ if (!Array.isArray(oldLicenseResult) || oldLicenseResult.length === 0) {+ console.warn(`[AppSumo] Old license not found: ${prevLicenseKey}, searching for any license with organization as fallback`);+ oldLicenseResult = await db.execute(+ sql`SELECT organization_id FROM as_licenses WHERE organization_id IS NOT NULL ORDER BY updated_at DESC LIMIT 1`+ );++ if (!Array.isArray(oldLicenseResult) || oldLicenseResult.length === 0) {+ console.error(`[AppSumo] No licenses with organization found, cannot process upgrade`);+ return;+ }+ console.log(`[AppSumo] Found fallback license:`, JSON.stringify(oldLicenseResult, null, 2));+ }++ const oldLicense = oldLicenseResult[0] as any;+ const organizationId = oldLicense.organization_id;+ console.log(`[AppSumo] Found old license with organization_id: ${organizationId}`);++ // Create new license with the organization transferred+ if (organizationId) {+ // Organization exists - create active license+ console.log(`[AppSumo] Organization exists - creating active license for ${licenseKey}`);+ try {+ await db.execute(sql`+ INSERT INTO as_licenses (+ organization_id,+ license_key,+ tier,+ status,+ activated_at,+ created_at,+ updated_at+ ) VALUES (+ ${organizationId},+ ${licenseKey},+ ${tierValue},+ 'active',+ NOW(),+ NOW(),+ NOW()+ )+ ON CONFLICT (license_key) DO UPDATE SET+ organization_id = ${organizationId},+ tier = ${tierValue},+ status = 'active',+ activated_at = NOW(),+ updated_at = NOW()+ `);+ console.log(`[AppSumo] Successfully created/updated active license ${licenseKey}`);+ } catch (error) {+ console.error(`[AppSumo] Error creating active license:`, error);+ throw error;+ }+ } else {+ // No organization yet - create pending license+ console.log(`[AppSumo] No organization - creating pending license for ${licenseKey}`);+ try {+ await db.execute(sql`+ INSERT INTO as_licenses (+ organization_id,+ license_key,+ tier,+ status,+ created_at,+ updated_at+ ) VALUES (+ NULL,+ ${licenseKey},+ ${tierValue},+ 'pending',+ NOW(),+ NOW()+ )+ ON CONFLICT (license_key) DO UPDATE SET+ tier = ${tierValue},+ status = 'pending',+ updated_at = NOW()+ `);+ console.log(`[AppSumo] Successfully created/updated pending license ${licenseKey}`);+ } catch (error) {+ console.error(`[AppSumo] Error creating pending license:`, error);+ throw error;+ }+ }++ // Deactivate the old license+ console.log(`[AppSumo] Deactivating old license ${prevLicenseKey}`);+ try {+ await db.execute(sql`+ UPDATE as_licenses+ SET+ status = 'inactive',+ deactivated_at = NOW(),+ updated_at = NOW()+ WHERE license_key = ${prevLicenseKey}+ `);+ console.log(`[AppSumo] Successfully deactivated old license ${prevLicenseKey}`);+ } catch (error) {+ console.error(`[AppSumo] Error deactivating old license:`, error);+ throw error;+ }+}++/**+ * Handle downgrade event - create new license and transfer organization+ */+async function handleDowngradeEvent(licenseKey: string, tier: any, prevLicenseKey?: string) {+ const tierValue = tier?.toString() || "1";+ console.log(`[AppSumo] handleDowngradeEvent - new license: ${licenseKey}, prev license: ${prevLicenseKey}, tier: ${tierValue}`);++ if (!prevLicenseKey) {+ console.warn("[AppSumo] No prev_license_key provided for downgrade event");+ return;+ }++ // Get the old license to find the organization+ console.log(`[AppSumo] Querying old license: ${prevLicenseKey}`);+ let oldLicenseResult = await db.execute(+ sql`SELECT organization_id FROM as_licenses WHERE license_key = ${prevLicenseKey} LIMIT 1`+ );++ console.log(`[AppSumo] Old license query result:`, JSON.stringify(oldLicenseResult, null, 2));++ // If previous license not found, try to find ANY license with an organization (fallback for missed webhooks)+ if (!Array.isArray(oldLicenseResult) || oldLicenseResult.length === 0) {+ console.warn(`[AppSumo] Old license not found: ${prevLicenseKey}, searching for any license with organization as fallback`);+ oldLicenseResult = await db.execute(+ sql`SELECT organization_id FROM as_licenses WHERE organization_id IS NOT NULL ORDER BY updated_at DESC LIMIT 1`+ );++ if (!Array.isArray(oldLicenseResult) || oldLicenseResult.length === 0) {+ console.error(`[AppSumo] No licenses with organization found, cannot process downgrade`);+ return;+ }+ console.log(`[AppSumo] Found fallback license:`, JSON.stringify(oldLicenseResult, null, 2));+ }++ const oldLicense = oldLicenseResult[0] as any;+ const organizationId = oldLicense.organization_id;+ console.log(`[AppSumo] Found old license with organization_id: ${organizationId}`);++ // Create new license with the organization transferred+ if (organizationId) {+ // Organization exists - create active license+ console.log(`[AppSumo] Organization exists - creating active license for ${licenseKey}`);+ try {+ await db.execute(sql`+ INSERT INTO as_licenses (+ organization_id,+ license_key,+ tier,+ status,+ activated_at,+ created_at,+ updated_at+ ) VALUES (+ ${organizationId},+ ${licenseKey},+ ${tierValue},+ 'active',+ NOW(),+ NOW(),+ NOW()+ )+ ON CONFLICT (license_key) DO UPDATE SET+ organization_id = ${organizationId},+ tier = ${tierValue},+ status = 'active',+ activated_at = NOW(),+ updated_at = NOW()+ `);+ console.log(`[AppSumo] Successfully created/updated active license ${licenseKey}`);+ } catch (error) {+ console.error(`[AppSumo] Error creating active license:`, error);+ throw error;+ }+ } else {+ // No organization yet - create pending license+ console.log(`[AppSumo] No organization - creating pending license for ${licenseKey}`);+ try {+ await db.execute(sql`+ INSERT INTO as_licenses (+ organization_id,+ license_key,+ tier,+ status,+ created_at,+ updated_at+ ) VALUES (+ NULL,+ ${licenseKey},+ ${tierValue},+ 'pending',+ NOW(),+ NOW()+ )+ ON CONFLICT (license_key) DO UPDATE SET+ tier = ${tierValue},+ status = 'pending',+ updated_at = NOW()+ `);+ console.log(`[AppSumo] Successfully created/updated pending license ${licenseKey}`);+ } catch (error) {+ console.error(`[AppSumo] Error creating pending license:`, error);+ throw error;+ }+ }++ // Deactivate the old license+ console.log(`[AppSumo] Deactivating old license ${prevLicenseKey}`);+ try {+ await db.execute(sql`+ UPDATE as_licenses+ SET+ status = 'inactive',+ deactivated_at = NOW(),+ updated_at = NOW()+ WHERE license_key = ${prevLicenseKey}+ `);+ console.log(`[AppSumo] Successfully deactivated old license ${prevLicenseKey}`);+ } catch (error) {+ console.error(`[AppSumo] Error deactivating old license:`, error);+ throw error;+ }+}++/**+ * Handle deactivate event - mark license as inactive+ */+async function handleDeactivateEvent(licenseKey: string) {+ console.log(`[AppSumo] handleDeactivateEvent - license: ${licenseKey}`);+ await db.execute(sql`+ UPDATE as_licenses+ SET+ status = 'inactive',+ deactivated_at = NOW(),+ updated_at = NOW()+ WHERE license_key = ${licenseKey}+ `);+ console.log(`[AppSumo] Successfully deactivated license ${licenseKey}`);+}++/**+ * Handle migrate event - update parent license for add-ons+ */+async function handleMigrateEvent(+ licenseKey: string,+ tier: any,+ parentLicenseKey?: string+) {+ const tierValue = tier?.toString() || "1";+ console.log(`[AppSumo] handleMigrateEvent - license: ${licenseKey}, tier: ${tierValue}, parent: ${parentLicenseKey}`);++ await db.execute(sql`+ UPDATE as_licenses+ SET+ tier = ${tierValue},+ parent_license_key = ${parentLicenseKey || null},+ updated_at = NOW()+ WHERE license_key = ${licenseKey}+ `);+ console.log(`[AppSumo] Successfully migrated license ${licenseKey}`);+}diff --git a/server/src/api/stripe/getSubscription.ts b/server/src/api/stripe/getSubscription.tsindex 1c4da24c3..82f283be6 100644--- a/server/src/api/stripe/getSubscription.ts+++ b/server/src/api/stripe/getSubscription.ts@@ -4,8 +4,7 @@ import { DateTime } from "luxon";import Stripe from "stripe";import { db } from "../../db/postgres/postgres.js";import { organization } from "../../db/postgres/schema.js";-import { DEFAULT_EVENT_LIMIT, getStripePrices } from "../../lib/const.js";-import { stripe } from "../../lib/stripe.js";+import { getBestSubscription } from "../../lib/subscriptionUtils.js";function getStartOfMonth() {return DateTime.now().startOf("month").toJSDate();@@ -34,86 +33,49 @@ export async function getSubscriptionInner(organizationId: string) {return null;}- if (org.name.includes("AppSumo")) {+ // Get the best subscription (highest event limit from AppSumo or Stripe)+ const subscription = await getBestSubscription(organizationId, org.stripeCustomerId);++ // Format response based on subscription source+ if (subscription.source === "appsumo") {return {id: null,- planName: "free",- status: "active",- eventLimit: 1000000,+ planName: subscription.planName,+ status: subscription.status,currentPeriodEnd: getStartOfNextMonth(),currentPeriodStart: getStartOfMonth(),+ eventLimit: subscription.eventLimit,monthlyEventCount: org.monthlyEventCount || 0,- appSumoPlan: "1m",+ interval: subscription.interval,+ cancelAtPeriodEnd: subscription.cancelAtPeriodEnd,+ isPro: false,};}- // Check if organization has an active Stripe subscription- if (org.stripeCustomerId) {- // 2. List active subscriptions for the customer from Stripe- const subscriptions = await (stripe as Stripe).subscriptions.list({- customer: org.stripeCustomerId,- status: "active", // Only fetch active subscriptions- limit: 1, // Organizations should only have one active subscription- expand: ["data.plan.product"], // Expand to get product details if needed- });-- if (subscriptions.data.length > 0) {- const subscription = subscriptions.data[0];- const subscriptionItem = subscription.items.data[0];-- const priceId = subscriptionItem.price.id;-- if (!priceId) {- throw new Error("Subscription item price ID not found");- }-- // 3. Find corresponding plan details from your constants- const planDetails = getStripePrices().find(plan => plan.priceId === priceId);-- if (!planDetails) {- console.error("Plan details not found for price ID:", priceId);- // Still return the basic subscription info even if local plan details missing- return {- id: subscription.id,- planName: "Unknown Plan", // Indicate missing details- status: subscription.status,- createdAt: new Date(subscription.created * 1000),- currentPeriodStart: new Date(subscriptionItem.current_period_start * 1000),- currentPeriodEnd: new Date(subscriptionItem.current_period_end * 1000),- cancelAtPeriodEnd: subscription.cancel_at_period_end,- eventLimit: 0, // Unknown limit- monthlyEventCount: org.monthlyEventCount || 0,- interval: subscriptionItem.price.recurring?.interval ?? "unknown",- };- }-- // 4. Format and return the subscription data- const responseData = {- id: subscription.id,- planName: planDetails.name,- isPro: planDetails.name.includes("pro"),- status: subscription.status,- createdAt: new Date(subscription.created * 1000),- currentPeriodStart: new Date(subscriptionItem.current_period_start * 1000),- currentPeriodEnd: new Date(subscriptionItem.current_period_end * 1000),- cancelAtPeriodEnd: subscription.cancel_at_period_end,- eventLimit: planDetails.limits.events,- monthlyEventCount: org.monthlyEventCount || 0,- interval: subscriptionItem.price.recurring?.interval ?? "unknown",- };-- return responseData;- }+ if (subscription.source === "stripe") {+ return {+ id: subscription.subscriptionId,+ planName: subscription.planName,+ isPro: subscription.isPro,+ status: subscription.status,+ createdAt: subscription.createdAt,+ currentPeriodStart: DateTime.fromISO(subscription.periodStart).toJSDate(),+ currentPeriodEnd: subscription.currentPeriodEnd,+ cancelAtPeriodEnd: subscription.cancelAtPeriodEnd,+ eventLimit: subscription.eventLimit,+ monthlyEventCount: org.monthlyEventCount || 0,+ interval: subscription.interval,+ };}- // If we get here, the organization has no active paid subscription+ // Free tierreturn {id: null,- planName: "free",- status: "free",+ planName: subscription.planName,+ status: subscription.status,currentPeriodEnd: getStartOfNextMonth(),currentPeriodStart: getStartOfMonth(),- eventLimit: DEFAULT_EVENT_LIMIT,+ eventLimit: subscription.eventLimit,monthlyEventCount: org.monthlyEventCount || 0,trialDaysRemaining: 0,};diff --git a/server/src/db/postgres/initPostgres.ts b/server/src/db/postgres/initPostgres.tsindex 6b6ab073a..0c0103f25 100644--- a/server/src/db/postgres/initPostgres.ts+++ b/server/src/db/postgres/initPostgres.ts@@ -1,4 +1,5 @@-import { asc, eq } from "drizzle-orm";+import { asc, eq, sql } from "drizzle-orm";+import { IS_CLOUD } from "../../lib/const.js";import { db } from "./postgres.js";import { user } from "./schema.js";@@ -11,7 +12,52 @@ export const initPostgres = async () => {// Update the oldest user's role to adminawait db.update(user).set({ role: "admin" }).where(eq(user.id, oldestUser[0].id));}++ // Initialize AppSumo tables in cloud environments only+ if (IS_CLOUD) {+ await initializeAppSumoTables();+ }} catch (error) {console.error("Error initializing postgres:", error);}};++/**+ * Creates AppSumo-specific tables if they don't exist+ * This runs only in cloud environments (IS_CLOUD === true)+ */+async function initializeAppSumoTables() {+ try {+ // Create as_licenses table+ await db.execute(sql`+ CREATE TABLE IF NOT EXISTS as_licenses (+ id SERIAL PRIMARY KEY NOT NULL,+ organization_id TEXT REFERENCES organization(id),+ license_key TEXT NOT NULL UNIQUE,+ tier TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'active',+ parent_license_key TEXT,+ activated_at TIMESTAMP,+ deactivated_at TIMESTAMP,+ created_at TIMESTAMP DEFAULT NOW(),+ updated_at TIMESTAMP DEFAULT NOW()+ )+ `);++ // Create as_webhook_events table for audit trail+ await db.execute(sql`+ CREATE TABLE IF NOT EXISTS as_webhook_events (+ id SERIAL PRIMARY KEY NOT NULL,+ license_key TEXT NOT NULL,+ event TEXT NOT NULL,+ payload TEXT NOT NULL,+ processed_at TIMESTAMP DEFAULT NOW(),+ created_at TIMESTAMP DEFAULT NOW()+ )+ `);++ console.info("AppSumo tables initialized successfully");+ } catch (error) {+ console.error("Error initializing AppSumo tables:", error);+ }+}diff --git a/server/src/db/postgres/schema-appsumo.ts b/server/src/db/postgres/schema-appsumo.tsnew file mode 100644index 000000000..b18b36fca--- /dev/null+++ b/server/src/db/postgres/schema-appsumo.ts@@ -0,0 +1,26 @@+import { pgTable, serial, text, timestamp } from "drizzle-orm/pg-core";+import { organization } from "./schema.js";++// AppSumo licenses table (only created in cloud environments)+export const asLicenses = pgTable("as_licenses", {+ id: serial("id").primaryKey().notNull(),+ organizationId: text("organization_id").references(() => organization.id),+ licenseKey: text("license_key").notNull().unique(),+ tier: text("tier").notNull(), // Tier level from AppSumo (e.g., "1", "2", "3")+ status: text("status").notNull().default("active"), // 'active', 'inactive', 'pending'+ parentLicenseKey: text("parent_license_key"), // For add-on licenses+ activatedAt: timestamp("activated_at", { mode: "string" }),+ deactivatedAt: timestamp("deactivated_at", { mode: "string" }),+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),+});++// Webhook events log for audit trail and idempotency+export const asWebhookEvents = pgTable("as_webhook_events", {+ id: serial("id").primaryKey().notNull(),+ licenseKey: text("license_key").notNull(),+ event: text("event").notNull(), // 'purchase', 'activate', 'upgrade', 'downgrade', 'deactivate', 'migrate'+ payload: text("payload").notNull(), // JSON string of full webhook payload+ processedAt: timestamp("processed_at", { mode: "string" }).defaultNow(),+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),+});diff --git a/server/src/index.ts b/server/src/index.tsindex 3ae8f9a78..922aa5a5d 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -202,6 +202,7 @@ const PUBLIC_ROUTES: string[] = ["/api/auth/callback/google","/api/auth/callback/github","/api/stripe/webhook",+ "/api/as/webhook","/api/session-replay/record","/api/admin/telemetry","/api/site/:siteId/tracking-config",@@ -409,6 +410,13 @@ if (IS_CLOUD) {server.get("/api/admin/sites", getAdminSites);server.get("/api/admin/organizations", getAdminOrganizations);server.post("/api/admin/telemetry", collectTelemetry);++ // AppSumo Routes+ const { activateAppSumoLicense } = await import("./api/as/activate.js");+ const { handleAppSumoWebhook } = await import("./api/as/webhook.js");++ server.post("/api/as/activate", activateAppSumoLicense);+ server.post("/api/as/webhook", handleAppSumoWebhook);}server.post("/track", trackEvent);diff --git a/server/src/lib/const.ts b/server/src/lib/const.tsindex dcf742587..c8a27269f 100644--- a/server/src/lib/const.ts+++ b/server/src/lib/const.ts@@ -14,6 +14,13 @@ export const MAPBOX_TOKEN = process.env.MAPBOX_TOKEN;export const DEFAULT_EVENT_LIMIT = 10_000;+// AppSumo tier limits (lifetime plans with standard features, no replays)+export const APPSUMO_TIER_LIMITS = {+ "1": 20_000,+ "2": 100_000,+ "3": 250_000,+} as const;+// Define a type for the plan objectsexport interface StripePlan {priceId: string;diff --git a/server/src/lib/subscriptionUtils.ts b/server/src/lib/subscriptionUtils.tsnew file mode 100644index 000000000..f908eea60--- /dev/null+++ b/server/src/lib/subscriptionUtils.ts@@ -0,0 +1,207 @@+import { sql } from "drizzle-orm";+import { DateTime } from "luxon";+import Stripe from "stripe";+import { db } from "../db/postgres/postgres.js";+import { APPSUMO_TIER_LIMITS, DEFAULT_EVENT_LIMIT, getStripePrices, StripePlan } from "./const.js";+import { stripe } from "./stripe.js";++export interface AppSumoSubscriptionInfo {+ source: "appsumo";+ tier: string;+ eventLimit: number;+ periodStart: string;+ planName: string;+ status: "active";+ interval: "lifetime";+ cancelAtPeriodEnd: false;+ isPro: false;+}++export interface StripeSubscriptionInfo {+ source: "stripe";+ subscriptionId: string;+ priceId: string;+ planName: string;+ eventLimit: number;+ periodStart: string;+ currentPeriodEnd: Date;+ status: string;+ interval: string;+ cancelAtPeriodEnd: boolean;+ isPro: boolean;+ createdAt: Date;+}++export interface FreeSubscriptionInfo {+ source: "free";+ eventLimit: number;+ periodStart: string;+ planName: "free";+ status: "free";+}++export type SubscriptionInfo = AppSumoSubscriptionInfo | StripeSubscriptionInfo | FreeSubscriptionInfo;++/**+ * Gets the first day of the current month in YYYY-MM-DD format+ */+function getStartOfMonth(): string {+ return DateTime.now().startOf("month").toISODate() as string;+}++/**+ * Gets AppSumo subscription info for an organization+ * @returns AppSumo subscription info or null if no active license found+ */+export async function getAppSumoSubscription(organizationId: string): Promise<AppSumoSubscriptionInfo | null> {+ try {+ const appsumoLicense = await db.execute(+ sql`SELECT tier, status FROM as_licenses WHERE organization_id = ${organizationId} AND status = 'active' LIMIT 1`+ );++ if (Array.isArray(appsumoLicense) && appsumoLicense.length > 0) {+ const license = appsumoLicense[0] as any;+ const tier = license.tier as keyof typeof APPSUMO_TIER_LIMITS;+ const eventLimit = APPSUMO_TIER_LIMITS[tier] || APPSUMO_TIER_LIMITS["1"];++ return {+ source: "appsumo",+ tier,+ eventLimit,+ periodStart: getStartOfMonth(),+ planName: `appsumo-${tier}`,+ status: "active",+ interval: "lifetime",+ cancelAtPeriodEnd: false,+ isPro: false,+ };+ }++ return null;+ } catch (error) {+ console.error("Error checking AppSumo license:", error);+ return null;+ }+}++/**+ * Gets Stripe subscription info for an organization+ * @returns Stripe subscription info or null if no active subscription found+ */+export async function getStripeSubscription(+ stripeCustomerId: string | null+): Promise<StripeSubscriptionInfo | null> {+ if (!stripeCustomerId) {+ return null;+ }++ try {+ const subscriptions = await (stripe as Stripe).subscriptions.list({+ customer: stripeCustomerId,+ status: "active",+ limit: 1,+ expand: ["data.plan.product"],+ });++ if (subscriptions.data.length === 0) {+ return null;+ }++ const subscription = subscriptions.data[0];+ const subscriptionItem = subscription.items.data[0];+ const priceId = subscriptionItem.price.id;++ if (!priceId) {+ console.error("Subscription item price ID not found");+ return null;+ }++ // Find corresponding plan details from constants+ const planDetails = getStripePrices().find((plan: StripePlan) => plan.priceId === priceId);++ if (!planDetails) {+ console.error("Plan details not found for price ID:", priceId);+ // Return basic info even without plan details+ return {+ source: "stripe",+ subscriptionId: subscription.id,+ priceId,+ planName: "Unknown Plan",+ eventLimit: 0,+ periodStart: getStartOfMonth(),+ currentPeriodEnd: new Date(subscriptionItem.current_period_end * 1000),+ status: subscription.status,+ interval: subscriptionItem.price.recurring?.interval ?? "unknown",+ cancelAtPeriodEnd: subscription.cancel_at_period_end,+ isPro: false,+ createdAt: new Date(subscription.created * 1000),+ };+ }++ // Determine period start+ const currentMonthStart = DateTime.now().startOf("month");+ const subscriptionStartDate = DateTime.fromSeconds(subscriptionItem.current_period_start);++ // If subscription started within current month, use that date; otherwise use month start+ const periodStart =+ subscriptionStartDate >= currentMonthStart+ ? subscriptionStartDate.toISODate() as string+ : getStartOfMonth();++ return {+ source: "stripe",+ subscriptionId: subscription.id,+ priceId,+ planName: planDetails.name,+ eventLimit: planDetails.limits.events,+ periodStart,+ currentPeriodEnd: new Date(subscriptionItem.current_period_end * 1000),+ status: subscription.status,+ interval: subscriptionItem.price.recurring?.interval ?? "unknown",+ cancelAtPeriodEnd: subscription.cancel_at_period_end,+ isPro: planDetails.name.includes("pro"),+ createdAt: new Date(subscription.created * 1000),+ };+ } catch (error) {+ console.error("Error fetching Stripe subscription:", error);+ return null;+ }+}++/**+ * Gets the best subscription for an organization (highest event limit)+ * Checks both AppSumo and Stripe subscriptions and returns the one with the higher limit+ * @returns The subscription with the highest event limit, or free tier if none found+ */+export async function getBestSubscription(+ organizationId: string,+ stripeCustomerId: string | null+): Promise<SubscriptionInfo> {+ // Get both subscription types+ const [appsumoSub, stripeSub] = await Promise.all([+ getAppSumoSubscription(organizationId),+ getStripeSubscription(stripeCustomerId),+ ]);++ // If we have both, return the one with higher event limit+ if (appsumoSub && stripeSub) {+ const bestSub = appsumoSub.eventLimit >= stripeSub.eventLimit ? appsumoSub : stripeSub;+ console.log(+ `Organization has both AppSumo (${appsumoSub.eventLimit} events) and Stripe (${stripeSub.eventLimit} events). Using ${bestSub.source} with ${bestSub.eventLimit} events.`+ );+ return bestSub;+ }++ // Return whichever one exists+ if (appsumoSub) return appsumoSub;+ if (stripeSub) return stripeSub;++ // Default to free tier+ return {+ source: "free",+ eventLimit: DEFAULT_EVENT_LIMIT,+ periodStart: getStartOfMonth(),+ planName: "free",+ status: "free",+ };+}diff --git a/server/src/services/usageService.ts b/server/src/services/usageService.tsindex c69828c31..0760f4b1c 100644--- a/server/src/services/usageService.ts+++ b/server/src/services/usageService.ts@@ -1,15 +1,14 @@import { and, eq } from "drizzle-orm";import { DateTime } from "luxon";import * as cron from "node-cron";-import Stripe from "stripe";import { processResults } from "../api/analytics/utils.js";import { clickhouse } from "../db/clickhouse/clickhouse.js";import { db } from "../db/postgres/postgres.js";import { member, organization, sites, user } from "../db/postgres/schema.js";-import { DEFAULT_EVENT_LIMIT, getStripePrices, IS_CLOUD, StripePlan } from "../lib/const.js";+import { IS_CLOUD } from "../lib/const.js";import { sendLimitExceededEmail } from "../lib/email/email.js";import { createServiceLogger } from "../lib/logger/logger.js";-import { stripe } from "../lib/stripe.js";+import { getBestSubscription } from "../lib/subscriptionUtils.js";class UsageService {private sitesOverLimit = new Set<number>();@@ -104,8 +103,8 @@ class UsageService {}/**- * Gets event limit and billing period start date for an organization based on their Stripe subscription.- * Fetches directly from Stripe if the organization has a stripeCustomerId.+ * Gets event limit and billing period start date for an organization based on their best subscription.+ * Checks both AppSumo and Stripe subscriptions and uses the one with the higher event limit.* @returns [eventLimit, periodStartDate]*/private async getOrganizationSubscriptionInfo(orgData: {@@ -114,82 +113,28 @@ class UsageService {createdAt: string;name: string;}): Promise<[number, string | null]> {+ // Special case for specific organizationsif (orgData.name === "tomato 2" || orgData.name === "Zam") {return [Infinity, this.getStartOfMonth()];}- if (orgData.name.includes("AppSumo")) {- return [1000000, this.getStartOfMonth()];- }- if (!orgData.stripeCustomerId) {- // No Stripe customer ID, use default limit and start of current month- return [DEFAULT_EVENT_LIMIT, this.getStartOfMonth()];- }-- try {- // Fetch active subscriptions for the customer from Stripe- const subscriptions = await (stripe as Stripe).subscriptions.list({- customer: orgData.stripeCustomerId,- status: "active",- limit: 1,- });-- if (subscriptions.data.length === 0) {- return [DEFAULT_EVENT_LIMIT, this.getStartOfMonth()];- }-- const subscription = subscriptions.data[0];- const subscriptionItem = subscription.items.data[0];-- const priceId = subscriptionItem.price.id;-- if (!priceId) {- this.logger.error(- `Subscription item price ID not found for organization ${orgData.id}, sub ${subscription.id}`- );- return [DEFAULT_EVENT_LIMIT, this.getStartOfMonth()];- }-- // Find corresponding plan details from constants- const planDetails = getStripePrices().find((plan: StripePlan) => plan.priceId === priceId);-- // Get the event limit from the plan- const eventLimit = planDetails- ? planDetails.limits.events // This is already the monthly event limit, regardless of billing interval- : DEFAULT_EVENT_LIMIT;-- // For the period start, we need to handle several cases:- const currentMonthStart = this.getStartOfMonth();- let periodStart = currentMonthStart;- if (subscriptionItem.current_period_start) {- // Convert subscription start timestamp to DateTime- const subscriptionStartDate = DateTime.fromSeconds(subscriptionItem.current_period_start);- const currentMonth = DateTime.now().startOf("month");+ // Get the best subscription (highest event limit from AppSumo or Stripe)+ const subscription = await getBestSubscription(orgData.id, orgData.stripeCustomerId);- // If the subscription started within the current month, use that as the start date- // This ensures we don't count events from before they subscribed (e.g., during their free trial)- if (subscriptionStartDate >= currentMonth) {- periodStart = subscriptionStartDate.toISODate() as string;- this.logger.info(- `Organization ${orgData.name} subscribed during current month on ${periodStart}. Using subscription start date for counting.`- );- } else {- this.logger.info(- `Organization ${orgData.name} subscription started before current month. Using month start for counting.`- );- }- }-- // Include subscription info for logging purposes- const interval = subscriptionItem.price.recurring?.interval || "unknown";- this.logger.info(`Organization ${orgData.name} has a ${interval} subscription.`);-- return [eventLimit, periodStart];- } catch (error: any) {- this.logger.error(error as Error, `Error fetching Stripe subscription info for organization ${orgData.name}`);- // Fallback to default limit and current month start on Stripe API error- return [DEFAULT_EVENT_LIMIT, this.getStartOfMonth()];+ // Log subscription details+ if (subscription.source === "appsumo") {+ this.logger.info(+ `Organization ${orgData.name} using AppSumo ${subscription.planName} with ${subscription.eventLimit} events/month`+ );+ } else if (subscription.source === "stripe") {+ this.logger.info(+ `Organization ${orgData.name} using Stripe ${subscription.planName} (${subscription.interval}) with ${subscription.eventLimit} events/month`+ );+ } else {+ this.logger.info(`Organization ${orgData.name} on free tier with ${subscription.eventLimit} events/month`);}++ return [subscription.eventLimit, subscription.periodStart];}/**