惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Latest news
Latest news
Schneier on Security
Schneier on Security
Cyberwarzone
Cyberwarzone
L
LINUX DO - 热门话题
P
Privacy International News Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
The Exploit Database - CXSecurity.com
C
Cybersecurity and Infrastructure Security Agency CISA
Scott Helme
Scott Helme
V
Vulnerabilities – Threatpost
I
Intezer
aimingoo的专栏
aimingoo的专栏
月光博客
月光博客
Simon Willison's Weblog
Simon Willison's Weblog
GbyAI
GbyAI
Google DeepMind News
Google DeepMind News
小众软件
小众软件
博客园 - 三生石上(FineUI控件)
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
N
News and Events Feed by Topic
阮一峰的网络日志
阮一峰的网络日志
S
Secure Thoughts
The Register - Security
The Register - Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
www.infosecurity-magazine.com
www.infosecurity-magazine.com
爱范儿
爱范儿
L
Lohrmann on Cybersecurity
M
MIT News - Artificial intelligence
H
Hacker News: Front Page
Last Week in AI
Last Week in AI
L
LINUX DO - 最新话题
C
Check Point Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
MyScale Blog
MyScale Blog
Engineering at Meta
Engineering at Meta
Project Zero
Project Zero
A
About on SuperTechFans
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Security Blog
Microsoft Security Blog
Hugging Face - Blog
Hugging Face - Blog
Recent Announcements
Recent Announcements
H
Heimdal Security Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
D
Docker
Forbes - Security
Forbes - Security
云风的 BLOG
云风的 BLOG

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Custom e-commerce on Firebase: catalog, atomic orders and admin panel
Andrea Roversi · 2026-06-28 · via DEV Community

How I built a fully custom e-commerce from scratch using Firebase Realtime Database and Netlify — no off-the-shelf platforms: per-product pricing variants, an admin panel protected by a PBKDF2 hash with no password in the source code, duplicate-proof atomic order numbering, and automatic vendor identification via a cross-app token.


The context

A POS terminal reseller needed a showcase site with an integrated e-commerce. The requirements were clear: no payment gateway to integrate (checkout with ready-made payment links or bank transfer details), a catalog of around seven products with selectable pricing variants, and the ability for their sales team to place orders directly from the site — with the salesperson’s name automatically saved on each order, read from their identity already authenticated in the internal management panel.

The decision to skip off-the-shelf e-commerce platforms was deliberate: something fully custom was needed, integrable with the Firebase ecosystem already in use for the management panel, and controllable in every detail. Resulting stack: vanilla HTML/CSS/JS, Firebase Realtime Database for catalog and orders, Firebase Storage for images and PDFs, Netlify for hosting and serverless functions.


Architecture: two separate Firebase projects

The first key decision was keeping the e-commerce database completely separate from the internal management panel’s database. With around forty orders per day (about fifteen thousand a year), merging them into the same Firebase project would have created risk of contamination between commercial data and administrative data (salaries, budgets, employee records).

The e-commerce Realtime Database structure:

{
  "products": {
    "{id}": {
      "name": "Product A",
      "price": 0,
      "image": "https://...",
      "activeTariffs": ["tariff_id_1", "tariff_id_2"]
    }
  },
  "tariffs": {
    "{id}": {
      "name": "Plan A", "code": "PLAN-CODE",
      "fee": "€0/month", "commission": "1.00%",
      "pdfUrl": "https://firebasestorage..."
    }
  },
  "orders": {
    "{pushKey}": {
      "number": 1, "vendor": "Alice",
      "customer": { "name": "...", "email": "..." },
      "items": [{ "product": "Product A", "tariff": "Plan A" }]
    }
  },
  "counters": {
    "lastOrderNumber": 42
  }
}


Pricing variants: global archive + per-product assignment

The most interesting data modeling challenge was handling pricing plans. Each POS terminal can be paired with multiple pricing tiers, but the same plans repeat across different products. Embedding tariffs inside each product would mean duplicating data and updating multiple nodes every time a plan changes.

The solution was a global archive at /tariffs with all plans defined once, and per product an activeTariffs array holding the IDs of applicable plans. The admin can check or uncheck plans per product with a checkbox, without touching the plan data itself. Products without plans (e.g. a printer) use the noTariffs: true flag instead.

On the frontend, when the user selects a plan from the product sheet, a detail box updates in real time showing all information: commissions, monthly fee, linked account and card, economic conditions, included services, and — highlighted in monospace — the provider plan code to communicate to the customer.


Order numbering: Firebase atomic transaction

Progressive order numbering sounds trivial, but with multiple vendors placing orders concurrently it becomes a classic race condition problem. If two vendors press “Confirm” at the same instant, both read lastOrderNumber = 41 and write 42 — one order vanishes.

Firebase Realtime Database solves this with atomic transactions: the runTransaction() function attempts the update, and if the value changed on the server in the meantime, it automatically retries until it succeeds with the correct value.

// Atomic counter increment — zero duplicates even with concurrent vendors
async function submitOrder(orderData) {
  const counterRef = ref(db, 'counters/lastOrderNumber');

  const { snapshot } = await runTransaction(counterRef, currentValue => {
    // currentValue is null on the first order
    return (currentValue || 0) + 1;
  });

  const orderNumber = snapshot.val(); // guaranteed unique

  const ordersRef = ref(db, 'orders');
  await push(ordersRef, {
    number:   orderNumber,
    vendor:   orderData.vendorName || 'Anonymous',
    customer: orderData.customer,
    items:    orderData.items,
    method:   orderData.paymentMethod,
    ts:       Date.now()
  });
}

