File size: 28,212 Bytes
9d4a3b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
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<string, string>;
};

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<User, "id" | "email" | "name">, 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<User, "id" | "email" | "name">) {
  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<string, string>;
};

type StripeCardSubscription = {
  id: string;
  status: string;
  customer: string;
  default_payment_method?: string | null;
  livemode: false;
  metadata: Record<string, string>;
};

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<typeof cardFlowMetadata>) {
  return Object.entries(metadata).map(([key, value]) => [`metadata[${key}]`, value] as [string, string]);
}

function validateCardMetadata(metadata: Record<string, string> | 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<string, unknown> | 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<User, "id" | "email" | "name">) {
  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<User, "id" | "email" | "name">) {
  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<User, "id" | "email" | "name">) {
  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;
}