{
  "event.schema.json": {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "urn:cem:webhooks:event:1.0",
    "title": "Evento de webhook de CEM",
    "description": "Cuerpo de cada solicitud de webhook. La entrega es al menos una vez: deduplique por `id` (igual a la cabecera `webhook-id` y estable entre reintentos y reenvíos) y ordene los eventos de un mismo mensaje por `sequence`. Los consumidores deben ignorar las propiedades que no conozcan.",
    "type": "object",
    "required": [
      "id",
      "type",
      "apiVersion",
      "occurredAt",
      "data"
    ],
    "properties": {
      "id": {
        "description": "Identificador único del evento. Es igual a la cabecera `webhook-id`; úselo para deduplicar.",
        "type": "string",
        "minLength": 1,
        "maxLength": 128
      },
      "type": {
        "description": "Tipo de evento; determina la forma de `data`.",
        "$ref": "#/$defs/eventType"
      },
      "apiVersion": {
        "description": "Versión del contrato del evento.",
        "const": "v1"
      },
      "occurredAt": {
        "description": "Instante en que ocurrió el evento, RFC 3339 en UTC.",
        "$ref": "#/$defs/timestamp"
      },
      "trackId": {
        "description": "Mensaje al que pertenece el evento. Presente en los eventos `message.*` y `evidence.*`.",
        "$ref": "#/$defs/trackId"
      },
      "rcptId": {
        "description": "Destinatario del mensaje al que pertenece el evento. Presente en los eventos `message.*` y `evidence.*`.",
        "$ref": "#/$defs/rcptId"
      },
      "clientTrackId": {
        "description": "El `clientTrackId` indicado al enviar el mensaje, cuando lo hubo.",
        "type": "string",
        "maxLength": 128
      },
      "sequence": {
        "description": "Posición del evento entre las transiciones de su mensaje.",
        "type": "integer",
        "minimum": 0
      },
      "data": {
        "description": "Detalles propios del `type` del evento.",
        "type": "object"
      },
      "evidence": {
        "description": "Acuses sellados que respaldan el evento, cuando los hay.",
        "type": "array",
        "items": {
          "$ref": "#/$defs/evidenceRef"
        }
      },
      "metadata": {
        "description": "El `metadata` indicado al enviar el mensaje.",
        "type": "object",
        "additionalProperties": {
          "type": "string"
        }
      }
    },
    "allOf": [
      {
        "if": {
          "properties": {
            "type": {
              "pattern": "^(message|evidence)\\."
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "required": [
            "trackId",
            "rcptId",
            "sequence"
          ]
        }
      },
      {
        "if": {
          "properties": {
            "type": {
              "const": "message.accepted"
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "properties": {
            "data": {
              "$ref": "#/$defs/data/accepted"
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "type": {
              "const": "message.sent"
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "properties": {
            "data": {
              "$ref": "#/$defs/data/sent"
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "type": {
              "const": "message.delivered"
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "properties": {
            "data": {
              "$ref": "#/$defs/data/delivered"
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "type": {
              "const": "message.delayed"
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "properties": {
            "data": {
              "$ref": "#/$defs/data/delayed"
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "type": {
              "const": "message.bounced"
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "properties": {
            "data": {
              "$ref": "#/$defs/data/bounced"
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "type": {
              "const": "message.complained"
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "properties": {
            "data": {
              "$ref": "#/$defs/data/complained"
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "type": {
              "enum": [
                "message.opened",
                "message.clicked",
                "message.read"
              ]
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "properties": {
            "data": {
              "$ref": "#/$defs/data/interaction"
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "type": {
              "const": "message.mdn_received"
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "properties": {
            "data": {
              "$ref": "#/$defs/data/mdnReceived"
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "type": {
              "const": "evidence.sealed"
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "required": [
            "evidence"
          ],
          "properties": {
            "evidence": {
              "minItems": 1
            },
            "data": {
              "$ref": "#/$defs/data/evidenceSealed"
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "type": {
              "const": "evidence.expiring"
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "required": [
            "evidence"
          ],
          "properties": {
            "evidence": {
              "minItems": 1
            },
            "data": {
              "$ref": "#/$defs/data/evidenceExpiring"
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "type": {
              "enum": [
                "tenant.sending_paused",
                "tenant.sending_resumed"
              ]
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "properties": {
            "data": {
              "$ref": "#/$defs/data/tenantSending"
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "type": {
              "enum": [
                "domain.verified",
                "domain.failed"
              ]
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "properties": {
            "data": {
              "$ref": "#/$defs/data/domain"
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "type": {
              "const": "batch.completed"
            }
          },
          "required": [
            "type"
          ]
        },
        "then": {
          "properties": {
            "data": {
              "$ref": "#/$defs/data/batchCompleted"
            }
          }
        }
      }
    ],
    "$defs": {
      "eventType": {
        "enum": [
          "message.accepted",
          "message.sent",
          "message.delivered",
          "message.delayed",
          "message.bounced",
          "message.complained",
          "message.opened",
          "message.clicked",
          "message.read",
          "message.mdn_received",
          "evidence.sealed",
          "evidence.expiring",
          "tenant.sending_paused",
          "tenant.sending_resumed",
          "domain.verified",
          "domain.failed",
          "batch.completed"
        ]
      },
      "timestamp": {
        "description": "Instante RFC 3339 en UTC.",
        "type": "string",
        "format": "date-time",
        "pattern": "Z$"
      },
      "trackId": {
        "type": "string",
        "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "rcptId": {
        "type": "string",
        "pattern": "^r(0|[1-9][0-9]{0,2})$"
      },
      "evidenceId": {
        "type": "string",
        "pattern": "^EV-[0-9A-HJKMNP-TV-Z]{10,26}$"
      },
      "sha256": {
        "type": "string",
        "pattern": "^[0-9a-f]{64}$"
      },
      "receiptType": {
        "enum": [
          "SUBMISSION",
          "DELIVERY",
          "READ",
          "DOWNLOAD",
          "FAILURE",
          "DELAY",
          "OPEN",
          "CLOSURE"
        ]
      },
      "readLevel": {
        "enum": [
          "L0",
          "L1",
          "L2",
          "L3",
          "L4"
        ]
      },
      "recipientStatus": {
        "enum": [
          "ACCEPTED",
          "REJECTED",
          "QUEUED",
          "HELD_FOR_SCAN",
          "SUPPRESSED",
          "ON_HOLD",
          "RENDERED",
          "SENDING",
          "SENT",
          "DELIVERED",
          "DELAYED",
          "BOUNCED",
          "REJECTED_SES",
          "COMPLAINED"
        ]
      },
      "evidenceRef": {
        "type": "object",
        "required": [
          "type",
          "evidenceId",
          "sha256",
          "links"
        ],
        "properties": {
          "type": {
            "$ref": "#/$defs/receiptType"
          },
          "evidenceId": {
            "$ref": "#/$defs/evidenceId"
          },
          "sha256": {
            "description": "Resumen del XML de evidencia firmado.",
            "$ref": "#/$defs/sha256"
          },
          "trustLevel": {
            "enum": [
              "TEST",
              "PRODUCTION"
            ]
          },
          "links": {
            "description": "Dónde obtener cada artefacto. Las URL de la API requieren la clave de API del tenant; `download` es una URL prefirmada válida durante `webhooks.presignedUrlTtlSeconds`.",
            "type": "object",
            "properties": {
              "xml": {
                "type": "string",
                "format": "uri"
              },
              "pdf": {
                "type": "string",
                "format": "uri"
              },
              "eml": {
                "type": "string",
                "format": "uri"
              },
              "asice": {
                "type": "string",
                "format": "uri"
              },
              "download": {
                "type": "string",
                "format": "uri"
              },
              "verify": {
                "type": "string",
                "format": "uri"
              }
            }
          },
          "inline": {
            "description": "El contenedor ASiC-E en sí, cuando es menor que `webhooks.inlineEvidence.maxBytes`.",
            "type": "object",
            "required": [
              "mediaType",
              "contentBase64"
            ],
            "properties": {
              "mediaType": {
                "const": "application/vnd.etsi.asic-e+zip"
              },
              "contentBase64": {
                "type": "string",
                "contentEncoding": "base64",
                "minLength": 1
              }
            }
          }
        }
      },
      "data": {
        "accepted": {
          "type": "object",
          "required": [
            "status"
          ],
          "properties": {
            "status": {
              "const": "ACCEPTED"
            },
            "channel": {
              "enum": [
                "API",
                "SMTP_SUFFIX"
              ]
            }
          }
        },
        "sent": {
          "type": "object",
          "required": [
            "status"
          ],
          "properties": {
            "status": {
              "const": "SENT"
            },
            "possibleDuplicate": {
              "type": "boolean"
            }
          }
        },
        "delivered": {
          "type": "object",
          "required": [
            "status",
            "smtpResponse"
          ],
          "properties": {
            "status": {
              "const": "DELIVERED"
            },
            "smtpResponse": {
              "description": "Respuesta literal del servidor de correo del destinatario.",
              "type": "string"
            },
            "remoteMtaIp": {
              "type": "string"
            },
            "reportingMta": {
              "type": "string"
            },
            "processingTimeMs": {
              "type": "integer",
              "minimum": 0
            }
          }
        },
        "delayed": {
          "type": "object",
          "required": [
            "status"
          ],
          "properties": {
            "status": {
              "const": "DELAYED"
            },
            "delayType": {
              "type": "string"
            },
            "expirationTime": {
              "$ref": "#/$defs/timestamp"
            }
          }
        },
        "bounced": {
          "type": "object",
          "required": [
            "status",
            "bounceType"
          ],
          "properties": {
            "status": {
              "const": "BOUNCED"
            },
            "bounceType": {
              "enum": [
                "Permanent",
                "Transient",
                "Undetermined"
              ]
            },
            "bounceSubType": {
              "type": "string"
            },
            "diagnosticCode": {
              "description": "Diagnóstico literal del servidor remoto.",
              "type": "string"
            },
            "suppressed": {
              "description": "La dirección se agregó a la lista de supresión.",
              "type": "boolean"
            }
          }
        },
        "complained": {
          "type": "object",
          "required": [
            "status"
          ],
          "properties": {
            "status": {
              "const": "COMPLAINED"
            },
            "feedbackType": {
              "type": "string"
            }
          }
        },
        "interaction": {
          "type": "object",
          "required": [
            "level",
            "classification",
            "classifierVersion"
          ],
          "properties": {
            "level": {
              "$ref": "#/$defs/readLevel"
            },
            "classification": {
              "enum": [
                "MACHINE_PREFETCH",
                "SECURITY_SCANNER",
                "PROXY_OPEN",
                "CONFIRMED_OPEN",
                "HUMAN",
                "HUMAN_CONFIRMED"
              ]
            },
            "classifierVersion": {
              "description": "Versión de las reglas que produjeron la clasificación.",
              "type": "string"
            },
            "linkIndex": {
              "type": "integer",
              "minimum": 0
            },
            "url": {
              "type": "string",
              "format": "uri"
            }
          }
        },
        "mdnReceived": {
          "type": "object",
          "required": [
            "disposition",
            "actionMode",
            "sendingMode",
            "authStrength"
          ],
          "properties": {
            "disposition": {
              "enum": [
                "displayed",
                "deleted",
                "denied",
                "processed",
                "dispatched",
                "failed"
              ]
            },
            "actionMode": {
              "enum": [
                "manual-action",
                "automatic-action"
              ]
            },
            "sendingMode": {
              "enum": [
                "MDN-sent-manually",
                "MDN-sent-automatically"
              ]
            },
            "authStrength": {
              "enum": [
                "STRONG",
                "WEAK"
              ]
            },
            "addressMode": {
              "enum": [
                "TOKEN",
                "SHARED"
              ]
            },
            "gesture": {
              "enum": [
                "MANUAL",
                "AUTOMATIC"
              ]
            },
            "level": {
              "$ref": "#/$defs/readLevel"
            },
            "classification": {
              "const": "CONFIRMED_OPEN"
            },
            "reportingUa": {
              "type": "string"
            },
            "finalRecipient": {
              "type": "string"
            },
            "originalMessageId": {
              "type": "string"
            },
            "mdnMessageId": {
              "type": "string"
            },
            "mdnSha256": {
              "$ref": "#/$defs/sha256"
            }
          }
        },
        "evidenceSealed": {
          "type": "object",
          "description": "Se emite cuando se sella un acuse. Si recibe `evidence.sealed` con `status: TSA_PENDING`, recibirá otro evento `evidence.sealed` (mismo `evidenceId`, nuevo `id` de evento) con `status: SEALED` una vez que se complete el sello de tiempo RFC 3161.",
          "required": [
            "status"
          ],
          "properties": {
            "status": {
              "enum": [
                "SEALED",
                "TSA_PENDING"
              ],
              "description": "Estado del sellado. Si recibe `evidence.sealed` con `TSA_PENDING`, recibirá otro `evidence.sealed` con `SEALED` cuando termine el sellado de tiempo."
            },
            "upgradedFrom": {
              "enum": [
                "TSA_PENDING"
              ],
              "description": "Presente cuando este evento promueve a `SEALED` un acuse emitido antes como `TSA_PENDING`."
            },
            "receiptKey": {
              "description": "Clave principal de acuse que satisface este acuse acumulativo (por ejemplo, `DELIVERY`, `READ#L3`, `OPEN#MDN`).",
              "type": "string",
              "minLength": 1
            },
            "satisfies": {
              "description": "Todas las claves de acuse que satisface este acuse acumulativo.",
              "type": "array",
              "items": {
                "type": "string",
                "minLength": 1
              },
              "minItems": 1
            },
            "covers": {
              "description": "Identificadores de evento cubiertos por primera vez por este acuse (incluidos los eventos que solo constan en el libro mayor).",
              "type": "array",
              "items": {
                "type": "string",
                "minLength": 1
              },
              "minItems": 1
            },
            "coveredSeq": {
              "description": "Mayor secuencia de eventos por destinatario (`evtSeq`) cubierta por este acuse.",
              "type": "integer",
              "minimum": 0
            },
            "signed": {
              "description": "`false` cuando se emitió como un registro informativo sin firma (`constancia sin firma`).",
              "type": "boolean"
            },
            "timestamp": {
              "description": "Modo de sellado de tiempo aplicado a este acuse (`NONE`, `BATCH` o `INDIVIDUAL`), o metadatos del token RFC 3161.",
              "oneOf": [
                {
                  "enum": [
                    "NONE",
                    "BATCH",
                    "INDIVIDUAL"
                  ]
                },
                {
                  "type": "object",
                  "required": [
                    "providerId",
                    "genTime"
                  ],
                  "properties": {
                    "mode": {
                      "enum": [
                        "NONE",
                        "BATCH",
                        "INDIVIDUAL"
                      ]
                    },
                    "providerId": {
                      "type": "string",
                      "minLength": 1
                    },
                    "genTime": {
                      "$ref": "#/$defs/timestamp"
                    }
                  }
                }
              ]
            },
            "chain": {
              "description": "Posición y referencias de este acuse acumulativo dentro de la cadena del destinatario.",
              "type": "object",
              "required": [
                "position",
                "coveredSeq",
                "headEvidenceId",
                "final"
              ],
              "properties": {
                "position": {
                  "type": "integer",
                  "minimum": 1
                },
                "coveredSeq": {
                  "type": "integer",
                  "minimum": 0
                },
                "previousEvidenceId": {
                  "oneOf": [
                    {
                      "$ref": "#/$defs/evidenceId"
                    },
                    {
                      "type": "null"
                    }
                  ]
                },
                "headEvidenceId": {
                  "$ref": "#/$defs/evidenceId"
                },
                "final": {
                  "type": "boolean"
                }
              }
            }
          }
        },
        "evidenceExpiring": {
          "type": "object",
          "required": [
            "expiresAt"
          ],
          "properties": {
            "expiresAt": {
              "description": "Los artefactos se purgan, como pronto, en este instante.",
              "$ref": "#/$defs/timestamp"
            }
          }
        },
        "tenantSending": {
          "type": "object",
          "required": [
            "breakerState"
          ],
          "properties": {
            "breakerState": {
              "enum": [
                "CLOSED",
                "THROTTLED",
                "OPEN",
                "HALF_OPEN"
              ]
            },
            "reason": {
              "type": "string"
            },
            "bounceRate": {
              "type": "number",
              "minimum": 0,
              "maximum": 1
            },
            "complaintRate": {
              "type": "number",
              "minimum": 0,
              "maximum": 1
            },
            "heldRecipients": {
              "type": "integer",
              "minimum": 0
            }
          }
        },
        "domain": {
          "type": "object",
          "required": [
            "domain",
            "status"
          ],
          "properties": {
            "domain": {
              "type": "string",
              "format": "hostname"
            },
            "status": {
              "enum": [
                "ACTIVE",
                "FAILED"
              ]
            },
            "reason": {
              "enum": [
                "dkim_verification_failed",
                "dns_verification_timeout",
                "ses_identity_missing"
              ]
            },
            "verifiedAt": {
              "type": "string",
              "format": "date-time"
            },
            "failedAt": {
              "type": "string",
              "format": "date-time"
            },
            "diagnostic": {
              "type": "string"
            }
          }
        },
        "batchCompleted": {
          "type": "object",
          "required": [
            "batchId",
            "status",
            "total",
            "accepted",
            "rejected"
          ],
          "properties": {
            "batchId": {
              "type": "string",
              "minLength": 1
            },
            "status": {
              "enum": [
                "COMPLETED",
                "FAILED",
                "CANCELED"
              ]
            },
            "total": {
              "type": "integer",
              "minimum": 0
            },
            "accepted": {
              "type": "integer",
              "minimum": 0
            },
            "rejected": {
              "type": "integer",
              "minimum": 0
            },
            "unprocessed": {
              "type": "integer",
              "minimum": 0
            },
            "name": {
              "type": "string"
            }
          }
        }
      }
    }
  },
  "headers.schema.json": {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "urn:cem:webhooks:headers:1.0",
    "title": "Cabeceras de solicitud de webhook de CEM",
    "description": "Cabeceras de cada solicitud de webhook (esquema Standard Webhooks, nombres de cabecera en minúscula). La firma es `v1,` seguida de base64(HMAC-SHA256(secret, `{webhook-id}.{webhook-timestamp}.{raw body}`)). Mientras se rota un secreto, la cabecera lleva una firma por cada secreto activo, separadas por espacios; acepte la solicitud si alguna coincide. Rechace las solicitudes cuya marca de tiempo esté más lejos de la hora actual que `webhooks.signature.toleranceSeconds`.",
    "type": "object",
    "required": [
      "webhook-id",
      "webhook-timestamp",
      "webhook-signature",
      "content-type"
    ],
    "properties": {
      "webhook-id": {
        "description": "Igual al `id` del cuerpo; estable entre reintentos y reenvíos.",
        "type": "string",
        "minLength": 1,
        "maxLength": 128
      },
      "webhook-timestamp": {
        "description": "Segundos desde la época Unix en el momento de este intento.",
        "type": "string",
        "pattern": "^[1-9][0-9]{9,10}$"
      },
      "webhook-signature": {
        "description": "Una o más firmas `v1,` separadas por espacios; consulte la descripción de este esquema para ver cómo se construyen.",
        "type": "string",
        "pattern": "^v1,[A-Za-z0-9+/]{43}=( v1,[A-Za-z0-9+/]{43}=)*$"
      },
      "content-type": {
        "description": "Siempre `application/json`.",
        "const": "application/json"
      },
      "user-agent": {
        "description": "Identifica a la plataforma como remitente.",
        "type": "string"
      }
    }
  }
}
