Skip to content
Merged
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 @@ -108,6 +108,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 @@ -47,16 +47,13 @@ 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')
);
}, []);
const isLocal = process.env.NODE_ENV !== 'production';

// Internal-only: fast-path to complete onboarding (not exposed to customers)
const canSkipOnboarding = useMemo(() => {
if (!userEmail) return false;
return userEmail.endsWith('@trycomp.ai');
}, [userEmail]);
Copy link

Choose a reason for hiding this comment

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

Case-sensitive mismatch in internal team email checks

The canSkipOnboarding check uses userEmail.endsWith('@trycomp.ai') which is case-sensitive, while the upgrade page's isTrycompEmail check uses extractDomain which lowercases the email domain before comparison. For an email like User@TryComp.AI, the upgrade page would auto-approve the organization (domain becomes trycomp.ai), but the onboarding page would not show the skip button (case-sensitive endsWith fails). This creates inconsistent behavior for the same internal team feature.

Additional Locations (1)

Fix in Cursor Fix in Web


// Check if current step has valid input
const currentStepValue = form.watch(step?.key);
Expand Down Expand Up @@ -217,7 +214,7 @@ export function PostPaymentOnboarding({
</motion.div>
)}
</AnimatePresence>
{isLocal && (
{(isLocal || canSkipOnboarding) && (
<motion.div
key="complete-now"
initial={{ opacity: 0, x: 20 }}
Expand Down
34 changes: 33 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, isPublicEmailDomain } from '@/lib/stripe';
import { auth } from '@/utils/auth';
import { db } from '@db';
import { headers } from 'next/headers';
Expand Down Expand Up @@ -39,7 +40,38 @@ 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 userEmailDomain = extractDomain(userEmail ?? '');
const orgWebsiteDomain = extractDomain(member.organization.website ?? '');

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

const canAutoApproveViaDomain =
!isTrycompEmail &&
Boolean(orgWebsiteDomain) &&
userEmailDomain === orgWebsiteDomain &&
!isPublicEmailDomain(userEmailDomain);

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

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

// If user has access to org but hasn't completed onboarding, redirect to onboarding
if (hasAccess && !member.organization.onboardingCompleted) {
Expand Down
2 changes: 0 additions & 2 deletions apps/app/src/app/posthog.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
'use server';

import { Properties } from 'posthog-js';
import { PostHog } from 'posthog-node';

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 @@ -44,6 +44,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 @@ -111,6 +112,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
186 changes: 186 additions & 0 deletions apps/app/src/lib/stripe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
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');
}

// Domains that should NEVER be used for domain-based auto-approval.
// These are shared/public mailbox providers where domain ownership does not imply company affiliation.
const PUBLIC_EMAIL_DOMAINS = new Set([
// Google
'gmail.com',
'googlemail.com',
// Microsoft
'outlook.com',
'hotmail.com',
'live.com',
'msn.com',
// Yahoo
'yahoo.com',
'ymail.com',
// Apple
'icloud.com',
'me.com',
'mac.com',
// Proton
'proton.me',
'protonmail.com',
'pm.me',
// AOL
'aol.com',
]);

export const isPublicEmailDomain = (domain: string): boolean => {
const normalized = domain.toLowerCase().trim().replace(/\.$/, '');
return PUBLIC_EMAIL_DOMAINS.has(normalized);
};

export const stripe = stripeSecretKey
? new Stripe(stripeSecretKey, {
apiVersion: '2025-12-15.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().replace(/\.$/, '');

// Defense-in-depth: never treat public mailbox domains as proof of company ownership.
if (isPublicEmailDomain(normalizedDomain)) {
return null;
}

try {
// Prefer exact domain match via metadata when available.
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,
};
}

// Fallback: Stripe's email~ operator is substring matching; post-filter for exact email domain.
const customers = await stripe.customers.search({
query: `email~"@${normalizedDomain}"`,
limit: 25,
});

const exactDomainCustomer = customers.data.find((customer) => {
const email = customer.email ?? '';
const emailDomain = email.split('@')[1]?.toLowerCase().trim() ?? '';
return emailDomain === normalizedDomain;
});

if (exactDomainCustomer) {
return {
customerId: exactDomainCustomer.id,
customerName: exactDomainCustomer.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 normalizedDomain = domain.toLowerCase().trim().replace(/\.$/, '');

if (!normalizedDomain) {
return false;
}

// Never auto-approve based on public email domains.
if (isPublicEmailDomain(normalizedDomain)) {
return false;
}

const customer = await findStripeCustomerByDomain(normalizedDomain);

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;
}
};
Loading
Loading