create-ailk 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/component-catalog.md +50 -53
- package/dist/lib/apply-module-patches.d.ts +47 -0
- package/dist/lib/apply-module-patches.js +370 -0
- package/dist/lib/extract-module-bundle.d.ts +12 -3
- package/dist/lib/extract-module-bundle.js +236 -24
- package/dist/lib/fetch-module.d.ts +3 -38
- package/dist/lib/fetch-module.js +26 -8
- package/dist/lib/module-license-gate.d.ts +2 -0
- package/dist/lib/module-license-gate.js +1 -0
- package/dist/lib/paid-paths.d.ts +16 -0
- package/dist/lib/paid-paths.js +90 -0
- package/dist/module-architecture.d.ts +139 -23
- package/dist/module-architecture.js +668 -25
- package/dist/parse-args.d.ts +2 -2
- package/dist/parse-args.js +3 -1
- package/dist/programmatic.d.ts +2 -1
- package/dist/programmatic.js +15 -4
- package/dist/surfaces.d.ts +12 -36
- package/dist/surfaces.js +35 -5
- package/dist/sync-routes.js +31 -1
- package/package.json +2 -2
- package/templates/.claude/agents/web.md +2 -3
- package/templates/.claude/rules/architecture.md +5 -5
- package/templates/.claude/skills/README.md +2 -1
- package/templates/.env.example +21 -9
- package/templates/CONVENTIONS.md +6 -7
- package/templates/apps/api/.env.example +9 -0
- package/templates/apps/api/CLAUDE.md +33 -5
- package/templates/apps/api/package.json +0 -1
- package/templates/apps/api/src/__tests__/cors.test.ts +195 -0
- package/templates/apps/api/src/__tests__/module-exclusion.test.ts +60 -2
- package/templates/apps/api/src/__tests__/vercel-handler.test.ts +159 -0
- package/templates/apps/api/src/config/__tests__/modules.test.ts +76 -0
- package/templates/apps/api/src/config/index.ts +19 -0
- package/templates/apps/api/src/config/modules.ts +12 -14
- package/templates/apps/api/src/lib/__mocks__/prisma.ts +3 -0
- package/templates/apps/api/src/lib/__tests__/slice-load.test.ts +89 -0
- package/templates/apps/api/src/lib/slice-load.ts +90 -0
- package/templates/apps/api/src/openapi/__tests__/openapi.test.ts +52 -32
- package/templates/apps/api/src/openapi/__tests__/spec-identity.test.ts +182 -0
- package/templates/apps/api/src/openapi/__tests__/surface-drift.test.ts +293 -0
- package/templates/apps/api/src/openapi/index.ts +9 -3
- package/templates/apps/api/src/openapi/spec.ts +505 -65
- package/templates/apps/api/src/openapi/surface-drift.ts +195 -0
- package/templates/apps/api/src/routes/content/__tests__/create.test.ts +14 -0
- package/templates/apps/api/src/routes/content/__tests__/delete.test.ts +14 -0
- package/templates/apps/api/src/routes/content/__tests__/update.test.ts +14 -0
- package/templates/apps/api/src/routes/content/index.ts +38 -11
- package/templates/apps/api/src/routes/project-listings/__tests__/configured-application.test.ts +17 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +17 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/founder-identity.test.ts +796 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/me.test.ts +10 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/public.test.ts +38 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/resume-email.test.ts +814 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/site-answers.test.ts +10 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/site-key.test.ts +24 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/structured-address.test.ts +17 -0
- package/templates/apps/api/src/routes/project-listings/index.ts +37 -10
- package/templates/apps/api/src/routes/project-listings/me.ts +10 -0
- package/templates/apps/api/src/routes/project-listings/patch-draft.ts +5 -0
- package/templates/apps/api/src/routes/project-listings/public.ts +5 -0
- package/templates/apps/api/src/routes/project-listings/respond.ts +11 -0
- package/templates/apps/api/src/routes/project-listings/resume-token.ts +5 -0
- package/templates/apps/api/src/routes/project-listings/start.ts +30 -0
- package/templates/apps/api/src/routes/project-listings/submit.ts +5 -0
- package/templates/apps/api/src/routes/project-listings/verify-email.ts +150 -0
- package/templates/apps/api/src/server.ts +459 -135
- package/templates/apps/api/src/services/deliverable-fulfillment.ts +10 -0
- package/templates/apps/api/src/services/listing-config.ts +58 -0
- package/templates/apps/api/src/services/project-listing-resume-email.ts +326 -0
- package/templates/apps/api/src/services/project-listings.ts +229 -4
- package/templates/apps/api/src/vercel-handler.ts +60 -26
- package/templates/apps/mcp/.env.example +8 -0
- package/templates/apps/mcp/CLAUDE.md +2 -2
- package/templates/apps/mcp/__tests__/catalog-drift.test.ts +21 -0
- package/templates/apps/mcp/__tests__/config/modules.test.ts +78 -0
- package/templates/apps/mcp/__tests__/module-exclusion.test.ts +1 -1
- package/templates/apps/mcp/src/config/modules.ts +14 -13
- package/templates/apps/mcp/src/server.ts +8 -4
- package/templates/apps/mcp/src/tools/index.ts +7 -22
- package/templates/apps/web/.env.example +15 -0
- package/templates/apps/web/app/[locale]/(authed)/{waitlist/__tests__ → __tests__}/gate.test.tsx +4 -4
- package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +2 -1
- package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.permalink.test.tsx +2 -1
- package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.test.tsx +2 -1
- package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/flow.actions.test.ts +1 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/two-route-tool.test.tsx +1 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/flow.actions.ts +2 -1
- package/templates/apps/web/app/[locale]/flows/[slug]/page.tsx +1 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/start/page.tsx +1 -0
- package/templates/apps/web/app/llms.txt/route.ts +12 -9
- package/templates/apps/web/jest.config.cjs +14 -13
- package/templates/apps/web/next.config.mjs +1 -3
- package/templates/apps/web/package.json +0 -6
- package/templates/apps/web/public/android-chrome-192x192.png +0 -0
- package/templates/apps/web/public/android-chrome-512x512.png +0 -0
- package/templates/apps/web/public/apple-touch-icon.png +0 -0
- package/templates/apps/web/public/favicon-16x16.png +0 -0
- package/templates/apps/web/public/favicon-32x32.png +0 -0
- package/templates/apps/web/public/favicon.ico +0 -0
- package/templates/apps/web/public/favicon.svg +6 -3
- package/templates/apps/web/public/lockup-horizontal.svg +4 -0
- package/templates/apps/web/public/logomark.svg +4 -0
- package/templates/apps/web/public/site.webmanifest +2 -2
- package/templates/apps/web/public/wordmark.svg +4 -0
- package/templates/database/CHANGELOG.md +33 -0
- package/templates/database/inbox/schema.prisma +67 -0
- package/templates/database/migrations/20260914120000_listing_founder_identity/migration.sql +123 -0
- package/templates/database/package.json +1 -1
- package/templates/package.json +1 -1
- package/templates/.claude/skills/scaffold-commerce/SKILL.md +0 -807
- package/templates/.claude/skills/scaffold-commerce/references/lookup-keys-template.md +0 -71
- package/templates/.claude/skills/scaffold-commerce/references/marketplace-brand-pages.md +0 -83
- package/templates/.claude/skills/scaffold-commerce/templates/checkout-route.template.ts +0 -370
- package/templates/.claude/skills/scaffold-commerce/templates/invoice-route.template.ts +0 -376
- package/templates/.claude/skills/scaffold-commerce/templates/marketplace-cta-route.tsx.tmpl +0 -72
- package/templates/.claude/skills/scaffold-commerce/templates/payment-link-route.template.ts +0 -471
- package/templates/.claude/skills/scaffold-commerce/templates/portal-route.template.ts +0 -365
- package/templates/.claude/skills/scaffold-commerce/templates/stripe-config.template.ts +0 -60
- package/templates/.claude/skills/scaffold-commerce/templates/subscription-route.template.ts +0 -446
- package/templates/apps/api/src/__tests__/server.test.ts +0 -253
- package/templates/apps/api/src/bin/deliverable-resend.ts +0 -144
- package/templates/apps/api/src/bin/deliverable-upload.ts +0 -114
- package/templates/apps/api/src/bin/followup-sweep.ts +0 -44
- package/templates/apps/api/src/bin/listing-csv-sweep.ts +0 -46
- package/templates/apps/api/src/bin/seed-presets.ts +0 -58
- package/templates/apps/api/src/bin/seed-waitlist-experiments.ts +0 -104
- package/templates/apps/api/src/bin/session-retention-sweep.ts +0 -46
- package/templates/apps/api/src/lib/__tests__/stripe.test.ts +0 -74
- package/templates/apps/api/src/lib/stripe.ts +0 -52
- package/templates/apps/api/src/lib/tenant-db.ts +0 -225
- package/templates/apps/api/src/lib/ws-token.ts +0 -91
- package/templates/apps/api/src/middleware/tenant.ts +0 -99
- package/templates/apps/api/src/routes/billing/__tests__/portal.test.ts +0 -450
- package/templates/apps/api/src/routes/billing/__tests__/read.test.ts +0 -262
- package/templates/apps/api/src/routes/billing/__tests__/usage.test.ts +0 -436
- package/templates/apps/api/src/routes/billing/index.ts +0 -36
- package/templates/apps/api/src/routes/billing/portal.ts +0 -182
- package/templates/apps/api/src/routes/billing/read.ts +0 -75
- package/templates/apps/api/src/routes/billing/usage.ts +0 -153
- package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +0 -687
- package/templates/apps/api/src/routes/checkout/index.ts +0 -13
- package/templates/apps/api/src/routes/checkout/sessions.ts +0 -197
- package/templates/apps/api/src/routes/deliverables/__tests__/index.test.ts +0 -393
- package/templates/apps/api/src/routes/deliverables/index.ts +0 -200
- package/templates/apps/api/src/routes/flow-checkouts/__tests__/index.test.ts +0 -443
- package/templates/apps/api/src/routes/flow-checkouts/index.ts +0 -82
- package/templates/apps/api/src/routes/flows/README.md +0 -147
- package/templates/apps/api/src/routes/flows/__tests__/index.test.ts +0 -752
- package/templates/apps/api/src/routes/flows/__tests__/recommender.test.ts +0 -671
- package/templates/apps/api/src/routes/flows/index.ts +0 -202
- package/templates/apps/api/src/routes/flows/recommender.ts +0 -443
- package/templates/apps/api/src/routes/project-listings/__tests__/copy-edit.test.ts +0 -815
- package/templates/apps/api/src/routes/project-listings/__tests__/me-route-precedence.test.ts +0 -221
- package/templates/apps/api/src/routes/project-listings/__tests__/tenant-isolation.test.ts +0 -566
- package/templates/apps/api/src/routes/project-listings/get.ts +0 -70
- package/templates/apps/api/src/routes/project-listings/list.ts +0 -47
- package/templates/apps/api/src/routes/project-listings/patch.ts +0 -136
- package/templates/apps/api/src/routes/schedule/__tests__/index.test.ts +0 -490
- package/templates/apps/api/src/routes/schedule/index.ts +0 -249
- package/templates/apps/api/src/routes/slack/__tests__/actions.test.ts +0 -385
- package/templates/apps/api/src/routes/slack/actions.ts +0 -177
- package/templates/apps/api/src/routes/slack/index.ts +0 -38
- package/templates/apps/api/src/routes/waitlist-experiments/__tests__/tenant-isolation.test.ts +0 -577
- package/templates/apps/api/src/routes/waitlist-experiments/comparison.ts +0 -78
- package/templates/apps/api/src/routes/waitlist-experiments/index.ts +0 -41
- package/templates/apps/api/src/routes/waitlist-experiments/list.ts +0 -64
- package/templates/apps/api/src/routes/waitlist-experiments/respond.ts +0 -42
- package/templates/apps/api/src/routes/waitlist-experiments/signup.ts +0 -84
- package/templates/apps/api/src/routes/waitlist-experiments/signups.ts +0 -119
- package/templates/apps/api/src/routes/waitlist-signups/__tests__/index.test.ts +0 -238
- package/templates/apps/api/src/routes/waitlist-signups/index.ts +0 -101
- package/templates/apps/api/src/routes/webhooks/README.md +0 -80
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +0 -315
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe-idempotency.test.ts +0 -247
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe-org-billing.test.ts +0 -270
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe-rate-limit.test.ts +0 -198
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe.test.ts +0 -633
- package/templates/apps/api/src/routes/webhooks/index.ts +0 -41
- package/templates/apps/api/src/routes/webhooks/stripe.ts +0 -481
- package/templates/apps/api/src/routes/workspaces/__tests__/config-tenant-isolation.test.ts +0 -356
- package/templates/apps/api/src/routes/workspaces/__tests__/tenant-isolation.test.ts +0 -671
- package/templates/apps/api/src/routes/workspaces/config.ts +0 -125
- package/templates/apps/api/src/routes/workspaces/index.ts +0 -194
- package/templates/apps/api/src/routes/workspaces/sessions.ts +0 -218
- package/templates/apps/api/src/services/__tests__/flow-aggregate.test.ts +0 -425
- package/templates/apps/api/src/services/__tests__/flow-engine.test.ts +0 -2840
- package/templates/apps/api/src/services/__tests__/lead-promotion.test.ts +0 -393
- package/templates/apps/api/src/services/__tests__/listing-csv-sweep.test.ts +0 -560
- package/templates/apps/api/src/services/__tests__/listing-promotion.test.ts +0 -684
- package/templates/apps/api/src/services/__tests__/playbook-compile.test.ts +0 -406
- package/templates/apps/api/src/services/__tests__/playbook-render.test.ts +0 -290
- package/templates/apps/api/src/services/__tests__/project-listing-decision.test.ts +0 -736
- package/templates/apps/api/src/services/__tests__/project-listing-flow.test.ts +0 -475
- package/templates/apps/api/src/services/__tests__/project-listing-issue.test.ts +0 -340
- package/templates/apps/api/src/services/__tests__/recommender-capture.test.ts +0 -983
- package/templates/apps/api/src/services/__tests__/tenant-context-cascade.test.ts +0 -71
- package/templates/apps/api/src/services/__tests__/tenant-context.test.ts +0 -379
- package/templates/apps/api/src/services/__tests__/usage-metering.test.ts +0 -768
- package/templates/apps/api/src/services/__tests__/waitlist-dashboard.test.ts +0 -1314
- package/templates/apps/api/src/services/__tests__/waitlist-experiments.test.ts +0 -341
- package/templates/apps/api/src/services/__tests__/waitlist-followup.test.ts +0 -567
- package/templates/apps/api/src/services/__tests__/waitlist-scoring.test.ts +0 -474
- package/templates/apps/api/src/services/__tests__/waitlist-signups.test.ts +0 -354
- package/templates/apps/api/src/services/flow-aggregate.ts +0 -232
- package/templates/apps/api/src/services/flow-checkouts.ts +0 -123
- package/templates/apps/api/src/services/flow-engine.ts +0 -1296
- package/templates/apps/api/src/services/lead-promotion.ts +0 -176
- package/templates/apps/api/src/services/listing-csv-sweep.ts +0 -455
- package/templates/apps/api/src/services/listing-promotion.ts +0 -342
- package/templates/apps/api/src/services/playbook-compile.ts +0 -398
- package/templates/apps/api/src/services/playbook-render.ts +0 -263
- package/templates/apps/api/src/services/project-listing-decision.ts +0 -510
- package/templates/apps/api/src/services/project-listing-flow.ts +0 -426
- package/templates/apps/api/src/services/project-listing-issue.ts +0 -251
- package/templates/apps/api/src/services/recommender-capture.ts +0 -835
- package/templates/apps/api/src/services/scheduling/cal-provider.ts +0 -392
- package/templates/apps/api/src/services/scheduling/index.ts +0 -63
- package/templates/apps/api/src/services/scheduling/types.ts +0 -88
- package/templates/apps/api/src/services/tenant-context.ts +0 -451
- package/templates/apps/api/src/services/usage-metering.ts +0 -699
- package/templates/apps/api/src/services/waitlist-dashboard.ts +0 -947
- package/templates/apps/api/src/services/waitlist-experiments.ts +0 -213
- package/templates/apps/api/src/services/waitlist-followup.ts +0 -486
- package/templates/apps/api/src/services/waitlist-scoring.ts +0 -166
- package/templates/apps/api/src/services/waitlist-signups.ts +0 -165
- package/templates/apps/mcp/__tests__/schedule_tools.test.ts +0 -242
- package/templates/apps/mcp/src/tools/create_booking.ts +0 -58
- package/templates/apps/mcp/src/tools/get_event_meta.ts +0 -55
- package/templates/apps/mcp/src/tools/get_flow.ts +0 -61
- package/templates/apps/mcp/src/tools/list_availability.ts +0 -67
- package/templates/apps/mcp/src/tools/submit_flow_step.ts +0 -83
- package/templates/apps/web/app/[locale]/(authed)/waitlist/[experimentId]/page.tsx +0 -309
- package/templates/apps/web/app/[locale]/(authed)/waitlist/[experimentId]/signups/[leadId]/page.tsx +0 -149
- package/templates/apps/web/app/[locale]/(authed)/waitlist/__tests__/comparison.test.tsx +0 -273
- package/templates/apps/web/app/[locale]/(authed)/waitlist/__tests__/list.test.tsx +0 -171
- package/templates/apps/web/app/[locale]/(authed)/waitlist/__tests__/signup.test.tsx +0 -179
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/ExperimentsTable.tsx +0 -116
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/OfferFunnelTable.tsx +0 -66
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/RollupTicker.tsx +0 -61
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/ScoreTrace.tsx +0 -114
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/SignupsTable.tsx +0 -139
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/WaitlistComparisonTabs.tsx +0 -85
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/status-badges.tsx +0 -67
- package/templates/apps/web/app/[locale]/(authed)/waitlist/page.tsx +0 -179
- package/templates/apps/web/app/[locale]/blog/[[...slug]]/page.tsx +0 -178
- package/templates/apps/web/app/[locale]/dev/purchase/__tests__/actions.test.ts +0 -160
- package/templates/apps/web/app/[locale]/dev/purchase/error.tsx +0 -25
- package/templates/apps/web/app/[locale]/dev/purchase/page.tsx +0 -117
- package/templates/apps/web/app/[locale]/dev/purchase/purchase.actions.ts +0 -58
- package/templates/apps/web/app/[locale]/docs/[[...slug]]/page.tsx +0 -119
- package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/checkout.actions.test.ts +0 -287
- package/templates/apps/web/app/[locale]/flows/[slug]/checkout.actions.ts +0 -254
- package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +0 -532
- package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsEmailStep.tsx +0 -121
- package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.checkout.test.tsx +0 -457
- package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/page.test.tsx +0 -396
- package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/page.tsx +0 -114
- package/templates/apps/web/app/[locale]/projects/apply/ListingApplicationClient.tsx +0 -110
- package/templates/apps/web/app/[locale]/projects/apply/__tests__/ListingApplicationClient.test.tsx +0 -96
- package/templates/apps/web/app/[locale]/schedule/__tests__/page.test.tsx +0 -117
- package/templates/apps/web/app/[locale]/schedule/confirmed/__tests__/page.test.tsx +0 -96
- package/templates/apps/web/app/[locale]/schedule/confirmed/page.tsx +0 -92
- package/templates/apps/web/app/[locale]/schedule/page.tsx +0 -82
- package/templates/apps/web/content/en/blog/README.txt +0 -25
- package/templates/apps/web/content/en/docs/index.mdx +0 -28
- package/templates/apps/web/lib/__mocks__/source-server.js +0 -31
- package/templates/apps/web/lib/blog-list-data.ts +0 -95
- package/templates/apps/web/lib/blog-post-data.ts +0 -79
- package/templates/apps/web/lib/source.ts +0 -34
- package/templates/apps/web/public/logomark-dark.svg +0 -4
- package/templates/apps/web/public/logomark-light.svg +0 -4
- package/templates/apps/web/source.config.ts +0 -78
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
# Webhooks — `apps/api/src/routes/webhooks/`
|
|
2
|
-
|
|
3
|
-
Stripe webhook receiver at `POST /v1/webhooks/stripe`. Verifies
|
|
4
|
-
signatures, dispatches events via a `switch`, and fires server-side
|
|
5
|
-
telemetry. Handles `customer.created`, `checkout.session.completed`, and
|
|
6
|
-
`checkout.session.expired` (the last two also stamp the recommender's
|
|
7
|
-
buyer row — below).
|
|
8
|
-
|
|
9
|
-
## How to add a new event handler
|
|
10
|
-
|
|
11
|
-
Add a `case` arm to the `switch` in `stripe.ts`:
|
|
12
|
-
|
|
13
|
-
```ts
|
|
14
|
-
case "invoice.payment_succeeded": {
|
|
15
|
-
const invoice = event.data.object as { ... };
|
|
16
|
-
await fireTelemetryWithTimeout(request, "invoice-paid", { ... });
|
|
17
|
-
break;
|
|
18
|
-
}
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
Customer forks edit `stripe.ts` directly. v1 ships no pluggable handler
|
|
22
|
-
registry — if multiple forks request one, file an issue.
|
|
23
|
-
|
|
24
|
-
## Recommender purchase stamp (#4838)
|
|
25
|
-
|
|
26
|
-
A Checkout Session the recommender opened (`POST /v1/flows/:slug/checkout`,
|
|
27
|
-
#4841) carries `metadata.flowCheckoutId` — the `FlowCheckout` buyer row's
|
|
28
|
-
id. On `checkout.session.completed` the handler stamps that row
|
|
29
|
-
`status: "completed"` (+ `completedAt`, `stripeSessionId`,
|
|
30
|
-
`stripeCustomerId`); on `checkout.session.expired` it stamps
|
|
31
|
-
`status: "expired"`. Both are ONE guarded update —
|
|
32
|
-
`updateMany({ where: { id, status: "created" } })` — so the stamp is
|
|
33
|
-
at-most-once regardless of the in-memory store below: a replay, a restart
|
|
34
|
-
between deliveries, or a late `expired` after a `completed` matches zero
|
|
35
|
-
rows and logs `outcome: "stale_or_unknown"`. A charged `amount_total` that
|
|
36
|
-
differs from the quoted `amountMinor` is logged (`expected` / `received`)
|
|
37
|
-
and the row is still stamped — the quote is never overwritten. The stamp
|
|
38
|
-
runs beside the telemetry + billing tasks, never instead of them, and an
|
|
39
|
-
event without the key never touches `flowCheckout`. Always 200.
|
|
40
|
-
|
|
41
|
-
## Idempotency caveat (load-bearing)
|
|
42
|
-
|
|
43
|
-
Stripe uses **at-least-once delivery semantics** and occasionally
|
|
44
|
-
double-delivers events. The in-memory store (`lib/webhook-idempotency.ts`)
|
|
45
|
-
short-circuits a replayed `event.id` within one process; it is not durable
|
|
46
|
-
across a restart or a second API instance. Telemetry-only side effects make
|
|
47
|
-
that an acceptable counting drift.
|
|
48
|
-
|
|
49
|
-
**A side effect with write semantics carries its own durable layer.** The
|
|
50
|
-
recommender stamp above uses a guarded conditional update (the row's
|
|
51
|
-
`status: "created"` is the key). A future write that cannot be expressed as
|
|
52
|
-
a guarded update (confirmation email, refund processing) needs a
|
|
53
|
-
`webhook_events` table keyed on `event.id` with an early-return for
|
|
54
|
-
already-seen IDs — add it first.
|
|
55
|
-
|
|
56
|
-
## Env contract
|
|
57
|
-
|
|
58
|
-
Both vars are **server-only** — never use a `NEXT_PUBLIC_` prefix.
|
|
59
|
-
|
|
60
|
-
| Var | Required | Notes |
|
|
61
|
-
| ----------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
62
|
-
| `STRIPE_WEBHOOK_SECRET` | For the route to do anything | `whsec_*` from Stripe Dashboard |
|
|
63
|
-
| `STRIPE_SECRET_KEY` | For checkout + sandbox check | Must match an allow-listed test-mode prefix (`sk_test_*` / `pk_test_*` / `rk_test_*`); anything else — including live and restricted-live keys — is runtime-blocked by `assertSandboxKey`. The commit-time hook is a partial backstop only: it greps for `sk_live_` / `pk_live_` and does **not** catch restricted-live (`rk_live_`) keys, so the runtime allow-list is the load-bearing guard |
|
|
64
|
-
|
|
65
|
-
Without `STRIPE_WEBHOOK_SECRET`, the route returns 503 on every request.
|
|
66
|
-
|
|
67
|
-
## Deployment note
|
|
68
|
-
|
|
69
|
-
Customer forks must:
|
|
70
|
-
|
|
71
|
-
1. Configure a Stripe Dashboard webhook endpoint pointing at
|
|
72
|
-
`https://<your-host>/v1/webhooks/stripe`.
|
|
73
|
-
2. Copy the endpoint's **Signing secret** (`whsec_*`) into
|
|
74
|
-
`STRIPE_WEBHOOK_SECRET` in their environment.
|
|
75
|
-
|
|
76
|
-
Without both, telemetry will not fire and 503s will be logged.
|
|
77
|
-
|
|
78
|
-
## Brief
|
|
79
|
-
|
|
80
|
-
`docs/internal/decisions/ailk-stripe-webhook-receiver.md`
|
|
@@ -1,315 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* POST /api/webhooks/stripe — the recommender FlowCheckout stamp (#4838).
|
|
3
|
-
*
|
|
4
|
-
* The stripe.test.ts mock shape: `@working-theory/analytics/server` `track`,
|
|
5
|
-
* the prisma auto-mock, `@working-theory/stripe-client`'s
|
|
6
|
-
* `verifyWebhookSignature` at the package boundary. AC-1 … AC-5. The four
|
|
7
|
-
* pre-existing webhook suites are the regression floor and are not edited.
|
|
8
|
-
* AC-6 (#4862) adds the `no_payment_required` (zero-due) case.
|
|
9
|
-
*/
|
|
10
|
-
import type { FastifyInstance } from "fastify";
|
|
11
|
-
import Fastify from "fastify";
|
|
12
|
-
|
|
13
|
-
const mockTrack = jest.fn().mockResolvedValue(undefined);
|
|
14
|
-
jest.mock("@working-theory/analytics/server", () => ({
|
|
15
|
-
track: (...args: unknown[]) => mockTrack(...args),
|
|
16
|
-
}));
|
|
17
|
-
|
|
18
|
-
// eslint-disable-next-line no-restricted-syntax -- lib/prisma.ts wraps the external DB boundary (PrismaClient requires a live connection); __mocks__/prisma.ts is the repo-standard test double for this boundary.
|
|
19
|
-
jest.mock("../../../lib/prisma.js");
|
|
20
|
-
|
|
21
|
-
const mockVerifyWebhookSignature = jest.fn();
|
|
22
|
-
class MockStripeWebhookSignatureError extends Error {
|
|
23
|
-
constructor(message: string) {
|
|
24
|
-
super(message);
|
|
25
|
-
this.name = "StripeWebhookSignatureError";
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
jest.mock("@working-theory/stripe-client", () => ({
|
|
29
|
-
verifyWebhookSignature: (...args: unknown[]) => mockVerifyWebhookSignature(...args),
|
|
30
|
-
StripeWebhookSignatureError: MockStripeWebhookSignatureError,
|
|
31
|
-
assertSandboxKey: jest.fn(),
|
|
32
|
-
createCheckoutSession: jest.fn(),
|
|
33
|
-
getStripeClient: jest.fn(),
|
|
34
|
-
STRIPE_API_VERSION: "2024-06-20",
|
|
35
|
-
StripeConfigError: class StripeConfigError extends Error {},
|
|
36
|
-
UnknownProductCodeError: class UnknownProductCodeError extends Error {},
|
|
37
|
-
WEBHOOK_TOLERANCE_SECONDS: 300,
|
|
38
|
-
}));
|
|
39
|
-
|
|
40
|
-
import * as configModule from "../../../config/index.js";
|
|
41
|
-
import { stripeWebhookHandler } from "../stripe.js";
|
|
42
|
-
import { __resetIdempotencyStore } from "../../../lib/webhook-idempotency.js";
|
|
43
|
-
import { prisma } from "../../../lib/prisma.js";
|
|
44
|
-
|
|
45
|
-
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
46
|
-
|
|
47
|
-
const FLOW_CHECKOUT_ID = "flchk_test_1";
|
|
48
|
-
const SESSION_ID = "cs_test_session_12345678901234567890";
|
|
49
|
-
const CUSTOMER_ID = "cus_test_12345678901234567890";
|
|
50
|
-
const EMAIL = "alice@example.com";
|
|
51
|
-
const PERMALINK = "eyJ2ZXJzaW9uIjoxLCJmbG93U2x1ZyI6ImFpbGstcmVjbyJ9";
|
|
52
|
-
|
|
53
|
-
function sessionEvent(type: "checkout.session.completed" | "checkout.session.expired", object: Record<string, unknown> = {}) {
|
|
54
|
-
return {
|
|
55
|
-
id: "evt_test_12345678abcdef",
|
|
56
|
-
type,
|
|
57
|
-
data: {
|
|
58
|
-
object: {
|
|
59
|
-
id: SESSION_ID,
|
|
60
|
-
payment_status: "paid",
|
|
61
|
-
amount_total: 24900,
|
|
62
|
-
currency: "usd",
|
|
63
|
-
customer: CUSTOMER_ID,
|
|
64
|
-
customer_details: { email: EMAIL },
|
|
65
|
-
metadata: { flowCheckoutId: FLOW_CHECKOUT_ID, flowSlug: "ailk-reco", offerKey: "pro", permalink: PERMALINK },
|
|
66
|
-
...object,
|
|
67
|
-
},
|
|
68
|
-
},
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
type LogCall = [unknown, string?];
|
|
73
|
-
const logCalls: LogCall[] = [];
|
|
74
|
-
|
|
75
|
-
async function buildTestServer(): Promise<FastifyInstance> {
|
|
76
|
-
const server = Fastify({ logger: false });
|
|
77
|
-
await server.register(async (webhooksScope) => {
|
|
78
|
-
webhooksScope.addContentTypeParser("application/json", { parseAs: "buffer" }, (_req, body, done) => {
|
|
79
|
-
done(null, body);
|
|
80
|
-
});
|
|
81
|
-
webhooksScope.addHook("onRequest", async (request) => {
|
|
82
|
-
for (const level of ["info", "warn", "error"] as const) {
|
|
83
|
-
const original = request.log[level].bind(request.log);
|
|
84
|
-
request.log[level] = ((...args: unknown[]) => {
|
|
85
|
-
logCalls.push(args as LogCall);
|
|
86
|
-
return (original as (...a: unknown[]) => void)(...args);
|
|
87
|
-
}) as typeof request.log.info;
|
|
88
|
-
}
|
|
89
|
-
});
|
|
90
|
-
webhooksScope.post("/v1/webhooks/stripe", stripeWebhookHandler);
|
|
91
|
-
});
|
|
92
|
-
await server.ready();
|
|
93
|
-
return server;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
const VALID_BODY = Buffer.from(JSON.stringify({ type: "test" }));
|
|
97
|
-
const HEADERS = { "content-type": "application/json", "stripe-signature": "t=1234,v1=abc" };
|
|
98
|
-
|
|
99
|
-
let server: FastifyInstance;
|
|
100
|
-
|
|
101
|
-
beforeEach(async () => {
|
|
102
|
-
jest.clearAllMocks();
|
|
103
|
-
logCalls.length = 0;
|
|
104
|
-
__resetIdempotencyStore();
|
|
105
|
-
jest.replaceProperty(configModule, "config", {
|
|
106
|
-
...configModule.config,
|
|
107
|
-
STRIPE_WEBHOOK_SECRET: "whsec_test_secret",
|
|
108
|
-
});
|
|
109
|
-
(prisma.flowCheckout.findUnique as jest.Mock).mockResolvedValue({ amountMinor: 24900 });
|
|
110
|
-
(prisma.flowCheckout.updateMany as jest.Mock).mockResolvedValue({ count: 1 });
|
|
111
|
-
(prisma.user.findFirst as jest.Mock).mockResolvedValue(null);
|
|
112
|
-
(prisma.user.findUnique as jest.Mock).mockResolvedValue(null);
|
|
113
|
-
server = await buildTestServer();
|
|
114
|
-
});
|
|
115
|
-
|
|
116
|
-
afterEach(async () => {
|
|
117
|
-
await server.close();
|
|
118
|
-
jest.restoreAllMocks();
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
async function post() {
|
|
122
|
-
return server.inject({ method: "POST", url: "/v1/webhooks/stripe", payload: VALID_BODY, headers: HEADERS });
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
function stampCall() {
|
|
126
|
-
expect(prisma.flowCheckout.updateMany).toHaveBeenCalledTimes(1);
|
|
127
|
-
return (prisma.flowCheckout.updateMany as jest.Mock).mock.calls[0][0];
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// ── AC-1 — completed stamps the row once, guarded, beside the legacy tasks ──
|
|
131
|
-
|
|
132
|
-
describe("AC-1 — completed stamps the row once, guarded, beside the legacy tasks", () => {
|
|
133
|
-
it("stamps completed with the guard, the session id and the customer; telemetry + billing still run", async () => {
|
|
134
|
-
mockVerifyWebhookSignature.mockReturnValue(sessionEvent("checkout.session.completed"));
|
|
135
|
-
const res = await post();
|
|
136
|
-
expect(res.statusCode).toBe(200);
|
|
137
|
-
expect(JSON.parse(res.body)).toEqual({ received: true });
|
|
138
|
-
|
|
139
|
-
const call = stampCall();
|
|
140
|
-
expect(call.where).toEqual({ id: FLOW_CHECKOUT_ID, status: "created" });
|
|
141
|
-
expect(call.data.status).toBe("completed");
|
|
142
|
-
expect(call.data.completedAt).toBeInstanceOf(Date);
|
|
143
|
-
expect(call.data.stripeSessionId).toBe(SESSION_ID);
|
|
144
|
-
expect(call.data.stripeCustomerId).toBe(CUSTOMER_ID);
|
|
145
|
-
|
|
146
|
-
// The legacy tasks, exactly as stripe.test.ts asserts them.
|
|
147
|
-
expect(mockTrack).toHaveBeenCalledTimes(1);
|
|
148
|
-
expect(mockTrack).toHaveBeenCalledWith("purchase-completed", {
|
|
149
|
-
amount: 24900,
|
|
150
|
-
currency: "usd",
|
|
151
|
-
productId: undefined,
|
|
152
|
-
eventType: "checkout.session.completed",
|
|
153
|
-
eventIdPrefix: "evt_test",
|
|
154
|
-
});
|
|
155
|
-
expect(prisma.user.findFirst).toHaveBeenCalledWith({
|
|
156
|
-
where: { billingProvider: "stripe", billingCustomerId: CUSTOMER_ID },
|
|
157
|
-
});
|
|
158
|
-
expect(prisma.user.findUnique).toHaveBeenCalledWith({ where: { email: EMAIL } });
|
|
159
|
-
});
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
// ── AC-2 — expired stamps expired ───────────────────────────────────────────
|
|
163
|
-
|
|
164
|
-
describe("AC-2 — expired stamps expired", () => {
|
|
165
|
-
it("stamps status expired under the same guard, with no completedAt", async () => {
|
|
166
|
-
mockVerifyWebhookSignature.mockReturnValue(sessionEvent("checkout.session.expired"));
|
|
167
|
-
const res = await post();
|
|
168
|
-
expect(res.statusCode).toBe(200);
|
|
169
|
-
const call = stampCall();
|
|
170
|
-
expect(call.where.status).toBe("created");
|
|
171
|
-
expect(call.where.id).toBe(FLOW_CHECKOUT_ID);
|
|
172
|
-
expect(call.data).toEqual({ status: "expired" });
|
|
173
|
-
expect(call.data).not.toHaveProperty("completedAt");
|
|
174
|
-
expect(prisma.flowCheckout.findUnique).not.toHaveBeenCalled();
|
|
175
|
-
expect(mockTrack).not.toHaveBeenCalled();
|
|
176
|
-
});
|
|
177
|
-
});
|
|
178
|
-
|
|
179
|
-
// ── AC-3 — the legacy paths are byte-unchanged ──────────────────────────────
|
|
180
|
-
|
|
181
|
-
describe("AC-3 — the legacy paths are byte-unchanged", () => {
|
|
182
|
-
it("an event without flowCheckoutId never touches prisma.flowCheckout", async () => {
|
|
183
|
-
mockVerifyWebhookSignature.mockReturnValue(
|
|
184
|
-
sessionEvent("checkout.session.completed", { metadata: { productId: "starter" } }),
|
|
185
|
-
);
|
|
186
|
-
const res = await post();
|
|
187
|
-
expect(res.statusCode).toBe(200);
|
|
188
|
-
expect(prisma.flowCheckout.findUnique).not.toHaveBeenCalled();
|
|
189
|
-
expect(prisma.flowCheckout.updateMany).not.toHaveBeenCalled();
|
|
190
|
-
expect(mockTrack).toHaveBeenCalledTimes(1);
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
it("an expired event without the key is a no-op 200 that logs the unhandled-event line", async () => {
|
|
194
|
-
mockVerifyWebhookSignature.mockReturnValue(sessionEvent("checkout.session.expired", { metadata: null }));
|
|
195
|
-
expect((await post()).statusCode).toBe(200);
|
|
196
|
-
expect(prisma.flowCheckout.updateMany).not.toHaveBeenCalled();
|
|
197
|
-
const unhandled = logCalls.find((c) => c[1] === "unhandled webhook event");
|
|
198
|
-
expect(unhandled?.[0]).toEqual({ eventType: "checkout.session.expired", eventIdPrefix: "evt_test" });
|
|
199
|
-
});
|
|
200
|
-
|
|
201
|
-
it("a completed session that is not paid logs `unpaid` and does NOT stamp — the row stays created", async () => {
|
|
202
|
-
mockVerifyWebhookSignature.mockReturnValue(
|
|
203
|
-
sessionEvent("checkout.session.completed", { payment_status: "unpaid" }),
|
|
204
|
-
);
|
|
205
|
-
expect((await post()).statusCode).toBe(200);
|
|
206
|
-
expect(prisma.flowCheckout.findUnique).not.toHaveBeenCalled();
|
|
207
|
-
expect(prisma.flowCheckout.updateMany).not.toHaveBeenCalled();
|
|
208
|
-
const unpaid = logCalls.find((c) => (c[0] as { outcome?: string })?.outcome === "unpaid");
|
|
209
|
-
expect(unpaid?.[0]).toEqual({
|
|
210
|
-
eventIdPrefix: "evt_test",
|
|
211
|
-
flowCheckoutIdPrefix: FLOW_CHECKOUT_ID.substring(0, 8),
|
|
212
|
-
outcome: "unpaid",
|
|
213
|
-
});
|
|
214
|
-
// The legacy tasks still ran for the event.
|
|
215
|
-
expect(mockTrack).toHaveBeenCalledTimes(1);
|
|
216
|
-
});
|
|
217
|
-
});
|
|
218
|
-
|
|
219
|
-
// ── AC-6 — a zero-due (no_payment_required) session stamps completed ───────
|
|
220
|
-
|
|
221
|
-
describe("AC-6 — no_payment_required stamps completed exactly as paid (#4862)", () => {
|
|
222
|
-
it("stamps completed with the guard, the session id and the customer; telemetry + billing still run", async () => {
|
|
223
|
-
mockVerifyWebhookSignature.mockReturnValue(
|
|
224
|
-
sessionEvent("checkout.session.completed", { payment_status: "no_payment_required" }),
|
|
225
|
-
);
|
|
226
|
-
const res = await post();
|
|
227
|
-
expect(res.statusCode).toBe(200);
|
|
228
|
-
expect(JSON.parse(res.body)).toEqual({ received: true });
|
|
229
|
-
|
|
230
|
-
const call = stampCall();
|
|
231
|
-
expect(call.where).toEqual({ id: FLOW_CHECKOUT_ID, status: "created" });
|
|
232
|
-
expect(call.data.status).toBe("completed");
|
|
233
|
-
expect(call.data.completedAt).toBeInstanceOf(Date);
|
|
234
|
-
expect(call.data.stripeSessionId).toBe(SESSION_ID);
|
|
235
|
-
expect(call.data.stripeCustomerId).toBe(CUSTOMER_ID);
|
|
236
|
-
|
|
237
|
-
expect(mockTrack).toHaveBeenCalledTimes(1);
|
|
238
|
-
const unpaid = logCalls.find((c) => (c[0] as { outcome?: string })?.outcome === "unpaid");
|
|
239
|
-
expect(unpaid).toBeUndefined();
|
|
240
|
-
});
|
|
241
|
-
});
|
|
242
|
-
|
|
243
|
-
// ── AC-4 — never a retry storm ──────────────────────────────────────────────
|
|
244
|
-
|
|
245
|
-
describe("AC-4 — never a retry storm", () => {
|
|
246
|
-
it("count 0 logs stale_or_unknown and still 200s", async () => {
|
|
247
|
-
(prisma.flowCheckout.updateMany as jest.Mock).mockResolvedValue({ count: 0 });
|
|
248
|
-
mockVerifyWebhookSignature.mockReturnValue(sessionEvent("checkout.session.completed"));
|
|
249
|
-
expect((await post()).statusCode).toBe(200);
|
|
250
|
-
const stale = logCalls.find((c) => (c[0] as { outcome?: string })?.outcome === "stale_or_unknown");
|
|
251
|
-
expect(stale).toBeDefined();
|
|
252
|
-
});
|
|
253
|
-
|
|
254
|
-
it("an updateMany rejection logs an error and still 200s", async () => {
|
|
255
|
-
(prisma.flowCheckout.updateMany as jest.Mock).mockRejectedValue(new Error("db down"));
|
|
256
|
-
mockVerifyWebhookSignature.mockReturnValue(sessionEvent("checkout.session.completed"));
|
|
257
|
-
expect((await post()).statusCode).toBe(200);
|
|
258
|
-
const failed = logCalls.find((c) => (c[0] as { outcome?: string })?.outcome === "stamp_failed");
|
|
259
|
-
expect(failed).toBeDefined();
|
|
260
|
-
});
|
|
261
|
-
|
|
262
|
-
it("a charged amount that differs from the quote logs both integers and STILL stamps completed", async () => {
|
|
263
|
-
mockVerifyWebhookSignature.mockReturnValue(sessionEvent("checkout.session.completed", { amount_total: 25000 }));
|
|
264
|
-
expect((await post()).statusCode).toBe(200);
|
|
265
|
-
const mismatch = logCalls.find((c) => (c[0] as { outcome?: string })?.outcome === "amount_mismatch");
|
|
266
|
-
expect(mismatch?.[0]).toEqual({
|
|
267
|
-
eventIdPrefix: "evt_test",
|
|
268
|
-
flowCheckoutIdPrefix: FLOW_CHECKOUT_ID.substring(0, 8),
|
|
269
|
-
outcome: "amount_mismatch",
|
|
270
|
-
expected: 24900,
|
|
271
|
-
received: 25000,
|
|
272
|
-
});
|
|
273
|
-
expect(stampCall().data.status).toBe("completed");
|
|
274
|
-
});
|
|
275
|
-
});
|
|
276
|
-
|
|
277
|
-
// ── AC-5 — PII boundary ─────────────────────────────────────────────────────
|
|
278
|
-
|
|
279
|
-
describe("AC-5 — PII boundary", () => {
|
|
280
|
-
it.each([
|
|
281
|
-
["the AC-1 event", sessionEvent("checkout.session.completed"), null],
|
|
282
|
-
["the AC-4 mismatch event", sessionEvent("checkout.session.completed", { amount_total: 25000 }), null],
|
|
283
|
-
[
|
|
284
|
-
"the stamp_failed branch",
|
|
285
|
-
sessionEvent("checkout.session.completed"),
|
|
286
|
-
new Error(`connection refused for ${EMAIL} at ${CUSTOMER_ID}`),
|
|
287
|
-
],
|
|
288
|
-
])("every log line for %s carries no email, customer_details, permalink, or a full cus_/cs_ id", async (_name, event, rejection) => {
|
|
289
|
-
if (rejection) (prisma.flowCheckout.updateMany as jest.Mock).mockRejectedValue(rejection);
|
|
290
|
-
mockVerifyWebhookSignature.mockReturnValue(event);
|
|
291
|
-
expect((await post()).statusCode).toBe(200);
|
|
292
|
-
const ALLOWED = new Set(["eventIdPrefix", "flowCheckoutIdPrefix", "outcome", "expected", "received", "errName"]);
|
|
293
|
-
const stampLines = logCalls.filter((c) => typeof c[0] === "object" && c[0] !== null && "flowCheckoutIdPrefix" in c[0]);
|
|
294
|
-
expect(stampLines.length).toBeGreaterThan(0);
|
|
295
|
-
for (const line of stampLines) {
|
|
296
|
-
for (const key of Object.keys(line[0] as object)) expect(ALLOWED.has(key)).toBe(true);
|
|
297
|
-
}
|
|
298
|
-
if (rejection) {
|
|
299
|
-
const failed = stampLines.find((c) => (c[0] as { outcome?: string }).outcome === "stamp_failed");
|
|
300
|
-
expect(failed?.[0]).toEqual({
|
|
301
|
-
eventIdPrefix: "evt_test",
|
|
302
|
-
flowCheckoutIdPrefix: FLOW_CHECKOUT_ID.substring(0, 8),
|
|
303
|
-
outcome: "stamp_failed",
|
|
304
|
-
errName: "Error",
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
for (const line of logCalls) {
|
|
308
|
-
const text = JSON.stringify(line);
|
|
309
|
-
expect(text).not.toContain(EMAIL);
|
|
310
|
-
expect(text).not.toContain("customer_details");
|
|
311
|
-
expect(text).not.toContain(PERMALINK);
|
|
312
|
-
for (const token of text.match(/\b(?:cus|cs)_[A-Za-z0-9_]+/g) ?? []) expect(token.length).toBeLessThanOrEqual(8);
|
|
313
|
-
}
|
|
314
|
-
});
|
|
315
|
-
});
|
|
@@ -1,247 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Stripe webhook idempotency — replay protection at the AILK layer.
|
|
3
|
-
*
|
|
4
|
-
* Stripe guarantees at-least-once delivery; an `event.id` can arrive multiple
|
|
5
|
-
* times (network retries, dashboard manual replay). The handler MUST be
|
|
6
|
-
* idempotent: a second arrival with the same `event.id` returns 200 without
|
|
7
|
-
* re-firing telemetry or any side effect.
|
|
8
|
-
*
|
|
9
|
-
* Implementation: module-scoped store with TTL — see
|
|
10
|
-
* `apps/api/src/lib/webhook-idempotency.ts` for the deliberate single-replica
|
|
11
|
-
* trade-off vs. a durable table.
|
|
12
|
-
*/
|
|
13
|
-
import type { FastifyInstance } from "fastify";
|
|
14
|
-
import Fastify from "fastify";
|
|
15
|
-
|
|
16
|
-
// ── Mocks ────────────────────────────────────────────────────────────────────
|
|
17
|
-
|
|
18
|
-
const mockConfig: { STRIPE_WEBHOOK_SECRET: string | undefined } = {
|
|
19
|
-
STRIPE_WEBHOOK_SECRET: "whsec_test_secret",
|
|
20
|
-
};
|
|
21
|
-
// eslint-disable-next-line no-restricted-syntax -- mirrors stripe.test.ts mock pattern
|
|
22
|
-
jest.mock("../../../config/index.js", () => ({
|
|
23
|
-
get config() {
|
|
24
|
-
return mockConfig;
|
|
25
|
-
},
|
|
26
|
-
}));
|
|
27
|
-
|
|
28
|
-
const mockTrack = jest.fn().mockResolvedValue(undefined);
|
|
29
|
-
jest.mock("@working-theory/analytics/server", () => ({
|
|
30
|
-
track: (...args: unknown[]) => mockTrack(...args),
|
|
31
|
-
}));
|
|
32
|
-
|
|
33
|
-
const mockVerifyWebhookSignature = jest.fn();
|
|
34
|
-
class MockStripeWebhookSignatureError extends Error {
|
|
35
|
-
constructor(message: string) {
|
|
36
|
-
super(message);
|
|
37
|
-
this.name = "StripeWebhookSignatureError";
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
// eslint-disable-next-line no-restricted-syntax -- mirrors stripe.test.ts mock pattern
|
|
41
|
-
jest.mock("../../../lib/stripe.js", () => ({
|
|
42
|
-
verifyWebhookSignature: (...args: unknown[]) =>
|
|
43
|
-
mockVerifyWebhookSignature(...args),
|
|
44
|
-
StripeWebhookSignatureError: MockStripeWebhookSignatureError,
|
|
45
|
-
}));
|
|
46
|
-
|
|
47
|
-
import { stripeWebhookHandler } from "../stripe.js";
|
|
48
|
-
import { __resetIdempotencyStore } from "../../../lib/webhook-idempotency.js";
|
|
49
|
-
|
|
50
|
-
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
51
|
-
|
|
52
|
-
function buildFakeEvent(id: string, overrides: Record<string, unknown> = {}) {
|
|
53
|
-
return {
|
|
54
|
-
id,
|
|
55
|
-
type: "checkout.session.completed",
|
|
56
|
-
data: {
|
|
57
|
-
object: {
|
|
58
|
-
amount_total: 4999,
|
|
59
|
-
currency: "usd",
|
|
60
|
-
metadata: { productId: "starter" },
|
|
61
|
-
},
|
|
62
|
-
},
|
|
63
|
-
...overrides,
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
async function buildTestServer(): Promise<FastifyInstance> {
|
|
68
|
-
const server = Fastify({ logger: false });
|
|
69
|
-
|
|
70
|
-
await server.register(async (webhooksScope) => {
|
|
71
|
-
webhooksScope.addContentTypeParser(
|
|
72
|
-
"application/json",
|
|
73
|
-
{ parseAs: "buffer" },
|
|
74
|
-
(_req, body, done) => {
|
|
75
|
-
done(null, body);
|
|
76
|
-
},
|
|
77
|
-
);
|
|
78
|
-
webhooksScope.post("/v1/webhooks/stripe", stripeWebhookHandler);
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
await server.ready();
|
|
82
|
-
return server;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
const VALID_BODY = Buffer.from(JSON.stringify({ type: "test" }));
|
|
86
|
-
const VALID_SIGNATURE = "t=1234,v1=abc";
|
|
87
|
-
|
|
88
|
-
// ── Tests ────────────────────────────────────────────────────────────────────
|
|
89
|
-
|
|
90
|
-
describe("POST /api/webhooks/stripe — idempotency", () => {
|
|
91
|
-
let server: FastifyInstance;
|
|
92
|
-
|
|
93
|
-
beforeEach(async () => {
|
|
94
|
-
jest.clearAllMocks();
|
|
95
|
-
__resetIdempotencyStore();
|
|
96
|
-
mockConfig.STRIPE_WEBHOOK_SECRET = "whsec_test_secret";
|
|
97
|
-
server = await buildTestServer();
|
|
98
|
-
});
|
|
99
|
-
|
|
100
|
-
afterEach(async () => {
|
|
101
|
-
await server.close();
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
it("processes a first-time event normally (200 + track called)", async () => {
|
|
105
|
-
const event = buildFakeEvent("evt_first_time_aaaa");
|
|
106
|
-
mockVerifyWebhookSignature.mockReturnValue(event);
|
|
107
|
-
|
|
108
|
-
const response = await server.inject({
|
|
109
|
-
method: "POST",
|
|
110
|
-
url: "/v1/webhooks/stripe",
|
|
111
|
-
payload: VALID_BODY,
|
|
112
|
-
headers: {
|
|
113
|
-
"content-type": "application/json",
|
|
114
|
-
"stripe-signature": VALID_SIGNATURE,
|
|
115
|
-
},
|
|
116
|
-
});
|
|
117
|
-
|
|
118
|
-
expect(response.statusCode).toBe(200);
|
|
119
|
-
expect(JSON.parse(response.body)).toEqual({ received: true });
|
|
120
|
-
expect(mockTrack).toHaveBeenCalledTimes(1);
|
|
121
|
-
});
|
|
122
|
-
|
|
123
|
-
it("returns 200 on replay of same event.id without re-firing telemetry", async () => {
|
|
124
|
-
const event = buildFakeEvent("evt_replay_same_id_bbbb");
|
|
125
|
-
mockVerifyWebhookSignature.mockReturnValue(event);
|
|
126
|
-
|
|
127
|
-
// First delivery — processed normally
|
|
128
|
-
const first = await server.inject({
|
|
129
|
-
method: "POST",
|
|
130
|
-
url: "/v1/webhooks/stripe",
|
|
131
|
-
payload: VALID_BODY,
|
|
132
|
-
headers: {
|
|
133
|
-
"content-type": "application/json",
|
|
134
|
-
"stripe-signature": VALID_SIGNATURE,
|
|
135
|
-
},
|
|
136
|
-
});
|
|
137
|
-
|
|
138
|
-
expect(first.statusCode).toBe(200);
|
|
139
|
-
expect(mockTrack).toHaveBeenCalledTimes(1);
|
|
140
|
-
|
|
141
|
-
// Second delivery — same event.id, should be treated as duplicate
|
|
142
|
-
const second = await server.inject({
|
|
143
|
-
method: "POST",
|
|
144
|
-
url: "/v1/webhooks/stripe",
|
|
145
|
-
payload: VALID_BODY,
|
|
146
|
-
headers: {
|
|
147
|
-
"content-type": "application/json",
|
|
148
|
-
"stripe-signature": VALID_SIGNATURE,
|
|
149
|
-
},
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
expect(second.statusCode).toBe(200);
|
|
153
|
-
expect(JSON.parse(second.body)).toEqual({ received: true });
|
|
154
|
-
// Telemetry must NOT have fired again
|
|
155
|
-
expect(mockTrack).toHaveBeenCalledTimes(1);
|
|
156
|
-
});
|
|
157
|
-
|
|
158
|
-
it("processes distinct event.ids independently", async () => {
|
|
159
|
-
const eventA = buildFakeEvent("evt_distinct_aaaa");
|
|
160
|
-
const eventB = buildFakeEvent("evt_distinct_bbbb");
|
|
161
|
-
|
|
162
|
-
mockVerifyWebhookSignature.mockReturnValueOnce(eventA);
|
|
163
|
-
await server.inject({
|
|
164
|
-
method: "POST",
|
|
165
|
-
url: "/v1/webhooks/stripe",
|
|
166
|
-
payload: VALID_BODY,
|
|
167
|
-
headers: {
|
|
168
|
-
"content-type": "application/json",
|
|
169
|
-
"stripe-signature": VALID_SIGNATURE,
|
|
170
|
-
},
|
|
171
|
-
});
|
|
172
|
-
|
|
173
|
-
mockVerifyWebhookSignature.mockReturnValueOnce(eventB);
|
|
174
|
-
await server.inject({
|
|
175
|
-
method: "POST",
|
|
176
|
-
url: "/v1/webhooks/stripe",
|
|
177
|
-
payload: VALID_BODY,
|
|
178
|
-
headers: {
|
|
179
|
-
"content-type": "application/json",
|
|
180
|
-
"stripe-signature": VALID_SIGNATURE,
|
|
181
|
-
},
|
|
182
|
-
});
|
|
183
|
-
|
|
184
|
-
expect(mockTrack).toHaveBeenCalledTimes(2);
|
|
185
|
-
});
|
|
186
|
-
|
|
187
|
-
it("logs duplicate detection at info level on replay", async () => {
|
|
188
|
-
const event = buildFakeEvent("evt_logs_duplicate_cccc");
|
|
189
|
-
mockVerifyWebhookSignature.mockReturnValue(event);
|
|
190
|
-
|
|
191
|
-
const logLines: Array<Record<string, unknown>> = [];
|
|
192
|
-
const logCapture = Fastify({
|
|
193
|
-
logger: {
|
|
194
|
-
level: "info",
|
|
195
|
-
stream: {
|
|
196
|
-
write(msg: string) {
|
|
197
|
-
logLines.push(JSON.parse(msg) as Record<string, unknown>);
|
|
198
|
-
},
|
|
199
|
-
},
|
|
200
|
-
},
|
|
201
|
-
});
|
|
202
|
-
|
|
203
|
-
await logCapture.register(async (scope) => {
|
|
204
|
-
scope.addContentTypeParser(
|
|
205
|
-
"application/json",
|
|
206
|
-
{ parseAs: "buffer" },
|
|
207
|
-
(_req, body, done) => {
|
|
208
|
-
done(null, body);
|
|
209
|
-
},
|
|
210
|
-
);
|
|
211
|
-
scope.post("/v1/webhooks/stripe", stripeWebhookHandler);
|
|
212
|
-
});
|
|
213
|
-
await logCapture.ready();
|
|
214
|
-
|
|
215
|
-
try {
|
|
216
|
-
// First delivery
|
|
217
|
-
await logCapture.inject({
|
|
218
|
-
method: "POST",
|
|
219
|
-
url: "/v1/webhooks/stripe",
|
|
220
|
-
payload: VALID_BODY,
|
|
221
|
-
headers: {
|
|
222
|
-
"content-type": "application/json",
|
|
223
|
-
"stripe-signature": VALID_SIGNATURE,
|
|
224
|
-
},
|
|
225
|
-
});
|
|
226
|
-
// Replay
|
|
227
|
-
logLines.length = 0;
|
|
228
|
-
await logCapture.inject({
|
|
229
|
-
method: "POST",
|
|
230
|
-
url: "/v1/webhooks/stripe",
|
|
231
|
-
payload: VALID_BODY,
|
|
232
|
-
headers: {
|
|
233
|
-
"content-type": "application/json",
|
|
234
|
-
"stripe-signature": VALID_SIGNATURE,
|
|
235
|
-
},
|
|
236
|
-
});
|
|
237
|
-
|
|
238
|
-
const matched = logLines.some((line) => {
|
|
239
|
-
const msg = String(line["msg"] ?? "");
|
|
240
|
-
return msg.includes("duplicate") || msg.includes("idempotent");
|
|
241
|
-
});
|
|
242
|
-
expect(matched).toBe(true);
|
|
243
|
-
} finally {
|
|
244
|
-
await logCapture.close();
|
|
245
|
-
}
|
|
246
|
-
});
|
|
247
|
-
});
|