@zero2webmaster/starter-kit 0.13.0 → 0.14.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.
@@ -46,7 +46,7 @@
46
46
  // allowlist stub in `.env.example`. This CLI emits no auth code, so it plants the
47
47
  // seam + the pointer at [[z2w-magic-link-auth]] §0 rule 2b rather than a check —
48
48
  // see CANONICAL_HOSTS_ENV_BLOCK for why that is the honest half.
49
- import { commonBaseFiles, EMAIL_DEPS, EMAIL_ENV_BLOCK, emailFiles, localEnvFrom, readableInkOn, resolveBrandSpec, SENTRY_DEPS, sub, } from "./common.js";
49
+ import { commonBaseFiles, EMAIL_DEPS, EMAIL_ENV_BLOCK, emailFiles, localEnvFrom, readableInkOn, resolveBrandSpec, SENTRY_DEPS, NEON_DRIVER_DEP, sub, } from "./common.js";
50
50
  const NARRATIVE = `## What this is
51
51
 
52
52
  \`{{slug}}\` is a Next.js App Router project scaffolded under the {{brand_name}} brand. The 7-item SEO baseline (per Z2W standing org requirement 2026-05-30) is wired in at instantiation.
@@ -816,25 +816,1105 @@ body {
816
816
  }
817
817
  `;
818
818
  }
