Compare commits

...

6 Commits

Author SHA1 Message Date
jkunz c18f2f7ca1 v1.27.0
Docker (tags) / release (push) Failing after 4s
2026-05-21 23:36:14 +00:00
jkunz 3e2fee16c1 feat(storage): persist siprouter data in smartdata and smartbucket 2026-05-21 23:35:50 +00:00
jkunz 04e706715f fix: return engine call IDs 2026-05-08 16:24:45 +00:00
jkunz 980a1500f5 docs: refresh readme and legal info 2026-05-07 20:22:12 +00:00
jkunz 33b4ae5dd0 v1.26.0
Docker (tags) / release (push) Failing after 5s
2026-04-20 20:43:42 +00:00
jkunz d2c18a4ebb feat(fax): add fax routing, job tracking, inbox management, and T.38/UDPTL media support 2026-04-20 20:43:42 +00:00
35 changed files with 6837 additions and 1707 deletions
+14
View File
@@ -19,5 +19,19 @@
"dockerregistry.lossless.digital": "serve.zone/siprouter"
},
"platforms": ["linux/amd64", "linux/arm64"]
},
"@git.zone/cli": {
"release": {
"targets": {
"git": {
"enabled": true,
"remote": "origin"
},
"docker": {
"enabled": true,
"engine": "tsdocker"
}
}
}
}
}
+22
View File
@@ -1,5 +1,27 @@
# Changelog
## Pending
## 2026-05-21 - 1.27.0
### Features
- persist siprouter config and media through SmartData and SmartBucket (storage)
- store runtime config, voicemail metadata, fax jobs, and fax inbox metadata in SmartData
- store voicemail audio, custom greetings, and fax payloads in SmartBucket while keeping local cache paths for Rust media access
- migrate legacy local voicemail and fax metadata/media into SmartData and SmartBucket on startup
- enable gitzone Docker release publishing through the configured tsdocker target
## 2026-04-20 - 1.26.0 - feat(fax)
add fax routing, job tracking, inbox management, and T.38/UDPTL media support
- adds outbound fax origination through the proxy engine with provider codec validation and a new send_fax command
- introduces fax box configuration, inbox storage, and dashboard/API endpoints for listing, downloading, and deleting received fax messages
- tracks fax lifecycle events and persisted fax jobs in the runtime layer
- extends SIP SDP parsing and rewriting to support non-audio media, including T.38 over UDPTL
- records leg media protocol details and bridge state to distinguish RTP, WebRTC, internal, and fax media paths
## 2026-04-14 - 1.25.2 - fix(proxy-engine)
improve inbound SIP routing diagnostics and enrich leg media state reporting
+23 -10
View File
@@ -1,10 +1,10 @@
{
"name": "siprouter",
"version": "1.25.2",
"version": "1.27.0",
"private": true,
"type": "module",
"scripts": {
"bundle": "node node_modules/.pnpm/esbuild@0.27.7/node_modules/esbuild/bin/esbuild ts_web/index.ts --bundle --format=esm --outfile=dist_ts_web/bundle.js --platform=browser --target=es2022 --minify",
"bundle": "esbuild ts_web/index.ts --bundle --format=esm --outfile=dist_ts_web/bundle.js --platform=browser --target=es2022 --minify",
"buildRust": "tsrust",
"build": "pnpm run buildRust && pnpm run bundle",
"build:docker": "tsdocker build --verbose",
@@ -13,18 +13,31 @@
"restartBackground": "pnpm run buildRust && pnpm run bundle; test -f .server.pid && kill $(cat .server.pid) 2>/dev/null; sleep 1; rm -f sip_trace.log proxy.out && nohup tsx ts/sipproxy.ts > proxy.out 2>&1 & echo $! > .server.pid; sleep 2; cat proxy.out"
},
"dependencies": {
"@design.estate/dees-catalog": "^3.77.0",
"@design.estate/dees-catalog": "^3.81.0",
"@design.estate/dees-element": "^2.2.4",
"@push.rocks/smartrust": "^1.3.2",
"@push.rocks/smartstate": "^2.3.0",
"@push.rocks/smartbucket": "^4.6.1",
"@push.rocks/smartdata": "^7.1.7",
"@push.rocks/smartrust": "^1.4.0",
"@push.rocks/smartstate": "^2.3.1",
"tsx": "^4.21.0",
"ws": "^8.20.0"
},
"devDependencies": {
"@git.zone/tsbundle": "^2.10.0",
"@git.zone/tsdocker": "^2.2.4",
"@git.zone/tsrust": "^1.3.2",
"@git.zone/tswatch": "^3.3.2",
"@types/ws": "^8.18.1"
"@git.zone/tsbundle": "^2.10.1",
"@git.zone/tsdocker": "^2.2.5",
"@git.zone/tsrust": "^1.3.3",
"@git.zone/tswatch": "^3.3.3",
"@types/node": "^25.8.0",
"@types/ws": "^8.18.1",
"esbuild": "^0.27.7"
},
"pnpm": {
"ignoredBuiltDependencies": [
"@design.estate/dees-catalog"
],
"onlyBuiltDependencies": [
"esbuild",
"mongodb-memory-server"
]
}
}
+1685 -688
View File
File diff suppressed because it is too large Load Diff
+5
View File
@@ -0,0 +1,5 @@
allowBuilds:
esbuild: true
mongodb-memory-server: true
ignoredBuiltDependencies:
- '@design.estate/dees-catalog'
+167 -351
View File
@@ -1,140 +1,104 @@
# @serve.zone/siprouter
# siprouter
A production-grade **SIP B2BUA + WebRTC bridge** built with TypeScript and Rust. Routes calls between SIP providers, SIP hardware devices, and browser softphones — with real-time codec transcoding, adaptive jitter buffering, ML noise suppression, neural TTS, voicemail, IVR menus, and a slick web dashboard.
siprouter is a TypeScript control plane plus Rust media/data plane for SIP routing, SIP device registration, SIP trunk calls, browser WebRTC softphones, voicemail/fax storage, and a live operations dashboard. It is intentionally split so TypeScript owns configuration, REST/WebSocket APIs, and UI glue while the Rust `proxy-engine` owns SIP, RTP, WebRTC media, codecs, mixing, jitter handling, fax transport, and real-time call state.
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
---
## Current Capabilities
## 🔥 What It Does
- SIP B2BUA behavior for SIP providers and LAN SIP devices, including dialog state, provider registration, digest auth retry, SDP negotiation, BYE/CANCEL handling, and routing decisions in Rust.
- Browser WebRTC softphone signaling through the TypeScript dashboard, with WebRTC media sessions implemented in the Rust engine.
- A call hub model: each call owns multiple legs and a 20 ms tick mix-minus mixer at a 48 kHz f32 internal bus.
- Codec handling for Opus, G.722, PCMU, and PCMA through `codec-lib`, including per-leg transcoding, resampling, packet loss concealment, and jitter buffering.
- Device registration push events from Rust into TypeScript, then into the dashboard status stream.
- Route configuration for inbound and outbound calls with provider/device matching, number patterns, failover provider fields, browser notification flags, voicemail, fax, and IVR-related action fields.
- Voicemail metadata and WAV storage through `VoiceboxManager` under `.nogit/voicemail/{boxId}/`.
- Fax box and fax job metadata storage under `.nogit/fax/`, backed by Rust fax handling that includes audio fax and T.38-related code paths.
- Web dashboard and REST API on the configured `webUiPort`, served over HTTPS if `.nogit/cert.pem` and `.nogit/key.pem` exist, otherwise HTTP.
siprouter sits between your SIP trunk providers and your endpoints — hardware phones, ATAs, browser softphones — and handles **everything** in between:
## Important Accuracy Notes
- 📞 **SIP B2BUA** — Terminates and re-originates calls with full RFC 3261 dialog state management, digest auth, and SDP negotiation
- 🌐 **WebRTC Bridge** — Browser-based softphone with bidirectional Opus audio to the SIP network
- 🎛️ **Multi-Provider Trunking** — Register with multiple SIP providers simultaneously (sipgate, easybell, etc.) with automatic failover
- 🎧 **48kHz f32 Audio Engine** — High-fidelity internal audio bus at 48kHz/32-bit float with native Opus float encode/decode, FFT-based resampling, and per-leg ML noise suppression
- 🔀 **N-Leg Mix-Minus Mixer** — Conference-grade mixing with dynamic leg add/remove, transfer, and per-source audio separation
- 🎯 **Adaptive Jitter Buffer** — Per-leg jitter buffering with sequence-based reordering, adaptive depth (60120ms), Opus PLC for lost packets, and hold/resume detection
- 📧 **Voicemail** — Configurable voicemail boxes with TTS greetings, recording, and web playback
- 🔢 **IVR Menus** — DTMF-navigable interactive voice response with nested menus, routing actions, and custom prompts
- 🗣️ **Neural TTS** — Kokoro-powered greetings and IVR prompts with 25+ voice presets
- 🎙️ **Call Recording** — Per-source separated WAV recording at 48kHz via tool legs
- 🖥️ **Web Dashboard** — Real-time SPA with 9 views: live calls, browser phone, routing, voicemail, IVR, contacts, providers, and streaming logs
- TypeScript does not handle raw SIP or RTP. It sends high-level commands to the Rust engine over `@push.rocks/smartrust` and receives high-level events back.
- Browser WebRTC calls use a strict two-stage link flow. The browser first creates a standalone WebRTC session with `webrtc-offer`; only after `webrtc-accept`/linking can Rust attach that session to the call mixer.
- Inbound route resolution is wired in Rust, but multi-target inbound forking is not implemented yet. Only the first registered target device from an inbound route is rung.
- `ringBrowsers` currently controls browser notifications. It is not first-answer-wins call racing against SIP devices.
- `voicemailBox`, `ivrMenuId`, and `noAnswerTimeout` are part of resolved inbound route data, but the project notes mark downstream honoring of those fields as not complete yet.
- The `/api/transfer` HTTP endpoint currently returns `501 not yet implemented`.
---
## Architecture
## 🏗️ Architecture
```mermaid
flowchart TB
Browser["🌐 Browser Softphone<br/>(WebRTC via WebSocket signaling)"]
Devices["📞 SIP Devices<br/>(HT801, desk phones, ATAs)"]
Trunks["☎️ SIP Trunk Providers<br/>(sipgate, easybell, …)"]
subgraph Router["siprouter"]
direction TB
subgraph TS["TypeScript Control Plane"]
TSBits["Config · WebRTC Signaling<br/>REST API · Web Dashboard<br/>Voicebox Manager · TTS Cache"]
end
subgraph Rust["Rust proxy-engine (data plane)"]
RustBits["SIP Stack · Dialog SM · Auth<br/>Call Manager · N-Leg Mixer<br/>48kHz f32 Bus · Jitter Buffer<br/>Codec Engine · RTP Port Pool<br/>WebRTC Engine · Kokoro TTS<br/>Voicemail · IVR · Recording"]
end
TS <-->|"JSON-over-stdio IPC"| Rust
end
Browser <-->|"Opus / WebRTC"| TS
Rust <-->|"SIP / RTP"| Devices
Rust <-->|"SIP / RTP"| Trunks
```text
Browser dashboard and softphone
|
| HTTP + WebSocket signaling
v
TypeScript control plane
ts/sipproxy.ts
ts/frontend.ts
ts/webrtcbridge.ts
ts/config.ts
ts/proxybridge.ts
|
| JSON-over-stdio via @push.rocks/smartrust
v
Rust proxy-engine
SIP transport and dialog state
Call manager and call hub
RTP port pool and RTP I/O
48 kHz f32 mix-minus mixer
WebRTC sessions
Fax, voicemail, TTS, recorder, tool legs
|
| SIP/RTP/UDPTL/WebRTC media
v
SIP providers, SIP devices, and browser clients
```
### 🧠 Key Design Decisions
## Key Files
- **Hub Model** — Every call is a hub with N legs. Each leg is a `SipLeg` (device/provider) or `WebRtcLeg` (browser). Legs can be dynamically added, removed, or transferred without tearing down the call.
- **Rust Data Plane** — All SIP protocol handling, codec transcoding, mixing, and RTP I/O runs in native Rust for real-time performance. TypeScript handles config, signaling, REST API, and dashboard.
- **48kHz f32 Internal Bus** — Audio is processed at maximum quality internally. Encoding/decoding to wire format (G.722, PCMU, Opus) happens solely at the leg boundary.
- **Per-Session Codec Isolation** — Each call leg gets its own encoder/decoder/resampler/denoiser state — no cross-call corruption.
- **SDP Codec Negotiation** — Outbound encoding uses the codec actually negotiated in SDP answers, not just the first offered codec.
| Path | Role |
| --- | --- |
| `ts/sipproxy.ts` | Process entry point. Loads config, starts web UI, starts Rust, wires event handlers, and handles shutdown. |
| `ts/config.ts` | `.nogit/config.json` schema, defaults, and validation. |
| `ts/proxybridge.ts` | Typed command bridge to the Rust `proxy-engine` binary. |
| `ts/frontend.ts` | HTTP API, static dashboard serving, status WebSocket, and WebRTC message routing. |
| `ts/webrtcbridge.ts` | Browser device registration and WebSocket-to-device mapping. |
| `ts/voicebox.ts` | Voicemail box config, WAV metadata, unheard counts, and message CRUD. |
| `ts/faxbox.ts` | Fax inbox metadata and TIFF file tracking. |
| `ts/faxjobs.ts` | Outbound/inbound fax job state persistence. |
| `rust/crates/proxy-engine/src/call_manager.rs` | Central call registry, SIP routing, B2BUA state, route resolution, fax metadata, and call orchestration. |
| `rust/crates/proxy-engine/src/mixer.rs` | 20 ms mix-minus engine with 48 kHz f32 processing, codec boundaries, jitter, PLC, DTMF, and tool-leg audio. |
| `rust/crates/proxy-engine/src/webrtc_engine.rs` | Browser WebRTC sessions. |
| `rust/crates/proxy-engine/src/fax_engine.rs` | Fax transfer engine using `spandsp` and `udptl`. |
| `rust/crates/sip-proto/` | Zero-dependency SIP data library for parsing, serializing, dialogs, SDP helpers, digest auth, and URI rewriting. |
| `ts_web/` | Lit/dees-element dashboard views and WebRTC browser client state. |
### 📲 WebRTC Browser Call Flow
## Configuration
Browser calls are set up in a strict three-step dance — the WebRTC leg cannot be attached at call-creation time because the browser's session ID is only known once the SDP offer arrives:
```mermaid
sequenceDiagram
participant B as Browser
participant TS as TypeScript (sipproxy.ts)
participant R as Rust proxy-engine
participant P as SIP Provider
B->>TS: POST /api/call
TS->>R: make_call (pending call, no WebRTC leg yet)
R-->>TS: call_created
TS-->>B: webrtc-incoming (callId)
B->>TS: webrtc-offer (sessionId, SDP)
TS->>R: handle_webrtc_offer
R-->>TS: webrtc-answer (SDP)
TS-->>B: webrtc-answer
Note over R: Standalone WebRTC session<br/>(not yet attached to call)
B->>TS: webrtc_link (callId + sessionId)
TS->>R: link session → call
R->>R: wire WebRTC leg through mixer
R->>P: SIP INVITE
P-->>R: 200 OK + SDP
R-->>TS: call_answered
Note over B,P: Bidirectional Opus ↔ codec-transcoded<br/>audio flows through the mixer
```
---
## 🚀 Getting Started
### Prerequisites
- **Node.js** ≥ 20 with `tsx` globally available
- **pnpm** for package management
- **Rust** toolchain (for building the proxy engine)
### Install & Build
```bash
# Clone and install dependencies
pnpm install
# Build the Rust proxy-engine binary
pnpm run buildRust
# Bundle the web frontend
pnpm run bundle
```
### Configuration
Create `.nogit/config.json`:
Create `.nogit/config.json` in the repository root before starting the service.
```jsonc
{
"proxy": {
"lanIp": "192.168.1.100", // Your server's LAN IP
"lanPort": 5070, // SIP signaling port
"publicIpSeed": "stun.example.com", // STUN server for public IP discovery
"rtpPortRange": { "min": 20000, "max": 20200 }, // RTP port pool (even ports)
"webUiPort": 3060 // Dashboard + REST API port
"lanIp": "192.168.1.100",
"lanPort": 5070,
"publicIpSeed": null,
"rtpPortRange": { "min": 20000, "max": 20200 },
"webUiPort": 3060
},
"providers": [
{
"id": "my-trunk",
"displayName": "My SIP Provider",
"domain": "sip.provider.com",
"outboundProxy": { "address": "sip.provider.com", "port": 5060 },
"username": "user",
"password": "pass",
"codecs": [9, 0, 8, 101], // G.722, PCMU, PCMA, telephone-event
"registerIntervalSec": 300
"id": "main-trunk",
"displayName": "Main SIP trunk",
"domain": "sip.example.net",
"outboundProxy": { "address": "sip.example.net", "port": 5060 },
"username": "trunk-user",
"password": "trunk-password",
"registerIntervalSec": 300,
"codecs": [9, 0, 8, 101],
"quirks": { "earlyMediaSilence": false }
}
],
"devices": [
@@ -148,13 +112,21 @@ Create `.nogit/config.json`:
"routing": {
"routes": [
{
"id": "inbound-main-did",
"name": "Main DID",
"id": "outbound-default",
"name": "Outbound via main trunk",
"priority": 100,
"enabled": true,
"match": { "direction": "outbound" },
"action": { "provider": "main-trunk" }
},
{
"id": "inbound-main",
"name": "Inbound main number",
"priority": 200,
"enabled": true,
"match": {
"direction": "inbound",
"sourceProvider": "my-trunk",
"sourceProvider": "main-trunk",
"numberPattern": "+49421219694"
},
"action": {
@@ -162,267 +134,111 @@ Create `.nogit/config.json`:
"ringBrowsers": true,
"voicemailBox": "main"
}
},
{
"id": "inbound-support-did",
"name": "Support DID",
"priority": 190,
"enabled": true,
"match": {
"direction": "inbound",
"sourceProvider": "my-trunk",
"numberPattern": "+49421219695"
},
"action": {
"ivrMenuId": "support-menu"
}
},
{
"id": "outbound-default",
"name": "Route via trunk",
"priority": 100,
"enabled": true,
"match": { "direction": "outbound" },
"action": { "provider": "my-trunk" }
}
]
},
"contacts": [],
"voiceboxes": [
{
"id": "main",
"enabled": true,
"greetingText": "Please leave a message after the beep.",
"greetingText": "Please leave a message after the tone.",
"greetingVoice": "af_bella",
"noAnswerTimeoutSec": 25,
"maxRecordingSec": 120,
"maxMessages": 50
}
],
"contacts": [
{ "id": "1", "name": "Alice", "number": "+491234567890", "starred": true }
]
"faxboxes": [],
"ivr": {
"enabled": false,
"entryMenuId": "main-menu",
"menus": []
}
}
```
Inbound number ownership is explicit: add one inbound route per DID (or DID prefix) and scope it with `sourceProvider` when a provider delivers multiple external numbers.
## Persistent Files
### TTS Setup (Optional)
| Path | Purpose |
| --- | --- |
| `.nogit/config.json` | Main app config. |
| `.nogit/cert.pem` and `.nogit/key.pem` | Optional HTTPS certificate for the dashboard. |
| `.nogit/voicemail/{boxId}/` | Voicemail WAV files and `messages.json`. |
| `.nogit/fax/inboxes/{boxId}/` | Fax inbox files and metadata. |
| `.nogit/fax/jobs.json` | Fax job state. |
| `.nogit/prompts/` | Cached prompt/TTS assets used by call flows. |
| `sip_trace.log` | Runtime log written by `ts/sipproxy.ts`. |
For neural voicemail greetings and IVR prompts, download the Kokoro TTS model:
## HTTP and WebSocket API
| Endpoint | Purpose |
| --- | --- |
| `GET /api/status` | Full status snapshot for providers, devices, calls, and dashboard state. |
| `POST /api/call` | Originate an outbound call. |
| `POST /api/hangup` | Hang up a call. |
| `POST /api/fax` | Start an outbound fax. |
| `GET /api/fax/jobs` | List fax jobs. |
| `GET /api/fax/inboxes/:boxId` | List fax inbox messages. |
| `GET /api/fax/inboxes/:boxId/:messageId/file` | Stream a fax TIFF. |
| `DELETE /api/fax/inboxes/:boxId/:messageId` | Delete a fax message. |
| `POST /api/call/:id/addleg` | Add a registered SIP device leg to an active call. |
| `POST /api/call/:id/addexternal` | Add an external dial-out leg to an active call. |
| `POST /api/call/:id/removeleg` | Remove a leg from a call. |
| `POST /api/transfer` | Present but returns `501 not yet implemented`. |
| `GET /api/config` | Read sanitized config. |
| `POST /api/config` | Update config and trigger runtime reload where possible. |
| `GET /api/voicemail/:boxId` | List voicemail messages. |
| `GET /api/voicemail/:boxId/unheard` | Get unheard voicemail count. |
| `GET /api/voicemail/:boxId/:messageId/audio` | Stream voicemail WAV audio. |
| `POST /api/voicemail/:boxId/:messageId/heard` | Mark voicemail as heard. |
| `DELETE /api/voicemail/:boxId/:messageId` | Delete voicemail metadata and WAV file. |
| `WS /ws` | Status updates, logs, WebRTC signaling, and browser phone events. |
## Build and Run
```bash
mkdir -p .nogit/tts
curl -L -o .nogit/tts/kokoro-v1.0.onnx \
https://github.com/mzdk100/kokoro/releases/download/V1.0/kokoro-v1.0.onnx
curl -L -o .nogit/tts/voices.bin \
https://github.com/mzdk100/kokoro/releases/download/V1.0/voices.bin
```
Without the model files, TTS prompts (IVR menus, voicemail greetings) are skipped — everything else works fine.
### Run
```bash
pnpm start
```
The SIP proxy starts on the configured port and the web dashboard is available at `https://<your-ip>:3060`.
### HTTPS (Optional)
Place `cert.pem` and `key.pem` in `.nogit/` for TLS on the dashboard.
---
## 📂 Project Structure
```
siprouter/
├── ts/ # TypeScript control plane
│ ├── sipproxy.ts # Main entry — bootstraps everything
│ ├── config.ts # Config loader & validation
│ ├── proxybridge.ts # Rust proxy-engine IPC bridge (smartrust)
│ ├── frontend.ts # Web dashboard HTTP/WS server + REST API
│ ├── webrtcbridge.ts # WebRTC signaling layer
│ ├── registrar.ts # Browser softphone registration
│ ├── voicebox.ts # Voicemail box management
│ └── call/
│ └── prompt-cache.ts # Named audio prompt WAV management
├── ts_web/ # Web frontend (Lit-based SPA)
│ ├── elements/ # Web components (9 dashboard views)
│ └── state/ # App state, WebRTC client, notifications
├── rust/ # Rust workspace (the data plane)
│ └── crates/
│ ├── codec-lib/ # Audio codec library (Opus/G.722/PCMU/PCMA)
│ ├── sip-proto/ # Zero-dependency SIP protocol library
│ └── proxy-engine/ # Main binary — SIP engine + mixer + RTP
├── html/ # Static HTML shell
├── .nogit/ # Secrets, config, TTS models (gitignored)
└── dist_rust/ # Compiled Rust binary (gitignored)
```
---
## 🎧 Audio Engine (Rust)
The `proxy-engine` binary handles all real-time audio processing with a **48kHz f32 internal bus** — encoding and decoding happens only at leg boundaries.
### Supported Codecs
| Codec | PT | Native Rate | Use Case |
|-------|:--:|:-----------:|----------|
| **Opus** | 111 | 48 kHz | WebRTC browsers (native float encode/decode — zero i16 quantization) |
| **G.722** | 9 | 16 kHz | HD SIP devices & providers |
| **PCMU** (G.711 µ-law) | 0 | 8 kHz | Legacy SIP |
| **PCMA** (G.711 A-law) | 8 | 8 kHz | Legacy SIP |
### Audio Pipeline
```mermaid
flowchart LR
subgraph Inbound["Inbound path (per leg)"]
direction LR
IN_RTP["Wire RTP"] --> IN_JB["Jitter Buffer"] --> IN_DEC["Decode"] --> IN_RS["Resample → 48 kHz"] --> IN_DN["Denoise (RNNoise)"] --> IN_BUS["Mix Bus"]
end
subgraph Outbound["Outbound path (per leg)"]
direction LR
OUT_BUS["Mix Bus"] --> OUT_MM["Mix-Minus"] --> OUT_RS["Resample → codec rate"] --> OUT_ENC["Encode"] --> OUT_RTP["Wire RTP"]
end
```
- **Adaptive jitter buffer** — per-leg `BTreeMap`-based buffer keyed by RTP sequence number. Delivers exactly one frame per 20ms mixer tick in sequence order. Adaptive target depth starts at 3 frames (60ms) and adjusts between 26 frames based on observed network jitter. Handles hold/resume by detecting large forward sequence jumps and resetting cleanly.
- **Packet loss concealment (PLC)** — on missing packets, Opus legs invoke the decoder's built-in PLC (`decode(None)`) to synthesize a smooth fill frame. Non-Opus legs (G.722, PCMU) apply exponential fade (0.85×) toward silence to avoid hard discontinuities.
- **FFT-based resampling** via `rubato` — high-quality sinc interpolation with canonical 20ms chunk sizes to ensure consistent resampler state across frames, preventing filter discontinuities
- **ML noise suppression** via `nnnoiseless` (RNNoise) — per-leg inbound denoising with SIMD acceleration (AVX/SSE). Skipped for WebRTC legs (browsers already denoise via getUserMedia)
- **Mix-minus mixing** — each participant hears everyone except themselves, accumulated in f64 precision
- **RFC 3550 compliant header parsing** — properly handles CSRC lists and header extensions
---
## 🗣️ Neural TTS
Voicemail greetings and IVR prompts are synthesized using [Kokoro TTS](https://github.com/mzdk100/kokoro) — an 82M parameter neural model running via ONNX Runtime directly in the Rust process:
- **24 kHz, 16-bit mono** output
- **25+ voice presets** — American/British, male/female (e.g., `af_bella`, `am_adam`, `bf_emma`, `bm_george`)
- **~800ms** synthesis time for a 3-second phrase
- Lazy-loaded on first use — no startup cost if TTS is unused
---
## 📧 Voicemail
- Configurable voicemail boxes with custom TTS greetings (text + voice) or uploaded WAV
- Automatic routing on no-answer timeout (configurable, default 25s)
- Recording with configurable max duration (default 120s) and message count limit (default 50)
- Unheard message tracking for MWI (message waiting indication)
- Web dashboard playback and management
- WAV storage in `.nogit/voicemail/`
---
## 🔢 IVR (Interactive Voice Response)
- DTMF-navigable menus with configurable entries
- Actions: route to extension, route to voicemail, transfer, submenu, hangup, repeat prompt
- Custom TTS prompts per menu
- Nested menu support
---
## 🌐 Web Dashboard & REST API
### Dashboard Views
| View | Description |
|------|-------------|
| 📊 **Overview** | Stats tiles — uptime, providers, devices, active calls |
| 📞 **Calls** | Active calls with leg details, codec info, add/remove legs, transfer, hangup |
| ☎️ **Phone** | Browser softphone — mic/speaker selection, audio meters, dial pad, incoming call popup |
| 🔀 **Routes** | Routing rule management — match/action model with priority |
| 📧 **Voicemail** | Voicemail box management + message playback |
| 🔢 **IVR** | IVR menu builder — DTMF entries, TTS prompts, nested menus |
| 👤 **Contacts** | Contact management with click-to-call |
| 🔌 **Providers** | SIP trunk configuration and registration status |
| 📋 **Log** | Live streaming log viewer |
### REST API
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/status` | GET | Full system status (providers, devices, calls, history) |
| `/api/call` | POST | Originate a call |
| `/api/hangup` | POST | Hang up a call |
| `/api/call/:id/addleg` | POST | Add a device leg to an active call |
| `/api/call/:id/addexternal` | POST | Add an external participant via provider |
| `/api/call/:id/removeleg` | POST | Remove a leg from a call |
| `/api/transfer` | POST | Transfer a call |
| `/api/config` | GET | Read current configuration |
| `/api/config` | POST | Update configuration (hot-reload) |
| `/api/voicemail/:box` | GET | List voicemail messages |
| `/api/voicemail/:box/unheard` | GET | Get unheard message count |
| `/api/voicemail/:box/:id/audio` | GET | Stream voicemail audio |
| `/api/voicemail/:box/:id/heard` | POST | Mark a voicemail message as heard |
| `/api/voicemail/:box/:id` | DELETE | Delete a voicemail message |
### WebSocket Events
Connect to `/ws` for real-time push:
```jsonc
{ "type": "status", "data": { ... } } // Full status snapshot (1s interval)
{ "type": "log", "data": { "message": "..." } } // Log lines in real-time
{ "type": "call-update", "data": { ... } } // Call state change notification
{ "type": "webrtc-answer", "data": { ... } } // WebRTC SDP answer for browser calls
{ "type": "webrtc-error", "data": { ... } } // WebRTC signaling error
```
Browser → server signaling:
```jsonc
{ "type": "webrtc-offer", "data": { ... } } // Browser sends SDP offer
{ "type": "webrtc-accept", "data": { ... } } // Browser accepts incoming call
{ "type": "webrtc-ice", "data": { ... } } // ICE candidate exchange
{ "type": "webrtc-hangup", "data": { ... } } // Browser hangs up
```
---
## 🔌 Ports
| Port | Protocol | Purpose |
|------|----------|---------|
| 5070 (configurable) | UDP | SIP signaling |
| 2000020200 (configurable) | UDP | RTP media (even ports, per-call allocation) |
| 3060 (configurable) | TCP | Web dashboard + WebSocket + REST API |
---
## 🛠️ Development
```bash
# Start in dev mode
pnpm start
# Build Rust proxy-engine
pnpm install
pnpm run buildRust
# Bundle web frontend
pnpm run bundle
# Build + bundle + restart background server
pnpm run restartBackground
pnpm start
```
---
Full build:
```bash
pnpm build
```
Docker build scripts are also present:
```bash
pnpm run build:docker
pnpm run release:docker
```
`pnpm run buildRust` uses `tsrust`. Per the project notes, do not replace that with a direct `cargo build` when validating the packaged Rust output. The configured build path cross-compiles the Rust engine for Linux amd64 and arm64 targets.
## Project Map
```text
siprouter/
├── ts/ # TypeScript control plane
├── ts_web/ # Browser dashboard
├── rust/
│ └── crates/
│ ├── codec-lib/ # Codec and transcoding helpers
│ ├── proxy-engine/ # Rust SIP/RTP/WebRTC/fax engine
│ └── sip-proto/ # SIP message/dialog/SDP library
├── html/ # Dashboard HTML shell
├── dist_rust/ # Built Rust binaries
├── dist_ts_web/ # Bundled web UI
└── .nogit/ # Local config, secrets, voicemail, fax, prompts
```
## License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](./license) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
+3
View File
@@ -28,3 +28,6 @@ rustflags = ["-C", "link-arg=-L.cargo/crosslibs/aarch64"]
CC_aarch64_unknown_linux_gnu = "aarch64-linux-gnu-gcc"
CXX_aarch64_unknown_linux_gnu = "aarch64-linux-gnu-g++"
AR_aarch64_unknown_linux_gnu = "aarch64-linux-gnu-ar"
PKG_CONFIG_ALLOW_CROSS = "1"
PKG_CONFIG_SYSROOT_DIR_aarch64_unknown_linux_gnu = "/"
PKG_CONFIG_LIBDIR_aarch64_unknown_linux_gnu = "/usr/lib/aarch64-linux-gnu/pkgconfig:/usr/share/pkgconfig"
+161 -23
View File
@@ -165,7 +165,7 @@ dependencies = [
"nom",
"num-traits",
"rusticata-macros",
"thiserror",
"thiserror 1.0.69",
"time",
]
@@ -181,7 +181,7 @@ dependencies = [
"nom",
"num-traits",
"rusticata-macros",
"thiserror",
"thiserror 1.0.69",
"time",
]
@@ -327,6 +327,26 @@ dependencies = [
"virtue",
]
[[package]]
name = "bindgen"
version = "0.72.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
dependencies = [
"bitflags 2.11.0",
"cexpr",
"clang-sys",
"itertools",
"log",
"prettyplease",
"proc-macro2",
"quote",
"regex",
"rustc-hash",
"shlex",
"syn 2.0.117",
]
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -429,6 +449,15 @@ dependencies = [
"smallvec",
]
[[package]]
name = "cexpr"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
dependencies = [
"nom",
]
[[package]]
name = "cfg-if"
version = "0.1.10"
@@ -498,6 +527,17 @@ dependencies = [
"inout",
]
[[package]]
name = "clang-sys"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
dependencies = [
"glob",
"libc",
"libloading",
]
[[package]]
name = "clap"
version = "3.2.25"
@@ -538,7 +578,7 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c9f73004e928ed46c3e7fd7406d2b12c8674153295f08af084b49860276dc02"
dependencies = [
"thiserror",
"thiserror 1.0.69",
]
[[package]]
@@ -1021,6 +1061,12 @@ dependencies = [
"signature",
]
[[package]]
name = "either"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
[[package]]
name = "elliptic-curve"
version = "0.12.3"
@@ -1367,6 +1413,12 @@ dependencies = [
"polyval",
]
[[package]]
name = "glob"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]]
name = "group"
version = "0.12.1"
@@ -1668,7 +1720,7 @@ dependencies = [
"rand 0.8.5",
"rtcp",
"rtp",
"thiserror",
"thiserror 1.0.69",
"tokio",
"waitgroup",
"webrtc-srtp",
@@ -1681,6 +1733,15 @@ version = "2.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.18"
@@ -1792,6 +1853,16 @@ dependencies = [
"rle-decode-fast",
]
[[package]]
name = "libloading"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
dependencies = [
"cfg-if 1.0.4",
"windows-link",
]
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -2386,7 +2457,9 @@ dependencies = [
"serde",
"serde_json",
"sip-proto",
"spandsp",
"tokio",
"udptl",
"webrtc",
]
@@ -2584,7 +2657,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6423493804221c276d27f3cc383cd5cbe1a1f10f210909fd4951b579b01293cd"
dependencies = [
"bytes",
"thiserror",
"thiserror 1.0.69",
"webrtc-util",
]
@@ -2594,7 +2667,7 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce5248489db464de29835170cd1f6e19933146b0016789effc59cb53d9f13844"
dependencies = [
"thiserror",
"thiserror 1.0.69",
]
[[package]]
@@ -2606,7 +2679,7 @@ dependencies = [
"bytes",
"rand 0.8.5",
"serde",
"thiserror",
"thiserror 1.0.69",
"webrtc-util",
]
@@ -2617,7 +2690,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7bb90df8268abfe08452ef2dae9e867a54edfdaa71b3127ef47d8b031f77ac73"
dependencies = [
"smallvec",
"thiserror",
"thiserror 1.0.69",
]
[[package]]
@@ -2744,7 +2817,7 @@ checksum = "4d22a5ef407871893fd72b4562ee15e4742269b173959db4b8df6f538c414e13"
dependencies = [
"rand 0.8.5",
"substring",
"thiserror",
"thiserror 1.0.69",
"url",
]
@@ -2957,6 +3030,28 @@ dependencies = [
"winapi",
]
[[package]]
name = "spandsp"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5f076b6e56f1a1062d6950dcd1c6c1df281ae2828db271929c50c191ec8c79e"
dependencies = [
"bitflags 2.11.0",
"spandsp-sys",
"thiserror 2.0.18",
]
[[package]]
name = "spandsp-sys"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c05ab99051230293dded61ba3cd32f06eb15b437a8135be21f560f72bab713db"
dependencies = [
"bindgen",
"cc",
"pkg-config",
]
[[package]]
name = "spin"
version = "0.5.2"
@@ -3004,7 +3099,7 @@ dependencies = [
"rand 0.8.5",
"ring",
"subtle",
"thiserror",
"thiserror 1.0.69",
"tokio",
"url",
"webrtc-util",
@@ -3104,7 +3199,16 @@ version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
dependencies = [
"thiserror-impl",
"thiserror-impl 1.0.69",
]
[[package]]
name = "thiserror"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
dependencies = [
"thiserror-impl 2.0.18",
]
[[package]]
@@ -3118,6 +3222,17 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "thiserror-impl"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "time"
version = "0.3.47"
@@ -3194,9 +3309,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
@@ -3230,7 +3357,7 @@ dependencies = [
"rand 0.8.5",
"ring",
"stun",
"thiserror",
"thiserror 1.0.69",
"tokio",
"webrtc-util",
]
@@ -3241,6 +3368,17 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
[[package]]
name = "udptl"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b255ad0ff36582a8a453c42a2bcc16c72d00f0ab16a14a4a7aeacb55ccb2a351"
dependencies = [
"thiserror 2.0.18",
"tokio",
"tracing",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
@@ -3532,7 +3670,7 @@ dependencies = [
"sha2",
"smol_str",
"stun",
"thiserror",
"thiserror 1.0.69",
"time",
"tokio",
"turn",
@@ -3557,7 +3695,7 @@ dependencies = [
"bytes",
"derive_builder",
"log",
"thiserror",
"thiserror 1.0.69",
"tokio",
"webrtc-sctp",
"webrtc-util",
@@ -3595,7 +3733,7 @@ dependencies = [
"sha2",
"signature",
"subtle",
"thiserror",
"thiserror 1.0.69",
"tokio",
"webpki",
"webrtc-util",
@@ -3617,7 +3755,7 @@ dependencies = [
"serde",
"serde_json",
"stun",
"thiserror",
"thiserror 1.0.69",
"tokio",
"turn",
"url",
@@ -3635,7 +3773,7 @@ checksum = "f08dfd7a6e3987e255c4dbe710dde5d94d0f0574f8a21afa95d171376c143106"
dependencies = [
"log",
"socket2 0.4.10",
"thiserror",
"thiserror 1.0.69",
"tokio",
"webrtc-util",
]
@@ -3650,7 +3788,7 @@ dependencies = [
"bytes",
"rand 0.8.5",
"rtp",
"thiserror",
"thiserror 1.0.69",
]
[[package]]
@@ -3665,7 +3803,7 @@ dependencies = [
"crc",
"log",
"rand 0.8.5",
"thiserror",
"thiserror 1.0.69",
"tokio",
"webrtc-util",
]
@@ -3688,7 +3826,7 @@ dependencies = [
"rtp",
"sha1",
"subtle",
"thiserror",
"thiserror 1.0.69",
"tokio",
"webrtc-util",
]
@@ -3709,7 +3847,7 @@ dependencies = [
"log",
"nix",
"rand 0.8.5",
"thiserror",
"thiserror 1.0.69",
"tokio",
"winapi",
]
@@ -3880,7 +4018,7 @@ dependencies = [
"nom",
"oid-registry 0.4.0",
"rusticata-macros",
"thiserror",
"thiserror 1.0.69",
"time",
]
@@ -3899,7 +4037,7 @@ dependencies = [
"oid-registry 0.6.1",
"ring",
"rusticata-macros",
"thiserror",
"thiserror 1.0.69",
"time",
]
+2
View File
@@ -19,6 +19,8 @@ regex-lite = "0.1"
webrtc = "0.8"
rand = "0.8"
hound = "3.5"
spandsp = "0.1.5"
udptl = "0.1.0"
kokoro-tts = { version = "0.3", default-features = false, features = ["use-cmudict"] }
ort = { version = "=2.0.0-rc.11", default-features = false, features = [
"std", "download-binaries", "copy-dylibs", "ndarray",
+52 -1
View File
@@ -11,7 +11,7 @@ use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Instant;
use tokio::net::UdpSocket;
use tokio::sync::mpsc;
use tokio::sync::{mpsc, watch};
use tokio::task::JoinHandle;
pub type LegId = String;
@@ -114,6 +114,13 @@ pub struct LegInfo {
pub kind: LegKind,
pub state: LegState,
pub codec_pt: u8,
/// Media transport currently negotiated for this leg.
///
/// `rtp` covers classic SIP audio media, `t38-udptl` covers T.38 fax,
/// `webrtc` is used for browser legs, and `internal` for proxy-local media/tool paths.
pub media_protocol: &'static str,
/// Whether this leg is currently wired into an active media bridge.
pub media_io_active: bool,
/// For SIP legs: the SIP dialog manager (handles 407 auth, BYE, etc).
pub sip_leg: Option<SipLeg>,
@@ -146,6 +153,15 @@ pub struct LegInfo {
pub metadata: HashMap<String, serde_json::Value>,
}
#[derive(Clone)]
pub struct PendingDialogBridge {
pub source_leg_id: LegId,
pub target_leg_id: LegId,
pub source_request: SipMessage,
pub target_request: SipMessage,
pub method: String,
}
/// A multiparty call with N legs and a central mixer.
pub struct Call {
// Duplicated from the HashMap key in CallManager. Kept for future
@@ -169,12 +185,21 @@ pub struct Call {
/// Used to construct proper 180/200/error responses back to the device.
pub device_invite: Option<SipMessage>,
/// Pending in-dialog B2BUA transaction bridged across two different SIP dialogs.
pub pending_dialog_bridge: Option<PendingDialogBridge>,
/// All legs in this call, keyed by leg ID.
pub legs: HashMap<LegId, LegInfo>,
/// Channel to send commands to the mixer task.
pub mixer_cmd_tx: mpsc::Sender<MixerCommand>,
/// Active passthrough media bridge mode, if any.
pub media_bridge_mode: Option<String>,
/// Cancellation handles for non-mixer passthrough media tasks.
media_bridge_cancel_txs: Vec<watch::Sender<bool>>,
/// Handle to the mixer task (aborted on call teardown).
mixer_task: Option<JoinHandle<()>>,
}
@@ -196,8 +221,11 @@ impl Call {
callee_number: None,
provider_id,
device_invite: None,
pending_dialog_bridge: None,
legs: HashMap::new(),
mixer_cmd_tx,
media_bridge_mode: None,
media_bridge_cancel_txs: Vec::new(),
mixer_task: Some(mixer_task),
}
}
@@ -235,8 +263,31 @@ impl Call {
self.created_at.elapsed().as_secs()
}
pub fn clear_media_bridge(&mut self) {
for cancel_tx in self.media_bridge_cancel_txs.drain(..) {
let _ = cancel_tx.send(true);
}
self.media_bridge_mode = None;
}
pub fn install_media_bridge(
&mut self,
mode: &str,
cancel_txs: Vec<watch::Sender<bool>>,
) {
self.clear_media_bridge();
self.media_bridge_mode = Some(mode.to_string());
self.media_bridge_cancel_txs = cancel_txs;
}
pub fn note_mixer_bridge(&mut self, mode: &str) {
self.clear_media_bridge();
self.media_bridge_mode = Some(mode.to_string());
}
/// Shut down the mixer and abort its task.
pub async fn shutdown_mixer(&mut self) {
self.clear_media_bridge();
let _ = self.mixer_cmd_tx.send(MixerCommand::Shutdown).await;
if let Some(handle) = self.mixer_task.take() {
handle.abort();
File diff suppressed because it is too large Load Diff
+19
View File
@@ -105,6 +105,8 @@ pub struct RouteAction {
pub ring_browsers: Option<bool>,
#[serde(rename = "voicemailBox")]
pub voicemail_box: Option<String>,
#[serde(rename = "faxBox")]
pub fax_box: Option<String>,
#[serde(rename = "ivrMenuId")]
pub ivr_menu_id: Option<String>,
#[serde(rename = "noAnswerTimeout")]
@@ -161,6 +163,8 @@ pub struct AppConfig {
pub devices: Vec<DeviceConfig>,
pub routing: RoutingConfig,
#[serde(default)]
pub faxboxes: Vec<FaxBoxConfig>,
#[serde(default)]
pub voiceboxes: Vec<VoiceboxConfig>,
#[serde(default)]
pub ivr: Option<IvrConfig>,
@@ -191,6 +195,16 @@ pub struct VoiceboxConfig {
pub max_recording_sec: Option<u32>,
}
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize)]
pub struct FaxBoxConfig {
pub id: String,
#[serde(default)]
pub enabled: bool,
#[serde(rename = "maxMessages")]
pub max_messages: Option<u32>,
}
// ---------------------------------------------------------------------------
// IVR config
// ---------------------------------------------------------------------------
@@ -415,6 +429,7 @@ pub struct InboundRouteResult {
pub ring_all_devices: bool,
pub ring_browsers: bool,
pub voicemail_box: Option<String>,
pub fax_box: Option<String>,
pub ivr_menu_id: Option<String>,
pub no_answer_timeout: Option<u32>,
}
@@ -525,6 +540,7 @@ impl AppConfig {
ring_all_devices: explicit_targets.is_none(),
ring_browsers: route.action.ring_browsers.unwrap_or(false),
voicemail_box: route.action.voicemail_box.clone(),
fax_box: route.action.fax_box.clone(),
ivr_menu_id: route.action.ivr_menu_id.clone(),
no_answer_timeout: route.action.no_answer_timeout,
});
@@ -574,6 +590,7 @@ mod tests {
extension: "100".to_string(),
}],
routing: RoutingConfig { routes },
faxboxes: vec![],
voiceboxes: vec![],
ivr: None,
}
@@ -620,6 +637,7 @@ mod tests {
targets: Some(vec!["desk".to_string()]),
ring_browsers: Some(true),
voicemail_box: None,
fax_box: None,
ivr_menu_id: None,
no_answer_timeout: None,
provider: None,
@@ -644,6 +662,7 @@ mod tests {
targets: None,
ring_browsers: Some(false),
voicemail_box: Some("support-box".to_string()),
fax_box: None,
ivr_menu_id: None,
no_answer_timeout: Some(20),
provider: None,
File diff suppressed because it is too large Load Diff
+54 -1
View File
@@ -10,7 +10,7 @@ use crate::mixer::RtpPacket;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::UdpSocket;
use tokio::sync::mpsc;
use tokio::sync::{mpsc, watch};
/// Channel pair for connecting a leg to the mixer.
pub struct LegChannels {
@@ -109,3 +109,56 @@ pub fn spawn_sip_outbound(
}
})
}
/// Spawn a raw UDP inbound task for non-RTP passthrough media such as T.38 UDPTL.
pub fn spawn_raw_udp_inbound(
media_socket: Arc<UdpSocket>,
inbound_tx: mpsc::Sender<Vec<u8>>,
mut cancel_rx: watch::Receiver<bool>,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
let mut buf = vec![0u8; 2048];
loop {
tokio::select! {
_ = cancel_rx.changed() => break,
recv = media_socket.recv_from(&mut buf) => {
match recv {
Ok((n, _from)) => {
if n == 0 {
continue;
}
if inbound_tx.send(buf[..n].to_vec()).await.is_err() {
break;
}
}
Err(_) => break,
}
}
}
}
})
}
/// Spawn a raw UDP outbound task for non-RTP passthrough media such as T.38 UDPTL.
pub fn spawn_raw_udp_outbound(
media_socket: Arc<UdpSocket>,
remote_media: SocketAddr,
mut outbound_rx: mpsc::Receiver<Vec<u8>>,
mut cancel_rx: watch::Receiver<bool>,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
loop {
tokio::select! {
_ = cancel_rx.changed() => break,
pkt = outbound_rx.recv() => {
match pkt {
Some(packet) => {
let _ = media_socket.send_to(&packet, remote_media).await;
}
None => break,
}
}
}
}
})
}
+165
View File
@@ -9,6 +9,8 @@ mod audio_player;
mod call;
mod call_manager;
mod config;
#[allow(dead_code)]
mod fax_engine;
mod ipc;
mod jitter_buffer;
mod leg_io;
@@ -139,6 +141,7 @@ async fn handle_command(
"configure" => handle_configure(engine, out_tx, &cmd).await,
"hangup" => handle_hangup(engine, out_tx, &cmd).await,
"make_call" => handle_make_call(engine, out_tx, &cmd).await,
"send_fax" => handle_send_fax(engine, out_tx, &cmd).await,
"add_leg" => handle_add_leg(engine, out_tx, &cmd).await,
"remove_leg" => handle_remove_leg(engine, out_tx, &cmd).await,
// WebRTC commands — lock webrtc only (no engine contention).
@@ -576,6 +579,162 @@ async fn handle_make_call(engine: Arc<Mutex<ProxyEngine>>, out_tx: &OutTx, cmd:
}
}
/// Handle `send_fax` — place an outbound server-side fax call via SpanDSP over G.711 audio.
async fn handle_send_fax(engine: Arc<Mutex<ProxyEngine>>, out_tx: &OutTx, cmd: &Command) {
let number = match cmd.params.get("number").and_then(|v| v.as_str()) {
Some(n) => n.to_string(),
None => {
respond_err(out_tx, &cmd.id, "missing number");
return;
}
};
let file_path = match cmd.params.get("file_path").and_then(|v| v.as_str()) {
Some(path) if std::path::Path::new(path).exists() => path.to_string(),
Some(_) => {
respond_err(out_tx, &cmd.id, "fax file does not exist");
return;
}
None => {
respond_err(out_tx, &cmd.id, "missing file_path");
return;
}
};
let provider_id = cmd.params.get("provider_id").and_then(|v| v.as_str());
let mut eng = engine.lock().await;
let config_ref = match &eng.config {
Some(c) => c.clone(),
None => {
respond_err(out_tx, &cmd.id, "not configured");
return;
}
};
let provider_config = if let Some(pid) = provider_id {
config_ref.providers.iter().find(|p| p.id == pid).cloned()
} else {
let route = config_ref.resolve_outbound_route(&number, None, &|_| true);
route.map(|r| r.provider)
};
let mut provider_config = match provider_config {
Some(p) => p,
None => {
respond_err(out_tx, &cmd.id, "no provider available");
return;
}
};
let fax_codec = if provider_config.codecs.contains(&codec_lib::PT_PCMU) {
codec_lib::PT_PCMU
} else if provider_config.codecs.contains(&codec_lib::PT_PCMA) {
codec_lib::PT_PCMA
} else {
respond_err(
out_tx,
&cmd.id,
&format!(
"provider {} does not advertise PCMU/PCMA, which outbound fax currently requires",
provider_config.id
),
);
return;
};
provider_config.codecs = vec![fax_codec];
let (public_ip, registered_aor) = if let Some(ps_arc) = eng
.provider_mgr
.find_by_address(
&provider_config
.outbound_proxy
.to_socket_addr()
.unwrap_or_else(|| "0.0.0.0:0".parse().unwrap()),
)
.await
{
let ps = ps_arc.lock().await;
(ps.public_ip.clone(), ps.registered_aor.clone())
} else {
(
None,
format!(
"sip:{}@{}",
provider_config.username, provider_config.domain
),
)
};
let socket = match &eng.transport {
Some(t) => t.socket(),
None => {
respond_err(out_tx, &cmd.id, "not initialized");
return;
}
};
let ProxyEngine {
ref mut call_mgr,
ref mut rtp_pool,
..
} = *eng;
let rtp_pool = rtp_pool.as_mut().unwrap();
let call_id = call_mgr
.make_outbound_call(
&number,
&provider_config,
&config_ref,
rtp_pool,
&socket,
public_ip.as_deref(),
&registered_aor,
)
.await;
let call_id = match call_id {
Some(id) => id,
None => {
respond_err(
out_tx,
&cmd.id,
"fax origination failed — provider not registered or no ports available",
);
return;
}
};
if let Some(call) = call_mgr.calls.get_mut(&call_id) {
let provider_leg_id = format!("{call_id}-prov");
if let Some(leg) = call.legs.get_mut(&provider_leg_id) {
leg.codec_pt = fax_codec;
leg.metadata
.insert("fax_mode".to_string(), serde_json::json!("outbound-audio"));
leg.metadata
.insert("fax_file_path".to_string(), serde_json::json!(file_path));
}
}
emit_event(
out_tx,
"outbound_call_started",
serde_json::json!({
"call_id": call_id,
"number": number,
"provider_id": provider_config.id,
"ring_browsers": false,
}),
);
respond_ok(
out_tx,
&cmd.id,
serde_json::json!({
"call_id": call_id,
"codec": if fax_codec == codec_lib::PT_PCMU { "PCMU" } else { "PCMA" },
}),
);
}
/// Handle the `hangup` command.
async fn handle_hangup(engine: Arc<Mutex<ProxyEngine>>, out_tx: &OutTx, cmd: &Command) {
let call_id = match cmd.params.get("call_id").and_then(|v| v.as_str()) {
@@ -738,6 +897,8 @@ async fn handle_webrtc_link(
kind: crate::call::LegKind::WebRtc,
state: crate::call::LegState::Connected,
codec_pt: codec_lib::PT_OPUS,
media_protocol: "webrtc",
media_io_active: true,
sip_leg: None,
sip_call_id: None,
webrtc_session_id: Some(session_id.clone()),
@@ -762,6 +923,7 @@ async fn handle_webrtc_link(
"state": "connected",
"codec": "Opus",
"rtpPort": 0,
"mediaProtocol": "webrtc",
"remoteMedia": null,
"metadata": {},
}),
@@ -1462,6 +1624,8 @@ async fn handle_add_tool_leg(engine: Arc<Mutex<ProxyEngine>>, out_tx: &OutTx, cm
kind: crate::call::LegKind::Tool,
state: crate::call::LegState::Connected,
codec_pt: 0,
media_protocol: "internal",
media_io_active: true,
sip_leg: None,
sip_call_id: None,
webrtc_session_id: None,
@@ -1485,6 +1649,7 @@ async fn handle_add_tool_leg(engine: Arc<Mutex<ProxyEngine>>, out_tx: &OutTx, cm
"state": "connected",
"codec": null,
"rtpPort": 0,
"mediaProtocol": "internal",
"remoteMedia": null,
"metadata": { "tool_type": tool_type_str },
}),
+25
View File
@@ -108,6 +108,24 @@ impl SipLeg {
..Default::default()
});
self.send_invite_with_sdp(from_uri, to_uri, sip_call_id, socket, sdp)
.await;
}
pub async fn send_invite_with_sdp(
&mut self,
from_uri: &str,
to_uri: &str,
sip_call_id: &str,
socket: &UdpSocket,
sdp: String,
) {
let ip = self
.config
.public_ip
.as_deref()
.unwrap_or(&self.config.lan_ip);
let invite = SipMessage::create_request(
"INVITE",
to_uri,
@@ -401,6 +419,10 @@ impl SipLeg {
return SipLegAction::Send(ok.serialize());
}
if method == "INVITE" || method == "UPDATE" {
return SipLegAction::InDialogRequest(method.to_string());
}
SipLegAction::None
}
@@ -436,6 +458,9 @@ pub enum SipLegAction {
StateChange(LegState),
/// Connected — send this ACK.
ConnectedWithAck(Vec<u8>),
/// Provider sent an in-dialog request (re-INVITE / UPDATE) that needs
/// call-manager-specific handling.
InDialogRequest(String),
/// Terminated with a reason.
Terminated(String),
/// Send 200 OK and terminate.
+107 -26
View File
@@ -4,6 +4,8 @@
use md5::{Digest, Md5};
use rand::Rng;
use crate::{Endpoint, SdpMediaKind};
// ---- ID generators ---------------------------------------------------------
/// Generate a random SIP Call-ID (32 hex chars).
@@ -55,6 +57,9 @@ pub struct SdpOptions<'a> {
pub ip: &'a str,
pub port: u16,
pub payload_types: &'a [u8],
pub media_kind: SdpMediaKind,
pub transport: &'a str,
pub media_formats: &'a [&'a str],
pub session_id: Option<&'a str>,
pub session_name: Option<&'a str>,
pub direction: Option<&'a str>,
@@ -67,6 +72,9 @@ impl<'a> Default for SdpOptions<'a> {
ip: "0.0.0.0",
port: 0,
payload_types: &[9, 0, 8, 101],
media_kind: SdpMediaKind::Audio,
transport: "RTP/AVP",
media_formats: &[],
session_id: None,
session_name: None,
direction: None,
@@ -83,7 +91,14 @@ pub fn build_sdp(opts: &SdpOptions) -> String {
.unwrap_or_else(|| format!("{}", rand::thread_rng().gen_range(0..1_000_000_000u64)));
let session_name = opts.session_name.unwrap_or("-");
let direction = opts.direction.unwrap_or("sendrecv");
let pts: Vec<String> = opts.payload_types.iter().map(|pt| pt.to_string()).collect();
let media_formats: Vec<String> = if !opts.media_formats.is_empty() {
opts.media_formats
.iter()
.map(|fmt| fmt.to_string())
.collect()
} else {
opts.payload_types.iter().map(|pt| pt.to_string()).collect()
};
let mut lines = vec![
"v=0".to_string(),
@@ -91,16 +106,24 @@ pub fn build_sdp(opts: &SdpOptions) -> String {
format!("s={session_name}"),
format!("c=IN IP4 {}", opts.ip),
"t=0 0".to_string(),
format!("m=audio {} RTP/AVP {}", opts.port, pts.join(" ")),
format!(
"m={} {} {} {}",
opts.media_kind.as_sdp_token(),
opts.port,
opts.transport,
media_formats.join(" ")
),
];
for &pt in opts.payload_types {
let name = codec_name(pt);
if name != "unknown" {
lines.push(format!("a=rtpmap:{pt} {name}"));
}
if pt == 101 {
lines.push("a=fmtp:101 0-16".to_string());
if opts.media_kind == SdpMediaKind::Audio {
for &pt in opts.payload_types {
let name = codec_name(pt);
if name != "unknown" {
lines.push(format!("a=rtpmap:{pt} {name}"));
}
if pt == 101 {
lines.push("a=fmtp:101 0-16".to_string());
}
}
}
@@ -199,38 +222,62 @@ pub fn compute_digest_auth(
// ---- SDP parser ------------------------------------------------------------
use crate::Endpoint;
/// Parse the audio media port, connection address, and preferred codec from an SDP body.
/// Parse the preferred media endpoint from an SDP body.
///
/// Audio `m=` lines are preferred when present so existing RTP call flows keep
/// their current behavior. If no audio section exists, the first media section
/// is returned, which allows T.38-only SDP offers/answers to be represented.
pub fn parse_sdp_endpoint(sdp: &str) -> Option<Endpoint> {
let mut addr: Option<&str> = None;
let mut port: Option<u16> = None;
let mut codec_pt: Option<u8> = None;
let mut preferred: Option<(SdpMediaKind, u16, Option<u8>, String)> = None;
let mut fallback: Option<(SdpMediaKind, u16, Option<u8>, String)> = None;
let normalized = sdp.replace("\r\n", "\n");
for raw in normalized.split('\n') {
let line = raw.trim();
if let Some(rest) = line.strip_prefix("c=IN IP4 ") {
addr = Some(rest.trim());
} else if let Some(rest) = line.strip_prefix("m=audio ") {
// m=audio <port> RTP/AVP <pt1> [<pt2> ...]
let parts: Vec<&str> = rest.split_whitespace().collect();
if !parts.is_empty() {
port = parts[0].parse().ok();
} else if let Some(rest) = line.strip_prefix("m=") {
// m=<media> <port> <transport> <fmt1> [<fmt2> ...]
let mut media_and_rest = rest.splitn(2, ' ');
let media = media_and_rest.next().unwrap_or("");
let remainder = media_and_rest.next().unwrap_or("");
let media_kind = SdpMediaKind::from_sdp_token(media);
if media_kind == SdpMediaKind::Unknown {
continue;
}
// parts[1] is "RTP/AVP" or similar, parts[2..] are payload types.
// The first PT is the preferred codec.
if parts.len() > 2 {
codec_pt = parts[2].parse::<u8>().ok();
let parts: Vec<&str> = remainder.split_whitespace().collect();
if !parts.is_empty() {
if let Ok(port) = parts[0].parse() {
let transport = parts.get(1).copied().unwrap_or("").to_string();
let codec_pt = if media_kind == SdpMediaKind::Audio && parts.len() > 2 {
parts[2].parse::<u8>().ok()
} else {
None
};
let candidate = (media_kind, port, codec_pt, transport);
if fallback.is_none() {
fallback = Some(candidate.clone());
}
if media_kind == SdpMediaKind::Audio {
preferred = Some(candidate);
} else if preferred.is_none() {
preferred = Some(candidate);
}
}
}
}
}
match (addr, port) {
(Some(a), Some(p)) => Some(Endpoint {
match (addr, preferred.or(fallback)) {
(Some(a), Some((media_kind, port, codec_pt, transport))) => Some(Endpoint {
address: a.to_string(),
port: p,
port,
codec_pt,
media_kind,
transport,
}),
_ => None,
}
@@ -327,6 +374,40 @@ mod tests {
let ep = parse_sdp_endpoint(sdp).unwrap();
assert_eq!(ep.address, "10.0.0.1");
assert_eq!(ep.port, 5060);
assert_eq!(ep.media_kind, SdpMediaKind::Audio);
assert_eq!(ep.transport, "RTP/AVP");
assert!(ep.is_audio_rtp());
}
#[test]
fn test_parse_t38_sdp_endpoint() {
let sdp = concat!(
"v=0\r\n",
"c=IN IP4 203.0.113.9\r\n",
"m=image 4000 udptl t38\r\n",
"a=T38FaxVersion:0\r\n",
);
let ep = parse_sdp_endpoint(sdp).unwrap();
assert_eq!(ep.address, "203.0.113.9");
assert_eq!(ep.port, 4000);
assert_eq!(ep.media_kind, SdpMediaKind::Image);
assert_eq!(ep.transport, "udptl");
assert!(ep.is_t38_udptl());
}
#[test]
fn test_build_t38_sdp() {
let sdp = build_sdp(&SdpOptions {
ip: "192.168.1.1",
port: 4000,
media_kind: SdpMediaKind::Image,
transport: "udptl",
media_formats: &["t38"],
attributes: &["T38FaxVersion:0"],
..Default::default()
});
assert!(sdp.contains("m=image 4000 udptl t38"));
assert!(sdp.contains("a=T38FaxVersion:0"));
}
#[test]
+43
View File
@@ -16,4 +16,47 @@ pub struct Endpoint {
pub port: u16,
/// First payload type from the SDP `m=audio` line (the preferred codec).
pub codec_pt: Option<u8>,
/// SDP media kind from the `m=` line.
pub media_kind: SdpMediaKind,
/// SDP transport token from the `m=` line (e.g. `RTP/AVP`, `udptl`).
pub transport: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SdpMediaKind {
Audio,
Image,
Application,
Unknown,
}
impl SdpMediaKind {
pub fn as_sdp_token(&self) -> &'static str {
match self {
Self::Audio => "audio",
Self::Image => "image",
Self::Application => "application",
Self::Unknown => "unknown",
}
}
pub fn from_sdp_token(token: &str) -> Self {
match token.to_ascii_lowercase().as_str() {
"audio" => Self::Audio,
"image" => Self::Image,
"application" => Self::Application,
_ => Self::Unknown,
}
}
}
impl Endpoint {
pub fn is_audio_rtp(&self) -> bool {
self.media_kind == SdpMediaKind::Audio
&& self.transport.to_ascii_uppercase().starts_with("RTP/")
}
pub fn is_t38_udptl(&self) -> bool {
self.media_kind == SdpMediaKind::Image && self.transport.eq_ignore_ascii_case("udptl")
}
}
+40 -9
View File
@@ -2,7 +2,7 @@
//!
//! Ported from ts/sip/rewrite.ts.
use crate::Endpoint;
use crate::{Endpoint, SdpMediaKind};
/// Replaces the host:port in every `sip:` / `sips:` URI found in `value`.
pub fn rewrite_sip_uri(value: &str, host: &str, port: u16) -> String {
@@ -57,12 +57,12 @@ pub fn rewrite_sip_uri(value: &str, host: &str, port: u16) -> String {
result
}
/// Rewrites the connection address (`c=`) and audio media port (`m=audio`)
/// in an SDP body. Returns the rewritten body together with the original
/// endpoint that was replaced (if any).
/// Rewrites the connection address (`c=`) and first supported media port
/// (`m=audio`, `m=image`, `m=application`) in an SDP body. Returns the
/// rewritten body together with the original endpoint that was replaced (if any).
pub fn rewrite_sdp(body: &str, ip: &str, port: u16) -> (String, Option<Endpoint>) {
let mut orig_addr: Option<String> = None;
let mut orig_port: Option<u16> = None;
let mut orig_media: Option<(SdpMediaKind, u16, String)> = None;
let lines: Vec<String> = body
.replace("\r\n", "\n")
@@ -71,10 +71,25 @@ pub fn rewrite_sdp(body: &str, ip: &str, port: u16) -> (String, Option<Endpoint>
if let Some(rest) = line.strip_prefix("c=IN IP4 ") {
orig_addr = Some(rest.trim().to_string());
format!("c=IN IP4 {ip}")
} else if line.starts_with("m=audio ") {
} else if line.starts_with("m=audio ")
|| line.starts_with("m=image ")
|| line.starts_with("m=application ")
{
let parts: Vec<&str> = line.split(' ').collect();
if parts.len() >= 2 {
orig_port = parts[1].parse().ok();
let media_kind = parts[0]
.strip_prefix("m=")
.map(SdpMediaKind::from_sdp_token)
.unwrap_or(SdpMediaKind::Unknown);
if orig_media.is_none() {
orig_media = parts[1].parse().ok().map(|orig_port| {
(
media_kind,
orig_port,
parts.get(2).copied().unwrap_or("").to_string(),
)
});
}
let mut rebuilt = parts[0].to_string();
rebuilt.push(' ');
rebuilt.push_str(&port.to_string());
@@ -91,11 +106,13 @@ pub fn rewrite_sdp(body: &str, ip: &str, port: u16) -> (String, Option<Endpoint>
})
.collect();
let original = match (orig_addr, orig_port) {
(Some(a), Some(p)) => Some(Endpoint {
let original = match (orig_addr, orig_media) {
(Some(a), Some((media_kind, p, transport))) => Some(Endpoint {
address: a,
port: p,
codec_pt: None,
media_kind,
transport,
}),
_ => None,
};
@@ -130,5 +147,19 @@ mod tests {
let ep = orig.unwrap();
assert_eq!(ep.address, "10.0.0.1");
assert_eq!(ep.port, 5060);
assert_eq!(ep.transport, "RTP/AVP");
}
#[test]
fn test_rewrite_t38_sdp() {
let sdp = "v=0\r\nc=IN IP4 10.0.0.1\r\nm=image 5060 udptl t38\r\na=T38FaxVersion:0\r\n";
let (rewritten, orig) = rewrite_sdp(sdp, "192.168.1.1", 4000);
assert!(rewritten.contains("c=IN IP4 192.168.1.1"));
assert!(rewritten.contains("m=image 4000 udptl t38"));
let ep = orig.unwrap();
assert_eq!(ep.address, "10.0.0.1");
assert_eq!(ep.port, 5060);
assert_eq!(ep.media_kind, SdpMediaKind::Image);
assert_eq!(ep.transport, "udptl");
}
}
+1 -1
View File
@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: 'siprouter',
version: '1.25.2',
version: '1.27.0',
description: 'undefined'
}
+184 -75
View File
@@ -1,13 +1,11 @@
/**
* Application configuration loaded from .nogit/config.json.
* Application configuration models and normalization helpers.
*
* All network addresses, credentials, provider settings, device definitions,
* and routing rules come from this single config file. No hardcoded values
* in source.
* and routing rules are persisted through SmartData.
*/
import fs from 'node:fs';
import path from 'node:path';
import type { IFaxBoxConfig } from './faxbox.ts';
import type { IVoiceboxConfig } from './voicebox.js';
// ---------------------------------------------------------------------------
@@ -113,6 +111,9 @@ export interface ISipRouteAction {
/** Voicemail fallback for matched inbound routes. */
voicemailBox?: string;
/** Fax inbox target for matched inbound routes. */
faxBox?: string;
/** Route to an IVR menu by menu ID (skip ringing devices). */
ivrMenuId?: string;
@@ -189,6 +190,7 @@ export interface IContact {
// "number | undefined is not assignable to number" type errors when
// passing config.voiceboxes into VoiceboxManager.init().
export type { IVoiceboxConfig };
export type { IFaxBoxConfig };
// ---------------------------------------------------------------------------
// IVR configuration
@@ -255,96 +257,203 @@ export interface IAppConfig {
incomingNumbers?: IIncomingNumberConfig[];
routing: IRoutingConfig;
contacts: IContact[];
faxboxes?: IFaxBoxConfig[];
voiceboxes?: IVoiceboxConfig[];
ivr?: IIvrConfig;
}
// ---------------------------------------------------------------------------
// Loader
// Defaults and normalization
// ---------------------------------------------------------------------------
const CONFIG_PATH = path.join(process.cwd(), '.nogit', 'config.json');
function requiredInitialEnv(keyArg: string): string {
const value = process.env[keyArg];
if (!value) {
throw new Error(`Missing required initial config environment variable: ${keyArg}`);
}
return value;
}
export function loadConfig(): IAppConfig {
let raw: string;
function numberFromEnv(keyArg: string, fallbackArg: number): number {
const value = process.env[keyArg];
if (!value) return fallbackArg;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : fallbackArg;
}
export function normalizeConfig(cfg: IAppConfig): IAppConfig {
try {
raw = fs.readFileSync(CONFIG_PATH, 'utf8');
} catch {
throw new Error(`config not found at ${CONFIG_PATH} — create .nogit/config.json`);
}
const cfg = JSON.parse(raw) as IAppConfig;
// Basic validation.
if (!cfg.proxy) throw new Error('config: missing "proxy" section');
if (!cfg.proxy.lanIp) throw new Error('config: missing proxy.lanIp');
if (!cfg.proxy.lanPort) throw new Error('config: missing proxy.lanPort');
if (!cfg.proxy.rtpPortRange?.min || !cfg.proxy.rtpPortRange?.max) {
throw new Error('config: missing proxy.rtpPortRange.min/max');
}
cfg.proxy.webUiPort ??= 3060;
cfg.proxy.publicIpSeed ??= null;
cfg.providers ??= [];
for (const p of cfg.providers) {
if (!p.id || !p.domain || !p.outboundProxy || !p.username || !p.password) {
throw new Error(`config: provider "${p.id || '?'}" missing required fields`);
// Basic validation.
if (!cfg.proxy) throw new Error('config: missing "proxy" section');
if (!cfg.proxy.lanIp) throw new Error('config: missing proxy.lanIp');
if (!cfg.proxy.lanPort) throw new Error('config: missing proxy.lanPort');
if (!cfg.proxy.rtpPortRange?.min || !cfg.proxy.rtpPortRange?.max) {
throw new Error('config: missing proxy.rtpPortRange.min/max');
}
p.displayName ??= p.id;
p.registerIntervalSec ??= 300;
p.codecs ??= [9, 0, 8, 101];
p.quirks ??= { earlyMediaSilence: false };
}
cfg.proxy.webUiPort ??= 3060;
cfg.proxy.publicIpSeed ??= null;
if (!Array.isArray(cfg.devices) || !cfg.devices.length) {
throw new Error('config: need at least one device');
}
for (const d of cfg.devices) {
if (!d.id || !d.expectedAddress) {
throw new Error(`config: device "${d.id || '?'}" missing required fields`);
cfg.providers ??= [];
for (const p of cfg.providers) {
if (!p.id || !p.domain || !p.outboundProxy || !p.username || !p.password) {
throw new Error(`config: provider "${p.id || '?'}" missing required fields`);
}
p.displayName ??= p.id;
p.registerIntervalSec ??= 300;
p.codecs ??= [9, 0, 8, 101];
p.quirks ??= { earlyMediaSilence: false };
}
d.displayName ??= d.id;
d.extension ??= '100';
if (!Array.isArray(cfg.devices) || !cfg.devices.length) {
throw new Error('config: need at least one device');
}
for (const d of cfg.devices) {
if (!d.id || !d.expectedAddress) {
throw new Error(`config: device "${d.id || '?'}" missing required fields`);
}
d.displayName ??= d.id;
d.extension ??= '100';
}
cfg.incomingNumbers ??= [];
for (const incoming of cfg.incomingNumbers) {
if (!incoming.id) incoming.id = `incoming-${Date.now()}`;
incoming.label ??= incoming.id;
incoming.mode ??= incoming.pattern ? 'regex' : incoming.rangeStart || incoming.rangeEnd ? 'range' : 'single';
incoming.countryCode ??= incoming.mode === 'regex' ? undefined : '+49';
}
cfg.routing ??= { routes: [] };
cfg.routing.routes ??= [];
cfg.contacts ??= [];
for (const c of cfg.contacts) {
c.starred ??= false;
}
cfg.faxboxes ??= [];
for (const fb of cfg.faxboxes) {
fb.enabled ??= true;
fb.maxMessages ??= 50;
}
cfg.voiceboxes ??= [];
for (const vb of cfg.voiceboxes) {
vb.enabled ??= true;
vb.noAnswerTimeoutSec ??= 25;
vb.maxRecordingSec ??= 120;
vb.maxMessages ??= 50;
vb.greetingVoice ??= 'af_bella';
}
if (cfg.ivr) {
cfg.ivr.enabled ??= false;
cfg.ivr.menus ??= [];
for (const menu of cfg.ivr.menus) {
menu.timeoutSec ??= 5;
menu.maxRetries ??= 3;
menu.entries ??= [];
}
}
return cfg;
} catch (error) {
throw error;
}
}
cfg.incomingNumbers ??= [];
for (const incoming of cfg.incomingNumbers) {
if (!incoming.id) incoming.id = `incoming-${Date.now()}`;
incoming.label ??= incoming.id;
incoming.mode ??= incoming.pattern ? 'regex' : incoming.rangeStart || incoming.rangeEnd ? 'range' : 'single';
incoming.countryCode ??= incoming.mode === 'regex' ? undefined : '+49';
}
export function createInitialConfigFromEnv(): IAppConfig {
return normalizeConfig({
proxy: {
lanIp: requiredInitialEnv('SIPROUTER_LAN_IP'),
lanPort: numberFromEnv('SIPROUTER_LAN_PORT', 5070),
publicIpSeed: process.env.SIPROUTER_PUBLIC_IP || null,
rtpPortRange: {
min: numberFromEnv('SIPROUTER_RTP_PORT_MIN', 20000),
max: numberFromEnv('SIPROUTER_RTP_PORT_MAX', 20200),
},
webUiPort: numberFromEnv('SIPROUTER_WEB_UI_PORT', 3060),
},
providers: [],
devices: [
{
id: process.env.SIPROUTER_INITIAL_DEVICE_ID || 'desk-phone',
displayName: process.env.SIPROUTER_INITIAL_DEVICE_DISPLAY_NAME || 'Desk Phone',
expectedAddress: requiredInitialEnv('SIPROUTER_INITIAL_DEVICE_ADDRESS'),
extension: process.env.SIPROUTER_INITIAL_DEVICE_EXTENSION || '100',
},
],
incomingNumbers: [],
routing: { routes: [] },
contacts: [],
faxboxes: [],
voiceboxes: [],
ivr: {
enabled: false,
entryMenuId: 'main-menu',
menus: [],
},
});
}
cfg.routing ??= { routes: [] };
cfg.routing.routes ??= [];
export function maskConfig(configArg: IAppConfig): IAppConfig {
return {
...configArg,
providers: configArg.providers?.map((providerArg) => ({
...providerArg,
password: providerArg.password ? '••••••' : providerArg.password,
})) || [],
};
}
cfg.contacts ??= [];
for (const c of cfg.contacts) {
c.starred ??= false;
}
export function applyConfigUpdates(configArg: IAppConfig, updatesArg: any): IAppConfig {
const cfg = JSON.parse(JSON.stringify(configArg)) as IAppConfig;
// Voicebox defaults.
cfg.voiceboxes ??= [];
for (const vb of cfg.voiceboxes) {
vb.enabled ??= true;
vb.noAnswerTimeoutSec ??= 25;
vb.maxRecordingSec ??= 120;
vb.maxMessages ??= 50;
vb.greetingVoice ??= 'af_bella';
}
// IVR defaults.
if (cfg.ivr) {
cfg.ivr.enabled ??= false;
cfg.ivr.menus ??= [];
for (const menu of cfg.ivr.menus) {
menu.timeoutSec ??= 5;
menu.maxRetries ??= 3;
menu.entries ??= [];
if (updatesArg.providers) {
for (const up of updatesArg.providers) {
const existing = cfg.providers?.find((p: any) => p.id === up.id);
if (existing) {
if (up.displayName !== undefined) existing.displayName = up.displayName;
if (up.password && up.password !== '••••••') existing.password = up.password;
if (up.domain !== undefined) existing.domain = up.domain;
if (up.outboundProxy !== undefined) existing.outboundProxy = up.outboundProxy;
if (up.username !== undefined) existing.username = up.username;
if (up.registerIntervalSec !== undefined) existing.registerIntervalSec = up.registerIntervalSec;
if (up.codecs !== undefined) existing.codecs = up.codecs;
if (up.quirks !== undefined) existing.quirks = up.quirks;
}
}
}
return cfg;
if (updatesArg.addProvider) {
cfg.providers ??= [];
cfg.providers.push(updatesArg.addProvider);
}
if (updatesArg.removeProvider) {
cfg.providers = (cfg.providers || []).filter((p: any) => p.id !== updatesArg.removeProvider);
if (cfg.routing?.routes) {
cfg.routing.routes = cfg.routing.routes.filter((r: any) =>
r.match?.sourceProvider !== updatesArg.removeProvider &&
r.action?.provider !== updatesArg.removeProvider
);
}
}
if (updatesArg.devices) {
for (const ud of updatesArg.devices) {
const existing = cfg.devices?.find((d: any) => d.id === ud.id);
if (existing && ud.displayName !== undefined) existing.displayName = ud.displayName;
}
}
if (updatesArg.incomingNumbers !== undefined) cfg.incomingNumbers = updatesArg.incomingNumbers;
if (updatesArg.routing?.routes) cfg.routing.routes = updatesArg.routing.routes;
if (updatesArg.contacts !== undefined) cfg.contacts = updatesArg.contacts;
if (updatesArg.faxboxes !== undefined) cfg.faxboxes = updatesArg.faxboxes;
if (updatesArg.voiceboxes !== undefined) cfg.voiceboxes = updatesArg.voiceboxes;
if (updatesArg.ivr !== undefined) cfg.ivr = updatesArg.ivr;
return normalizeConfig(cfg);
}
// Route resolution, pattern matching, and provider/device lookup
+197
View File
@@ -0,0 +1,197 @@
import fs from 'node:fs';
import * as fsPromises from 'node:fs/promises';
import path from 'node:path';
import type { SiprouterStorage } from './storage.ts';
export interface IFaxBoxConfig {
id: string;
enabled: boolean;
maxMessages?: number;
}
export interface IFaxMessage {
id: string;
boxId: string;
callerNumber?: string;
timestamp: number;
fileName: string;
objectKey?: string;
completionCode?: number | null;
completionLabel?: string | null;
pageCount?: number;
bitRate?: number;
}
export class FaxBoxManager {
private boxes = new Map<string, IFaxBoxConfig>();
private messagesByBox = new Map<string, IFaxMessage[]>();
private readonly basePath: string;
private readonly log: (msg: string) => void;
private readonly storage: SiprouterStorage;
constructor(log: (msg: string) => void, storageArg: SiprouterStorage) {
this.basePath = path.join(process.cwd(), '.nogit', 'fax', 'inboxes');
this.log = log;
this.storage = storageArg;
}
async init(faxBoxConfigs: IFaxBoxConfig[]): Promise<void> {
this.boxes.clear();
for (const cfg of faxBoxConfigs) {
cfg.enabled ??= true;
cfg.maxMessages ??= 50;
this.boxes.set(cfg.id, cfg);
this.messagesByBox.set(cfg.id, await this.loadMessages(cfg.id));
}
await fsPromises.mkdir(this.basePath, { recursive: true });
this.log(`[faxbox] initialized ${this.boxes.size} fax box(es)`);
}
getBox(boxId: string): IFaxBoxConfig | null {
return this.boxes.get(boxId) ?? null;
}
getBoxDir(boxId: string): string {
return path.join(this.basePath, boxId);
}
async prepareOutboundFaxFile(filePathArg: string): Promise<string> {
const localPath = path.isAbsolute(filePathArg) ? filePathArg : path.join(process.cwd(), filePathArg);
await fsPromises.access(localPath);
return localPath;
}
async addMessage(
boxId: string,
info: {
callerNumber?: string;
fileName: string;
completionCode?: number | null;
completionLabel?: string | null;
pageCount?: number;
bitRate?: number;
},
): Promise<void> {
const id = crypto.randomUUID();
const localPath = path.isAbsolute(info.fileName) ? info.fileName : path.join(process.cwd(), info.fileName);
const objectKey = await this.storage.putFileObject(`fax/inboxes/${boxId}/${id}.tif`, localPath);
const msg: IFaxMessage = {
id,
boxId,
callerNumber: info.callerNumber,
timestamp: Date.now(),
fileName: path.basename(localPath),
objectKey,
completionCode: info.completionCode ?? null,
completionLabel: info.completionLabel ?? null,
pageCount: info.pageCount,
bitRate: info.bitRate,
};
const messages = this.getMessages(boxId);
messages.unshift(msg);
await this.enforceLimit(boxId, messages);
await this.writeMessages(boxId, messages);
await fsPromises.rm(localPath, { force: true }).catch(() => {});
this.log(`[faxbox] saved fax ${msg.id} in box "${msg.boxId}" (${msg.fileName})`);
}
getMessages(boxId: string): IFaxMessage[] {
return [...(this.messagesByBox.get(boxId) || [])];
}
getMessage(boxId: string, messageId: string): IFaxMessage | null {
const messages = this.messagesByBox.get(boxId) || [];
return messages.find((m) => m.id === messageId) ?? null;
}
async getMessageFilePath(boxId: string, messageId: string): Promise<string | null> {
const msg = this.getMessage(boxId, messageId);
if (!msg) return null;
if (msg.objectKey) {
return await this.storage.getObjectAsCachedFile(msg.objectKey, msg.fileName);
}
const filePath = path.join(this.getBoxDir(boxId), msg.fileName);
return fs.existsSync(filePath) ? filePath : null;
}
async deleteMessage(boxId: string, messageId: string): Promise<boolean> {
const messages = this.messagesByBox.get(boxId) || [];
const idx = messages.findIndex((m) => m.id === messageId);
if (idx === -1) return false;
const msg = messages[idx];
await this.storage.removeObject(msg.objectKey);
if (!msg.objectKey) {
await fsPromises.rm(path.join(this.getBoxDir(boxId), msg.fileName), { force: true }).catch(() => {});
}
messages.splice(idx, 1);
await this.writeMessages(boxId, messages);
return true;
}
private async enforceLimit(boxId: string, messages: IFaxMessage[]): Promise<void> {
const box = this.boxes.get(boxId);
const maxMessages = box?.maxMessages ?? 50;
while (messages.length > maxMessages) {
const old = messages.pop()!;
await this.storage.removeObject(old.objectKey);
if (!old.objectKey) {
await fsPromises.rm(path.join(this.getBoxDir(boxId), old.fileName), { force: true }).catch(() => {});
}
}
}
private async loadMessages(boxId: string): Promise<IFaxMessage[]> {
const storedMessages = await this.storage.getFaxMessages(boxId);
if (storedMessages.length) return await this.ensureMessageObjects(boxId, storedMessages);
const filePath = path.join(this.getBoxDir(boxId), 'messages.json');
try {
if (!fs.existsSync(filePath)) return [];
const raw = await fsPromises.readFile(filePath, 'utf8');
const legacyMessages = await this.ensureMessageObjects(boxId, JSON.parse(raw) as IFaxMessage[]);
await this.storage.writeFaxMessages(boxId, legacyMessages);
return legacyMessages;
} catch {
return [];
}
}
private async ensureMessageObjects(boxId: string, messages: IFaxMessage[]): Promise<IFaxMessage[]> {
let changed = false;
for (const msg of messages) {
if (!msg.id) {
msg.id = crypto.randomUUID();
changed = true;
}
if (msg.objectKey) continue;
const localPath = path.isAbsolute(msg.fileName) ? msg.fileName : path.join(this.getBoxDir(boxId), msg.fileName);
if (!fs.existsSync(localPath)) continue;
const extension = path.extname(localPath) || '.tif';
msg.objectKey = await this.storage.putFileObject(`fax/inboxes/${boxId}/${msg.id}${extension}`, localPath);
msg.fileName = path.basename(localPath);
changed = true;
}
if (changed) {
await this.storage.writeFaxMessages(boxId, messages);
this.log(`[faxbox] migrated legacy messages for box "${boxId}" to smartbucket`);
}
return messages;
}
private async writeMessages(boxId: string, messages: IFaxMessage[]): Promise<void> {
this.messagesByBox.set(boxId, [...messages]);
await this.storage.writeFaxMessages(boxId, messages);
}
}
+149
View File
@@ -0,0 +1,149 @@
import fs from 'node:fs';
import path from 'node:path';
import type { SiprouterStorage } from './storage.ts';
import type {
IFaxCompletedEvent,
IFaxFailedEvent,
IFaxStartedEvent,
} from './shared/proxy-events.ts';
export interface IFaxJob {
id: string;
callId: string;
number?: string;
providerId?: string;
direction: 'outbound' | 'inbound';
status: 'dialing' | 'started' | 'completed' | 'failed';
transport?: 'audio' | 't38';
filePath?: string;
objectKey?: string;
codec?: string;
remoteMedia?: string;
success?: boolean;
completionCode?: number | null;
completionLabel?: string | null;
error?: string;
stats?: IFaxCompletedEvent['stats'];
createdAt: number;
updatedAt: number;
}
export class FaxJobManager {
private jobs: IFaxJob[] = [];
private readonly log: (msg: string) => void;
private readonly storage: SiprouterStorage;
constructor(log: (msg: string) => void, storageArg: SiprouterStorage) {
this.log = log;
this.storage = storageArg;
}
async init(): Promise<void> {
this.jobs = await this.storage.getFaxJobs();
}
async noteDialing(callId: string, number: string, providerId: string): Promise<void> {
const jobs = this.jobs;
const now = Date.now();
const existing = jobs.find((job) => job.callId === callId);
if (existing) {
existing.number = number;
existing.providerId = providerId;
existing.updatedAt = now;
} else {
jobs.unshift({
id: callId,
callId,
number,
providerId,
direction: 'outbound',
status: 'dialing',
createdAt: now,
updatedAt: now,
});
}
await this.writeJobs();
}
async noteStarted(event: IFaxStartedEvent): Promise<void> {
const now = Date.now();
const job = this.getOrCreateJob(event.call_id, event.direction, now);
job.status = 'started';
job.transport = event.transport;
job.filePath = event.file_path;
await this.ensureOutboundFileObject(job, event.file_path);
job.codec = event.codec;
job.remoteMedia = event.remote_media;
job.updatedAt = now;
await this.writeJobs();
}
async noteCompleted(event: IFaxCompletedEvent): Promise<void> {
const now = Date.now();
const job = this.getOrCreateJob(event.call_id, event.direction, now);
job.status = 'completed';
job.transport = event.transport;
job.filePath = event.file_path;
await this.ensureOutboundFileObject(job, event.file_path);
job.codec = event.codec;
job.success = event.success;
job.completionCode = event.completion_code ?? null;
job.completionLabel = event.completion_label ?? null;
job.stats = event.stats;
job.updatedAt = now;
await this.writeJobs();
}
async noteFailed(event: IFaxFailedEvent): Promise<void> {
const now = Date.now();
const job = this.getOrCreateJob(event.call_id, event.direction, now);
job.status = 'failed';
job.transport = event.transport;
job.filePath = event.file_path;
await this.ensureOutboundFileObject(job, event.file_path);
job.error = event.error;
job.success = false;
job.updatedAt = now;
await this.writeJobs();
}
getJobs(): IFaxJob[] {
return [...this.jobs];
}
private getOrCreateJob(
callId: string,
direction: 'outbound' | 'inbound',
now: number,
): IFaxJob {
let job = this.jobs.find((entry) => entry.callId === callId);
if (!job) {
job = {
id: callId,
callId,
direction,
status: 'dialing',
createdAt: now,
updatedAt: now,
};
this.jobs.unshift(job);
}
return job;
}
private async ensureOutboundFileObject(jobArg: IFaxJob, filePathArg: string | undefined): Promise<void> {
if (jobArg.direction !== 'outbound' || jobArg.objectKey || !filePathArg) return;
const localPath = path.isAbsolute(filePathArg) ? filePathArg : path.join(process.cwd(), filePathArg);
if (!fs.existsSync(localPath)) return;
const extension = path.extname(localPath) || '.tif';
jobArg.objectKey = await this.storage.putFileObject(`fax/outbound/${jobArg.callId}${extension}`, localPath);
}
private async writeJobs(): Promise<void> {
await this.storage.writeFaxJobs(this.jobs);
this.log(`[fax] persisted ${this.jobs.length} job(s)`);
}
}
+88 -75
View File
@@ -11,17 +11,21 @@ import path from 'node:path';
import http from 'node:http';
import https from 'node:https';
import { WebSocketServer, WebSocket } from 'ws';
import { maskConfig, type IAppConfig } from './config.ts';
import type { FaxBoxManager } from './faxbox.ts';
import type { FaxJobManager } from './faxjobs.ts';
import { handleWebRtcSignaling } from './webrtcbridge.ts';
import type { VoiceboxManager } from './voicebox.ts';
const CONFIG_PATH = path.join(process.cwd(), '.nogit', 'config.json');
interface IHandleRequestContext {
getStatus: () => unknown;
getConfig: () => IAppConfig;
updateConfig: (updatesArg: any) => Promise<IAppConfig>;
log: (msg: string) => void;
onStartCall: (number: string, deviceId?: string, providerId?: string) => { id: string } | null;
onStartCall: (number: string, deviceId?: string, providerId?: string) => Promise<{ id: string } | null>;
onHangupCall: (callId: string) => boolean;
onConfigSaved?: () => void | Promise<void>;
faxBoxManager?: FaxBoxManager;
faxJobManager?: FaxJobManager;
voiceboxManager?: VoiceboxManager;
}
@@ -108,7 +112,7 @@ async function handleRequest(
res: http.ServerResponse,
context: IHandleRequestContext,
): Promise<void> {
const { getStatus, log, onStartCall, onHangupCall, onConfigSaved, voiceboxManager } = context;
const { getStatus, getConfig, updateConfig, log, onStartCall, onHangupCall, faxBoxManager, faxJobManager, voiceboxManager } = context;
const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
const method = req.method || 'GET';
@@ -125,7 +129,7 @@ async function handleRequest(
if (!number || typeof number !== 'string') {
return sendJson(res, { ok: false, error: 'missing "number" field' }, 400);
}
const call = onStartCall(number, body?.deviceId, body?.providerId);
const call = await onStartCall(number, body?.deviceId, body?.providerId);
if (call) return sendJson(res, { ok: true, callId: call.id });
return sendJson(res, { ok: false, error: 'call origination failed — provider not registered or no ports available' }, 503);
} catch (e: any) {
@@ -147,6 +151,68 @@ async function handleRequest(
}
}
// API: send outbound fax.
if (url.pathname === '/api/fax' && method === 'POST') {
try {
const body = await readJsonBody(req);
const number = body?.number;
let filePath = body?.filePath;
if (!number || typeof number !== 'string') {
return sendJson(res, { ok: false, error: 'missing "number" field' }, 400);
}
if (!filePath || typeof filePath !== 'string') {
return sendJson(res, { ok: false, error: 'missing "filePath" field' }, 400);
}
if (faxBoxManager) {
filePath = await faxBoxManager.prepareOutboundFaxFile(filePath);
}
const { sendFax } = await import('./proxybridge.ts');
const callId = await sendFax(number, filePath, body?.providerId);
if (callId) {
log(`[dashboard] fax started: ${callId} -> ${number} file=${filePath}`);
return sendJson(res, { ok: true, callId });
}
return sendJson(res, { ok: false, error: 'fax origination failed' }, 503);
} catch (e: any) {
return sendJson(res, { ok: false, error: e.message }, 400);
}
}
// API: fax jobs.
if (url.pathname === '/api/fax/jobs' && method === 'GET' && faxJobManager) {
return sendJson(res, { ok: true, jobs: faxJobManager.getJobs() });
}
// API: fax inbox - list messages.
const faxListMatch = url.pathname.match(/^\/api\/fax\/inboxes\/([^/]+)$/);
if (faxListMatch && method === 'GET' && faxBoxManager) {
const boxId = faxListMatch[1];
return sendJson(res, { ok: true, messages: faxBoxManager.getMessages(boxId) });
}
// API: fax inbox - stream TIFF.
const faxFileMatch = url.pathname.match(/^\/api\/fax\/inboxes\/([^/]+)\/([^/]+)\/file$/);
if (faxFileMatch && method === 'GET' && faxBoxManager) {
const [, boxId, msgId] = faxFileMatch;
const filePath = await faxBoxManager.getMessageFilePath(boxId, msgId);
if (!filePath) return sendJson(res, { ok: false, error: 'not found' }, 404);
const stat = fs.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'image/tiff',
'Content-Length': stat.size.toString(),
'Accept-Ranges': 'bytes',
});
fs.createReadStream(filePath).pipe(res);
return;
}
// API: fax inbox - delete message.
const faxDeleteMatch = url.pathname.match(/^\/api\/fax\/inboxes\/([^/]+)\/([^/]+)$/);
if (faxDeleteMatch && method === 'DELETE' && faxBoxManager) {
const [, boxId, msgId] = faxDeleteMatch;
return sendJson(res, { ok: await faxBoxManager.deleteMessage(boxId, msgId) });
}
// API: add a SIP device to a call (mid-call INVITE to desk phone).
if (url.pathname.startsWith('/api/call/') && url.pathname.endsWith('/addleg') && method === 'POST') {
try {
@@ -209,10 +275,7 @@ async function handleRequest(
// API: get config (sans passwords).
if (url.pathname === '/api/config' && method === 'GET') {
try {
const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
const cfg = JSON.parse(raw);
const safe = { ...cfg, providers: cfg.providers?.map((p: any) => ({ ...p, password: '••••••' })) };
return sendJson(res, safe);
return sendJson(res, maskConfig(getConfig()));
} catch (e: any) {
return sendJson(res, { ok: false, error: e.message }, 500);
}
@@ -222,64 +285,9 @@ async function handleRequest(
if (url.pathname === '/api/config' && method === 'POST') {
try {
const updates = await readJsonBody(req);
const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
const cfg = JSON.parse(raw);
// Update existing providers.
if (updates.providers) {
for (const up of updates.providers) {
const existing = cfg.providers?.find((p: any) => p.id === up.id);
if (existing) {
if (up.displayName !== undefined) existing.displayName = up.displayName;
if (up.password && up.password !== '••••••') existing.password = up.password;
if (up.domain !== undefined) existing.domain = up.domain;
if (up.outboundProxy !== undefined) existing.outboundProxy = up.outboundProxy;
if (up.username !== undefined) existing.username = up.username;
if (up.registerIntervalSec !== undefined) existing.registerIntervalSec = up.registerIntervalSec;
if (up.codecs !== undefined) existing.codecs = up.codecs;
if (up.quirks !== undefined) existing.quirks = up.quirks;
}
}
}
// Add a new provider.
if (updates.addProvider) {
cfg.providers ??= [];
cfg.providers.push(updates.addProvider);
}
// Remove a provider.
if (updates.removeProvider) {
cfg.providers = (cfg.providers || []).filter((p: any) => p.id !== updates.removeProvider);
// Clean up routing references — remove routes that reference this provider.
if (cfg.routing?.routes) {
cfg.routing.routes = cfg.routing.routes.filter((r: any) =>
r.match?.sourceProvider !== updates.removeProvider &&
r.action?.provider !== updates.removeProvider
);
}
}
if (updates.devices) {
for (const ud of updates.devices) {
const existing = cfg.devices?.find((d: any) => d.id === ud.id);
if (existing && ud.displayName !== undefined) existing.displayName = ud.displayName;
}
}
if (updates.incomingNumbers !== undefined) cfg.incomingNumbers = updates.incomingNumbers;
if (updates.routing) {
if (updates.routing.routes) {
cfg.routing.routes = updates.routing.routes;
}
}
if (updates.contacts !== undefined) cfg.contacts = updates.contacts;
if (updates.voiceboxes !== undefined) cfg.voiceboxes = updates.voiceboxes;
if (updates.ivr !== undefined) cfg.ivr = updates.ivr;
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2) + '\n');
log('[config] updated config.json');
await onConfigSaved?.();
return sendJson(res, { ok: true });
const config = await updateConfig(updates);
log('[config] updated smartdata config');
return sendJson(res, { ok: true, config: maskConfig(config) });
} catch (e: any) {
return sendJson(res, { ok: false, error: e.message }, 400);
}
@@ -303,7 +311,7 @@ async function handleRequest(
const vmAudioMatch = url.pathname.match(/^\/api\/voicemail\/([^/]+)\/([^/]+)\/audio$/);
if (vmAudioMatch && method === 'GET' && voiceboxManager) {
const [, boxId, msgId] = vmAudioMatch;
const audioPath = voiceboxManager.getMessageAudioPath(boxId, msgId);
const audioPath = await voiceboxManager.getMessageAudioPath(boxId, msgId);
if (!audioPath) return sendJson(res, { ok: false, error: 'not found' }, 404);
const stat = fs.statSync(audioPath);
res.writeHead(200, {
@@ -319,14 +327,14 @@ async function handleRequest(
const vmHeardMatch = url.pathname.match(/^\/api\/voicemail\/([^/]+)\/([^/]+)\/heard$/);
if (vmHeardMatch && method === 'POST' && voiceboxManager) {
const [, boxId, msgId] = vmHeardMatch;
return sendJson(res, { ok: voiceboxManager.markHeard(boxId, msgId) });
return sendJson(res, { ok: await voiceboxManager.markHeard(boxId, msgId) });
}
// API: voicemail - delete message.
const vmDeleteMatch = url.pathname.match(/^\/api\/voicemail\/([^/]+)\/([^/]+)$/);
if (vmDeleteMatch && method === 'DELETE' && voiceboxManager) {
const [, boxId, msgId] = vmDeleteMatch;
return sendJson(res, { ok: voiceboxManager.deleteMessage(boxId, msgId) });
return sendJson(res, { ok: await voiceboxManager.deleteMessage(boxId, msgId) });
}
// Static files.
@@ -364,10 +372,13 @@ export function initWebUi(
const {
port,
getStatus,
getConfig,
updateConfig,
log,
onStartCall,
onHangupCall,
onConfigSaved,
faxBoxManager,
faxJobManager,
voiceboxManager,
onWebRtcOffer,
onWebRtcIce,
@@ -387,12 +398,12 @@ export function initWebUi(
const cert = fs.readFileSync(certPath, 'utf8');
const key = fs.readFileSync(keyPath, 'utf8');
server = https.createServer({ cert, key }, (req, res) =>
handleRequest(req, res, { getStatus, log, onStartCall, onHangupCall, onConfigSaved, voiceboxManager }).catch(() => { res.writeHead(500); res.end(); }),
handleRequest(req, res, { getStatus, getConfig, updateConfig, log, onStartCall, onHangupCall, faxBoxManager, faxJobManager, voiceboxManager }).catch(() => { res.writeHead(500); res.end(); }),
);
useTls = true;
} catch {
server = http.createServer((req, res) =>
handleRequest(req, res, { getStatus, log, onStartCall, onHangupCall, onConfigSaved, voiceboxManager }).catch(() => { res.writeHead(500); res.end(); }),
handleRequest(req, res, { getStatus, getConfig, updateConfig, log, onStartCall, onHangupCall, faxBoxManager, faxJobManager, voiceboxManager }).catch(() => { res.writeHead(500); res.end(); }),
);
}
@@ -429,7 +440,9 @@ export function initWebUi(
}
} else if (msg.type?.startsWith('webrtc-')) {
msg._remoteIp = remoteIp;
handleWebRtcSignaling(socket, msg);
if (msg.type) {
handleWebRtcSignaling(socket, msg as IWebRtcSocketMessage & { type: string });
}
}
} catch { /* ignore */ }
});
+4
View File
@@ -0,0 +1,4 @@
import * as smartbucket from '@push.rocks/smartbucket';
import * as smartdata from '@push.rocks/smartdata';
export { smartbucket, smartdata };
+22
View File
@@ -17,6 +17,9 @@ export type {
ICallEndedEvent,
ICallRingingEvent,
IDeviceRegisteredEvent,
IFaxCompletedEvent,
IFaxFailedEvent,
IFaxStartedEvent,
IIncomingCallEvent,
ILegAddedEvent,
ILegRemovedEvent,
@@ -52,6 +55,10 @@ type TProxyCommands = {
params: { number: string; device_id?: string; provider_id?: string };
result: { call_id: string };
};
send_fax: {
params: { number: string; file_path: string; provider_id?: string };
result: { call_id: string; codec: 'PCMU' | 'PCMA' };
};
add_leg: {
params: { call_id: string; number: string; provider_id?: string };
result: { leg_id: string };
@@ -262,6 +269,21 @@ export async function makeCall(number: string, deviceId?: string, providerId?: s
}
}
export async function sendFax(number: string, filePath: string, providerId?: string): Promise<string | null> {
if (!bridge || !initialized) return null;
try {
const result = await sendProxyCommand('send_fax', {
number,
file_path: filePath,
provider_id: providerId,
});
return result.call_id || null;
} catch (error: unknown) {
logFn?.(`[proxy-engine] send_fax error: ${errorMessage(error)}`);
return null;
}
}
/**
* Send a hangup command.
*/
+59 -3
View File
@@ -1,4 +1,6 @@
import { onProxyEvent } from '../proxybridge.ts';
import { hangupCall, onProxyEvent } from '../proxybridge.ts';
import type { FaxBoxManager } from '../faxbox.ts';
import type { FaxJobManager } from '../faxjobs.ts';
import type { VoiceboxManager } from '../voicebox.ts';
import type { StatusStore } from './status-store.ts';
import type { IProviderMediaInfo, WebRtcLinkManager } from './webrtc-linking.ts';
@@ -6,6 +8,8 @@ import type { IProviderMediaInfo, WebRtcLinkManager } from './webrtc-linking.ts'
export interface IRegisterProxyEventHandlersOptions {
log: (msg: string) => void;
statusStore: StatusStore;
faxBoxManager: FaxBoxManager;
faxJobManager: FaxJobManager;
voiceboxManager: VoiceboxManager;
webRtcLinks: WebRtcLinkManager;
getBrowserDeviceIds: () => string[];
@@ -19,6 +23,8 @@ export function registerProxyEventHandlers(options: IRegisterProxyEventHandlersO
const {
log,
statusStore,
faxBoxManager,
faxJobManager,
voiceboxManager,
webRtcLinks,
getBrowserDeviceIds,
@@ -30,6 +36,7 @@ export function registerProxyEventHandlers(options: IRegisterProxyEventHandlersO
const legMediaDetails = (data: {
codec?: string | null;
mediaProtocol?: string | null;
remoteMedia?: string | null;
rtpPort?: number | null;
}): string => {
@@ -37,6 +44,9 @@ export function registerProxyEventHandlers(options: IRegisterProxyEventHandlersO
if (data.codec) {
parts.push(`codec=${data.codec}`);
}
if (data.mediaProtocol) {
parts.push(`media=${data.mediaProtocol}`);
}
if (data.remoteMedia) {
parts.push(`remote=${data.remoteMedia}`);
}
@@ -91,6 +101,15 @@ export function registerProxyEventHandlers(options: IRegisterProxyEventHandlersO
log(`[call] outbound started: ${data.call_id} -> ${data.number} via ${data.provider_id}`);
statusStore.noteOutboundCallStarted(data);
if (data.ring_browsers === false) {
void faxJobManager.noteDialing(data.call_id, data.number, data.provider_id)
.catch((error) => log(`[fax] persist dialing failed: ${error instanceof Error ? error.message : String(error)}`));
}
if (data.ring_browsers === false) {
return;
}
for (const deviceId of getBrowserDeviceIds()) {
sendToBrowserDevice(deviceId, {
type: 'webrtc-incoming',
@@ -110,6 +129,10 @@ export function registerProxyEventHandlers(options: IRegisterProxyEventHandlersO
log(`[call] ${data.call_id} connected`);
}
if (data.media_protocol && data.media_protocol !== 'rtp') {
return;
}
if (!data.provider_media_addr || !data.provider_media_port) {
return;
}
@@ -196,15 +219,48 @@ export function registerProxyEventHandlers(options: IRegisterProxyEventHandlersO
onProxyEvent('recording_done', (data) => {
const boxId = data.voicebox_id || 'default';
log(`[voicemail] recording done: ${data.file_path} (${data.duration_ms}ms) box=${boxId} caller=${data.caller_number}`);
voiceboxManager.addMessage(boxId, {
void voiceboxManager.addMessage(boxId, {
callerNumber: data.caller_number || 'Unknown',
callerName: null,
fileName: data.file_path,
durationMs: data.duration_ms,
});
}).catch((error) => log(`[voicemail] persist failed: ${error instanceof Error ? error.message : String(error)}`));
});
onProxyEvent('voicemail_error', (data) => {
log(`[voicemail] error: ${data.error} call=${data.call_id}`);
});
onProxyEvent('fax_started', (data) => {
void faxJobManager.noteStarted(data).catch((error) => log(`[fax] persist start failed: ${error instanceof Error ? error.message : String(error)}`));
log(`[fax] started: call=${data.call_id} leg=${data.leg_id} ${data.direction}/${data.transport} codec=${data.codec || '?'} file=${data.file_path}`);
});
onProxyEvent('fax_completed', (data) => {
void faxJobManager.noteCompleted(data).catch((error) => log(`[fax] persist completion failed: ${error instanceof Error ? error.message : String(error)}`));
log(
`[fax] completed: call=${data.call_id} leg=${data.leg_id} success=${data.success} pagesTx=${data.stats.pages_tx} bitrate=${data.stats.bit_rate} completion=${data.completion_label || data.completion_code || 'unknown'}`,
);
if (data.direction === 'inbound' && data.success && data.fax_box_id) {
void faxBoxManager.addMessage(data.fax_box_id, {
callerNumber: data.caller_number,
fileName: data.file_path,
completionCode: data.completion_code,
completionLabel: data.completion_label,
pageCount: data.stats.pages_rx || data.stats.pages_tx,
bitRate: data.stats.bit_rate,
}).catch((error) => log(`[fax] persist inbox failed: ${error instanceof Error ? error.message : String(error)}`));
}
if (data.direction === 'outbound' || data.fax_box_id) {
void hangupCall(data.call_id);
}
});
onProxyEvent('fax_failed', (data) => {
void faxJobManager.noteFailed(data).catch((error) => log(`[fax] persist failure failed: ${error instanceof Error ? error.message : String(error)}`));
log(`[fax] failed: call=${data.call_id} leg=${data.leg_id} error=${data.error}`);
if (data.direction === 'outbound' || data.fax_box_id) {
void hangupCall(data.call_id);
}
});
}
+66 -64
View File
@@ -88,16 +88,12 @@ export class StatusStore {
}
noteDashboardCallStarted(callId: string, number: string, providerId?: string): void {
this.activeCalls.set(callId, {
id: callId,
direction: 'outbound',
callerNumber: null,
calleeNumber: number,
providerUsed: providerId || null,
state: 'setting-up',
startedAt: Date.now(),
legs: new Map(),
});
const call = this.getOrCreateCall(callId, 'outbound');
call.direction = 'outbound';
call.callerNumber = null;
call.calleeNumber = number;
call.providerUsed = providerId || null;
call.state = 'setting-up';
}
noteProviderRegistered(data: IProviderRegisteredEvent): { wasRegistered: boolean } | null {
@@ -126,56 +122,39 @@ export class StatusStore {
}
noteIncomingCall(data: IIncomingCallEvent): void {
this.activeCalls.set(data.call_id, {
id: data.call_id,
direction: 'inbound',
callerNumber: data.from_uri,
calleeNumber: data.to_number,
providerUsed: data.provider_id,
state: 'ringing',
startedAt: Date.now(),
legs: new Map(),
});
}
noteOutboundDeviceCall(data: IOutboundCallEvent): void {
this.activeCalls.set(data.call_id, {
id: data.call_id,
direction: 'outbound',
callerNumber: data.from_device,
calleeNumber: data.to_number,
providerUsed: null,
state: 'setting-up',
startedAt: Date.now(),
legs: new Map(),
});
}
noteOutboundCallStarted(data: IOutboundCallStartedEvent): void {
this.activeCalls.set(data.call_id, {
id: data.call_id,
direction: 'outbound',
callerNumber: null,
calleeNumber: data.number,
providerUsed: data.provider_id,
state: 'setting-up',
startedAt: Date.now(),
legs: new Map(),
});
}
noteCallRinging(data: ICallRingingEvent): void {
const call = this.activeCalls.get(data.call_id);
if (call) {
const call = this.getOrCreateCall(data.call_id, 'inbound');
call.direction = 'inbound';
call.callerNumber = data.from_uri;
call.calleeNumber = data.to_number;
call.providerUsed = data.provider_id;
if (call.state === 'setting-up') {
call.state = 'ringing';
}
}
noteOutboundDeviceCall(data: IOutboundCallEvent): void {
const call = this.getOrCreateCall(data.call_id, 'outbound');
call.direction = 'outbound';
call.callerNumber = data.from_device;
call.calleeNumber = data.to_number;
call.providerUsed = null;
}
noteOutboundCallStarted(data: IOutboundCallStartedEvent): void {
const call = this.getOrCreateCall(data.call_id, 'outbound');
call.direction = 'outbound';
call.callerNumber = call.callerNumber ?? null;
call.calleeNumber = data.number;
call.providerUsed = data.provider_id;
}
noteCallRinging(data: ICallRingingEvent): void {
const call = this.getOrCreateCall(data.call_id);
call.state = 'ringing';
}
noteCallAnswered(data: ICallAnsweredEvent): boolean {
const call = this.activeCalls.get(data.call_id);
if (!call) {
return false;
}
const call = this.getOrCreateCall(data.call_id);
call.state = 'connected';
@@ -186,7 +165,12 @@ export class StatusStore {
}
leg.remoteMedia = `${data.provider_media_addr}:${data.provider_media_port}`;
if (data.sip_pt !== undefined) {
if (data.media_protocol) {
leg.mediaProtocol = data.media_protocol;
}
if (data.media_protocol === 't38-udptl') {
leg.codec = 'T.38';
} else if (data.sip_pt !== undefined) {
leg.codec = CODEC_NAMES[data.sip_pt] || `PT${data.sip_pt}`;
}
break;
@@ -216,6 +200,7 @@ export class StatusStore {
state: leg.state,
codec: leg.codec,
rtpPort: leg.rtpPort,
mediaProtocol: leg.mediaProtocol,
remoteMedia: leg.remoteMedia,
metadata: leg.metadata || {},
})),
@@ -230,10 +215,7 @@ export class StatusStore {
}
noteLegAdded(data: ILegAddedEvent): void {
const call = this.activeCalls.get(data.call_id);
if (!call) {
return;
}
const call = this.getOrCreateCall(data.call_id);
call.legs.set(data.leg_id, {
id: data.leg_id,
@@ -241,6 +223,7 @@ export class StatusStore {
state: data.state,
codec: data.codec ?? null,
rtpPort: data.rtpPort ?? null,
mediaProtocol: data.mediaProtocol ?? null,
remoteMedia: data.remoteMedia ?? null,
metadata: data.metadata || {},
});
@@ -251,10 +234,7 @@ export class StatusStore {
}
noteLegStateChanged(data: ILegStateChangedEvent): void {
const call = this.activeCalls.get(data.call_id);
if (!call) {
return;
}
const call = this.getOrCreateCall(data.call_id);
const existingLeg = call.legs.get(data.leg_id);
if (existingLeg) {
@@ -265,6 +245,9 @@ export class StatusStore {
if (data.rtpPort !== undefined) {
existingLeg.rtpPort = data.rtpPort;
}
if (data.mediaProtocol !== undefined) {
existingLeg.mediaProtocol = data.mediaProtocol;
}
if (data.remoteMedia !== undefined) {
existingLeg.remoteMedia = data.remoteMedia;
}
@@ -280,6 +263,7 @@ export class StatusStore {
state: data.state,
codec: data.codec ?? null,
rtpPort: data.rtpPort ?? null,
mediaProtocol: data.mediaProtocol ?? null,
remoteMedia: data.remoteMedia ?? null,
metadata: data.metadata || {},
});
@@ -323,4 +307,22 @@ export class StatusStore {
}
return 'webrtc';
}
private getOrCreateCall(callId: string, direction: 'inbound' | 'outbound' = 'inbound'): IActiveCall {
let call = this.activeCalls.get(callId);
if (!call) {
call = {
id: callId,
direction,
callerNumber: null,
calleeNumber: null,
providerUsed: null,
state: 'setting-up',
startedAt: Date.now(),
legs: new Map(),
};
this.activeCalls.set(callId, call);
}
return call;
}
}
+57
View File
@@ -18,6 +18,7 @@ export interface IOutboundCallStartedEvent {
call_id: string;
number: string;
provider_id: string;
ring_browsers?: boolean;
}
export interface ICallRingingEvent {
@@ -28,6 +29,7 @@ export interface ICallAnsweredEvent {
call_id: string;
provider_media_addr?: string;
provider_media_port?: number;
media_protocol?: string;
sip_pt?: number;
}
@@ -67,6 +69,7 @@ export interface ILegAddedEvent {
state: string;
codec?: string | null;
rtpPort?: number | null;
mediaProtocol?: string | null;
remoteMedia?: string | null;
metadata?: Record<string, unknown>;
}
@@ -82,6 +85,7 @@ export interface ILegStateChangedEvent {
state: string;
codec?: string | null;
rtpPort?: number | null;
mediaProtocol?: string | null;
remoteMedia?: string | null;
metadata?: Record<string, unknown>;
}
@@ -128,6 +132,56 @@ export interface IVoicemailErrorEvent {
error: string;
}
export interface IFaxStartedEvent {
call_id: string;
leg_id: string;
direction: 'outbound' | 'inbound';
transport: 'audio' | 't38';
file_path: string;
fax_box_id?: string;
caller_number?: string;
codec?: string;
remote_media?: string;
}
export interface IFaxCompletedEvent {
call_id: string;
leg_id: string;
direction: 'outbound' | 'inbound';
transport: 'audio' | 't38';
file_path: string;
fax_box_id?: string;
caller_number?: string;
codec?: string;
success: boolean;
completion_code?: number | null;
completion_label?: string | null;
stats: {
bit_rate: number;
error_correcting_mode: boolean;
pages_tx: number;
pages_rx: number;
image_size: number;
bad_rows: number;
longest_bad_row_run: number;
ecm_retries: number;
current_status: number;
rtp_events: number;
rtn_events: number;
};
}
export interface IFaxFailedEvent {
call_id: string;
leg_id: string;
direction: 'outbound' | 'inbound';
transport: 'audio' | 't38';
file_path: string;
fax_box_id?: string;
caller_number?: string;
error: string;
}
export type TProxyEventMap = {
provider_registered: IProviderRegisteredEvent;
device_registered: IDeviceRegisteredEvent;
@@ -148,4 +202,7 @@ export type TProxyEventMap = {
voicemail_started: IVoicemailStartedEvent;
recording_done: IRecordingDoneEvent;
voicemail_error: IVoicemailErrorEvent;
fax_started: IFaxStartedEvent;
fax_completed: IFaxCompletedEvent;
fax_failed: IFaxFailedEvent;
};
+1
View File
@@ -26,6 +26,7 @@ export interface IActiveLeg {
state: string;
codec: string | null;
rtpPort: number | null;
mediaProtocol: string | null;
remoteMedia: string | null;
metadata: Record<string, unknown>;
}
+102 -64
View File
@@ -8,7 +8,9 @@
import fs from 'node:fs';
import path from 'node:path';
import { loadConfig, type IAppConfig } from './config.ts';
import { applyConfigUpdates, type IAppConfig } from './config.ts';
import { FaxBoxManager } from './faxbox.ts';
import { FaxJobManager } from './faxjobs.ts';
import { broadcastWs, initWebUi } from './frontend.ts';
import { initWebRtcSignaling, getAllBrowserDeviceIds, sendToBrowserDevice } from './webrtcbridge.ts';
import { VoiceboxManager } from './voicebox.ts';
@@ -25,20 +27,21 @@ import {
} from './proxybridge.ts';
import { registerProxyEventHandlers } from './runtime/proxy-events.ts';
import { StatusStore } from './runtime/status-store.ts';
import { SiprouterStorage } from './storage.ts';
import { WebRtcLinkManager, type IProviderMediaInfo } from './runtime/webrtc-linking.ts';
let appConfig: IAppConfig = loadConfig();
let appConfig: IAppConfig;
const LOG_PATH = path.join(process.cwd(), 'sip_trace.log');
const startTime = Date.now();
const instanceId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const statusStore = new StatusStore(appConfig);
const webRtcLinks = new WebRtcLinkManager();
const voiceboxManager = new VoiceboxManager(log);
voiceboxManager.init(appConfig.voiceboxes ?? []);
initWebRtcSignaling({ log });
const storage = new SiprouterStorage(log);
let statusStore: StatusStore;
let webRtcLinks: WebRtcLinkManager;
let faxBoxManager: FaxBoxManager;
let faxJobManager: FaxJobManager;
let voiceboxManager: VoiceboxManager;
function now(): string {
return new Date().toISOString().replace('T', ' ').slice(0, 19);
@@ -61,6 +64,7 @@ function buildProxyConfig(config: IAppConfig): Record<string, unknown> {
providers: config.providers,
devices: config.devices,
routing: config.routing,
faxboxes: config.faxboxes ?? [],
voiceboxes: config.voiceboxes ?? [],
ivr: config.ivr,
};
@@ -89,11 +93,12 @@ async function configureRuntime(config: IAppConfig): Promise<boolean> {
async function reloadConfig(): Promise<void> {
try {
const previousConfig = appConfig;
const nextConfig = loadConfig();
const nextConfig = await storage.getAppConfig();
appConfig = nextConfig;
statusStore.updateConfig(nextConfig);
voiceboxManager.init(nextConfig.voiceboxes ?? []);
await faxBoxManager.init(nextConfig.faxboxes ?? []);
await voiceboxManager.init(nextConfig.voiceboxes ?? []);
if (nextConfig.proxy.lanPort !== previousConfig.proxy.lanPort) {
log('[config] proxy.lanPort changed; restart required for SIP socket rebinding');
@@ -113,6 +118,13 @@ async function reloadConfig(): Promise<void> {
}
}
async function updateConfig(updatesArg: any): Promise<IAppConfig> {
const nextConfig = applyConfigUpdates(appConfig, updatesArg);
await storage.writeAppConfig(nextConfig);
await reloadConfig();
return appConfig;
}
async function startProxyEngine(): Promise<void> {
const started = await initProxyEngine(log);
if (!started) {
@@ -123,6 +135,8 @@ async function startProxyEngine(): Promise<void> {
registerProxyEventHandlers({
log,
statusStore,
faxBoxManager,
faxJobManager,
voiceboxManager,
webRtcLinks,
getBrowserDeviceIds: getAllBrowserDeviceIds,
@@ -145,77 +159,101 @@ async function startProxyEngine(): Promise<void> {
log(`proxy engine started | LAN ${appConfig.proxy.lanIp}:${appConfig.proxy.lanPort} | providers: ${providerList} | devices: ${deviceList}`);
}
initWebUi({
port: appConfig.proxy.webUiPort,
getStatus,
log,
onStartCall: (number, deviceId, providerId) => {
log(`[dashboard] start call: ${number} device=${deviceId || 'any'} provider=${providerId || 'auto'}`);
void makeCall(number, deviceId, providerId).then((callId) => {
if (callId) {
log(`[dashboard] call started: ${callId}`);
statusStore.noteDashboardCallStarted(callId, number, providerId);
} else {
async function main(): Promise<void> {
await storage.init();
appConfig = await storage.getAppConfig();
statusStore = new StatusStore(appConfig);
webRtcLinks = new WebRtcLinkManager();
faxBoxManager = new FaxBoxManager(log, storage);
faxJobManager = new FaxJobManager(log, storage);
voiceboxManager = new VoiceboxManager(log, storage);
await faxBoxManager.init(appConfig.faxboxes ?? []);
await faxJobManager.init();
await voiceboxManager.init(appConfig.voiceboxes ?? []);
initWebRtcSignaling({ log });
initWebUi({
port: appConfig.proxy.webUiPort,
getStatus,
getConfig: () => appConfig,
updateConfig,
log,
onStartCall: async (number, deviceId, providerId) => {
log(`[dashboard] start call: ${number} device=${deviceId || 'any'} provider=${providerId || 'auto'}`);
const callId = await makeCall(number, deviceId, providerId);
if (!callId) {
log(`[dashboard] call failed for ${number}`);
return null;
}
log(`[dashboard] call started: ${callId}`);
statusStore.noteDashboardCallStarted(callId, number, providerId);
return { id: callId };
},
onHangupCall: (callId) => {
void hangupCall(callId);
return true;
},
faxBoxManager,
faxJobManager,
voiceboxManager,
onWebRtcOffer: async (sessionId, sdp, ws) => {
log(`[webrtc] offer from browser session=${sessionId.slice(0, 8)} sdp_type=${typeof sdp} sdp_len=${sdp?.length || 0}`);
if (!sdp || typeof sdp !== 'string' || sdp.length < 10) {
log(`[webrtc] WARNING: invalid SDP (type=${typeof sdp}), skipping offer`);
return;
}
});
return { id: `pending-${Date.now()}` };
},
onHangupCall: (callId) => {
void hangupCall(callId);
return true;
},
onConfigSaved: reloadConfig,
voiceboxManager,
onWebRtcOffer: async (sessionId, sdp, ws) => {
log(`[webrtc] offer from browser session=${sessionId.slice(0, 8)} sdp_type=${typeof sdp} sdp_len=${sdp?.length || 0}`);
if (!sdp || typeof sdp !== 'string' || sdp.length < 10) {
log(`[webrtc] WARNING: invalid SDP (type=${typeof sdp}), skipping offer`);
return;
}
log(`[webrtc] sending offer to Rust (${sdp.length}b)...`);
const result = await webrtcOffer(sessionId, sdp);
log(`[webrtc] Rust result: ${JSON.stringify(result)?.slice(0, 200)}`);
if (result?.sdp) {
ws.send(JSON.stringify({ type: 'webrtc-answer', sessionId, sdp: result.sdp }));
log(`[webrtc] answer sent to browser session=${sessionId.slice(0, 8)}`);
return;
}
log(`[webrtc] sending offer to Rust (${sdp.length}b)...`);
const result = await webrtcOffer(sessionId, sdp);
log(`[webrtc] Rust result: ${JSON.stringify(result)?.slice(0, 200)}`);
if (result?.sdp) {
ws.send(JSON.stringify({ type: 'webrtc-answer', sessionId, sdp: result.sdp }));
log(`[webrtc] answer sent to browser session=${sessionId.slice(0, 8)}`);
return;
}
log('[webrtc] ERROR: no answer SDP from Rust');
},
onWebRtcIce: async (sessionId, candidate) => {
await webrtcIce(sessionId, candidate as Parameters<typeof webrtcIce>[1]);
},
onWebRtcClose: async (sessionId) => {
webRtcLinks.removeSession(sessionId);
await webrtcClose(sessionId);
},
onWebRtcAccept: (callId, sessionId) => {
log(`[webrtc] accept: callId=${callId} sessionId=${sessionId.slice(0, 8)}`);
log('[webrtc] ERROR: no answer SDP from Rust');
},
onWebRtcIce: async (sessionId, candidate) => {
await webrtcIce(sessionId, candidate);
},
onWebRtcClose: async (sessionId) => {
webRtcLinks.removeSession(sessionId);
await webrtcClose(sessionId);
},
onWebRtcAccept: (callId, sessionId) => {
log(`[webrtc] accept: callId=${callId} sessionId=${sessionId.slice(0, 8)}`);
const pendingMedia = webRtcLinks.acceptCall(callId, sessionId);
if (pendingMedia) {
requestWebRtcLink(callId, sessionId, pendingMedia);
return;
}
const pendingMedia = webRtcLinks.acceptCall(callId, sessionId);
if (pendingMedia) {
requestWebRtcLink(callId, sessionId, pendingMedia);
return;
}
log(`[webrtc] session ${sessionId.slice(0, 8)} accepted, waiting for call_answered media info`);
},
});
log(`[webrtc] session ${sessionId.slice(0, 8)} accepted, waiting for call_answered media info`);
},
await startProxyEngine();
}
void main().catch((error) => {
log(`[FATAL] ${errorMessage(error)}`);
process.exit(1);
});
void startProxyEngine();
process.on('SIGINT', () => {
log('SIGINT, exiting');
shutdownProxyEngine();
void storage.close();
process.exit(0);
});
process.on('SIGTERM', () => {
log('SIGTERM, exiting');
shutdownProxyEngine();
void storage.close();
process.exit(0);
});
+250
View File
@@ -0,0 +1,250 @@
import fs from 'node:fs';
import * as fsPromises from 'node:fs/promises';
import path from 'node:path';
import * as plugins from './plugins.ts';
import {
createInitialConfigFromEnv,
normalizeConfig,
type IAppConfig,
} from './config.ts';
import type { IFaxMessage } from './faxbox.ts';
import type { IFaxJob } from './faxjobs.ts';
import type { IVoicemailMessage } from './voicebox.ts';
interface ISiprouterDataStore {
appConfig: IAppConfig;
faxJobs: IFaxJob[];
faxMessagesByBox: Record<string, IFaxMessage[]>;
voicemailMessagesByBox: Record<string, IVoicemailMessage[]>;
}
type TLogFunction = (messageArg: string) => void;
const legacyConfigPath = path.join(process.cwd(), '.nogit', 'config.json');
function requiredEnv(keysArg: string[]): string {
for (const key of keysArg) {
const value = process.env[key];
if (value) return value;
}
throw new Error(`Missing required environment variable: ${keysArg.join(' or ')}`);
}
function optionalNumber(valueArg: string | undefined, fallbackArg?: number): number | undefined {
if (!valueArg) return fallbackArg;
const parsed = Number(valueArg);
return Number.isFinite(parsed) ? parsed : fallbackArg;
}
function optionalBoolean(valueArg: string | undefined, fallbackArg?: boolean): boolean | undefined {
if (valueArg === undefined) return fallbackArg;
return !['0', 'false', 'no', 'off'].includes(valueArg.toLowerCase());
}
function normalizeObjectKey(keyArg: string): string {
const normalizedKey = keyArg.replace(/\\/g, '/').replace(/^\/+/, '').replace(/\/+/g, '/');
if (normalizedKey.split('/').includes('..')) {
throw new Error(`Invalid object key: ${keyArg}`);
}
return normalizedKey;
}
export class SiprouterStorage {
private db!: InstanceType<typeof plugins.smartdata.SmartdataDb>;
private store!: any;
private bucket!: any;
private readonly cacheDir = path.join(process.cwd(), '.nogit', 'cache');
private readonly log: TLogFunction;
constructor(logArg: TLogFunction) {
this.log = logArg;
}
public async init(): Promise<void> {
this.db = new plugins.smartdata.SmartdataDb(this.getMongoDescriptor() as any);
await this.db.init();
this.store = await this.db.createEasyStore('siprouter-data');
const smartBucket = new plugins.smartbucket.SmartBucket(this.getS3Descriptor() as any);
const bucketName = requiredEnv(['SIPROUTER_S3_BUCKET', 'S3_BUCKET']);
this.bucket = await smartBucket.bucketExists(bucketName)
? await smartBucket.getBucketByName(bucketName)
: await smartBucket.createBucket(bucketName);
await fsPromises.mkdir(this.cacheDir, { recursive: true });
this.log('[storage] smartdata and smartbucket initialized');
}
public async close(): Promise<void> {
if (this.db) {
await this.db.close();
}
}
public async getAppConfig(): Promise<IAppConfig> {
const storedConfig = await this.readKey('appConfig');
if (storedConfig) {
return normalizeConfig(storedConfig);
}
const legacyConfig = await this.readLegacyConfig();
const initialConfig = legacyConfig || createInitialConfigFromEnv();
await this.writeAppConfig(initialConfig);
this.log(legacyConfig ? '[storage] imported legacy .nogit/config.json into smartdata' : '[storage] created initial smartdata config');
return initialConfig;
}
public async writeAppConfig(configArg: IAppConfig): Promise<void> {
await this.writeKey('appConfig', normalizeConfig(configArg));
}
public async getFaxJobs(): Promise<IFaxJob[]> {
return (await this.readKey('faxJobs')) || [];
}
public async writeFaxJobs(jobsArg: IFaxJob[]): Promise<void> {
await this.writeKey('faxJobs', jobsArg);
}
public async getVoicemailMessages(boxIdArg: string): Promise<IVoicemailMessage[]> {
const allMessages = (await this.readKey('voicemailMessagesByBox')) || {};
return allMessages[boxIdArg] || [];
}
public async writeVoicemailMessages(boxIdArg: string, messagesArg: IVoicemailMessage[]): Promise<void> {
const allMessages = (await this.readKey('voicemailMessagesByBox')) || {};
allMessages[boxIdArg] = messagesArg;
await this.writeKey('voicemailMessagesByBox', allMessages);
}
public async getFaxMessages(boxIdArg: string): Promise<IFaxMessage[]> {
const allMessages = (await this.readKey('faxMessagesByBox')) || {};
return allMessages[boxIdArg] || [];
}
public async writeFaxMessages(boxIdArg: string, messagesArg: IFaxMessage[]): Promise<void> {
const allMessages = (await this.readKey('faxMessagesByBox')) || {};
allMessages[boxIdArg] = messagesArg;
await this.writeKey('faxMessagesByBox', allMessages);
}
public async putFileObject(objectKeyArg: string, filePathArg: string): Promise<string> {
const objectKey = normalizeObjectKey(objectKeyArg);
const contents = await fsPromises.readFile(filePathArg);
await this.bucket.fastPut({ path: objectKey, contents, overwrite: true });
await this.removeCachedObject(objectKey);
return objectKey;
}
public async putBufferObject(objectKeyArg: string, bufferArg: Buffer): Promise<string> {
const objectKey = normalizeObjectKey(objectKeyArg);
await this.bucket.fastPut({ path: objectKey, contents: bufferArg, overwrite: true });
await this.removeCachedObject(objectKey);
return objectKey;
}
public async getObjectAsCachedFile(objectKeyArg: string, fileNameArg?: string): Promise<string | null> {
const objectKey = normalizeObjectKey(objectKeyArg);
const cachePath = this.getCachePath(objectKey);
try {
if (fs.existsSync(cachePath)) {
return cachePath;
}
const contents = await this.bucket.fastGet({ path: objectKey });
await fsPromises.mkdir(path.dirname(cachePath), { recursive: true });
await fsPromises.writeFile(cachePath, contents);
return cachePath;
} catch {
if (fileNameArg) {
const fallbackPath = path.join(this.cacheDir, path.basename(fileNameArg));
return fs.existsSync(fallbackPath) ? fallbackPath : null;
}
return null;
}
}
public async removeObject(objectKeyArg: string | undefined): Promise<void> {
if (!objectKeyArg) return;
const objectKey = normalizeObjectKey(objectKeyArg);
try {
await this.bucket.fastRemove({ path: objectKey });
} catch {
// Missing objects are harmless during metadata cleanup.
}
await this.removeCachedObject(objectKey);
}
private getCachePath(objectKeyArg: string): string {
return path.join(this.cacheDir, normalizeObjectKey(objectKeyArg));
}
private async removeCachedObject(objectKeyArg: string): Promise<void> {
await fsPromises.rm(this.getCachePath(objectKeyArg), { force: true }).catch(() => {});
}
private async readLegacyConfig(): Promise<IAppConfig | null> {
try {
const raw = await fsPromises.readFile(legacyConfigPath, 'utf8');
return normalizeConfig(JSON.parse(raw) as IAppConfig);
} catch {
return null;
}
}
private async readKey<TKey extends keyof ISiprouterDataStore>(keyArg: TKey): Promise<ISiprouterDataStore[TKey] | undefined> {
try {
return await this.store.readKey(keyArg) as ISiprouterDataStore[TKey] | undefined;
} catch {
return undefined;
}
}
private async writeKey<TKey extends keyof ISiprouterDataStore>(
keyArg: TKey,
valueArg: ISiprouterDataStore[TKey],
): Promise<void> {
await this.store.writeKey(keyArg, valueArg);
}
private getMongoDescriptor(): Record<string, string> {
const mongoDbUrl = requiredEnv([
'SIPROUTER_MONGODB_URL',
'MONGODB_URI',
'MONGODB_URL',
]);
const descriptor: Record<string, string> = {
mongoDbUrl,
mongoDbName: process.env.SIPROUTER_MONGODB_NAME || process.env.MONGODB_DATABASE || process.env.MONGODB_NAME || 'siprouter',
};
const mongoDbUser = process.env.SIPROUTER_MONGODB_USER || process.env.MONGODB_USERNAME || process.env.MONGODB_USER;
const mongoDbPass = process.env.SIPROUTER_MONGODB_PASS || process.env.MONGODB_PASSWORD || process.env.MONGODB_PASS;
if (mongoDbUser) descriptor.mongoDbUser = mongoDbUser;
if (mongoDbPass) descriptor.mongoDbPass = mongoDbPass;
return descriptor;
}
private getS3Descriptor(): Record<string, string | number | boolean> {
const rawEndpoint = requiredEnv(['SIPROUTER_S3_ENDPOINT', 'S3_ENDPOINT', 'AWS_ENDPOINT_URL']);
let endpoint = rawEndpoint;
let port = optionalNumber(process.env.SIPROUTER_S3_PORT || process.env.S3_PORT);
let useSsl = optionalBoolean(process.env.SIPROUTER_S3_USESSL || process.env.S3_USESSL || process.env.S3_USE_SSL);
if (/^https?:\/\//.test(rawEndpoint)) {
const url = new URL(rawEndpoint);
endpoint = url.hostname;
port = url.port ? Number(url.port) : port;
useSsl = url.protocol === 'https:';
}
return {
endpoint,
accessKey: requiredEnv(['SIPROUTER_S3_ACCESS_KEY', 'S3_ACCESS_KEY', 'AWS_ACCESS_KEY_ID']),
accessSecret: requiredEnv(['SIPROUTER_S3_SECRET_KEY', 'S3_SECRET_KEY', 'AWS_SECRET_ACCESS_KEY']),
region: process.env.SIPROUTER_S3_REGION || process.env.S3_REGION || process.env.AWS_REGION || 'us-east-1',
...(port ? { port } : {}),
...(useSsl !== undefined ? { useSsl } : {}),
};
}
}
+104 -166
View File
@@ -1,22 +1,12 @@
/**
* VoiceboxManager manages voicemail boxes, message storage, and MWI.
*
* Each voicebox corresponds to a device/extension. Messages are stored
* as WAV files with JSON metadata in .nogit/voicemail/{boxId}/.
*
* Supports:
* - Per-box configurable TTS greetings (text + voice) or uploaded WAV
* - Message CRUD: save, list, mark heard, delete
* - Unheard count for MWI (Message Waiting Indicator)
* - Storage limit (max messages per box)
* VoiceboxManager manages voicemail boxes, message metadata, and audio objects.
*/
import fs from 'node:fs';
import * as fsPromises from 'node:fs/promises';
import path from 'node:path';
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
import type { SiprouterStorage } from './storage.ts';
export interface IVoiceboxConfig {
/** Unique ID — typically matches device ID or extension. */
@@ -27,11 +17,9 @@ export interface IVoiceboxConfig {
greetingText?: string;
/** Kokoro TTS voice ID for the greeting (default 'af_bella'). */
greetingVoice?: string;
/** Path to uploaded WAV greeting (overrides TTS). */
/** Path to cached uploaded WAV greeting (overrides TTS). */
greetingWavPath?: string;
/** Seconds to wait before routing to voicemail. Defaults to 25 when
* absent both the config loader and `VoiceboxManager.init` apply
* the default via `??=`. */
/** Seconds to wait before routing to voicemail. */
noAnswerTimeoutSec?: number;
/** Maximum recording duration in seconds. Defaults to 120. */
maxRecordingSec?: number;
@@ -52,112 +40,80 @@ export interface IVoicemailMessage {
timestamp: number;
/** Duration in milliseconds. */
durationMs: number;
/** Relative path to the WAV file (within the box directory). */
/** Display file name. */
fileName: string;
/** SmartBucket object key for the WAV payload. */
objectKey?: string;
/** Whether the message has been listened to. */
heard: boolean;
}
// Default greeting text when no custom text is configured.
const DEFAULT_GREETING = 'The person you are trying to reach is not available. Please leave a message after the tone.';
// ---------------------------------------------------------------------------
// VoiceboxManager
// ---------------------------------------------------------------------------
export class VoiceboxManager {
private boxes = new Map<string, IVoiceboxConfig>();
private basePath: string;
private log: (msg: string) => void;
private messagesByBox = new Map<string, IVoicemailMessage[]>();
private readonly basePath: string;
private readonly log: (msg: string) => void;
private readonly storage: SiprouterStorage;
constructor(log: (msg: string) => void) {
constructor(log: (msg: string) => void, storageArg: SiprouterStorage) {
this.basePath = path.join(process.cwd(), '.nogit', 'voicemail');
this.log = log;
this.storage = storageArg;
}
// -------------------------------------------------------------------------
// Initialization
// -------------------------------------------------------------------------
/**
* Load voicebox configurations from the app config.
*/
init(voiceboxConfigs: IVoiceboxConfig[]): void {
async init(voiceboxConfigs: IVoiceboxConfig[]): Promise<void> {
this.boxes.clear();
for (const cfg of voiceboxConfigs) {
// Apply defaults.
cfg.noAnswerTimeoutSec ??= 25;
cfg.maxRecordingSec ??= 120;
cfg.maxMessages ??= 50;
cfg.greetingVoice ??= 'af_bella';
this.boxes.set(cfg.id, cfg);
this.messagesByBox.set(cfg.id, await this.loadMessages(cfg.id));
}
// Ensure base directory exists.
fs.mkdirSync(this.basePath, { recursive: true });
await fsPromises.mkdir(this.basePath, { recursive: true });
this.log(`[voicebox] initialized ${this.boxes.size} voicebox(es)`);
}
// -------------------------------------------------------------------------
// Box management
// -------------------------------------------------------------------------
/** Get config for a specific voicebox. */
getBox(boxId: string): IVoiceboxConfig | null {
return this.boxes.get(boxId) ?? null;
}
/** Get all configured voicebox IDs. */
getBoxIds(): string[] {
return [...this.boxes.keys()];
}
/** Get the greeting text for a voicebox. */
getGreetingText(boxId: string): string {
const box = this.boxes.get(boxId);
return box?.greetingText || DEFAULT_GREETING;
}
/** Get the greeting voice for a voicebox. */
getGreetingVoice(boxId: string): string {
const box = this.boxes.get(boxId);
return box?.greetingVoice || 'af_bella';
}
/** Check if a voicebox has a custom WAV greeting. */
hasCustomGreetingWav(boxId: string): boolean {
const box = this.boxes.get(boxId);
if (!box?.greetingWavPath) return false;
return fs.existsSync(box.greetingWavPath);
}
/** Get the greeting WAV path (custom or null). */
getCustomGreetingWavPath(boxId: string): string | null {
const box = this.boxes.get(boxId);
if (!box?.greetingWavPath) return null;
return fs.existsSync(box.greetingWavPath) ? box.greetingWavPath : null;
}
/** Get the directory path for a voicebox. */
getBoxDir(boxId: string): string {
return path.join(this.basePath, boxId);
}
// -------------------------------------------------------------------------
// Message CRUD
// -------------------------------------------------------------------------
/**
* Convenience wrapper around `saveMessage` used by the `recording_done`
* event handler, which has a raw recording path + caller info and needs
* to persist metadata. Generates `id`, sets `timestamp = now`, defaults
* `heard = false`, and normalizes `fileName` to a basename (the WAV is
* expected to already live in the box's directory).
*/
addMessage(
async addMessage(
boxId: string,
info: {
callerNumber: string;
@@ -165,124 +121,87 @@ export class VoiceboxManager {
fileName: string;
durationMs: number;
},
): void {
): Promise<void> {
const id = crypto.randomUUID();
const localPath = path.isAbsolute(info.fileName) ? info.fileName : path.join(process.cwd(), info.fileName);
const objectKey = await this.storage.putFileObject(`voicemail/${boxId}/${id}.wav`, localPath);
const msg: IVoicemailMessage = {
id: crypto.randomUUID(),
id,
boxId,
callerNumber: info.callerNumber,
callerName: info.callerName ?? undefined,
timestamp: Date.now(),
durationMs: info.durationMs,
fileName: path.basename(info.fileName),
fileName: path.basename(localPath),
objectKey,
heard: false,
};
this.saveMessage(msg);
}
/**
* Save a new voicemail message.
* The WAV file should already exist at the expected path.
*/
saveMessage(msg: IVoicemailMessage): void {
const boxDir = this.getBoxDir(msg.boxId);
fs.mkdirSync(boxDir, { recursive: true });
const messages = this.getMessages(boxId);
messages.unshift(msg);
await this.enforceLimit(boxId, messages);
await this.writeMessages(boxId, messages);
const messages = this.loadMessages(msg.boxId);
messages.unshift(msg); // newest first
// Enforce max messages — delete oldest.
const box = this.boxes.get(msg.boxId);
const maxMessages = box?.maxMessages ?? 50;
while (messages.length > maxMessages) {
const old = messages.pop()!;
const oldPath = path.join(boxDir, old.fileName);
try {
if (fs.existsSync(oldPath)) fs.unlinkSync(oldPath);
} catch { /* best effort */ }
}
this.writeMessages(msg.boxId, messages);
await fsPromises.rm(localPath, { force: true }).catch(() => {});
this.log(`[voicebox] saved message ${msg.id} in box "${msg.boxId}" (${msg.durationMs}ms from ${msg.callerNumber})`);
}
/**
* List messages for a voicebox (newest first).
*/
getMessages(boxId: string): IVoicemailMessage[] {
return this.loadMessages(boxId);
return [...(this.messagesByBox.get(boxId) || [])];
}
/**
* Get a single message by ID.
*/
getMessage(boxId: string, messageId: string): IVoicemailMessage | null {
const messages = this.loadMessages(boxId);
const messages = this.messagesByBox.get(boxId) || [];
return messages.find((m) => m.id === messageId) ?? null;
}
/**
* Mark a message as heard.
*/
markHeard(boxId: string, messageId: string): boolean {
const messages = this.loadMessages(boxId);
async markHeard(boxId: string, messageId: string): Promise<boolean> {
const messages = this.messagesByBox.get(boxId) || [];
const msg = messages.find((m) => m.id === messageId);
if (!msg) return false;
msg.heard = true;
this.writeMessages(boxId, messages);
await this.writeMessages(boxId, messages);
return true;
}
/**
* Delete a message (both metadata and WAV file).
*/
deleteMessage(boxId: string, messageId: string): boolean {
const messages = this.loadMessages(boxId);
async deleteMessage(boxId: string, messageId: string): Promise<boolean> {
const messages = this.messagesByBox.get(boxId) || [];
const idx = messages.findIndex((m) => m.id === messageId);
if (idx === -1) return false;
const msg = messages[idx];
const boxDir = this.getBoxDir(boxId);
const wavPath = path.join(boxDir, msg.fileName);
await this.storage.removeObject(msg.objectKey);
if (!msg.objectKey) {
await fsPromises.rm(path.join(this.getBoxDir(boxId), msg.fileName), { force: true }).catch(() => {});
}
// Delete WAV file.
try {
if (fs.existsSync(wavPath)) fs.unlinkSync(wavPath);
} catch { /* best effort */ }
// Remove from list and save.
messages.splice(idx, 1);
this.writeMessages(boxId, messages);
await this.writeMessages(boxId, messages);
this.log(`[voicebox] deleted message ${messageId} from box "${boxId}"`);
return true;
}
/**
* Get the full file path for a message's WAV file.
*/
getMessageAudioPath(boxId: string, messageId: string): string | null {
async getMessageAudioPath(boxId: string, messageId: string): Promise<string | null> {
const msg = this.getMessage(boxId, messageId);
if (!msg) return null;
if (msg.objectKey) {
return await this.storage.getObjectAsCachedFile(msg.objectKey, msg.fileName);
}
const filePath = path.join(this.getBoxDir(boxId), msg.fileName);
return fs.existsSync(filePath) ? filePath : null;
}
// -------------------------------------------------------------------------
// Counts
// -------------------------------------------------------------------------
/** Get count of unheard messages for a voicebox. */
getUnheardCount(boxId: string): number {
const messages = this.loadMessages(boxId);
const messages = this.messagesByBox.get(boxId) || [];
return messages.filter((m) => !m.heard).length;
}
/** Get total message count for a voicebox. */
getTotalCount(boxId: string): number {
return this.loadMessages(boxId).length;
return (this.messagesByBox.get(boxId) || []).length;
}
/** Get unheard counts for all voiceboxes. */
getAllUnheardCounts(): Record<string, number> {
const counts: Record<string, number> = {};
for (const boxId of this.boxes.keys()) {
@@ -291,55 +210,74 @@ export class VoiceboxManager {
return counts;
}
// -------------------------------------------------------------------------
// Greeting management
// -------------------------------------------------------------------------
/**
* Save a custom greeting WAV file for a voicebox.
*/
saveCustomGreeting(boxId: string, wavData: Buffer): string {
const boxDir = this.getBoxDir(boxId);
fs.mkdirSync(boxDir, { recursive: true });
const greetingPath = path.join(boxDir, 'greeting.wav');
fs.writeFileSync(greetingPath, wavData);
async saveCustomGreeting(boxId: string, wavData: Buffer): Promise<string> {
const objectKey = await this.storage.putBufferObject(`voicemail/${boxId}/greeting.wav`, wavData);
const greetingPath = await this.storage.getObjectAsCachedFile(objectKey, `voicemail-${boxId}-greeting.wav`);
this.log(`[voicebox] saved custom greeting for box "${boxId}"`);
return greetingPath;
return greetingPath || '';
}
/**
* Delete the custom greeting for a voicebox (falls back to TTS).
*/
deleteCustomGreeting(boxId: string): void {
const boxDir = this.getBoxDir(boxId);
const greetingPath = path.join(boxDir, 'greeting.wav');
try {
if (fs.existsSync(greetingPath)) fs.unlinkSync(greetingPath);
} catch { /* best effort */ }
async deleteCustomGreeting(boxId: string): Promise<void> {
await this.storage.removeObject(`voicemail/${boxId}/greeting.wav`);
}
// -------------------------------------------------------------------------
// Internal: JSON persistence
// -------------------------------------------------------------------------
private messagesPath(boxId: string): string {
return path.join(this.getBoxDir(boxId), 'messages.json');
private async enforceLimit(boxId: string, messages: IVoicemailMessage[]): Promise<void> {
const box = this.boxes.get(boxId);
const maxMessages = box?.maxMessages ?? 50;
while (messages.length > maxMessages) {
const old = messages.pop()!;
await this.storage.removeObject(old.objectKey);
if (!old.objectKey) {
await fsPromises.rm(path.join(this.getBoxDir(boxId), old.fileName), { force: true }).catch(() => {});
}
}
}
private loadMessages(boxId: string): IVoicemailMessage[] {
const filePath = this.messagesPath(boxId);
private async loadMessages(boxId: string): Promise<IVoicemailMessage[]> {
const storedMessages = await this.storage.getVoicemailMessages(boxId);
if (storedMessages.length) return await this.ensureMessageObjects(boxId, storedMessages);
const filePath = path.join(this.getBoxDir(boxId), 'messages.json');
try {
if (!fs.existsSync(filePath)) return [];
const raw = fs.readFileSync(filePath, 'utf8');
return JSON.parse(raw) as IVoicemailMessage[];
const raw = await fsPromises.readFile(filePath, 'utf8');
const legacyMessages = await this.ensureMessageObjects(boxId, JSON.parse(raw) as IVoicemailMessage[]);
await this.storage.writeVoicemailMessages(boxId, legacyMessages);
return legacyMessages;
} catch {
return [];
}
}
private writeMessages(boxId: string, messages: IVoicemailMessage[]): void {
const boxDir = this.getBoxDir(boxId);
fs.mkdirSync(boxDir, { recursive: true });
fs.writeFileSync(this.messagesPath(boxId), JSON.stringify(messages, null, 2), 'utf8');
private async ensureMessageObjects(boxId: string, messages: IVoicemailMessage[]): Promise<IVoicemailMessage[]> {
let changed = false;
for (const msg of messages) {
if (!msg.id) {
msg.id = crypto.randomUUID();
changed = true;
}
if (msg.objectKey) continue;
const localPath = path.isAbsolute(msg.fileName) ? msg.fileName : path.join(this.getBoxDir(boxId), msg.fileName);
if (!fs.existsSync(localPath)) continue;
const extension = path.extname(localPath) || '.wav';
msg.objectKey = await this.storage.putFileObject(`voicemail/${boxId}/${msg.id}${extension}`, localPath);
msg.fileName = path.basename(localPath);
changed = true;
}
if (changed) {
await this.storage.writeVoicemailMessages(boxId, messages);
this.log(`[voicebox] migrated legacy messages for box "${boxId}" to smartbucket`);
}
return messages;
}
private async writeMessages(boxId: string, messages: IVoicemailMessage[]): Promise<void> {
this.messagesByBox.set(boxId, [...messages]);
await this.storage.writeVoicemailMessages(boxId, messages);
}
}
+1 -1
View File
@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: 'siprouter',
version: '1.25.2',
version: '1.27.0',
description: 'undefined'
}
+346 -65
View File
@@ -175,36 +175,240 @@ export class SipproxyViewCalls extends DeesElement {
.call-body {
padding: 12px 16px 16px;
display: grid;
gap: 16px;
}
.legs-table {
width: 100%;
border-collapse: collapse;
font-size: 0.75rem;
margin-bottom: 12px;
.call-overview {
display: grid;
grid-template-columns: minmax(0, 1.6fr) minmax(240px, 0.9fr);
gap: 14px;
}
.legs-table th {
text-align: left;
color: #64748b;
font-weight: 500;
font-size: 0.65rem;
.call-route-card,
.call-facts-card,
.legs-section {
border-radius: 14px;
border: 1px solid rgba(51, 65, 85, 0.75);
background:
linear-gradient(180deg, rgba(15, 23, 42, 0.92) 0%, rgba(8, 15, 31, 0.88) 100%);
box-shadow: inset 0 1px 0 rgba(148, 163, 184, 0.08);
}
.call-route-card,
.call-facts-card {
padding: 14px;
}
.section-kicker {
font-size: 0.62rem;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
letter-spacing: 0.04em;
padding: 6px 8px;
border-bottom: 1px solid var(--dees-color-border-default, #334155);
color: #64748b;
}
.legs-table td {
padding: 8px;
font-family: 'JetBrains Mono', monospace;
font-size: 0.7rem;
border-bottom: 1px solid var(--dees-color-border-subtle, rgba(51, 65, 85, 0.5));
vertical-align: middle;
.route-line {
display: grid;
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
align-items: center;
gap: 12px;
margin-top: 12px;
}
.legs-table tr:last-child td {
.route-party {
min-width: 0;
display: flex;
flex-direction: column;
gap: 4px;
padding: 12px;
border-radius: 12px;
background: rgba(15, 23, 42, 0.6);
border: 1px solid rgba(71, 85, 105, 0.45);
}
.route-party.align-end {
text-align: right;
align-items: flex-end;
}
.route-party-label {
font-size: 0.64rem;
letter-spacing: 0.06em;
text-transform: uppercase;
color: #64748b;
}
.route-party-value {
min-width: 0;
font-size: 0.95rem;
font-weight: 600;
color: #e2e8f0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.route-arrow {
width: 34px;
height: 34px;
border-radius: 999px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1rem;
color: #93c5fd;
background: rgba(30, 41, 59, 0.8);
border: 1px solid rgba(59, 130, 246, 0.35);
}
.call-tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 12px;
}
.subtle-badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 9px;
border-radius: 999px;
font-size: 0.66rem;
font-weight: 700;
letter-spacing: 0.03em;
color: #cbd5e1;
background: rgba(30, 41, 59, 0.9);
border: 1px solid rgba(71, 85, 105, 0.45);
}
.call-facts-card {
display: grid;
gap: 8px;
}
.fact-row {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
padding: 7px 0;
border-bottom: 1px solid rgba(51, 65, 85, 0.55);
}
.fact-row:last-child {
border-bottom: none;
padding-bottom: 0;
}
.fact-label {
font-size: 0.65rem;
letter-spacing: 0.06em;
text-transform: uppercase;
color: #64748b;
}
.fact-value {
font-family: 'JetBrains Mono', monospace;
font-size: 0.76rem;
text-align: right;
color: #e2e8f0;
word-break: break-word;
}
.legs-section {
padding: 14px;
display: grid;
gap: 12px;
}
.legs-header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
}
.legs-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 12px;
}
.leg-card {
display: grid;
gap: 12px;
padding: 12px;
border-radius: 12px;
background: rgba(15, 23, 42, 0.6);
border: 1px solid rgba(71, 85, 105, 0.4);
}
.leg-card-top {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 10px;
}
.leg-card-badges {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.leg-card-id {
font-family: 'JetBrains Mono', monospace;
font-size: 0.64rem;
color: #64748b;
word-break: break-all;
text-align: right;
}
.leg-facts {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px 12px;
}
.leg-fact {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.leg-fact-wide {
grid-column: 1 / -1;
}
.leg-fact-label {
font-size: 0.62rem;
letter-spacing: 0.06em;
text-transform: uppercase;
color: #64748b;
}
.leg-fact-value {
font-family: 'JetBrains Mono', monospace;
font-size: 0.76rem;
color: #e2e8f0;
word-break: break-word;
}
.leg-actions {
display: flex;
justify-content: flex-end;
}
.no-legs {
padding: 16px;
border-radius: 12px;
border: 1px dashed rgba(71, 85, 105, 0.55);
color: #64748b;
font-size: 0.75rem;
text-align: center;
}
.card-actions {
@@ -247,6 +451,34 @@ export class SipproxyViewCalls extends DeesElement {
.empty-state-icon { font-size: 2.5rem; margin-bottom: 12px; opacity: 0.4; }
.empty-state-text { font-size: 0.9rem; font-weight: 500; }
.empty-state-sub { font-size: 0.75rem; margin-top: 4px; }
@media (max-width: 820px) {
.call-overview {
grid-template-columns: 1fr;
}
.route-line {
grid-template-columns: 1fr;
}
.route-arrow {
justify-self: center;
transform: rotate(90deg);
}
.route-party.align-end {
text-align: left;
align-items: flex-start;
}
.leg-card-top {
flex-direction: column;
}
.leg-card-id {
text-align: left;
}
}
`,
];
@@ -550,61 +782,110 @@ export class SipproxyViewCalls extends DeesElement {
</div>
<div class="call-id">${call.id}</div>
<div class="call-body">
${call.legs.length
? html`
<table class="legs-table">
<thead>
<tr>
<th>Type</th>
<th>State</th>
<th>Remote</th>
<th>Port</th>
<th>Codec</th>
<th>Pkts In</th>
<th>Pkts Out</th>
<th></th>
</tr>
</thead>
<tbody>
<div class="call-overview">
<div class="call-route-card">
<div class="section-kicker">Call Route</div>
<div class="route-line">
<div class="route-party">
<div class="route-party-label">From</div>
<div class="route-party-value">${call.callerNumber || 'Unknown caller'}</div>
</div>
<div class="route-arrow">${directionIcon(call.direction)}</div>
<div class="route-party align-end">
<div class="route-party-label">To</div>
<div class="route-party-value">${call.calleeNumber || 'System'}</div>
</div>
</div>
<div class="call-tags">
<span class="subtle-badge">${call.legs.length} ${call.legs.length === 1 ? 'leg' : 'legs'}</span>
<span class="subtle-badge">${call.providerUsed || 'system handled'}</span>
<span class="subtle-badge">started ${fmtTime(call.startedAt)}</span>
</div>
</div>
<div class="call-facts-card">
<div class="section-kicker">Session</div>
<div class="fact-row">
<span class="fact-label">State</span>
<span class="fact-value">${STATE_LABELS[call.state] || call.state}</span>
</div>
<div class="fact-row">
<span class="fact-label">Direction</span>
<span class="fact-value">${call.direction}</span>
</div>
<div class="fact-row">
<span class="fact-label">Duration</span>
<span class="fact-value">${fmtDuration(call.duration)}</span>
</div>
<div class="fact-row">
<span class="fact-label">Provider</span>
<span class="fact-value">${call.providerUsed || '--'}</span>
</div>
</div>
</div>
<div class="legs-section">
<div class="legs-header">
<div class="section-kicker">Active Legs</div>
<span class="subtle-badge">${call.legs.length}</span>
</div>
${call.legs.length
? html`
<div class="legs-grid">
${call.legs.map(
(leg) => html`
<tr>
<td>
<span class="badge" style="${legTypeBadgeStyle(leg.type)}">
${LEG_TYPE_LABELS[leg.type] || leg.type}
</span>
</td>
<td>
<span class="badge" style="${stateBadgeStyle(leg.state)}">
${leg.state}
</span>
</td>
<td>
${leg.remoteMedia || '--'}
</td>
<td>${leg.rtpPort ?? '--'}</td>
<td>
${leg.codec || '--'}${leg.transcoding ? ' (transcode)' : ''}
</td>
<td>${leg.pktReceived}</td>
<td>${leg.pktSent}</td>
<td>
<div class="leg-card">
<div class="leg-card-top">
<div class="leg-card-badges">
<span class="badge" style="${legTypeBadgeStyle(leg.type)}">
${LEG_TYPE_LABELS[leg.type] || leg.type}
</span>
<span class="badge" style="${stateBadgeStyle(leg.state)}">
${STATE_LABELS[leg.state] || leg.state}
</span>
</div>
<div class="leg-card-id">${leg.id}</div>
</div>
<div class="leg-facts">
<div class="leg-fact">
<span class="leg-fact-label">Codec</span>
<span class="leg-fact-value">${leg.codec || '--'}${leg.transcoding ? ' (transcode)' : ''}</span>
</div>
<div class="leg-fact">
<span class="leg-fact-label">RTP Port</span>
<span class="leg-fact-value">${leg.rtpPort ?? '--'}</span>
</div>
<div class="leg-fact leg-fact-wide">
<span class="leg-fact-label">Remote Media</span>
<span class="leg-fact-value">${leg.remoteMedia || '--'}</span>
</div>
<div class="leg-fact">
<span class="leg-fact-label">Packets In</span>
<span class="leg-fact-value">${leg.pktReceived}</span>
</div>
<div class="leg-fact">
<span class="leg-fact-label">Packets Out</span>
<span class="leg-fact-value">${leg.pktSent}</span>
</div>
</div>
<div class="leg-actions">
<button
class="btn btn-remove"
@click=${() => this.handleRemoveLeg(call, leg)}
>
Remove
</button>
</td>
</tr>
</div>
</div>
`,
)}
</tbody>
</table>
`
: html`<div style="color:#64748b;font-size:.75rem;font-style:italic;margin-bottom:8px;">
No legs
</div>`}
</div>
`
: html`<div class="no-legs">No legs reported yet. SIP/system legs should appear here as soon as the call is wired.</div>`}
</div>
<div class="card-actions">
<button class="btn btn-primary" @click=${() => this.handleAddParticipant(call)}>