# siprouter

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

- 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.

## Important Accuracy Notes

- 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

```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 Files

| 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. |

## Configuration

Create `.nogit/config.json` in the repository root before starting the service.

```jsonc
{
  "proxy": {
    "lanIp": "192.168.1.100",
    "lanPort": 5070,
    "publicIpSeed": null,
    "rtpPortRange": { "min": 20000, "max": 20200 },
    "webUiPort": 3060
  },
  "providers": [
    {
      "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": [
    {
      "id": "desk-phone",
      "displayName": "Desk Phone",
      "expectedAddress": "192.168.1.50",
      "extension": "100"
    }
  ],
  "routing": {
    "routes": [
      {
        "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": "main-trunk",
          "numberPattern": "+49421219694"
        },
        "action": {
          "targets": ["desk-phone"],
          "ringBrowsers": true,
          "voicemailBox": "main"
        }
      }
    ]
  },
  "contacts": [],
  "voiceboxes": [
    {
      "id": "main",
      "enabled": true,
      "greetingText": "Please leave a message after the tone.",
      "greetingVoice": "af_bella",
      "noAnswerTimeoutSec": 25,
      "maxRecordingSec": 120,
      "maxMessages": 50
    }
  ],
  "faxboxes": [],
  "ivr": {
    "enabled": false,
    "entryMenuId": "main-menu",
    "menus": []
  }
}
```

## Persistent Files

| 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`. |

## 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
pnpm install
pnpm run buildRust
pnpm run bundle
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.

**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.

### Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

### Company Information

Task Venture Capital GmbH  
Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
