Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Payment Concepts and Security

API Security: HMAC, CSRF, Rate Limits and Trust

Secure the code around your payments. Learn trust boundaries, signed requests with HMAC, constant-time comparison, rate limiting, safe error messages and why the client must never decide the price.

Stripe secures its side of a payment. Your side is still yours: the endpoints that create a Checkout Session, the page that shows the order, the webhook receiver. Attackers target those because they are easier than breaking card networks. This lesson covers the habits that keep a payment integration safe, and the cryptographic tool Stripe uses itself, the HMAC signature, which you will use to verify webhooks in the Webhooks chapter.

Draw the trust boundary

A trust boundary is the line between code you control and input you do not. Everything crossing from the browser into your server is untrusted: form fields, query strings, headers, cookies, JSON bodies. The browser may be a real customer or a script written by someone who read your JavaScript.

For payments, this leads to three firm rules:

  1. The server decides the price. Accept a product ID and quantity from the client. Look up the amount yourself.
  2. The server decides who the customer is. Use your session, not a customerId field sent by the browser, or one user can pay with (or view) another's saved cards.
  3. The server decides when an order is paid. Mark it paid only after Stripe confirms, usually through a verified webhook, never because the browser said "success".

This stand-in shows rule 1 clearly: the same handler written unsafely and safely.

Node.js Never trust the client's price (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

HMAC: proving a message came from who you think

Stripe cannot give webhooks a password, because anyone could POST JSON to your public URL claiming "payment succeeded". Instead Stripe and you share a secret (the whsec_... signing secret). Stripe computes a keyed hash of the message body, called an HMAC, and sends it in a header. You recompute it with the same secret. If the two match, the message is genuine and unmodified, because nobody without the secret can produce the right value.

Node has HMAC built in. Try it: change one character of the body and the signature changes completely.

Node.js Sign and verify a message with HMAC-SHA256

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two details protect you. timingSafeEqual compares in constant time; a normal === can return slightly faster when the first bytes differ, which in theory lets an attacker guess a signature byte by byte. And you verify against the raw body: if a framework parses and re-serializes the JSON first, the bytes change and the check fails.

Replay attacks and timestamps

A captured valid request can be replayed later. Stripe's signature header includes a timestamp that is part of the signed text; you reject anything older than a tolerance (the official library defaults to five minutes). The idea is simple enough to build:

Node.js Reject replayed (old) requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This mirrors the shape of Stripe's Stripe-Signature header (t=...,v1=...). In production you use the official stripe.webhooks.constructEvent, which does exactly these steps for you.

Rate limiting your endpoints

Endpoints that create payments are targets for card testing: bots try thousands of stolen card numbers against any checkout that will let them, looking for ones that work. Defences include rate limits per IP and per session, CAPTCHAs on high-risk forms, requiring a logged-in user, and Stripe Radar rules (see the fraud lesson later). A simple limiter counts requests in a time window:

Node.js A sliding-window rate limiter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Safer errors

Return generic messages to the browser ("Payment could not be completed") and log the details server-side with the Stripe Request-Id. Detailed errors help attackers probe your system, and may reveal API behaviour or internal IDs. Never include a stack trace in a response.

CSRF and CORS in short

Your endpoint that creates Checkout Sessions is a state-changing POST. Protect it with your framework's CSRF token or same-site cookies so another website cannot trigger it using a visitor's session. Do not enable broad CORS (Access-Control-Allow-Origin: *) on endpoints that use cookies. The webhook endpoint is different: it has no cookies, is called by Stripe's servers, and is protected by the signature instead, so it is excluded from CSRF checks.

Next, the rule that makes online card payments safer for customers, and sometimes trickier for you: Strong Customer Authentication and 3D Secure.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. The browser sends { productId: 'mug', amount: 1 }. What should the server charge?

    Prices come from the server's catalog. Client-supplied amounts can be forged.
  2. 2. Why compare signatures with timingSafeEqual?

    A normal comparison can exit early, and timing differences can reveal how many bytes matched.
  3. 3. What defends against replay of a captured, validly signed webhook?

    The timestamp is part of the signed text. Rejecting old timestamps stops replays.
  4. 4. Why must webhook signature verification use the raw request body?

    The signature is over the exact bytes Stripe sent. Any re-serialization breaks the match.

Summary

  • Treat everything from the browser as untrusted: the server sets price, identity and "paid" status.
  • HMAC signatures prove a message is genuine; compare in constant time over the raw body.
  • Signed timestamps and a tolerance window stop replays.
  • Rate-limit payment endpoints against card testing; return generic errors.
  • Webhook endpoints are protected by signatures, not CSRF tokens.

Next: Strong Customer Authentication and 3D Secure