OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M15-128): Per-module fixes: packages/core/src/modules/tools - R13 and the findings no rule covers
ralph5ef5c3865e79
diff --git a/packages/core/src/modules/tools/src/ip-lookup.test.ts b/packages/core/src/modules/tools/src/ip-lookup.test.tsnew file mode 100644index 000000000..a506f6fa8--- /dev/null+++ b/packages/core/src/modules/tools/src/ip-lookup.test.ts@@ -0,0 +1,67 @@+// Route-handler coverage for runIpLookup — the smell docs/review/tools.md+// (M14-133) flagged as "zero test coverage of the two route handlers."+// getGeoLocation is mocked; everything else (validation, rate limiting,+// private-range classification) runs for real.++import { beforeAll, describe, expect, it, mock } from 'bun:test';+import { testCoreConfig } from '../../../../test/config-fixture';++const GEO = {+ city: 'Stockholm',+ country: 'SE',+ region: 'Stockholm County',+ latitude: 59.33,+ longitude: 18.07,+};++const getGeoLocation = mock((_ip?: string) => Promise.resolve(GEO));+mock.module('../../../clients/geo', () => ({ getGeoLocation }));++let runIpLookup: typeof import('./ip-lookup').runIpLookup;+beforeAll(async () => {+ ({ runIpLookup } = await import('./ip-lookup'));+});++const config = testCoreConfig();++describe('runIpLookup', () => {+ it('rejects when no IP is provided or detectable', async () => {+ const outcome = await runIpLookup(config, undefined, {});+ expect(outcome.status).toBe(400);+ });++ it('rejects a malformed IP', async () => {+ const outcome = await runIpLookup(config, 'not-an-ip', {});+ expect(outcome.status).toBe(400);+ });++ it('resolves a valid IPv4 address via the geo client', async () => {+ getGeoLocation.mockClear();+ const outcome = await runIpLookup(config, '8.8.8.8', {});+ expect(outcome.status).toBe(200);+ if (outcome.status === 200) {+ expect(outcome.result.ip).toBe('8.8.8.8');+ expect(outcome.result.location.city).toBe(GEO.city);+ expect(outcome.result.isPrivate).toBe(false);+ }+ expect(getGeoLocation).toHaveBeenCalledTimes(1);+ });++ it('flags a private address without treating it as localhost', async () => {+ const outcome = await runIpLookup(config, '10.0.0.5', {});+ expect(outcome.status).toBe(200);+ if (outcome.status === 200) {+ expect(outcome.result.isPrivate).toBe(true);+ expect(outcome.result.isLocalhost).toBe(false);+ }+ });++ it('enforces the per-caller rate limit', async () => {+ const headers = { 'x-forwarded-for': '203.0.113.9' };+ let lastOutcome: Awaited<ReturnType<typeof runIpLookup>> | undefined;+ for (let i = 0; i < 21; i++) {+ lastOutcome = await runIpLookup(config, '8.8.8.8', headers);+ }+ expect(lastOutcome?.status).toBe(429);+ });+});diff --git a/packages/core/src/modules/tools/src/rate-limit.ts b/packages/core/src/modules/tools/src/rate-limit.tsindex 3f52bbb9e..e2f200e18 100644--- a/packages/core/src/modules/tools/src/rate-limit.ts+++ b/packages/core/src/modules/tools/src/rate-limit.ts@@ -2,7 +2,22 @@// verbatim from apps/api/src/controllers/tools.controller.ts (M7-008): one// process-local map, keyed per endpoint by the caller.+// Both endpoints are public and unauthenticated, so a key (one per distinct+// caller IP) that is only ever seen once would otherwise sit in the map+// forever. Sweep expired entries every N calls instead of on a timer, so an+// idle process does no extra work.+const SWEEP_EVERY_N_CALLS = 500;+const rateLimitMap = new Map<string, { count: number; resetAt: number }>();+let callsSinceSweep = 0;++function sweepExpired(now: number): void {+ for (const [key, record] of rateLimitMap) {+ if (now > record.resetAt) {+ rateLimitMap.delete(key);+ }+ }+}export function checkRateLimit(key: string,@@ -10,6 +25,13 @@ export function checkRateLimit(max: number): boolean {const now = Date.now();++ callsSinceSweep++;+ if (callsSinceSweep >= SWEEP_EVERY_N_CALLS) {+ callsSinceSweep = 0;+ sweepExpired(now);+ }+const record = rateLimitMap.get(key);if (!record || now > record.resetAt) {diff --git a/packages/core/src/modules/tools/src/site-checker.test.ts b/packages/core/src/modules/tools/src/site-checker.test.tsnew file mode 100644index 000000000..e4406f96a--- /dev/null+++ b/packages/core/src/modules/tools/src/site-checker.test.ts@@ -0,0 +1,39 @@+// Route-handler coverage for runSiteCheck — the smell docs/review/tools.md+// (M14-133) flagged as "zero test coverage of the two route handlers." Only+// the pre-fetch guards (missing/invalid URL, SSRF rejection, rate limit) are+// covered here: they run with no outbound I/O. The full probe (fetch, TLS,+// robots.txt, hosting lookup) is 700 lines of live network calls and is left+// uncovered — exercising it would mean mocking most of the file's behaviour,+// which risks diverging from what it actually does more than it protects.++import { describe, expect, it } from 'bun:test';+import { testCoreConfig } from '../../../../test/config-fixture';+import { runSiteCheck } from './site-checker';++const config = testCoreConfig();++describe('runSiteCheck', () => {+ it('rejects when no URL is provided', async () => {+ const outcome = await runSiteCheck(config, undefined, {});+ expect(outcome.status).toBe(400);+ });++ it('rejects an unparsable URL', async () => {+ const outcome = await runSiteCheck(config, 'not a url', {});+ expect(outcome.status).toBe(400);+ });++ it('rejects a URL that resolves to a non-public address (SSRF guard)', async () => {+ const outcome = await runSiteCheck(config, 'http://127.0.0.1', {});+ expect(outcome.status).toBe(400);+ });++ it('enforces the per-caller rate limit', async () => {+ const headers = { 'x-forwarded-for': '203.0.113.10' };+ let lastOutcome: Awaited<ReturnType<typeof runSiteCheck>> | undefined;+ for (let i = 0; i < 11; i++) {+ lastOutcome = await runSiteCheck(config, 'http://127.0.0.1', headers);+ }+ expect(lastOutcome?.status).toBe(429);+ });+});diff --git a/packages/core/src/modules/tools/tools.routes.ts b/packages/core/src/modules/tools/tools.routes.tsindex cc6c3dcc7..ee5f4ecfb 100644--- a/packages/core/src/modules/tools/tools.routes.ts+++ b/packages/core/src/modules/tools/tools.routes.ts@@ -1,12 +1,9 @@// Ported from apps/api/src/routes/tools.router.ts +-// apps/api/src/controllers/tools.controller.ts (M7-008). V1's Fastify router-// stays the LIVE route (DELEGATE PATTERN) and calls the same-// src/site-checker.ts + src/ip-lookup.ts functions this file does. Both-// routes are hidden from the OpenAPI document, matching V1's+// apps/api/src/controllers/tools.controller.ts (M7-008), calling the same+// src/site-checker.ts + src/ip-lookup.ts functions this file does. Mounted+// into publicApiRoutes since M9-004; both routes stay unauthenticated (V1's+// shape) and hidden from the OpenAPI document, matching V1's// `schema: { hide: true }`.-//-// NAMED GAP, same as every other module here: not yet reachable — main.ts-// does not mount `publicApiRoutes` until a real `AppDeps` exists (P3/P4/P8).import { z } from 'zod';import { defineRoutes } from '../../http/define';