infrahub-sdk 0.0.6 → 0.0.8

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.
Files changed (41) hide show
  1. package/.github/workflows/publish.yml +13 -9
  2. package/README.md +83 -0
  3. package/dist/index.d.ts +36 -0
  4. package/dist/index.js +83 -14
  5. package/dist/index.test.js +125 -2
  6. package/examples/expired-certificate-example.ts +36 -0
  7. package/package.json +5 -3
  8. package/src/index.test.ts +143 -2
  9. package/src/index.ts +134 -17
  10. package/dist/cjs/index.js +0 -65
  11. package/dist/cjs/index.js.map +0 -7
  12. package/dist/client.d.ts +0 -6
  13. package/dist/client.js +0 -35
  14. package/dist/constants.d.ts +0 -0
  15. package/dist/constants.js +0 -1
  16. package/dist/esm/index.js +0 -32
  17. package/dist/esm/index.js.map +0 -7
  18. package/dist/types/client.d.ts +0 -7
  19. package/dist/types/client.d.ts.map +0 -1
  20. package/dist/types/constants.d.ts +0 -1
  21. package/dist/types/constants.d.ts.map +0 -1
  22. package/dist/types/index.d.ts +0 -2
  23. package/dist/types/index.d.ts.map +0 -1
  24. package/dist/types/utils/auth.d.ts +0 -1
  25. package/dist/types/utils/auth.d.ts.map +0 -1
  26. package/dist/types/utils/error-handling.d.ts +0 -1
  27. package/dist/types/utils/error-handling.d.ts.map +0 -1
  28. package/dist/types/utils/index.d.ts +0 -1
  29. package/dist/types/utils/index.d.ts.map +0 -1
  30. package/dist/types/utils/validation.d.ts +0 -1
  31. package/dist/types/utils/validation.d.ts.map +0 -1
  32. package/dist/utils/auth.d.ts +0 -0
  33. package/dist/utils/auth.js +0 -1
  34. package/dist/utils/error-handling.d.ts +0 -0
  35. package/dist/utils/error-handling.js +0 -1
  36. package/dist/utils/index.d.ts +0 -0
  37. package/dist/utils/index.js +0 -1
  38. package/dist/utils/validation.d.ts +0 -0
  39. package/dist/utils/validation.js +0 -1
  40. package/test/package-lock.json +0 -1044
  41. package/test/package.json +0 -14
@@ -2,21 +2,25 @@ name: Publish Package to npmjs
2
2
  on:
3
3
  release:
4
4
  types: [published]
5
+
6
+ permissions:
7
+ id-token: write # Required for OIDC
8
+ contents: read
9
+
5
10
  jobs:
6
- build:
11
+ publish:
7
12
  runs-on: ubuntu-latest
8
- permissions:
9
- contents: read
10
- id-token: write
11
13
  steps:
12
14
  - uses: actions/checkout@v4
13
- # Setup .npmrc file to publish to npm
15
+
14
16
  - uses: actions/setup-node@v4
15
17
  with:
16
- node-version: '20.x'
18
+ node-version: '20'
17
19
  registry-url: 'https://registry.npmjs.org'
20
+
21
+ # Ensure npm 11.5.1 or later is installed
22
+ - name: Update npm
23
+ run: npm install -g npm@latest
18
24
  - run: npm ci
19
- - run: npm run build
25
+ - run: npm run build --if-present
20
26
  - run: npm publish
21
- env:
22
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/README.md CHANGED
@@ -37,6 +37,89 @@ const listDevices = gql`
37
37
  const usersData = await client.executeGraphQL(listDevices);
38
38
  ```
39
39
 
