Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Dependencias y artefactos
node_modules
dist
.git
.github
*.log

# Secretos
.env
.env.*
!.env.example
!.env.production.example

# Base de datos local
pgdata
51 changes: 27 additions & 24 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,36 +1,39 @@
# ============================================================
# Backend Xupply / Hackathon - Variables de entorno
# Copia este archivo a .env y ajusta los valores.
# ============================================================

PORT=4000

# Base de datos PostgreSQL (local o en la nube: Neon, Render, Supabase...)
DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/xupply

# Obligatorio en produccion (el servidor no arranca sin esto fuera de desarrollo).
# Genera uno con:
DATABASE_URL=postgres://postgres:postgres@localhost:5432/xupply
# Obligatorio. Genera uno con:
# node -e "console.log(require('crypto').randomBytes(48).toString('hex'))"
JWT_SECRET=change-me-to-a-long-random-value

# Lista blanca de origenes permitidos (CORS HTTP + Socket.IO), separados por coma.
# Si se deja vacio se permite cualquier origen (solo recomendado en desarrollo).
JWT_EXPIRES_IN=12h
CLIENT_ORIGIN=http://localhost:5173

# Notificaciones por email (EmailJS) - opcional
# --- Correo transaccional ---
# En local puedes dejarlo vacío: los correos se omiten sin romper la app.
MAIL_PROVIDER=
MAIL_FROM=
MAIL_FROM_NAME=Xupply
MAIL_REPLY_TO=
MAIL_BCC=
APP_URL=http://localhost:5173
MAIL_COMPANY_NAME=Xupply
MAIL_COMPANY_ADDRESS=Bucaramanga, Santander, Colombia

# SMTP empresarial
# SMTP_HOST=smtp.gmail.com
# SMTP_PORT=587
# SMTP_SECURE=false
# SMTP_USER=tu-correo@tudominio.com
# SMTP_PASS=tu-contrasena-de-aplicacion

# Resend (alternativa)
# RESEND_API_KEY=re_...

# EmailJS (legacy)
EMAILJS_SERVICE_ID=
EMAILJS_TEMPLATE_ID=
EMAILJS_PUBLIC_KEY=
EMAILJS_PRIVATE_KEY=

# Agente XupAI (DeepSeek) - opcional
# La clave puede ir en XUPAI_API_KEY, DEEPSEEK_API_KEY u OPENAI_API_KEY.
XUPAI_API_KEY=
DEEPSEEK_API_KEY=
# Agente XupAI (DeepSeek)
DEEPSEEK_API_KEY=sk-your-deepseek-api-key
XUPAI_MODEL=deepseek-chat
XUPAI_BASE_URL=https://api.deepseek.com

# Notas:
# - En Vercel tambien se detectan automaticamente POSTGRES_URL, POSTGRES_URL_NON_POOLING,
# POSTGRES_PRISMA_URL y las variables POSTGRES_HOST/USER/PASSWORD/DATABASE.
# - PGSSLMODE=require fuerza SSL si tu proveedor lo necesita.
77 changes: 77 additions & 0 deletions .env.production.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# ============================================================
# Xupply Backend - variables de entorno para PRODUCCIÓN
# Copia este archivo a .env.production (nunca lo subas al repo).
# Genera secretos con: openssl rand -base64 48
# ============================================================

NODE_ENV=production
DOMAIN=xupply.example.com
PORT=4420

# --- PostgreSQL ---
POSTGRES_DB=xupply
POSTGRES_USER=xupply
POSTGRES_PASSWORD=CAMBIA_ESTA_CONTRASENA_LARGA
# Docker Compose: host "db". Render/Vercel/Neon/Supabase: usa la URL que te den.
DATABASE_URL=postgres://xupply:CAMBIA_ESTA_CONTRASENA_LARGA@db:5432/xupply

# --- Autenticación ---
# Obligatorio. El servidor se niega a arrancar en producción sin este valor.
JWT_SECRET=CAMBIA_ESTE_SECRETO_POR_UNO_ALEATORIO_DE_64_CARACTERES
JWT_EXPIRES_IN=12h

# Origen(es) permitidos para CORS, separados por coma. Sin esto, en producción
# no se acepta ningún origen cruzado (fail-closed).
CLIENT_ORIGIN=https://xupply.example.com

# --- Bootstrap del administrador ---
# Solo se usa la primera vez, cuando la base de datos no tiene usuarios.
# La contraseña debe tener 12+ caracteres. Elimina estas variables después.
ADMIN_USERNAME=admin
ADMIN_PASSWORD=CAMBIA_ESTA_CONTRASENA_DE_ADMIN

# NUNCA activar en producción: crea usuarios demo con contraseñas conocidas.
SEED_DEMO_DATA=false

# --- Agente XupAI (opcional) ---
# Opción 1: DeepSeek (recomendado)
DEEPSEEK_API_KEY=sk-your-deepseek-api-key
XUPAI_MODEL=deepseek-chat
XUPAI_BASE_URL=https://api.deepseek.com

