all repos — snow-editor @ 65993a713586363acceab129af67161a5fbe71cc

small and cozy markdown, and orgmode editor

backend/src/originGuard.js (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
import { MSG } from './messages.js';
import { sendError } from './utils.js';

const DEFAULT_ORIGINS = [
  'http://localhost:41737',
  'http://127.0.0.1:41737',
];

let allowedOrigins = [...DEFAULT_ORIGINS];

export function parseAllowedOrigins(value) {
  if (!value || value.trim() === '') {
    return [...DEFAULT_ORIGINS];
  }
  return value
    .split(',')
    .map((origin) => origin.trim())
    .filter(Boolean);
}

export function setAllowedOrigins(origins) {
  allowedOrigins = origins.length > 0 ? origins : [...DEFAULT_ORIGINS];
}

export function getAllowedOrigins() {
  return allowedOrigins;
}

function normalizeOrigin(urlString) {
  try {
    const url = new URL(urlString);
    return `${url.protocol}//${url.host}`;
  } catch {
    return null;
  }
}

function resolveRequestOrigin(req) {
  const origin = req.headers.origin;
  if (origin) {
    return normalizeOrigin(origin);
  }

  const referer = req.headers.referer;
  if (referer) {
    return normalizeOrigin(referer);
  }

  return null;
}

export function requireAllowedOrigin(req, res, next) {
  const requestOrigin = resolveRequestOrigin(req);

  if (!requestOrigin || !allowedOrigins.includes(requestOrigin)) {
    console.warn(
      `[origin-guard] blocked POST /documents origin=${requestOrigin ?? 'missing'}`,
    );
    return sendError(res, 403, 'ORIGIN_NOT_ALLOWED', MSG.ORIGIN_NOT_ALLOWED);
  }

  return next();
}