-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathstripe.ts
More file actions
4406 lines (4005 loc) · 131 KB
/
Copy pathstripe.ts
File metadata and controls
4406 lines (4005 loc) · 131 KB
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createRoute, OpenAPIHono } from "@hono/zod-openapi";
import { HTTPException } from "hono/http-exception";
import { z } from "zod";
import {
and,
db,
enqueueWebhookDeliveries,
eq,
inArray,
isNull,
sql,
tables,
} from "@llmgateway/db";
import { logger } from "@llmgateway/logger";
import {
getChatPlanCreditsLimit,
getDevPlanCreditsLimit,
getProratedCreditDelta,
type ChatPlanCycle,
type ChatPlanTier,
type DevPlanCycle,
type DevPlanTier,
} from "@llmgateway/shared";
import { computeReferralBonus } from "./lib/referral-bonus.js";
import { posthog } from "./posthog.js";
import { getStripe, type StripeMode } from "./routes/payments.js";
import { resolveDevPassBillingDetails } from "./utils/devpass-billing.js";
import {
notifyChatPlanCancelled,
notifyChatPlanRenewed,
notifyChatPlanSubscribed,
notifyCreditsPurchased,
notifyDevPlanCancelled,
notifyDevPlanRenewed,
notifyDevPlanSubscribed,
} from "./utils/discord.js";
import {
generateDevPlanCancellationFeedbackEmailHtml,
generateDevPlanDuplicateCardEmailHtml,
generatePaymentFailureEmailHtml,
generateSubscriptionCancelledEmailHtml,
sendTransactionalEmail,
} from "./utils/email.js";
import { generateAndEmailInvoice } from "./utils/invoice.js";
import type { ServerTypes } from "./vars.js";
import type Stripe from "stripe";
export async function ensureStripeCustomer(
organizationId: string,
): Promise<string> {
const organization = await db.query.organization.findFirst({
where: {
id: organizationId,
},
});
if (!organization) {
throw new Error(`Organization not found: ${organizationId}`);
}
let stripeCustomerId = organization.stripeCustomerId;
if (!stripeCustomerId) {
const customer = await getStripe().customers.create({
email: organization.billingEmail,
metadata: {
organizationId,
},
});
stripeCustomerId = customer.id;
await db
.update(tables.organization)
.set({
stripeCustomerId,
})
.where(eq(tables.organization.id, organizationId));
} else {
// Update existing customer email if billingEmail has changed
await getStripe().customers.update(stripeCustomerId, {
email: organization.billingEmail,
});
}
return stripeCustomerId;
}
/**
* LLM SDK: ensure the end-customer has its own Stripe customer, separate
* from the developer's org customer, so cards and receipts are per-end-user.
*/
export async function ensureEndCustomerStripeCustomer(
endCustomerId: string,
mode: StripeMode = "live",
): Promise<string> {
// Claim the row under a lock so two concurrent top-ups for the same customer
// can't each create a Stripe customer (orphaning one). The second caller
// blocks until the first commits, then sees the persisted id.
return await db.transaction(async (tx) => {
const [endCustomer] = await tx
.select()
.from(tables.endCustomer)
.where(eq(tables.endCustomer.id, endCustomerId))
.for("update")
.limit(1);
if (!endCustomer) {
throw new Error(`End customer not found: ${endCustomerId}`);
}
if (endCustomer.stripeCustomerId) {
return endCustomer.stripeCustomerId;
}
const customer = await getStripe(mode).customers.create({
email: endCustomer.email ?? undefined,
name: endCustomer.name ?? undefined,
metadata: {
endCustomerId,
projectId: endCustomer.projectId,
organizationId: endCustomer.organizationId,
},
});
await tx
.update(tables.endCustomer)
.set({ stripeCustomerId: customer.id })
.where(eq(tables.endCustomer.id, endCustomerId));
return customer.id;
});
}
/**
* Unified helper to resolve organizationId from various Stripe event sources
* and validate that the organization exists in the database.
*/
async function resolveOrganizationFromStripeEvent(eventData: {
metadata?: { organizationId?: string };
customer?: string;
subscription?: string;
lines?: { data?: Array<{ metadata?: { organizationId?: string } }> };
}): Promise<{ organizationId: string; organization: any } | null> {
let organizationId: string | null = null;
// 1. Try to get organizationId from direct metadata
if (eventData.metadata?.organizationId) {
organizationId = eventData.metadata.organizationId;
logger.debug("Found organizationId in direct metadata", { organizationId });
}
// 2. Check line items metadata (common in invoices)
if (!organizationId && eventData.lines?.data) {
logger.info(
`Checking ${eventData.lines.data.length} line items for organizationId`,
);
for (const lineItem of eventData.lines.data) {
if (lineItem.metadata?.organizationId) {
organizationId = lineItem.metadata.organizationId;
logger.info(
`Found organizationId in line item metadata: ${organizationId}`,
);
break;
}
}
}
// 3. Try to get from subscription metadata if subscription ID is available
if (!organizationId && eventData.subscription) {
try {
const stripeSubscription = await getStripe().subscriptions.retrieve(
eventData.subscription,
);
if (stripeSubscription.metadata?.organizationId) {
organizationId = stripeSubscription.metadata.organizationId;
logger.info(
`Found organizationId in subscription metadata: ${organizationId}`,
);
}
} catch (error) {
logger.error("Error retrieving subscription:", error as Error);
}
}
// 4. Fallback: find organization by Stripe customer ID
if (!organizationId && eventData.customer) {
const organization = await db.query.organization.findFirst({
where: {
stripeCustomerId: eventData.customer,
},
});
if (organization) {
organizationId = organization.id;
logger.info(
`Found organizationId via customer lookup: ${organizationId}`,
);
}
}
if (!organizationId) {
logger.error(`Organization not found for event data:`, {
hasMetadata: !!eventData.metadata,
customer: eventData.customer,
subscription: eventData.subscription,
lineItemsCount: eventData.lines?.data?.length ?? 0,
});
return null;
}
// Validate that the organization exists
const organization = await db.query.organization.findFirst({
where: {
id: organizationId,
},
});
if (!organization) {
logger.error(
`Organization with ID ${organizationId} does not exist in database`,
);
return null;
}
logger.info(
`Successfully resolved organization: ${organization.name} (${organization.id})`,
);
return { organizationId, organization };
}
export const stripeRoutes = new OpenAPIHono<ServerTypes>();
const webhookHandler = createRoute({
method: "post",
path: "/webhook",
request: {},
responses: {
200: {
content: {
"application/json": {
schema: z.object({
received: z.boolean(),
}),
},
},
description: "Webhook received successfully",
},
},
});
/**
* Verify a Stripe webhook signature against the live secret, then the sandbox
* secret. Whichever verifies wins; if both are configured and neither matches,
* the last error is rethrown so the handler returns 400.
*/
function constructWebhookEvent(
body: string,
sig: string,
): { event: Stripe.Event; mode: StripeMode } {
const secrets: ReadonlyArray<[StripeMode, string | undefined]> = [
["live", process.env.STRIPE_WEBHOOK_SECRET],
["test", process.env.STRIPE_WEBHOOK_SECRET_TEST],
];
let lastError: Error | undefined;
for (const [mode, secret] of secrets) {
if (!secret) {
continue;
}
try {
return {
event: getStripe(mode).webhooks.constructEvent(body, sig, secret),
mode,
};
} catch (err) {
lastError = err instanceof Error ? err : new Error(String(err));
}
}
throw lastError ?? new Error("No Stripe webhook secret configured");
}
/**
* Test-mode (sandbox) webhook events are only ever legitimate for LLM SDK
* end-user wallet top-ups. Route them to the SDK handlers only — never the live
* org billing handlers (credit top-ups, subscriptions, invoices) — even if the
* test webhook endpoint is configured to forward broader event types. The
* `payment_intent.*` handlers already gate on `kind === "end_user_topup"`, and
* `charge.refunded` is restricted to end-user top-up refunds here.
*/
async function handleTestModeWebhookEvent(event: Stripe.Event): Promise<void> {
switch (event.type) {
case "payment_intent.succeeded": {
const pi = event.data.object;
if (pi.metadata?.kind === "end_user_topup") {
await handleEndUserTopUpSucceeded(pi);
} else {
logger.warn("Ignoring non-SDK test-mode payment_intent.succeeded", {
paymentIntentId: pi.id,
});
}
break;
}
case "payment_intent.payment_failed": {
const pi = event.data.object;
logger.info("Test-mode payment intent failed", {
paymentIntentId: pi.id,
kind: pi.metadata?.kind,
});
break;
}
case "charge.refunded":
await handleChargeRefunded(event, { endUserOnly: true });
break;
default:
logger.info(`Ignoring test-mode event: ${event.type}`);
}
}
stripeRoutes.openapi(webhookHandler, async (c) => {
const sig = c.req.header("stripe-signature");
if (!sig) {
throw new HTTPException(400, {
message: "Missing stripe-signature header",
});
}
try {
const body = await c.req.raw.text();
// Verify against the live secret first, then the sandbox secret. Stripe
// signs test-mode events (from LLM SDK test secret keys topping up via the
// sandbox) with STRIPE_WEBHOOK_SECRET_TEST, delivered to the same endpoint.
const { event, mode } = constructWebhookEvent(body, sig);
logger.info("Stripe webhook received", {
eventId: event.id,
eventType: event.type,
mode,
});
// Sandbox events must never reach the live org billing handlers — only the
// SDK end-user wallet flow operates in test mode.
if (mode === "test") {
await handleTestModeWebhookEvent(event);
return c.json({ received: true });
}
switch (event.type) {
case "payment_intent.succeeded":
await handlePaymentIntentSucceeded(event);
break;
case "payment_intent.payment_failed":
await handlePaymentIntentFailed(event);
break;
case "setup_intent.succeeded":
await handleSetupIntentSucceeded(event);
break;
case "checkout.session.completed":
await handleCheckoutSessionCompleted(event);
break;
case "invoice.payment_succeeded":
await handleInvoicePaymentSucceeded(event);
break;
case "invoice.paid":
await handleInvoicePaymentSucceeded(event);
break;
case "invoice.payment_failed":
await handleInvoicePaymentFailed(event);
break;
case "customer.subscription.created":
await handleSubscriptionCreated(event);
break;
case "customer.subscription.updated":
await handleSubscriptionUpdated(event);
break;
case "customer.subscription.deleted":
await handleSubscriptionDeleted(event);
break;
case "charge.refunded":
await handleChargeRefunded(event);
break;
default:
logger.warn(`Unhandled event type: ${event.type}`);
}
return c.json({ received: true });
} catch (error) {
logger.error("Webhook error:", error as Error);
throw new HTTPException(400, {
message: `Webhook error: ${error instanceof Error ? error.message : "Unknown error"}`,
});
}
});
/**
* Resolve the card fingerprint used for a Stripe subscription. Returns null
* when the subscription is paid by a non-card payment method (SEPA, etc.) or
* when the payment method is missing for any reason.
*/
async function getSubscriptionCardFingerprint(
subscriptionId: string,
): Promise<string | null> {
try {
const subscription = await getStripe().subscriptions.retrieve(
subscriptionId,
{ expand: ["default_payment_method"] },
);
const defaultPaymentMethod = subscription.default_payment_method;
let paymentMethod: Stripe.PaymentMethod | null = null;
if (defaultPaymentMethod) {
paymentMethod =
typeof defaultPaymentMethod === "string"
? await getStripe().paymentMethods.retrieve(defaultPaymentMethod)
: defaultPaymentMethod;
} else if (subscription.latest_invoice) {
const invoiceId =
typeof subscription.latest_invoice === "string"
? subscription.latest_invoice
: subscription.latest_invoice.id;
if (invoiceId) {
const invoice = await getStripe().invoices.retrieve(invoiceId, {
expand: ["payment_intent"],
});
const paymentIntent = (invoice as any).payment_intent as
| Stripe.PaymentIntent
| string
| null
| undefined;
const pi =
typeof paymentIntent === "string"
? await getStripe().paymentIntents.retrieve(paymentIntent)
: paymentIntent;
const pm = pi?.payment_method;
if (pm) {
paymentMethod =
typeof pm === "string"
? await getStripe().paymentMethods.retrieve(pm)
: pm;
}
}
}
if (!paymentMethod || paymentMethod.type !== "card") {
return null;
}
return paymentMethod.card?.fingerprint ?? null;
} catch (error) {
logger.error(
`Failed to resolve card fingerprint for subscription ${subscriptionId}`,
error instanceof Error ? error : new Error(String(error)),
);
return null;
}
}
export type FinalizeDevPlanResult =
| { status: "ok"; subscriptionId: string }
| {
status: "requires_action";
subscriptionId: string;
clientSecret: string;
paymentMethodId?: string;
}
| {
status: "payment_pending";
subscriptionId: string;
subscriptionStatus?: string;
invoiceId?: string;
invoiceStatus?: string | null;
paymentIntentStatus?: string;
hasClientSecret?: boolean;
}
| { status: "duplicate_card"; conflictingOrgId: string }
| { status: "already_processed"; subscriptionId: string | null }
| { status: "no_payment_method" }
| { status: "invalid_session"; reason: string };
// The current billing period end is the authoritative renewal date. It lives on
// the subscription item (not the subscription) in current Stripe API versions.
// Returns null when the subscription has no items yet (e.g. mid-creation).
function getSubscriptionPeriodEnd(
subscription: Stripe.Subscription,
): Date | null {
const periodEnd = subscription.items.data[0]?.current_period_end;
return periodEnd ? new Date(periodEnd * 1000) : null;
}
function isStripePaymentIntent(value: unknown): value is Stripe.PaymentIntent {
if (!value || typeof value !== "object") {
return false;
}
return (value as { object?: unknown }).object === "payment_intent";
}
function getSubscriptionPaymentIntent(
subscription: Stripe.Subscription,
): Stripe.PaymentIntent | null {
const latestInvoice = subscription.latest_invoice;
if (
!latestInvoice ||
typeof latestInvoice === "string" ||
!("payment_intent" in latestInvoice)
) {
return null;
}
const { payment_intent: paymentIntent } = latestInvoice as {
payment_intent?: unknown;
};
if (!paymentIntent || typeof paymentIntent === "string") {
return null;
}
return isStripePaymentIntent(paymentIntent) ? paymentIntent : null;
}
function getInvoiceConfirmationClientSecret(
invoice: Stripe.Invoice,
): string | null {
const confirmationSecret = invoice.confirmation_secret;
return confirmationSecret?.client_secret ?? null;
}
async function getPaymentIntentFromInvoicePayments(
invoice: Stripe.Invoice,
): Promise<Stripe.PaymentIntent | null> {
let invoicePayments = invoice.payments?.data ?? [];
if (invoicePayments.length === 0) {
const listedPayments = await getStripe().invoicePayments.list({
invoice: invoice.id,
limit: 10,
});
invoicePayments = listedPayments.data;
}
for (const invoicePayment of invoicePayments) {
const paymentIntent = invoicePayment.payment.payment_intent;
if (!paymentIntent) {
continue;
}
if (typeof paymentIntent !== "string") {
if (isStripePaymentIntent(paymentIntent)) {
return paymentIntent;
}
continue;
}
const retrieved = await getStripe().paymentIntents.retrieve(paymentIntent);
return isStripePaymentIntent(retrieved) ? retrieved : null;
}
return null;
}
async function getSubscriptionInvoice(
subscription: Stripe.Subscription,
): Promise<Stripe.Invoice | null> {
const latestInvoice = subscription.latest_invoice;
if (!latestInvoice) {
return null;
}
if (typeof latestInvoice !== "string") {
return latestInvoice;
}
return await getStripe().invoices.retrieve(latestInvoice, {
expand: ["payment_intent"],
});
}
async function getSubscriptionPaymentConfirmation(
subscription: Stripe.Subscription,
): Promise<{
paymentIntent: Stripe.PaymentIntent | null;
clientSecret: string | null;
invoice: Stripe.Invoice | null;
}> {
const invoice = await getSubscriptionInvoice(subscription);
if (!invoice) {
return { paymentIntent: null, clientSecret: null, invoice: null };
}
let paymentIntent = getSubscriptionPaymentIntent(subscription);
if (!paymentIntent) {
const { payment_intent: invoicePaymentIntent } = invoice as {
payment_intent?: unknown;
};
if (
invoicePaymentIntent &&
typeof invoicePaymentIntent !== "string" &&
isStripePaymentIntent(invoicePaymentIntent)
) {
paymentIntent = invoicePaymentIntent;
}
}
paymentIntent ??= await getPaymentIntentFromInvoicePayments(invoice);
return {
paymentIntent,
clientSecret:
paymentIntent?.client_secret ??
getInvoiceConfirmationClientSecret(invoice),
invoice,
};
}
function getPaymentPendingResult({
subscription,
invoice,
paymentIntent,
clientSecret,
}: {
subscription: Stripe.Subscription;
invoice: Stripe.Invoice | null;
paymentIntent: Stripe.PaymentIntent | null;
clientSecret: string | null;
}): FinalizeDevPlanResult {
logger.info("Dev plan subscription payment is pending", {
subscriptionId: subscription.id,
subscriptionStatus: subscription.status,
invoiceId: invoice?.id,
invoiceStatus: invoice?.status,
paymentIntentId: paymentIntent?.id,
paymentIntentStatus: paymentIntent?.status,
hasClientSecret: Boolean(clientSecret),
});
return {
status: "payment_pending",
subscriptionId: subscription.id,
subscriptionStatus: subscription.status,
invoiceId: invoice?.id,
invoiceStatus: invoice?.status,
paymentIntentStatus: paymentIntent?.status,
hasClientSecret: Boolean(clientSecret),
};
}
async function findDevPlanSubscriptionForSetupSession(
customerId: string,
sessionId: string,
): Promise<Stripe.Subscription | null> {
const subscriptions = await getStripe().subscriptions.list({
customer: customerId,
status: "all",
limit: 100,
});
const existing = subscriptions.data.find(
(subscription) => subscription.metadata?.setupSessionId === sessionId,
);
if (!existing) {
return null;
}
return await getStripe().subscriptions.retrieve(existing.id, {
expand: ["latest_invoice.payment_intent"],
});
}
/**
* Cancel stale DevPass subscriptions left on the customer by an earlier checkout
* attempt. A setup-mode checkout creates one subscription per setup session, so
* a first attempt whose payment never completes leaves a dangling `incomplete`
* subscription that later flips to `incomplete_expired` — emitting events for a
* plan the org never activated and, before the id-gating fix, freezing the
* active plan's credits. Before activating the current session's subscription we
* cancel those dangling attempts so the customer is never left with duplicate
* DevPass subscriptions. The current session's own subscription is matched by
* `setupSessionId` and never cancelled — which also keeps this safe under the
* finalize/webhook race (both runs share the same session id).
*/
async function cancelStaleDevPlanSubscriptions(
customerId: string,
currentSessionId: string,
): Promise<void> {
const subscriptions = await getStripe().subscriptions.list({
customer: customerId,
status: "all",
limit: 100,
});
const stale = subscriptions.data.filter(
(s) =>
s.metadata?.subscriptionType === "dev_plan" &&
s.metadata?.setupSessionId !== currentSessionId &&
(s.status === "incomplete" || s.status === "past_due"),
);
for (const s of stale) {
try {
await getStripe().subscriptions.cancel(s.id);
logger.info(
`Cancelled stale DevPass subscription ${s.id} (status ${s.status}) for customer ${customerId}`,
);
} catch (err) {
logger.warn(`Failed to cancel stale DevPass subscription ${s.id}`, {
error: err instanceof Error ? err.message : String(err),
});
}
}
}
/**
* Collapse duplicate copies of a card down to a single payment method. Each
* setup session saves the card as a fresh PaymentMethod object, so a retried
* checkout would otherwise leave several PaymentMethods for the same physical
* card on the customer. Keeps `keepPaymentMethodId` and detaches every other
* payment method that shares its fingerprint.
*/
async function detachDuplicateCardPaymentMethods(
customerId: string,
keepPaymentMethodId: string,
fingerprint: string | null,
): Promise<void> {
if (!fingerprint) {
return;
}
const paymentMethods = await getStripe().paymentMethods.list({
customer: customerId,
type: "card",
limit: 100,
});
const duplicates = paymentMethods.data.filter(
(pm) =>
pm.id !== keepPaymentMethodId && pm.card?.fingerprint === fingerprint,
);
for (const pm of duplicates) {
try {
await getStripe().paymentMethods.detach(pm.id);
logger.info(
`Detached duplicate card ${pm.id} (fingerprint ${fingerprint}) from customer ${customerId}`,
);
} catch (err) {
logger.warn(`Failed to detach duplicate card ${pm.id}`, {
error: err instanceof Error ? err.message : String(err),
});
}
}
}
function shouldForceDevPlan3dsChallenge(): boolean {
return process.env.STRIPE_DEV_PLAN_FORCE_3DS === "true";
}
async function resolvePaymentMethodFromSetupSession(
session: Stripe.Checkout.Session,
): Promise<Stripe.PaymentMethod | null> {
let setupIntent: Stripe.SetupIntent | null = null;
const rawSetupIntent = session.setup_intent;
if (typeof rawSetupIntent === "string") {
setupIntent = await getStripe().setupIntents.retrieve(rawSetupIntent);
} else if (rawSetupIntent) {
setupIntent = rawSetupIntent;
}
if (!setupIntent?.payment_method) {
return null;
}
const pm = setupIntent.payment_method;
if (typeof pm === "string") {
return await getStripe().paymentMethods.retrieve(pm);
}
return pm;
}
/**
* Finalize a DevPass setup-mode checkout session: verify the card fingerprint
* is not already in use by another organization, then create the Stripe
* subscription server-side. Idempotent: safe to call from both the
* /dev-plans/finalize endpoint (user-triggered after redirect) and the
* checkout.session.completed webhook (fallback if the user closes the tab).
*
* Critically, no Stripe subscription is created — and no charge is issued —
* when the card is a duplicate. The duplicate payment method is detached
* from the customer so it isn't accidentally reused later.
*/
export async function finalizeDevPlanSetupSession(
sessionId: string,
): Promise<FinalizeDevPlanResult> {
const session = await getStripe().checkout.sessions.retrieve(sessionId);
if (session.mode !== "setup") {
return { status: "invalid_session", reason: "not_setup_mode" };
}
const metadata = session.metadata ?? {};
if (metadata.subscriptionType !== "dev_plan") {
return { status: "invalid_session", reason: "not_dev_plan" };
}
const organizationId = metadata.organizationId;
const devPlanTier = metadata.devPlan as DevPlanTier | undefined;
const devPlanCycle: DevPlanCycle =
metadata.devPlanCycle === "annual" ? "annual" : "monthly";
const priceId = metadata.priceId;
const userEmail = metadata.userEmail;
if (!organizationId || !devPlanTier || !priceId) {
return { status: "invalid_session", reason: "missing_metadata" };
}
const organization = await db.query.organization.findFirst({
where: { id: organizationId },
});
if (!organization) {
return { status: "invalid_session", reason: "org_not_found" };
}
if (
organization.devPlan !== "none" &&
organization.devPlanStripeSubscriptionId
) {
return {
status: "already_processed",
subscriptionId: organization.devPlanStripeSubscriptionId,
};
}
const paymentMethod = await resolvePaymentMethodFromSetupSession(session);
if (!paymentMethod) {
return { status: "no_payment_method" };
}
const fingerprint =
paymentMethod.type === "card"
? (paymentMethod.card?.fingerprint ?? null)
: null;
if (fingerprint) {
const conflictingOrg = await db.query.organization.findFirst({
where: {
devPlanCardFingerprint: { eq: fingerprint },
id: { ne: organizationId },
},
});
if (conflictingOrg) {
try {
await getStripe().paymentMethods.detach(paymentMethod.id);
} catch (err) {
logger.warn(
`Failed to detach duplicate dev plan card ${paymentMethod.id}`,
{
error: err instanceof Error ? err.message : String(err),
},
);
}
logger.warn(
`Rejecting dev plan setup ${sessionId} for org ${organizationId}: card fingerprint already used by org ${conflictingOrg.id}`,
);
posthog.capture({
distinctId: "organization",
event: "dev_plan_blocked_duplicate_card",
groups: { organization: organizationId },
properties: {
organization: organizationId,
conflictingOrganization: conflictingOrg.id,
sessionId,
},
});
const notifyEmail = userEmail ?? organization.billingEmail;
if (notifyEmail) {
try {
await sendTransactionalEmail({
to: notifyEmail,
organizationId: organization.id,
subject: "DevPass activation failed — card already in use",
html: generateDevPlanDuplicateCardEmailHtml(organization.name),
});
} catch (err) {
logger.error(
"Failed to send dev plan duplicate-card email",
err instanceof Error ? err : new Error(String(err)),
);
}
}
return {
status: "duplicate_card",
conflictingOrgId: conflictingOrg.id,
};
}
}
const stripeCustomerId = await ensureStripeCustomer(organizationId);
await getStripe().customers.update(stripeCustomerId, {
invoice_settings: { default_payment_method: paymentMethod.id },
});
// Prevent duplicate DevPass subscriptions/cards from a retried checkout. A
// failed first attempt leaves a dangling `incomplete` subscription and a
// duplicate copy of the card on the customer; cancel the former and detach the
// latter before creating/activating this session's subscription. Cancel stale
// subscriptions before detaching cards so we never detach a card still
// referenced by a live subscription.
await cancelStaleDevPlanSubscriptions(stripeCustomerId, sessionId);
await detachDuplicateCardPaymentMethods(
stripeCustomerId,
paymentMethod.id,
fingerprint,
);
// The /finalize endpoint and the checkout.session.completed webhook can
// race for the same setup session. We guard against duplicate subscription
// creation on two levels: (1) a deterministic Stripe idempotency key
// derived from org+session so a second `subscriptions.create()` call
// returns the same subscription instead of a new one; (2) an atomic
// conditional UPDATE that only writes the dev plan state if no other
// writer has filled in devPlanStripeSubscriptionId yet — the loser then
// reports already_processed so it doesn't double-insert the transaction
// row or re-send notifications.
const existingSubscription = await findDevPlanSubscriptionForSetupSession(
stripeCustomerId,
sessionId,
);
const stripeIdempotencyKey = `devpass-sub:${organizationId}:${sessionId}`;
const subscription =
existingSubscription ??
(await getStripe().subscriptions.create(
{
customer: stripeCustomerId,
items: [{ price: priceId }],
default_payment_method: paymentMethod.id,
payment_behavior: "default_incomplete",
...(shouldForceDevPlan3dsChallenge()
? {
payment_settings: {
payment_method_options: {
card: {
request_three_d_secure: "challenge" as const,
},
},
},
}
: {}),
metadata: {
organizationId,
subscriptionType: "dev_plan",
devPlan: devPlanTier,
devPlanCycle,
setupSessionId: sessionId,
userEmail: userEmail ?? "",
},
expand: ["latest_invoice.payment_intent"],
},
{ idempotencyKey: stripeIdempotencyKey },
));
const { paymentIntent, clientSecret, invoice } =
await getSubscriptionPaymentConfirmation(subscription);
if (
clientSecret &&
((paymentIntent &&
(paymentIntent.status === "requires_action" ||
paymentIntent.status === "requires_confirmation" ||
paymentIntent.status === "requires_payment_method")) ||
(!paymentIntent &&
(subscription.status === "incomplete" ||
subscription.status === "past_due")))
) {
return {
status: "requires_action",
subscriptionId: subscription.id,
clientSecret,
paymentMethodId: paymentMethod.id,
};
}
if (paymentIntent && paymentIntent.status !== "succeeded") {
return getPaymentPendingResult({
subscription,
invoice,
paymentIntent,
clientSecret,
});
}
if (
!paymentIntent &&
(subscription.status === "incomplete" || subscription.status === "past_due")
) {
return getPaymentPendingResult({
subscription,
invoice,
paymentIntent,
clientSecret,
});
}
const creditsLimit = getDevPlanCreditsLimit(devPlanTier);
const claimed = await db
.update(tables.organization)
.set({
devPlan: devPlanTier,
devPlanCreditsLimit: creditsLimit.toString(),
devPlanCreditsUsed: "0",