40
+ ## TLS/SSL Configuration
41
+
42
+ When connecting to Infrahub instances with custom, self-signed, or expired certificates, you can configure TLS options:
43
+
44
+ ### Handling Certificate Errors
45
+
46
+ If you encounter certificate errors such as:
47
+ - `certificate has expired`
48
+ - `self-signed certificate`
49
+ - `unable to verify the first certificate`
50
+ - `UNABLE_TO_VERIFY_LEAF_SIGNATURE`
51
+
52
+ You can resolve these by configuring the TLS options as shown below.
53
+
54
+ ### Disable Certificate Verification (for development/testing)
55
+
56
+ This is the recommended approach for handling expired certificates in development/testing environments:
57
+
58
+ ```typescript
59
+ import { InfrahubClient, InfrahubClientOptions } from 'infrahub-sdk';
60
+
61
+ const options: InfrahubClientOptions = {
62
+ address: "https://infrahub.example.com",
63
+ token: "your-api-token",
64
+ tls: {
65
+ rejectUnauthorized: false
66
+ }
67
+ }
68
+
69
+ const client = new InfrahubClient(options);
70
+ ```
71
+
72
+ **Important Notes:**
73
+ - Setting `rejectUnauthorized: false` disables ALL certificate validation
74
+ - This bypasses checks for expired, self-signed, and invalid certificates
75
+ - **Warning**: Never use this in production environments as it makes your connection vulnerable to man-in-the-middle attacks
76
+ - Only use this for development, testing, or when connecting to trusted internal servers
77
+
78
+ **Example:** See [examples/expired-certificate-example.ts](examples/expired-certificate-example.ts) for a complete working example.
79
+
80
+ ### Troubleshooting
81
+
82
+ If you're still experiencing certificate errors after setting `rejectUnauthorized: false`:
83
+
84
+ 1. **Verify the configuration is being applied**: Make sure you're creating the client with the TLS options
85
+ 2. **Check for multiple client instances**: Ensure all instances use the same TLS configuration
86
+ 3. **Network/Proxy Issues**: If you're behind a proxy, you may need additional configuration
87
+ 4. **Node.js Version**: Ensure you're using Node.js 14 or later
88
+
89
+ ### Use Custom CA Certificate
90
+
91
+ ```typescript
92
+ import fs from 'fs';
93
+
94
+ const options: InfrahubClientOptions = {
95
+ address: "https://infrahub.example.com",
96
+ token: "your-api-token",
97
+ tls: {
98
+ ca: fs.readFileSync('/path/to/ca-certificate.pem')
99
+ }
100
+ }
101
+
102
+ const client = new InfrahubClient(options);
103
+ ```
104
+
105
+ ### Mutual TLS (Client Certificate Authentication)
106
+
107
+ ```typescript
108
+ import fs from 'fs';
109
+
110
+ const options: InfrahubClientOptions = {
111
+ address: "https://infrahub.example.com",
112
+ token: "your-api-token",
113
+ tls: {
114
+ ca: fs.readFileSync('/path/to/ca-certificate.pem'),
115
+ cert: fs.readFileSync('/path/to/client-cert.pem'),
116
+ key: fs.readFileSync('/path/to/client-key.pem')
117
+ }
118
+ }
119
+
120
+ const client = new InfrahubClient(options);
121
+ ```
122
+
40
123
  ## Development
41
124
 
42
125
  - Build: `npm run build`
package/dist/index.d.ts CHANGED
@@ -13,10 +13,46 @@ import { InfrahubBranchManager } from './branch';
13
13
  import { InfrahubUserResponse } from './graphql/client';
14
14
  export * from 'graphql-request';
15
15
  export * from './types';
16
+ export interface TLSConfig {
17
+ /**
18
+ * If true, the server certificate is verified against the list of supplied CAs.
19
+ * Set to false to disable certificate verification (not recommended for production).
20
+ *
21
+ * Note: Setting this to false will bypass all certificate validation, including
22
+ * expired certificates, self-signed certificates, and hostname mismatches.
23
+ */
24
+ rejectUnauthorized?: boolean;
25
+ /**
26
+ * Optional CA certificates to trust. Can be a string or Buffer containing the certificate(s).
27
+ * Use this when connecting to servers with custom or self-signed certificates.
28
+ */
29
+ ca?: string | Buffer | Array<string | Buffer>;
30
+ /**
31
+ * Optional client certificate for mutual TLS authentication.
32
+ */
33
+ cert?: string | Buffer;
34
+ /**
35
+ * Optional client private key for mutual TLS authentication.
36
+ */
37
+ key?: string | Buffer;
38
+ }
16
39
  export interface InfrahubClientOptions {
17
40
  address: string;
18
41
  token?: string;
19
42
  branch?: string;
43
+ /**
44
+ * TLS/SSL configuration options for HTTPS connections.
45
+ * Use this to handle custom certificates, expired certificates, or disable certificate verification.
46
+ *
47
+ * @example
48
+ * // Disable certificate verification (development only)
49
+ * { tls: { rejectUnauthorized: false } }
50
+ *
51
+ * @example
52
+ * // Use custom CA certificate
53
+ * { tls: { ca: fs.readFileSync('/path/to/ca.pem') } }
54
+ */
55
+ tls?: TLSConfig;
20
56
  }
