Skip to content

Commit

Permalink
chore(api):updated api services to js packages
Browse files Browse the repository at this point in the history
  • Loading branch information
VigneshKna committed Oct 1, 2024
1 parent 5e61f73 commit d77bc1e
Show file tree
Hide file tree
Showing 13 changed files with 1,099 additions and 376 deletions.
2 changes: 1 addition & 1 deletion src/js/config.ini
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[DEFAULT]
package_name = @how2validate/how2validate
version = 0.0.1-beta.22
version = 0.0.1-beta.24

[SECRET]
secret_active = Active
Expand Down
20 changes: 12 additions & 8 deletions src/js/how2validate/handler/validator_handler.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
import { validateSnykAuthKey } from "../validators/snyk/snyk_auth_key.js"; // Import the Snyk authentication key validator
import { validateSonarcloudToken } from "../validators/sonarcloud/sonarcloud_token.js"; // Import the Sonarcloud token validator
import { validateNpmAccessToken } from "../validators/npm/npm_access_token.js"; // Import the NPM access token validator
// import { validateSonarcloudToken } from "../validators/sonarcloud/sonarcloud_token.js"; // Import the Sonarcloud token validator
// import { validateNpmAccessToken } from "../validators/npm/npm_access_token.js"; // Import the NPM access token validator
import { ValidationResult } from "../utility/validationResult.js";
import { validateNpmAccessToken } from "../validators/npm/npm_access_token.js";

// Define a type for the validator function signature
type ValidatorFunction = (
service: string, // The name of the service being validated
secret: string, // The secret (e.g., API key, token) to validate
response: boolean, // Indicates whether to include response data in the output
report?: boolean // Optional parameter for additional reporting functionality
) => Promise<string>; // The function returns a promise that resolves to a validation result message
report: boolean, // Optional parameter for additional reporting functionality
isBrowser:boolean
) => Promise<ValidationResult | {} | ""| undefined>; // The function returns a promise that resolves to a validation result message

