BlueGit

timfa filemanager

Files

filemanager / server / public-url.js

public-url.js

public-url.js 2.5 KiB Download Raw
1'use strict';
2
3// Public base URL of this server, as seen by clients. Used for OAuth
4// metadata, the `iss` parameter, and links in the OpenAPI spec.
5//
6// config.json:
7// "publicUrl": "https://files.example.com" (optional, wins when set)
8// "trustProxy": "loopback" (Express "trust proxy"; default
9// trusts only a proxy on the same
10// machine; false disables)
11
12const { loadConfig } = require('./config');
13
14const DEFAULT_TRUST_PROXY = 'loopback';
15
16function normalizePublicUrl (raw)
17{
18 if (typeof raw !== 'string' || !raw.trim()) return null;
19 let u;
20 try { u = new URL(raw.trim()); } catch { return null; }
21 if (u.protocol !== 'https:' && u.protocol !== 'http:') return null;
22 if (u.username || u.password || u.search || u.hash) return null;
23 return `${u.protocol}//${u.host}${u.pathname.replace(/\/+$/, '')}`;
24}
25
26/**
27 * Value for app.set('trust proxy', ...). Accepts what Express accepts:
28 * boolean, hop count, or (comma separated / array of) addresses, subnets
29 * and the names loopback, linklocal, uniquelocal.
30 */
31function trustProxySetting (config)
32{
33 const v = config ? config.trustProxy : undefined;
34 if (v === undefined || v === null || v === '') return DEFAULT_TRUST_PROXY;
35 if (typeof v === 'boolean') return v;
36 if (typeof v === 'number' && Number.isInteger(v) && v >= 0) return v;
37 if (typeof v === 'string') return v.trim();
38 if (Array.isArray(v) && v.every((x) => typeof x === 'string')) return v;
39 return DEFAULT_TRUST_PROXY;
40}
41
42function publicBaseUrl (req)
43{
44 const configured = normalizePublicUrl(loadConfig().publicUrl);
45 if (configured) return configured;
46 return `${req.protocol}://${requestHost(req)}`;
47}
48
49/** Host header, or X-Forwarded-Host when the direct peer is a trusted proxy. */
50function requestHost (req)
51{
52 const fwd = req.get('x-forwarded-host');
53 const trust = req.app && req.app.get('trust proxy fn');
54 const peer = req.socket && req.socket.remoteAddress;
55 if (fwd && typeof trust === 'function' && trust(peer, 0))
56 {
57 const first = fwd.split(',')[0].trim();
58 if (/^[A-Za-z0-9.\-:[\]]+$/.test(first)) return first;
59 }
60 return req.get('host');
61}
62
63/** Path prefix of the public URL ('' when served at the root). */
64function publicPathPrefix (req)
65{
66 try { return new URL(publicBaseUrl(req)).pathname.replace(/\/+$/, ''); } catch { return ''; }
67}
68
69module.exports = { normalizePublicUrl, trustProxySetting, publicBaseUrl, publicPathPrefix, DEFAULT_TRUST_PROXY };