Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,16 @@ OSIRIS_PORT=3000
# osintdefender,insiderpaper,aljazeeraenglish,nexta_live,war_monitor
# OSIRIS_TELEGRAM_CHANNELS=

# Umami page-view analytics — OPTIONAL, OFF by default. Nothing is sent
# anywhere unless BOTH are set, pointing at an Umami instance YOU run.
# UMAMI_URL is the base URL (OSIRIS posts to <UMAMI_URL>/api/send).
# Privacy: when enabled, each page load sends the path, hostname, referrer and
# User-Agent; the visitor IP goes only as an X-Forwarded-For header (for
# Umami's own geo lookup), never in the event payload. If Umami runs in another
# Compose project, attach its network to the osiris service via an override.
# UMAMI_URL=http://umami:3000
# UMAMI_WEBSITE_ID=

# Set by the Docker image already — override only if needed.
# NODE_ENV=production
# PORT=3000
Expand Down
2 changes: 1 addition & 1 deletion SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ ZAP baseline (2026-10-18): **0 High, 5 Medium, 5 Low, 5 Informational** alert ty
- ✅ Scanner repository: Semgrep (JavaScript, Node, secrets, command-injection rules) on every PR.

### A06 — Insecure Design · 🟠 Medium
- ⚠️ **Analytics middleware forwards every page view, including the visitor's IP address, to a hardcoded `http://umami-umami-1:3000`** with a default site ID inherited from the upstream project. This is undisclosed IP logging aimed at infrastructure you may not control; it should be opt-in via configuration.
- ✅ **Analytics is opt-in and off by default**: the middleware sends nothing unless `UMAMI_URL` and `UMAMI_WEBSITE_ID` are both set (no hardcoded host or upstream site ID). The separate visitor-IP "Network Log" event was removed; page views time out after 2s and fail silently. Covered by unit tests.
- ⚠️ Active recon capability exposed on a public dashboard (see A01).
- ⚠️ The SSRF guard checks DNS at validation time; a DNS-rebinding race remains possible (documented in `src/lib/ssrf-guard.ts`).
- ✅ Fail-closed defaults for optional integrations (webhook #44, scanner without key → 503); fixed-upstream proxies instead of caller-supplied URLs.
Expand Down
5 changes: 0 additions & 5 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ services:
restart: unless-stopped
networks:
- default
- umami_default

osiris-cache:
image: nginx:alpine
Expand Down Expand Up @@ -57,10 +56,6 @@ services:
volumes:
nginx-cache:

networks:
umami_default:
external: true

# ── CasaOS app-store metadata (ignored by plain Docker Compose) ──
x-casaos:
architectures:
Expand Down
150 changes: 150 additions & 0 deletions src/middleware.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { NextRequest } from 'next/server';
import type { NextFetchEvent } from 'next/server';
import { middleware } from './middleware';

type FetchArgs = [input: string | URL | Request, init?: RequestInit];

function fakeEvent() {
const pending: Promise<unknown>[] = [];
const event = {
waitUntil: (p: Promise<unknown>) => {
pending.push(p);
},
} as unknown as NextFetchEvent;
return { event, pending };
}

function request(path = '/', headers: Record<string, string> = {}) {
return new NextRequest(`https://osiris.example${path}`, {
headers: { 'user-agent': 'vitest-agent', ...headers },
});
}

function bodyOf(call: FetchArgs) {
return JSON.parse(String(call[1]?.body)) as {
type: string;
payload: Record<string, unknown>;
};
}

describe('analytics middleware', () => {
let fetchMock: ReturnType<typeof vi.fn<(...args: FetchArgs) => Promise<Response>>>;

beforeEach(() => {
fetchMock = vi.fn<(...args: FetchArgs) => Promise<Response>>(
async () => new Response('{}', { status: 200 }),
);
vi.stubGlobal('fetch', fetchMock);
vi.stubEnv('UMAMI_URL', '');
vi.stubEnv('UMAMI_WEBSITE_ID', '');
});

afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
});

it('sends nothing when analytics is not configured', async () => {
const { event, pending } = fakeEvent();
const res = middleware(request('/', { 'x-forwarded-for': '203.0.113.7' }), event);
await Promise.all(pending);
expect(res.status).toBe(200);
expect(res.headers.get('x-middleware-next')).toBe('1');
expect(fetchMock).not.toHaveBeenCalled();
expect(pending).toHaveLength(0);
});

it('sends nothing when only one of UMAMI_URL / UMAMI_WEBSITE_ID is set', async () => {
for (const [url, id] of [
['http://umami.internal:3000', ''],
['', 'site-123'],
]) {
vi.stubEnv('UMAMI_URL', url);
vi.stubEnv('UMAMI_WEBSITE_ID', id);
const { event, pending } = fakeEvent();
middleware(request('/'), event);
await Promise.all(pending);
}
expect(fetchMock).not.toHaveBeenCalled();
});

it('sends nothing when UMAMI_URL is not a valid http(s) URL', async () => {
vi.stubEnv('UMAMI_URL', 'not a url');
vi.stubEnv('UMAMI_WEBSITE_ID', 'site-123');
const { event, pending } = fakeEvent();
middleware(request('/'), event);
await Promise.all(pending);
expect(fetchMock).not.toHaveBeenCalled();
});

it('sends a single page view to the configured endpoint and website id', async () => {
vi.stubEnv('UMAMI_URL', 'http://umami.internal:3000/');
vi.stubEnv('UMAMI_WEBSITE_ID', 'site-123');
const { event, pending } = fakeEvent();
const res = middleware(
request('/dashboard', { 'x-forwarded-for': '203.0.113.7, 10.0.0.1', referer: 'https://ref.example/' }),
event,
);
await Promise.all(pending);

expect(res.headers.get('x-middleware-next')).toBe('1');
expect(fetchMock).toHaveBeenCalledTimes(1);
const call = fetchMock.mock.calls[0];
expect(String(call[0])).toBe('http://umami.internal:3000/api/send');
expect(call[1]?.method).toBe('POST');
expect(call[1]?.signal).toBeInstanceOf(AbortSignal);

const body = bodyOf(call);
expect(body.type).toBe('event');
expect(body.payload.website).toBe('site-123');
expect(body.payload.url).toBe('/dashboard');
expect(body.payload.hostname).toBe('osiris.example');
expect(body.payload.referrer).toBe('https://ref.example/');
// A page view carries no custom event name or data, and never the IP.
expect(body.payload).not.toHaveProperty('name');
expect(body.payload).not.toHaveProperty('data');
expect(JSON.stringify(body)).not.toContain('203.0.113.7');

// Client IP is only forwarded as a header, for Umami's own geo lookup.
const headers = new Headers(call[1]?.headers);
expect(headers.get('x-forwarded-for')).toBe('203.0.113.7');
expect(headers.get('user-agent')).toBe('vitest-agent');
});

it('never sends the visitor-IP "Network Log" event', async () => {
vi.stubEnv('UMAMI_URL', 'http://umami.internal:3000');
vi.stubEnv('UMAMI_WEBSITE_ID', 'site-123');
vi.stubEnv('UMAMI_TRACK_IP', 'true');
const { event, pending } = fakeEvent();
middleware(request('/', { 'cf-connecting-ip': '198.51.100.9' }), event);
await Promise.all(pending);

for (const call of fetchMock.mock.calls) {
const body = bodyOf(call);
expect(body.payload.name).not.toBe('Network Log');
expect(JSON.stringify(body.payload)).not.toContain('198.51.100.9');
}
});

it('does not throw or reject when the analytics request fails', async () => {
vi.stubEnv('UMAMI_URL', 'http://umami.internal:3000');
vi.stubEnv('UMAMI_WEBSITE_ID', 'site-123');
fetchMock.mockRejectedValue(new TypeError('fetch failed'));
const { event, pending } = fakeEvent();
const res = middleware(request('/'), event);
expect(res.headers.get('x-middleware-next')).toBe('1');
await expect(Promise.all(pending)).resolves.toBeDefined();
expect(fetchMock).toHaveBeenCalledTimes(1);
});

it('does not throw when fetch throws synchronously', () => {
vi.stubEnv('UMAMI_URL', 'http://umami.internal:3000');
vi.stubEnv('UMAMI_WEBSITE_ID', 'site-123');
fetchMock.mockImplementation(() => {
throw new TypeError('boom');
});
const { event } = fakeEvent();
expect(() => middleware(request('/'), event)).not.toThrow();
});
});
81 changes: 53 additions & 28 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,63 @@
import { NextResponse } from 'next/server';
import type { NextRequest, NextFetchEvent } from 'next/server';

