Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
"remark-parse": "^11.0.0",
"resend": "^4.4.1",
"sonner": "^2.0.5",
"stripe": "^20.0.0",
"swr": "^2.3.4",
"three": "^0.177.0",
"ts-pattern": "^5.7.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,11 @@ export function PostPaymentOnboarding({
userEmail,
});

const isLocal = useMemo(() => {
if (typeof window === 'undefined') return false;
const host = window.location.host || '';
return (
process.env.NODE_ENV !== 'production' ||
host.includes('localhost') ||
host.startsWith('127.0.0.1') ||
host.startsWith('::1')
);
}, []);
// Only show skip button for internal team members
const canSkipOnboarding = useMemo(() => {
if (!userEmail) return false;
return userEmail.endsWith('@trycomp.ai');
}, [userEmail]);

// Check if current step has valid input
const currentStepValue = form.watch(step?.key);
Expand Down Expand Up @@ -193,7 +188,7 @@ export function PostPaymentOnboarding({
</motion.div>
)}
</AnimatePresence>
{isLocal && (
{canSkipOnboarding && (
<motion.div
key="complete-now"
initial={{ opacity: 0, x: 20 }}
Expand Down
27 changes: 26 additions & 1 deletion apps/app/src/app/(app)/upgrade/[orgId]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { extractDomain, isDomainActiveStripeCustomer } from '@/lib/stripe';
import { auth } from '@/utils/auth';
import { db } from '@db';
import { headers } from 'next/headers';
Expand Down Expand Up @@ -39,7 +40,31 @@ export default async function UpgradePage({ params }: PageProps) {
redirect('/');
}

const hasAccess = member.organization.hasAccess;
let hasAccess = member.organization.hasAccess;

// Auto-approve based on user's email domain
if (!hasAccess) {
const userEmail = authSession.user.email;
const emailDomain = extractDomain(userEmail ?? '');

if (emailDomain) {
// Auto-approve for trycomp.ai emails (internal team)
const isTrycompEmail = emailDomain === 'trycomp.ai';

// Check Stripe for other domains
const isStripeCustomer = isTrycompEmail
? false
: await isDomainActiveStripeCustomer(emailDomain);

if (isTrycompEmail || isStripeCustomer) {
await db.organization.update({
where: { id: orgId },
data: { hasAccess: true },
});
hasAccess = true;
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Domain-based access grants for common email providers

The auto-approval logic in isDomainActiveStripeCustomer grants access based solely on matching the user's email domain with any Stripe customer's email domain. This means users with common email domains like gmail.com, yahoo.com, or outlook.com could gain unauthorized access to any organization they're a member of, if any existing Stripe customer uses the same email provider. The domain check doesn't verify the user actually belongs to the paying organization, only that someone with the same email domain has an active subscription somewhere.

Additional Locations (1)

Fix in Cursor Fix in Web

}

// If user has access to org but hasn't completed onboarding, redirect to onboarding
if (hasAccess && !member.organization.onboardingCompleted) {
Expand Down
2 changes: 2 additions & 0 deletions apps/app/src/env.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export const env = createEnv({
GA4_MEASUREMENT_ID: z.string().optional(),
LINKEDIN_CONVERSIONS_ACCESS_TOKEN: z.string().optional(),
NOVU_API_KEY: z.string().optional(),
STRIPE_SECRET_KEY: z.string().optional(),
},

client: {
Expand Down Expand Up @@ -107,6 +108,7 @@ export const env = createEnv({
NEXT_PUBLIC_BETTER_AUTH_URL: process.env.NEXT_PUBLIC_BETTER_AUTH_URL,
NOVU_API_KEY: process.env.NOVU_API_KEY,
NEXT_PUBLIC_NOVU_APPLICATION_IDENTIFIER: process.env.NEXT_PUBLIC_NOVU_APPLICATION_IDENTIFIER,
STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
},

skipValidation: !!process.env.CI || !!process.env.SKIP_ENV_VALIDATION,
Expand Down
136 changes: 136 additions & 0 deletions apps/app/src/lib/stripe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { env } from '@/env.mjs';
import Stripe from 'stripe';

// Initialize Stripe client with secret key from environment
const stripeSecretKey = env.STRIPE_SECRET_KEY;

if (!stripeSecretKey) {
console.warn('STRIPE_SECRET_KEY is not set - Stripe auto-approval will be disabled');
}

export const stripe = stripeSecretKey
? new Stripe(stripeSecretKey, {
apiVersion: '2025-11-17.clover',
})
: null;

/**
* Extract domain from a website URL or email
* @param input - URL (e.g., "https://example.com") or email (e.g., "user@example.com")
* @returns Normalized domain (e.g., "example.com")
*/
export const extractDomain = (input: string): string | null => {
if (!input) return null;

try {
// If it looks like an email, extract domain from after @
if (input.includes('@') && !input.includes('://')) {
const domain = input.split('@')[1]?.toLowerCase().trim();
return domain || null;
}

// Otherwise, treat as URL
let url = input.trim().toLowerCase();

// Add protocol if missing
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = `https://${url}`;
}

const parsed = new URL(url);
return parsed.hostname.replace(/^www\./, '');
} catch {
return null;
}
};

/**
* Check if a domain belongs to an existing Stripe customer
* Searches by customer email domain and metadata
*
* @param domain - The domain to check (e.g., "acme.com")
* @returns Customer ID if found, null otherwise
*/
export const findStripeCustomerByDomain = async (
domain: string,
): Promise<{ customerId: string; customerName: string | null } | null> => {
if (!stripe) {
console.warn('Stripe client not initialized - skipping customer lookup');
return null;
}

if (!domain) {
return null;
}

const normalizedDomain = domain.toLowerCase().trim();

try {
// Search for customers with emails matching this domain
// Stripe's search supports email domain matching
const customers = await stripe.customers.search({
query: `email~"@${normalizedDomain}"`,
limit: 1,
});

if (customers.data.length > 0) {
const customer = customers.data[0];
return {
customerId: customer.id,
customerName: customer.name ?? null,
};
}

// Fallback: Check customers with domain in metadata
// This handles cases where customer email might not match company domain
const customersWithMetadata = await stripe.customers.search({
query: `metadata["domain"]:"${normalizedDomain}"`,
limit: 1,
});

if (customersWithMetadata.data.length > 0) {
const customer = customersWithMetadata.data[0];
return {
customerId: customer.id,
customerName: customer.name ?? null,
};
}

return null;
} catch (error) {
console.error('Error searching Stripe customers:', error);
return null;
}
};

/**
* Check if a domain is an active Stripe customer with a valid subscription
*
* @param domain - The domain to check
* @returns true if domain has an active subscription
*/
export const isDomainActiveStripeCustomer = async (domain: string): Promise<boolean> => {
const customer = await findStripeCustomerByDomain(domain);

if (!customer) {
return false;
}

if (!stripe) {
return false;
}

try {
// Check if customer has an active subscription
const subscriptions = await stripe.subscriptions.list({
customer: customer.customerId,
status: 'active',
limit: 1,
});

return subscriptions.data.length > 0;
} catch (error) {
console.error('Error checking Stripe subscriptions:', error);
return false;
}
};
3 changes: 3 additions & 0 deletions bun.lock
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@
"remark-parse": "^11.0.0",
"resend": "^4.4.1",
"sonner": "^2.0.5",
"stripe": "^20.0.0",
"swr": "^2.3.4",
"three": "^0.177.0",
"ts-pattern": "^5.7.0",
Expand Down Expand Up @@ -5098,6 +5099,8 @@

"strip-literal": ["strip-literal@3.1.0", "", { "dependencies": { "js-tokens": "^9.0.1" } }, "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg=="],

"stripe": ["stripe@20.0.0", "", { "dependencies": { "qs": "^6.11.0" }, "peerDependencies": { "@types/node": ">=16" }, "optionalPeers": ["@types/node"] }, "sha512-EaZeWpbJOCcDytdjKSwdrL5BxzbDGNueiCfHjHXlPdBQvLqoxl6AAivC35SPzTmVXJb5duXQlXFGS45H0+e6Gg=="],

"strnum": ["strnum@2.1.1", "", {}, "sha512-7ZvoFTiCnGxBtDqJ//Cu6fWtZtc7Y3x+QOirG15wztbdngGSkht27o2pyGWrVy0b4WAy3jbKmnoK6g5VlVNUUw=="],

"strtok3": ["strtok3@10.3.4", "", { "dependencies": { "@tokenizer/token": "^0.3.0" } }, "sha512-KIy5nylvC5le1OdaaoCJ07L+8iQzJHGH6pWDuzS+d07Cu7n1MZ2x26P8ZKIWfbK02+XIL8Mp4RkWeqdUCrDMfg=="],
Expand Down