From e0b10781636ad60dc64825eddc3a3b3fb72a3aed Mon Sep 17 00:00:00 2001 From: Alicia Sykes Date: Sat, 15 Nov 2025 20:38:58 +0000 Subject: [PATCH 1/7] Adds npm start script (node env only) --- package.json | 1 + start.js | 164 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 165 insertions(+) create mode 100644 start.js diff --git a/package.json b/package.json index 6ca618e..4e629a7 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "dev": "vite dev", "build": "vite build", "preview": "vite preview", + "start": "node start.js", "prepare": "svelte-kit sync || echo ''", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "lint": "eslint src --ext .ts,.svelte", diff --git a/start.js b/start.js new file mode 100644 index 0000000..3c328c1 --- /dev/null +++ b/start.js @@ -0,0 +1,164 @@ +#!/usr/bin/env node + +/** + * This is just a wrapper around the built SvelteKit app, + * which can otherwise be started with `node build` + * The purpose of this wrapper is to add: + * - Automatic restarts with exponential backoff on crashes + * - Graceful shutdown on SIGTERM and SIGINT + * - Improved logging + */ + +import { spawn } from 'child_process'; +import { existsSync } from 'fs'; +import { join, dirname } from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const BUILD_DIR = join(__dirname, 'build'); +const ENTRY_FILE = join(BUILD_DIR, 'index.js'); +const MAX_RESTARTS = 10; +const INITIAL_BACKOFF = 1000; +const MAX_BACKOFF = 30000; + +let restartCount = 0; +let backoffTime = INITIAL_BACKOFF; +let child = null; +let isShuttingDown = false; + +// Console logging with colors and icons +const colors = { + reset: '\x1b[0m', + red: '\x1b[31m', + green: '\x1b[32m', + yellow: '\x1b[33m', + blue: '\x1b[34m', + cyan: '\x1b[36m' +}; + +const log = (message, type = 'info') => { + const styles = { + error: { color: colors.red, icon: '❌' }, + success: { color: colors.green, icon: '✅' }, + warning: { color: colors.yellow, icon: '⚠️ ' }, + info: { color: colors.cyan, icon: 'ℹ️ ' }, + start: { color: colors.blue, icon: '🚀' }, + stop: { color: colors.yellow, icon: '⏹️ ' }, + wait: { color: colors.yellow, icon: '⏳' } + }; + + const { color, icon } = styles[type] || styles.info; + console.log(`${color}${icon} ${message}${colors.reset}`); +}; + +// Validate build exists and is correct type +function validateBuild() { + if (!existsSync(BUILD_DIR)) { + log('Build directory not found.', 'error'); + log('Run: npm run build:node', 'info'); + process.exit(1); + } + + if (!existsSync(ENTRY_FILE)) { + log('Build entry file not found.', 'error'); + log('The build might not be a Node.js build.', 'warning'); + log('Run: npm run build:node', 'info'); + process.exit(1); + } + + // Check for handler.js which indicates adapter-node + const handlerFile = join(BUILD_DIR, 'handler.js'); + if (!existsSync(handlerFile)) { + log('This appears to be a static build, not a Node.js build.', 'error'); + log('Run: npm run build:node', 'info'); + process.exit(1); + } +} + +function startServer() { + if (isShuttingDown) return; + + log(`Starting server... (attempt ${restartCount + 1})`, 'start'); + + child = spawn('node', ['build'], { + stdio: 'inherit', + env: { ...process.env, NODE_ENV: process.env.NODE_ENV || 'production' } + }); + + // Reset counters after successful run (30s uptime) + const successTimer = setTimeout(() => { + restartCount = 0; + backoffTime = INITIAL_BACKOFF; + }, 30000); + + child.on('error', (err) => { + clearTimeout(successTimer); + log(`Failed to start server: ${err.message}`, 'error'); + // Error event is always followed by exit event, so we handle restart there + }); + + child.on('exit', (code, signal) => { + clearTimeout(successTimer); + child = null; + + if (isShuttingDown) { + log('Server stopped gracefully', 'success'); + process.exit(0); + } + + if (code === 0) { + log('Server exited normally', 'success'); + process.exit(0); + } + + restartCount++; + + if (restartCount >= MAX_RESTARTS) { + log(`Server crashed ${MAX_RESTARTS} times. Giving up.`, 'error'); + process.exit(1); + } + + log(`Server crashed with ${signal ? `signal ${signal}` : `code ${code}`}`, 'warning'); + log(`Restarting in ${backoffTime / 1000}s...`, 'wait'); + + setTimeout(() => { + backoffTime = Math.min(backoffTime * 2, MAX_BACKOFF); + startServer(); + }, backoffTime); + }); +} + +function shutdown(signal) { + if (isShuttingDown) return; + isShuttingDown = true; + + log(`Received ${signal}, shutting down gracefully...`, 'stop'); + + if (child) { + child.kill('SIGTERM'); + + // Force kill after 10s if not stopped + setTimeout(() => { + if (child) { + log('Force killing server...', 'warning'); + child.kill('SIGKILL'); + } + }, 10000); + } else { + process.exit(0); + } +} + +// Handle shutdown signals +process.on('SIGTERM', () => shutdown('SIGTERM')); +process.on('SIGINT', () => shutdown('SIGINT')); +process.on('unhandledRejection', (err) => { + log(`Unhandled rejection: ${err.message}`, 'error'); + shutdown('unhandledRejection'); +}); + +// Validate and start +validateBuild(); +log('Node.js build detected', 'success'); +startServer(); + From 5813e0123b4fd4f3ed2e4cbd053b307bb5063dea Mon Sep 17 00:00:00 2001 From: Alicia Sykes Date: Sat, 15 Nov 2025 21:06:10 +0000 Subject: [PATCH 2/7] Disable Plausible analytic (#30) --- .github/docs/app-customization.md | 27 +++++++++++++++++++ .../about/DeployingSection.svelte | 6 +++-- src/lib/config/customizable-settings.ts | 27 +++++++++++++++++++ src/routes/+layout.svelte | 7 +++-- 4 files changed, 63 insertions(+), 4 deletions(-) diff --git a/.github/docs/app-customization.md b/.github/docs/app-customization.md index d4d2d33..5055e50 100644 --- a/.github/docs/app-customization.md +++ b/.github/docs/app-customization.md @@ -157,6 +157,21 @@ environment: - **Example:** `NTB_ALLOWED_DNS_SERVERS='8.8.8.8,1.1.1.1,9.9.9.9'` - **Note:** Only used when `NTB_ALLOW_CUSTOM_DNS='false'` +### Analytics Settings + +- **`NTB_ANALYTICS_DOMAIN`** + - **Description:** Domain for analytics tracking (for Plausible or similar) + - **Default:** `networking-toolbox.as93.net` + - **Example:** `NTB_ANALYTICS_DOMAIN='myapp.example.com'` + - **Disable:** Set to `false` to disable analytics: `NTB_ANALYTICS_DOMAIN='false'` + +- **`NTB_ANALYTICS_DSN`** + - **Description:** URL to the analytics script + - **Default:** `https://no-track.as93.net/js/script.js` + - **Example:** `NTB_ANALYTICS_DSN='https://plausible.io/js/script.js'` + - **Disable:** Set to `false` to disable analytics: `NTB_ANALYTICS_DSN='false'` + - **Note:** Analytics is disabled if either `NTB_ANALYTICS_DOMAIN` or `NTB_ANALYTICS_DSN` is set to `false` + --- ## Example Configurations @@ -174,6 +189,8 @@ NTB_HOMEPAGE_LAYOUT='categories' NTB_ALLOW_CUSTOM_DNS='false' NTB_BLOCK_PRIVATE_DNS_IPS='true' NTB_ALLOWED_DNS_SERVERS='8.8.8.8,1.1.1.1' +NTB_ANALYTICS_DOMAIN='false' +NTB_ANALYTICS_DSN='false' ``` ### Full Customization @@ -190,5 +207,15 @@ NTB_DEFAULT_LANGUAGE='en' NTB_SHOW_TIPS_ON_HOMEPAGE='true' NTB_ALLOW_CUSTOM_DNS='true' NTB_BLOCK_PRIVATE_DNS_IPS='true' +NTB_ANALYTICS_DOMAIN='myapp.example.com' +NTB_ANALYTICS_DSN='https://plausible.io/js/script.js' +``` + +### Self-Hosted (No Analytics) +```bash +NTB_SITE_TITLE='Internal Network Tools' +NTB_DEFAULT_THEME='dark' +NTB_ANALYTICS_DOMAIN='false' +NTB_ANALYTICS_DSN='false' ``` diff --git a/src/lib/components/page-specific/about/DeployingSection.svelte b/src/lib/components/page-specific/about/DeployingSection.svelte index e7739e4..ad59263 100644 --- a/src/lib/components/page-specific/about/DeployingSection.svelte +++ b/src/lib/components/page-specific/about/DeployingSection.svelte @@ -52,13 +52,15 @@

