| 1 | import axios from "axios"; |
| 2 | import chalk from "chalk"; |
| 3 | import { Command } from "commander"; |
| 4 | import path from "node:path"; |
| 5 | import { |
| 6 | getConfig, |
| 7 | getInstantiatedVirtualResourceName, |
| 8 | getVirtualResourceName, |
| 9 | } from "./config.js"; |
| 10 | import { logger } from "./log.js"; |
| 11 | import { |
| 12 | buildLegalRegistrationNumberVC, |
| 13 | buildParticipantVC, |
| 14 | buildTermsConditionsVC, |
| 15 | writeDIDFile, |
| 16 | } from "./participant.js"; |
| 17 | import { buildOpenAPIResources, buildServiceOffering } from "./service.js"; |
| 18 | import { buildVerifiablePresentation, joinUrl, writeFile } from "./utils.js"; |
| 19 | import { validateCertificate, isEVSSL, checkTrustAnchor } from "./certificate-validator.js"; |
| 20 | import { generateSelfDescription } from "./self-description-generator.js"; |
| 21 | import { getLetsEncryptCert } from "./letsencrypt.js"; |
| 22 | import { generateComplianceReport } from "./report-generator.js"; |
| 23 | import { analyzeComplianceError } from './ai/AIAnalyzer.js'; |
| 24 | import { analyzeAnyError } from './ai/AIAnalyzer.js'; |
| 25 | |
| 26 | export async function signCredentials({ verifiableCredentials }) { |
| 27 | const config = getConfig(); |
| 28 | |
| 29 | const verifiablePresentation = buildVerifiablePresentation({ |
| 30 | verifiableCredentials, |
| 31 | }); |
| 32 | |
| 33 | logger.info("Sending Verifiable Presentation to Compliance API"); |
| 34 | logger.info(`POST -> ${config.urlAPICompliance}`); |
| 35 | logger.debug(verifiablePresentation); |
| 36 | |
| 37 | try { |
| 38 | const res = await axios.post( |
| 39 | config.urlAPICompliance, |
| 40 | verifiablePresentation |
| 41 | ); |
| 42 | |
| 43 | logger.info(chalk.green("✅ Compliance success")); |
| 44 | logger.debug(res.data); |
| 45 | |
| 46 | return res.data; |
| 47 | } catch (err) { |
| 48 | logger.error(chalk.red("🔴 Compliance error")); |
| 49 | const errMsg = (err.response && err.response.data) || err; |
| 50 | logger.error(errMsg); |
| 51 | throw new Error(`Error in Compliance API request: ${JSON.stringify(errMsg)}`); |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | async function actionCredentials(options) { |
| 56 | try { |
| 57 | if (!options.apiSpec) { |
| 58 | throw new Error(chalk.red("Es necesario especificar la ruta a la especificación OpenAPI/AsyncAPI usando --api-spec")); |
| 59 | } |
| 60 | |
| 61 | const config = getConfig(); |
| 62 | |
| 63 | // Validar certificado |
| 64 | logger.info("Validating trust anchor certificate..."); |
| 65 | const certInfo = await validateCertificate(options.cert || config.cert); |
| 66 | |
| 67 | if (!isEVSSL(certInfo)) { |
| 68 | if (!options.allowNonEVSSL) { |
| 69 | throw new Error(chalk.red("Certificate is not from an EV-SSL authority. Use --allow-non-evssl to override.")); |
| 70 | } |
| 71 | logger.warn(chalk.yellow("⚠️ Warning: Using non-EV-SSL certificate")); |
| 72 | } |
| 73 | |
| 74 | // Verificar emisor conocido |
| 75 | const trustAnchorStatus = await checkTrustAnchor(certInfo); |
| 76 | if (trustAnchorStatus.knownIssuer && !trustAnchorStatus.compatible) { |
| 77 | logger.warn(chalk.yellow(`⚠️ Known issuer ${trustAnchorStatus.issuer} has compatibility issues with GXDCH`)); |
| 78 | } |
| 79 | |
| 80 | // Generar Self-Description desde OpenAPI/AsyncAPI |
| 81 | logger.info("Generating Self-Description from API specification..."); |
| 82 | const selfDescription = await generateSelfDescription({ |
| 83 | apiSpec: config.openAPISpec, |
| 84 | type: "OpenAPI", // o "AsyncAPI" |
| 85 | didIssuer: config.didWebId, |
| 86 | certInfo |
| 87 | }); |
| 88 | |
| 89 | logger.info("Building Participant Verifiable Credential"); |
| 90 | const vcParticipant = await buildParticipantVC(); |
| 91 | logger.debug(vcParticipant); |
| 92 | |
| 93 | logger.info("Building Legal Registration Number Verifiable Credential"); |
| 94 | const vcLRN = await buildLegalRegistrationNumberVC(); |
| 95 | logger.debug(vcLRN); |
| 96 | |
| 97 | logger.info("Building Terms and Conditions Verifiable Credential"); |
| 98 | const vcTC = await buildTermsConditionsVC(); |
| 99 | logger.debug(vcTC); |
| 100 | |
| 101 | logger.info("Building Verifiable Credentials for Resources"); |
| 102 | |
| 103 | const virtResourceName = getVirtualResourceName({ |
| 104 | openAPISpec: config.openAPISpec, |
| 105 | }); |
| 106 | |
| 107 | const instVirtResourceName = getInstantiatedVirtualResourceName({ |
| 108 | openAPISpec: config.openAPISpec, |
| 109 | }); |
| 110 | |
| 111 | const virtResourceUrl = joinUrl(config.baseUrl, `${virtResourceName}.json`); |
| 112 | |
| 113 | const instVirtResourceUrl = joinUrl( |
| 114 | config.baseUrl, |
| 115 | `${instVirtResourceName}.json` |
| 116 | ); |
| 117 | |
| 118 | const virtResourceWritePath = path.join( |
| 119 | config.webserverDir, |
| 120 | `${virtResourceName}.json` |
| 121 | ); |
| 122 | |
| 123 | const instVirtResourceWritePath = path.join( |
| 124 | config.webserverDir, |
| 125 | `${instVirtResourceName}.json` |
| 126 | ); |
| 127 | |
| 128 | const { instantiatedVirtualResource: vcIVR, virtualResource: vcVR } = |
| 129 | await buildOpenAPIResources({ |
| 130 | openAPIUrl: config.openAPISpec, |
| 131 | didIssuer: config.didWebId, |
| 132 | participantUrl: config.urlParticipant, |
| 133 | virtResourceUrl, |
| 134 | virtResourceWritePath, |
| 135 | instVirtResourceUrl, |
| 136 | instVirtResourceWritePath, |
| 137 | }); |
| 138 | |
| 139 | logger.debug(vcIVR); |
| 140 | logger.debug(vcVR); |
| 141 | |
| 142 | logger.info("Building Verifiable Credential for Service Offering"); |
| 143 | |
| 144 | const vcSO = await buildServiceOffering({ |
| 145 | didIssuer: config.didWebId, |
| 146 | legalParticipantUrl: config.urlParticipant, |
| 147 | termsConditionsUrl: config.urlTermsConditions, |
| 148 | serviceOfferingUrl: config.urlServiceOffering, |
| 149 | serviceOfferingWritePath: config.pathServiceOffering, |
| 150 | aggregatedResourceUrls: [virtResourceUrl], |
| 151 | }); |
| 152 | |
| 153 | logger.debug(vcSO); |
| 154 | |
| 155 | const verifiableCredentials = [vcParticipant, vcLRN, vcTC, vcSO]; |
| 156 | |
| 157 | const vcCompliance = await signCredentials({ |
| 158 | verifiableCredentials, |
| 159 | }); |
| 160 | |
| 161 | const vpResult = buildVerifiablePresentation({ |
| 162 | verifiableCredentials: [ |
| 163 | ...verifiableCredentials, |
| 164 | vcCompliance, |
| 165 | vcVR, |
| 166 | vcIVR, |
| 167 | ], |
| 168 | }); |
| 169 | |
| 170 | logger.info( |
| 171 | `Writing resulting Verifiable Presentation to ${config.pathVerifiablePresentation}` |
| 172 | ); |
| 173 | |
| 174 | await writeFile(config.pathVerifiablePresentation, vpResult); |
| 175 | |
| 176 | // Añadir validación final |
| 177 | const isValid = await validateCompliance(vpResult); |
| 178 | if (!isValid) { |
| 179 | logger.warn(chalk.yellow("⚠️ Se detectaron problemas en la validación final")); |
| 180 | |
| 181 | const errorReport = await analyzeComplianceError(vpResult); |
| 182 | |
| 183 | logger.error("Informe de IA sobre incumplimiento GAIA-X:"); |
| 184 | logger.error(errorReport.summary); |
| 185 | logger.error("Soluciones recomendadas:"); |
| 186 | errorReport.solutions.forEach(solution => { |
| 187 | logger.info(`- ${solution}`); |
| 188 | }); |
| 189 | |
| 190 | // Guardar análisis detallado |
| 191 | const errorReportPath = path.join(config.webserverDir, "gaiax-error-analysis.md"); |
| 192 | await writeFile(errorReportPath, `# GAIA-X Compliance Error Analysis |
| 193 | |
| 194 | ${errorReport.detailedAnalysis} |
| 195 | |
| 196 | ## Recomendaciones |
| 197 | ${errorReport.solutions.map(sol => `- ${sol}`).join('\n')} |
| 198 | |
| 199 | ## Análisis LLM Completo |
| 200 | ${errorReport.rawLLMResponse} |
| 201 | `); |
| 202 | |
| 203 | logger.info(chalk.yellow(`Análisis detallado guardado en: ${errorReportPath}`)); |
| 204 | throw new Error("La validación final no cumple con los estándares GAIA-X"); |
| 205 | } |
| 206 | |
| 207 | if (isValid) { |
| 208 | logger.info(chalk.green("✅ Self-Description validation successful")); |
| 209 | |
| 210 | // Generar informe detallado |
| 211 | const report = await generateComplianceReport({ |
| 212 | verifiablePresentation: vpResult, |
| 213 | selfDescription, |
| 214 | outputFiles: { |
| 215 | vp: config.pathVerifiablePresentation, |
| 216 | serviceOffering: config.pathServiceOffering, |
| 217 | virtualResource: virtResourceWritePath, |
| 218 | instantiatedResource: instVirtResourceWritePath |
| 219 | }, |
| 220 | apiSpec: config.openAPISpec |
| 221 | }); |
| 222 | |
| 223 | // Mostrar informe |
| 224 | logger.info(chalk.blue("\n📋 GAIA-X Compliance Report")); |
| 225 | logger.info("========================="); |
| 226 | |
| 227 | logger.info(chalk.yellow("\n📑 Generated Files:")); |
| 228 | report.files.forEach(file => { |
| 229 | logger.info(`- ${chalk.cyan(file.path)}: ${file.description}`); |
| 230 | }); |
| 231 | |
| 232 | logger.info(chalk.yellow("\n🔍 Service Details:")); |
| 233 | logger.info(`- Service Name: ${report.service.name}`); |
| 234 | logger.info(`- Version: ${report.service.version}`); |
| 235 | logger.info(`- Endpoints: ${report.service.endpoints.length}`); |
| 236 | |
| 237 | logger.info(chalk.yellow("\n✨ Extended Attributes:")); |
| 238 | report.extendedAttributes.forEach(attr => { |
| 239 | logger.info(`- ${chalk.cyan(attr.name)}: ${attr.value}`); |
| 240 | logger.info(` ${chalk.gray(attr.description)}`); |
| 241 | }); |
| 242 | |
| 243 | logger.info(chalk.yellow("\n📌 Next Steps:")); |
| 244 | report.nextSteps.forEach((step, index) => { |
| 245 | logger.info(`${index + 1}. ${step}`); |
| 246 | }); |
| 247 | |
| 248 | // Guardar informe en archivo |
| 249 | const reportPath = path.join(config.webserverDir, "gaiax-report.md"); |
| 250 | await writeFile(reportPath, report.toMarkdown()); |
| 251 | logger.info(chalk.green(`\n✅ Full report saved to: ${reportPath}`)); |
| 252 | } |
| 253 | } catch (error) { |
| 254 | logger.error(chalk.red("🔴 Error en el proceso de credenciales")); |
| 255 | |
| 256 | // Analizar el error con IA |
| 257 | const errorAnalysis = await analyzeAnyError(error, { |
| 258 | options, |
| 259 | config: getConfig(), |
| 260 | context: 'actionCredentials' |
| 261 | }); |
| 262 | |
| 263 | // Mostrar análisis del error |
| 264 | logger.error(chalk.red("\n🤖 Análisis de IA del error:")); |
| 265 | logger.error(chalk.yellow("Explicación:")); |
| 266 | logger.error(errorAnalysis.analysis.explanation); |
| 267 | |
| 268 | logger.error(chalk.yellow("\nPasos a seguir:")); |
| 269 | errorAnalysis.analysis.nextSteps.forEach((step, index) => { |
| 270 | logger.error(`${index + 1}. ${step}`); |
| 271 | }); |
| 272 | |
| 273 | logger.error(chalk.yellow("\nPrevención:")); |
| 274 | errorAnalysis.analysis.prevention.forEach(tip => { |
| 275 | logger.error(`- ${tip}`); |
| 276 | }); |
| 277 | |
| 278 | logger.error(chalk.yellow("\nRecursos útiles:")); |
| 279 | errorAnalysis.analysis.resources.forEach(resource => { |
| 280 | logger.error(`- ${resource}`); |
| 281 | }); |
| 282 | |
| 283 | // Guardar análisis detallado en archivo |
| 284 | const errorReportPath = path.join(process.cwd(), "gaiax-error-analysis.md"); |
| 285 | await writeFile(errorReportPath, `# GAIA-X Error Analysis |
| 286 | |
| 287 | ## Error |
| 288 | ${errorAnalysis.error} |
| 289 | |
| 290 | ## Explicación |
| 291 | ${errorAnalysis.analysis.explanation} |
| 292 | |
| 293 | ## Pasos a seguir |
| 294 | ${errorAnalysis.analysis.nextSteps.map(step => `- ${step}`).join('\n')} |
| 295 | |
| 296 | ## Prevención |
| 297 | ${errorAnalysis.analysis.prevention.map(tip => `- ${tip}`).join('\n')} |
| 298 | |
| 299 | ## Recursos |
| 300 | ${errorAnalysis.analysis.resources.map(resource => `- ${resource}`).join('\n')} |
| 301 | |
| 302 | ## Análisis completo |
| 303 | \`\`\` |
| 304 | ${errorAnalysis.rawLLMResponse} |
| 305 | \`\`\` |
| 306 | `); |
| 307 | |
| 308 | logger.info(chalk.yellow(`\nAnálisis detallado guardado en: ${errorReportPath}`)); |
| 309 | process.exit(1); |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | async function validateCompliance(verifiablePresentation) { |
| 314 | try { |
| 315 | const config = getConfig(); |
| 316 | const response = await axios.post( |
| 317 | `${config.urlAPICompliance}/validate`, |
| 318 | verifiablePresentation |
| 319 | ); |
| 320 | return response.data.isValid; |
| 321 | } catch (error) { |
| 322 | logger.error("Error en la validación de compliance"); |
| 323 | return false; |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | const program = new Command(); |
| 328 | |
| 329 | program |
| 330 | .name("gaiax-credentials-cli") |
| 331 | .description("CLI for automatic generation of Gaia-X Self-Descriptions") |
| 332 | .version("0.1.0"); |
| 333 | |
| 334 | program |
| 335 | .command("credentials") |
| 336 | .description("Build and sign Gaia-X Self-Descriptions") |
| 337 | .requiredOption("--api-spec <path>", "Path to OpenAPI/AsyncAPI specification") |
| 338 | .option("-c, --cert <path>", "Path to trust anchor certificate") |
| 339 | .option("-k, --key <path>", "Path to private key") |
| 340 | .option("--allow-non-evssl", "Allow non-EV-SSL certificates") |
| 341 | .option("--gxdch <url>", "GXDCH instance URL", "https://compliance.gaia-x.aire.es") |
| 342 | .action(actionCredentials); |
| 343 | |
| 344 | program |
| 345 | .command("generate-cert") |
| 346 | .description("Generate Let's Encrypt certificate for testing") |
| 347 | .option("-d, --domain <domain>", "Domain for certificate") |
| 348 | .action(async (options) => { |
| 349 | try { |
| 350 | const cert = await getLetsEncryptCert(options.domain); |
| 351 | logger.info(chalk.green("✅ Certificate generated successfully")); |
| 352 | logger.info(`Certificate saved to: ${cert.path}`); |
| 353 | } catch (error) { |
| 354 | logger.error(chalk.red("🔴 Error generating certificate")); |
| 355 | |
| 356 | // Analizar el error con IA |
| 357 | const errorAnalysis = await analyzeAnyError(error, { |
| 358 | options, |
| 359 | context: 'generate-cert' |
| 360 | }); |
| 361 | |
| 362 | // Mostrar análisis |
| 363 | logger.error(chalk.yellow("\nAnálisis del error:")); |
| 364 | logger.error(errorAnalysis.analysis.explanation); |
| 365 | logger.error("\nPasos sugeridos:"); |
| 366 | errorAnalysis.analysis.nextSteps.forEach((step, index) => { |
| 367 | logger.error(`${index + 1}. ${step}`); |
| 368 | }); |
| 369 | } |
| 370 | }); |
| 371 | |
| 372 | program.parse(); |