21
57
  export declare class InfrahubClient {
22
58
  rest: ReturnType<typeof createClient<paths>>;
package/dist/index.js CHANGED
@@ -18,6 +18,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
20
  exports.InfrahubClient = void 0;
21
+ const https_1 = __importDefault(require("https"));
22
+ const node_fetch_1 = __importDefault(require("node-fetch"));
21
23
  const openapi_fetch_1 = __importDefault(require("openapi-fetch"));
22
24
  const graphql_request_1 = require("graphql-request");
23
25
  const branch_1 = require("./branch");
@@ -32,24 +34,52 @@ class InfrahubClient {
32
34
  this.token = options.token;
33
35
  this.defaultBranch = options.branch || DEFAULT_BRANCH_NAME;
34
36
  this.branch = new branch_1.InfrahubBranchManager(this);
35
- // Initialize the openapi-fetch client
37
+ // Create custom fetch with TLS options if provided
38
+ let customFetch = node_fetch_1.default;
39
+ if (options.tls) {
40
+ // Build agent options, ensuring rejectUnauthorized is explicitly set if provided
41
+ const agentOptions = {};
42
+ if (options.tls.rejectUnauthorized !== undefined) {
43
+ agentOptions.rejectUnauthorized = options.tls.rejectUnauthorized;
44
+ }
45
+ if (options.tls.ca !== undefined) {
46
+ agentOptions.ca = options.tls.ca;
47
+ }
48
+ if (options.tls.cert !== undefined) {
49
+ agentOptions.cert = options.tls.cert;
50
+ }
51
+ if (options.tls.key !== undefined) {
52
+ agentOptions.key = options.tls.key;
53
+ }
54
+ const httpsAgent = new https_1.default.Agent(agentOptions);
55
+ customFetch = ((url, opts = {}) => {
56
+ // Ensure agent is passed for HTTPS URLs
57
+ // node-fetch v2 requires the agent to be explicitly set
58
+ const fetchOptions = { ...opts, agent: httpsAgent };
59
+ return (0, node_fetch_1.default)(url, fetchOptions);
60
+ });
61
+ }
62
+ // Initialize the openapi-fetch client with TLS configuration
36
63
  this.rest = (0, openapi_fetch_1.default)({
37
- baseUrl: this.baseUrl
64
+ baseUrl: this.baseUrl,
65
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
66
+ fetch: customFetch
38
67
  });
39
- const token = this.token;
40
- const myMiddleware = {
41
- async onRequest({ request }) {
42
- // set "X-INFRAHUB-KEY" header if token is present
43
- if (token) {
44
- request.headers.set('X-INFRAHUB-KEY', token);
68
+ // Use middleware to dynamically add the auth token to every REST request.
69
+ this.rest.use({
70
+ onRequest: (req) => {
71
+ req.headers.set('content-type', 'application/json');
72
+ if (this.token) {
73
+ req.headers.set('X-INFRAHUB-KEY', this.token);
45
74
  }
46
- request.headers.set('content-type', 'application/json');
47
- return request;
48
- },
49
- };
50
- this.rest.use(myMiddleware);
75
+ return req;
76
+ }
77
+ });
51
78
  // Initialize the GraphQL client with the default branch endpoint
52
- this.graphqlClient = new graphql_request_1.GraphQLClient(this._graphqlUrl(this.defaultBranch));
79
+ this.graphqlClient = new graphql_request_1.GraphQLClient(this._graphqlUrl(this.defaultBranch), {
80
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
81
+ fetch: customFetch
82
+ });
53
83
  this.graphqlClient.setHeaders({
54
84
  'Content-Type': 'application/json'
55
85
  });
@@ -110,6 +140,45 @@ class InfrahubClient {
110
140
  return await this.graphqlClient.request(query, variables);
111
141
  }
112
142
  catch (error) {
143
+ // Check if this is a certificate error and provide helpful guidance
144
+ if (error instanceof Error) {
145
+ const errorMessage = error.message.toLowerCase();
146
+ const isCertError = errorMessage.includes('certificate') ||
147
+ errorMessage.includes('cert') ||
148
+ errorMessage.includes('ssl') ||
149
+ errorMessage.includes('tls');
150
+ const isExpired = errorMessage.includes('expired');
151
+ const isSelfSigned = errorMessage.includes('self-signed') || errorMessage.includes('self signed');
152
+ const isUnauthorized = errorMessage.includes('unauthorized');
153
+ if (isCertError && (isExpired || isSelfSigned || isUnauthorized)) {
154
+ const helpMessage = [
155
+ '',
156
+ 'Certificate validation failed. To resolve this issue, you can configure TLS options:',
157
+ '',
158
+ '1. Disable certificate verification (for development/testing only):',
159
+ ' const client = new InfrahubClient({',
160
+ ' address: "your-address",',
161
+ ' token: "your-token",',
162
+ ' tls: { rejectUnauthorized: false }',
163
+ ' });',
164
+ '',
165
+ '2. Or provide a custom CA certificate (requires: import fs from "fs"):',
166
+ ' const client = new InfrahubClient({',
167
+ ' address: "your-address",',
168
+ ' token: "your-token",',
169
+ ' tls: { ca: fs.readFileSync("/path/to/ca-cert.pem") }',
170
+ ' });',
171
+ '',
172
+ 'See the README.md for more TLS configuration options.',
173
+ ''
174
+ ].join('\n');
175
+ console.error(helpMessage);
176
+ // Create a new error with helpful message appended
177
+ const enhancedError = new Error(`${error.message}\n${helpMessage}`);
178
+ enhancedError.stack = error.stack;
179
+ throw enhancedError;
180
+ }
181
+ }
113
182
  console.error('Error executing GraphQL query:', error);
114
183
  throw error;
115
184
  }
@@ -24,8 +24,8 @@ const globals_1 = require("@jest/globals");
24
24
  const newToken = 'new-token';
25
25
  client.setAuthToken(newToken);
26
26
  (0, globals_1.expect)(client.token).toBe(newToken);
27
- // GraphQLClient headers are private, so we check no error is thrown
28
- (0, globals_1.expect)(() => client.executeGraphQL('{ __typename }')).not.toThrow();
27
+ // Check that the GraphQL headers are properly set by verifying the token is updated
28
+ (0, globals_1.expect)(client.graphqlClient.requestConfig.headers['X-INFRAHUB-KEY']).toBe(newToken);
29
29
  });
30
30
  (0, globals_1.it)('should call graphqlQuery and handle errors', async () => {
31
31
  const mockRequest = globals_1.jest
@@ -38,6 +38,50 @@ const globals_1 = require("@jest/globals");
38
38
  await (0, globals_1.expect)(client.executeGraphQL('{ test }')).rejects.toThrow('GraphQL error');
39
39
  consoleErrorSpy.mockRestore();
40
40
  });
41
+ (0, globals_1.it)('should provide helpful error message for certificate errors', async () => {
42
+ const mockRequest = globals_1.jest
43
+ .fn()
44
+ .mockImplementation(() => Promise.reject(new Error('request failed, reason: certificate has expired')));
45
+ client.graphqlClient.request = mockRequest;
46
+ const consoleErrorSpy = globals_1.jest
47
+ .spyOn(console, 'error')
48
+ .mockImplementation(() => { });
49
+ try {
50
+ await client.executeGraphQL('{ test }');
51
+ (0, globals_1.expect)(true).toBe(false); // Should not reach here
52
+ }
53
+ catch (error) {
54
+ (0, globals_1.expect)(error).toBeInstanceOf(Error);
55
+ if (error instanceof Error) {
56
+ (0, globals_1.expect)(error.message).toContain('certificate has expired');
57
+ (0, globals_1.expect)(error.message).toContain('Certificate validation failed');
58
+ (0, globals_1.expect)(error.message).toContain('rejectUnauthorized: false');
59
+ }
60
+ }
61
+ consoleErrorSpy.mockRestore();
62
+ });
63
+ (0, globals_1.it)('should provide helpful error message for self-signed certificate errors', async () => {
64
+ const mockRequest = globals_1.jest
65
+ .fn()
66
+ .mockImplementation(() => Promise.reject(new Error('request failed, reason: self-signed certificate')));
67
+ client.graphqlClient.request = mockRequest;
68
+ const consoleErrorSpy = globals_1.jest
69
+ .spyOn(console, 'error')
70
+ .mockImplementation(() => { });
71
+ try {
72
+ await client.executeGraphQL('{ test }');
73
+ (0, globals_1.expect)(true).toBe(false); // Should not reach here
74
+ }
75
+ catch (error) {
76
+ (0, globals_1.expect)(error).toBeInstanceOf(Error);
77
+ if (error instanceof Error) {
78
+ (0, globals_1.expect)(error.message).toContain('self-signed certificate');
79
+ (0, globals_1.expect)(error.message).toContain('Certificate validation failed');
80
+ (0, globals_1.expect)(error.message).toContain('tls: { rejectUnauthorized: false }');
81
+ }
82
+ }
83
+ consoleErrorSpy.mockRestore();
84
+ });
41
85
  (0, globals_1.it)('should initialize rest client with baseUrl', () => {
42
86
  (0, globals_1.expect)(client.rest).toBeDefined();
43
87
  });
@@ -59,4 +103,83 @@ const globals_1 = require("@jest/globals");
59
103
  const url = client._graphqlUrl(branchName);
60
104
  (0, globals_1.expect)(url).toBe(`${baseURL}/graphql/${branchName}`);
61
105
  });
