Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 397x 397x 397x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 204x 204x 204x 204x 204x 204x 204x 204x 1x 1x 1x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 193x 193x 193x 193x 193x 215x 215x 215x 215x 215x 215x 63x 63x 63x 152x 152x 152x 157x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 150x 150x 150x 150x 215x 193x 193x 193x 193x 193x 193x 193x 193x 193x 11x 11x 11x 11x 11x 11x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 11x 11x 11x 11x 11x 11x 11x 193x 193x 193x 193x 193x 193x 11x 11x 178x 178x 11x 11x 11x | import path from 'node:path';
import { z } from 'zod';
import { readJsonSync, writeJson } from '../lib/fs.js';
import { Logger } from '../logger.js';
import { getConfigPath } from './paths.js';
const OverridesSchema = z.object({
API_HOST: z.string().url().optional(),
CONSOLE_URL: z.string().url().optional(),
AUTH_BRIDGE_HOST: z.string().url().optional(),
SSH_GATEWAY: z.string().optional(),
OAUTH_CONSUMER_KEY: z.string().optional(),
OAUTH_CONSUMER_SECRET: z.string().optional(),
});
const ProfileSchema = z.object({
alias: z.string(),
token: z.string(),
secret: z.string(),
expirationDate: z.string().optional(),
userId: z.string().optional(),
email: z.string().optional(),
overrides: OverridesSchema.optional(),
});
/** @typedef {z.infer<typeof ProfileSchema>} Profile */
const LegacyConfigFileSchema = z.object({
token: z.string(),
secret: z.string(),
expirationDate: z.string().optional(),
});
/** @typedef {z.infer<typeof LegacyConfigFileSchema>} LegacyConfigFile */
const ConfigFileSchema = z.object({
version: z.literal(1),
profiles: z.array(ProfileSchema).default([]),
});
/** @typedef {z.infer<typeof ConfigFileSchema>} ConfigFile */
const ConfigSchema = z
.object({
CONFIGURATION_FILE: z.string().default(() => getConfigPath('clever-tools.json')),
EXPERIMENTAL_FEATURES_FILE: z.string().default(() => getConfigPath('clever-tools-experimental-features.json')),
IDS_CACHE_FILE: z.string().default(() => getConfigPath('ids-cache.json')),
APP_CONFIGURATION_FILE: z.string().default(() => path.resolve('.', '.clever.json')),
API_HOST: z.url().default('https://api.clever-cloud.com'),
AUTH_BRIDGE_HOST: z.url().default('https://api-bridge.clever-cloud.com'),
SSH_GATEWAY: z.string().default('ssh@sshgateway-clevercloud-customers.services.clever-cloud.com'),
// The disclosure of these tokens is not considered as a vulnerability.
// Do not report this to our security service.
OAUTH_CONSUMER_KEY: z.string().default('T5nFjKeHH4AIlEveuGhB5S3xg8T19e'),
OAUTH_CONSUMER_SECRET: z.string().default('MgVMqTr6fWlf2M0tkC2MXOnhfqBWDT'),
API_DOC_URL: z.url().default('https://www.clever.cloud/developers/api'),
DOC_URL: z.url().default('https://www.clever.cloud/developers/doc'),
CONSOLE_URL: z.url().default('https://console.clever-cloud.com'),
// Default values are computed from `CONSOLE_URL` below
CONSOLE_TOKEN_URL: z.url().optional(),
GOTO_URL: z.url().optional(),
token: z.string().optional(),
secret: z.string().optional(),
expirationDate: z.string().optional(),
profiles: z.array(ProfileSchema).default([]),
})
.transform((config) => ({
...config,
CONSOLE_TOKEN_URL: config.CONSOLE_TOKEN_URL ?? `${config.CONSOLE_URL}/cli-oauth`,
GOTO_URL: config.GOTO_URL ?? `${config.CONSOLE_URL}/goto`,
}));
/**
* Base configuration: environment variables + Zod schema defaults, without any profile overrides.
* Use this as fallback when operating on a specific profile (login, profile list)
* to avoid being affected by the active profile's overrides.
*/
export const baseConfig = loadBaseConfig();
/**
* @returns {z.output<typeof ConfigSchema>}
*/
function loadBaseConfig() {
const result = ConfigSchema.safeParse(process.env);
if (!result.success) {
const errors = result.error.issues.map((issue) => `- ${issue.path.join('.')}: ${issue.message}`).join('\n');
Logger.error(`Invalid configuration:\n${errors}`);
process.exit(1);
}
return result.data;
}
/**
* The complete configuration object, loaded synchronously at startup.
* Priority: environment variables > active profile overrides > Zod schema defaults.
*/
export const config = loadConfig();
/**
* @returns {z.output<typeof ConfigSchema>}
*/
function loadConfig() {
Logger.debug(`Load configuration from ${baseConfig.CONFIGURATION_FILE}`);
const configFromFile = loadConfigFile();
// If CLEVER_TOKEN and CLEVER_SECRET are set, inject a virtual "$env" profile as the active one
const profiles =
process.env.CLEVER_TOKEN != null && process.env.CLEVER_SECRET != null
? [
{ alias: '$env', token: process.env.CLEVER_TOKEN, secret: process.env.CLEVER_SECRET },
...configFromFile.profiles,
]
: configFromFile.profiles;
const activeProfile = profiles[0];
/** @type {z.input<typeof ConfigSchema>} */
const rawConfig = {
...activeProfile,
// Profile overrides (e.g. custom API_HOST) applied after profile auth data, before env vars
...activeProfile?.overrides,
profiles,
...process.env,
};
const result = ConfigSchema.safeParse(rawConfig);
if (!result.success) {
const errors = result.error.issues.map((issue) => `- ${issue.path.join('.')}: ${issue.message}`).join('\n');
Logger.error(`Invalid configuration:\n${errors}`);
process.exit(1);
}
return result.data;
}
/**
* Reads and parses the config file, handling both current and legacy formats.
* @returns {ConfigFile}
*/
function loadConfigFile() {
const data = readJsonSync(baseConfig.CONFIGURATION_FILE);
// Try parsing as current format
const result = ConfigFileSchema.safeParse(data);
if (result.success) {
Logger.debug('Loaded config file with current format');
return result.data;
}
// Try parsing as legacy format
const legacyResult = LegacyConfigFileSchema.safeParse(data);
if (legacyResult.success) {
Logger.debug('Loaded config file with legacy format, converting to profile');
const legacyConfig = legacyResult.data;
return {
version: 1,
profiles: [
{
alias: 'default',
token: legacyConfig.token,
secret: legacyConfig.secret,
expirationDate: legacyConfig.expirationDate,
},
],
};
}
// No valid config found
Logger.debug('No valid config file found, using empty config');
return { version: 1, profiles: [] };
}
/**
* Saves a profile to the configuration.
* If a profile with the same alias exists, it is replaced.
* The saved profile becomes the active profile (first in the list).
* @param {Profile} profile
* @returns {Promise<void>}
*/
export async function saveProfile(profile) {
const configFile = loadConfigFile();
const otherProfiles = configFile.profiles.filter((p) => p.alias !== profile.alias);
// Always put the active profile in the first position
configFile.profiles = [profile, ...otherProfiles];
await updateConfigFile(configFile);
}
/**
* Removes a profile by alias and returns the new active profile (if any).
* @param {string} alias
* @returns {Promise<Profile | null>}
*/
export async function removeProfile(alias) {
const configFile = loadConfigFile();
configFile.profiles = configFile.profiles.filter((p) => p.alias !== alias);
await updateConfigFile(configFile);
return configFile.profiles[0] ?? null;
}
/**
* Writes the configuration to the config file and reloads the in-memory config.
* @param {ConfigFile} newConfig - The new configuration to persist
* @returns {Promise<void>}
*/
async function updateConfigFile(newConfig) {
Logger.debug('Write the new config in the configuration fileā¦');
try {
await writeJson(baseConfig.CONFIGURATION_FILE, newConfig, { mode: 0o700 });
reloadConfig();
} catch (error) {
throw new Error(`Cannot write configuration to ${baseConfig.CONFIGURATION_FILE}\n${error.message}`);
}
}
/**
* Reloads the configuration from file and updates the config object in place.
* This ensures all modules referencing the config object see the updated values.
*/
export function reloadConfig() {
const mutableConfig = /** @type {Record<string, unknown>} */ (config);
for (const key of Object.keys(mutableConfig)) {
delete mutableConfig[key];
}
const newConfig = loadConfig();
Object.assign(config, newConfig);
}
|