819
+ /* --- Card-path bot protection (acceptsCards) -------------------------------- */
820
+ /**
821
+ * Emitted only when `acceptsCards` is set. Four decisions are encoded here and
822
+ * none is cosmetic — settled 2026-08-07 with `z2w-seller-suite`, reference
823
+ * implementation `z2w-crowdcommerce` v0.7.0:
824
+ *
825
+ * 1. invisible unless needed 2. limits sized for card entry, no global cap
826
+ * 3. a five-valued verdict that fails OPEN 4. the enumeration grep ships too
827
+ *
828
+ * The reasoning is written into the emitted comments deliberately. The whole
829
+ * failure mode this guards against is someone "fixing" the fail-open check into
830
+ * a fail-closed one because it shares the word "verify" with webhook signature
831
+ * verification — and a comment is the only thing that reaches that person.
832
+ */
833
+ const TURNSTILE_MODULE_TEMPLATE = `import "server-only";
834
+
835
+ /**
836
+ * Cloudflare Turnstile — server-side token verification for card-accepting paths.
837
+ *
838
+ * WHY THIS EXISTS. {{brand_name}} portfolio rule: anywhere credit cards are
839
+ * accepted, a bot check and a rate limit sit on the endpoint. Turnstile is the
840
+ * sanctioned bot mitigation for this stack — never Akismet.
841
+ * \`paymentIntents.create\` and \`setupIntents.create\` are the primitives
842
+ * card-testing wants: a stolen-card list can be validated against them, and
843
+ * \`setupIntents.create\` does it WITHOUT charging, so it leaves no failed-charge
844
+ * trail for anyone to notice.
845
+ *
846
+ * ⚠️ THIS FAILS **OPEN**, AND THAT IS DELIBERATE — it is the exact opposite of
847
+ * [[webhook-fail-closed]], and the two get conflated because they share the word
848
+ * "verify". A webhook signature governs INBOUND AUTHENTICITY: an unsigned request
849
+ * is provably not from Stripe, so reject it. A bot check governs FRICTION ON A
850
+ * HUMAN: an unreachable Cloudflare is not evidence of abuse, it is evidence that
851
+ * Cloudflare is down — and a payment path that fails closed on a Cloudflare blip
852
+ * is an outage you inflicted on yourself. Do not "fix" this into a fail-closed
853
+ * check.
854
+ *
855
+ * The verdict is five-valued rather than boolean because "Cloudflare said no" and
856
+ * "we could not ask Cloudflare" must not collapse into the same answer
857
+ * ([[zero-is-not-a-pass]]): only the first is evidence of a bot. The caller pairs
858
+ * a non-\`pass\` verdict with a TIGHTER RATE LIMIT instead of a refusal — see
859
+ * \`lib/payments/card-path-guard.ts\`.
860
+ *
861
+ * Full standard: [[stripe-elements-confirm-path]] §8.
862
+ */
863
+
864
+ const SITEVERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
865
+
866
+ /**
867
+ * Widget \`action\` this app mints tokens under. Pinned so a token minted for some
868
+ * other widget on some other origin cannot be replayed at a money endpoint. Give
869
+ * each distinct card surface its own action (e.g. "checkout", "save-card").
870
+ */
871
+ export const TURNSTILE_CARD_ACTION = "card-path";
872
+
873
+ /**
874
+ * How long to wait on Cloudflare before giving up and failing OPEN. A customer is
875
+ * sitting in front of a spinner; 4s is already generous for one edge call.
876
+ */
877
+ const SITEVERIFY_TIMEOUT_MS = 4_000;
878
+
879
+ export type TurnstileOutcome =
880
+ /** Cloudflare affirmatively verified this token. Full trust. */
881
+ | "pass"
882
+ /** Cloudflare affirmatively rejected it: forged, replayed, expired, wrong action. */
883
+ | "fail"
884
+ /** We could not get an answer (Cloudflare down/slow, or OUR secret is wrong).
885
+ * Not evidence of a bot — the customer did present a token. Fail open, report loudly. */
886
+ | "degraded"
887
+ /** A token was required but none arrived: the challenge script never loaded (a real
888
+ * outage shape) **or** a bot skipped it. Indistinguishable from here, so this is
889
+ * allowed but tightly throttled rather than trusted or refused. */
890
+ | "no-token"
891
+ /** No secret configured — Turnstile is not switched on for this deployment yet. */
892
+ | "unconfigured";
893
+
894
+ export type TurnstileVerdict = {
895
+ outcome: TurnstileOutcome;
896
+ /** Short machine-ish reason for logs. NEVER contains the token itself. */
897
+ reason: string;
898
+ };
899
+
900
+ /** Cloudflare's siteverify response, narrowed to the fields we act on. */
901
+ export type SiteverifyResponse = {
902
+ success: boolean;
903
+ "error-codes"?: string[];
904
+ action?: string;
905
+ hostname?: string;
906
+ };
907
+
908
+ /**
909
+ * Error codes meaning "the problem is on OUR side or Cloudflare's", not "this
910
+ * caller is a bot". Failing a payment closed because we typo'd a secret would be
911
+ * a self-inflicted outage, so these degrade (and get reported) instead. This is
912
+ * the most tempting place to fail closed and the most wrong: our mistake would
913
+ * refuse every payment with a message blaming the customer.
914
+ */
915
+ const NOT_THE_CALLERS_FAULT = new Set([
916
+ "internal-error", // Cloudflare had a problem; retryable
917
+ "missing-input-secret", // we sent no secret
918
+ "invalid-input-secret", // our secret is wrong / rotated
919
+ "bad-request", // our request was malformed
920
+ ]);
921
+
922
+ /**
923
+ * PURE verdict logic — split from the fetch so every branch is unit-testable
924
+ * without a network or a Cloudflare account. \`test/card-path-standards.test.ts\`
925
+ * executes this rather than grepping it.
926
+ */
927
+ export function interpretSiteverify(
928
+ body: SiteverifyResponse,
929
+ expectedAction: string,
930
+ ): TurnstileVerdict {
931
+ if (body.success) {
932
+ // A valid token minted for a DIFFERENT action is still a valid token — this
933
+ // is the check that stops one being lifted from another widget and replayed.
934
+ if (body.action && body.action !== expectedAction) {
935
+ return { outcome: "fail", reason: \`action-mismatch:\${body.action}\` };
936
+ }
937
+ return { outcome: "pass", reason: "verified" };
938
+ }
939
+
940
+ const codes = body["error-codes"] ?? [];
941
+ if (codes.some((c) => NOT_THE_CALLERS_FAULT.has(c))) {
942
+ return { outcome: "degraded", reason: \`siteverify-error:\${codes.join(",")}\` };
943
+ }
944
+ // Everything else — invalid-input-response, timeout-or-duplicate (a REPLAYED
945
+ // token), missing-input-response — is a bad token from the caller.
946
+ return { outcome: "fail", reason: \`rejected:\${codes.join(",") || "no-code"}\` };
947
+ }
948
+
949
+ /** Is Turnstile switched on for this deployment? */
950
+ export function isTurnstileConfigured(): boolean {
951
+ return Boolean(process.env.TURNSTILE_SECRET_KEY);
952
+ }
953
+
954
+ /** The site key the browser widget renders with (public — safe to expose). */
955
+ export function turnstileSiteKey(): string | null {
956
+ return process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || null;
957
+ }
958
+
959
+ /**
960
+ * A once-per-runtime line saying whether the card path is actually bot-protected.
961
+ *
962
+ * An integration present in the diff but switched off in the environment is the
963
+ * state nothing else can see: payments keep succeeding, tests keep passing and
964
+ * the health probe keeps returning 200 whether Turnstile is on or off. Without
965
+ * this line the only way to learn it is off is to read the env
966
+ * ([[zero-is-not-a-pass]]). Log it from \`instrumentation.ts\`.
967
+ *
968
+ * Returns null when everything is wired — silence means configured, which is the
969
+ * one case that needs no words.
970
+ */
971
+ export function turnstileStartupNotice(): string | null {
972
+ const hasSecret = Boolean(process.env.TURNSTILE_SECRET_KEY);
973
+ const hasSiteKey = Boolean(process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY);
974
+ if (hasSecret && hasSiteKey) return null;
975
+
976
+ if (!hasSecret && !hasSiteKey) {
977
+ return "[turnstile] NOT ENABLED — no TURNSTILE_SECRET_KEY / NEXT_PUBLIC_TURNSTILE_SITE_KEY. Card-accepting paths are rate-limited but have NO bot check. Create a widget at https://dash.cloudflare.com/?to=/:account/turnstile before taking live payments.";
978
+ }
979
+ // A half-configured pair is worse than neither: the widget mints tokens nobody
980
+ // verifies, or the server demands tokens the browser renders no widget for.
981
+ return hasSecret
982
+ ? "[turnstile] HALF-CONFIGURED — TURNSTILE_SECRET_KEY is set but NEXT_PUBLIC_TURNSTILE_SITE_KEY is not, so no widget renders and every payment takes the token-less (tightly rate-limited) path."
983
+ : "[turnstile] HALF-CONFIGURED — NEXT_PUBLIC_TURNSTILE_SITE_KEY is set but TURNSTILE_SECRET_KEY is not, so tokens are minted in the browser and never verified.";
984
+ }
985
+
986
+ /**
987
+ * Verify a Turnstile token with Cloudflare.
988
+ *
989
+ * \`remoteIp\` is optional but worth sending: Cloudflare uses it as a signal, and
990
+ * it costs nothing since the caller already parsed it for rate limiting.
991
+ */
992
+ export async function verifyTurnstile(
993
+ token: string | undefined | null,
994
+ opts: { remoteIp?: string; action?: string } = {},
995
+ ): Promise<TurnstileVerdict> {
996
+ const secret = process.env.TURNSTILE_SECRET_KEY;
997
+ if (!secret) return { outcome: "unconfigured", reason: "no-secret" };
998
+ if (!token) return { outcome: "no-token", reason: "absent" };
999
+
1000
+ const expectedAction = opts.action ?? TURNSTILE_CARD_ACTION;
1001
+
1002
+ const form = new URLSearchParams({ secret, response: token });
1003
+ if (opts.remoteIp && opts.remoteIp !== "unknown") form.set("remoteip", opts.remoteIp);
1004
+
1005
+ try {
1006
+ const res = await fetch(SITEVERIFY_URL, {
1007
+ method: "POST",
1008
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1009
+ body: form,
1010
+ signal: AbortSignal.timeout(SITEVERIFY_TIMEOUT_MS),
1011
+ cache: "no-store",
1012
+ });
1013
+ if (!res.ok) {
1014
+ // A 5xx from Cloudflare is Cloudflare's problem, not the customer's.
1015
+ return { outcome: "degraded", reason: \`siteverify-http-\${res.status}\` };
1016
+ }
1017
+ return interpretSiteverify((await res.json()) as SiteverifyResponse, expectedAction);
1018
+ } catch (err) {
1019
+ // Timeout, DNS failure, TLS failure, unparseable body. All the same answer:
1020
+ // we do not know, so we do not block the payment.
1021
+ const kind = err instanceof Error ? err.name : "unknown";
1022
+ return { outcome: "degraded", reason: \`siteverify-unreachable:\${kind}\` };
1023
+ }
1024
+ }
1025
+ `;
1026
+ const CARD_PATH_GUARD_TEMPLATE = `/**
1027
+ * Abuse policy for card-accepting endpoints — PURE, so every branch is
1028
+ * unit-testable without Stripe, Cloudflare or a database.
1029
+ *
1030
+ * ╔══════════════════════════════════════════════════════════════════════════╗
1031
+ * ║ ENUMERATE YOUR CARD PATHS BY GREP, NOT BY EYE. Run this in the repo root: ║
1032
+ * ║ ║
1033
+ * ║ grep -rn "paymentIntents.create\\|setupIntents.create" app lib ║
1034
+ * ║ grep -rn "confirmSetup(\\|confirmPayment(" app components lib ║
1035
+ * ║ grep -rn "/payment_intents\\|/setup_intents" app lib ║
1036
+ * ║ ║
1037
+ * ║ Every server hit needs BOTH a bot check and its own rate limit IN THAT ║
1038
+ * ║ HANDLER. Every client hit needs to actually mint a token. ║
1039
+ * ║ \`test/card-path-standards.test.ts\` runs this for you on every \`npm test\`. ║
1040
+ * ╚══════════════════════════════════════════════════════════════════════════╝
1041
+ *
1042
+ * Why the grep is part of the standard: a Z2W WooCommerce gateway (measured
1043
+ * 2026-08-06) had a working \`verify_turnstile()\` and \`is_rate_limited()\` and
1044
+ * called them in EXACTLY ONE of three card-accepting paths. The two bare ones
1045
+ * were authenticated, nonce'd and ownership-checked — none of which limits
1046
+ * volume. Authentication answers *who*, not *how many*. And on Next.js a
1047
+ * page-level gate does not cover a Server Action, which is a publicly
1048
+ * addressable POST endpoint invocable without ever loading its page
1049
+ * ([[server-actions-are-public-endpoints]]).
1050
+ *
1051
+ * ── THE POLICY ──────────────────────────────────────────────────────────────
1052
+ * A failed bot check does NOT map onto a refusal. Three states stay distinct
1053
+ * ([[zero-is-not-a-pass]]):
1054
+ *
1055
+ * • Cloudflare said this token is bad → refuse. Evidence of abuse.
1056
+ * • Cloudflare could not be reached → allow at the full budget. The customer
1057
+ * presented a token; our inability to
1058
+ * check it is not their problem.
1059
+ * • No token arrived at all → allow at a TIGHT budget. Genuinely
1060
+ * ambiguous: it is what a bot skipping
1061
+ * the widget looks like, and equally
1062
+ * what a customer behind a blocked
1063
+ * challenges.cloudflare.com looks like.
1064
+ * Refusing hands a Cloudflare outage the
1065
+ * power to stop your checkout; trusting
1066
+ * makes the check optional at the
1067
+ * attacker's discretion. A small budget
1068
+ * serves the customer and starves the
1069
+ * card-tester.
1070
+ *
1071
+ * ── ON THE BUDGETS ──────────────────────────────────────────────────────────
1072
+ * A limit tuned for ORDER SUBMISSION will block a customer legitimately retrying
1073
+ * a mistyped card, so do not copy one. The shape that actually matters is a
1074
+ * SHARED IP: thirty people giving from one wifi NAT at a fundraising dinner, or a
1075
+ * school, or an office, is a completely normal evening and must not look like an
1076
+ * attack. Hence a generous budget over a LONG window rather than a tight
1077
+ * per-minute one — a per-minute limit turns the moment the campaign works into a
1078
+ * wall of 429s. Card-testing needs volume orders of magnitude above this to be
1079
+ * worth anything.
1080
+ *
1081
+ * NO GLOBAL CAP, deliberately. A site-wide ceiling on a payment endpoint converts
1082
+ * the single best thing that can happen — going viral — into an outage, and the
1083
+ * per-source cap plus Turnstile already bounds the realistic attack. (This is the
1084
+ * one place to diverge from a magic-link limiter, where a global cap IS right
1085
+ * because every send costs money and no burst of them is ever good news.)
1086
+ *
1087
+ * Tune these numbers for YOUR flow; do not treat them as sacred. What is not
1088
+ * negotiable is the SHAPE: long window, per-source, no global cap, tighter budget
1089
+ * for unverified than verified.
1090
+ */
1091
+ import type { TurnstileOutcome, TurnstileVerdict } from "@/lib/payments/turnstile";
1092
+
1093
+ /** Window both budgets are measured over. Long on purpose — see above. */
1094
+ export const CARD_PATH_WINDOW_MS = 10 * 60 * 1000;
1095
+
1096
+ /** Bot-check passed, or could not be performed through no fault of the customer. */
1097
+ export const VERIFIED_BUDGET = 30;
1098
+
1099
+ /** No token presented. Comfortably above any human's retries, far below useful abuse. */
1100
+ export const UNVERIFIED_BUDGET = 5;
1101
+
1102
+ export type GuardPolicy = {
1103
+ /** Refuse outright with 403 — the token was affirmatively rejected. */
1104
+ refuse: boolean;
1105
+ limit: number;
1106
+ windowMs: number;
1107
+ /** Report as a bot-protection DEGRADATION, not as a payment failure. */
1108
+ report: boolean;
1109
+ reason: string;
1110
+ };
1111
+
1112
+ export function policyForVerdict(verdict: TurnstileVerdict): GuardPolicy {
1113
+ const base = { windowMs: CARD_PATH_WINDOW_MS, reason: verdict.reason };
1114
+
1115
+ switch (verdict.outcome) {
1116
+ case "pass":
1117
+ return { ...base, refuse: false, limit: VERIFIED_BUDGET, report: false };
1118
+
1119
+ case "unconfigured":
1120
+ // Turnstile is not switched on for this deployment. Not a degradation of a
1121
+ // working system — it is the pre-Turnstile posture, and reporting it per
1122
+ // request would fire on every single payment. Visibility lives in the
1123
+ // once-per-runtime startup notice instead (\`turnstileStartupNotice\`).
1124
+ return { ...base, refuse: false, limit: VERIFIED_BUDGET, report: false };
1125
+
1126
+ case "degraded":
1127
+ return { ...base, refuse: false, limit: VERIFIED_BUDGET, report: true };
1128
+
1129
+ case "no-token":
1130
+ return { ...base, refuse: false, limit: UNVERIFIED_BUDGET, report: true };
1131
+
1132
+ case "fail":
1133
+ // Do NOT report. A rejected token is the check WORKING, and alerting on it
1134
+ // would bury the degradations above under routine noise — the same reason
1135
+ // ordinary card declines stay out of error tracking.
1136
+ return { ...base, refuse: true, limit: UNVERIFIED_BUDGET, report: false };
1137
+ }
1138
+ }
1139
+
1140
+ /** Rate-limit bucket key. Namespaced so buckets from other paths never collide. */
1141
+ export function cardPathBucket(ip: string, outcome: TurnstileOutcome): string {
1142
+ // Verified and unverified traffic from one IP count SEPARATELY on purpose: a
1143
+ // shared-NAT customer who passes the bot check must not have their budget eaten
1144
+ // by an unrelated token-less request from the same office.
1145
+ const lane = outcome === "pass" ? "v" : "u";
1146
+ return \`card:\${lane}:ip:\${ip}\`;
1147
+ }
1148
+
1149
+ /**
1150
+ * Best-effort client IP. Trusts \`x-forwarded-for\` because this app runs behind a
1151
+ * proxy that sets it; on a host where it does not, this is spoofable and the
1152
+ * durable limit is the only thing that holds.
1153
+ */
1154
+ export function clientIpFrom(headers: Headers): string {
1155
+ const fwd = headers.get("x-forwarded-for");
1156
+ if (fwd) return fwd.split(",")[0]!.trim();
1157
+ return headers.get("x-real-ip")?.trim() || "unknown";
1158
+ }
1159
+ `;
1160
+ /**
1161
+ * The shared-store limiter, emitted only for `dbStrategy === "neon-postgres"`.
1162
+ *
1163
+ * Self-contained on purpose: the Next.js scaffold ships NO db layer, so an
1164
+ * `import { db } from "@/lib/db"` would not compile. It brings its own thin
1165
+ * `@neondatabase/serverless` client and reads `DATABASE_URL`, which also keeps
1166
+ * it usable whichever ORM the project later adopts.
1167
+ */
1168
+ const RATE_LIMIT_DURABLE_TEMPLATE = `import "server-only";
1169
+
1170
+ /**
1171
+ * Durable, cross-instance rate limiting on top of the \`rate_limits\` table.
1172
+ *
1173
+ * WHY THIS EXISTS SEPARATELY FROM AN IN-MEMORY LIMITER. Per-instance state means
1174
+ * the real ceiling is \`limit × instances\`, and card-testing fans out — which is
1175
+ * exactly the shape an in-memory limiter cannot hold ([[z2w-magic-link-auth]]
1176
+ * §8.6.1 #3). An in-memory limiter is still worth having in FRONT of this one as
1177
+ * a free short-circuit on a warm instance; it is not a substitute for it.
1178
+ *
1179
+ * ⚠️ FAILS OPEN, LOUDLY. If Postgres is unreachable, or the migration creating
1180
+ * the table has not landed yet, \`check()\` returns \`{ allowed: true, durable:
1181
+ * false }\` and reports. A rate limiter is a guard on the payment path, not the
1182
+ * payment path — a limiter outage must never become a payment outage. But per
1183
+ * [[zero-is-not-a-pass]] the caller must be able to tell "checked, under the
1184
+ * limit" from "could not check", so the verdict carries \`durable\`, and a failure
1185
+ * is surfaced rather than swallowed into a green boolean.
1186
+ *
1187
+ * Requires \`db/migrations/0001_rate_limits.sql\` to have been applied.
1188
+ */
1189
+ import { neon } from "@neondatabase/serverless";
1190
+
1191
+ export type DurableVerdict = {
1192
+ /** May the request proceed? */
1193
+ allowed: boolean;
1194
+ /** Did the shared store actually answer? \`false\` ⇒ this verdict proves nothing. */
1195
+ durable: boolean;
1196
+ /** Hits recorded in the current window (null when the store did not answer). */
1197
+ hits: number | null;
1198
+ };
1199
+
1200
+ /** Fraction of calls that also sweep aged-out windows. No cron — [[neon-postgres]]. */
1201
+ const SWEEP_PROBABILITY = 0.02;
1202
+ /** Windows older than this are garbage; nothing reads them. */
1203
+ const SWEEP_OLDER_THAN_MS = 24 * 60 * 60 * 1000;
1204
+
1205
+ /**
1206
+ * Floor \`now\` to the start of its fixed window. PURE — exported for tests, and so
1207
+ * the boundary is one obvious line rather than an inline expression to re-derive.
1208
+ */
1209
+ export function windowStartFor(now: number, windowMs: number): Date {
1210
+ return new Date(Math.floor(now / windowMs) * windowMs);
1211
+ }
1212
+
1213
+ function client() {
1214
+ const url = process.env.DATABASE_URL;
1215
+ if (!url) throw new Error("DATABASE_URL is not set");
1216
+ return neon(url);
1217
+ }
1218
+
1219
+ /**
1220
+ * Record a hit and report whether the bucket is still under its limit.
1221
+ *
1222
+ * Note this counts REJECTED requests too. That is safe here because the window is
1223
+ * FIXED: it always ends at a wall-clock boundary no amount of attacker traffic
1224
+ * can push out, so a steady attacker cannot extend a legitimate user's lockout
1225
+ * forever. Counting every attempt is what makes ONE atomic upsert sufficient.
1226
+ */
1227
+ export async function checkDurableLimit(
1228
+ bucket: string,
1229
+ opts: { limit: number; windowMs: number; now?: number },
1230
+ ): Promise<DurableVerdict> {
1231
+ const now = opts.now ?? Date.now();
1232
+ const windowStart = windowStartFor(now, opts.windowMs);
1233
+
1234
+ try {
1235
+ const sql = client();
1236
+ const rows = (await sql\`
1237
+ INSERT INTO rate_limits (bucket, window_start, hits)
1238
+ VALUES (\${bucket}, \${windowStart.toISOString()}, 1)
1239
+ ON CONFLICT (bucket, window_start)
1240
+ DO UPDATE SET hits = rate_limits.hits + 1
1241
+ RETURNING hits
1242
+ \`) as Array<{ hits: number }>;
1243
+
1244
+ const hits = Number(rows[0]?.hits ?? 0);
1245
+ if (Math.random() < SWEEP_PROBABILITY) void sweepExpired(now);
1246
+ return { allowed: hits <= opts.limit, durable: true, hits };
1247
+ } catch (err) {
1248
+ // The most likely cause on a fresh deploy is \`42P01 relation "rate_limits"
1249
+ // does not exist\` — the migration has not landed yet. That must not stop
1250
+ // payments, but it must not look like a passing check either.
1251
+ console.error("[rate-limit-durable] shared store unavailable:", err);
1252
+ return { allowed: true, durable: false, hits: null };
1253
+ }
1254
+ }
1255
+
1256
+ /** Best-effort deletion of windows nothing will ever read again. */
1257
+ async function sweepExpired(now: number): Promise<void> {
1258
+ try {
1259
+ const sql = client();
1260
+ const cutoff = new Date(now - SWEEP_OLDER_THAN_MS).toISOString();
1261
+ await sql\`DELETE FROM rate_limits WHERE window_start < \${cutoff}\`;
1262
+ } catch {
1263
+ // A failed sweep is housekeeping debt, not a request failure. The row count
1264
+ // is bounded anyway: one row per active bucket per window.
1265
+ }
1266
+ }
1267
+ `;
1268
+ const RATE_LIMITS_DDL_TEMPLATE = `-- Shared-store rate limiting for card-accepting paths.
1269
+ --
1270
+ -- Apply this BEFORE taking live payments. Until it exists,
1271
+ -- \`checkDurableLimit()\` fails OPEN and logs — which is the right behaviour for
1272
+ -- an outage and the wrong state to ship in deliberately.
1273
+ --
1274
+ -- One row per (bucket, fixed window). Bounded by design: buckets are per-IP
1275
+ -- per-lane, windows are 10 minutes, and anything older than 24h is swept
1276
+ -- probabilistically by the caller (no cron — [[neon-postgres]]).
1277
+
1278
+ CREATE TABLE IF NOT EXISTS rate_limits (
1279
+ bucket text NOT NULL,
1280
+ window_start timestamptz NOT NULL,
1281
+ hits integer NOT NULL DEFAULT 0,
1282
+ PRIMARY KEY (bucket, window_start)
1283
+ );
1284
+
1285
+ -- Supports the probabilistic sweep. Without it the DELETE degrades to a seq scan
1286
+ -- on a table that only ever grows between sweeps.
1287
+ CREATE INDEX IF NOT EXISTS rate_limits_window_start_idx
1288
+ ON rate_limits (window_start);
1289
+ `;
1290
+ const TURNSTILE_WIDGET_TEMPLATE = `"use client";
1291
+
1292
+ /**
1293
+ * Cloudflare Turnstile widget — the browser half of the card-path bot check.
1294
+ *
1295
+ * THREE THINGS THIS DOES DIFFERENTLY FROM A COPY-PASTED TURNSTILE SNIPPET, each
1296
+ * for a reason worth keeping:
1297
+ *
1298
+ * 1. **\`appearance: "interaction-only"\` — invisible unless Cloudflare actually
1299
+ * wants a human.** A bare \`<div class="cf-turnstile">\` renders a visible
1300
+ * checkbox to EVERY customer, and a visible challenge on a checkout or
1301
+ * donation form costs real conversions. (The old standalone "Invisible"
1302
+ * widget *type* is deprecated; Managed vs Non-interactive is a Cloudflare
1303
+ * dashboard setting, not markup.)
1304
+ *
1305
+ * 2. **The script loads on USER INTENT, not page load.** A payment page is
1306
+ * usually also a page graded on Core Web Vitals. Nothing Cloudflare-shaped is
1307
+ * fetched until someone touches the form, by which point they have told us
1308
+ * they mean it and a third-party script is cheap next to Stripe.js. Someone
1309
+ * who fills and submits faster than the script loads is handled by
1310
+ * \`awaitToken()\`'s timeout, not by a blocked submit.
1311
+ *
1312
+ * 3. **Every failure callback is wired and REPORTED.** \`error\` / \`timeout\` /
1313
+ * \`expired\` left unwired is the classic silent break: the widget quietly never
1314
+ * mints a token and the customer gets a baffling refusal at submit with
1315
+ * nothing to act on. Here a load failure degrades to "no token" (which the
1316
+ * server allows under a tighter limit) and is reported, so an outage is
1317
+ * visible to us instead of only to the customer.
1318
+ *
1319
+ * See [[stripe-elements-confirm-path]] §8 and [[async-action-feedback]].
1320
+ */
1321
+
1322
+ import { useCallback, useEffect, useRef, useState } from "react";
1323
+ import { reportCardPathIssue } from "@/lib/payments/report";
1324
+
1325
+ const SCRIPT_SRC =
1326
+ "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
1327
+
1328
+ type TurnstileRenderOptions = {
1329
+ sitekey: string;
1330
+ action?: string;
1331
+ appearance?: "always" | "execute" | "interaction-only";
1332
+ callback?: (token: string) => void;
1333
+ "error-callback"?: (code?: string) => void;
1334
+ "expired-callback"?: () => void;
1335
+ "timeout-callback"?: () => void;
1336
+ };
1337
+
1338
+ type TurnstileApi = {
1339
+ render: (el: HTMLElement, opts: TurnstileRenderOptions) => string | undefined;
1340
+ reset: (widgetId?: string) => void;
1341
+ remove: (widgetId?: string) => void;
1342
+ };
1343
+
1344
+ declare global {
1345
+ interface Window {
1346
+ turnstile?: TurnstileApi;
1347
+ }
1348
+ }
1349
+
1350
+ /**
1351
+ * \`idle\` — not armed yet (nobody has touched the form).
1352
+ * \`loading\` — script/widget in flight.
1353
+ * \`ready\` — a token is in hand.
1354
+ * \`unavailable\` — script or widget failed; submits proceed WITHOUT a token.
1355
+ */
1356
+ export type TurnstileStatus = "idle" | "loading" | "ready" | "unavailable";
1357
+
1358
+ /** Singleton script load — many widgets, one \`<script>\`, one in-flight promise. */
1359
+ let scriptPromise: Promise<TurnstileApi | null> | null = null;
1360
+
1361
+ function loadTurnstileScript(): Promise<TurnstileApi | null> {
1362
+ if (scriptPromise) return scriptPromise;
1363
+ if (typeof window === "undefined") return Promise.resolve(null);
1364
+ if (window.turnstile) return (scriptPromise = Promise.resolve(window.turnstile));
1365
+
1366
+ scriptPromise = new Promise<TurnstileApi | null>((resolve) => {
1367
+ const script = document.createElement("script");
1368
+ script.src = SCRIPT_SRC;
1369
+ script.async = true;
1370
+ script.defer = true;
1371
+ script.onload = () => resolve(window.turnstile ?? null);
1372
+ // A blocked CDN, an ad-blocker, or a Cloudflare outage all land here. Resolve
1373
+ // null rather than reject: the caller's job is to keep going, not to retry.
1374
+ script.onerror = () => resolve(null);
1375
+ document.head.appendChild(script);
1376
+ });
1377
+ return scriptPromise;
1378
+ }
1379
+
1380
+ export function useTurnstile(opts: { siteKey: string | null; action: string }) {
1381
+ const { siteKey, action } = opts;
1382
+
1383
+ const containerRef = useRef<HTMLDivElement | null>(null);
1384
+ const widgetIdRef = useRef<string | null>(null);
1385
+ const tokenRef = useRef<string | null>(null);
1386
+ /** Callers parked in \`awaitToken()\` while the first token is still in flight. */
1387
+ const waitersRef = useRef<Array<(token: string | null) => void>>([]);
1388
+ const armedRef = useRef(false);
1389
+
1390
+ const [status, setStatus] = useState<TurnstileStatus>("idle");
1391
+
1392
+ const settle = useCallback((token: string | null) => {
1393
+ tokenRef.current = token;
1394
+ const waiters = waitersRef.current;
1395
+ waitersRef.current = [];
1396
+ for (const resolve of waiters) resolve(token);
1397
+ }, []);
1398
+
1399
+ /**
1400
+ * Begin loading Turnstile. Safe to call on every keystroke — it self-guards, so
1401
+ * a form can hand it straight to \`onFocus\`/\`onChange\` without debouncing.
1402
+ */
1403
+ const arm = useCallback(() => {
1404
+ if (armedRef.current || !siteKey) return;
1405
+ armedRef.current = true;
1406
+ setStatus("loading");
1407
+
1408
+ void loadTurnstileScript().then((api) => {
1409
+ const el = containerRef.current;
1410
+ if (!api || !el) {
1411
+ setStatus("unavailable");
1412
+ settle(null);
1413
+ void reportCardPathIssue("turnstile:script-unavailable", { action });
1414
+ return;
1415
+ }
1416
+ try {
1417
+ const id = api.render(el, {
1418
+ sitekey: siteKey,
1419
+ action,
1420
+ appearance: "interaction-only",
1421
+ callback: (token) => {
1422
+ setStatus("ready");
1423
+ settle(token);
1424
+ },
1425
+ "error-callback": (code) => {
1426
+ setStatus("unavailable");
1427
+ settle(null);
1428
+ void reportCardPathIssue(\`turnstile:error-callback:\${code ?? "no-code"}\`, {
1429
+ action,
1430
+ });
1431
+ },
1432
+ "timeout-callback": () => {
1433
+ setStatus("unavailable");
1434
+ settle(null);
1435
+ void reportCardPathIssue("turnstile:timeout-callback", { action });
1436
+ },
1437
+ // A token dies after ~5 minutes. Anyone reading a page before paying
1438
+ // will absolutely cross that line, so refresh rather than fail at submit.
1439
+ "expired-callback": () => {
1440
+ tokenRef.current = null;
1441
+ setStatus("loading");
1442
+ try {
1443
+ api.reset(widgetIdRef.current ?? undefined);
1444
+ } catch {
1445
+ setStatus("unavailable");
1446
+ settle(null);
1447
+ }
1448
+ },
1449
+ });
1450
+ widgetIdRef.current = id ?? null;
1451
+ } catch (err) {
1452
+ setStatus("unavailable");
1453
+ settle(null);
1454
+ void reportCardPathIssue(
1455
+ \`turnstile:render-threw:\${err instanceof Error ? err.name : "unknown"}\`,
1456
+ { action },
1457
+ );
1458
+ }
1459
+ });
1460
+ }, [siteKey, action, settle]);
1461
+
1462
+ /**
1463
+ * Resolve with a token, waiting up to \`timeoutMs\` if one is still in flight.
1464
+ *
1465
+ * Resolves \`null\` rather than throwing when Turnstile is unavailable or slow —
1466
+ * the payment must still be attempted. The SERVER decides what a missing token
1467
+ * costs; the client's job is never to block the payment.
1468
+ */
1469
+ const awaitToken = useCallback(
1470
+ (timeoutMs = 3_000): Promise<string | null> => {
1471
+ if (!siteKey) return Promise.resolve(null);
1472
+ if (tokenRef.current) return Promise.resolve(tokenRef.current);
1473
+ if (!armedRef.current) arm();
1474
+ if (status === "unavailable") return Promise.resolve(null);
1475
+
1476
+ return new Promise<string | null>((resolve) => {
1477
+ let done = false;
1478
+ const finish = (token: string | null) => {
1479
+ if (done) return;
1480
+ done = true;
1481
+ resolve(token);
1482
+ };
1483
+ waitersRef.current.push(finish);
1484
+ window.setTimeout(() => finish(null), timeoutMs);
1485
+ });
1486
+ },
1487
+ [siteKey, status, arm],
1488
+ );
1489
+
1490
+ /**
1491
+ * Discard the spent token and mint a fresh one. Turnstile tokens are SINGLE-USE
1492
+ * — siteverify consumes them — so a second attempt with the same token comes
1493
+ * back \`timeout-or-duplicate\` and reads as a bot. Call after EVERY attempt.
1494
+ */
1495
+ const reset = useCallback(() => {
1496
+ tokenRef.current = null;
1497
+ if (!widgetIdRef.current || !window.turnstile) return;
1498
+ setStatus("loading");
1499
+ try {
1500
+ window.turnstile.reset(widgetIdRef.current);
1501
+ } catch {
1502
+ setStatus("unavailable");
1503
+ settle(null);
1504
+ }
1505
+ }, [settle]);
1506
+
1507
+ // Tear the widget down on unmount so a re-mount (React strict mode in dev, or
1508
+ // navigating back) doesn't leave an orphaned iframe behind.
1509
+ useEffect(() => {
1510
+ return () => {
1511
+ const id = widgetIdRef.current;
1512
+ widgetIdRef.current = null;
1513
+ if (id && window.turnstile) {
1514
+ try {
1515
+ window.turnstile.remove(id);
1516
+ } catch {
1517
+ // Already gone. Nothing to do.
1518
+ }
1519
+ }
1520
+ };
1521
+ }, []);
1522
+
1523
+ return { containerRef, status, arm, awaitToken, reset };
1524
+ }
1525
+
1526
+ /**
1527
+ * Mount point for the widget. Renders nothing visible in the normal case
1528
+ * (\`interaction-only\`); when Cloudflare DOES want a human, the challenge appears
1529
+ * HERE — so place it immediately above the submit button, where the user is
1530
+ * already looking ([[async-action-feedback]] §2), not at the bottom of the page.
1531
+ */
1532
+ export function TurnstileMount({
1533
+ containerRef,
1534
+ status,
1535
+ }: {
1536
+ containerRef: React.RefObject<HTMLDivElement | null>;
1537
+ status: TurnstileStatus;
1538
+ }) {
1539
+ return (
1540
+ <div style={{ margin: status === "idle" ? 0 : "0 0 0.9rem" }}>
1541
+ <div ref={containerRef} />
1542
+ {status === "unavailable" && (
1543
+ <p style={{ margin: "0.4rem 0 0", fontSize: "1rem", color: "#555" }}>
1544
+ Our bot check could not load — your payment will still go through.
1545
+ </p>
1546
+ )}
1547
+ </div>
1548
+ );
1549
+ }
1550
+ `;
1551
+ /**
1552
+ * The reporting seam, in two variants.
1553
+ *
1554
+ * Split out so neither the widget nor the route decides HOW to report, and so a
1555
+ * project without Sentry does not carry a broken import. The Sentry variant uses
1556
+ * a dynamic import so one module works in both the browser and the server
1557
+ * without pulling the SDK into a bundle that does not need it.
1558
+ */
1559
+ const CARD_PATH_REPORT_SENTRY_TEMPLATE = `/**
1560
+ * Where card-path bot-protection problems get reported.
1561
+ *
1562
+ * A degradation here is NOT a payment failure — the payment proceeds. But a bot
1563
+ * check that quietly stops working is invisible otherwise: payments still
1564
+ * succeed, analytics still counts, \`/api/health\` still returns 200. This is the
1565
+ * only thing that makes the difference visible to US rather than only to the
1566
+ * customer.
1567
+ *
1568
+ * Never pass a token, a card number, or an email through here.
1569
+ */
1570
+ export async function reportCardPathIssue(
1571
+ reason: string,
1572
+ tags: Record<string, string> = {},
1573
+ ): Promise<void> {
1574
+ console.warn(\`[card-path] \${reason}\`, tags);
1575
+ try {
1576
+ const Sentry = await import("@sentry/nextjs");
1577
+ Sentry.captureMessage(\`card-path: \${reason}\`, {
1578
+ level: "warning",
1579
+ tags: { flow: "card-path", provider: "turnstile", ...tags },
1580
+ });
1581
+ } catch {
1582
+ // Never let error reporting become the error. A throw here would turn a
1583
+ // deliberate fail-open into a 500 on the payment path — the exact outcome
1584
+ // this whole module exists to prevent.
1585
+ }
1586
+ }
1587
+ `;
1588
+ const CARD_PATH_REPORT_CONSOLE_TEMPLATE = `/**
1589
+ * Where card-path bot-protection problems get reported.
1590
+ *
1591
+ * A degradation here is NOT a payment failure — the payment proceeds. But a bot
1592
+ * check that quietly stops working is invisible otherwise: payments still
1593
+ * succeed, analytics still counts, \`/api/health\` still returns 200.
1594
+ *
1595
+ * ⚠️ THIS PROJECT HAS NO ERROR TRACKING WIRED, so these land in the runtime log
1596
+ * and nowhere else — which means nobody is alerted when the bot check breaks.
1597
+ * Before taking live payments, either wire Sentry ([[sentry-runtime-errors]]) and
1598
+ * report here, or point this at something a human actually watches. Leaving it as
1599
+ * a bare \`console.warn\` is a decision, not a default.
1600
+ *
1601
+ * Never pass a token, a card number, or an email through here.
1602
+ */
1603
+ export async function reportCardPathIssue(
1604
+ reason: string,
1605
+ tags: Record<string, string> = {},
1606
+ ): Promise<void> {
1607
+ console.warn(\`[card-path] \${reason}\`, tags);
1608
+ }
1609
+ `;
1610
+ /**
1611
+ * The emitted ENFORCEMENT half — the part that survives contact with a future
1612
+ * agent. The modules above make the right thing easy; only a test fails the build
1613
+ * on the next card path someone adds bare.
1614
+ *
1615
+ * Two deliberate choices, both learned in this repo:
1616
+ *
1617
+ * - It splits SERVER primitives from CLIENT ones, because they need different
1618
+ * things. A `confirmPayment(` call site needs to mint a token; it has no
1619
+ * business holding a rate limit.
1620
+ * - It uses `it.skipIf` rather than a `console.warn` when a fresh scaffold has
1621
+ * no card paths yet. vitest's default reporter SWALLOWS `console.warn` for a
1622
+ * passing test (found the hard way in v0.12.0), so a warning would be
1623
+ * invisible; `2 skipped` in the summary is not.
1624
+ */
1625
+ const CARD_PATH_STANDARDS_TEST_TEMPLATE = `/**
1626
+ * Card-path bot protection, enforced as a test rather than as a convention
1627
+ * someone has to remember.
1628
+ *
1629
+ * THE RULE: every endpoint that can charge or validate a card carries BOTH a bot
1630
+ * check and its own rate limit, in that handler. Authentication answers *who*,
1631
+ * not *how many* — an authenticated, nonce'd, ownership-checked endpoint is still
1632
+ * a card-testing oracle if nothing limits volume.
1633
+ *
1634
+ * A Z2W WooCommerce gateway (measured 2026-08-06) had both guards implemented and
1635
+ * called them in exactly ONE of three card-accepting paths. Nobody spotted it by
1636
+ * reading the code; a grep did. This test is that grep, run on every \`npm test\`.
1637
+ *
1638
+ * Full standard: [[stripe-elements-confirm-path]] §8.
1639
+ */
1640
+ import { describe, it, expect } from "vitest";
1641
+ import { readFileSync, readdirSync, existsSync } from "node:fs";
1642
+ import { join, dirname } from "node:path";
1643
+ import { fileURLToPath } from "node:url";
1644
+
1645
+ // NOT \`__dirname\` — this package is "type": "module", where it is undefined.
1646
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
1647
+
1648
+ function sourceFiles(dir: string): string[] {
1649
+ const abs = join(ROOT, dir);
1650
+ if (!existsSync(abs)) return [];
1651
+ const out: string[] = [];
1652
+ for (const e of readdirSync(abs, { withFileTypes: true })) {
1653
+ if (e.name === "node_modules" || e.name.startsWith(".")) continue;
1654
+ const rel = join(dir, e.name);
1655
+ if (e.isDirectory()) out.push(...sourceFiles(rel));
1656
+ else if (e.name.endsWith(".ts") || e.name.endsWith(".tsx")) out.push(rel);
1657
+ }
1658
+ return out;
1659
+ }
1660
+
1661
+ const SOURCES = [
1662
+ ...sourceFiles("app"),
1663
+ ...sourceFiles("lib"),
1664
+ ...sourceFiles("components"),
1665
+ ];
1666
+ const read = (f: string) => readFileSync(join(ROOT, f), "utf8");
1667
+
1668
+ /** Files that DEFINE the standard rather than consume it. */
1669
+ const SELF = /^lib[\\\\/]payments[\\\\/]/;
1670
+
1671
+ /**
1672
+ * Server-side primitives: these CREATE an intent, so the handler holding them
1673
+ * must verify a token and apply its own limit.
1674
+ */
1675
+ const SERVER_PRIMITIVES = [
1676
+ "paymentIntents.create",
1677
+ "setupIntents.create",
1678
+ "/payment_intents",
1679
+ "/setup_intents",
1680
+ ];
1681
+
1682
+ /**
1683
+ * Client-side primitives: these CONFIRM an intent in the browser, so the call
1684
+ * site must actually mint a token. It must NOT hold a rate limit — a limit that
1685
+ * lives in the browser is not a limit.
1686
+ */
1687
+ const CLIENT_PRIMITIVES = ["confirmSetup(", "confirmPayment("];
1688
+
1689
+ const hits = (needles: string[]) =>
1690
+ SOURCES.filter((f) => !SELF.test(f)).filter((f) => {
1691
+ const src = read(f);
1692
+ return needles.some((n) => src.includes(n));
1693
+ });
1694
+
1695
+ const SERVER_CARD_PATHS = hits(SERVER_PRIMITIVES);
1696
+ const CLIENT_CARD_PATHS = hits(CLIENT_PRIMITIVES);
1697
+
1698
+ describe("card-path bot protection", () => {
1699
+ // A scaffold starts with no card paths, which would make every grep below
1700
+ // vacuously green. Prove the SCANNER works even when it finds nothing, so
1701
+ // "examined nothing" can never masquerade as "found nothing wrong"
1702
+ // ([[zero-is-not-a-pass]]).
1703
+ it("the scanner actually walks this project's source", () => {
1704
+ expect(SOURCES.length).toBeGreaterThan(0);
1705
+ });
1706
+
1707
+ // \`skipIf\` rather than an early return: a skipped test is VISIBLE in the run
1708
+ // summary, whereas a console.warn on a passing test is swallowed by vitest's
1709
+ // default reporter. "0 card paths" must look different from "all protected".
1710
+ it.skipIf(SERVER_CARD_PATHS.length === 0)(
1711
+ "every server-side card path verifies a bot token",
1712
+ () => {
1713
+ const bare = SERVER_CARD_PATHS.filter((f) => !read(f).includes("verifyTurnstile"));
1714
+ expect(bare, "card-accepting handler with no bot check").toEqual([]);
1715
+ },
1716
+ );
1717
+
1718
+ it.skipIf(SERVER_CARD_PATHS.length === 0)(
1719
+ "every server-side card path applies its OWN rate limit",
1720
+ () => {
1721
+ // Authentication is not a rate limit. Ownership checks are not a rate
1722
+ // limit. The handler has to consult the policy and a bucket.
1723
+ const bare = SERVER_CARD_PATHS.filter((f) => {
1724
+ const src = read(f);
1725
+ return !(src.includes("policyForVerdict") && src.includes("cardPathBucket"));
1726
+ });
1727
+ expect(bare, "card-accepting handler with no rate limit").toEqual([]);
1728
+ },
1729
+ );
1730
+
1731
+ it.skipIf(CLIENT_CARD_PATHS.length === 0)(
1732
+ "every browser confirm() call site actually mints a Turnstile token",
1733
+ () => {
1734
+ const bare = CLIENT_CARD_PATHS.filter((f) => !read(f).includes("awaitToken"));
1735
+ expect(bare, "confirm call site that never requests a token").toEqual([]);
1736
+ },
1737
+ );
1738
+
1739
+ it("the emitted policy still fails OPEN and keeps its verdicts distinct", async () => {
1740
+ // EXECUTED, not grepped. A toContain on the source would pass against a
1741
+ // policy that had been quietly inverted.
1742
+ const guard = await import("../lib/payments/card-path-guard");
1743
+
1744
+ const p = (outcome: string) =>
1745
+ guard.policyForVerdict({ outcome, reason: "t" } as never);
1746
+
1747
+ // Only an AFFIRMATIVE rejection refuses. Everything else proceeds.
1748
+ expect(p("fail").refuse).toBe(true);
1749
+ expect(p("pass").refuse).toBe(false);
1750
+ expect(p("degraded").refuse, "a Cloudflare outage must not stop payments").toBe(false);
1751
+ expect(p("no-token").refuse).toBe(false);
1752
+ expect(p("unconfigured").refuse).toBe(false);
1753
+
1754
+ // "Could not check" keeps the full budget; "no token at all" is throttled.
1755
+ expect(p("degraded").limit).toBe(guard.VERIFIED_BUDGET);
1756
+ expect(p("no-token").limit).toBe(guard.UNVERIFIED_BUDGET);
1757
+ expect(guard.UNVERIFIED_BUDGET).toBeLessThan(guard.VERIFIED_BUDGET);
1758
+
1759
+ // A degradation is reported; the check WORKING (a rejected token) is not,
1760
+ // or routine noise buries the signal.
1761
+ expect(p("degraded").report).toBe(true);
1762
+ expect(p("no-token").report).toBe(true);
1763
+ expect(p("fail").report).toBe(false);
1764
+ expect(p("pass").report).toBe(false);
1765
+ });
1766
+
1767
+ it("the verdict logic keeps 'rejected' and 'unreachable' on different branches", async () => {
1768
+ // The PURE core of the fail-open decision, EXECUTED. This import only works
1769
+ // because \`vitest.config.ts\` aliases \`server-only\` to a stub — without it the
1770
+ // whole file fails to LOAD, and this module's promise of being "unit-testable
1771
+ // without a network or a Cloudflare account" is not true.
1772
+ const { interpretSiteverify } = await import("../lib/payments/turnstile");
1773
+ const out = (body: Parameters<typeof interpretSiteverify>[0]) =>
1774
+ interpretSiteverify(body, "card-path").outcome;
1775
+
1776
+ expect(out({ success: true })).toBe("pass");
1777
+ // A token minted for a DIFFERENT widget is still a valid token. This is the
1778
+ // check that stops one being lifted from elsewhere and replayed here.
1779
+ expect(out({ success: true, action: "signup" })).toBe("fail");
1780
+ // Affirmative rejections — the caller really is suspect.
1781
+ expect(out({ success: false, "error-codes": ["invalid-input-response"] })).toBe("fail");
1782
+ expect(out({ success: false, "error-codes": ["timeout-or-duplicate"] })).toBe("fail");
1783
+ // OUR fault, not theirs. These MUST degrade: failing closed on our own
1784
+ // rotated or typo'd secret would refuse every payment with a message
1785
+ // blaming the customer.
1786
+ expect(out({ success: false, "error-codes": ["invalid-input-secret"] })).toBe("degraded");
1787
+ expect(out({ success: false, "error-codes": ["internal-error"] })).toBe("degraded");
1788
+ });
1789
+
1790
+ it("the rate-limit window stays sized for card entry, not order submission", async () => {
1791
+ const guard = await import("../lib/payments/card-path-guard");
1792
+ // Thirty people giving over one wifi NAT at a fundraising dinner is a good
1793
+ // night, not an attack. A per-minute window turns that into a wall of 429s.
1794
+ expect(guard.CARD_PATH_WINDOW_MS).toBeGreaterThanOrEqual(10 * 60 * 1000);
1795
+ expect(guard.VERIFIED_BUDGET).toBeGreaterThanOrEqual(20);
1796
+ });
1797
+
1798
+ it("verified and unverified traffic occupy separate buckets", async () => {
1799
+ const guard = await import("../lib/payments/card-path-guard");
1800
+ // Otherwise a token-less request from one office eats the budget of a
1801
+ // shared-NAT customer who passed the check.
1802
+ expect(guard.cardPathBucket("1.2.3.4", "pass" as never)).not.toBe(
1803
+ guard.cardPathBucket("1.2.3.4", "no-token" as never),
1804
+ );
1805
+ });
1806
+
1807
+ it("the widget is invisible unless Cloudflare wants a human", () => {
1808
+ // A bare <div class="cf-turnstile"> shows a checkbox to every customer, and
1809
+ // a visible challenge on a payment form costs real conversions.
1810
+ const widget = read("components/TurnstileWidget.tsx");
1811
+ expect(widget).toContain('appearance: "interaction-only"');
1812
+ });
1813
+
1814
+ it("every Turnstile failure callback is wired", () => {
1815
+ // Unwired, the widget silently never mints a token and the customer gets a
1816
+ // baffling refusal at submit with nothing to act on.
1817
+ const widget = read("components/TurnstileWidget.tsx");
1818
+ for (const cb of ["error-callback", "timeout-callback", "expired-callback"]) {
1819
+ expect(widget, \`\${cb} is not wired\`).toContain(cb);
1820
+ }
1821
+ });
1822
+ });
1823
+ `;
1824
+ const CARD_PATH_ENV_BLOCK = `
1825
+ # --- Card-path bot protection (Cloudflare Turnstile) -------------------------
1826
+ # Create a widget: https://dash.cloudflare.com/?to=/:account/turnstile
1827
+ #
1828
+ # Set BOTH or NEITHER. A half-configured pair is worse than neither — the widget
1829
+ # mints tokens nobody verifies, or the server expects tokens no widget renders.
1830
+ # \`turnstileStartupNotice()\` says so out loud at boot; log it from instrumentation.
1831
+ #
1832
+ # Cloudflare's always-passes / always-blocks TEST keys are the right thing to use
1833
+ # in development: https://developers.cloudflare.com/turnstile/troubleshooting/testing/
1834
+ NEXT_PUBLIC_TURNSTILE_SITE_KEY=
1835
+ TURNSTILE_SECRET_KEY=
1836
+ `;
819
1837
  /**
820
1838
  * Vitest config for the scaffolded project.
821
1839
  *
822
- * Emitted for ONE reason that is not optional: vitest's default `exclude` covers
823
- * `node_modules` / `dist` but NOT `.next`, so after the first `next build` the
824
- * runner starts walking build output. It also pins `include` to the project's
825
- * own source rather than everything on disk.
1840
+ * THREE things here, and each was emitted only after a real scaffold proved it
1841
+ * necessary — none is boilerplate:
1842
+ *
1843
+ * 1. `exclude` names `.next`. Vitest's default covers `node_modules` / `dist`
1844
+ * but NOT `.next`, so after the first `next build` the runner starts walking
1845
+ * build output.
1846
+ * 2. The `@/*` alias mirrors `tsconfig.json`'s `paths`. Without it a test can
1847
+ * only reach the app's own modules by relative path, so a test importing the
1848
+ * way the APPLICATION does fails to resolve. `tsc --noEmit` passes either
1849
+ * way — it reads tsconfig, not this file — so the gap only appears at
1850
+ * `vitest run`.
1851
+ * 3. `server-only` is aliased to a stub. Found 2026-08-08 while verifying the
1852
+ * card-path emitter on a real scaffold: `import "server-only"` is a
1853
+ * BUILD-TIME poison pill Next resolves through its own `react-server` export
1854
+ * condition, so outside that toolchain the bare import throws `Cannot find
1855
+ * package 'server-only'` and the whole test file fails to LOAD. That made
1856
+ * every server module in a scaffold untestable — including
1857
+ * `lib/payments/turnstile.ts`, whose header promises its pure verdict logic
1858
+ * is "unit-testable without a network or a Cloudflare account". It was not.
1859
+ *
1860
+ * The near-miss is the instructive part: `next build` passed, and the emitted
1861
+ * card-path suite passed too, because its one cross-module import happens to
1862
+ * be `import type` — erased before resolution. The defect was invisible to
1863
+ * both, and surfaced only from writing a throwaway test that imported the
1864
+ * module for real. Ported from `z2w-crowdcommerce`, which hit it first.
826
1865
  */
