Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(csp): emit upgrade-insecure-requests only for HTTPS requests (#682) (#699)

suantead1e7b1915a53
diff --git a/.env.example b/.env.example
index fe987e88..befc7961 100644
--- a/.env.example
+++ b/.env.example
@@ -181,6 +181,14 @@ REQUEST_ANALYTICS_MAX_ROWS=100000
# different host than the API (e.g. http://my-server.local).
# DASHBOARD_ORIGINS=http://my-server.local,http://192.168.1.50
+# Content-Security-Policy `upgrade-insecure-requests` directive (#682).
+# Auto (unset): emit only when the request arrives over TLS or behind an
+# HTTPS reverse proxy (X-Forwarded-Proto: https). Plain-HTTP LAN installs
+# (HOST_BIND=0.0.0.0, no TLS in front) stay renderable.
+# true: force the directive on even over plain HTTP (rarely useful).
+# false: force it off even behind HTTPS (e.g. mixed-content reverse proxies).
+# CSP_UPGRADE_INSECURE_REQUESTS=false
+
# --- Advanced / embedding ---------------------------------------------------
# Path to a prebuilt client `dist` directory to serve. Defaults to the bundled
# client build; set this only if you build the dashboard separately.
diff --git a/server/src/__tests__/routes/csp-security.test.ts b/server/src/__tests__/routes/csp-security.test.ts
index 1c4a2750..ac09565b 100644
--- a/server/src/__tests__/routes/csp-security.test.ts
+++ b/server/src/__tests__/routes/csp-security.test.ts
@@ -1,12 +1,15 @@
-import { describe, it, expect, beforeAll } from 'vitest';
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import type { Express } from 'express';
import { createApp } from '../../app.js';
import { initDb } from '../../db/index.js';
+import { loadConfig } from '../../lib/config.js';
-async function getHeaders(app: Express, path: string): Promise<Headers> {
+async function getHeaders(app: Express, path: string, forwardedProto?: string): Promise<Headers> {
const server = app.listen(0);
const addr = server.address() as any;
- const res = await fetch(`http://127.0.0.1:${addr.port}${path}`);
+ const headers: Record<string, string> = {};
+ if (forwardedProto) headers['x-forwarded-proto'] = forwardedProto;
+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, { headers });
server.close();
return res.headers;
}
@@ -49,3 +52,53 @@ describe('CSP security headers', () => {
expect(headers.get('strict-transport-security')).toBeNull();
});
});
+
+// #682: upgrade-insecure-requests broke plain-HTTP LAN installs because the
+// browser rewrites /assets/* to https:// on an origin with no TLS. The directive
+// is now gated by request protocol + the CSP_UPGRADE_INSECURE_REQUESTS env.
+describe('CSP upgrade-insecure-requests (#682)', () => {
+ let app: Express;
+
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ app = createApp();
+ });
+
+ it('omits upgrade-insecure-requests on plain HTTP (LAN)', async () => {
+ const headers = await getHeaders(app, '/api/ping');
+ const csp = headers.get('content-security-policy')!;
+ expect(csp).not.toContain('upgrade-insecure-requests');
+ });
+
+ it('emits upgrade-insecure-requests behind an HTTPS reverse proxy (X-Forwarded-Proto)', async () => {
+ const headers = await getHeaders(app, '/api/ping', 'https');
+ const csp = headers.get('content-security-policy')!;
+ expect(csp).toContain('upgrade-insecure-requests');
+ });
+});
+
+describe('CSP_UPGRADE_INSECURE_REQUESTS env override (#682)', () => {
+ let app: Express;
+ const envKey = 'CSP_UPGRADE_INSECURE_REQUESTS';
+
+ afterAll(() => {
+ delete process.env[envKey];
+ });
+
+ it('force-on: emits the directive even on plain HTTP', async () => {
+ process.env[envKey] = 'true';
+ app = createApp(loadConfig());
+ const headers = await getHeaders(app, '/api/ping');
+ const csp = headers.get('content-security-policy')!;
+ expect(csp).toContain('upgrade-insecure-requests');
+ });
+
+ it('force-off: omits the directive even behind an HTTPS reverse proxy', async () => {
+ process.env[envKey] = 'false';
+ app = createApp(loadConfig());
+ const headers = await getHeaders(app, '/api/ping', 'https');
+ const csp = headers.get('content-security-policy')!;
+ expect(csp).not.toContain('upgrade-insecure-requests');
+ });
+});
diff --git a/server/src/app.ts b/server/src/app.ts
index 7684727f..db663aa2 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -70,6 +70,13 @@ export function createApp(config?: Config) {
// are hashed by the Vite/React build, so 'self' works in production. Inline
// styles from React hydration need 'unsafe-inline'. HSTS stays off because
// this is a single-user local proxy served over HTTP (see README).
+ //
+ // `upgrade-insecure-requests` is emitted by Helmet by default; v0.6.6's
+ // CSP hardening (#498) inherited it and broke HTTP LAN installs because the
+ // browser rewrites /assets/* to https:// on an origin that has no TLS,
+ // producing ERR_SSL_PROTOCOL_ERROR and a blank dashboard (#682).
+ // The directive is dropped from the static Helmet config and re-added per
+ // request below, gated by protocol + the CSP_UPGRADE_INSECURE_REQUESTS env.
app.use(helmet({
contentSecurityPolicy: {
directives: {
@@ -81,10 +88,36 @@ export function createApp(config?: Config) {
fontSrc: ["'self'"],
formAction: ["'self'"],
baseUri: ["'self'"],
+ upgradeInsecureRequests: null,
},
},
hsts: false,
}));
+ // Per-request CSP re-issue: only HTTPS origins should tell the browser to
+ // upgrade http→https, since plain-HTTP LAN setups have no TLS to upgrade to.
+ // `req.secure` is true when the TLS socket terminated on this server; the
+ // X-Forwarded-Proto check covers HTTPS reverse proxies (the documented setup
+ // for publishing the proxy beyond localhost). The env flag overrides both.
+ // Helmet ran above and synchronously set the CSP header on res; this runs
+ // next, still before any route handler writes the body, so setHeader here
+ // lands before the response is flushed.
+ app.use((req, res, next) => {
+ const forwardedProto = req.headers['x-forwarded-proto'];
+ const isHttps =
+ String(forwardedProto ?? '').toLowerCase().startsWith('https') || req.secure;
+ const shouldEmit =
+ cfg.cspUpgradeInsecureRequests === true ||
+ (cfg.cspUpgradeInsecureRequests === undefined && isHttps);
+
+ if (shouldEmit) {
+ const csp = res.getHeader('content-security-policy');
+ if (typeof csp === 'string' && !csp.includes('upgrade-insecure-requests')) {
+ res.setHeader('content-security-policy', `${csp}; upgrade-insecure-requests`);
+ }
+ }
+
+ next();
+ });
app.use(cors({
origin(origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) {
callback(null, !origin || allowedCorsOrigins.has(origin));
diff --git a/server/src/lib/config.ts b/server/src/lib/config.ts
index 63a6ce40..fc3c59ed 100644
--- a/server/src/lib/config.ts
+++ b/server/src/lib/config.ts
@@ -17,6 +17,14 @@ export interface Config {
proxyRateLimitRpm: number;
nodeEnv: string;
serveStaticAssets: boolean;
+ /**
+ * Tri-state override for the CSP `upgrade-insecure-requests` directive (#682).
+ * - undefined: auto — emit the directive only when the request arrived over
+ * TLS (or behind an HTTPS reverse proxy that forwarded X-Forwarded-Proto).
+ * - true: always emit (force HTTPS upgrade even on plain HTTP).
+ * - false: never emit (let HTTP LAN installs render the dashboard).
+ */
+ cspUpgradeInsecureRequests: boolean | undefined;
}
export function loadConfig(): Config {
@@ -35,5 +43,18 @@ export function loadConfig(): Config {
proxyRateLimitRpm: parseRateLimitRpm(),
nodeEnv: process.env.NODE_ENV ?? 'development',
serveStaticAssets: true,
+ // CSP_UPGRADE_INSECURE_REQUESTS: true|false forces the directive on/off;
+ // unset (the default) leaves it on auto — emit only when the request is
+ // already TLS or forwarded as https, so HTTP LAN installs still render.
+ cspUpgradeInsecureRequests: parseCspUpgradeInsecureRequests(),
};
}
+
+function parseCspUpgradeInsecureRequests(): boolean | undefined {
+ const raw = process.env.CSP_UPGRADE_INSECURE_REQUESTS;
+ if (raw === undefined || raw.trim() === '') return undefined;
+ const lower = raw.trim().toLowerCase();
+ if (lower === 'true' || lower === '1' || lower === 'yes') return true;
+ if (lower === 'false' || lower === '0' || lower === 'no') return false;
+ return undefined;
+}