import { createHash, randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; import Stripe from "stripe"; import { getDb } from "@/db"; import { subscriptions, type User } from "@/db/schema"; import { ApiError } from "./api"; import { appUrl } from "./app-url"; import { localCheckout } from "@/lib/public-local-account"; type SubscriptionShape = { id: string; customer: string | { id: string }; status: string; cancel_at_period_end?: boolean; current_period_start?: number; current_period_end?: number; items?: { data?: Array<{ price?: { id?: string } }> }; metadata?: { userId?: string }; }; let stripeClient: Stripe | undefined; const STRIPE_TEST_AMOUNT_MINOR = 2999; const STRIPE_TEST_CURRENCY = "USD"; const STRIPE_TEST_PRODUCT_NAME = "LinkedIn Premium Career (Test Mode)"; const STRIPE_TEST_PRICE_ID = "price_linkedin_premium_test_2999"; function providerPriceId() { const value = process.env.LINKEDIN_STRIPE_TEST_PRICE_ID ?? ""; if (!/^price_[A-Za-z0-9_]{8,240}$/u.test(value)) { throw new ApiError(503, "Stripe test pricing is not configured.", "stripe_price_not_configured"); } return value; } export function publicBillingDisabled() { return process.env.PUBLIC_DEPLOYMENT_DISABLE_STRIPE === "true"; } function localBillingFallbackEnabled() { return process.env.PUBLIC_BILLING_ALLOW_LOCAL_FALLBACK === "true"; } function assertPublicBillingEnabled() { if (publicBillingDisabled()) { throw new ApiError( 503, "Premium checkout is unavailable in this public review deployment.", "billing_not_available", ); } } function sha256(value: string) { return createHash("sha256").update(value).digest("hex"); } function stripeTestProxyUrl() { const raw = process.env.STRIPE_TEST_PROXY_URL; if (!raw) return null; const parsed = new URL(raw); if ( parsed.protocol !== "http:" || parsed.hostname !== "stripe.internal" || parsed.port || parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash ) { throw new ApiError(503, "Stripe Test Mode proxy is not configured safely.", "stripe_proxy_invalid"); } return parsed.origin; } type StripeTestCheckoutSession = { id: string; url?: string | null; mode: "subscription"; status: "open" | "complete" | "expired"; payment_status: "paid" | "unpaid" | "no_payment_required"; amount_total: number; currency: string; livemode: false; customer?: string | null; payment_intent?: string | null; subscription?: string | null; client_reference_id?: string | null; metadata: Record; }; function validateStripeTestCheckout( payload: StripeTestCheckoutSession | { error?: string } | null, userId: string, expectedSessionId?: string, ) { if (!payload || !("id" in payload)) { throw new ApiError(502, "Stripe returned an invalid Checkout Session.", "stripe_test_response_invalid"); } const flowId = payload.metadata?.flow_id ?? ""; const fingerprint = sha256(`linkedin\n${userId}\n${flowId}\n${STRIPE_TEST_AMOUNT_MINOR}\n${STRIPE_TEST_CURRENCY}`); if ( !/^cs_test_[A-Za-z0-9_]{8,240}$/u.test(payload.id) || (expectedSessionId && payload.id !== expectedSessionId) || payload.mode !== "subscription" || !["open", "complete", "expired"].includes(payload.status) || !["paid", "unpaid", "no_payment_required"].includes(payload.payment_status) || payload.livemode !== false || payload.amount_total !== STRIPE_TEST_AMOUNT_MINOR || payload.currency.toUpperCase() !== STRIPE_TEST_CURRENCY || payload.client_reference_id !== flowId || !/^[0-9a-f]{64}$/u.test(flowId) || payload.metadata?.site_id !== "linkedin" || payload.metadata?.owner !== userId || payload.metadata?.amount_minor !== String(STRIPE_TEST_AMOUNT_MINOR) || payload.metadata?.currency !== STRIPE_TEST_CURRENCY || payload.metadata?.is_simulation !== "true" || payload.metadata?.fingerprint !== fingerprint ) { throw new ApiError(502, "Stripe returned an invalid Checkout Session.", "stripe_test_response_invalid"); } return payload; } async function retrieveStripeTestCheckout(proxyUrl: string, sessionId: string) { const response = await fetch(`${proxyUrl}/v1/checkout/sessions/${encodeURIComponent(sessionId)}`, { headers: { Accept: "application/json" }, }); const payload = await response.json().catch(() => null) as StripeTestCheckoutSession | { error?: string } | null; if (!response.ok) { throw new ApiError(502, payload && "error" in payload ? payload.error ?? "Unable to verify Stripe Checkout." : "Unable to verify Stripe Checkout.", "stripe_checkout_verification_failed"); } return payload; } async function activateStripeTestCheckout( existing: typeof subscriptions.$inferSelect, session: StripeTestCheckoutSession, ) { const now = new Date(); const ownerHash = sha256(`linkedin-checkout-owner\n${existing.userId}`); const customerId = session.customer && /^cus_[A-Za-z0-9_]{8,240}$/u.test(session.customer) ? session.customer : `cus_checkout_${ownerHash.slice(0, 24)}`; const paymentReference = session.subscription && /^sub_[A-Za-z0-9_]{8,240}$/u.test(session.subscription) ? session.subscription : session.payment_intent && /^pi_[A-Za-z0-9_]{8,240}$/u.test(session.payment_intent) ? session.payment_intent : `pay_checkout_${sha256(session.id).slice(0, 24)}`; const [updated] = await getDb().update(subscriptions).set({ stripeCustomerId: customerId, stripeSubscriptionId: paymentReference, stripePriceId: STRIPE_TEST_PRICE_ID, status: "active", currentPeriodStart: now, currentPeriodEnd: new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000), cancelAtPeriodEnd: false, checkoutSessionId: session.id, updatedAt: now, }).where(eq(subscriptions.id, existing.id)).returning(); return updated; } async function createStripeTestCheckout(user: Pick, proxyUrl: string) { const db = getDb(); const [existing] = await db.select().from(subscriptions).where(eq(subscriptions.userId, user.id)).limit(1); if (existing && ["active", "trialing"].includes(existing.status)) { return `${appUrl()}/premium`; } const flowId = sha256(`linkedin-premium-checkout\n${user.id}\n${randomUUID()}`); const fingerprint = sha256(`linkedin\n${user.id}\n${flowId}\n${STRIPE_TEST_AMOUNT_MINOR}\n${STRIPE_TEST_CURRENCY}`); const expiresAt = Math.floor(Date.now() / 1000) + 30 * 60; const fields = new URLSearchParams([ ["mode", "subscription"], ["payment_method_types[0]", "card"], ["name_collection[individual][enabled]", "true"], ["wallet_options[link][display]", "never"], ["customer_email", user.email], ["success_url", `${appUrl()}/premium?session_id={CHECKOUT_SESSION_ID}`], ["cancel_url", `${appUrl()}/premium?cancelled=1&session_id={CHECKOUT_SESSION_ID}`], ["client_reference_id", flowId], ["expires_at", String(expiresAt)], ["metadata[site_id]", "linkedin"], ["metadata[flow_id]", flowId], ["metadata[owner]", user.id], ["metadata[amount_minor]", String(STRIPE_TEST_AMOUNT_MINOR)], ["metadata[currency]", STRIPE_TEST_CURRENCY], ["metadata[fingerprint]", fingerprint], ["metadata[is_simulation]", "true"], ["line_items[0][price_data][currency]", STRIPE_TEST_CURRENCY.toLowerCase()], ["line_items[0][price_data][unit_amount]", String(STRIPE_TEST_AMOUNT_MINOR)], ["line_items[0][price_data][product_data][name]", STRIPE_TEST_PRODUCT_NAME], ["line_items[0][price_data][recurring][interval]", "month"], ["line_items[0][quantity]", "1"], ]); const response = await fetch(`${proxyUrl}/v1/checkout/sessions`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "Idempotency-Key": `linkedin-checkout-${flowId.slice(0, 48)}`, }, body: fields.toString(), }); const payload = await response.json().catch(() => null) as StripeTestCheckoutSession | { error?: string } | null; if (!response.ok) { throw new ApiError(502, payload && "error" in payload ? payload.error ?? "Unable to open Stripe Checkout." : "Unable to open Stripe Checkout.", "stripe_checkout_unavailable"); } const session = validateStripeTestCheckout(payload, user.id); if (session.status !== "open" || session.payment_status !== "unpaid" || !session.url) { throw new ApiError(502, "Stripe Checkout did not return an unpaid session.", "stripe_checkout_unavailable"); } const checkoutUrl = new URL(session.url); if (checkoutUrl.protocol !== "https:" || checkoutUrl.hostname !== "checkout.stripe.com" || checkoutUrl.username || checkoutUrl.password) { throw new ApiError(502, "Stripe Checkout returned an invalid hosted URL.", "stripe_checkout_unavailable"); } const values = { stripeCustomerId: null, stripeSubscriptionId: null, stripePriceId: STRIPE_TEST_PRICE_ID, status: "incomplete", currentPeriodStart: null, currentPeriodEnd: null, cancelAtPeriodEnd: false, checkoutSessionId: session.id, updatedAt: new Date(), }; if (existing) await db.update(subscriptions).set(values).where(eq(subscriptions.id, existing.id)); else await db.insert(subscriptions).values({ userId: user.id, ...values }); return session.url; } async function createDirectStripeTestCheckout(user: Pick) { const db = getDb(); const [existing] = await db.select().from(subscriptions).where(eq(subscriptions.userId, user.id)).limit(1); if (existing && ["active", "trialing"].includes(existing.status)) { return `${appUrl()}/premium`; } const flowId = sha256(`linkedin-premium-checkout\n${user.id}\n${randomUUID()}`); const fingerprint = sha256(`linkedin\n${user.id}\n${flowId}\n${STRIPE_TEST_AMOUNT_MINOR}\n${STRIPE_TEST_CURRENCY}`); const sessionResponse = await getStripe().checkout.sessions.create({ mode: "subscription", payment_method_types: ["card"], name_collection: { individual: { enabled: true } }, wallet_options: { link: { display: "never" } }, customer_email: user.email, success_url: `${appUrl()}/premium?session_id={CHECKOUT_SESSION_ID}`, cancel_url: `${appUrl()}/premium?cancelled=1&session_id={CHECKOUT_SESSION_ID}`, client_reference_id: flowId, expires_at: Math.floor(Date.now() / 1000) + 30 * 60, metadata: { site_id: "linkedin", flow_id: flowId, owner: user.id, amount_minor: String(STRIPE_TEST_AMOUNT_MINOR), currency: STRIPE_TEST_CURRENCY, fingerprint, is_simulation: "true", }, line_items: [{ price_data: { currency: STRIPE_TEST_CURRENCY.toLowerCase(), unit_amount: STRIPE_TEST_AMOUNT_MINOR, product_data: { name: STRIPE_TEST_PRODUCT_NAME }, recurring: { interval: "month" }, }, quantity: 1, }], }, { idempotencyKey: `linkedin-checkout-${flowId.slice(0, 48)}` }); const session = validateStripeTestCheckout( sessionResponse as unknown as StripeTestCheckoutSession, user.id, ); if (session.status !== "open" || session.payment_status !== "unpaid" || !session.url) { throw new ApiError(502, "Stripe Checkout did not return an unpaid session.", "stripe_checkout_unavailable"); } const checkoutUrl = new URL(session.url); if (checkoutUrl.protocol !== "https:" || checkoutUrl.hostname !== "checkout.stripe.com" || checkoutUrl.username || checkoutUrl.password) { throw new ApiError(502, "Stripe Checkout returned an invalid hosted URL.", "stripe_checkout_unavailable"); } const values = { stripeCustomerId: null, stripeSubscriptionId: null, stripePriceId: STRIPE_TEST_PRICE_ID, status: "incomplete", currentPeriodStart: null, currentPeriodEnd: null, cancelAtPeriodEnd: false, checkoutSessionId: session.id, updatedAt: new Date(), }; if (existing) await db.update(subscriptions).set(values).where(eq(subscriptions.id, existing.id)); else await db.insert(subscriptions).values({ userId: user.id, ...values }); return session.url; } export async function completeStripeTestCheckout(userId: string, sessionId: string) { assertPublicBillingEnabled(); const proxyUrl = stripeTestProxyUrl(); if (!/^cs_test_[A-Za-z0-9_]{8,240}$/u.test(sessionId)) { throw new ApiError(400, "Invalid Stripe Checkout Session.", "stripe_checkout_invalid"); } const [existing] = await getDb().select().from(subscriptions).where(eq(subscriptions.userId, userId)).limit(1); if (!existing || existing.checkoutSessionId !== sessionId) { throw new ApiError(404, "Stripe Checkout Session was not found for this account.", "stripe_checkout_missing"); } if (["active", "trialing"].includes(existing.status)) return existing; const payload = proxyUrl ? await retrieveStripeTestCheckout(proxyUrl, sessionId) : await getStripe().checkout.sessions.retrieve(sessionId) as unknown as StripeTestCheckoutSession; const session = validateStripeTestCheckout(payload, userId, sessionId); if (session.status !== "complete" || session.payment_status !== "paid") { throw new ApiError(409, "Complete payment in Stripe before activating Premium.", "stripe_checkout_unpaid"); } return activateStripeTestCheckout(existing, session); } type StripeCardSetupIntent = { id: string; client_secret?: string | null; status: string; customer?: string | null; payment_method?: string | null; usage?: string; livemode: false; metadata: Record; }; type StripeCardSubscription = { id: string; status: string; customer: string; default_payment_method?: string | null; livemode: false; metadata: Record; }; function cardFlowMetadata(userId: string, flowId: string) { return { site_id: "linkedin", owner: userId, flow_id: flowId, amount_minor: String(STRIPE_TEST_AMOUNT_MINOR), currency: STRIPE_TEST_CURRENCY, fingerprint: sha256(`linkedin\n${userId}\n${flowId}\n${STRIPE_TEST_AMOUNT_MINOR}\n${STRIPE_TEST_CURRENCY}`), is_simulation: "true", }; } function cardMetadataFields(metadata: ReturnType) { return Object.entries(metadata).map(([key, value]) => [`metadata[${key}]`, value] as [string, string]); } function validateCardMetadata(metadata: Record | null | undefined, userId: string) { const flowId = metadata?.flow_id ?? ""; const expected = cardFlowMetadata(userId, flowId); if (!/^[0-9a-f]{64}$/u.test(flowId) || Object.entries(expected).some(([key, value]) => metadata?.[key] !== value)) { throw new ApiError(502, "Stripe returned invalid card setup metadata.", "stripe_card_response_invalid"); } return flowId; } async function proxyFormRequest(proxyUrl: string, path: string, fields: URLSearchParams, idempotencyKey: string) { const response = await fetch(`${proxyUrl}${path}`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "Idempotency-Key": idempotencyKey }, body: fields.toString(), }); const payload = await response.json().catch(() => null) as Record | null; if (!response.ok || !payload) throw new ApiError(502, "Stripe card setup is unavailable.", "stripe_card_unavailable"); return payload; } export async function createStripeCardSetup(user: Pick) { assertPublicBillingEnabled(); const db = getDb(); const [existing] = await db.select().from(subscriptions).where(eq(subscriptions.userId, user.id)).limit(1); if (existing && ["active", "trialing"].includes(existing.status)) { throw new ApiError(409, "Premium is already active for this account.", "subscription_active"); } const proxyUrl = stripeTestProxyUrl(); const flowId = sha256(`linkedin-card-setup\n${user.id}\n${randomUUID()}`); const metadata = cardFlowMetadata(user.id, flowId); let customerId: string | null = null; if (proxyUrl) { const payload = await proxyFormRequest(proxyUrl, "/v1/customers", new URLSearchParams([ ["email", user.email], ["name", user.name], ...cardMetadataFields(metadata), ]), `linkedin-customer-${flowId.slice(0, 48)}`); customerId = typeof payload.id === "string" && /^cus_[A-Za-z0-9_]{8,240}$/u.test(payload.id) ? payload.id : null; } else { const customer = await getStripe().customers.create({ email: user.email, name: user.name, metadata }, { idempotencyKey: `linkedin-customer-${flowId.slice(0, 48)}` }); customerId = customer.id; } if (!customerId) throw new ApiError(502, "Stripe did not create a Customer.", "stripe_customer_invalid"); let setupIntent: StripeCardSetupIntent; if (proxyUrl) { setupIntent = await proxyFormRequest(proxyUrl, "/v1/setup_intents", new URLSearchParams([ ["customer", customerId], ["payment_method", "pm_card_visa"], ["payment_method_types[0]", "card"], ["usage", "off_session"], ["confirm", "true"], ...cardMetadataFields(metadata), ]), `linkedin-setup-${flowId.slice(0, 48)}`) as unknown as StripeCardSetupIntent; } else { setupIntent = await getStripe().setupIntents.create({ customer: customerId, payment_method: "pm_card_visa", payment_method_types: ["card"], usage: "off_session", confirm: true, metadata, }, { idempotencyKey: `linkedin-setup-${flowId.slice(0, 48)}` }) as unknown as StripeCardSetupIntent; } if (!/^seti_[A-Za-z0-9_]{8,240}$/u.test(setupIntent.id) || setupIntent.status !== "succeeded" || setupIntent.customer !== customerId || !/^pm_[A-Za-z0-9_]{8,240}$/u.test(setupIntent.payment_method ?? "") || setupIntent.livemode !== false) { throw new ApiError(502, "Stripe returned an invalid SetupIntent.", "stripe_card_response_invalid"); } validateCardMetadata(setupIntent.metadata, user.id); const values = { stripeCustomerId: customerId, stripeSubscriptionId: null, stripePriceId: STRIPE_TEST_PRICE_ID, status: "incomplete", currentPeriodStart: null, currentPeriodEnd: null, cancelAtPeriodEnd: false, checkoutSessionId: setupIntent.id, updatedAt: new Date(), }; if (existing) await db.update(subscriptions).set(values).where(eq(subscriptions.id, existing.id)); else await db.insert(subscriptions).values({ userId: user.id, ...values }); return { setupIntentId: setupIntent.id }; } export async function completeStripeCardSubscription(userId: string, setupIntentId: string) { assertPublicBillingEnabled(); if (!/^seti_[A-Za-z0-9_]{8,240}$/u.test(setupIntentId)) throw new ApiError(400, "Invalid Stripe card setup.", "stripe_card_invalid"); const db = getDb(); const [existing] = await db.select().from(subscriptions).where(eq(subscriptions.userId, userId)).limit(1); if (!existing || existing.checkoutSessionId !== setupIntentId || !existing.stripeCustomerId) { throw new ApiError(404, "Stripe card setup was not found for this account.", "stripe_card_missing"); } if (["active", "trialing"].includes(existing.status)) return existing; const proxyUrl = stripeTestProxyUrl(); let setupIntent: StripeCardSetupIntent; if (proxyUrl) { const response = await fetch(`${proxyUrl}/v1/setup_intents/${encodeURIComponent(setupIntentId)}`, { headers: { Accept: "application/json" } }); setupIntent = await response.json().catch(() => null) as StripeCardSetupIntent; if (!response.ok || !setupIntent) throw new ApiError(502, "Unable to verify the card with Stripe.", "stripe_card_verification_failed"); } else { setupIntent = await getStripe().setupIntents.retrieve(setupIntentId) as unknown as StripeCardSetupIntent; } validateCardMetadata(setupIntent.metadata, userId); if (setupIntent.status !== "succeeded" || setupIntent.customer !== existing.stripeCustomerId || !setupIntent.payment_method || !/^pm_[A-Za-z0-9_]{8,240}$/u.test(setupIntent.payment_method) || setupIntent.livemode !== false) { throw new ApiError(409, "Verify the card with Stripe before subscribing.", "stripe_card_unverified"); } const flowId = setupIntent.metadata.flow_id; const metadata = cardFlowMetadata(userId, flowId); let subscription: StripeCardSubscription; if (proxyUrl) { subscription = await proxyFormRequest(proxyUrl, "/v1/subscriptions", new URLSearchParams([ ["customer", existing.stripeCustomerId], ["default_payment_method", setupIntent.payment_method], ["items[0][price]", STRIPE_TEST_PRICE_ID], ["items[0][quantity]", "1"], ["payment_behavior", "error_if_incomplete"], ["payment_settings[save_default_payment_method]", "on_subscription"], ...cardMetadataFields(metadata), ]), `linkedin-subscription-${setupIntentId.slice(0, 48)}`) as unknown as StripeCardSubscription; } else { subscription = await getStripe().subscriptions.create({ customer: existing.stripeCustomerId, default_payment_method: setupIntent.payment_method, items: [{ price: providerPriceId(), quantity: 1 }], payment_behavior: "error_if_incomplete", payment_settings: { save_default_payment_method: "on_subscription" }, metadata, }, { idempotencyKey: `linkedin-subscription-${setupIntentId.slice(0, 48)}` }) as unknown as StripeCardSubscription; } if (!/^sub_[A-Za-z0-9_]{8,240}$/u.test(subscription.id) || !["active", "trialing"].includes(subscription.status) || subscription.customer !== existing.stripeCustomerId || subscription.livemode !== false) { throw new ApiError(502, "Stripe did not activate the test subscription.", "stripe_subscription_invalid"); } validateCardMetadata(subscription.metadata, userId); const now = new Date(); const [updated] = await db.update(subscriptions).set({ stripeSubscriptionId: subscription.id, stripePriceId: STRIPE_TEST_PRICE_ID, status: subscription.status, currentPeriodStart: now, currentPeriodEnd: new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000), cancelAtPeriodEnd: false, updatedAt: now, }).where(eq(subscriptions.id, existing.id)).returning(); return updated; } function stripeSecretKey() { const key = process.env.STRIPE_SECRET_KEY; if (!key) throw new ApiError(503, "STRIPE_SECRET_KEY is not configured.", "stripe_not_configured"); if (!key.startsWith("sk_test_")) { throw new ApiError(503, "LinkedIn billing is locked to Stripe Test Mode for this environment.", "stripe_live_key_rejected"); } return key; } export function premiumPriceId() { const priceId = process.env.STRIPE_PREMIUM_PRICE_ID; if (!priceId) throw new ApiError(503, "STRIPE_PREMIUM_PRICE_ID is not configured.", "stripe_not_configured"); return priceId; } export function getStripe() { if (!stripeClient) stripeClient = new Stripe(stripeSecretKey()); return stripeClient; } export function stripeWebhookSecret() { const secret = process.env.STRIPE_WEBHOOK_SECRET; if (!secret) throw new ApiError(503, "STRIPE_WEBHOOK_SECRET is not configured.", "stripe_not_configured"); return secret; } function dateFromUnix(value?: number) { return value ? new Date(value * 1000) : null; } function customerIdFrom(value: SubscriptionShape["customer"]) { return typeof value === "string" ? value : value.id; } export async function ensureStripeCustomer(user: Pick) { const db = getDb(); const [existing] = await db.select().from(subscriptions).where(eq(subscriptions.userId, user.id)).limit(1); if (existing?.stripeCustomerId) return existing.stripeCustomerId; const customer = await getStripe().customers.create({ email: user.email, name: user.name, metadata: { userId: user.id }, }); if (existing) { await db.update(subscriptions).set({ stripeCustomerId: customer.id, stripePriceId: premiumPriceId(), updatedAt: new Date(), }).where(eq(subscriptions.id, existing.id)); } else { await db.insert(subscriptions).values({ userId: user.id, stripeCustomerId: customer.id, stripePriceId: premiumPriceId(), }); } return customer.id; } export async function createCheckoutUrl(user: Pick) { assertPublicBillingEnabled(); const proxyUrl = stripeTestProxyUrl(); if (proxyUrl) return createStripeTestCheckout(user, proxyUrl); if (process.env.STRIPE_SECRET_KEY) return createDirectStripeTestCheckout(user); if (localBillingFallbackEnabled() || "passwordHash" in user && user.passwordHash === "local-test") { if (process.env.PUBLIC_CLONE_AUTH_MODE === "local-dev" || "passwordHash" in user && user.passwordHash === "local-test") { const checkoutSessionId = localCheckout(user.id); return `${appUrl()}/premium?checkout=success&session_id=${encodeURIComponent(checkoutSessionId)}`; } const db = getDb(); const [existing] = await db.select().from(subscriptions).where(eq(subscriptions.userId, user.id)).limit(1); const now = new Date(); const checkoutSessionId = `cs_test_local_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`; const values = { stripeCustomerId: `cus_local_${user.id}`, stripeSubscriptionId: `sub_local_${user.id}`, stripePriceId: "price_local_test", status: "active", currentPeriodStart: now, currentPeriodEnd: new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000), cancelAtPeriodEnd: false, checkoutSessionId, updatedAt: now, }; if (existing) { await db.update(subscriptions).set(values).where(eq(subscriptions.id, existing.id)); } else { await db.insert(subscriptions).values({ userId: user.id, ...values }); } return `${appUrl()}/premium?checkout=success&session_id=${encodeURIComponent(checkoutSessionId)}`; } const customerId = await ensureStripeCustomer(user); const session = await getStripe().checkout.sessions.create({ mode: "subscription", customer: customerId, line_items: [{ price: premiumPriceId(), quantity: 1 }], success_url: `${appUrl()}/premium?checkout=success`, cancel_url: `${appUrl()}/premium?checkout=cancelled`, client_reference_id: user.id, metadata: { userId: user.id }, subscription_data: { metadata: { userId: user.id } }, }); await getDb().update(subscriptions).set({ checkoutSessionId: session.id, updatedAt: new Date(), }).where(eq(subscriptions.userId, user.id)); if (!session.url) throw new ApiError(502, "Stripe did not return a checkout URL.", "stripe_checkout_unavailable"); return session.url; } export async function createPortalUrl(userId: string) { assertPublicBillingEnabled(); if (stripeTestProxyUrl()) { throw new ApiError(409, "Stripe Test Mode subscriptions do not require a billing portal.", "stripe_test_portal_unavailable"); } const [subscription] = await getDb().select().from(subscriptions).where(eq(subscriptions.userId, userId)).limit(1); if (!subscription?.stripeCustomerId) throw new ApiError(404, "No Stripe customer exists for this account.", "stripe_customer_missing"); const session = await getStripe().billingPortal.sessions.create({ customer: subscription.stripeCustomerId, return_url: `${appUrl()}/premium`, }); return session.url; } export async function syncStripeSubscription(subscription: SubscriptionShape) { const customerId = customerIdFrom(subscription.customer); const priceId = subscription.items?.data?.[0]?.price?.id ?? premiumPriceId(); const db = getDb(); const [existing] = await db.select().from(subscriptions).where(eq(subscriptions.stripeCustomerId, customerId)).limit(1); const userId = subscription.metadata?.userId ?? existing?.userId; if (!userId) return null; const values = { stripeCustomerId: customerId, stripeSubscriptionId: subscription.id, stripePriceId: priceId, status: subscription.status, currentPeriodStart: dateFromUnix(subscription.current_period_start), currentPeriodEnd: dateFromUnix(subscription.current_period_end), cancelAtPeriodEnd: subscription.cancel_at_period_end ?? false, updatedAt: new Date(), }; if (existing) { const [updated] = await db.update(subscriptions).set(values).where(eq(subscriptions.id, existing.id)).returning(); return updated; } const [created] = await db.insert(subscriptions).values({ userId, ...values }).returning(); return created; }