Customizing

You can customize the branding of your instance, by setting a few environment variables. All are optional.

diff --git a/src/lib/config/customizable-settings.ts b/src/lib/config/customizable-settings.ts index b1cfcbf..dca2118 100644 --- a/src/lib/config/customizable-settings.ts +++ b/src/lib/config/customizable-settings.ts @@ -110,6 +110,31 @@ export const ALLOWED_DNS_SERVERS = env.NTB_ALLOWED_DNS_SERVERS ? env.NTB_ALLOWED_DNS_SERVERS.split(',').map((ip) => ip.trim()) : DEFAULT_TRUSTED_DNS_SERVERS; +/** + * Analytics Settings + * Configure analytics tracking for self-hosted instances + */ + +/** + * Analytics domain (for Plausible or similar analytics) + * Set to 'false' to disable analytics entirely + * Default: 'networking-toolbox.as93.net' + */ +export const ANALYTICS_DOMAIN = env.NTB_ANALYTICS_DOMAIN ?? 'networking-toolbox.as93.net'; + +/** + * Analytics script URL (for Plausible or similar analytics) + * Set to 'false' to disable analytics entirely + * Default: 'https://no-track.as93.net/js/script.js' + */ +export const ANALYTICS_DSN = env.NTB_ANALYTICS_DSN ?? 'https://no-track.as93.net/js/script.js'; + +/** + * Check if analytics is enabled + * Analytics is disabled if either ANALYTICS_DOMAIN or ANALYTICS_DSN is set to 'false' + */ +export const ANALYTICS_ENABLED = ANALYTICS_DOMAIN !== 'false' && ANALYTICS_DSN !== 'false'; + /** * Get user settings list with values prioritized as: * 1. User-set value from localStorage @@ -153,5 +178,7 @@ export function getUserSettingsList(): Array<{ name: string; value: string }> { { name: 'NTB_ALLOW_CUSTOM_DNS', value: env.NTB_ALLOW_CUSTOM_DNS || '' }, { name: 'NTB_BLOCK_PRIVATE_DNS_IPS', value: env.NTB_BLOCK_PRIVATE_DNS_IPS || '' }, { name: 'NTB_ALLOWED_DNS_SERVERS', value: env.NTB_ALLOWED_DNS_SERVERS || '' }, + { name: 'NTB_ANALYTICS_DOMAIN', value: env.NTB_ANALYTICS_DOMAIN || '' }, + { name: 'NTB_ANALYTICS_DSN', value: env.NTB_ANALYTICS_DSN || '' }, ]; } diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index 8692cd7..1ebff0f 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -24,6 +24,7 @@ import { ALL_PAGES } from '$lib/constants/nav'; import { initializeOfflineSupport } from '$lib/stores/offline'; import { bookmarks } from '$lib/stores/bookmarks'; + import { ANALYTICS_ENABLED, ANALYTICS_DOMAIN, ANALYTICS_DSN } from '$lib/config/customizable-settings'; import Header from '$lib/components/furniture/Header.svelte'; import SubHeader from '$lib/components/furniture/SubHeader.svelte'; @@ -400,8 +401,10 @@ })} {/if} - - + + {#if ANALYTICS_ENABLED} + + {/if} From 8076df2212d700c0e5cb2c12ebfecaa4331c94fe Mon Sep 17 00:00:00 2001 From: Alicia Sykes Date: Sat, 15 Nov 2025 21:24:51 +0000 Subject: [PATCH 3/7] Adds tests --- .../lib/config/customizable-settings.test.ts | 345 ++++++++++++++++++ 1 file changed, 345 insertions(+) create mode 100644 tests/unit/lib/config/customizable-settings.test.ts diff --git a/tests/unit/lib/config/customizable-settings.test.ts b/tests/unit/lib/config/customizable-settings.test.ts new file mode 100644 index 0000000..34ea06f --- /dev/null +++ b/tests/unit/lib/config/customizable-settings.test.ts @@ -0,0 +1,345 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; + +describe('customizable-settings - Analytics Configuration', () => { + beforeEach(() => { + vi.resetModules(); + }); + + describe('ANALYTICS_DOMAIN', () => { + it('should use default domain when env var is not set', async () => { + vi.doMock('$env/dynamic/public', () => ({ + env: {}, + })); + vi.doMock('$app/environment', () => ({ + browser: false, + })); + + const { ANALYTICS_DOMAIN } = await import('$lib/config/customizable-settings'); + expect(ANALYTICS_DOMAIN).toBe('networking-toolbox.as93.net'); + }); + + it('should use custom domain when env var is set', async () => { + vi.doMock('$env/dynamic/public', () => ({ + env: { + NTB_ANALYTICS_DOMAIN: 'custom-domain.example.com', + }, + })); + vi.doMock('$app/environment', () => ({ + browser: false, + })); + + const { ANALYTICS_DOMAIN } = await import('$lib/config/customizable-settings'); + expect(ANALYTICS_DOMAIN).toBe('custom-domain.example.com'); + }); + + it('should accept "false" as a value to disable analytics', async () => { + vi.doMock('$env/dynamic/public', () => ({ + env: { + NTB_ANALYTICS_DOMAIN: 'false', + }, + })); + vi.doMock('$app/environment', () => ({ + browser: false, + })); + + const { ANALYTICS_DOMAIN } = await import('$lib/config/customizable-settings'); + expect(ANALYTICS_DOMAIN).toBe('false'); + }); + }); + + describe('ANALYTICS_DSN', () => { + it('should use default DSN when env var is not set', async () => { + vi.doMock('$env/dynamic/public', () => ({ + env: {}, + })); + vi.doMock('$app/environment', () => ({ + browser: false, + })); + + const { ANALYTICS_DSN } = await import('$lib/config/customizable-settings'); + expect(ANALYTICS_DSN).toBe('https://no-track.as93.net/js/script.js'); + }); + + it('should use custom DSN when env var is set', async () => { + vi.doMock('$env/dynamic/public', () => ({ + env: { + NTB_ANALYTICS_DSN: 'https://plausible.io/js/script.js', + }, + })); + vi.doMock('$app/environment', () => ({ + browser: false, + })); + + const { ANALYTICS_DSN } = await import('$lib/config/customizable-settings'); + expect(ANALYTICS_DSN).toBe('https://plausible.io/js/script.js'); + }); + + it('should accept "false" as a value to disable analytics', async () => { + vi.doMock('$env/dynamic/public', () => ({ + env: { + NTB_ANALYTICS_DSN: 'false', + }, + })); + vi.doMock('$app/environment', () => ({ + browser: false, + })); + + const { ANALYTICS_DSN } = await import('$lib/config/customizable-settings'); + expect(ANALYTICS_DSN).toBe('false'); + }); + }); + + describe('ANALYTICS_ENABLED', () => { + it('should be true when both domain and DSN use defaults', async () => { + vi.doMock('$env/dynamic/public', () => ({ + env: {}, + })); + vi.doMock('$app/environment', () => ({ + browser: false, + })); + + const { ANALYTICS_ENABLED } = await import('$lib/config/customizable-settings'); + expect(ANALYTICS_ENABLED).toBe(true); + }); + + it('should be true when both domain and DSN are custom values', async () => { + vi.doMock('$env/dynamic/public', () => ({ + env: { + NTB_ANALYTICS_DOMAIN: 'custom.example.com', + NTB_ANALYTICS_DSN: 'https://analytics.example.com/script.js', + }, + })); + vi.doMock('$app/environment', () => ({ + browser: false, + })); + + const { ANALYTICS_ENABLED } = await import('$lib/config/customizable-settings'); + expect(ANALYTICS_ENABLED).toBe(true); + }); + + it('should be false when domain is set to "false"', async () => { + vi.doMock('$env/dynamic/public', () => ({ + env: { + NTB_ANALYTICS_DOMAIN: 'false', + NTB_ANALYTICS_DSN: 'https://no-track.as93.net/js/script.js', + }, + })); + vi.doMock('$app/environment', () => ({ + browser: false, + })); + + const { ANALYTICS_ENABLED } = await import('$lib/config/customizable-settings'); + expect(ANALYTICS_ENABLED).toBe(false); + }); + + it('should be false when DSN is set to "false"', async () => { + vi.doMock('$env/dynamic/public', () => ({ + env: { + NTB_ANALYTICS_DOMAIN: 'networking-toolbox.as93.net', + NTB_ANALYTICS_DSN: 'false', + }, + })); + vi.doMock('$app/environment', () => ({ + browser: false, + })); + + const { ANALYTICS_ENABLED } = await import('$lib/config/customizable-settings'); + expect(ANALYTICS_ENABLED).toBe(false); + }); + + it('should be false when both domain and DSN are set to "false"', async () => { + vi.doMock('$env/dynamic/public', () => ({ + env: { + NTB_ANALYTICS_DOMAIN: 'false', + NTB_ANALYTICS_DSN: 'false', + }, + })); + vi.doMock('$app/environment', () => ({ + browser: false, + })); + + const { ANALYTICS_ENABLED } = await import('$lib/config/customizable-settings'); + expect(ANALYTICS_ENABLED).toBe(false); + }); + }); + + describe('getUserSettingsList - Analytics', () => { + it('should include analytics settings in the list', async () => { + const mockLocalStorage: Record = {}; + + global.localStorage = { + getItem: (key: string) => mockLocalStorage[key] || null, + setItem: (key: string, value: string) => { + mockLocalStorage[key] = value; + }, + removeItem: (key: string) => { + delete mockLocalStorage[key]; + }, + clear: () => { + Object.keys(mockLocalStorage).forEach((key) => delete mockLocalStorage[key]); + }, + length: Object.keys(mockLocalStorage).length, + key: (index: number) => Object.keys(mockLocalStorage)[index] || null, + } as Storage; + + vi.doMock('$env/dynamic/public', () => ({ + env: { + NTB_ANALYTICS_DOMAIN: 'test.example.com', + NTB_ANALYTICS_DSN: 'https://test.example.com/script.js', + }, + })); + vi.doMock('$app/environment', () => ({ + browser: true, + })); + + const { getUserSettingsList } = await import('$lib/config/customizable-settings'); + const settings = getUserSettingsList(); + + const analyticsDomain = settings.find((s) => s.name === 'NTB_ANALYTICS_DOMAIN'); + const analyticsDsn = settings.find((s) => s.name === 'NTB_ANALYTICS_DSN'); + + expect(analyticsDomain).toBeDefined(); + expect(analyticsDomain?.value).toBe('test.example.com'); + expect(analyticsDsn).toBeDefined(); + expect(analyticsDsn?.value).toBe('https://test.example.com/script.js'); + }); + + it('should return empty string when analytics env vars are not set', async () => { + const mockLocalStorage: Record = {}; + + global.localStorage = { + getItem: (key: string) => mockLocalStorage[key] || null, + setItem: (key: string, value: string) => { + mockLocalStorage[key] = value; + }, + removeItem: (key: string) => { + delete mockLocalStorage[key]; + }, + clear: () => { + Object.keys(mockLocalStorage).forEach((key) => delete mockLocalStorage[key]); + }, + length: Object.keys(mockLocalStorage).length, + key: (index: number) => Object.keys(mockLocalStorage)[index] || null, + } as Storage; + + vi.doMock('$env/dynamic/public', () => ({ + env: {}, + })); + vi.doMock('$app/environment', () => ({ + browser: true, + })); + + const { getUserSettingsList } = await import('$lib/config/customizable-settings'); + const settings = getUserSettingsList(); + + const analyticsDomain = settings.find((s) => s.name === 'NTB_ANALYTICS_DOMAIN'); + const analyticsDsn = settings.find((s) => s.name === 'NTB_ANALYTICS_DSN'); + + expect(analyticsDomain?.value).toBe(''); + expect(analyticsDsn?.value).toBe(''); + }); + }); + + describe('getUserCustomization - Error Handling', () => { + it('should return null when localStorage throws an error', async () => { + global.localStorage = { + getItem: () => { + throw new Error('localStorage error'); + }, + setItem: vi.fn(), + removeItem: vi.fn(), + clear: vi.fn(), + length: 0, + key: vi.fn(), + } as Storage; + + vi.doMock('$env/dynamic/public', () => ({ + env: { + NTB_SITE_TITLE: 'Test Site', + }, + })); + vi.doMock('$app/environment', () => ({ + browser: true, + })); + + // Re-import to trigger getUserCustomization with error + const { SITE_TITLE } = await import('$lib/config/customizable-settings'); + // Should fall back to env var when localStorage fails + expect(SITE_TITLE).toBe('Test Site'); + }); + + it('should handle invalid JSON in localStorage gracefully', async () => { + global.localStorage = { + getItem: () => 'invalid-json{', + setItem: vi.fn(), + removeItem: vi.fn(), + clear: vi.fn(), + length: 0, + key: vi.fn(), + } as Storage; + + vi.doMock('$env/dynamic/public', () => ({ + env: { + NTB_SITE_TITLE: 'Fallback Site', + }, + })); + vi.doMock('$app/environment', () => ({ + browser: true, + })); + + const { SITE_TITLE } = await import('$lib/config/customizable-settings'); + // Should fall back to env var when JSON parsing fails + expect(SITE_TITLE).toBe('Fallback Site'); + }); + }); + + describe('ALLOWED_DNS_SERVERS', () => { + it('should split and trim custom DNS servers from env var', async () => { + vi.doMock('$env/dynamic/public', () => ({ + env: { + NTB_ALLOWED_DNS_SERVERS: '8.8.8.8, 1.1.1.1 , 9.9.9.9', + }, + })); + vi.doMock('$app/environment', () => ({ + browser: false, + })); + + const { ALLOWED_DNS_SERVERS } = await import('$lib/config/customizable-settings'); + expect(ALLOWED_DNS_SERVERS).toEqual(['8.8.8.8', '1.1.1.1', '9.9.9.9']); + }); + }); + + describe('getUserSettingsList - Error Handling', () => { + it('should handle localStorage errors when getting individual values', async () => { + let callCount = 0; + global.localStorage = { + getItem: () => { + callCount++; + if (callCount > 2) { + throw new Error('localStorage error'); + } + return null; + }, + setItem: vi.fn(), + removeItem: vi.fn(), + clear: vi.fn(), + length: 0, + key: vi.fn(), + } as Storage; + + vi.doMock('$env/dynamic/public', () => ({ + env: {}, + })); + vi.doMock('$app/environment', () => ({ + browser: true, + })); + + const { getUserSettingsList } = await import('$lib/config/customizable-settings'); + const settings = getUserSettingsList(); + + // Should still return the settings list even if some localStorage calls fail + expect(settings).toBeDefined(); + expect(Array.isArray(settings)).toBe(true); + }); + }); +}); From baf980d0de7bb309fd2c0721ab050433c89b9964 Mon Sep 17 00:00:00 2001 From: Alicia Sykes Date: Sat, 15 Nov 2025 21:39:11 +0000 Subject: [PATCH 4/7] Adds codacy config, so that it can shut the fuck up about test duplication --- .codacy.yml | 96 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 .codacy.yml diff --git a/.codacy.yml b/.codacy.yml new file mode 100644 index 0000000..ed54cea --- /dev/null +++ b/.codacy.yml @@ -0,0 +1,96 @@ +--- +# Codacy Configuration File +# https://docs.codacy.com/repositories-configure/codacy-configuration-file/ + +comment: + enabled: false + +github_checks: + annotations: true + +file_extensions: + - ".ts" + - ".js" + - ".svelte" + - ".scss" + - ".css" + +duplication: + exclude_paths: + - "tests/**" + +engines: + eslint: + config_file: eslintrc.config.js + +# Exclude patterns - ignore test files and build artifacts from analysis +exclude_paths: + - "tests/**" + - "**/*.test.ts" + - "**/*.test.js" + - "**/*.spec.ts" + - "**/*.spec.js" + - ".svelte-kit/**" + - "build/**" + - "dist/**" + - "coverage/**" + - "playwright-report/**" + - "node_modules/**" + - "**/*.config.ts" + - "**/*.config.js" + - "**/*.d.ts" + - "static/**" + - ".github/**" + +# Language-specific engines configuration +engines: + # ESLint configuration (if you want to customize) + eslint: + enabled: true + exclude_paths: + - "tests/**" + + # TypeScript/TSLint + tslint: + enabled: true + exclude_paths: + - "tests/**" + +# Additional configuration +duplication: + enabled: true + exclude_paths: + - "tests/**" + +# Complexity and code style checks +metrics: + enabled: true + exclude_paths: + - "tests/**" + +# Coverage configuration +coverage: + # Enable coverage tracking + enabled: true + + # Exclude test files from coverage reports + exclude_paths: + - "tests/**" + - "**/*.test.ts" + - "**/*.spec.ts" + + # Coverage thresholds (optional but recommended) + status: + # Project-wide coverage threshold + project: + default: + enabled: true + target: 80% + threshold: 10% # Allow 5% decrease + + # Diff/patch coverage threshold (new code in PRs) + patch: + default: + enabled: true + target: 80% + threshold: 20% # Allow 10% decrease for patches From 92f46e0b3723d98e6db9dc93df4699f4451c099c Mon Sep 17 00:00:00 2001 From: Alicia Sykes Date: Sat, 15 Nov 2025 23:00:54 +0000 Subject: [PATCH 5/7] Fixes incorrect usable hosts for ipv4 subnet (#29) --- .../components/tools/NetworkVisualizer.svelte | 41 +++++++++---- src/lib/utils/ip-calculations.ts | 33 ++++++++++- .../subnetting/ipv4-subnet-calculator.test.ts | 6 +- tests/unit/utils/ip-calculations.test.ts | 59 +++++++++++++++++++ 4 files changed, 123 insertions(+), 16 deletions(-) diff --git a/src/lib/components/tools/NetworkVisualizer.svelte b/src/lib/components/tools/NetworkVisualizer.svelte index 1944c1b..0c13321 100644 --- a/src/lib/components/tools/NetworkVisualizer.svelte +++ b/src/lib/components/tools/NetworkVisualizer.svelte @@ -16,6 +16,7 @@ function generateNetworkBlocks() { const totalHosts = subnetInfo.hostCount; const _usableHosts = subnetInfo.usableHosts; + const cidr = subnetInfo.cidr; // For visualization, we'll show up to 256 blocks max const maxBlocks = 256; @@ -24,20 +25,40 @@ const blocks = []; - for (let i = 0; i < blocksToShow; i++) { - const isNetwork = i === 0; - const isBroadcast = i === blocksToShow - 1 && totalHosts > 2; - const _isUsable = !isNetwork && !isBroadcast; + // RFC 3021: /31 networks have no network/broadcast addresses + const is31Subnet = cidr === 31; + const is32Subnet = cidr === 32; - blocks.push({ - id: i, - type: isNetwork ? 'network' : isBroadcast ? 'broadcast' : 'usable', - represents: blockSize, - tooltip: isNetwork + for (let i = 0; i < blocksToShow; i++) { + let type: 'network' | 'broadcast' | 'usable'; + let tooltip: string; + + if (is31Subnet) { + // /31: Both IPs are usable hosts (point-to-point) + type = 'usable'; + tooltip = i === 0 ? 'Usable Host 1 (P2P)' : 'Usable Host 2 (P2P)'; + } else if (is32Subnet) { + // /32: Single host + type = 'usable'; + tooltip = 'Single Host'; + } else { + // Normal subnet: first is network, last is broadcast, rest are usable + const isNetwork = i === 0; + const isBroadcast = i === blocksToShow - 1 && totalHosts > 2; + + type = isNetwork ? 'network' : isBroadcast ? 'broadcast' : 'usable'; + tooltip = isNetwork ? 'Network Address' : isBroadcast ? 'Broadcast Address' - : `Usable Host${blockSize > 1 ? 's' : ''}`, + : `Usable Host${blockSize > 1 ? 's' : ''}`; + } + + blocks.push({ + id: i, + type, + represents: blockSize, + tooltip, }); } diff --git a/src/lib/utils/ip-calculations.ts b/src/lib/utils/ip-calculations.ts index ed092cb..f03abd2 100644 --- a/src/lib/utils/ip-calculations.ts +++ b/src/lib/utils/ip-calculations.ts @@ -73,10 +73,37 @@ export function calculateSubnet(ip: string, cidr: number): SubnetInfo { const hostBits = 32 - cidr; const hostCount = Math.pow(2, hostBits); - const usableHosts = hostCount > 2 ? hostCount - 2 : 0; - const firstHost = numberToIP(ipToNumber(network.octets.join('.')) + 1); - const lastHost = numberToIP(ipToNumber(broadcast.octets.join('.')) - 1); + // Calculate usable hosts based on CIDR + // RFC 3021: /31 has 2 usable hosts (point-to-point, no network/broadcast) + // /32 has 1 usable host (single host route) + // All others: total - 2 (excluding network and broadcast) + let usableHosts: number; + if (cidr === 32) { + usableHosts = 1; + } else if (cidr === 31) { + usableHosts = 2; // Both IPs are usable for point-to-point links + } else { + usableHosts = hostCount - 2; + } + + // Calculate first and last host based on CIDR + let firstHost: IPAddress; + let lastHost: IPAddress; + + if (cidr === 32) { + // Host route - first and last are the same + firstHost = network; + lastHost = network; + } else if (cidr === 31) { + // Point-to-point - use network and broadcast as hosts (RFC 3021) + firstHost = network; + lastHost = broadcast; + } else { + // Normal subnet - exclude network and broadcast + firstHost = numberToIP(ipToNumber(network.octets.join('.')) + 1); + lastHost = numberToIP(ipToNumber(broadcast.octets.join('.')) - 1); + } return { network, diff --git a/tests/unit/routes/subnetting/ipv4-subnet-calculator.test.ts b/tests/unit/routes/subnetting/ipv4-subnet-calculator.test.ts index a1615c4..6d4f419 100644 --- a/tests/unit/routes/subnetting/ipv4-subnet-calculator.test.ts +++ b/tests/unit/routes/subnetting/ipv4-subnet-calculator.test.ts @@ -51,10 +51,10 @@ describe('IPv4 Subnet Calculator Route Functionality', () => { expect(result.wildcardMask.octets).toEqual([0, 0, 0, 0]); expect(result.cidr).toBe(32); expect(result.hostCount).toBe(1); - expect(result.usableHosts).toBe(0); + expect(result.usableHosts).toBe(1); // Single host route }); - it('handles /31 point-to-point link correctly', () => { + it('handles /31 point-to-point link correctly (RFC 3021)', () => { const result = calculateSubnet('192.168.1.0', 31); expect(result.network.octets).toEqual([192, 168, 1, 0]); @@ -63,7 +63,7 @@ describe('IPv4 Subnet Calculator Route Functionality', () => { expect(result.wildcardMask.octets).toEqual([0, 0, 0, 1]); expect(result.cidr).toBe(31); expect(result.hostCount).toBe(2); - expect(result.usableHosts).toBe(0); // Traditional calculation: 2 hosts = 0 usable + expect(result.usableHosts).toBe(2); // RFC 3021: both IPs usable for point-to-point }); it('handles /28 network correctly', () => { diff --git a/tests/unit/utils/ip-calculations.test.ts b/tests/unit/utils/ip-calculations.test.ts index 4676b2d..6b40cdb 100644 --- a/tests/unit/utils/ip-calculations.test.ts +++ b/tests/unit/utils/ip-calculations.test.ts @@ -186,4 +186,63 @@ describe('IP calculations core logic', () => { }); }); }); + + describe('/31 point-to-point subnet (RFC 3021)', () => { + it('reports 2 usable hosts for /31 subnet', () => { + const subnet = calculateSubnetInfo('192.168.1.0', 31); + expect(subnet.usableHosts).toBe(2); + expect(subnet.hostCount).toBe(2); + }); + + it('uses network address as first usable host', () => { + const subnet = calculateSubnetInfo('10.0.0.0', 31); + expect(subnet.firstHost.octets).toEqual([10, 0, 0, 0]); + }); + + it('uses broadcast address as second usable host', () => { + const subnet = calculateSubnetInfo('10.0.0.0', 31); + expect(subnet.lastHost.octets).toEqual([10, 0, 0, 1]); + }); + + it('calculates correct network and broadcast for /31', () => { + const subnet = calculateSubnetInfo('172.16.0.10', 31); + // Network should be even address + expect(subnet.network.octets).toEqual([172, 16, 0, 10]); + // Broadcast should be odd address (network + 1) + expect(subnet.broadcast.octets).toEqual([172, 16, 0, 11]); + }); + + it('handles multiple /31 subnets in same range', () => { + const subnet1 = calculateSubnetInfo('192.168.1.0', 31); + const subnet2 = calculateSubnetInfo('192.168.1.2', 31); + const subnet3 = calculateSubnetInfo('192.168.1.4', 31); + + // First /31: .0 and .1 + expect(subnet1.firstHost.octets[3]).toBe(0); + expect(subnet1.lastHost.octets[3]).toBe(1); + + // Second /31: .2 and .3 + expect(subnet2.firstHost.octets[3]).toBe(2); + expect(subnet2.lastHost.octets[3]).toBe(3); + + // Third /31: .4 and .5 + expect(subnet3.firstHost.octets[3]).toBe(4); + expect(subnet3.lastHost.octets[3]).toBe(5); + }); + + it('reports 100% address utilization for /31', () => { + const subnet = calculateSubnetInfo('192.168.1.0', 31); + const utilization = (subnet.usableHosts / subnet.hostCount) * 100; + expect(utilization).toBe(100); + }); + + it('correctly identifies both IPs as usable in /31', () => { + const subnet = calculateSubnetInfo('203.0.113.0', 31); + + // Both the network and broadcast addresses are usable + expect(subnet.firstHost.octets).toEqual(subnet.network.octets); + expect(subnet.lastHost.octets).toEqual(subnet.broadcast.octets); + expect(subnet.usableHosts).toBe(2); + }); + }); }); \ No newline at end of file From 1903456172bd0b9c7d1f05b54dbc2f632e50abdd Mon Sep 17 00:00:00 2001 From: Alicia Sykes Date: Sat, 15 Nov 2025 23:09:02 +0000 Subject: [PATCH 6/7] Refactos IPv4 /31,32 fix and improves logic --- .../components/tools/NetworkVisualizer.svelte | 75 ++++++++----------- src/lib/utils/ip-calculations.ts | 26 ++----- tests/unit/utils/ip-calculations.test.ts | 2 +- 3 files changed, 38 insertions(+), 65 deletions(-) diff --git a/src/lib/components/tools/NetworkVisualizer.svelte b/src/lib/components/tools/NetworkVisualizer.svelte index 0c13321..bac7417 100644 --- a/src/lib/components/tools/NetworkVisualizer.svelte +++ b/src/lib/components/tools/NetworkVisualizer.svelte @@ -14,55 +14,44 @@ * Generates visual representation of network range */ function generateNetworkBlocks() { - const totalHosts = subnetInfo.hostCount; - const _usableHosts = subnetInfo.usableHosts; - const cidr = subnetInfo.cidr; - - // For visualization, we'll show up to 256 blocks max + const { hostCount, cidr } = subnetInfo; const maxBlocks = 256; - const blocksToShow = Math.min(totalHosts, maxBlocks); - const blockSize = totalHosts > maxBlocks ? Math.ceil(totalHosts / maxBlocks) : 1; + const blocksToShow = Math.min(hostCount, maxBlocks); + const blockSize = hostCount > maxBlocks ? Math.ceil(hostCount / maxBlocks) : 1; - const blocks = []; + return Array.from({ length: blocksToShow }, (_, i) => { + const isFirst = i === 0; + const isLast = i === blocksToShow - 1; - // RFC 3021: /31 networks have no network/broadcast addresses - const is31Subnet = cidr === 31; - const is32Subnet = cidr === 32; - - for (let i = 0; i < blocksToShow; i++) { - let type: 'network' | 'broadcast' | 'usable'; - let tooltip: string; - - if (is31Subnet) { - // /31: Both IPs are usable hosts (point-to-point) - type = 'usable'; - tooltip = i === 0 ? 'Usable Host 1 (P2P)' : 'Usable Host 2 (P2P)'; - } else if (is32Subnet) { - // /32: Single host - type = 'usable'; - tooltip = 'Single Host'; - } else { - // Normal subnet: first is network, last is broadcast, rest are usable - const isNetwork = i === 0; - const isBroadcast = i === blocksToShow - 1 && totalHosts > 2; - - type = isNetwork ? 'network' : isBroadcast ? 'broadcast' : 'usable'; - tooltip = isNetwork - ? 'Network Address' - : isBroadcast - ? 'Broadcast Address' - : `Usable Host${blockSize > 1 ? 's' : ''}`; + // RFC 3021: /31 and /32 have all IPs usable + if (cidr === 31) { + return { + id: i, + type: 'usable' as const, + represents: blockSize, + tooltip: isFirst ? 'Usable Host 1 (P2P)' : 'Usable Host 2 (P2P)', + }; } - blocks.push({ - id: i, - type, - represents: blockSize, - tooltip, - }); - } + if (cidr === 32) { + return { + id: i, + type: 'usable' as const, + represents: blockSize, + tooltip: 'Single Host', + }; + } - return blocks; + // Normal subnets have network/broadcast reserved + const type = isFirst ? 'network' : isLast && hostCount > 2 ? 'broadcast' : 'usable'; + const tooltip = isFirst + ? 'Network Address' + : isLast && hostCount > 2 + ? 'Broadcast Address' + : `Usable Host${blockSize > 1 ? 's' : ''}`; + + return { id: i, type, represents: blockSize, tooltip }; + }); } let networkBlocks = $derived(generateNetworkBlocks()); diff --git a/src/lib/utils/ip-calculations.ts b/src/lib/utils/ip-calculations.ts index f03abd2..80cc6d5 100644 --- a/src/lib/utils/ip-calculations.ts +++ b/src/lib/utils/ip-calculations.ts @@ -74,33 +74,17 @@ export function calculateSubnet(ip: string, cidr: number): SubnetInfo { const hostBits = 32 - cidr; const hostCount = Math.pow(2, hostBits); - // Calculate usable hosts based on CIDR - // RFC 3021: /31 has 2 usable hosts (point-to-point, no network/broadcast) - // /32 has 1 usable host (single host route) - // All others: total - 2 (excluding network and broadcast) - let usableHosts: number; - if (cidr === 32) { - usableHosts = 1; - } else if (cidr === 31) { - usableHosts = 2; // Both IPs are usable for point-to-point links - } else { - usableHosts = hostCount - 2; - } + // RFC 3021: /31 point-to-point has both IPs usable, /32 is single host + const usableHosts = cidr === 32 ? 1 : cidr === 31 ? 2 : hostCount - 2; - // Calculate first and last host based on CIDR + // For /31 and /32, all IPs are usable (no reserved network/broadcast) let firstHost: IPAddress; let lastHost: IPAddress; - if (cidr === 32) { - // Host route - first and last are the same + if (cidr >= 31) { firstHost = network; - lastHost = network; - } else if (cidr === 31) { - // Point-to-point - use network and broadcast as hosts (RFC 3021) - firstHost = network; - lastHost = broadcast; + lastHost = cidr === 32 ? network : broadcast; } else { - // Normal subnet - exclude network and broadcast firstHost = numberToIP(ipToNumber(network.octets.join('.')) + 1); lastHost = numberToIP(ipToNumber(broadcast.octets.join('.')) - 1); } diff --git a/tests/unit/utils/ip-calculations.test.ts b/tests/unit/utils/ip-calculations.test.ts index 6b40cdb..584f235 100644 --- a/tests/unit/utils/ip-calculations.test.ts +++ b/tests/unit/utils/ip-calculations.test.ts @@ -245,4 +245,4 @@ describe('IP calculations core logic', () => { expect(subnet.usableHosts).toBe(2); }); }); -}); \ No newline at end of file +}); From e9a3ab7b1cafdc9325afe50af6e072e99e567dea Mon Sep 17 00:00:00 2001 From: Alicia Sykes Date: Sat, 15 Nov 2025 23:17:35 +0000 Subject: [PATCH 7/7] Resolves failing API contract tests for IPv4 subnet calc class 31 --- tests/api/internal-endpoints/ct-log-search.test.ts | 4 ++-- tests/api/subnetting.test.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/api/internal-endpoints/ct-log-search.test.ts b/tests/api/internal-endpoints/ct-log-search.test.ts index bb14253..5f7fab1 100644 --- a/tests/api/internal-endpoints/ct-log-search.test.ts +++ b/tests/api/internal-endpoints/ct-log-search.test.ts @@ -33,7 +33,7 @@ describe('CT Log Search API', () => { expect(data.expiringSoon).toBeGreaterThanOrEqual(0); expect(data.wildcardCertificates).toBeGreaterThanOrEqual(0); expect(data.timestamp).toBeDefined(); - }); + }, 60000); // Increase timeout to 60s for slow external API it('should include required certificate fields', async () => { const { status, data } = await makeRequest('example.com'); @@ -123,6 +123,6 @@ describe('CT Log Search API', () => { expect(data.totalCertificates).toBe(0); expect(data.certificates).toHaveLength(0); expect(data.discoveredHostnames).toHaveLength(0); - }); + }, 60000); // Increase timeout to 60s for slow external API }); }); diff --git a/tests/api/subnetting.test.ts b/tests/api/subnetting.test.ts index 1fc44cf..7078ad6 100644 --- a/tests/api/subnetting.test.ts +++ b/tests/api/subnetting.test.ts @@ -72,7 +72,7 @@ describe('Subnetting API Endpoints', () => { expect(ipObjectToString(result.broadcast)).toBe('192.168.1.1'); expect(ipObjectToString(result.subnet)).toBe('255.255.255.255'); expect(result.hostCount).toBe(1); - expect(result.usableHosts).toBe(0); + expect(result.usableHosts).toBe(1); // RFC 3021: /32 is a single usable host }); it('should handle invalid CIDR format', async () => {