Note: The /counters node in Firebase rules has ".read": false — it’s not readable by the client. Only the transaction writes to that node; the number comes back in the transaction response itself.


Admin panel: PBKDF2 with no password in the source

The admin panel lets you manage products (name, price, images, assigned plans) and the global pricing archive (provider codes, fees, conditions, T&C PDFs). It must be accessible only to those who know the password, but without a dedicated backend.

Storing the password in plain text in the source code is obviously out of the question — anyone reading the HTML file sees it. But even hashing isn’t enough with plain MD5 or SHA-256: they’re fast to brute-force. The solution is PBKDF2 (Password-Based Key Derivation Function 2), which applies the hash function thousands of times making it computationally expensive to attack.

The browser’s Web Crypto API exposes PBKDF2 natively. At first setup, the hash is generated outside the site (or with a small Node script) and only the hash and salt are put in the code — never the original password.

// In the source: only salt and hash. The password is never there.
const STORED_SALT = "a7f3..."; // randomly generated at setup
const STORED_HASH = "e9b2..."; // PBKDF2 of the real password

async function verifyPassword(input) {
  const enc = new TextEncoder();
  const keyMaterial = await crypto.subtle.importKey(
    'raw', enc.encode(input), 'PBKDF2', false, ['deriveBits']
  );
  const derived = await crypto.subtle.deriveBits({
    name: 'PBKDF2',
    salt: hexToBuffer(STORED_SALT),
    iterations: 310000,   // expensive to brute-force
    hash: 'SHA-256'
  }, keyMaterial, 256);

  return bufferToHex(derived) === STORED_HASH;
}

After a successful verification, the admin performs an anonymous Firebase sign-in in the background: this allows the database Security Rules to recognize the user as authenticated (auth != null) and authorize writes on products and plans. The catalog remains publicly readable, orders are protected.


The zero-value trap in JavaScript

During development I encountered a subtle bug worth documenting: a terminal’s price was zero (included in the monthly fee), but the site kept showing “price to be defined” even after saving it correctly.

The problem was JavaScript’s falsy evaluation. In two places in the code I was using patterns like:

// ❌ WRONG: 0 is falsy, treated as absent
const price = p.price || null;        // 0 → null → Firebase deletes the field
const display = p.price ? ... : 'price to be defined'; // 0 → else branch

// In the admin HTML template:
`value="${p.price || ''}"`   // 0 || '' → '', field appears empty on reload

// ✅ CORRECT: != null is true for any number, including zero
const price = p.price != null ? p.price : null;
const display = p.price != null ? ... : 'price to be defined';
`value="${p.price != null ? p.price : ''}"`

The bug manifested in three different places with different effects: during save (the field was deleted by Firebase because it received null), in the admin template (the field appeared empty on reload and the next save wrote null again), and in the frontend display (showing the fallback instead of the price). The fix is always the same: use != null instead of || or a ternary without a guard.


Content Security Policy and Firebase: dynamic subdomains

Adding a Content Security Policy is good security practice, but Firebase Realtime Database uses long-polling as a fallback channel alongside WebSockets, and the subdomains it generates are dynamic and unpredictable (e.g. s-gke-euw1-nssi1-1.europe-west1.firebasedatabase.app). A CSP in an HTML <meta> tag doesn’t support subdomain wildcards, so Firebase was silently blocked.

The solution is moving the CSP from HTML to Netlify’s HTTP headers in netlify.toml, where wildcards work correctly:

[[headers]]
  for = "/*"
  [headers.values]
    Content-Security-Policy = """
      default-src 'self';
      script-src 'self' 'unsafe-inline'
        https://www.gstatic.com
        https://cdnjs.cloudflare.com;
      connect-src 'self'
        https://*.firebasedatabase.app
        wss://*.firebasedatabase.app
        https://*.googleapis.com
        https://firebasestorage.googleapis.com;
      img-src 'self' data: blob:
        https://firebasestorage.googleapis.com;
    """
    X-Frame-Options          = "DENY"
    X-Content-Type-Options   = "nosniff"
    Strict-Transport-Security = "max-age=31536000; includeSubDomains"

⚠️ <meta http-equiv="Content-Security-Policy"> tags don’t support subdomain wildcards in script-src. For Firebase — and any service using dynamic subdomains — always configure the CSP in HTTP server headers. On Netlify, that means netlify.toml.


Security: Firebase rules and architecture

Real protection isn’t about hiding buttons in JavaScript, but in Firebase Security Rules. The final structure:

{
  "rules": {
    "products": {
      ".read": true,
      ".write": "auth != null"
    },
    "tariffs": {
      ".read": true,
      ".write": "auth != null"
    },
    "orders": {
      ".read":  "auth != null",
      ".write": "auth != null"
    },
    "counters": {
      ".read":  false,
      ".write": "auth != null"
    }
  }
}

The next step is replacing the generic auth != null on the orders section with a Firebase custom claim (role: 'vendor') assigned by the Netlify Function that validates the management panel token. This way only vendors with a valid panel-issued token will have access to orders, not just any authenticated user.


The result

A fully custom e-commerce, without off-the-shelf platforms, built on a familiar stack: Firebase for data, Netlify for deployment, vanilla JS for everything else. The vendor opens the site from the management panel with a token in the URL, gets recognized automatically, selects the terminal and plan, fills in customer details, and the order lands on Firebase with a guaranteed-unique sequential number and their name attached.

The most instructive part of the project wasn’t the technical complexity, but how many architectural decisions depend on seemingly simple requirements: separating databases, keeping plans global, using transactions instead of simple writes, moving the CSP from HTML headers to HTTP headers. Each choice prevented a problem that would have surfaced in production.


Originally published on roversia.it