fix(documentation): Improve documentation formatting and code consistency across project files

This commit is contained in:
2025-05-26 12:57:15 +00:00
parent 393f479b4e
commit 5593c3932a
7 changed files with 228 additions and 73 deletions

View File

@@ -1,5 +1,13 @@
# Changelog # Changelog
## 2025-05-26 - 2.1.2 - fix(documentation)
Improve documentation formatting and code consistency across project files
- Refined readme.md: replaced CI status badges with streamlined installation and usage instructions
- Updated code formatting and whitespace in detector classes and interfaces for clarity
- Enhanced test file formatting and adjusted options to improve test readability
- Minor improvements in commit info data structure
## 2025-05-26 - 2.1.1 - fix(detector) ## 2025-05-26 - 2.1.1 - fix(detector)
Improve test coverage and adjust detection result handling Improve test coverage and adjust detection result handling

View File

@@ -52,4 +52,4 @@
"pnpm": { "pnpm": {
"overrides": {} "overrides": {}
} }
} }

165
readme.md
View File

@@ -9,26 +9,163 @@ a detector for answering network questions locally. It does not rely on any onli
- [github.com (source mirror)](https://github.com/uptime.link/detector) - [github.com (source mirror)](https://github.com/uptime.link/detector)
- [docs (typedoc)](https://uptime.link.gitlab.io/detector/) - [docs (typedoc)](https://uptime.link.gitlab.io/detector/)
## Status for master ## Installation
| Status Category | Status Badge | ```bash
| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | npm install @uptime.link/detector
| GitLab Pipelines | [![pipeline status](https://gitlab.com/uptime.link/detector/badges/master/pipeline.svg)](https://lossless.cloud) | ```
| GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/uptime.link/detector/badges/master/coverage.svg)](https://lossless.cloud) |
| npm | [![npm downloads per month](https://badgen.net/npm/dy/@uptime.link/detector)](https://lossless.cloud) |
| Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/uptime.link/detector)](https://lossless.cloud) |
| TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud) |
| node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/) |
| Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud) |
| PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@uptime.link/detector)](https://lossless.cloud) |
| PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@uptime.link/detector)](https://lossless.cloud) |
| BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@uptime.link/detector)](https://lossless.cloud) |
| Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud) |
## Usage ## Usage
Use TypeScript for best in class intellisense Use TypeScript for best in class intellisense
### Basic Port Detection
```typescript
import { Detector } from '@uptime.link/detector';
const detector = new Detector();
// Check if a port is active (returns detailed result)
const result = await detector.isActive('https://example.com');
console.log(result.isActive); // true
// Simple boolean check (backward compatible)
const isActive = await detector.isActiveSimple('https://example.com');
console.log(isActive); // true
```
### Service Type Detection
The detector can identify what service is running on a port:
```typescript
// Detect service type along with port check
const result = await detector.isActive('https://github.com', {
detectServiceType: true,
});
console.log(result.isActive); // true
console.log(result.serviceType); // 'https'
// Direct service type detection
const serviceType = await detector.detectType('ssh://github.com:22');
console.log(serviceType); // 'ssh'
```
### Supported Service Types
The detector can identify the following services:
- **HTTP** (port 80)
- **HTTPS** (port 443)
- **SSH** (port 22)
- **FTP** (port 21)
- **SMTP** (port 25)
- **POP3** (port 110)
- **IMAP** (port 143)
- **MySQL** (port 3306)
- **PostgreSQL** (port 5432)
- **MongoDB** (port 27017)
- **Redis** (port 6379)
- **Unknown** (for unidentified services)
### Advanced Examples
```typescript
// Check localhost ports
const localResult = await detector.isActive('http://localhost:3000', {
detectServiceType: true,
});
if (localResult.isActive) {
console.log(`Local service detected: ${localResult.serviceType}`);
}
// Check multiple services
const urls = ['https://api.github.com', 'http://example.com', 'ssh://gitlab.com:22'];
for (const url of urls) {
const result = await detector.isActive(url, { detectServiceType: true });
console.log(`${url}: ${result.isActive ? result.serviceType : 'offline'}`);
}
// Handle different URL schemes with automatic port detection
const sshDetection = await detector.detectType('ssh://github.com');
// Automatically uses port 22 for SSH
const mysqlDetection = await detector.detectType('mysql://localhost');
// Automatically uses port 3306 for MySQL
```
### API Reference
#### `Detector`
The main class for network detection.
##### Methods
- **`isActive(url: string, options?: IDetectorOptions): Promise<IDetectorResult>`**
- Checks if a port is active and optionally detects the service type
- Returns detailed information about the port status and service
- **`isActiveSimple(url: string): Promise<boolean>`**
- Simple boolean check for backward compatibility
- Returns `true` if port is active, `false` otherwise
- **`detectType(url: string): Promise<ServiceType>`**
- Detects the service type running on the specified URL
- Uses protocol-specific detection methods and banner grabbing
#### Interfaces
```typescript
interface IDetectorResult {
isActive: boolean;
serviceType?: ServiceType;
protocol?: 'tcp' | 'udp';
responseTime?: number;
tlsVersion?: string;
serviceBanner?: string;
error?: string;
}
interface IDetectorOptions {
timeout?: number;
includeNetworkDiagnostics?: boolean;
detectServiceType?: boolean;
}
enum ServiceType {
HTTP = 'http',
HTTPS = 'https',
SSH = 'ssh',
FTP = 'ftp',
SMTP = 'smtp',
POP3 = 'pop3',
IMAP = 'imap',
MYSQL = 'mysql',
POSTGRESQL = 'postgresql',
MONGODB = 'mongodb',
REDIS = 'redis',
UNKNOWN = 'unknown',
}
```
## Features
-**Local Network Detection** - Check ports on localhost without external services
-**Remote Port Detection** - Verify if remote ports are accessible
-**Service Identification** - Detect what service is running on a port
-**Protocol Detection** - Identify HTTP/HTTPS and other protocols
-**Banner Grabbing** - Extract service information from response banners
-**TypeScript Support** - Full type definitions included
-**ESM Module** - Modern ES module support
-**No External Dependencies** - All detection happens locally
## Contribution ## Contribution
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :) We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)

