Skip to content

Commit

Permalink
align with master
Browse files Browse the repository at this point in the history
  • Loading branch information
karanrainafynd committed Jul 10, 2024
2 parents 1cd18a7 + 7a11165 commit af67b10
Show file tree
Hide file tree
Showing 14 changed files with 255 additions and 12 deletions.
90 changes: 89 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,14 @@ ___
| [preview-url](#extension-preview-url) | Create a ngrok tunnel and provide a link to tryout extension on development company
| [launch-url](#extension-launch-url) | Get/set extension's lanuch url |

### Config Commands

| Command Type | Description |
|--------------|--------------------------------------|
| [set](#config-set-commands) | Set configuration values. |
| [get](#config-get-commands) | Retrieve current configuration values.|
| [delete](#config-delete-commands) (alias: `rm`) | Delete configuration values. |

<div id="debugMode"></div>


Expand All @@ -104,7 +112,6 @@ fdk login --verbose
<div id="commands-reference"><div/>

## Commands Reference
___
### Environment Commands
Before you start using FDK CLI you will have to set an environment

Expand Down Expand Up @@ -472,6 +479,87 @@ fdk partner connect [options]
fdk partner connect
```
___
### Config Commands
<div id="config-commands"></div>

<div id="config-set-commands"></div>

#### Set Commands
The `set` commands allow you to configure the `cafile` and `strict-ssl` settings for the tool. This is useful for ensuring that the tool uses the correct SSL certificates and validation settings according to your requirements.

| Command | Description |
|-------------------------------------------|----------------------------------------------|
| `set cafile <file-path>` | Sets the CA file to the specified file path. |
| `set strict-ssl <true/false>` | Enables or disables strict SSL validation. |

#### **Example**
```sh
fdk config set cafile /etc/ssl/certs/ca-certificates.pem
```
```sh
fdk config set strict-ssl false
```

#### Notes

> - Ensure that the file path provided for the CA file is valid and accessible.
> - The strict SSL setting should be either `true` or `false`.
#### Environment Variables

> Developers can configure settings using environment variables.<br/><hr/>`FDK_EXTRA_CA_CERTS`: Set this variable to specify the CA file path (`cafile`).
<br/><hr/>`FDK_SSL_NO_VERIFY`: Set this variable to `true` to disable strict SSL validation (`strict-ssl=false`).<hr/>
#### **Example**

```sh
FDK_EXTRA_CA_CERTS=/path/to/your/cafile fdk login
```
```sh
FDK_SSL_NO_VERIFY=true fdk login
```

<div id="config-get-commands"></div>

#### Get Commands
The `get` commands allow you to view the current configuration values for `cafile` and `strict-ssl`. This is useful for verifying what values are currently set and ensuring that your configuration is correct.

| Command | Description |
|-------------------------------|----------------------------------------------|
| `get cafile` | Retrieves the current CA file path. |
| `get strict-ssl` | Retrieves the current strict SSL setting. |

#### **Example**
```sh
fdk config get cafile
```
```sh
fdk config get strict-ssl
```

<div id="config-delete-commands"></div>

#### Delete Commands
The `delete` commands allow you to remove the current configuration for `cafile` and `strict-ssl`. This can be useful for resetting configurations or removing settings that are no longer needed.

| Command | Description |
|------------------------------- |----------------------------------------------|
| `delete cafile` | Deletes the current CA file configuration. |
| `delete strict-ssl` | Deletes the current strict SSL configuration.|
| `rm cafile` | Alias for `delete`: Deletes the current CA file configuration. |


#### **Example**
```sh
fdk config delete cafile
```
```sh
fdk config delete strict-ssl
```
```sh
fdk config rm cafile
```
___

<div id="OtherProjects"></div>

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@gofynd/fdk-cli",
"version": "5.1.0-beta.2",
"version": "5.1.2",
"main": "index.js",
"license": "MIT",
"bin": {
Expand Down
80 changes: 80 additions & 0 deletions src/commands/config/config-builder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { Command } from 'commander';
import Configstore, { CONFIG_KEYS } from '../../lib/Config';
import fs from 'fs-extra';
import chalk from 'chalk';

export default function extensionCommandBuilder() {
const configCommander = new Command('config').description(
'Config Commands',
);
const setCommander = new Command('set').description(
'set config items',
);

setCommander
.command('cafile <ca-file-path>')
.description('To set CA file')
.action((caFilePath: string) => {
if (fs.existsSync(caFilePath)) {
Configstore.set(CONFIG_KEYS.CA_FILE, caFilePath);
} else {
console.log(chalk.red("Provided file path does not exist."));
}
})

setCommander
.command('strict-ssl <boolean>')
.description('To set CA file')
.action((value: string) => {
const ACCEPTED_VALUES = ['false', 'true']
if (ACCEPTED_VALUES.includes(value)) {
Configstore.set(CONFIG_KEYS.STRICT_SSL, value);
} else {
console.log(chalk.red("Entered value is not valid."));
}
})

configCommander.addCommand(setCommander);

const getCommander = new Command('get').description(
'set config items',
);

getCommander
.command('cafile')
.description('To set CA file')
.action(() => {
console.log(Configstore.get(CONFIG_KEYS.CA_FILE) || "");
})

getCommander
.command('strict-ssl')
.description('To set strict-ssl')
.action(() => {
console.log(Configstore.get(CONFIG_KEYS.STRICT_SSL) || "");
})

configCommander.addCommand(getCommander);

const deleteCommander = new Command('delete').alias('rm').description(
'delete config items',
);

deleteCommander
.command('cafile')
.description('To delete CA file')
.action(() => {
Configstore.delete(CONFIG_KEYS.CA_FILE)
})

deleteCommander
.command('strict-ssl')
.description('To reset strict-ssl')
.action(() => {
Configstore.delete(CONFIG_KEYS.STRICT_SSL)
})

configCommander.addCommand(deleteCommander);

return configCommander;
}
6 changes: 6 additions & 0 deletions src/commands/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Command } from 'commander';

import configCommandBuilder from './config-builder';
export default function env(program: Command) {
program.addCommand(configCommandBuilder());
}
1 change: 1 addition & 0 deletions src/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const COMMANDS = [
require('./populate'),
require('./extension'),
require('./partner'),
require('./config'),
];

export function registerCommands(program: CommanderStatic) {
Expand Down
38 changes: 37 additions & 1 deletion src/fdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,44 @@ Command.prototype.asyncAction = async function (asyncFn: Action) {
} else {
process.env.DEBUG = 'false';
}

initializeLogger();

// check in config if user have set certificate
const CA_FILE = configStore.get(CONFIG_KEYS.CA_FILE)
// if user shared certificate while executing the command
const sharedInlineCert = process.env.FDK_EXTRA_CA_CERTS;

// if shared inline then it should be exist
if(sharedInlineCert && !fs.existsSync(sharedInlineCert)){
throw new CommandError("Provided file path does not exist.");
}
// inline CA will get priority
if (!sharedInlineCert && CA_FILE) {
process.env.FDK_EXTRA_CA_CERTS = CA_FILE;
}

if(process.env.FDK_EXTRA_CA_CERTS){
Logger.info(`Using CA file from ${process.env.FDK_EXTRA_CA_CERTS}`)
}

const disableSSL = () => {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
process.env.FDK_SSL_NO_VERIFY = 'true';
}

const sharedInlineNoSSL = process.env.FDK_SSL_NO_VERIFY;
const STRICT_SSL = configStore.get(CONFIG_KEYS.STRICT_SSL);
if(sharedInlineNoSSL == 'true'){
disableSSL();
}
if(!sharedInlineNoSSL && STRICT_SSL == 'false'){
disableSSL();
}

if(process.env.FDK_SSL_NO_VERIFY == 'true'){
Logger.warn(`Bypassing SSL verification`)
}

const latest = await checkCliVersionAsync();
const isCurrentLessThanLatest = semver.lt(
packageJSON.version,
Expand Down
28 changes: 22 additions & 6 deletions src/helper/serve.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import webpackHotMiddleware from 'webpack-hot-middleware';
import webpack from 'webpack';
import createBaseWebpackConfig from '../helper/theme.react.config';
import Debug from '../lib/Debug';
import https from 'https';
const packageJSON = require('../../package.json');

const BUILD_FOLDER = './.fdk/dist';
Expand Down Expand Up @@ -56,12 +57,27 @@ export function getPort(port) {
function applyProxy(app: any) {
const currentContext = getActiveContext();
const currentDomain = `https://${currentContext.domain}`;
let httpsAgent;

if(process.env.FDK_EXTRA_CA_CERTS){
// Load the VPN's CA certificate
const ca = fs.readFileSync(process.env.FDK_EXTRA_CA_CERTS);
// Create an HTTPS agent with the CA certificate
httpsAgent = { ca }
}
if(process.env.FDK_SSL_NO_VERIFY == 'true'){
httpsAgent = { rejectUnauthorized: false }
}
if(httpsAgent){
httpsAgent = new https.Agent(httpsAgent);
}
const options = {
target: currentDomain, // target host
changeOrigin: true, // needed for virtual hosted sites
cookieDomainRewrite: '127.0.0.1', // rewrite cookies to localhost
onProxyReq: fixRequestBody,
onError: (error) => Logger.error(error),
agent: httpsAgent
};

// proxy to solve CORS issue
Expand Down Expand Up @@ -137,10 +153,10 @@ async function requestToOriginalSource(req, res, domain, themeId) {
return res.send(publicCache[url].body);
} catch (error) {
// If there's an error, pass it to the client
if (error.response) {
if (error?.response) {
// If there is a response from the server
res.status(error.response.status).send(error.response.data);
} else if (error.request) {
res.status(error?.response?.status).send(error?.response?.data);
} else if (error?.request) {
// If the request was made but no response was received
res.status(500).send('No response from server');
} else {
Expand Down Expand Up @@ -215,7 +231,7 @@ export async function startServer({ domain, host, isSSR, port }) {
data: {
theme_url: themeUrl,
domain: getFullLocalUrl(port),
},
}
});

let $ = cheerio.load(html);
Expand Down Expand Up @@ -269,9 +285,9 @@ export async function startServer({ domain, host, isSSR, port }) {
});
res.send($.html({ decodeEntities: false }));
} catch (e) {
if (e.response && e.response.status == 504) {
if (e?.response && e?.response?.status == 504) {
res.redirect(req.originalUrl);
} else if (e.response && e.response.status == 500) {
} else if (e?.response && e?.response?.status == 500) {
try {
Logger.error(e.response.data);
let errorString = e.response.data
Expand Down
2 changes: 2 additions & 0 deletions src/lib/Auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,10 @@ export default class Auth {
const currentEnv = ConfigStore.get(
CONFIG_KEYS.CURRENT_ENV_VALUE,
);
const extras = ConfigStore.get(CONFIG_KEYS.EXTRAS);
ConfigStore.clear();
ConfigStore.set(CONFIG_KEYS.CURRENT_ENV_VALUE, currentEnv);
ConfigStore.set(CONFIG_KEYS.EXTRAS, extras);
Logger.info(`User logged out successfully`);
}
});
Expand Down
3 changes: 3 additions & 0 deletions src/lib/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ export const CONFIG_KEYS = {
COMPANY_ID: 'current_env.company_id',
AUTH_TOKEN: 'current_env.auth_token',
ORGANIZATION: 'current_env.organization',
EXTRAS: 'extras',
STRICT_SSL: 'extras.strict_ssl',
CA_FILE: 'extras.ca_file',
};

// global config store - The config is stored in a JSON file located in $XDG_CONFIG_HOME or ~/.config
Expand Down
2 changes: 1 addition & 1 deletion src/lib/Extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ export default class Extension {
await ExtensionService.registerExtensionPartners(data);
answers.extension_api_key = extension_data.client_id;
answers.extension_api_secret = extension_data.secret;
answers.base_url = extension_data.launch_url;
answers.base_url = extension_data.base_url;
spinner.succeed();
} catch (error) {
spinner.fail();
Expand Down
1 change: 1 addition & 0 deletions src/lib/api/ApiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
import Curl from '../../helper/curl';
import Logger from '../Logger';
import { MAX_RETRY } from '../../helper/constants';
import https from 'https'
axios.defaults.withCredentials = true;
axios.defaults.timeout = 60000; // 1 minute

Expand Down
Loading

0 comments on commit af67b10

Please sign in to comment.