<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Ahmed Elbashier]]></title><description><![CDATA[Ahmed Elbashier]]></description><link>https://ahmedelbashier.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 28 Nov 2026 02:13:29 GMT</lastBuildDate><atom:link href="https://ahmedelbashier.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Your SIP Call Connects, but Only One Side Can Hear. The Bug Is Usually One Line of SDP.]]></title><description><![CDATA[A support agent picks up a call. The customer can hear the agent perfectly, but the agent hears nothing at all. Both phones show "connected", the SIP…]]></description><link>https://ahmedelbashier.hashnode.dev/your-sip-call-connects-but-only-one-side-can-hear-the-bug-is-usually-one-line-of-sdp</link><guid isPermaLink="true">https://ahmedelbashier.hashnode.dev/your-sip-call-connects-but-only-one-side-can-hear-the-bug-is-usually-one-line-of-sdp</guid><category><![CDATA[voip]]></category><category><![CDATA[WebRTC]]></category><category><![CDATA[networking]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[SIP]]></category><dc:creator><![CDATA[Ahmed Elbashier]]></dc:creator><pubDate>Fri, 27 Nov 2026 09:35:51 GMT</pubDate><content:encoded><![CDATA[<p>A support agent picks up a call. The customer can hear the agent perfectly, but the agent hears nothing at all. Both phones show "connected", the SIP ladder in the logs looks perfect (INVITE, 100, 180, 200 OK, ACK), and the call times out with the customer still saying "hello?" into silence.</p>
<p>The first place to look is one line of the SDP, the <code>c=</code> line, before touching any firewall rule. If it holds an address like <code>192.168.1.23</code>, nobody on the internet can send packets there.</p>
<p>To make that check fast and repeatable, I wrote a small tool, <a href="https://github.com/AhmedElbashier/sip-nat-sdp-doctor">sip-nat-sdp-doctor</a>. You give it an INVITE and its 200 OK, and it tells you who won't hear whom. This post explains the mechanism behind its checks.</p>
<h2>Why it's one-way and not no-way</h2>
<p>SIP only sets the call up. The audio travels separately as RTP, and each side's SDP tells the other side where to send it:</p>
<pre><code>c=IN IP4 192.168.1.23
m=audio 4000 RTP/AVP 8 0 101
</code></pre>
<p>That means "send my audio to 192.168.1.23, port 4000". A softphone on a home LAN puts its own interface address there, because that is the only address it knows.</p>
<p>Now follow the packets.</p>
<p><img src="https://raw.githubusercontent.com/AhmedElbashier/sip-nat-sdp-doctor/main/docs/one-way-audio.png" alt="One-way audio: RTP out of the NAT arrives, RTP back to the SDP address is lost" /></p>
<ol>
<li><strong>Phone â†’ PBX works.</strong> The phone sends RTP to the PBX's public address. The NAT rewrites the source to <code>203.0.113.45:&lt;some port&gt;</code> and the packet arrives. The PBX side hears the caller.</li>
<li><strong>PBX â†’ phone fails.</strong> The PBX does what the SDP says and sends RTP to <code>192.168.1.23:4000</code>. That address is not routable on the internet. The packet is dropped, or worse, it goes to some unrelated host on the PBX's own LAN. The caller hears nothing.</li>
</ol>
<p>Outbound through NAT works and inbound to a private address doesn't, so you get one-way audio. If both sides advertise private addresses, you get silence in both directions.</p>
<p>The same thing happens in reverse, and this version shows up in cloud deployments. A PBX on a VM with 1:1 NAT only sees its private NIC address (say <code>172.31.5.10</code>) and advertises that in its 200 OK. This time the <em>callee</em> side goes deaf.</p>
<h2>The evidence is already in the SIP message</h2>
<p>The useful part is that signalling usually shows you the NAT, as long as you know where to look. Here is the phone's Via header as the proxy forwarded it (synthetic trace from the repo):</p>
<pre><code>Via: SIP/2.0/UDP 192.168.1.23:5060;branch=z9hG4bK-02a;rport=62011;received=203.0.113.45
</code></pre>
<ul>
<li><code>192.168.1.23:5060</code> is the <em>sent-by</em>: where the phone thinks it is.</li>
<li><code>received=203.0.113.45</code> was added by the proxy because the packet arrived from a different IP (RFC 3261, section 18.2.1).</li>
<li><code>rport=62011</code> was filled in because the phone asked for it with an empty <code>;rport</code> (<a href="https://www.rfc-editor.org/rfc/rfc3581">RFC 3581</a>). It shows that the NAT also rewrote the port, 5060 to 62011.</li>
</ul>
<p>When <code>received=</code> is a public IP and the SDP <code>c=</code> is a private one in the same message, the diagnosis is basically done. The tool encodes exactly that comparison.</p>
<h2>What the tool checks</h2>
<p>It is about 450 lines of TypeScript with zero runtime dependencies. Node 22.18+ runs the <code>.ts</code> files directly. The core address check is short:</p>
<pre><code class="language-ts">export function classify(addr: string): AddrClass {
  const v4 = parseIPv4(addr);
  if (v4) {
    const [x, y] = v4;
    if (x === 10) return 'private';
    if (x === 172 &amp;&amp; y &gt;= 16 &amp;&amp; y &lt;= 31) return 'private';   // RFC 1918
    if (x === 192 &amp;&amp; y === 168) return 'private';
    if (x === 100 &amp;&amp; y &gt;= 64 &amp;&amp; y &lt;= 127) return 'cgnat';    // RFC 6598
    if (x === 127) return 'loopback';
    if (x === 169 &amp;&amp; y === 254) return 'link-local';
    // ...0.0.0.0, IPv6 ULA/link-local, *.local mDNS
  }
}
</code></pre>
<p>The <code>100.64.0.0/10</code> line is the one most homemade checks miss. Mobile carriers use carrier-grade NAT, so a softphone on 4G/5G can advertise <code>100.64.37.9</code>. That is not RFC 1918, but it is just as unreachable.</p>
<p>On top of that, it checks:</p>
<ul>
<li><strong>SDP media</strong> (<code>c=</code> session- or media-level, plus <code>m=</code> port) against the side's real public address: the Via <code>received=</code>, or a <code># source:</code> line you copy from your pcap.</li>
<li><strong>Via without <code>;rport</code></strong> over UDP from behind NAT. The server will answer to the <em>sent-by port</em>, and a NAT that remaps ports drops that answer. Then you don't even get the 200 OK.</li>
<li><strong>Private <code>Contact</code></strong>, which is where ACK, BYE and re-INVITE get sent. This is the "call won't hang up" sibling of one-way audio.</li>
<li><strong>RTCP</strong>: a private <code>a=rtcp:</code> address, or no <code>a=rtcp-mux</code>, which means RTCP needs a second NAT pinhole on port+1 (<a href="https://www.rfc-editor.org/rfc/rfc5761">RFC 5761</a>).</li>
<li><strong>ICE</strong>: a private <code>c=</code> <em>with</em> a srflx or relay candidate is a warning, not an error. ICE peers will connect, but a non-ICE peer will still send media to <code>c=</code>. Host-only or <code>.local</code> (mDNS) candidates are flagged too.</li>
<li><strong>Things that look like NAT but aren't</strong>: <code>a=sendonly</code>/<code>recvonly</code>/<code>inactive</code> (hold), and <code>c=0.0.0.0</code>, which means old-style hold without ICE and is just a placeholder with ICE.</li>
</ul>
<p>The verdict comes from combining offer and answer. A private address in the INVITE means the caller won't hear. A private address in the 200 OK means the callee won't hear.</p>
<h2>Running it</h2>
<p>The repo ships six <strong>synthetic</strong> traces I wrote by hand, using RFC 5737 documentation addresses. None of them is a capture from a real network. They are a clean call, a home-NAT softphone, a cloud PBX with a private answer, a CGNAT mobile client without <code>;rport</code> (written with compact headers like <code>v:</code> and <code>m:</code> to exercise the parser), an ICE softphone with a srflx candidate, and a hold that only looks like one-way audio.</p>
<p>Here is the real output for the home-NAT trace:</p>
<p><img src="https://raw.githubusercontent.com/AhmedElbashier/sip-nat-sdp-doctor/main/docs/terminal-02.png" alt="sip-nat-doctor output for the home NAT trace" /></p>
<p>Across all six traces (10 SIP messages), my run on Node v24.22.1 produced 3 errors, 6 warnings and 17 info findings, with these verdicts:</p>
<table>
<thead>
<tr>
<th>Trace</th>
<th>Verdict</th>
</tr>
</thead>
<tbody><tr>
<td>01 clean public</td>
<td>no findings</td>
</tr>
<tr>
<td>02 home NAT, private INVITE SDP</td>
<td>caller won't hear</td>
</tr>
<tr>
<td>03 cloud PBX, private 200 OK SDP</td>
<td>callee won't hear</td>
</tr>
<tr>
<td>04 CGNAT, no <code>;rport</code></td>
<td>caller won't hear, and responses may not arrive</td>
</tr>
<tr>
<td>05 ICE softphone</td>
<td>works with ICE peers only (warning)</td>
</tr>
<tr>
<td>06 <code>sendonly</code>/<code>recvonly</code></td>
<td>negotiated hold, not NAT</td>
</tr>
</tbody></table>
<p>The test suite is 18 <code>node:test</code> tests. They cover the RFC 1918 and CGNAT boundaries (<code>172.15.x</code> public, <code>172.16.x</code> private, <code>100.63.x</code> public, <code>100.64.x</code> CGNAT), IPv6 sent-by in brackets, comma-joined Vias, header folding, and every trace's verdict. All 18 pass, locally and in CI on Node 22 and 24. The CLI exits with code 2 when it finds an error, so you can run it against recorded traces in a pipeline.</p>
<h2>Fixing it, in the order I'd try</h2>
<ol>
<li><strong>Tell the box its public address.</strong> For a PBX behind 1:1 NAT, this is configuration, not a workaround. In Asterisk PJSIP, set <code>external_media_address</code>, <code>external_signaling_address</code> and <code>local_net</code> on the transport. In FreeSWITCH, set <code>ext-rtp-ip</code> and <code>ext-sip-ip</code> on the Sofia profile.</li>
<li><strong>ICE with STUN/TURN</strong> on endpoints you control. WebRTC already requires ICE. Many desk phones and older SIP stacks don't support it.</li>
<li><strong>Latching, or symmetric RTP</strong> (<a href="https://www.rfc-editor.org/rfc/rfc7362">RFC 7362</a>), on the public side: ignore the SDP address and send media back to wherever RTP actually arrived from. Asterisk does this with <code>rtp_symmetric=yes</code>, and FreeSWITCH with its RTP auto-adjust. It works because the NAT will let return traffic through the mapping the phone opened. The trade-off: whoever sends to that port first can steer the media, which is why the RFC spends a whole section on security.</li>
<li><strong>A media relay</strong> (rtpengine via Kamailio <code>rtpengine_manage()</code>, or an SBC) that rewrites the SDP and anchors the media. For signalling, use <code>force_rport()</code> with <code>fix_nated_contact()</code> or <code>set_contact_alias()</code>.</li>
</ol>
<p>Before any of these, check <code>a=sendonly</code>. Sometimes "one-way audio" is just a hold that nobody released.</p>
<h2>What the tool can't see</h2>
<p>It reads SDP. It doesn't watch packets. It can't see a router's SIP ALG rewriting the SDP in flight, which is a whole separate kind of breakage, or firewall rules, or an SBC changing media mid-path. Use it to decide where to point <code>sngrep</code> and <code>tcpdump</code> first.</p>
<h2>The takeaway</h2>
<p>One-way audio is almost never "the network being flaky". It's an address in the SDP that the other side can't reach. The signalling in the same message usually tells you the real address (<code>received=</code>, <code>rport=</code>). Compare the two before you open any firewall ports.</p>
<hr />
<p><strong>Code:</strong> <a href="https://github.com/AhmedElbashier/sip-nat-sdp-doctor">github.com/AhmedElbashier/sip-nat-sdp-doctor</a> has the CLI, six synthetic traces, 18 tests and the raw run output. Run <code>npm test</code>, then <code>node src/cli.ts traces/*.sip</code>.</p>
<p>I'm Ahmed, a full-stack and integrations engineer (.NET, Next.js, VoIP/WebRTC/SIP). More of my work is on <a href="https://github.com/AhmedElbashier">GitHub</a> and <a href="https://ahmedelbashier-portfolio.netlify.app/">my portfolio</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Your HttpClient Retry Policy Probably Never Retried a Hung Request]]></title><description><![CDATA[A phone is ringing, and your service has a couple of seconds to look the caller up in the CRM so the agent sees a name instead of a bare number. The CRM's…]]></description><link>https://ahmedelbashier.hashnode.dev/your-httpclient-retry-policy-probably-never-retried-a-hung-request</link><guid isPermaLink="true">https://ahmedelbashier.hashnode.dev/your-httpclient-retry-policy-probably-never-retried-a-hung-request</guid><category><![CDATA[APIs]]></category><category><![CDATA[Testing]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[c sharp]]></category><dc:creator><![CDATA[Ahmed Elbashier]]></dc:creator><pubDate>Thu, 26 Nov 2026 09:03:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b06946373ae72dc5760aaaf/4d9512a0-3ccf-428d-87e0-5467f579bcb7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A phone is ringing, and your service has a couple of seconds to look the caller up in the CRM so the agent sees a name instead of a bare number. The CRM's first request hangs. You have a retry policy with three retries and exponential backoff, so you expect the second attempt to save you. It never runs. The call is answered with no context, and the logs show one <code>TaskCanceledException</code>.</p>
<p>I found this pattern in my own public template, <a href="https://github.com/AhmedElbashier/dotnet-integration-api-template">dotnet-integration-api-template</a>. It sets <code>http.Timeout = 10s</code> on a typed <code>HttpClient</code> and adds a Polly retry with <code>AddPolicyHandler</code>. The retries work fine for fast failures (a 503, a refused connection). For a request that <strong>hangs</strong>, the whole 10 seconds goes to attempt one, and the retry loop is cancelled with it.</p>
<p>So I built a small lab to measure exactly what each common wiring does.</p>
<h2>The setup</h2>
<p>Every scenario uses the same fake upstream: attempt 1 hangs (30 s), and attempt 2 onwards answers <code>200</code> immediately. Every scenario has the same budget: 2 s for the whole call, 500 ms per attempt where a per-attempt timeout exists, 3 retries, 200 ms base backoff.</p>
<p>The fake upstream is a primary <code>HttpMessageHandler</code> that logs every attempt, so the tests can count what really went over the "wire":</p>
<pre><code class="language-csharp">protected override async Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken ct)
{
    var n = Interlocked.Increment(ref _attempts);
    if (n &lt;= HangingAttempts)
        await Task.Delay(HangFor, ct);   // hang until cancelled
    return new HttpResponseMessage(HttpStatusCode.OK);
}
</code></pre>
<p>These are the four wirings:</p>
<pre><code class="language-csharp">// A: the common one. HttpClient.Timeout + retry handler
b.ConfigureHttpClient(c =&gt; c.Timeout = TimeSpan.FromSeconds(2));
b.AddPolicyHandler(retry);

// B: a Polly timeout, but registered BEFORE the retry
b.AddPolicyHandler(Policy.TimeoutAsync&lt;HttpResponseMessage&gt;(TimeSpan.FromSeconds(2)));
b.AddPolicyHandler(retry);

// C: retry first, per-attempt timeout second, HttpClient.Timeout as the total budget
b.ConfigureHttpClient(c =&gt; c.Timeout = TimeSpan.FromSeconds(2));
b.AddPolicyHandler(retry);   // retry also handles TimeoutRejectedException
b.AddPolicyHandler(Policy.TimeoutAsync&lt;HttpResponseMessage&gt;(TimeSpan.FromMilliseconds(500)));

// D: Microsoft.Extensions.Http.Resilience
b.AddStandardResilienceHandler(o =&gt;
{
    o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(2);
    o.AttemptTimeout.Timeout = TimeSpan.FromMilliseconds(500);
    o.Retry.Delay = TimeSpan.FromMilliseconds(200);
});
</code></pre>
<h2>The results</h2>
<p>This is one real run on my Linux x64 dev box with .NET 8.0.34. The exact milliseconds will vary on your machine. The attempt counts won't.</p>
<p><img src="https://raw.githubusercontent.com/AhmedElbashier/httpclient-timeout-retry-lab/main/docs/demo-table.png" alt="Demo output: A and B fail after one attempt at ~2 s; C and D succeed on attempt two in ~0.7 s" /></p>
<table>
<thead>
<tr>
<th>Scenario</th>
<th>Outcome</th>
<th>Attempts</th>
<th>Elapsed</th>
</tr>
</thead>
<tbody><tr>
<td>A: <code>HttpClient.Timeout</code> + retry</td>
<td><code>TaskCanceledException</code></td>
<td>1</td>
<td>2006 ms</td>
</tr>
<tr>
<td>B: timeout policy outside retry</td>
<td><code>TimeoutRejectedException</code></td>
<td>1</td>
<td>2000 ms</td>
</tr>
<tr>
<td>C: retry outside per-attempt timeout</td>
<td><code>200 OK</code></td>
<td>2</td>
<td>705 ms</td>
</tr>
<tr>
<td>D: <code>AddStandardResilienceHandler</code></td>
<td><code>200 OK</code></td>
<td>2</td>
<td>742 ms</td>
</tr>
</tbody></table>
<p>All four have the same retry policy, and only two of them ever retry. Here is the per-attempt timeline from the same run:</p>
<p><img src="https://raw.githubusercontent.com/AhmedElbashier/httpclient-timeout-retry-lab/main/docs/timeline.png" alt="Timeline of attempts per scenario" /></p>
<h2>Why A fails: HttpClient.Timeout wraps the whole pipeline</h2>
<p><code>HttpClient.Timeout</code> is not a socket timeout. <code>HttpClient</code> creates a cancellation token linked to that timeout and passes it into the entire <code>DelegatingHandler</code> chain that <code>IHttpClientFactory</code> built. That chain includes your Polly handler. Retries happen <em>inside</em> that token's lifetime.</p>
<p>When attempt one hangs, nothing fails fast. The token fires at 2 s, the in-flight attempt is cancelled, and the retry handler sees a cancellation rather than a transient failure. The template's retry uses <code>HandleTransientHttpError()</code>, which handles <code>HttpRequestException</code>, 5xx and 408, but not cancellation.</p>
<p>The obvious "fix" is to also handle <code>TaskCanceledException</code>. I added that as a separate test (A2), and it still makes exactly <strong>one</strong> attempt. The token that <code>HttpClient</code> passed down is already cancelled, so there is nothing left to retry with. The default <code>HttpClient.Timeout</code> is 100 seconds, which is why many apps never notice: they just wait a very long time.</p>
<h2>Why B fails: handler order is outermost-first</h2>
<p>With <code>IHttpClientFactory</code>, handlers run in the order you register them, and the first one registered is the outermost. Registering the timeout before the retry gives one timeout around <em>all</em> attempts. That makes it a total-budget timeout, not a per-attempt one. Polly's own guidance for HttpClientFactory says the same thing: put the per-try timeout inside the retry (<a href="https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory">Polly wiki: Polly and HttpClientFactory</a>).</p>
<h2>Why C and D work</h2>
<p>In C, the retry is the outer handler, and each attempt gets its own 500 ms timeout. Attempt one is cut at ~500 ms with a <code>TimeoutRejectedException</code>, which the retry handles. After a 200 ms backoff, attempt two returns 200 at ~705 ms. <code>HttpClient.Timeout</code> is still there, but now it means what it should: the total budget for the call.</p>
<p>D is the same shape, packaged. According to the <a href="https://learn.microsoft.com/en-us/dotnet/core/resilience/http-resilience">Microsoft Learn docs</a>, the standard handler chains rate limiter → <strong>total timeout</strong> → <strong>retry</strong> → circuit breaker → <strong>attempt timeout</strong>, outermost to innermost. The defaults are a 30 s total, a 10 s per attempt, and 3 retries with a 2 s exponential base delay and jitter. The retry handles <code>TimeoutRejectedException</code> by default.</p>
<p>I also tested the worst case, where the upstream hangs on <em>every</em> attempt. Both C and D stop at the 2 s total budget after 2–4 attempts instead of blowing past it.</p>
<h2>Gotchas I hit along the way</h2>
<ul>
<li><strong>Leave <code>HttpClient.Timeout</code> above the pipeline's total timeout.</strong> With D, I set it to the total plus one second. If it is lower, it fires first, and you are back in scenario A with a cancellation instead of the pipeline's own <code>TimeoutRejectedException</code>.</li>
<li><strong>Polly v7 and Polly v8 collide.</strong> <code>Microsoft.Extensions.Http.Polly</code> (v7) and <code>Microsoft.Extensions.Http.Resilience</code> (Polly.Core v8) both define <code>Polly.Timeout.TimeoutRejectedException</code>. Referencing both in one project gives <code>CS0433</code>. The lab uses an <code>extern alias</code> so it can compare them side by side. In a real app, pick one stack.</li>
<li><strong>Retries and POST don't mix by default.</strong> The standard handler retries all HTTP methods. Retrying a POST that creates a record can create it twice unless the endpoint is idempotent. The docs show <code>options.Retry.DisableFor(HttpMethod.Post, ...)</code>.</li>
<li><strong>Test attempt counts, not just outcomes.</strong> A test that only asserts "eventually got an exception" passes for A and B. The useful assertion is <code>Assert.Equal(2, upstream.Attempts)</code>.</li>
</ul>
<h2>The takeaway</h2>
<p>A retry policy only retries what it is allowed to see. If your only timeout is <code>HttpClient.Timeout</code>, or a Polly timeout registered before the retry, a hung upstream uses up the whole budget on attempt one, and your retries are decoration.</p>
<p>Give every call two numbers: a <strong>per-attempt</strong> timeout inside the retry and a <strong>total</strong> budget outside it. For anything with a human waiting on the other end, such as a ringing phone, a checkout or a chat reply, choose those numbers from how long that human will wait, not from the 100-second default.</p>
<p>My template has the same issue, so updating its wiring is my next change.</p>
<hr />
<p><strong>Code:</strong> <a href="https://github.com/AhmedElbashier/httpclient-timeout-retry-lab">github.com/AhmedElbashier/httpclient-timeout-retry-lab</a> has the four scenarios, 7 xUnit tests, the raw run output and the chart script. Run it with <code>dotnet test -c Release</code>.</p>
<p>I'm Ahmed, a full-stack and integrations engineer (.NET, Next.js, VoIP/WebRTC). More of my work is on <a href="https://github.com/AhmedElbashier">GitHub</a> and <a href="https://ahmedelbashier-portfolio.netlify.app/">my portfolio</a>.</p>
]]></content:encoded></item><item><title><![CDATA[How I built a browser softphone with a one-command Kamailio + FreeSWITCH lab and real-call E2E tests]]></title><description><![CDATA[Getting a browser to place a real SIP call is a messy weekend. You need a JavaScript SIP stack, a WebSocket signalling path, WebRTC media (DTLS-SRTP, ICE…]]></description><link>https://ahmedelbashier.hashnode.dev/how-i-built-a-browser-softphone-with-a-one-command-kamailio-freeswitch-lab-and-real-call-e2e-tests</link><guid isPermaLink="true">https://ahmedelbashier.hashnode.dev/how-i-built-a-browser-softphone-with-a-one-command-kamailio-freeswitch-lab-and-real-call-e2e-tests</guid><category><![CDATA[Testing]]></category><category><![CDATA[WebRTC]]></category><category><![CDATA[voip]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Ahmed Elbashier]]></dc:creator><pubDate>Wed, 25 Nov 2026 07:58:08 GMT</pubDate><content:encoded><![CDATA[<p>Getting a browser to place a real SIP call is a messy weekend. You need a JavaScript SIP stack, a WebSocket signalling path, WebRTC media (DTLS-SRTP, ICE, a codec), and something on the other end that answers. Most samples give you one of those pieces. I wanted a repo where <code>docker compose up -d</code> and <code>npm run dev</code> is enough to register, call an echo test, walk an IVR with DTMF, and call another browser tab.</p>
<p>That repo is <a href="https://github.com/AhmedElbashier/webrtc-sip-softphone">webrtc-sip-softphone</a>. This post is a walk through how it is put together, how the tests work, and what the lab deliberately leaves out.</p>
<h2>What you get</h2>
<p>The softphone is framework-free TypeScript and Vite. It registers over <code>ws://</code> or <code>wss://</code>, dials a number or a SIP URI, answers, hangs up, mutes, holds and resumes, and sends DTMF (RFC 2833 in-media, or SIP INFO). During a call it shows live stats from <code>RTCPeerConnection.getStats()</code>: codec, packets, loss, jitter and RTT. One call at a time; a second incoming call is rejected with <code>486 Busy Here</code>.</p>
<p>The lab is a <code>docker-compose</code> file:</p>
<ul>
<li><strong>Kamailio 5.8</strong> as the WebSocket SIP proxy and in-memory registrar (RFC 7118 on port 8088), with NAT handling for WebSocket clients, record-routing, and routing of lab numbers to FreeSWITCH and of everything else to registered softphones.</li>
<li><strong>FreeSWITCH 1.10</strong> with a single-file config, WebRTC media (DTLS-SRTP, ICE, Opus) and three extensions:</li>
</ul>
<table>
<thead>
<tr>
<th>Dial</th>
<th>What happens</th>
</tr>
</thead>
<tbody><tr>
<td><code>9196</code></td>
<td>Echo: you hear yourself, which tests the full media path</td>
</tr>
<tr>
<td><code>5000</code></td>
<td>IVR: a flite text-to-speech menu. <strong>1</strong> echo, <strong>2</strong> tone, <strong>3</strong> goodbye and hang up</td>
</tr>
<tr>
<td><code>9664</code></td>
<td>Continuous 440 Hz tone</td>
</tr>
<tr>
<td><code>1002</code> (and so on)</td>
<td>Another softphone. Open a second tab with <code>?user=1002</code></td>
</tr>
</tbody></table>
<p>FreeSWITCH runs in Kamailio's network namespace (<code>network_mode: service:kamailio</code>). Kamailio reaches it on loopback, the FreeSWITCH SIP port is not published, and only the RTP range is exposed.</p>
<h2>Quickstart</h2>
<p>You need Docker with Compose, Node 20+, a Chromium or Firefox browser, and a microphone.</p>
<pre><code class="language-bash">docker compose up -d --wait
npm install
npm run dev   # http://localhost:5173
</code></pre>
<p>Click Connect (defaults: <code>ws://localhost:8088</code>, <code>sip:1001@lab.local</code>, no password) and dial <strong>9196</strong>. For phone-to-phone, open <code>http://localhost:5173/?user=1002&amp;autoconnect</code> in a second tab and call <code>1002</code>.</p>
<p>If you want to call from another device on your LAN, start the lab with <code>EXT_RTP_IP=&lt;your LAN IP&gt;</code> and serve the page over HTTPS. Browsers only allow the microphone on <code>https://</code> or <code>localhost</code>.</p>
<h2>Architecture, in short</h2>
<p>The UI talks to a <code>Softphone</code> class, which talks to a small <code>UALike</code> interface. The only production adapter is JsSIP. The phone's behaviour is a pure reducer in <code>src/core/state.ts</code>, driven by SIP events. That split is what makes the unit tests possible: everything except the JsSIP adapter is tested without a browser.</p>
<p>A call to the IVR looks like this:</p>
<ol>
<li>The browser REGISTERs over the WebSocket. Kamailio stores the contact with a WebSocket alias and returns 200.</li>
<li>The phone INVITEs <code>sip:5000@lab.local</code> with an SDP offer (Opus, DTLS, ICE).</li>
<li>Kamailio record-routes and forwards the INVITE to FreeSWITCH over UDP on loopback.</li>
<li>FreeSWITCH answers with SDP. ICE and DTLS complete, then SRTP audio flows between the browser and FreeSWITCH.</li>
<li>FreeSWITCH plays the menu. The phone sends DTMF <code>1</code> as RFC 2833 telephone-event. FreeSWITCH transfers that call into <code>echo()</code>.</li>
<li>BYE tears the call down along the record-route set, with Kamailio handling the WebSocket alias on the way back.</li>
</ol>
<p>The README has mermaid diagrams for the architecture and this sequence if you want the boxed version.</p>
<h2>Why the state is a reducer</h2>
<p>SIP events arrive late, twice, or out of order. A hold request should be ignored if the call already ended. A second incoming INVITE should not clobber an active call. Putting that in event-handler closures gets messy, and it is hard to test.</p>
<p>A reducer (<code>(state, event) =&gt; nextState</code>) can be fed a recorded list of events in a unit test, including the late and out-of-order ones, with no WebSocket and no browser. The <code>Softphone</code> class is tested against a fake user agent for dialling options, mute/hold/DTMF and the busy rejection. Settings validation, dial-string normalisation, DTMF checks, duration formatting and stats summarising are all pure functions.</p>
<p>There are 42 of those unit tests, run with Vitest (<code>npm test</code>).</p>
<h2>Real-call end-to-end tests</h2>
<p>Unit tests cannot tell you that ICE connected or that FreeSWITCH actually switched into echo after a DTMF 1. For that there are 4 Playwright tests (<code>npm run test:e2e</code>) that drive Chromium against the running lab, with a fake microphone:</p>
<ol>
<li>Register, call <code>9196</code>, wait until remote audio packets arrive, hang up.</li>
<li>Call the IVR, press <strong>1</strong>, and assert via <code>fs_cli</code> that FreeSWITCH is now running <code>echo</code> on that call.</li>
<li>Two browser contexts register as 1001 and 1002, call each other through Kamailio, and hold/resume.</li>
<li>Calling an unregistered number ends with Not Found.</li>
</ol>
<p>GitHub Actions runs the unit job, then a job that starts the lab with <code>docker compose up --wait</code>, checks the Kamailio config, and runs the Playwright suite.</p>
<p>A limit of those tests is worth stating clearly: Chromium's fake microphone means the audio checks are packet counts, not a human listening. The suite has not been run against Safari, real handsets, TURN, or a path that crosses real NAT. The lab's media path assumes the browser and the Docker host can reach each other directly.</p>
<h2>What the lab deliberately leaves out</h2>
<p>This is a development lab, not a box you should put on the public internet as-is.</p>
<ul>
<li><strong>TLS.</strong> Use <code>wss://</code> (Kamailio's <code>tls</code> module, or a TLS-terminating proxy in front of port 8088).</li>
<li><strong>Auth.</strong> The lab registrar accepts anyone. Add digest auth (<code>auth</code> / <code>auth_db</code>) or token auth before exposing it.</li>
<li><strong>Media relay.</strong> Behind real NAT, use TURN for browsers and/or <code>rtpengine</code> with Kamailio.</li>
<li><strong>FreeSWITCH lock-down.</strong> The profile has <code>auth-calls=false</code> and is only safe because it listens on loopback.</li>
</ul>
<p>I would rather document those gaps than pretend the compose file is production-ready.</p>
<h2>If you want to try it</h2>
<p>The code is MIT licensed: <a href="https://github.com/AhmedElbashier/webrtc-sip-softphone">github.com/AhmedElbashier/webrtc-sip-softphone</a>. Issues and reviews are welcome. I also published an ASP.NET Core 8 webhook relay for WhatsApp Cloud API and HubSpot in the same week, if that is more your stack: <a href="https://github.com/AhmedElbashier/dotnet-webhook-relay">dotnet-webhook-relay</a>.</p>
<p>More of my work is on <a href="https://ahmedelbashier-portfolio.netlify.app/">my site</a>.</p>
]]></content:encoded></item></channel></rss>