package httpapi import ( "crypto/rand" "encoding/hex" "encoding/json" "errors" "fmt" "net/http" "strings" "time" "cotizador/internal/audit" "cotizador/internal/auth" "cotizador/internal/db" "cotizador/internal/webhooks" "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5" ) func (s *Server) handleAgentKeysList(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"}); !ok { return } rows, err := s.Pool.Query(r.Context(), ` SELECT "id", "nombre", "prefijo", "scopes", "rateLimitPerMin", "activo", "revokedAt", "lastUsedAt", "createdById", "createdAt", "updatedAt" FROM "AgentApiKey" ORDER BY "createdAt" DESC `) if err != nil { writeError(w, http.StatusInternalServerError, "Error listando claves de agente") return } defer rows.Close() keys := []map[string]any{} for rows.Next() { var id, nombre, prefijo string var scopes []string var rateLimit int var activo bool var revokedAt, lastUsedAt *time.Time var createdByID *string var createdAt, updatedAt time.Time if rows.Scan(&id, &nombre, &prefijo, &scopes, &rateLimit, &activo, &revokedAt, &lastUsedAt, &createdByID, &createdAt, &updatedAt) == nil { keys = append(keys, map[string]any{ "id": id, "nombre": nombre, "prefijo": prefijo, "scopes": scopes, "rateLimitPerMin": rateLimit, "activo": activo, "revokedAt": revokedAt, "lastUsedAt": lastUsedAt, "createdById": createdByID, "createdAt": createdAt, "updatedAt": updatedAt, }) } } writeJSON(w, http.StatusOK, map[string]any{"data": keys, "scopesDisponibles": auth.AgentScopes}) } func (s *Server) handleAgentKeysCreate(w http.ResponseWriter, r *http.Request) { actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"}) if !ok { return } var body struct { Nombre string `json:"nombre"` Scopes []string `json:"scopes"` RateLimitPerMin *int `json:"rateLimitPerMin"` } if err := decodeJSON(r, &body); err != nil { writeError(w, http.StatusBadRequest, "JSON invalido") return } nombre := strings.TrimSpace(body.Nombre) if nombre == "" || len(body.Scopes) == 0 { writeError(w, http.StatusBadRequest, "nombre y scopes son requeridos") return } for _, sc := range body.Scopes { if !auth.IsValidScope(sc) { writeError(w, http.StatusBadRequest, fmt.Sprintf("Scope invalido o no permitido: %s", sc)) return } } rl := 60 if body.RateLimitPerMin != nil { rl = *body.RateLimitPerMin if rl < 1 || rl > 1000 { writeError(w, http.StatusBadRequest, "rateLimitPerMin debe estar entre 1 y 1000") return } } rawKey, prefijo, keyHash := auth.GenerateAPIKey() id := db.NewID() _, err := s.Pool.Exec(r.Context(), ` INSERT INTO "AgentApiKey" ("id", "nombre", "prefijo", "keyHash", "scopes", "rateLimitPerMin", "activo", "createdById", "createdAt", "updatedAt") VALUES ($1, $2, $3, $4, $5, $6, true, $7, NOW(), NOW()) `, id, nombre, prefijo, keyHash, body.Scopes, rl, actor.UserID) if err != nil { if strings.Contains(err.Error(), "duplicate") || strings.Contains(err.Error(), "23505") { writeError(w, http.StatusConflict, "Ya existe una clave con ese nombre") return } writeError(w, http.StatusInternalServerError, "Error creando clave de agente") return } tipo, aid, anom := actor.AuditActor() audit.Registrar(r.Context(), s.Pool, audit.Entry{ ActorTipo: tipo, ActorID: aid, ActorNombre: anom, Accion: "agent_key.crear", RecursoTipo: "agent_key", RecursoID: id, IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, Detalle: map[string]any{"nombre": nombre, "scopes": body.Scopes, "rateLimitPerMin": rl}, }) writeJSON(w, http.StatusCreated, map[string]any{ "id": id, "nombre": nombre, "prefijo": prefijo, "rawKey": rawKey, "scopes": body.Scopes, "rateLimitPerMin": rl, "activo": true, }) } func (s *Server) handleAgentKeysRotate(w http.ResponseWriter, r *http.Request) { actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"}) if !ok { return } id := chi.URLParam(r, "id") rawKey, prefijo, keyHash := auth.GenerateAPIKey() var nombre string err := s.Pool.QueryRow(r.Context(), ` UPDATE "AgentApiKey" SET "prefijo" = $1, "keyHash" = $2, "activo" = true, "revokedAt" = NULL, "updatedAt" = NOW() WHERE "id" = $3 RETURNING "nombre" `, prefijo, keyHash, id).Scan(&nombre) if err != nil { if errors.Is(err, pgx.ErrNoRows) { writeError(w, http.StatusNotFound, "Clave no encontrada") return } writeError(w, http.StatusInternalServerError, "Error rotando clave") return } tipo, aid, anom := actor.AuditActor() audit.Registrar(r.Context(), s.Pool, audit.Entry{ ActorTipo: tipo, ActorID: aid, ActorNombre: anom, Accion: "agent_key.rotar", RecursoTipo: "agent_key", RecursoID: id, IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, Detalle: map[string]any{"nombre": nombre, "prefijo": prefijo}, }) writeJSON(w, http.StatusOK, map[string]any{ "id": id, "nombre": nombre, "prefijo": prefijo, "rawKey": rawKey, "activo": true, }) } func (s *Server) handleAgentKeysRevoke(w http.ResponseWriter, r *http.Request) { actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"}) if !ok { return } id := chi.URLParam(r, "id") var nombre string err := s.Pool.QueryRow(r.Context(), ` UPDATE "AgentApiKey" SET "activo" = false, "revokedAt" = NOW(), "updatedAt" = NOW() WHERE "id" = $1 RETURNING "nombre" `, id).Scan(&nombre) if err != nil { if errors.Is(err, pgx.ErrNoRows) { writeError(w, http.StatusNotFound, "Clave no encontrada") return } writeError(w, http.StatusInternalServerError, "Error revocando clave") return } tipo, aid, anom := actor.AuditActor() audit.Registrar(r.Context(), s.Pool, audit.Entry{ ActorTipo: tipo, ActorID: aid, ActorNombre: anom, Accion: "agent_key.revocar", RecursoTipo: "agent_key", RecursoID: id, IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, Detalle: map[string]any{"nombre": nombre}, }) writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "activo": false}) } func (s *Server) handleAuditLogs(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "audit_log"}); !ok { return } q := r.URL.Query() page := parseIntQuery(r, "page", 1, 1, 10000) limit := parseIntQuery(r, "limit", 50, 1, 200) offset := (page - 1) * limit conds := []string{"1=1"} args := []any{} addArg := func(v any) string { args = append(args, v) return fmt.Sprintf("$%d", len(args)) } if v := strings.TrimSpace(q.Get("accion")); v != "" { conds = append(conds, `"accion" = `+addArg(v)) } if v := strings.TrimSpace(q.Get("actorNombre")); v != "" { conds = append(conds, `"actorNombre" ILIKE `+addArg("%"+v+"%")) } if v := strings.TrimSpace(q.Get("recursoId")); v != "" { conds = append(conds, `"recursoId" = `+addArg(v)) } whereSQL := strings.Join(conds, " AND ") var total int _ = s.Pool.QueryRow(r.Context(), `SELECT COUNT(*) FROM "AuditLog" WHERE `+whereSQL, args...).Scan(&total) limArg := addArg(limit) offArg := addArg(offset) rows, err := s.Pool.Query(r.Context(), ` SELECT "id", "actorTipo", "actorId", "actorNombre", "accion", "recursoTipo", "recursoId", "ip", "requestId", "exito", "detalle", "createdAt" FROM "AuditLog" WHERE `+whereSQL+` ORDER BY "createdAt" DESC LIMIT `+limArg+` OFFSET `+offArg, args...) if err != nil { writeError(w, http.StatusInternalServerError, "Error consultando auditoria") return } defer rows.Close() data := []map[string]any{} for rows.Next() { var id, actorTipo, actorNombre, accion, recursoTipo string var actorID, recursoID, ip, reqID *string var exito bool var detalle []byte var createdAt time.Time if rows.Scan(&id, &actorTipo, &actorID, &actorNombre, &accion, &recursoTipo, &recursoID, &ip, &reqID, &exito, &detalle, &createdAt) == nil { var det any if len(detalle) > 0 { _ = json.Unmarshal(detalle, &det) } data = append(data, map[string]any{ "id": id, "actorTipo": actorTipo, "actorId": actorID, "actorNombre": actorNombre, "accion": accion, "recursoTipo": recursoTipo, "recursoId": recursoID, "ip": ip, "requestId": reqID, "exito": exito, "detalle": det, "createdAt": createdAt, }) } } writeJSON(w, http.StatusOK, map[string]any{ "data": data, "meta": map[string]any{"total": total, "page": page, "limit": limit}, }) } func (s *Server) handleWebhooksList(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"}); !ok { return } rows, err := s.Pool.Query(r.Context(), ` SELECT "id", "nombre", "url", "eventos", "activo", "createdAt", "updatedAt" FROM "WebhookEndpoint" ORDER BY "createdAt" DESC `) if err != nil { writeError(w, http.StatusInternalServerError, "Error listando webhooks") return } defer rows.Close() list := []map[string]any{} for rows.Next() { var id, nombre, urlStr string var eventos []string var activo bool var createdAt, updatedAt time.Time if rows.Scan(&id, &nombre, &urlStr, &eventos, &activo, &createdAt, &updatedAt) == nil { list = append(list, map[string]any{ "id": id, "nombre": nombre, "url": urlStr, "eventos": eventos, "activo": activo, "createdAt": createdAt, "updatedAt": updatedAt, }) } } writeJSON(w, http.StatusOK, map[string]any{"data": list, "eventosDisponibles": webhooks.EventosOficiales}) } func (s *Server) handleWebhooksCreate(w http.ResponseWriter, r *http.Request) { actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"}) if !ok { return } var body struct { Nombre string `json:"nombre"` URL string `json:"url"` Secret string `json:"secret"` Eventos []string `json:"eventos"` } if err := decodeJSON(r, &body); err != nil { writeError(w, http.StatusBadRequest, "JSON invalido") return } nombre := strings.TrimSpace(body.Nombre) urlStr := strings.TrimSpace(body.URL) if nombre == "" || urlStr == "" || len(body.Eventos) == 0 { writeError(w, http.StatusBadRequest, "nombre, url y eventos son requeridos") return } for _, ev := range body.Eventos { if !webhooks.EsEventoValido(ev) { writeError(w, http.StatusBadRequest, fmt.Sprintf("Evento invalido: %s", ev)) return } } secret := strings.TrimSpace(body.Secret) if secret == "" { var b [24]byte _, _ = rand.Read(b[:]) secret = "whsec_" + hex.EncodeToString(b[:]) } id := db.NewID() _, err := s.Pool.Exec(r.Context(), ` INSERT INTO "WebhookEndpoint" ("id", "nombre", "url", "secret", "eventos", "activo", "createdAt", "updatedAt") VALUES ($1, $2, $3, $4, $5, true, NOW(), NOW()) `, id, nombre, urlStr, secret, body.Eventos) if err != nil { if strings.Contains(err.Error(), "23505") || strings.Contains(err.Error(), "duplicate") { writeError(w, http.StatusConflict, "Ya existe un webhook con ese nombre") return } writeError(w, http.StatusInternalServerError, "Error creando webhook") return } tipo, aid, anom := actor.AuditActor() audit.Registrar(r.Context(), s.Pool, audit.Entry{ ActorTipo: tipo, ActorID: aid, ActorNombre: anom, Accion: "webhook.crear", RecursoTipo: "webhook", RecursoID: id, IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, Detalle: map[string]any{"nombre": nombre, "url": urlStr, "eventos": body.Eventos}, }) writeJSON(w, http.StatusCreated, map[string]any{ "id": id, "nombre": nombre, "url": urlStr, "secret": secret, "eventos": body.Eventos, "activo": true, }) } func (s *Server) handleWebhooksDelete(w http.ResponseWriter, r *http.Request) { actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"}) if !ok { return } id := chi.URLParam(r, "id") tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "WebhookEndpoint" WHERE "id" = $1`, id) if err != nil || tag.RowsAffected() == 0 { writeError(w, http.StatusNotFound, "Webhook no encontrado") return } tipo, aid, anom := actor.AuditActor() audit.Registrar(r.Context(), s.Pool, audit.Entry{ ActorTipo: tipo, ActorID: aid, ActorNombre: anom, Accion: "webhook.eliminar", RecursoTipo: "webhook", RecursoID: id, IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, }) writeJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (s *Server) handleWebhooksDeliveries(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"}); !ok { return } q := r.URL.Query() limit := parseIntQuery(r, "limit", 50, 1, 200) conds := []string{"1=1"} args := []any{} if ev := strings.TrimSpace(q.Get("evento")); ev != "" { args = append(args, ev) conds = append(conds, fmt.Sprintf(`"evento" = $%d`, len(args))) } if eid := strings.TrimSpace(q.Get("endpointId")); eid != "" { args = append(args, eid) conds = append(conds, fmt.Sprintf(`"endpointId" = $%d`, len(args))) } args = append(args, limit) rows, err := s.Pool.Query(r.Context(), fmt.Sprintf(` SELECT "id", "endpointId", "url", "evento", "payload", "statusCode", "exito", "intentos", "error", "createdAt" FROM "WebhookDelivery" WHERE %s ORDER BY "createdAt" DESC LIMIT $%d `, strings.Join(conds, " AND "), len(args)), args...) if err != nil { writeError(w, http.StatusInternalServerError, "Error consultando entregas de webhooks") return } defer rows.Close() list := []map[string]any{} for rows.Next() { var id, urlStr, evento string var endpointID, errStr *string var payload []byte var statusCode *int var exito bool var intentos int var createdAt time.Time if rows.Scan(&id, &endpointID, &urlStr, &evento, &payload, &statusCode, &exito, &intentos, &errStr, &createdAt) == nil { var p any _ = json.Unmarshal(payload, &p) list = append(list, map[string]any{ "id": id, "endpointId": endpointID, "url": urlStr, "evento": evento, "payload": p, "statusCode": statusCode, "exito": exito, "intentos": intentos, "error": errStr, "createdAt": createdAt, }) } } writeJSON(w, http.StatusOK, map[string]any{"data": list}) } var configAllowedKeys = map[string]bool{ "razon_social": true, "rfc": true, "domicilio_fiscal": true, "banco_nacional": true, "cuenta_nacional": true, "clabe_interbancaria": true, "clabe_nacional": true, "banco_internacional": true, "cuenta_internacional": true, "cuenta_internacional_swift": true, "swift": true, "routing_number": true, "hora_centinela": true, "anualidad_hosting": true, "iva": true, "terminos_condiciones": true, "no_incluye": true, "notas_adicionales": true, "nota_legal": true, "color_primario": true, "color_secundario": true, "logo_base64": true, "email_facturacion": true, "telefono_contacto": true, } func (s *Server) handleConfiguracionGet(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "configuracion"}); !ok { return } writeJSON(w, http.StatusOK, s.getAllConfigMap(r.Context())) } func (s *Server) handleConfiguracionPut(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "configuracion"}); !ok { return } var body map[string]string if err := decodeJSON(r, &body); err != nil { writeError(w, http.StatusBadRequest, "JSON invalido") return } for k, v := range body { if !configAllowedKeys[k] { continue } _, err := s.Pool.Exec(r.Context(), ` INSERT INTO "Configuracion" ("id", "clave", "valor", "updatedAt") VALUES ($1, $2, $3, NOW()) ON CONFLICT ("clave") DO UPDATE SET "valor" = EXCLUDED."valor", "updatedAt" = NOW() `, db.NewID(), k, v) if err != nil { writeError(w, http.StatusInternalServerError, "Error guardando configuracion") return } } writeJSON(w, http.StatusOK, s.getAllConfigMap(r.Context())) }