827
1866
  const VITEST_CONFIG_TEMPLATE = `import { defineConfig } from "vitest/config";
1867
+ import { fileURLToPath } from "node:url";
828
1868
 
829
1869
  export default defineConfig({
830
1870
  test: {
831
- include: ["test/**/*.test.ts", "{app,components,lib}/**/*.test.ts"],
1871
+ include: ["test/**/*.test.ts", "{app,components,lib}/**/*.test.{ts,tsx}"],
832
1872
  // .next is NOT in vitest's default exclude list — without this, the runner
833
1873
  // walks build output after the first \`next build\`.
834
1874
  exclude: ["node_modules/**", ".next/**", "dist/**"],
835
1875
  },
1876
+ resolve: {
1877
+ alias: {
1878
+ // Mirrors tsconfig's \`paths\`, so a test can import exactly the way the
1879
+ // application does. \`tsc --noEmit\` reads tsconfig and passes without this;
1880
+ // only \`vitest run\` notices it is missing.
1881
+ "@": fileURLToPath(new URL("./", import.meta.url)),
1882
+ // See test/server-only.stub.ts for why this alias exists. It does NOT
1883
+ // weaken the real guarantee: the poison pill protects the CLIENT BUNDLE,
1884
+ // and \`next build\` still resolves the genuine package. A test runner is
1885
+ // not a client bundle.
1886
+ "server-only": fileURLToPath(
1887
+ new URL("./test/server-only.stub.ts", import.meta.url),
1888
+ ),
1889
+ },
1890
+ },
836
1891
  });
837
1892
  `;
