Case study
JRB Premier Ride
October 28, 2026
PCI DSSStripeCSPTrusted TypesAPI securitySPF / DKIM / DMARCCAADNSSEC
jrbpremierride.com is the booking site for JRB Premier Ride, a Los Angeles black-car service. I built it and maintain it through deltoro.codes.
The project
- Instant quotes. A rider enters a pickup and a drop-off; the server geocodes both through Mapbox, works out distance and drive time, and runs the fare formula.
- Online booking and payment through Stripe Checkout, with a booking confirmation page.
- One-tap ride requests by WhatsApp or text message.
- Bilingual in English and Spanish, and mobile-first.
- Stack: a React and Vite front end prerendered to static HTML, and a Node, Express and MongoDB API, hosted on Render.
Security
It takes bookings and money, so the attack surface is the browser, the API, the payment flow, and the domain. I hardened it end to end and rolled it out in stages so nothing broke in production.
A+
140 / 100 on Mozilla’s HTTP Observatory, 12 of 12 tests passed (baseline before this work: A+, 135). View the live report.
01Threat model
A booking app that takes payments has more to protect than a static site:
- Card-payment fraud and PCI scope: how much of the card flow the site is responsible for.
- Script injection that could tamper with the handoff to checkout.
- API abuse: spam bookings, scraping the billed Mapbox endpoints, junk Stripe sessions.
- Information leakage through error messages.
- Cross-site use of the API from origins that aren’t the site.
- Email spoofing from the business domain.
- Mis-issued certificates for the domain.
- Account takeover of the host, Git, Stripe, the registrar, or the database.
02Starting point
I ran a baseline scan before changing anything. The site was already at A+ (135): HTTPS, a CSP with no 'unsafe-inline' (a postbuild step moves the prerenderer’s inline scripts into external files), Helmet, CORS, Zod validation, rate limiting, signed Stripe webhooks, and DNSSEC. The gaps:
- Google Fonts was allowed in the CSP, and the policy started from
default-src 'self' rather than denying by default. No Trusted Types.
- HSTS was set for one year.
- An unused
mapbox-gl dependency.
- No SPF on the apex or on the email provider’s bounce subdomain, and no CAA record.
03Payments and PCI scope
Payment uses Stripe Checkout (hosted): the browser is redirected to checkout.stripe.com, so card data never touches the site, its scripts, or the API. That keeps the merchant at PCI DSS SAQ A, the lightest self-assessment.
- The charge amount always comes from the server-stored quote, never from the browser.
- The webhook verifies Stripe’s signature against the raw request body and is the only thing that can mark a booking paid. Requests with no signature are rejected with a generic error.
- Stripe secret keys exist only as host environment variables, not in the repo (full Git history scanned clean) and not in the client bundle.
- Defense in depth: the client refuses to redirect anywhere except
https://checkout.stripe.com.
Because Checkout is a full-page redirect, the CSP needs no Stripe origins at all. Adding js.stripe.com “just in case” would only widen the policy. If the site ever moves to Stripe Elements, it would need js.stripe.com in script-src and frame-src, and api.stripe.com in connect-src.
04Front end: deny-by-default CSP and Trusted Types
I self-hosted the Marcellus webfont via @fontsource (its Latin subset covers English and Spanish) and removed Google Fonts, so the site makes no requests to any origin except its own, the API, and Mapbox’s search API. I also removed the unused mapbox-gl package. The final policy, with the API’s origin replaced by a placeholder:
default-src 'none';
script-src 'self'; style-src 'self'; font-src 'self';
img-src 'self' data:;
connect-src 'self' <api-origin>
https://api.mapbox.com;
manifest-src 'self'; form-action 'self'; base-uri 'none';
object-src 'none'; frame-src 'none'; worker-src 'none';
frame-ancestors 'none';
require-trusted-types-for 'script'; trusted-types default;
upgrade-insecure-requests
Trusted Types with React. This app can’t use trusted-types 'none', because it has one legitimate sink: the head manager writes each page’s JSON-LD structured data with innerHTML during client-side navigation. The solution is a single default policy, loaded as the first script, whose createHTML accepts a string only if it contains no <, since text without < can’t create elements, attributes, or event handlers. There is deliberately no createScript or createScriptURL, so string-to-script stays blocked outright. I verified in the browser that markup injection through HTML sinks throws, and that a script whose text is set from a string never executes.
05HTTP response headers
| Header | Why |
Content-Security-Policy | Deny-by-default; only the site itself, the API, and Mapbox search; Trusted Types enforced. |
Strict-Transport-Security | Two years with includeSubDomains (raised from one year). |
X-Frame-Options: DENY | Clickjacking protection for older browsers; frame-ancestors covers modern ones. |
X-Content-Type-Options | nosniff. |
Referrer-Policy | strict-origin-when-cross-origin. |
Permissions-Policy | Geolocation only for the site itself (the “use my location” pickup button); camera, microphone, payment, USB, motion sensors, display capture and ad-topics disabled. payment=() is correct because Stripe Checkout runs on Stripe’s own page. |
Cross-Origin-Opener-Policy | same-origin. |
Cross-Origin-Resource-Policy | same-origin (tightened from same-site). |
06The API
- Headers. Helmet with a deny-everything CSP (the API only returns JSON), two-year HSTS, and
no-referrer.
- CORS. Limited to the custom domain (apex and www),
GET/POST only, Content-Type only, no credentials. Even the host’s own onrender.com copy of the site is refused, which I verified live.
- Validation. Zod on every write endpoint: vehicle restricted to priced vehicles, ObjectId format on quote and booking IDs, phone format, length caps, control-character stripping. Unknown fields are dropped, so a client can never set status or payment fields.
- Rate limits per IP. Tight limits on quotes (each one triggers billed Mapbox calls) and on bookings, contact and checkout (each creates database records or a Stripe session), sized to the cost of each call, plus an overall cap. The JSON body size limit was cut sharply.
- Errors. A central error handler never returns stack traces or internal error text: server errors are a generic 500, malformed JSON is “Bad request”, and database cast or validation errors are a generic 400.
- Email output. The paid-booking notification email HTML-escapes every rider-supplied field.
- Dependencies. The API is at zero vulnerabilities after upgrading Zod (3 → 4) and Express. The remaining front-end advisories are limited to development-only tooling that is never deployed, or to code paths that user input can’t reach.
07Domain: email and certificates
I identified the providers before writing any records. DNS and the registrar are Squarespace Domains; the domain receives no mail (no MX); and the only sender is Resend (on Amazon SES) for booking notifications.
@ TXT "v=spf1 -all"
send TXT "v=spf1 include:amazonses.com ~all"
resend._domainkey TXT (Resend DKIM key, already present)
_dmarc TXT "v=DMARC1; p=quarantine;"
@ CAA 0 issue "pki.goog"
@ CAA 0 issue "letsencrypt.org"
- Apex SPF is
-all because the apex itself sends nothing. Resend sends with a bounce address on the send subdomain, which was missing its SPF record.
- DMARC passes through the aligned DKIM signature. It started at
p=none to monitor. After confirming that a real booking notification passed and reached the client’s inbox, I moved it to p=quarantine the same day. It moves to p=reject after two weeks of clean delivery.
- CAA issuers came from Certificate Transparency logs. Every certificate ever issued for the domain came from Google Trust Services, so
pki.goog is required; Let’s Encrypt is listed as a precaution in case the host ever falls back to it.
- DNSSEC was already on, and every record was confirmed through a public DNSSEC-validating resolver.
08Rollout and verification
The rule throughout: never tighten a header before the code that needs it is live.
- Before deploying: 23 automated API tests (validation, error bodies, CORS, rate limits, and webhook signatures: forged, missing and valid), plus a headless browser run of every page on desktop and mobile under the final enforced policy, including a mocked quote-to-payment handoff to Stripe, asserting zero CSP violations and self-hosted fonts. That run is how I found the JSON-LD Trusted Types sink and designed the default policy.
- Stage 1 shipped the code plus the strict policy as
Content-Security-Policy-Report-Only. On the live site every page reported zero would-be violations, address autocomplete and quotes worked against real Mapbox and the live API, and a real Book & Pay went through Stripe end to end.
- Stage 2 enforced the policy and tightened the remaining headers. I re-ran every check live and tested Book & Pay again.
- One gotcha: the host’s infrastructure-as-code sync added the new headers but didn’t remove the old report-only header, so I deleted it in the dashboard and confirmed with a re-scan. It happened again with routing: removing the catch-all rewrite from
render.yaml didn’t remove the live rule either, so I deleted it in the dashboard too. Lesson: on this host, removing something from the config file doesn’t remove it from the live service, so always re-verify after a removal.
09Follow-ups
- DMARC enforcement (in progress):
p=none → p=quarantine (done) → p=reject (scheduled after two weeks of clean delivery).
- HSTS preload (deferred): it’s effectively permanent and adds little over a two-year HSTS policy.
- Account security: multi-factor authentication is on for every account that can change the site, its data, or its payments.
For a small business that takes payments online, this is the standard I aim for: card data never touches the site, and every layer around checkout is locked down and verified in production.
← Back to projects
Caso de estudio
JRB Premier Ride
28 de octubre de 2026
PCI DSSStripeCSPTrusted TypesSeguridad de APISPF / DKIM / DMARCCAADNSSEC
jrbpremierride.com es el sitio de reservas de JRB Premier Ride, un servicio de autos ejecutivos en Los Ángeles. Lo desarrollé y lo mantengo a través de deltoro.codes.
El proyecto
- Cotizaciones instantáneas. El pasajero indica el punto de recogida y el destino; el servidor geocodifica ambos con Mapbox, calcula la distancia y el tiempo de viaje, y aplica la fórmula de tarifas.
- Reservas y pagos en línea con Stripe Checkout, con una página de confirmación de la reserva.
- Solicitudes de viaje con un toque por WhatsApp o mensaje de texto.
- Bilingüe en inglés y español, y diseñado primero para móviles.
- Stack: un front end en React y Vite prerrenderizado a HTML estático, y una API en Node, Express y MongoDB, alojados en Render.
Seguridad
Este sitio recibe reservas y dinero, así que la superficie de ataque abarca el navegador, la API, el flujo de pago y el dominio. Lo protegí de principio a fin y lo implementé por etapas para que nada fallara en producción.
A+
140 / 100 en el HTTP Observatory de Mozilla, 12 de 12 pruebas superadas (punto de partida antes de este trabajo: A+, 135). Ver el informe en vivo.
01Modelo de amenazas
Una aplicación de reservas que cobra tiene más que proteger que un sitio estático:
- Fraude con tarjetas y alcance de PCI: cuánta parte del flujo de la tarjeta queda bajo la responsabilidad del sitio.
- Inyección de scripts que podría alterar el paso hacia el pago.
- Abuso de la API: reservas falsas, extracción masiva de los endpoints de Mapbox que se cobran por uso, sesiones basura de Stripe.
- Filtración de información a través de los mensajes de error.
- Uso de la API desde otros sitios que no son el propio.
- Suplantación de correo desde el dominio de la empresa.
- Certificados emitidos indebidamente para el dominio.
- Toma de control de cuentas: el proveedor de alojamiento, Git, Stripe, el registrador o la base de datos.
02Punto de partida
Antes de cambiar nada, hice un análisis de referencia. El sitio ya tenía A+ (135): HTTPS, una CSP sin 'unsafe-inline' (un paso posterior a la compilación traslada los scripts en línea del prerrenderizador a archivos externos), Helmet, CORS, validación con Zod, límites de solicitudes, webhooks de Stripe firmados y DNSSEC. Las deficiencias:
- La CSP permitía Google Fonts y partía de
default-src 'self' en lugar de denegar todo por defecto. Sin Trusted Types.
- HSTS estaba configurado a un año.
- Una dependencia
mapbox-gl sin usar.
- Sin SPF en el dominio raíz ni en el subdominio de rebotes del proveedor de correo, y sin registro CAA.
03Pagos y alcance de PCI
El pago usa Stripe Checkout (alojado por Stripe): el navegador se redirige a checkout.stripe.com, así que los datos de la tarjeta nunca pasan por el sitio, sus scripts ni la API. Eso mantiene al comercio en PCI DSS SAQ A, la autoevaluación más sencilla.
- El monto del cobro siempre proviene de la cotización guardada en el servidor, nunca del navegador.
- El webhook verifica la firma de Stripe sobre el cuerpo original de la solicitud y es lo único que puede marcar una reserva como pagada. Las solicitudes sin firma se rechazan con un error genérico.
- Las claves secretas de Stripe existen únicamente como variables de entorno en el servidor: no están en el repositorio (se revisó todo el historial de Git sin hallazgos) ni en el paquete del cliente.
- Defensa en profundidad: el cliente se niega a redirigir a cualquier destino que no sea
https://checkout.stripe.com.
Como Checkout es una redirección de página completa, la CSP no necesita ningún origen de Stripe. Agregar js.stripe.com «por si acaso» solo ampliaría la política. Si algún día el sitio pasa a Stripe Elements, necesitará js.stripe.com en script-src y frame-src, y api.stripe.com en connect-src.
04Front end: CSP que deniega por defecto y Trusted Types
Alojé la tipografía Marcellus en el propio sitio mediante @fontsource (su subconjunto latino cubre el inglés y el español) y eliminé Google Fonts, de modo que el sitio no hace solicitudes a ningún origen salvo el propio, la API y la API de búsqueda de Mapbox. También eliminé el paquete mapbox-gl, que no se usaba. La política final, con el origen de la API sustituido por un marcador de posición:
default-src 'none';
script-src 'self'; style-src 'self'; font-src 'self';
img-src 'self' data:;
connect-src 'self' <api-origin>
https://api.mapbox.com;
manifest-src 'self'; form-action 'self'; base-uri 'none';
object-src 'none'; frame-src 'none'; worker-src 'none';
frame-ancestors 'none';
require-trusted-types-for 'script'; trusted-types default;
upgrade-insecure-requests
Trusted Types con React. Esta aplicación no puede usar trusted-types 'none', porque tiene un punto de inserción legítimo: el gestor del <head> escribe los datos estructurados JSON-LD de cada página con innerHTML durante la navegación del lado del cliente. La solución es una única política default, cargada como el primer script, cuyo createHTML solo acepta una cadena si no contiene <: un texto sin < no puede crear elementos, atributos ni manejadores de eventos. A propósito no tiene createScript ni createScriptURL, así que convertir una cadena en script sigue bloqueado por completo. Comprobé en el navegador que inyectar marcado a través de los puntos de inserción de HTML genera un error, y que un script cuyo texto se asigna desde una cadena nunca se ejecuta.
05Encabezados de respuesta HTTP
| Encabezado | Propósito |
Content-Security-Policy | Deniega por defecto; solo el propio sitio, la API y la búsqueda de Mapbox; Trusted Types aplicado. |
Strict-Transport-Security | Dos años con includeSubDomains (antes, un año). |
X-Frame-Options: DENY | Protección contra clickjacking para navegadores antiguos; frame-ancestors cubre los modernos. |
X-Content-Type-Options | nosniff. |
Referrer-Policy | strict-origin-when-cross-origin. |
Permissions-Policy | Ubicación permitida solo para el propio sitio (el botón «usar mi ubicación» para el punto de recogida); cámara, micrófono, pagos, USB, sensores de movimiento, captura de pantalla y temas publicitarios desactivados. payment=() es correcto porque Stripe Checkout se ejecuta en la página de Stripe. |
Cross-Origin-Opener-Policy | same-origin. |
Cross-Origin-Resource-Policy | same-origin (antes, same-site). |
06La API
- Encabezados. Helmet con una CSP que lo deniega todo (la API solo devuelve JSON), HSTS de dos años y
no-referrer.
- CORS. Limitado al dominio propio (raíz y www), solo
GET/POST, solo el encabezado Content-Type, sin credenciales. Incluso la copia del sitio en onrender.com del propio proveedor queda rechazada; se verificó en vivo.
- Validación. Zod en todos los endpoints de escritura: el vehículo se limita a los que tienen precio, formato de ObjectId en los identificadores de cotizaciones y reservas, formato de teléfono, longitudes máximas y eliminación de caracteres de control. Los campos desconocidos se descartan, así que un cliente nunca puede asignar campos de estado o de pago.
- Límites de solicitudes por IP. Límites estrictos en las cotizaciones (cada una genera llamadas a Mapbox que se cobran) y en las reservas, el contacto y el pago (cada una crea registros en la base de datos o una sesión de Stripe), ajustados al costo de cada llamada, además de un límite general. El tamaño máximo del cuerpo JSON se redujo considerablemente.
- Errores. Un gestor central de errores nunca devuelve trazas de pila ni texto interno: los errores del servidor son un 500 genérico, el JSON mal formado devuelve «Bad request» y los errores de conversión o validación de la base de datos son un 400 genérico.
- Correos salientes. El correo de notificación de reservas pagadas escapa en HTML todos los campos escritos por el pasajero.
- Dependencias. La API quedó sin vulnerabilidades tras actualizar Zod (3 → 4) y Express. Los avisos que quedan en el front end se limitan a herramientas de desarrollo que nunca se despliegan o a partes del código a las que no llega ninguna entrada del usuario.
07Dominio: correo y certificados
Identifiqué a los proveedores antes de escribir cualquier registro. El DNS y el registrador son Squarespace Domains; el dominio no recibe correo (sin MX); y el único remitente es Resend (sobre Amazon SES), para las notificaciones de reservas.
@ TXT "v=spf1 -all"
send TXT "v=spf1 include:amazonses.com ~all"
resend._domainkey TXT (Resend DKIM key, already present)
_dmarc TXT "v=DMARC1; p=quarantine;"
@ CAA 0 issue "pki.goog"
@ CAA 0 issue "letsencrypt.org"
- El SPF del dominio raíz es
-all porque la raíz no envía nada. Resend envía con una dirección de rebote en el subdominio send, al que le faltaba su registro SPF.
- DMARC se cumple gracias a la firma DKIM alineada. Empezó en
p=none para monitorear. Tras confirmar que una notificación de reserva real pasó la verificación y llegó a la bandeja de entrada del cliente, lo cambié a p=quarantine ese mismo día. Pasará a p=reject después de dos semanas de entregas sin problemas.
- Las autoridades del CAA salieron de los registros de Certificate Transparency. Todos los certificados emitidos para el dominio provienen de Google Trust Services, así que
pki.goog es obligatorio; Let’s Encrypt se incluye como precaución por si el proveedor alguna vez recurre a él.
- DNSSEC ya estaba activado, y cada registro se confirmó mediante un resolutor público que valida DNSSEC.
08Implementación y verificación
La regla en todo momento: nunca endurecer un encabezado antes de que esté en producción el código que lo necesita.
- Antes del despliegue: 23 pruebas automatizadas de la API (validación, cuerpos de error, CORS, límites de solicitudes y firmas de webhook falsificadas, ausentes y válidas), además de un navegador sin interfaz que recorrió cada página en escritorio y en móvil bajo la política final aplicada, incluido un paso simulado de cotización a pago en Stripe, y verificó que no hubiera ninguna violación de la CSP y que las fuentes fueran propias. Esa prueba es la que me permitió descubrir el punto de inserción de Trusted Types en el JSON-LD y diseñar la política
default.
- Etapa 1: se publicó el código junto con la política estricta como
Content-Security-Policy-Report-Only. En el sitio en vivo, ninguna página reportó posibles violaciones, el autocompletado de direcciones y las cotizaciones funcionaron con Mapbox real y la API en producción, y una reserva real con pago completó el recorrido por Stripe de principio a fin.
- Etapa 2: se aplicó la política y se endurecieron los demás encabezados. Repetí todas las verificaciones en vivo y volví a probar la reserva con pago.
- Un imprevisto: la sincronización de infraestructura como código del proveedor agregó los encabezados nuevos, pero no eliminó el antiguo encabezado de solo reporte, así que lo borré desde el panel y lo confirmé con un nuevo análisis. Volvió a ocurrir con el enrutamiento: quitar la regla de reescritura general de
render.yaml tampoco eliminó la regla activa, así que también la borré desde el panel. Lección: en este proveedor, quitar algo del archivo de configuración no lo quita del servicio en vivo; siempre hay que volver a verificar después de eliminar algo.
09Seguimiento
- En curso: aplicación de DMARC:
p=none → p=quarantine (hecho) → p=reject (programado tras dos semanas de entregas sin problemas).
- Pospuesto: precarga de HSTS: es prácticamente permanente y aporta poco frente a una política HSTS de dos años.
- Seguridad de las cuentas: la autenticación multifactor está activada en todas las cuentas que pueden modificar el sitio, sus datos o sus pagos.
Para una pequeña empresa que cobra en línea, este es el estándar que busco: los datos de la tarjeta nunca pasan por el sitio, y cada capa alrededor del pago está protegida y verificada en producción.
← Volver a proyectos