# Opción 2: variable genérica
# XUPAI_API_KEY=sk-your-deepseek-or-openai-key

# --- Correo transaccional enterprise ---
# Rellena estos valores con datos reales: los placeholders no envían correo.
# smtp | resend | emailjs (vacío = autodetección)
MAIL_PROVIDER=smtp
# Usa SIEMPRE un dominio corporativo verificado. Nunca gmail.com/hotmail.com en producción.
MAIL_FROM=notificaciones@tudominio.com
MAIL_FROM_NAME=Xupply
# Bandeja de entrada enterprise que recibe las respuestas de los clientes.
MAIL_REPLY_TO=soporte@tudominio.com
# Copia oculta de auditoría (opcional, recomendado en enterprise).
MAIL_BCC=auditoria@tudominio.com
APP_URL=https://tudominio.com
MAIL_COMPANY_NAME=Xupply
MAIL_COMPANY_ADDRESS=Bucaramanga, Santander, Colombia

# SMTP empresarial (Google Workspace, Microsoft 365, Amazon SES, Zoho...)
# Google Workspace: smtp.gmail.com:587 con contraseña de aplicación.
# Microsoft 365: smtp.office365.com:587 (requiere SMTP AUTH habilitado).
# Amazon SES: email-smtp.<region>.amazonaws.com:587 con credenciales SMTP.
SMTP_HOST=smtp.tudominio.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=notificaciones@tudominio.com
SMTP_PASS=CAMBIA_ESTA_CONTRASENA

# Alternativa recomendada: Resend (DKIM/SPF gestionados, HTTPS sin problemas en serverless)
# RESEND_API_KEY=re_xxxxxxxxx

# EmailJS (legacy, solo si no usas SMTP/Resend)
EMAILJS_SERVICE_ID=
EMAILJS_TEMPLATE_ID=
EMAILJS_PUBLIC_KEY=
EMAILJS_PRIVATE_KEY=
41 changes: 41 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
name: CI

on:
push:
branches: [main, master, Backend]
pull_request:
workflow_dispatch:

permissions:
contents: read

concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true

jobs:
build-and-test:
name: Typecheck, build y auditoría
runs-on: ubuntu-latest
timeout-minutes: 15

steps:
- name: Checkout
uses: actions/checkout@v4

- name: Node 20
uses: actions/setup-node@v4
with:
node-version: 20

- name: Instalar dependencias
run: npm ci --no-audit --no-fund

- name: Typecheck
run: npm run typecheck

- name: Build
run: npm run build

- name: Auditar dependencias de producción
run: npm audit --omit=dev --audit-level=high
31 changes: 29 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,31 @@
# Secrets and local configuration
.env
.env.production
.env.*.local
*.local

# Dependencies and generated output
node_modules/
dist/
.env
*.log
*.tsbuildinfo

# Local databases and runtime files
pgdata/
pg.log
*.pid
*.log

# IDE and OS files
.vscode/
.idea/
.DS_Store
Thumbs.db

# Android releases and keystores
dist-apk/
release-manual/
*.jks
*.apk

# Docker local
docker-compose.override.yml
25 changes: 25 additions & 0 deletions Caddyfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{$DOMAIN} {
encode zstd gzip

# Cabeceras de seguridad. La CSP se aplica aquí (borde) además de helmet,
# para defensa en profundidad.
header {
-Server
-X-Powered-By
Content-Security-Policy "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self' https: wss:; manifest-src 'self'; worker-src 'self' blob:; upgrade-insecure-requests"
X-Content-Type-Options "nosniff"
X-Frame-Options "DENY"
Referrer-Policy "strict-origin-when-cross-origin"
Permissions-Policy "camera=(), microphone=(), payment=(), usb=(), geolocation=(self)"
Cross-Origin-Opener-Policy "same-origin"
Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
}

# Socket.IO necesita el upgrade de WebSocket: reverse_proxy lo soporta por defecto.
reverse_proxy app:4420 {
header_up X-Real-IP {remote_host}
health_uri /health
health_interval 30s
health_timeout 5s
}
}
41 changes: 41 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# syntax=docker/dockerfile:1

# ---------- Build (TypeScript -> dist) ----------
FROM node:20-bookworm-slim AS build
WORKDIR /app

COPY package*.json ./
RUN npm ci --no-audit --no-fund

COPY tsconfig*.json index.ts index.js ./
COPY src ./src

RUN npm run build

# ---------- Dependencias de producción (sin devDependencies) ----------
FROM node:20-bookworm-slim AS prod-deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev --no-audit --no-fund

# ---------- Runtime ----------
FROM node:20-bookworm-slim AS runtime
ENV NODE_ENV=production \
PORT=4420
WORKDIR /app

COPY --from=prod-deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY --from=build /app/package.json ./package.json
COPY --from=build /app/index.js ./index.js

# Ejecutar como usuario sin privilegios (node:node, uid/gid 1000).
USER node

EXPOSE 4420
STOPSIGNAL SIGTERM

HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||4420)+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"

CMD ["node", "dist/server.js"]
Loading
Loading