View File

@@ -51,7 +51,9 @@ tap.test('should detect SSH service on GitHub', async () => {
}); });
tap.test('should detect HTTPS on non-standard port', async () => { tap.test('should detect HTTPS on non-standard port', async () => {
const result = await testDetector.isActive('https://lossless.com:443', { detectServiceType: true }); const result = await testDetector.isActive('https://lossless.com:443', {
detectServiceType: true,
});
if (result.isActive) { if (result.isActive) {
expect(result.serviceType).toEqual(detector.ServiceType.HTTPS); expect(result.serviceType).toEqual(detector.ServiceType.HTTPS);
} }
@@ -146,4 +148,4 @@ tap.test('should detect commonly used local development ports', async () => {
} }
}); });
export default tap.start(); export default tap.start();

View File

@@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@uptime.link/detector', name: '@uptime.link/detector',
version: '2.1.1', version: '2.1.2',
description: 'a detector for answering network questions locally. It does not rely on any online services.' description: 'a detector for answering network questions locally. It does not rely on any online services.'
} }

View File

@@ -24,11 +24,11 @@ export class Detector {
parseInt(parsedUrl.port, 10), parseInt(parsedUrl.port, 10),
); );
const portAvailable = !portUnused; const portAvailable = !portUnused;
const result: IDetectorResult = { const result: IDetectorResult = {
isActive: portAvailable isActive: portAvailable,
}; };
if (options?.detectServiceType) { if (options?.detectServiceType) {
if (portAvailable) { if (portAvailable) {
const serviceType = await this.detectType(urlArg); const serviceType = await this.detectType(urlArg);
@@ -37,7 +37,7 @@ export class Detector {
result.serviceType = ServiceType.UNKNOWN; result.serviceType = ServiceType.UNKNOWN;
} }
} }
return result; return result;
} else { } else {
console.log(`detector target is remote domain ${parsedUrl.host} on port ${parsedUrl.port}`); console.log(`detector target is remote domain ${parsedUrl.host} on port ${parsedUrl.port}`);
@@ -45,11 +45,11 @@ export class Detector {
parsedUrl.host, parsedUrl.host,
parseInt(parsedUrl.port, 10), parseInt(parsedUrl.port, 10),
); );
const result: IDetectorResult = { const result: IDetectorResult = {
isActive: portAvailable isActive: portAvailable,
}; };
if (options?.detectServiceType) { if (options?.detectServiceType) {
if (portAvailable) { if (portAvailable) {
const serviceType = await this.detectType(urlArg); const serviceType = await this.detectType(urlArg);
@@ -58,36 +58,36 @@ export class Detector {
result.serviceType = ServiceType.UNKNOWN; result.serviceType = ServiceType.UNKNOWN;
} }
} }
return result; return result;
} }
} }
public async detectType(urlArg: string): Promise<ServiceType> { public async detectType(urlArg: string): Promise<ServiceType> {
const parsedUrl = plugins.smarturl.Smarturl.createFromUrl(urlArg); const parsedUrl = plugins.smarturl.Smarturl.createFromUrl(urlArg);
// Handle different URL schemes and default ports // Handle different URL schemes and default ports
let port = parseInt(parsedUrl.port, 10); let port = parseInt(parsedUrl.port, 10);
if (isNaN(port)) { if (isNaN(port)) {
// Set default ports based on scheme // Set default ports based on scheme
const defaultPorts: { [key: string]: number } = { const defaultPorts: { [key: string]: number } = {
'http': 80, http: 80,
'https': 443, https: 443,
'ssh': 22, ssh: 22,
'ftp': 21, ftp: 21,
'smtp': 25, smtp: 25,
'mysql': 3306, mysql: 3306,
'postgresql': 5432, postgresql: 5432,
'mongodb': 27017, mongodb: 27017,
'redis': 6379 redis: 6379,
}; };
const scheme = parsedUrl.protocol.replace(':', '').toLowerCase(); const scheme = parsedUrl.protocol.replace(':', '').toLowerCase();
port = defaultPorts[scheme] || 80; port = defaultPorts[scheme] || 80;
} }
const hostname = parsedUrl.hostname; const hostname = parsedUrl.hostname;
// Check common ports first // Check common ports first
const commonPorts: { [key: number]: ServiceType } = { const commonPorts: { [key: number]: ServiceType } = {
80: ServiceType.HTTP, 80: ServiceType.HTTP,
@@ -100,9 +100,9 @@ export class Detector {
3306: ServiceType.MYSQL, 3306: ServiceType.MYSQL,
5432: ServiceType.POSTGRESQL, 5432: ServiceType.POSTGRESQL,
27017: ServiceType.MONGODB, 27017: ServiceType.MONGODB,
6379: ServiceType.REDIS 6379: ServiceType.REDIS,
}; };
if (commonPorts[port]) { if (commonPorts[port]) {
// Verify the service is actually what we expect // Verify the service is actually what we expect
const verified = await this.verifyServiceType(hostname, port, commonPorts[port]); const verified = await this.verifyServiceType(hostname, port, commonPorts[port]);
@@ -110,12 +110,16 @@ export class Detector {
return commonPorts[port]; return commonPorts[port];
} }
} }
// Try to detect service by banner/protocol // Try to detect service by banner/protocol
return await this.detectServiceByProtocol(hostname, port); return await this.detectServiceByProtocol(hostname, port);
} }
private async verifyServiceType(hostname: string, port: number, expectedType: ServiceType): Promise<boolean> { private async verifyServiceType(
hostname: string,
port: number,
expectedType: ServiceType,
): Promise<boolean> {
try { try {
switch (expectedType) { switch (expectedType) {
case ServiceType.HTTP: case ServiceType.HTTP:
@@ -130,33 +134,37 @@ export class Detector {
return false; return false;
} }
} }
private async detectServiceByProtocol(hostname: string, port: number): Promise<ServiceType> { private async detectServiceByProtocol(hostname: string, port: number): Promise<ServiceType> {
// Try HTTPS first // Try HTTPS first
if (await this.checkHttpService(hostname, port, true)) { if (await this.checkHttpService(hostname, port, true)) {
return ServiceType.HTTPS; return ServiceType.HTTPS;
} }
// Try HTTP // Try HTTP
if (await this.checkHttpService(hostname, port, false)) { if (await this.checkHttpService(hostname, port, false)) {
return ServiceType.HTTP; return ServiceType.HTTP;
} }
// Try SSH // Try SSH
if (await this.checkSshService(hostname, port)) { if (await this.checkSshService(hostname, port)) {
return ServiceType.SSH; return ServiceType.SSH;
} }
// Try to get banner for other services // Try to get banner for other services
const banner = await this.getBanner(hostname, port); const banner = await this.getBanner(hostname, port);
if (banner) { if (banner) {
return this.identifyServiceByBanner(banner); return this.identifyServiceByBanner(banner);
} }
return ServiceType.UNKNOWN; return ServiceType.UNKNOWN;
} }
private async checkHttpService(hostname: string, port: number, isHttps: boolean): Promise<boolean> { private async checkHttpService(
hostname: string,
port: number,
isHttps: boolean,
): Promise<boolean> {
return new Promise((resolve) => { return new Promise((resolve) => {
const protocol = isHttps ? plugins.https : plugins.http; const protocol = isHttps ? plugins.https : plugins.http;
const options = { const options = {
@@ -164,81 +172,81 @@ export class Detector {
port, port,
method: 'HEAD', method: 'HEAD',
timeout: 5000, timeout: 5000,
rejectUnauthorized: false // Accept self-signed certificates rejectUnauthorized: false, // Accept self-signed certificates
}; };
const req = protocol.request(options, () => { const req = protocol.request(options, () => {
resolve(true); resolve(true);
}); });
req.on('error', () => { req.on('error', () => {
resolve(false); resolve(false);
}); });
req.on('timeout', () => { req.on('timeout', () => {
req.destroy(); req.destroy();
resolve(false); resolve(false);
}); });
req.end(); req.end();
}); });
} }
private async checkSshService(hostname: string, port: number): Promise<boolean> { private async checkSshService(hostname: string, port: number): Promise<boolean> {
return new Promise((resolve) => { return new Promise((resolve) => {
const socket = new plugins.net.Socket(); const socket = new plugins.net.Socket();
socket.setTimeout(5000); socket.setTimeout(5000);
socket.on('data', (data) => { socket.on('data', (data) => {
const banner = data.toString(); const banner = data.toString();
socket.destroy(); socket.destroy();
// SSH banners typically start with "SSH-" // SSH banners typically start with "SSH-"
resolve(banner.startsWith('SSH-')); resolve(banner.startsWith('SSH-'));
}); });
socket.on('error', () => { socket.on('error', () => {
resolve(false); resolve(false);
}); });
socket.on('timeout', () => { socket.on('timeout', () => {
socket.destroy(); socket.destroy();
resolve(false); resolve(false);
}); });
socket.connect(port, hostname); socket.connect(port, hostname);
}); });
} }
private async getBanner(hostname: string, port: number): Promise<string | null> { private async getBanner(hostname: string, port: number): Promise<string | null> {
return new Promise((resolve) => { return new Promise((resolve) => {
const socket = new plugins.net.Socket(); const socket = new plugins.net.Socket();
let banner = ''; let banner = '';
socket.setTimeout(5000); socket.setTimeout(5000);
socket.on('data', (data) => { socket.on('data', (data) => {
banner += data.toString(); banner += data.toString();
socket.destroy(); socket.destroy();
resolve(banner); resolve(banner);
}); });
socket.on('error', () => { socket.on('error', () => {
resolve(null); resolve(null);
}); });
socket.on('timeout', () => { socket.on('timeout', () => {
socket.destroy(); socket.destroy();
resolve(banner || null); resolve(banner || null);
}); });
socket.connect(port, hostname); socket.connect(port, hostname);
}); });
} }
private identifyServiceByBanner(banner: string): ServiceType { private identifyServiceByBanner(banner: string): ServiceType {
const bannerLower = banner.toLowerCase(); const bannerLower = banner.toLowerCase();
if (bannerLower.includes('ssh')) return ServiceType.SSH; if (bannerLower.includes('ssh')) return ServiceType.SSH;
if (bannerLower.includes('ftp')) return ServiceType.FTP; if (bannerLower.includes('ftp')) return ServiceType.FTP;
if (bannerLower.includes('smtp')) return ServiceType.SMTP; if (bannerLower.includes('smtp')) return ServiceType.SMTP;
@@ -248,7 +256,7 @@ export class Detector {
if (bannerLower.includes('postgresql')) return ServiceType.POSTGRESQL; if (bannerLower.includes('postgresql')) return ServiceType.POSTGRESQL;
if (bannerLower.includes('mongodb')) return ServiceType.MONGODB; if (bannerLower.includes('mongodb')) return ServiceType.MONGODB;
if (bannerLower.includes('redis')) return ServiceType.REDIS; if (bannerLower.includes('redis')) return ServiceType.REDIS;
return ServiceType.UNKNOWN; return ServiceType.UNKNOWN;
} }
} }

View File

@@ -10,7 +10,7 @@ export enum ServiceType {
POSTGRESQL = 'postgresql', POSTGRESQL = 'postgresql',
MONGODB = 'mongodb', MONGODB = 'mongodb',
REDIS = 'redis', REDIS = 'redis',
UNKNOWN = 'unknown' UNKNOWN = 'unknown',
} }
export interface IDetectorResult { export interface IDetectorResult {
@@ -41,4 +41,4 @@ export interface IDetectorOptions {
timeout?: number; timeout?: number;
includeNetworkDiagnostics?: boolean; includeNetworkDiagnostics?: boolean;
detectServiceType?: boolean; detectServiceType?: boolean;
} }