106
+ (0, globals_1.describe)('TLS Configuration', () => {
107
+ (0, globals_1.it)('should accept TLS configuration with rejectUnauthorized set to false', () => {
108
+ const options = {
109
+ address: baseURL,
110
+ token: token,
111
+ tls: {
112
+ rejectUnauthorized: false
113
+ }
114
+ };
115
+ const tlsClient = new index_1.InfrahubClient(options);
116
+ (0, globals_1.expect)(tlsClient).toBeDefined();
117
+ (0, globals_1.expect)(tlsClient.graphqlClient).toBeInstanceOf(graphql_request_1.GraphQLClient);
118
+ });
119
+ (0, globals_1.it)('should create agent with rejectUnauthorized: false when explicitly set', () => {
120
+ const https = require('https');
121
+ const createAgentSpy = globals_1.jest.spyOn(https, 'Agent');
122
+ const options = {
123
+ address: baseURL,
124
+ token: token,
125
+ tls: {
126
+ rejectUnauthorized: false
127
+ }
128
+ };
129
+ const tlsClient = new index_1.InfrahubClient(options);
130
+ (0, globals_1.expect)(createAgentSpy).toHaveBeenCalled();
131
+ const agentOptions = createAgentSpy.mock.calls[createAgentSpy.mock.calls.length - 1][0];
132
+ (0, globals_1.expect)(agentOptions.rejectUnauthorized).toBe(false);
133
+ createAgentSpy.mockRestore();
134
+ });
135
+ (0, globals_1.it)('should accept TLS configuration with custom CA certificate', () => {
136
+ const options = {
137
+ address: baseURL,
138
+ token: token,
139
+ tls: {
140
+ ca: '-----BEGIN CERTIFICATE-----\nMockCertificate\n-----END CERTIFICATE-----'
141
+ }
142
+ };
143
+ const tlsClient = new index_1.InfrahubClient(options);
144
+ (0, globals_1.expect)(tlsClient).toBeDefined();
145
+ (0, globals_1.expect)(tlsClient.graphqlClient).toBeInstanceOf(graphql_request_1.GraphQLClient);
146
+ });
147
+ (0, globals_1.it)('should accept TLS configuration with client certificate and key', () => {
148
+ const options = {
149
+ address: baseURL,
150
+ token: token,
151
+ tls: {
152
+ cert: '-----BEGIN CERTIFICATE-----\nMockCert\n-----END CERTIFICATE-----',
153
+ key: '-----BEGIN PRIVATE KEY-----\nMockKey\n-----END PRIVATE KEY-----'
154
+ }
155
+ };
156
+ const tlsClient = new index_1.InfrahubClient(options);
157
+ (0, globals_1.expect)(tlsClient).toBeDefined();
158
+ (0, globals_1.expect)(tlsClient.graphqlClient).toBeInstanceOf(graphql_request_1.GraphQLClient);
159
+ });
160
+ (0, globals_1.it)('should accept TLS configuration with all options', () => {
161
+ const options = {
162
+ address: baseURL,
163
+ token: token,
164
+ tls: {
165
+ rejectUnauthorized: true,
166
+ ca: '-----BEGIN CERTIFICATE-----\nMockCA\n-----END CERTIFICATE-----',
167
+ cert: '-----BEGIN CERTIFICATE-----\nMockCert\n-----END CERTIFICATE-----',
168
+ key: '-----BEGIN PRIVATE KEY-----\nMockKey\n-----END PRIVATE KEY-----'
169
+ }
170
+ };
171
+ const tlsClient = new index_1.InfrahubClient(options);
172
+ (0, globals_1.expect)(tlsClient).toBeDefined();
173
+ (0, globals_1.expect)(tlsClient.graphqlClient).toBeInstanceOf(graphql_request_1.GraphQLClient);
174
+ });
175
+ (0, globals_1.it)('should work without TLS configuration (backward compatibility)', () => {
176
+ const options = {
177
+ address: baseURL,
178
+ token: token
179
+ };
180
+ const normalClient = new index_1.InfrahubClient(options);
181
+ (0, globals_1.expect)(normalClient).toBeDefined();
182
+ (0, globals_1.expect)(normalClient.graphqlClient).toBeInstanceOf(graphql_request_1.GraphQLClient);
183
+ });
184
+ });
62
185
  });