1893
+ /**
1894
+ * The stub the alias above points at. Emitted unconditionally, because the
1895
+ * hazard arrives the moment anyone writes their first server module — not when
1896
+ * they write their first test.
1897
+ */
1898
+ const SERVER_ONLY_STUB_TEMPLATE = `/**
1899
+ * Test stub for the \`server-only\` package.
1900
+ *
1901
+ * \`import "server-only"\` is a BUILD-TIME poison pill: Next.js resolves it through
1902
+ * its own \`react-server\` export condition so that importing a server module from
1903
+ * a client component fails the build. The package is not resolvable outside that
1904
+ * toolchain, so under vitest the bare import throws \`Cannot find package
1905
+ * 'server-only'\` and the whole test file fails to LOAD — which would otherwise
1906
+ * make every \`server-only\` module in this project impossible to unit-test.
1907
+ *
1908
+ * Aliasing it to this empty module in \`vitest.config.ts\` lets those modules be
1909
+ * imported by a test. It does NOT weaken the real guarantee: the poison pill
1910
+ * exists to protect the CLIENT BUNDLE, and \`next build\` still resolves the
1911
+ * genuine package. A test runner is not a client bundle.
1912
+ *
1913
+ * Do not delete this file without also removing the alias, or every server-side
1914
+ * test starts failing at import time with an error that names the wrong problem.
1915
+ */
1916
+ export {};
1917
+ `;
838
1918
  /**
839
1919
  * The emitted enforcement half of the form standards.
840
1920
  *
@@ -1741,11 +2821,19 @@ export function scaffoldNextjs(inputs, opts) {
1741
2821
  // means the axis contract is enforced from the first build, not from whenever
1742
2822
  // somebody remembers to re-read a prose checklist.
1743
2823
  const hasObservability = inputs.hasObservability === true;
2824
+ const acceptsCards = inputs.acceptsCards === true;
2825
+ // The shared-store limiter needs a table, so it only ships where the project
2826
+ // already has Postgres. Without one, the in-memory story is all there is and
2827
+ // the emitted comments say so plainly rather than implying a guarantee that
2828
+ // isn't there — an in-memory limiter's real ceiling is `limit × instances`.
2829
+ const durableLimit = acceptsCards && inputs.dbStrategy === "neon-postgres";
1744
2830
  let packageJson = sub(PACKAGE_JSON_TEMPLATE, inputs, opts, spec);
1745
2831
  if (sendsEmail)
1746
2832
  packageJson = withEmailDeps(packageJson);
1747
2833
  if (hasObservability)
1748
2834
  packageJson = withExtraDeps(packageJson, SENTRY_DEPS);
2835
+ if (durableLimit)
2836
+ packageJson = withExtraDeps(packageJson, NEON_DRIVER_DEP);
1749
2837
  let envExample = sub(ENV_EXAMPLE_TEMPLATE, inputs, opts, spec);
1750
2838
  if (sendsEmail)
1751
2839
  envExample += EMAIL_ENV_BLOCK;
@@ -1753,6 +2841,8 @@ export function scaffoldNextjs(inputs, opts) {
1753
2841
  // and Host-routed tenancy (the Host selects the tenant). Emitted once for both.
1754
2842
  if (sendsEmail || hostRouted)
1755
2843
  envExample += CANONICAL_HOSTS_ENV_BLOCK;
2844
+ if (acceptsCards)
2845
+ envExample += CARD_PATH_ENV_BLOCK;
1756
2846
  const typeSpecific = [
1757
2847
  { path: "package.json", content: packageJson },
1758
2848
  {
@@ -1769,6 +2859,7 @@ export function scaffoldNextjs(inputs, opts) {
1769
2859
  },
1770
2860
  { path: "tsconfig.json", content: sub(TSCONFIG_TEMPLATE, inputs, opts, spec) },
1771
2861
  { path: "vitest.config.ts", content: VITEST_CONFIG_TEMPLATE },
2862
+ { path: "test/server-only.stub.ts", content: SERVER_ONLY_STUB_TEMPLATE },
1772
2863
  { path: "app/globals.css", content: globalsCss(spec.primaryColor) },
1773
2864
  { path: "components/FormBits.tsx", content: sub(FORM_BITS_TEMPLATE, inputs, opts, spec) },
1774
2865
  {
@@ -1827,6 +2918,32 @@ export function scaffoldNextjs(inputs, opts) {
1827
2918
  if (sendsEmail) {
1828
2919
  typeSpecific.push(...emailFiles(inputs, opts, spec, "nextjs"));
1829
2920
  }
2921
+ if (acceptsCards) {
2922
+ typeSpecific.push({
2923
+ path: "lib/payments/turnstile.ts",
2924
+ content: sub(TURNSTILE_MODULE_TEMPLATE, inputs, opts, spec),
2925
+ }, {
2926
+ path: "lib/payments/card-path-guard.ts",
2927
+ content: sub(CARD_PATH_GUARD_TEMPLATE, inputs, opts, spec),
2928
+ }, {
2929
+ path: "lib/payments/report.ts",
2930
+ content: hasObservability
2931
+ ? CARD_PATH_REPORT_SENTRY_TEMPLATE
2932
+ : CARD_PATH_REPORT_CONSOLE_TEMPLATE,
2933
+ }, {
2934
+ path: "components/TurnstileWidget.tsx",
2935
+ content: sub(TURNSTILE_WIDGET_TEMPLATE, inputs, opts, spec),
2936
+ }, {
2937
+ path: "test/card-path-standards.test.ts",
2938
+ content: sub(CARD_PATH_STANDARDS_TEST_TEMPLATE, inputs, opts, spec),
2939
+ });
2940
+ if (durableLimit) {
2941
+ typeSpecific.push({
2942
+ path: "lib/payments/rate-limit-durable.ts",
2943
+ content: sub(RATE_LIMIT_DURABLE_TEMPLATE, inputs, opts, spec),
2944
+ }, { path: "db/migrations/0001_rate_limits.sql", content: RATE_LIMITS_DDL_TEMPLATE });
2945
+ }
2946
+ }
1830
2947
  return [...base, ...typeSpecific];
1831
2948
  }
1832
2949
  /**