Files
starr-philproperties/middleware/mediaGuard.middleware.js
T
kennethobsequio 439bb33f77 ready to test
Testing

Signed-off-by: Kenneth Obsequio <k80308392@gmail.com>
2026-06-22 10:06:58 +08:00

50 lines
2.2 KiB
JavaScript

/***********************************************************************************************************************************************************************
* File Name: mediaGuard.middleware.js
* Type of Program: Middleware
* Description: Blocks non-browser clients from accessing protected media stream endpoints.
* Checks:
* 1. User-Agent blocklist — cURL, wget, python, httpie, etc.
* 2. Origin / Referer — must be present (browser always sends at least one)
* 3. Allowed origin — must match APP_ORIGIN env (prevents hotlinking)
* Author: rgrgogu
* Date Created: Jun. 12, 2026
***********************************************************************************************************************************************************************/
"use strict";
const R = require("../utils/response.util");
const UA_BLOCKLIST = [
"curl", "wget", "python-requests", "python-urllib",
"axios", "httpie", "insomnia", "postman", "thunder client",
"go-http-client", "java/", "ruby", "php/", "perl/",
];
const APP_ORIGIN = process.env.FRONTEND_URL ?? "http://localhost:5173";
module.exports = function mediaGuard(req, res, next) {
const ua = (req.headers["user-agent"] ?? "").toLowerCase();
const origin = req.headers["origin"] ?? "";
const referer = req.headers["referer"] ?? "";
// ── 1. Block known non-browser user-agents ────────────────────────────────
if (UA_BLOCKLIST.some((b) => ua.includes(b))) {
return R.error(res, "Forbidden.", 403);
}
// ── 2. No UA at all → almost certainly a script ──────────────────────────
if (!ua) {
return R.error(res, "Forbidden.", 403);
}
// ── 3. Must have at least Origin or Referer (browsers always send one) ───
if (!origin && !referer) {
return R.error(res, "Forbidden.", 403);
}
// ── 4. Origin must match app origin (blocks hotlinking from other sites) ─
if (origin && origin !== APP_ORIGIN) {
return R.error(res, "Forbidden.", 403);
}
next();
};