@miguelmorales13/nestkit 0.31.4 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +234 -0
- package/dist/chunk-2RQINZCR.cjs +17 -0
- package/dist/{chunk-LU3HO7B3.js → chunk-3WISEIHK.js} +4 -15
- package/dist/chunk-HMHUOXGB.cjs +63 -0
- package/dist/chunk-L2QK2HN5.js +17 -0
- package/dist/chunk-PBAPT3L5.js +63 -0
- package/dist/chunk-QVLTEABJ.cjs +248 -0
- package/dist/chunk-XKI3DJVA.js +248 -0
- package/dist/{chunk-33KFVAUZ.cjs → chunk-ZBOQKXGZ.cjs} +7 -18
- package/dist/payments/index.cjs +6 -5
- package/dist/payments/index.js +2 -1
- package/dist/resilience/index.cjs +48 -262
- package/dist/resilience/index.js +19 -233
- package/dist/security/index.cjs +4 -2
- package/dist/security/index.js +5 -3
- package/dist/telephony/adapters/meta-whatsapp.telephony.d.ts +21 -0
- package/dist/telephony/adapters/simulated.telephony.d.ts +49 -0
- package/dist/telephony/adapters/twilio.telephony.d.ts +54 -0
- package/dist/telephony/index.cjs +2269 -0
- package/dist/telephony/index.d.ts +20 -0
- package/dist/telephony/index.js +2269 -0
- package/dist/telephony/provider-http.d.ts +35 -0
- package/dist/telephony/relay/access.d.ts +72 -0
- package/dist/telephony/relay/backend.d.ts +81 -0
- package/dist/telephony/relay/index.cjs +483 -0
- package/dist/telephony/relay/index.d.ts +9 -0
- package/dist/telephony/relay/index.js +483 -0
- package/dist/telephony/relay/server.d.ts +89 -0
- package/dist/telephony/relay/session.d.ts +100 -0
- package/dist/telephony/rules/call-limits.d.ts +48 -0
- package/dist/telephony/rules/call-token.d.ts +30 -0
- package/dist/telephony/rules/destination-policy.d.ts +21 -0
- package/dist/telephony/rules/dial-destination.d.ts +21 -0
- package/dist/telephony/rules/event-deduper.d.ts +15 -0
- package/dist/telephony/rules/handoff.d.ts +7 -0
- package/dist/telephony/rules/index.d.ts +20 -0
- package/dist/telephony/rules/opt-out.d.ts +32 -0
- package/dist/telephony/rules/phone.d.ts +9 -0
- package/dist/telephony/rules/provider-gate.d.ts +31 -0
- package/dist/telephony/rules/redact.d.ts +11 -0
- package/dist/telephony/rules/sanitize.d.ts +10 -0
- package/dist/telephony/rules/sliding-window.d.ts +10 -0
- package/dist/telephony/rules/ttl-cache.d.ts +14 -0
- package/dist/telephony/rules/usage-counter.d.ts +16 -0
- package/dist/telephony/telephony.errors.d.ts +46 -0
- package/dist/telephony/telephony.facade.d.ts +71 -0
- package/dist/telephony/telephony.module.d.ts +38 -0
- package/dist/telephony/telephony.options.d.ts +187 -0
- package/dist/telephony/telephony.port.d.ts +421 -0
- package/dist/telephony/telephony.registry.d.ts +24 -0
- package/dist/telephony/telephony.webhook.controller.d.ts +22 -0
- package/dist/telephony/telephony.webhooks.d.ts +53 -0
- package/dist/whatsapp/index.cjs +28 -0
- package/dist/whatsapp/index.js +28 -0
- package/dist/whatsapp/whatsapp-client.d.ts +5 -0
- package/package.json +12 -2
package/README.md
CHANGED
|
@@ -1407,6 +1407,238 @@ await facturacion.issue({
|
|
|
1407
1407
|
- **El complemento de pago** se emite como un CFDI `type: 'P'`, pero el módulo no modela sus campos:
|
|
1408
1408
|
para eso, por ahora, se usa el adaptador directo.
|
|
1409
1409
|
|
|
1410
|
+
### `telephony` — números, llamadas, SMS, WhatsApp y uso, con el proveedor como configuración
|
|
1411
|
+
|
|
1412
|
+
Todo el ciclo de telefonía detrás de **un solo puerto** (`TelephonyAdapter`, versión 1) y una fachada, `Telephony`, que
|
|
1413
|
+
es lo único que inyecta tu proyecto. Cada proveedor implementa **solo las capacidades que soporta**; nada del puerto
|
|
1414
|
+
menciona a Twilio ni a nadie. Qué dice la IA, qué cuesta, qué plan lo incluye o qué menú lee **no va aquí**: eso es de
|
|
1415
|
+
cada app (entra por *ganchos*, abajo).
|
|
1416
|
+
|
|
1417
|
+
| Capacidad | Qué cubre | Twilio | Meta WhatsApp | Simulado |
|
|
1418
|
+
|---|---|:-:|:-:|:-:|
|
|
1419
|
+
| `numbers` | buscar por país/tipo/lada/ciudad, comprar, configurar, listar (paginado), soltar, transferir, trámites regulatorios, renta mensual | ✅ | — | ✅ |
|
|
1420
|
+
| `voice` | contestar (relay con IA, desvío, rechazo, colgar), llamada saliente, llamada de prueba, estado/duración/minutos cobrables | ✅ | — | ✅ |
|
|
1421
|
+
| `sms` | enviar, consultar, recibir, estado, baja (STOP/BAJA) | ✅ | — | ✅ |
|
|
1422
|
+
| `whatsapp` | texto, plantillas, recibir, estado | ✅ (vía Twilio) | ✅ (Cloud API directa) | ✅ |
|
|
1423
|
+
| `usage` | consumo y costo del proveedor por categoría, periodo y número | ✅ | — | ✅ |
|
|
1424
|
+
| `webhooks` | firma, eventos normalizados, idempotencia | ✅ | ✅ | ✅ |
|
|
1425
|
+
|
|
1426
|
+
La librería **no cobra ni calcula márgenes**: te da el consumo y el costo del proveedor (`usage`) y ganchos para que
|
|
1427
|
+
tú pongas tus topes y tu precio.
|
|
1428
|
+
|
|
1429
|
+
```ts
|
|
1430
|
+
TelephonyModule.forRoot({ provider: 'twilio' }) // lee TWILIO_*
|
|
1431
|
+
TelephonyModule.forRoot({ provider: 'simulated' }) // sin red, sin costo
|
|
1432
|
+
TelephonyModule.forRoot(
|
|
1433
|
+
{ provider: 'twilio', fallbacks: ['simulated'], channels: { whatsapp: 'meta-whatsapp' }, metaWhatsApp: { client } },
|
|
1434
|
+
{ hooks: MisGanchos }, // resolveTenant / onEvent de tu negocio
|
|
1435
|
+
)
|
|
1436
|
+
```
|
|
1437
|
+
|
|
1438
|
+
| Variable | Para qué |
|
|
1439
|
+
|---|---|
|
|
1440
|
+
| `TELEPHONY_PROVIDER`, `TELEPHONY_FALLBACKS` | proveedor principal y respaldos (lista separada por comas) |
|
|
1441
|
+
| `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN` | credenciales de la cuenta |
|
|
1442
|
+
| `TWILIO_BUNDLE_SID`, `TWILIO_ADDRESS_SID` | **los números de México los exigen**: un *Regulatory Bundle* aprobado y una dirección; los crea y aprueba una persona en la consola de Twilio |
|
|
1443
|
+
| `TWILIO_AREA_CODE`, `TWILIO_WHATSAPP_FROM` | lada por omisión (Twilio exige que sea de la zona de la dirección del Bundle) y línea de WhatsApp |
|
|
1444
|
+
|
|
1445
|
+
#### Integración mínima en NestJS
|
|
1446
|
+
|
|
1447
|
+
```ts
|
|
1448
|
+
// telefonia.ganchos.ts — lo único de tu negocio que la librería necesita saber
|
|
1449
|
+
@Injectable()
|
|
1450
|
+
export class TelefoniaGanchos implements TelephonyHooks {
|
|
1451
|
+
constructor(private readonly lineas: LineasService, private readonly ia: ContestadorService) {}
|
|
1452
|
+
|
|
1453
|
+
resolveTenant(numero: string) { return this.lineas.dueñoDe(numero); } // null = línea sin dueño: se ignora
|
|
1454
|
+
|
|
1455
|
+
async onEvent(e: TelephonyEvent) {
|
|
1456
|
+
if (e.type === 'llamada.entrante') {
|
|
1457
|
+
const token = signCallToken({ callId: e.callId, tenantId: e.tenantId!, actorId: 'system' }, SECRETO);
|
|
1458
|
+
return { kind: 'relay', url: `wss://voz.miapp.com/relay?k=${RELAY_SECRET}`, greeting: 'Hola, gracias por llamar.',
|
|
1459
|
+
actionUrl: `${API}/voz/accion`, parameters: { t: token } }; // cómo contestar
|
|
1460
|
+
}
|
|
1461
|
+
if (e.type === 'llamada.terminada') await this.lineas.registrarConsumo(e.tenantId!, e.billableMinutes);
|
|
1462
|
+
if (e.type === 'sms.recibido' && !e.keyword) await this.ia.atender(e); // la baja ya quedó registrada
|
|
1463
|
+
}
|
|
1464
|
+
onError(error: unknown) { /* tu logger: nunca viaja al proveedor */ }
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
// app.module.ts
|
|
1468
|
+
@Module({
|
|
1469
|
+
imports: [TelephonyModule.forRoot({ provider: 'twilio' }, { hooks: TelefoniaGanchos, imports: [LineasModule] })],
|
|
1470
|
+
controllers: [createTelephonyWebhookController({ publicBaseUrl: 'https://api.miapp.com' })], // POST /telephony/webhooks/:provider[/:tenantId]
|
|
1471
|
+
})
|
|
1472
|
+
export class AppModule {}
|
|
1473
|
+
|
|
1474
|
+
// en cualquier servicio
|
|
1475
|
+
constructor(private readonly tel: Telephony) {}
|
|
1476
|
+
const numero = await this.tel.numbers.provision({ voiceUrl: `${API}/telephony/webhooks/twilio`, label: 'miapp-ab12' });
|
|
1477
|
+
await this.tel.sms.send({ from: numero!.number, to: '+5215512345678', body: 'Tu pedido va en camino' });
|
|
1478
|
+
const [uso] = await this.tel.usage.query({ category: 'voice', from: '2026-01-01', to: '2026-02-01', number: numero!.number });
|
|
1479
|
+
```
|
|
1480
|
+
|
|
1481
|
+
La app se crea con `NestFactory.create(AppModule, { rawBody: true })` si recibirás webhooks de Meta (firman el cuerpo).
|
|
1482
|
+
El controlador devuelve `response.body` con su `Content-Type` (Twilio lee el XML desde el primer byte; el sobre
|
|
1483
|
+
`{ success, data }` lo rompe).
|
|
1484
|
+
|
|
1485
|
+
#### Las capacidades
|
|
1486
|
+
|
|
1487
|
+
| `tel.` | Método | Notas |
|
|
1488
|
+
|---|---|---|
|
|
1489
|
+
| `numbers` | `search`, `requirements`, `monthlyCost`, `provision`, `configure`, `get`, `list`, `release`, `transfer?` | `provision` devuelve `null` **solo sin inventario** (no se cobra); cualquier otra falla lanza. `idempotencyKey` = un reintento tras un corte no compra dos. `release` es idempotente |
|
|
1490
|
+
| `voice` | `buildAnswer`, `placeCall`, `placeTestCall`, `getCall` | intención (`relay` · `dial` · `reject` · `hangup`), no TwiML: cada adaptador la traduce. Un `dial` a un destino no permitido degrada a `hangup` con tu `fallbackMessage` |
|
|
1491
|
+
| `sms` | `send`, `get` | valida E.164, destino, baja y contenido antes de pagar |
|
|
1492
|
+
| `whatsapp` | `sendText`, `sendTemplate`, `get?` | el texto libre solo vale dentro de la ventana de 24 h (política de WhatsApp); fuera de ella, plantilla |
|
|
1493
|
+
| `usage` | `query({ category, from, to, number?, granularity? })` | `{ count, units, unit, providerCost }`; el costo es **del proveedor** |
|
|
1494
|
+
|
|
1495
|
+
`tel.supports('sms')` / `tel.capabilities()` dicen qué hay. Pedir lo que ningún proveedor soporta lanza
|
|
1496
|
+
`UnsupportedCapabilityException` (501); los errores del proveedor salen como `TelephonyProviderException` (502) con un
|
|
1497
|
+
`reason` **estable** (`auth`, `invalid_number`, `regulation_required`, `insufficient_funds`, `opted_out`, `rate_limited`,
|
|
1498
|
+
`timeout`, `circuit_open`…): tu código ramifica por eso, y el mensaje crudo del proveedor queda solo en `err.raw` (no
|
|
1499
|
+
enumerable, no se serializa al cliente).
|
|
1500
|
+
|
|
1501
|
+
#### Webhooks y eventos normalizados
|
|
1502
|
+
|
|
1503
|
+
Un solo camino para todo proveedor (`TelephonyWebhooks.handle`): **firma → normalizar → descartar repeticiones →
|
|
1504
|
+
resolver tenant → registrar bajas → tu `onEvent`**. Los eventos son iguales con cualquier proveedor:
|
|
1505
|
+
|
|
1506
|
+
| Evento | Cuándo | Campos clave |
|
|
1507
|
+
|---|---|---|
|
|
1508
|
+
| `llamada.entrante` | suena una línea tuya | `callId`, `from`, `to` — **tu `onEvent` devuelve cómo contestar** |
|
|
1509
|
+
| `llamada.estado` / `llamada.terminada` | cambia / termina | `status`, `durationSeconds`, `billableMinutes` |
|
|
1510
|
+
| `llamada.accion` | terminó la sesión del relay | `handoff`, `sessionFailed` |
|
|
1511
|
+
| `sms.recibido` / `whatsapp.recibido` | llega un mensaje | `from`, `to`, `body`, `keyword?` (`opt_out`/`opt_in`/`help`) |
|
|
1512
|
+
| `sms.estado` / `whatsapp.estado` | entregado, leído, falló | `status`, `errorReason?` |
|
|
1513
|
+
|
|
1514
|
+
Cada evento trae un `id` estable (el proveedor reintenta; tú no procesas dos veces) y `tenantId` si implementaste
|
|
1515
|
+
`resolveTenant`. Con credenciales por tenant, monta la ruta con el tenant (`/telephony/webhooks/twilio/:tenantId`): sus
|
|
1516
|
+
credenciales verifican la firma.
|
|
1517
|
+
|
|
1518
|
+
#### Seguridad y rendimiento (por defecto, no opcional)
|
|
1519
|
+
|
|
1520
|
+
| Qué | Cómo | Por omisión | Se ajusta con |
|
|
1521
|
+
|---|---|---|---|
|
|
1522
|
+
| Firma de webhooks | HMAC en **tiempo constante** contra la URL pública exacta (`publicBaseUrl`, nunca el `Host` de la petición); sin secreto no hay webhook válido; falla cerrado y nunca lanza | siempre | — |
|
|
1523
|
+
| Repetición (replay) | descarta eventos ya vistos (`id`) y más viejos que la ventana si el proveedor da hora | ventana 5 min; memoria 15 min / 50 000 ids | `webhook.maxSkewMs`, `deduper` (con 2+ instancias pasa uno en Redis/SQL) |
|
|
1524
|
+
| Abuso de webhooks | tope por origen; rechazos sin cuerpo ni detalle | 600 por minuto | `webhook.rateLimit` (`false` lo apaga) |
|
|
1525
|
+
| Secretos y datos personales | los logs pasan por redacción: teléfono = `•••1234`, secretos fuera; los errores nunca llevan el texto del proveedor | siempre | `logger` |
|
|
1526
|
+
| Anti fraude de peaje | solo destinos E.164 de México; bloquea 800/900/700, +1 900/976/809/829/849 y satelitales | `+52` | `policy.destinations` (`allowedPrefixes`, `blockedPrefixes`, `extraBlockedPrefixes`) |
|
|
1527
|
+
| Bajas (obligatorias) | STOP/BAJA/ALTA exactos (sin acentos); la baja queda registrada **antes** de tu `onEvent` y se consulta antes de cada envío, por tenant y línea | memoria acotada | `policy.optOutStore` (en producción pasa uno persistente) |
|
|
1528
|
+
| Contenido | quita caracteres de control y de dirección de texto; mensaje 1–1600 caracteres; variables de plantilla sin saltos de línea (máx. 1024) | siempre | `policy.maxMessageLength` |
|
|
1529
|
+
| Tus topes | `beforeOutbound(op)` lanza para cortar (gasto, simultáneas, periodo); `afterOutbound` cuenta lo enviado | sin topes | `policy.beforeOutbound` / `afterOutbound` |
|
|
1530
|
+
| Aislamiento por tenant | adaptador, caché, cortacircuito y bajas por tenant | — | `tenantProvider` |
|
|
1531
|
+
| Proveedor lento o caído | tiempo límite y reintentos de `resilience` (solo lo idempotente: un POST se reintenta únicamente con clave de idempotencia); concurrencia 20 con cola de 100; cortacircuito tras 5 fallos seguidos, 30 s | siempre | `resilience`, `gate` (por proveedor) |
|
|
1532
|
+
| Llamada entrante | tu `onEvent` tiene presupuesto; vencido, se contesta con el respaldo (nadie queda en silencio) | 2500 ms | `webhook.answerBudgetMs`, `webhook.fallbackAnswer` |
|
|
1533
|
+
| Lecturas | caché corto que **comparte** la consulta en vuelo (N peticiones iguales = 1), listados paginados, uso sin N+1; una lectura prueba el respaldo si el principal cae; **una escritura nunca** (sería un cargo doble) | 30 s | `policy.readCacheTtlMs` |
|
|
1534
|
+
| Privacidad | sin audio ni transcripción en disco; el relay solo guarda en memoria | siempre | — |
|
|
1535
|
+
|
|
1536
|
+
`maxMessageLength`, topes y ventanas son configurables; los valores por omisión son conservadores. Lo que **no** se
|
|
1537
|
+
puede garantizar desde aquí: el almacén de bajas y de ids de eventos por omisión son por proceso (con varias
|
|
1538
|
+
instancias, pasa los tuyos), y el costo exacto que cobra el proveedor solo se conoce cuando él lo informa.
|
|
1539
|
+
|
|
1540
|
+
#### Por tenant, respaldos y canales
|
|
1541
|
+
|
|
1542
|
+
```ts
|
|
1543
|
+
const tel = await this.tel.forTenant(tenantId); // sus credenciales, su caché, su cortacircuito, sus bajas
|
|
1544
|
+
await tel.sms.send(…);
|
|
1545
|
+
```
|
|
1546
|
+
|
|
1547
|
+
`tenantProvider: async (id) => ({ provider: 'twilio', config: { accountSid, authToken }, fallbacks: […] })`. Se conserva
|
|
1548
|
+
en memoria acotada (500 tenants, 10 min; `forgetTenant(id)` al cambiar credenciales). `fallbacks` cubre capacidades que
|
|
1549
|
+
el principal no tiene y lecturas ante una caída; `channels: { whatsapp: 'meta-whatsapp' }` fuerza una capacidad a un
|
|
1550
|
+
proveedor concreto (p. ej. WhatsApp directo con Meta y voz con Twilio). `MetaWhatsAppTelephony` reutiliza el
|
|
1551
|
+
`WhatsAppClient` de `@miguelmorales13/nestkit/whatsapp` (que ahora también manda plantillas) y suma firma
|
|
1552
|
+
`X-Hub-Signature-256`, reto de verificación y eventos.
|
|
1553
|
+
|
|
1554
|
+
#### Cómo agregar un proveedor
|
|
1555
|
+
|
|
1556
|
+
Implementar las capacidades que soporte y **pasar el contrato compartido**; nada más.
|
|
1557
|
+
|
|
1558
|
+
```ts
|
|
1559
|
+
// plivo.telephony.ts
|
|
1560
|
+
export class PlivoTelephony implements TelephonyAdapter {
|
|
1561
|
+
readonly provider = 'plivo';
|
|
1562
|
+
readonly portVersion = TELEPHONY_PORT_VERSION;
|
|
1563
|
+
readonly webhooks: WebhooksPort = { verify, parse, acknowledge }; // obligatorio
|
|
1564
|
+
readonly sms: SmsPort = { send, get }; // solo lo que soporta: omitir = «no»
|
|
1565
|
+
constructor(private readonly o: { authId: string; authToken: string } & ProviderHttpOptions) {
|
|
1566
|
+
const http = createProviderHttp('plivo', o); // tiempo límite, reintentos, cortacircuito
|
|
1567
|
+
… // y `providerError('plivo', res, { 400: 'invalid_number' })`
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
// mi-proveedor.spec.ts — el contrato corre solo los bloques de las capacidades que declaras
|
|
1572
|
+
import { runTelephonyContract } from '../telephony.contract.js'; // solo en el repo (usa bun:test), no en dist
|
|
1573
|
+
runTelephonyContract('Plivo', () => ({ adapter: new PlivoTelephony(…), signed: (kind, info) => /* petición firmada real */, tamper: (r) => /* alterada */ }));
|
|
1574
|
+
|
|
1575
|
+
// registrarlo
|
|
1576
|
+
TelephonyModule.forRoot({ provider: 'plivo', providers: { plivo: { authId, authToken } }, factories: { plivo: (c) => new PlivoTelephony(c) } });
|
|
1577
|
+
```
|
|
1578
|
+
|
|
1579
|
+
Reglas del puerto para que crezca sin romper a nadie: una capacidad nueva (MMS, video, OTP) es una propiedad opcional
|
|
1580
|
+
nueva; los campos nuevos de las respuestas son opcionales; lo específico de un proveedor viaja en `extra` (entrada,
|
|
1581
|
+
opt-in y acotado) o `raw` (salida), nunca en los tipos; `TELEPHONY_PORT_VERSION` sube solo ante un cambio
|
|
1582
|
+
incompatible. Los errores se traducen con `providerError`/`TelephonyProviderException` (motivo estable, nunca el texto
|
|
1583
|
+
del proveedor), y las firmas se comparan con `constantTimeEqual`.
|
|
1584
|
+
|
|
1585
|
+
#### Reglas comunes (puras, sirven con cualquier proveedor)
|
|
1586
|
+
|
|
1587
|
+
| Función | Para qué |
|
|
1588
|
+
|---|---|
|
|
1589
|
+
| `signCallToken` / `verifyCallToken` / `verifyCallTokenFor(token, secreto, { callId, tenantId? })` | token HMAC por llamada, caduca a los 10 min; **atado a la llamada y al tenant**: el de otra llamada no abre esta sesión |
|
|
1590
|
+
| `CallLimiter` + `DEFAULT_CALL_LIMITS` | topes por línea (simultáneas) y por llamante (ventana); `isOverTurnLimit` / `isOverDuration`. Por proceso |
|
|
1591
|
+
| `checkDestination`, `normalizeE164`, `isE164`, `sanitizeDialDestination` | destino permitido y formato; el teléfono de desvío sale de lo que teclea un usuario y se marca **con tus números** |
|
|
1592
|
+
| `classifyKeyword`, `MemoryOptOutStore` | STOP/BAJA/ALTA exactos |
|
|
1593
|
+
| `sanitizeMessageBody`, `sanitizeTemplateVariable`, `redactPhone`, `redactText` | contenido limpio y datos personales fuera de los logs |
|
|
1594
|
+
| `SlidingWindowLimiter`, `TtlCache`, `ProviderGate`, `UsageCounter`, `billableMinutes` | topes de tasa, caché, cortacircuito y consumo |
|
|
1595
|
+
|
|
1596
|
+
#### `telephony/relay` — el servidor de voz
|
|
1597
|
+
|
|
1598
|
+
El WebSocket al que se conecta ConversationRelay, **en su propio proceso** para que una llamada larga no le quite
|
|
1599
|
+
recursos al API. Recibe lo que dice el llamante, se lo pasa al API de tu proyecto y devuelve el texto a leer:
|
|
1600
|
+
|
|
1601
|
+
```ts
|
|
1602
|
+
import { startRelayServer, httpRelayBackend } from '@miguelmorales13/nestkit/telephony/relay';
|
|
1603
|
+
|
|
1604
|
+
startRelayServer({
|
|
1605
|
+
backend: httpRelayBackend({ baseUrl: 'https://api.miapp.com/api/v1/voz' }), // POST turn | progress | finish | session (https obligatorio)
|
|
1606
|
+
// secret: por omisión RELAY_SECRET; en producción es obligatorio (sin él no arranca)
|
|
1607
|
+
});
|
|
1608
|
+
```
|
|
1609
|
+
|
|
1610
|
+
- **Solo Bun** (`Bun.serve`, sin dependencias). En otro runtime usa `RelaySession` (sin sockets) y `decideRelayAccess`.
|
|
1611
|
+
- **Protocolo**: mensajes de Twilio ConversationRelay (`setup`, `prompt`, `text`, `end`).
|
|
1612
|
+
- **Se protege solo**: rechaza `Origin` (un navegador no es el proveedor), exige `?k=<RELAY_SECRET>` (en producción
|
|
1613
|
+
siempre) y `wss` (rechaza lo que el proxy marca `http`), y cierra el socket que no presenta en 10 s un `setup` con un
|
|
1614
|
+
token que el API acepte; el relay reenvía `{ t, callId }` y tu endpoint `session` debe validar con
|
|
1615
|
+
`verifyCallTokenFor` (token de **esta** llamada). Solo un `401` lo invalida: si el API no responde, la llamada sigue.
|
|
1616
|
+
- **Topes** (todos por entorno `RELAY_*` o `limits`): 100 conexiones, 30 conexiones nuevas por IP por minuto (la IP es
|
|
1617
|
+
la del socket; `trustProxy: true` usa `X-Forwarded-For` solo detrás de un proxy propio), 64 KB por mensaje, 200
|
|
1618
|
+
mensajes por socket cada 10 s (más cierra), 1 MB pendiente de enviar a un cliente lento (más cierra), 120 s sin
|
|
1619
|
+
tráfico, llamada de 8 min 30 s o 40 turnos (se despide y pasa a una persona).
|
|
1620
|
+
- **Cierre ordenado**: `SIGINT`/`SIGTERM` dejan de aceptar llamadas (503 también en `/health`) y esperan hasta 55 s a
|
|
1621
|
+
que se guarden las pendientes; `finish` se reintenta 6 veces. Lo que no se logre queda como `LLAMADA SIN GUARDAR
|
|
1622
|
+
callId=…`, **sin** nombre, teléfono ni transcripción. Todo log pasa por redacción (teléfonos y el secreto).
|
|
1623
|
+
- **Contrato con tu API** (`httpRelayBackend`, o implementa `RelayBackend`): `turn` devuelve
|
|
1624
|
+
`{ reply, action: 'continue' | 'end' | 'handoff', outcome, summary, data? }`; una respuesta ilegible cuenta como falla
|
|
1625
|
+
y se pasa a una persona.
|
|
1626
|
+
|
|
1627
|
+
#### Migración gradual (Caxuela, Cajón)
|
|
1628
|
+
|
|
1629
|
+
1. Cambia `ProveedorDeNumeros` por `tel.numbers` y `verifyWebhook`/`parseCallWebhook`/`buildAnswer` por
|
|
1630
|
+
`tel.voice.buildAnswer` + `TelephonyWebhooks` (mismas firmas y mismo TwiML; el controlador de voz queda en un
|
|
1631
|
+
`onEvent`).
|
|
1632
|
+
2. Mueve tus topes a `policy.beforeOutbound`/`afterOutbound` y tus bajas a `policy.optOutStore`.
|
|
1633
|
+
3. Cuando quieras SMS/WhatsApp/uso, ya está en la misma fachada; apaga lo que no uses omitiendo la capacidad.
|
|
1634
|
+
4. Cambiar de proveedor después es `provider: '…'` (y su bloque de configuración).
|
|
1635
|
+
|
|
1636
|
+
#### Lo que no se pudo verificar sin cuenta real
|
|
1637
|
+
|
|
1638
|
+
Las llamadas a Twilio y a Meta se prueban con un `fetch` doble y con el vector de firma publicado por Twilio; no hay
|
|
1639
|
+
una llamada, un SMS ni una compra reales detrás de las pruebas. Los esquemas de requisitos regulatorios, precios y
|
|
1640
|
+
categorías de uso de Twilio están tomados de su documentación y deben comprobarse una vez con una cuenta de prueba.
|
|
1641
|
+
|
|
1410
1642
|
### `auth` — flujo completo de registro/login, para empresa o para persona sola
|
|
1411
1643
|
|
|
1412
1644
|
Mismo espíritu que `crud`: `nestkit` define el puerto (`AuthUserPort`) y la orquestación
|
|
@@ -2184,6 +2416,8 @@ trae los datos.
|
|
|
2184
2416
|
| `@miguelmorales13/nestkit/auth/oauth` | `OAuthAuthModule`, `OAuthAuthService`, `createOAuthController`, `googleProvider`, `appleProvider`, `facebookProvider`, `tiktokProvider`, `githubProvider`, `microsoftProvider`, `discordProvider`, `linkedinProvider`, `OAuthStorePort`, `RefreshTokenStorePort`, `MagicLinkStorePort`, `MagicLinkSenderPort`, `TwoFactorStorePort`, `PasskeyStorePort`, `WebAuthnPort`, stores en memoria, `totp`/`verifyTotp` |
|
|
2185
2417
|
| `@miguelmorales13/nestkit/umami` | `UmamiModule`, `UmamiService` — lectura de la API de analítica |
|
|
2186
2418
|
| `@miguelmorales13/nestkit/invoicing` | `InvoicingModule`, `INVOICING`, `InvoicingPort`, adaptadores `FacturapiInvoicing`/`FacturamaInvoicing` — CFDI 4.0 |
|
|
2419
|
+
| `@miguelmorales13/nestkit/telephony` | `TelephonyModule`, `Telephony` (fachada), `TelephonyAdapter`, `TelephonyWebhooks`, `createTelephonyWebhookController`, adaptadores `TwilioTelephony`/`MetaWhatsAppTelephony`/`SimulatedTelephony`, reglas puras (`checkDestination`, `signCallToken`, `classifyKeyword`, `redactPhone`…) — números, voz, SMS, WhatsApp, uso y webhooks |
|
|
2420
|
+
| `@miguelmorales13/nestkit/telephony/relay` | `startRelayServer` (solo Bun), `RelaySession`, `httpRelayBackend`, `decideRelayAccess` — servidor de voz de ConversationRelay |
|
|
2187
2421
|
| `@miguelmorales13/nestkit/payments` | `PaymentsModule`, `TERMINAL_PAYMENTS`, `TerminalPaymentsPort`, adaptadores `MercadoPagoTerminalPayments`/`ClipTerminalPayments`, `MercadoPagoConnect` (OAuth marketplace), `isIntegrableTerminalModel`, `createTerminalPaymentsWebhookController` |
|
|
2188
2422
|
| `@miguelmorales13/nestkit/storage` | `StorageModule`, `STORAGE`, `StoragePort`, adaptadores `LocalStorage`/`S3Storage`/`BunnyStorage` |
|
|
2189
2423
|
| `@miguelmorales13/nestkit/push` | `PushModule`, `PUSH`, `PushPort`, `PUSH_DEVICE_STORE`, `PushDeviceStorePort`, canales `FcmChannel`/`WebPushChannel`, `toFcmMessage` |
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/security/hash.ts
|
|
2
|
+
var _crypto = require('crypto');
|
|
3
|
+
var hashSha256 = (value) => _crypto.createHash.call(void 0, "sha256").update(value).digest("hex");
|
|
4
|
+
function constantTimeEqual(a, b) {
|
|
5
|
+
const ba = Buffer.from(a);
|
|
6
|
+
const bb = Buffer.from(b);
|
|
7
|
+
if (ba.length !== bb.length) {
|
|
8
|
+
_crypto.timingSafeEqual.call(void 0, ba, ba);
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
return _crypto.timingSafeEqual.call(void 0, ba, bb);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
exports.hashSha256 = hashSha256; exports.constantTimeEqual = constantTimeEqual;
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
constantTimeEqual
|
|
3
|
+
} from "./chunk-L2QK2HN5.js";
|
|
4
|
+
|
|
1
5
|
// src/security/signed-state.ts
|
|
2
6
|
import { createHmac, randomBytes, timingSafeEqual } from "crypto";
|
|
3
7
|
function signState(payload, options) {
|
|
@@ -89,19 +93,6 @@ function maskFields(value, rules, maxDepth = 8) {
|
|
|
89
93
|
return walk(value, 0);
|
|
90
94
|
}
|
|
91
95
|
|
|
92
|
-
// src/security/hash.ts
|
|
93
|
-
import { createHash, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
94
|
-
var hashSha256 = (value) => createHash("sha256").update(value).digest("hex");
|
|
95
|
-
function constantTimeEqual(a, b) {
|
|
96
|
-
const ba = Buffer.from(a);
|
|
97
|
-
const bb = Buffer.from(b);
|
|
98
|
-
if (ba.length !== bb.length) {
|
|
99
|
-
timingSafeEqual2(ba, ba);
|
|
100
|
-
return false;
|
|
101
|
-
}
|
|
102
|
-
return timingSafeEqual2(ba, bb);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
96
|
// src/security/signed-grant.ts
|
|
106
97
|
import { createHmac as createHmac2, randomBytes as randomBytes2 } from "crypto";
|
|
107
98
|
var sign = (b64, secret) => createHmac2("sha256", secret).update(b64).digest("base64url");
|
|
@@ -144,8 +135,6 @@ export {
|
|
|
144
135
|
maskToken,
|
|
145
136
|
shapeOf,
|
|
146
137
|
maskFields,
|
|
147
|
-
hashSha256,
|
|
148
|
-
constantTimeEqual,
|
|
149
138
|
signGrant,
|
|
150
139
|
verifyGrant
|
|
151
140
|
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/telephony/rules/redact.ts
|
|
2
|
+
function redactPhone(value) {
|
|
3
|
+
const digits = (_nullishCoalesce(value, () => ( ""))).replace(/\D/g, "");
|
|
4
|
+
if (!digits) return "";
|
|
5
|
+
return `\u2022\u2022\u2022${digits.slice(-4)}`;
|
|
6
|
+
}
|
|
7
|
+
function redactPhonesInText(text) {
|
|
8
|
+
return text.replace(/\+?\d[\d\s().-]{5,}\d/g, (m) => m.replace(/\D/g, "").length >= 7 ? redactPhone(m) : m);
|
|
9
|
+
}
|
|
10
|
+
function redactText(text, secrets = []) {
|
|
11
|
+
let out = text;
|
|
12
|
+
for (const secret of secrets) {
|
|
13
|
+
if (secret && secret.length >= 6) out = out.split(secret).join("[secreto]");
|
|
14
|
+
}
|
|
15
|
+
return redactPhonesInText(out);
|
|
16
|
+
}
|
|
17
|
+
function createRedactingLogger(write, secrets = () => []) {
|
|
18
|
+
return (line) => write(redactText(line, secrets()));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// src/telephony/rules/sliding-window.ts
|
|
22
|
+
var SlidingWindowLimiter = class {
|
|
23
|
+
constructor(maxEvents, windowMs, maxKeys = 1e4) {
|
|
24
|
+
this.maxEvents = maxEvents;
|
|
25
|
+
this.windowMs = windowMs;
|
|
26
|
+
this.maxKeys = maxKeys;
|
|
27
|
+
this.hits = /* @__PURE__ */ new Map();
|
|
28
|
+
}
|
|
29
|
+
/** Registra un evento; `false` = se pasó del tope (el evento no cuenta). */
|
|
30
|
+
allow(key, now = Date.now()) {
|
|
31
|
+
const recent = (_nullishCoalesce(this.hits.get(key), () => ( []))).filter((t) => t > now - this.windowMs);
|
|
32
|
+
if (recent.length >= this.maxEvents) {
|
|
33
|
+
this.hits.set(key, recent);
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
recent.push(now);
|
|
37
|
+
this.hits.delete(key);
|
|
38
|
+
this.hits.set(key, recent);
|
|
39
|
+
if (this.hits.size > this.maxKeys) this.hits.delete(this.hits.keys().next().value);
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
// src/telephony/rules/handoff.ts
|
|
45
|
+
var HANDOFF_DATA = JSON.stringify({ a: "handoff" });
|
|
46
|
+
function isHandoffRequested(handoff) {
|
|
47
|
+
if (!handoff) return false;
|
|
48
|
+
try {
|
|
49
|
+
return _optionalChain([JSON, 'access', _ => _.parse, 'call', _2 => _2(handoff), 'optionalAccess', _3 => _3.a]) === "handoff";
|
|
50
|
+
} catch (e) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
exports.redactPhone = redactPhone; exports.redactPhonesInText = redactPhonesInText; exports.redactText = redactText; exports.createRedactingLogger = createRedactingLogger; exports.SlidingWindowLimiter = SlidingWindowLimiter; exports.HANDOFF_DATA = HANDOFF_DATA; exports.isHandoffRequested = isHandoffRequested;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// src/security/hash.ts
|
|
2
|
+
import { createHash, timingSafeEqual } from "crypto";
|
|
3
|
+
var hashSha256 = (value) => createHash("sha256").update(value).digest("hex");
|
|
4
|
+
function constantTimeEqual(a, b) {
|
|
5
|
+
const ba = Buffer.from(a);
|
|
6
|
+
const bb = Buffer.from(b);
|
|
7
|
+
if (ba.length !== bb.length) {
|
|
8
|
+
timingSafeEqual(ba, ba);
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
return timingSafeEqual(ba, bb);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export {
|
|
15
|
+
hashSha256,
|
|
16
|
+
constantTimeEqual
|
|
17
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// src/telephony/rules/redact.ts
|
|
2
|
+
function redactPhone(value) {
|
|
3
|
+
const digits = (value ?? "").replace(/\D/g, "");
|
|
4
|
+
if (!digits) return "";
|
|
5
|
+
return `\u2022\u2022\u2022${digits.slice(-4)}`;
|
|
6
|
+
}
|
|
7
|
+
function redactPhonesInText(text) {
|
|
8
|
+
return text.replace(/\+?\d[\d\s().-]{5,}\d/g, (m) => m.replace(/\D/g, "").length >= 7 ? redactPhone(m) : m);
|
|
9
|
+
}
|
|
10
|
+
function redactText(text, secrets = []) {
|
|
11
|
+
let out = text;
|
|
12
|
+
for (const secret of secrets) {
|
|
13
|
+
if (secret && secret.length >= 6) out = out.split(secret).join("[secreto]");
|
|
14
|
+
}
|
|
15
|
+
return redactPhonesInText(out);
|
|
16
|
+
}
|
|
17
|
+
function createRedactingLogger(write, secrets = () => []) {
|
|
18
|
+
return (line) => write(redactText(line, secrets()));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// src/telephony/rules/sliding-window.ts
|
|
22
|
+
var SlidingWindowLimiter = class {
|
|
23
|
+
constructor(maxEvents, windowMs, maxKeys = 1e4) {
|
|
24
|
+
this.maxEvents = maxEvents;
|
|
25
|
+
this.windowMs = windowMs;
|
|
26
|
+
this.maxKeys = maxKeys;
|
|
27
|
+
this.hits = /* @__PURE__ */ new Map();
|
|
28
|
+
}
|
|
29
|
+
/** Registra un evento; `false` = se pasó del tope (el evento no cuenta). */
|
|
30
|
+
allow(key, now = Date.now()) {
|
|
31
|
+
const recent = (this.hits.get(key) ?? []).filter((t) => t > now - this.windowMs);
|
|
32
|
+
if (recent.length >= this.maxEvents) {
|
|
33
|
+
this.hits.set(key, recent);
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
recent.push(now);
|
|
37
|
+
this.hits.delete(key);
|
|
38
|
+
this.hits.set(key, recent);
|
|
39
|
+
if (this.hits.size > this.maxKeys) this.hits.delete(this.hits.keys().next().value);
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
// src/telephony/rules/handoff.ts
|
|
45
|
+
var HANDOFF_DATA = JSON.stringify({ a: "handoff" });
|
|
46
|
+
function isHandoffRequested(handoff) {
|
|
47
|
+
if (!handoff) return false;
|
|
48
|
+
try {
|
|
49
|
+
return JSON.parse(handoff)?.a === "handoff";
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export {
|
|
56
|
+
redactPhone,
|
|
57
|
+
redactPhonesInText,
|
|
58
|
+
redactText,
|
|
59
|
+
createRedactingLogger,
|
|
60
|
+
SlidingWindowLimiter,
|
|
61
|
+
HANDOFF_DATA,
|
|
62
|
+
isHandoffRequested
|
|
63
|
+
};
|