aboutsummaryrefslogtreecommitdiffstats
path: root/lib/adminip.ts
blob: c870af8b052df1fff4f13e2760048754de83feb5 (plain) (blame)
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
// The admin account and the admin password only work from Adam's own
// addresses (2026-12-04: after the desk breach the JWT secret was kept, so a
// copied or forged admin session must be useless from anywhere else).
// config.adminIps: exact IPs and/or IPv4 CIDR ranges. Unset or empty: no
// restriction (so a config without it behaves as before).
import config from "$config";

const v4 = (ip: string) =>
  ip.split(".").reduce((a, o) => a * 256 + Number(o), 0);
const isV4 = (ip: string) => /^\d{1,3}(\.\d{1,3}){3}$/.test(ip);

// The real client: Cloudflare's header (the app is only reachable through the
// tunnel and Caddy). Tor pages carry a placeholder address, never allowed.
export const clientIp = (req: any): string =>
  String(req.headers?.["cf-connecting-ip"] || req.ip || "").replace(/^::ffff:/, "");

export const adminIpAllowed = (req: any): boolean => {
  const list: string[] = (config as any).adminIps;
  if (!Array.isArray(list) || !list.length) return true;
  if (req.isTor) return false;
  const ip = clientIp(req);
  return list.some((entry) => {
    const [net, bits] = String(entry).split("/");
    if (bits === undefined) return ip === net;
    if (!isV4(ip) || !isV4(net)) return false;
    const n = Number(bits);
    if (!(n >= 0 && n <= 32)) return false;
    const block = 2 ** (32 - n); // addresses per network at this prefix length
    return Math.floor(v4(ip) / block) === Math.floor(v4(net) / block);
  });
};