@@ -0,0 +1,36 @@
1
+ // Example: Connecting to Infrahub with an expired or self-signed certificate
2
+ import { InfrahubClient, InfrahubClientOptions } from 'infrahub-sdk';
3
+ import fs from 'fs';
4
+
5
+ // Option 1: Disable certificate verification (for development/testing only)
6
+ // This will bypass ALL certificate validation including expired certificates
7
+ const clientWithoutVerification = new InfrahubClient({
8
+ address: 'https://your-infrahub-server.com',
9
+ token: 'your-api-token',
10
+ tls: {
11
+ rejectUnauthorized: false
12
+ }
13
+ });
14
+
15
+ // Test the connection
16
+ async function testConnection() {
17
+ try {
18
+ const version = await clientWithoutVerification.getVersion();
19
+ console.log('Successfully connected! Infrahub version:', version);
20
+ } catch (error) {
21
+ console.error('Connection failed:', error);
22
+ }
23
+ }
24
+
25
+ testConnection();
26
+
27
+ // Option 2: Use a custom CA certificate (production-friendly approach)
28
+ // Uncomment the following to use a custom CA certificate instead:
29
+ //
30
+ // const clientWithCustomCA = new InfrahubClient({
31
+ // address: 'https://your-infrahub-server.com',
32
+ // token: 'your-api-token',
33
+ // tls: {
34
+ // ca: fs.readFileSync('/path/to/your/ca-certificate.pem')
35
+ // }
36
+ // });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "infrahub-sdk",
3
- "version": "0.0.6",
3
+ "version": "0.0.8",
4
4
  "description": "A client SDK for the Infrahub API.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -19,14 +19,16 @@