// Map of service names to their corresponding validator functions
const serviceHandlers: Record<string, ValidatorFunction> = {
snyk_auth_key: validateSnykAuthKey, // Snyk auth key validator
sonarcloud_token: validateSonarcloudToken, // Sonarcloud token validator
// sonarcloud_token: validateSonarcloudToken, // Sonarcloud token validator
npm_access_token: validateNpmAccessToken, // NPM access token validator
// Add additional services and their validators here
};
Expand All @@ -33,14 +36,15 @@ export async function validatorHandleService(
service: string,
secret: string,
response: boolean,
report?: boolean
): Promise<string> {
report: boolean,
isBrowser:boolean = false
): Promise<ValidationResult | {} | ""| undefined> {
// Retrieve the handler function based on the provided service name
const handler = serviceHandlers[service];

if (handler) {
// If a handler exists, call it with the provided parameters
return handler(service, secret, response, report);
return handler(service, secret, response, report, isBrowser);
} else {
// Return an error message if no handler is found for the given service
return `Error: No handler for service '${service}'`;
Expand Down
53 changes: 30 additions & 23 deletions src/js/how2validate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,17 @@ import {
} from "./utility/config_utility.js"; // Importing configuration utility functions
import {
formatString,
getScopedProviders,
getScopedServices,
getSecretProviders,
getSecretscope,
getSecretServices,
updateTool,
validateChoice,
} from "./utility/tool_utility.js"; // Importing utility functions for secret validation
import { validatorHandleService } from "./handler/validator_handler.js"; // Importing the validation handler
import { fileURLToPath } from "url";
import { ValidationResult } from "./utility/validationResult.js";

/**
* Creates a new instance of the Commander program to build the CLI application.
Expand All @@ -36,13 +40,13 @@ program
* Retrieve the list of supported secret providers.
* @type {string[]}
*/
const providerChoices = getSecretProviders();
const providerChoices = getScopedProviders();

/**
* Retrieve the list of supported secret services.
* @type {string[]}
*/
const serviceChoices = getSecretServices();
const serviceChoices = getScopedServices();

/**
* Define CLI options using Commander.
Expand Down Expand Up @@ -76,22 +80,22 @@ program
`Monitor the status. View if your secret ${getActiveSecretStatus()} or ${getInactiveSecretStatus()}.`
)
.option("-report", "Get detailed reports. Receive validated secrets via email [Alpha Feature].", false)
// .option("--update", "Hack the tool to the latest version.");
.option("--update", "Hack the tool to the latest version.");

/**
* Get the list of available providers.
* @returns {string[]} Array of provider names.
*/
export function getProvider(): string[] {
return providerChoices;
export function getProvider(): object {
return getSecretProviders();
}

/**
* Get the list of available services for a given provider.
* @param {string} provider - The provider to get services for.
* @returns {string[]} Array of service names.
*/
export function getService(provider: string): string[] {
export function getService(provider: string): object {
return getSecretServices(undefined, provider);
}

Expand All @@ -113,16 +117,19 @@ export async function validate(
service: string,
secret: string,
response: boolean,
report: boolean
): Promise<void> {
console.info("Started validating secret...");
report: boolean,
isBrowser:boolean = false
): Promise<{} | "" | ValidationResult | undefined> {
// console.info("Started validating secret...");
const result = await validatorHandleService(
formatString(service),
secret,
response,
report
report,
isBrowser
); // Call the handler for validation
console.info(result);
// console.info(result);
return result;
}

/**
Expand Down Expand Up @@ -156,18 +163,18 @@ async function main(): Promise<void> {
}
}

// // Check for the update option
// if (options.update) {
// try {
// console.info("Initiating tool update...");
// await updateTool(); // Call the update function
// console.info("Tool updated successfully.");
// return; // Exit after updating
// } catch (error) {
// console.error(`Error during tool update: ${error}`); // Log any errors
// return;
// }
// }
// Check for the update option
if (options.update) {
try {
console.info("Initiating tool update...");
await updateTool(); // Call the update function
console.info("Tool updated successfully.");
return; // Exit after updating
} catch (error) {
console.error(`Error during tool update: ${error}`); // Log any errors
return;
}
}

// Validate required arguments
if (!options.provider || !options.service || !options.secret) {
Expand Down
26 changes: 26 additions & 0 deletions src/js/how2validate/utility/config_utility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ let config: Config | null = null;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Path to the package.json file
const packageJsonPath = path.resolve(__dirname, "..", "..", "package.json");

/**
* Initializes the configuration by reading the config.ini file.
* This function reads the config file from the provided path or defaults to
Expand Down Expand Up @@ -166,5 +169,28 @@ export function getVersion(): string | undefined {
}
}

/**
* Retrieves the app name from the package.json file.
* If package.json cannot be read, an error message is logged.
*
* @returns {string | undefined} The app name from package.json.
*
* @throws {Error} If the package.json file is not found or cannot be read.
*
* @example
* const appName = getAppName();
* console.log(appName); // Outputs the app name from package.json
*/
export function getAppName(): string {
try {
const packageJsonContent = fs.readFileSync(packageJsonPath, "utf-8");
const packageJson = JSON.parse(packageJsonContent);
return packageJson.appName as string;
} catch (error) {
console.error("Error reading package.json:", error);
return "appName";
}
}

// Automatically initialize config when the file is imported
initConfig();
24 changes: 18 additions & 6 deletions src/js/how2validate/utility/log_utility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
getActiveSecretStatus,
getInactiveSecretStatus,
} from "./config_utility.js";
import { SecretStatusMessage } from "./secretStatusMessage.js";

/**
* Generates a formatted message about the status of a secret.
Expand Down Expand Up @@ -30,28 +31,39 @@ export function getSecretStatusMessage(
isActive: string,
response?: boolean,
responseData?: any
): string {
): SecretStatusMessage {
let state: string | undefined;
let msgData: string;
let resData: string = ""; // Initialize as empty string
let status: string;

// Check if the secret is active or inactive based on the provided status
if (isActive === getActiveSecretStatus()) {
state = getActiveSecretStatus();
status = "active and operational"; // Set status message for active secret
} else if (isActive === getInactiveSecretStatus()) {
state = getInactiveSecretStatus();
status = "inactive and not operational"; // Set status message for inactive secret
} else {
state = `Unexpected isActive value: ${isActive}. Expected 'Active' or 'Inactive'.`;
// Throw an error if the status doesn't match the expected active/inactive values
throw new Error(
`Unexpected isActive value: ${isActive}. Expected 'Active' or 'Inactive'.`
);
}

// Base message about the secret's status
let message = `The provided secret '${service}' is currently ${status}.`;

msgData = `The provided secret '${service}' is currently ${status}.`; // Assign value without redeclaration
// If response data exists, append it to the message
if (responseData) {
message += `\nHere is the additional response data:\n${responseData}`;
if (response) {
resData = `\nHere is the additional response data:\n${responseData}`;
}else{
resData = "";
}

return message; // Return the formatted status message
return {
state: state,
message: msgData,
response: resData, // Ensure it returns the initialized variable
}; // Return the formatted status message
}
10 changes: 10 additions & 0 deletions src/js/how2validate/utility/secretStatusMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @interface SecretStatusMessage
* Represents the structure of a validation result for the Snyk Auth Key.
*/
export interface SecretStatusMessage {
state: string | undefined;
message: string | undefined;
response: string | undefined;
}

Loading

0 comments on commit d77bc1e

Please sign in to comment.