// Optional, self-hosted Umami page-view analytics. OFF by default: nothing is
// sent anywhere unless the operator sets BOTH UMAMI_URL and UMAMI_WEBSITE_ID.
const ANALYTICS_TIMEOUT_MS = 2000;

function umamiEndpoint(): { endpoint: string; websiteId: string } | null {
const base = process.env.UMAMI_URL?.trim();
const websiteId = process.env.UMAMI_WEBSITE_ID?.trim();
if (!base || !websiteId) return null;
try {
const url = new URL(base);
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
url.pathname = `${url.pathname.replace(/\/+$/, '')}/api/send`;
return { endpoint: url.toString(), websiteId };
} catch {
return null;
}
}

export function middleware(request: NextRequest, event: NextFetchEvent) {
const url = request.nextUrl.pathname;

const ip = request.headers.get('cf-connecting-ip') || request.headers.get('x-forwarded-for') || '127.0.0.1';
const userAgent = request.headers.get('user-agent') || 'Unknown OSIRIS Client';

const basePayload = {
const umami = umamiEndpoint();
if (!umami) return NextResponse.next();

// The client IP is forwarded only as a header so Umami can do its own geo
// lookup / visitor hashing; it is never put in the event payload.
const ip = (request.headers.get('cf-connecting-ip') || request.headers.get('x-forwarded-for') || '')
.split(',')[0]
.trim();
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'User-Agent': request.headers.get('user-agent') || 'Unknown OSIRIS Client',
};
if (ip) headers['x-forwarded-for'] = ip;

const payload = {
hostname: request.nextUrl.hostname,
language: "en-US",
referrer: request.headers.get('referer') || "",
screen: "1920x1080",
title: "OSIRIS",
url: url,
website: process.env.UMAMI_WEBSITE_ID || "cd8f216c-fc3f-45f5-ba1a-e10309a61d18"
language: 'en-US',
referrer: request.headers.get('referer') || '',
screen: '1920x1080',
title: 'OSIRIS',
url: request.nextUrl.pathname,
website: umami.websiteId,
};

const pageView = fetch('http://umami-umami-1:3000/api/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'User-Agent': userAgent, 'x-forwarded-for': ip },
body: JSON.stringify({ payload: basePayload, type: "event" })
}).catch(() => {});

const ipEvent = fetch('http://umami-umami-1:3000/api/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'User-Agent': userAgent, 'x-forwarded-for': ip },
body: JSON.stringify({
payload: { ...basePayload, name: "Network Log", data: { IP: ip } },
type: "event"
})
}).catch(() => {});

event.waitUntil(Promise.all([pageView, ipEvent]));
try {
const pageView = fetch(umami.endpoint, {
method: 'POST',
headers,
body: JSON.stringify({ payload, type: 'event' }),
signal: AbortSignal.timeout(ANALYTICS_TIMEOUT_MS),
}).then(
() => undefined,
() => undefined,
);
event.waitUntil(pageView);
} catch {
// Analytics must never break page loads.
}

return NextResponse.next();
}
Expand Down
Loading