19
19
  "dependencies": {
20
20
  "@graphql-codegen/typed-document-node": "^5.1.2",
21
21
  "graphql-request": "^6.1.0",
22
- "openapi-fetch": "^0.14.0"
22
+ "node-fetch": "^2.7.0",
23
+ "openapi-fetch": "^0.9.4"
23
24
  },
24
25
  "devDependencies": {
25
26
  "@eslint/js": "^9.31.0",
27
+ "@types/node": "^24.10.0",
28
+ "@types/node-fetch": "^2.6.13",
26
29
  "eslint": "^9.31.0",
27
30
  "eslint-config-prettier": "^10.1.5",
28
31
  "eslint-plugin-prettier": "^5.5.1",
29
- "openapi-typescript": "^7.8.0",
30
32
  "prettier": "3.6.2",
31
33
  "ts-jest": "^29.4.0",
32
34
  "typescript": "^5.8.3",
package/src/index.test.ts CHANGED
@@ -27,8 +27,8 @@ describe('InfrahubClient', () => {
27
27
  const newToken = 'new-token';
28
28
  client.setAuthToken(newToken);
29
29
  expect((client as any).token).toBe(newToken);
30
- // GraphQLClient headers are private, so we check no error is thrown
31
- expect(() => client.executeGraphQL('{ __typename }')).not.toThrow();
30
+ // Check that the GraphQL headers are properly set by verifying the token is updated
31
+ expect((client as any).graphqlClient.requestConfig.headers['X-INFRAHUB-KEY']).toBe(newToken);
32
32
  });
33
33
 
34
34
  it('should call graphqlQuery and handle errors', async () => {
@@ -45,6 +45,58 @@ describe('InfrahubClient', () => {
45
45
  consoleErrorSpy.mockRestore();
46
46
  });
47
47
 
48
+ it('should provide helpful error message for certificate errors', async () => {
49
+ const mockRequest = jest
50
+ .fn()
51
+ .mockImplementation(() =>
52
+ Promise.reject(new Error('request failed, reason: certificate has expired'))
53
+ );
54
+ (client as any).graphqlClient.request = mockRequest;
55
+ const consoleErrorSpy = jest
56
+ .spyOn(console, 'error')
57
+ .mockImplementation(() => {});
58
+
59
+ try {
60
+ await client.executeGraphQL('{ test }');
61
+ expect(true).toBe(false); // Should not reach here
62
+ } catch (error) {
63
+ expect(error).toBeInstanceOf(Error);
64
+ if (error instanceof Error) {
65
+ expect(error.message).toContain('certificate has expired');
66
+ expect(error.message).toContain('Certificate validation failed');
67
+ expect(error.message).toContain('rejectUnauthorized: false');
68
+ }
69
+ }
70
+
71
+ consoleErrorSpy.mockRestore();
72
+ });
73
+
74
+ it('should provide helpful error message for self-signed certificate errors', async () => {
75
+ const mockRequest = jest
76
+ .fn()
77
+ .mockImplementation(() =>
78
+ Promise.reject(new Error('request failed, reason: self-signed certificate'))
79
+ );
80
+ (client as any).graphqlClient.request = mockRequest;
81
+ const consoleErrorSpy = jest
82
+ .spyOn(console, 'error')
83
+ .mockImplementation(() => {});
84
+
85
+ try {
86
+ await client.executeGraphQL('{ test }');
87
+ expect(true).toBe(false); // Should not reach here
88
+ } catch (error) {
89
+ expect(error).toBeInstanceOf(Error);
90
+ if (error instanceof Error) {
91
+ expect(error.message).toContain('self-signed certificate');
92
+ expect(error.message).toContain('Certificate validation failed');
93
+ expect(error.message).toContain('tls: { rejectUnauthorized: false }');
94
+ }
95
+ }
96
+
97
+ consoleErrorSpy.mockRestore();
98
+ });
99
+
48
100
  it('should initialize rest client with baseUrl', () => {
49
101
  expect((client as any).rest).toBeDefined();
50
102
  });
@@ -71,4 +123,93 @@ describe('InfrahubClient', () => {
71
123
  const url = (client as any)._graphqlUrl(branchName);
72
124
  expect(url).toBe(`${baseURL}/graphql/${branchName}`);
73
125
  });
126
+
127
+ describe('TLS Configuration', () => {
128
+ it('should accept TLS configuration with rejectUnauthorized set to false', () => {
129
+ const options: InfrahubClientOptions = {
130
+ address: baseURL,
131
+ token: token,
132
+ tls: {
133
+ rejectUnauthorized: false
134
+ }
135
+ };
136
+ const tlsClient = new InfrahubClient(options);
137
+ expect(tlsClient).toBeDefined();
138
+ expect((tlsClient as any).graphqlClient).toBeInstanceOf(GraphQLClient);
139
+ });
140
+
141
+ it('should create agent with rejectUnauthorized: false when explicitly set', () => {
142
+ const https = require('https');
143
+ const createAgentSpy = jest.spyOn(https, 'Agent');
144
+
145
+ const options: InfrahubClientOptions = {
146
+ address: baseURL,
147
+ token: token,
148
+ tls: {
149
+ rejectUnauthorized: false
150
+ }
151
+ };
152
+
153
+ const tlsClient = new InfrahubClient(options);
154
+
155
+ expect(createAgentSpy).toHaveBeenCalled();
156
+ const agentOptions = createAgentSpy.mock.calls[createAgentSpy.mock.calls.length - 1][0] as any;
157
+ expect(agentOptions.rejectUnauthorized).toBe(false);
158
+
159
+ createAgentSpy.mockRestore();
160
+ });
161
+
162
+ it('should accept TLS configuration with custom CA certificate', () => {
163
+ const options: InfrahubClientOptions = {
164
+ address: baseURL,
165
+ token: token,
166
+ tls: {
167
+ ca: '-----BEGIN CERTIFICATE-----\nMockCertificate\n-----END CERTIFICATE-----'
168
+ }
169
+ };
170
+ const tlsClient = new InfrahubClient(options);
171
+ expect(tlsClient).toBeDefined();
172
+ expect((tlsClient as any).graphqlClient).toBeInstanceOf(GraphQLClient);
173
+ });
174
+
175
+ it('should accept TLS configuration with client certificate and key', () => {
176
+ const options: InfrahubClientOptions = {
177
+ address: baseURL,
178
+ token: token,
179
+ tls: {
180
+ cert: '-----BEGIN CERTIFICATE-----\nMockCert\n-----END CERTIFICATE-----',
181
+ key: '-----BEGIN PRIVATE KEY-----\nMockKey\n-----END PRIVATE KEY-----'
182
+ }
183
+ };
184
+ const tlsClient = new InfrahubClient(options);
185
+ expect(tlsClient).toBeDefined();
186
+ expect((tlsClient as any).graphqlClient).toBeInstanceOf(GraphQLClient);
187
+ });
188
+
189
+ it('should accept TLS configuration with all options', () => {
190
+ const options: InfrahubClientOptions = {
191
+ address: baseURL,
192
+ token: token,
193
+ tls: {
194
+ rejectUnauthorized: true,
195
+ ca: '-----BEGIN CERTIFICATE-----\nMockCA\n-----END CERTIFICATE-----',
196
+ cert: '-----BEGIN CERTIFICATE-----\nMockCert\n-----END CERTIFICATE-----',
197
+ key: '-----BEGIN PRIVATE KEY-----\nMockKey\n-----END PRIVATE KEY-----'
198
+ }
199
+ };
200
+ const tlsClient = new InfrahubClient(options);
201
+ expect(tlsClient).toBeDefined();
202
+ expect((tlsClient as any).graphqlClient).toBeInstanceOf(GraphQLClient);
203
+ });
204
+
205
+ it('should work without TLS configuration (backward compatibility)', () => {
206
+ const options: InfrahubClientOptions = {
207
+ address: baseURL,
208
+ token: token
209
+ };
210
+ const normalClient = new InfrahubClient(options);
211
+ expect(normalClient).toBeDefined();
212
+ expect((normalClient as any).graphqlClient).toBeInstanceOf(GraphQLClient);
213
+ });
214
+ });
74
215
  });