ssrf-agent-guard 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -49,7 +49,7 @@ function isSafeHost(hostname, isValidDomainOptions) {
49
49
  // Case 2: Domain name
50
50
  return isValidDomain(hostname, {
51
51
  allowUnicode: false,
52
- subdomain: false,
52
+ subdomain: true,
53
53
  ...isValidDomainOptions,
54
54
  });
55
55
  }
@@ -80,7 +80,7 @@ const CREATE_CONNECTION = Symbol('createConnection');
80
80
  * @param isValidDomainOptions Options for validating domain names.
81
81
  * @returns The patched CustomAgent instance.
82
82
  */
83
- function index (url, isValidDomainOptions) {
83
+ const ssrfAgentGuard = function (url, isValidDomainOptions) {
84
84
  const finalAgent = getAgent(url);
85
85
  // Prevent patching the agent multiple times
86
86
  if (finalAgent[CREATE_CONNECTION]) {
@@ -111,7 +111,7 @@ function index (url, isValidDomainOptions) {
111
111
  }
112
112
  // Ensure resolvedAddress is a string for the check (it's typically a string for simple lookups)
113
113
  const ipToCheck = Array.isArray(resolvedAddress) ? resolvedAddress[0] : resolvedAddress;
114
- if (!isSafeIp(ipToCheck)) {
114
+ if (!isSafeHost(ipToCheck)) {
115
115
  // If the resolved IP is NOT allowed (e.g., a private IP), destroy the connection.
116
116
  return client?.destroy(new Error(`DNS lookup ${ipToCheck} is not allowed.`));
117
117
  }
@@ -119,6 +119,7 @@ function index (url, isValidDomainOptions) {
119
119
  return client;
120
120
  };
121
121
  return finalAgent;
122
- }
122
+ };
123
+ module.exports = ssrfAgentGuard;
123
124
 
124
- exports.default = index;
125
+ exports.default = ssrfAgentGuard;
package/dist/index.esm.js CHANGED
@@ -45,7 +45,7 @@ function isSafeHost(hostname, isValidDomainOptions) {
45
45
  // Case 2: Domain name
46
46
  return isValidDomain(hostname, {
47
47
  allowUnicode: false,
48
- subdomain: false,
48
+ subdomain: true,
49
49
  ...isValidDomainOptions,
50
50
  });
51
51
  }
@@ -76,7 +76,7 @@ const CREATE_CONNECTION = Symbol('createConnection');
76
76
  * @param isValidDomainOptions Options for validating domain names.
77
77
  * @returns The patched CustomAgent instance.
78
78
  */
79
- function index (url, isValidDomainOptions) {
79
+ const ssrfAgentGuard = function (url, isValidDomainOptions) {
80
80
  const finalAgent = getAgent(url);
81
81
  // Prevent patching the agent multiple times
82
82
  if (finalAgent[CREATE_CONNECTION]) {
@@ -107,7 +107,7 @@ function index (url, isValidDomainOptions) {
107
107
  }
108
108
  // Ensure resolvedAddress is a string for the check (it's typically a string for simple lookups)
109
109
  const ipToCheck = Array.isArray(resolvedAddress) ? resolvedAddress[0] : resolvedAddress;
110
- if (!isSafeIp(ipToCheck)) {
110
+ if (!isSafeHost(ipToCheck)) {
111
111
  // If the resolved IP is NOT allowed (e.g., a private IP), destroy the connection.
112
112
  return client?.destroy(new Error(`DNS lookup ${ipToCheck} is not allowed.`));
113
113
  }
@@ -115,6 +115,7 @@ function index (url, isValidDomainOptions) {
115
115
  return client;
116
116
  };
117
117
  return finalAgent;
118
- }
118
+ };
119
+ module.exports = ssrfAgentGuard;
119
120
 
120
- export { index as default };
121
+ export { ssrfAgentGuard as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssrf-agent-guard",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "A TypeScript SSRF protection library for Node.js (express/axios) with advanced policies, DNS rebinding detection and cloud metadata protection.",
5
5
  "main": "dist/index.cjs.js",
6
6
  "module": "dist/index.esm.js",
package/.eslintrc.js DELETED
@@ -1,27 +0,0 @@
1
- module.exports = {
2
- root: true,
3
- parser: '@typescript-eslint/parser',
4
- parserOptions: {
5
- ecmaVersion: 2020,
6
- sourceType: 'module',
7
- },
8
- env: {
9
- node: true,
10
- es2020: true,
11
- jest: true,
12
- },
13
- extends: [
14
- 'eslint:recommended',
15
- 'plugin:@typescript-eslint/recommended', // TypeScript rules
16
- 'plugin:prettier/recommended' // Integrate Prettier
17
- ],
18
- plugins: ['@typescript-eslint', 'prettier'],
19
- rules: {
20
- 'prettier/prettier': 'error', // Show prettier errors as ESLint errors
21
- '@typescript-eslint/explicit-function-return-type': 'off',
22
- '@typescript-eslint/no-explicit-any': 'off',
23
- '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
24
- 'no-console': 'warn',
25
- 'prefer-const': 'error',
26
- },
27
- };
package/.prettierrc DELETED
@@ -1,8 +0,0 @@
1
- {
2
- "semi": true,
3
- "singleQuote": true,
4
- "trailingComma": "all",
5
- "printWidth": 100,
6
- "tabWidth": 4,
7
- "endOfLine": "lf"
8
- }
package/index.ts DELETED
@@ -1,92 +0,0 @@
1
- import { Agent as HttpAgent, AgentOptions as HttpAgentOptions } from 'http';
2
- import { Agent as HttpsAgent, AgentOptions as HttpsAgentOptions } from 'https';
3
- import { Duplex } from 'stream';
4
-
5
- import { isSafeHost, isSafeIp } from './lib/utils';
6
- import { IsValidDomainOptions } from './lib/types';
7
-
8
- // Define the type for the Agent that this module will modify and return.
9
- // It can be either an HttpAgent or an HttpsAgent.
10
- type CustomAgent = HttpAgent | HttpsAgent;
11
-
12
- // Instantiate the default agents
13
- const httpAgent = new HttpAgent();
14
- const httpsAgent = new HttpsAgent();
15
-
16
- /**
17
- * Determines the correct Agent instance based on the input.
18
- * @param url The URL or another input to determine the agent type.
19
- * @returns The appropriate HttpAgent or HttpsAgent instance.
20
- */
21
- const getAgent = (url: string): CustomAgent => {
22
- // If it's a string, check if it implies HTTPS
23
- if (typeof url === 'string' && url.startsWith('https')) {
24
- return httpsAgent;
25
- }
26
- // Default to HTTP agent
27
- return httpAgent;
28
- };
29
-
30
- // Define a Symbol for a unique property to prevent double-patching the agent.
31
- const CREATE_CONNECTION = Symbol('createConnection');
32
-
33
- /**
34
- * Patches an http.Agent or https.Agent to enforce an HOST/IP check
35
- * before and after a DNS lookup.
36
- *
37
- * @param url The URL or another input to determine the agent type.
38
- * @param isValidDomainOptions Options for validating domain names.
39
- * @returns The patched CustomAgent instance.
40
- */
41
- export default function (url: string, isValidDomainOptions?: IsValidDomainOptions): CustomAgent {
42
- const finalAgent = getAgent(url);
43
-
44
- // Prevent patching the agent multiple times
45
- if ((finalAgent as any)[CREATE_CONNECTION]) {
46
- return finalAgent;
47
- }
48
- (finalAgent as any)[CREATE_CONNECTION] = true;
49
-
50
- // The original createConnection function from the Agent
51
- const createConnection = finalAgent.createConnection;
52
-
53
- // Patch the createConnection method on the agent
54
- finalAgent.createConnection = (
55
- options: HttpAgentOptions | HttpsAgentOptions,
56
- fn?: (err: Error | null, stream: Duplex) => void,
57
- ) => {
58
- const { host: address } = options;
59
- // --- 1. Pre-DNS Check (Host/Address Check) ---
60
- // If the 'host' option is an IP address, check it immediately.
61
- // If it's a hostname, this check will usually pass (via defaultIpChecker).
62
- if (address && !isSafeHost(address, isValidDomainOptions)) {
63
- throw new Error(`DNS lookup ${address} is not allowed.`);
64
- }
65
-
66
- // Call the original createConnection
67
- // @ts-expect-error 'this' is not assignable to type 'HttpAgent | HttpsAgent'
68
- const client = createConnection.call(this, options, fn);
69
-
70
- // --- 2. Post-DNS Check (Lookup Event Check) ---
71
- // The 'lookup' event fires after the DNS lookup is complete
72
- // and provides the resolved IP address.
73
- client?.on('lookup', (err: Error | null, resolvedAddress: string | string[]) => {
74
- // If there was an error in lookup, or if the resolved IP is allowed, do nothing.
75
- if (err) {
76
- return;
77
- }
78
-
79
- // Ensure resolvedAddress is a string for the check (it's typically a string for simple lookups)
80
- const ipToCheck = Array.isArray(resolvedAddress) ? resolvedAddress[0] : resolvedAddress;
81
-
82
- if (!isSafeIp(ipToCheck)) {
83
- // If the resolved IP is NOT allowed (e.g., a private IP), destroy the connection.
84
- return client?.destroy(new Error(`DNS lookup ${ipToCheck} is not allowed.`));
85
- }
86
- });
87
-
88
- return client;
89
- };
90
-
91
- return finalAgent;
92
- }
package/lib/types.ts DELETED
@@ -1,37 +0,0 @@
1
- // lib/types.ts
2
- export interface Options {
3
- protocal?: string;
4
- metadataHosts?: string[];
5
- mode?: 'block' | 'report' | 'allow';
6
- policy?: PolicyOptions;
7
- blockCloudMetadata?: boolean;
8
- detectDnsRebinding?: boolean;
9
- logger?: (level: 'info' | 'warn' | 'error', msg: string, meta?: any) => void;
10
- }
11
-
12
- export interface PolicyOptions {
13
- allowDomains?: string[];
14
- denyDomains?: string[];
15
- denyTLD?: string[];
16
- }
17
-
18
- export interface BlockEvent {
19
- url: string;
20
- reason: string;
21
- ip?: string;
22
- timestamp: number;
23
- }
24
-
25
- export interface IsValidDomainOptions {
26
- subdomain?: boolean;
27
- wildcard?: boolean;
28
- allowUnicode?: boolean;
29
- topLevel?: boolean;
30
- }
31
-
32
- export const CLOUD_METADATA_HOSTS: string[] = [
33
- '169.254.169.254',
34
- '169.254.169.253',
35
- 'metadata.google.internal',
36
- '169.254.170.2',
37
- ];
package/lib/utils.ts DELETED
@@ -1,46 +0,0 @@
1
- // lib/utils.ts
2
- import isValidDomain from 'is-valid-domain';
3
- import ipaddr from 'ipaddr.js';
4
- import { IsValidDomainOptions, CLOUD_METADATA_HOSTS } from './types';
5
-
6
- /**
7
- * Checks if the input is an IP address (v4/v6).
8
- */
9
- function isIp(input: string): boolean {
10
- return ipaddr.isValid(input);
11
- }
12
-
13
- /**
14
- * Returns true for valid public unicast IP addresses.
15
- */
16
- function isPublicIp(ip: string): boolean {
17
- return ipaddr.parse(ip).range() === 'unicast';
18
- }
19
-
20
- /**
21
- * Validates whether a domain is syntactically valid.
22
- */
23
- export function isSafeIp(hostname: string): boolean {
24
- // Case 1: IP address
25
- if (isIp(hostname)) {
26
- return isPublicIp(hostname); // only allow public IPs
27
- }
28
- return true;
29
- }
30
-
31
- /**
32
- * High-level validation for hostnames (domains + public IPs).
33
- */
34
- export function isSafeHost(hostname: string, isValidDomainOptions?: IsValidDomainOptions): boolean {
35
- // Block cloud metadata IP/domains
36
- if (CLOUD_METADATA_HOSTS.indexOf(hostname)) return false;
37
-
38
- if (!isSafeIp(hostname)) return false;
39
-
40
- // Case 2: Domain name
41
- return isValidDomain(hostname, {
42
- allowUnicode: false,
43
- subdomain: false,
44
- ...isValidDomainOptions,
45
- });
46
- }
package/rollup.config.mjs DELETED
@@ -1,10 +0,0 @@
1
- import typescript from 'rollup-plugin-typescript2';
2
-
3
- export default {
4
- input: 'index.ts',
5
- output: [
6
- { file: 'dist/index.esm.js', format: 'es' },
7
- { file: 'dist/index.cjs.js', format: 'cjs', exports: 'named' },
8
- ],
9
- plugins: [typescript({ useTsconfigDeclarationDir: true })],
10
- };
@@ -1,63 +0,0 @@
1
- describe('SSRF Agent Guard', () => {
2
- describe('Agent Selection', () => {
3
- it('should return HttpsAgent for HTTPS URLs', () => {
4
- expect(true).toBe(true);
5
- });
6
-
7
- it('should return HttpAgent for HTTP URLs', () => {
8
- expect(true).toBe(true);
9
- });
10
-
11
- it('should return HttpAgent by default for non-HTTPS URLs', () => {
12
- expect(true).toBe(true);
13
- });
14
- });
15
-
16
- describe('Pre-DNS Validation', () => {
17
- it('should throw error if host is not safe', () => {
18
- expect(true).toBe(true);
19
- });
20
-
21
- it('should not throw if host is safe', () => {
22
- expect(true).toBe(true);
23
- });
24
-
25
- it('should pass options to isSafeHost', () => {
26
- expect(true).toBe(true);
27
- });
28
-
29
- it('should handle missing host option', () => {
30
- expect(true).toBe(true);
31
- });
32
- });
33
-
34
- describe('Post-DNS Validation', () => {
35
- it('should destroy connection if resolved IP is not safe', () => {
36
- expect(true).toBe(true);
37
- });
38
-
39
- it('should not destroy connection if resolved IP is safe', () => {
40
- expect(true).toBe(true);
41
- });
42
-
43
- it('should handle array of resolved addresses', () => {
44
- expect(true).toBe(true);
45
- });
46
-
47
- it('should ignore lookup errors', () => {
48
- expect(true).toBe(true);
49
- });
50
- });
51
-
52
- describe('Patch Prevention', () => {
53
- it('should not patch agent multiple times', () => {
54
- expect(true).toBe(true);
55
- });
56
- });
57
-
58
- describe('Callback Handling', () => {
59
- it('should call provided callback with client', () => {
60
- expect(true).toBe(true);
61
- });
62
- });
63
- });
package/tsconfig.json DELETED
@@ -1,16 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2020",
4
- "module": "ESNext",
5
- "declaration": true,
6
- "outDir": "dist",
7
- "strict": true,
8
- "esModuleInterop": true,
9
- "moduleResolution": "node",
10
- "skipLibCheck": true
11
- },
12
- "include": [
13
- "lib/**/*",
14
- "rollup.config.mjs"
15
- ]
16
- }