A self-hosted unified-communications web app: WebRTC phone calls, SMS/MMS messaging, fax, voicemail, call history and contacts — one Go binary, one page, one login (your PBX extension and directory password). No plugin, no app install, no CDN, strict same-origin CSP.
The SIP call UI is a proven sip.js 0.21
island (multi-line calls, blind transfer, attended transfer (client half; the
network bridge is only proven once your PBX dialplan handles Replaces), DTMF, reconnect
watchdog, ICE diagnostics); everything around it — threads, faxes,
voicemail, history, contacts, live updates — is server-rendered
templ + HTMX, stored
in SQLite, and pushed to the browser over SSE.
Built as the dedicated home of the phone experience of nix-international-telephony, but usable against any SIP/WebSocket PBX (FreeSWITCH/sofia or compatible).
| Capability | Notes |
|---|---|
| Phone calls | Multi-line (N-deep ring queue + call dock), hold/focus/mute, blind transfer + an attended-transfer REFER (client half; the bridge needs Replaces in the dialplan); ended calls keep a post-call card (freeform note, optional AI summarize → draft SMS) |
| Resilience | Bounded reconnect watchdog with re-registration; live calls survive |
| Call comfort | Dial typeahead from your contacts, call state chip, missed-call badge, audio output picker for multi-output desks (the chosen device carries the call audio AND the locally generated ring tones), live-call context beside the island when the CRM knows the caller |
| SMS & MMS | Threads with unread badges, attachments in/out, delivery receipts, live updates, search over remote + message bodies; pin/mute/archive a conversation, quick reply snippets, optimistic send with retry |
| Fax | Send PDFs, receive documents, per-job status timeline, resend failed jobs, download; optional fire-and-forget Paperless-ngx archive of inbound faxes. Per-deployment: a server with no fax lane hides the send form and says so (fax.send / fax.receive, see Fax capabilities) |
| Voicemail | List, play (inline scrubber + speed control), delete — straight from the PBX's per-extension API |
| Call history | Server-side CDR records through the same API; outcome filters (missed/answered), day grouping, shareable filter URLs; per-call notes + reassembled live transcripts with search |
| Contacts | Shared (config) + personal (per extension), vCard import/export, click-to-dial |
| Reports | A pure fold of the same call records History lists: talk time, calls by direction and outcome, the per-day and busiest-hour ladders, the contacts that consumed the time, and an optional weekly talk-time budget as one bar (reports.weekly_talk_budget) |
| Data export | One session-gated download (Settings tab) zips every thread, fax job and personal contact of the signed-in extension |
| TURN auth | Optional short-lived coturn REST credentials derived per response (turn_rest.secret) — long-lived TURN passwords never ship |
| Live updates | Per-extension SSE feed: threads, open transcripts, fax list, voicemail |
| AI agent lane | OPTIONAL supervised textagent: an AI-drafts review panel in Messages (approve/discard/autopilot modes), a draft-mode pill in the header, ended-call summarize → draft SMS, draft-ready push to your phone, one greppable audit line per action |
| Sign-in | Credentials verified against the PBX directory server-side (401 on rejection, 502 if the PBX is down); the SIP island and the tabs share that login |
| Diagnostics | Live ICE/media panel with setup timings (gather, first media), pre-call mic/speaker self-test, English event log |
| i18n / themes | Everything in English + German; dark + light themes with a manual toggle |
| Command palette | Ctrl/Cmd-K palette for tabs and actions (Call, New message, Cycle theme); ? lists every keyboard shortcut |
| Accessibility | Skip-to-content link, screen-reader live announcements, aria-current nav, labelled badges, focus moves to the new panel on swap |
| Mobile | Nav becomes a fixed bottom tab bar; a live call keeps the island front and center; 44px tap targets |
| Deployment | Single static binary, SQLite + content-addressed blob store, /healthz, five-part operator boot-error contract (exit 1 designed / 2 panic), NixOS module |
| Recording | Done PBX-side by the telephony stack (stereo WAV, /recordings/ behind operator auth); this app shows CDR history rows only |
Pick the lane that matches your host:
nix run github:LarsArtmann/webphone # run straight from the flake
nix build github:LarsArtmann/webphone#webphone # build the closure, keep ./resultOn a NixOS host the flake exports a module
(nixosModules.default, see Deployment) that wires the
systemd unit, the Caddy vhost, backups and the typed option tree; on a
non-Nix host a plain go build ./cmd/webphone produces the same single
static binary (Go 1.27+, no cgo, SQLite via modernc).
nix run github:LarsArtmann/webphone # or: nix build .#webphone && ./result/bin/webphoneWith zero configuration the server starts on :8080 in loopback
gateway mode: messages and faxes are accepted instantly and marked
sent/transmitted, so the whole product is explorable without a PBX.
curl -fsS http://127.0.0.1:8080/healthz # readiness -> {"status":"ok",...} (sqlite ping + blob-dir write probe)
curl -fsS http://127.0.0.1:8080/livez # liveness -> 200 while the process serves (no checks run)
curl -fsS http://127.0.0.1:8080/startupz # startup -> 503 until the backing resources first pass, then latched 200All three are session-free GETs whose bodies name checks and statuses
only. Readiness stays /healthz alone; /livez deliberately runs no
checks so a prober can tell "wedged process" from "degraded
dependencies".
Set WEBPHONE_DASHBOARD__ENABLE=true (or dashboard.enable in the
config file) and /health serves a live operator dashboard — check
cards over SSE (go-health-dashboard), the container's health checks
(sqlite, blob-dir, plus the dashboard's own pusher staleness as a
non-critical warn), a status trend, and JSON on Accept: application/json. The page is CSP-strict: per-request nonces, no
unsafe-eval anywhere, and the Datastar SDK + its stylesheet served
same-origin from the binary (the SDK compiles its expressions from the
nonce stamped on the page root, dashboard v0.13.3). Probe aliases live at /health/livez,
/health/readyz, /health/startupz — same probe as the root triple,
never a second truth. Treat the subtree like the probe triple in front
of it: it is an operator surface, so fence it. Two fronts already do the
mechanical half: this module's optional Caddy vhost proxies /health/*
unbuffered for the SSE stream, and the telephony stack's
services.telephony.webphone.dashboard option does the same in its nginx
vhost — unbuffered, and fenced by the operator SSO gate when the operator
window runs in forwardAuth mode (loopback-only otherwise), because the
dashboard itself carries no authentication.
dashboard.title names the deployment on the page.
WEBPHONE_DEBUG_FLIGHTRECORDER=1 turns on a rolling execution-trace
window: the runtime keeps the last ten seconds of trace data in memory,
and a snapshot lands in <dataDir>/traces whenever a request runs
longer than two seconds or answers 5xx (newest 20 kept, gzip-compressed).
GET /internal/flightrecorder on the loopback listener captures one on
demand and answers with the path; gunzip it and open it with go tool trace. The endpoint is loopback-only and answers 404 while the seam is
off — like the rest of the debug surfaces, it never exists in the
browser. Leave it off unless you are chasing something: the runtime
tracer costs CPU on every goroutine.
Open the page, sign in on the phone panel (any extension format your PBX accepts; against nothing it will just fail to register), and the tabs unlock with the same login.
For real use you want, in front of or around the binary:
- TLS +
wss://<host>/sipproxied to your PBX's WebSocket transport (FreeSWITCH: sofiawss-binding). The island speaks SIP over that socket. - Optionally a phone API upstream (voicemail + CDR history).
- Optionally a gateway for real SMS/MMS/fax delivery (webhook mode).
Config comes from an optional JSON file (path via WEBPHONE_CONFIG,
default /etc/webphone/config.json), overridden by WEBPHONE_*
environment variables. Env keys use __ to nest:
WEBPHONE_GATEWAY__MODE=webhook → gateway.mode; single underscores stay
literal: WEBPHONE_DATA_DIR → data_dir. Scalars are env-friendly;
nested lists (ice_servers, contacts) and maps (identities) belong
in the JSON file.
Unknown keys warn at boot (one WARN line listing the key paths,
values never logged) and are then ignored — a config written for a newer
binary on an older binary shows up in the journal instead of silently
dropping its declarations. Zero unknown keys log nothing. Dynamic-key
maps (identities, auth.passkey.users) accept arbitrary children by
design and are exempt.
| Key | Default | Meaning |
|---|---|---|
addr |
:8080 |
Listen address |
data_dir |
/var/lib/webphone |
SQLite DB + content-addressed attachment/fax files (created if missing) |
sip_domain |
empty | SIP domain the island registers at (rendered into /config.js) |
websocket_path |
/sip |
WSS path the island connects to (must be proxied to the PBX) |
phone_api_url |
empty = disabled | Base URL of the per-extension API, e.g. https://pbx.example.com |
session_ttl |
7d |
Sliding idle window: activity past its halfway point renews the session (a regularly used device never re-signs-in) |
session_max_ttl |
30d |
Absolute session lifetime from sign-in — the cap that re-signs even a continuously renewed (or stolen) session |
retention_days |
0 |
0 keeps everything forever; a positive value makes a daily sweep delete messages (with attachments), fax jobs (with documents) and empty threads older than that many days |
timezone |
system local | IANA zone name owning every wall-clock rendering and log line; a typo fails validation instead of silently rendering UTC |
ice_servers |
empty | STUN/TURN entries handed to the island (urls, username, credential) |
turn_rest.secret |
empty | coturn REST API shared secret (must match coturn's static-auth-secret); when set, /config.js derives short-lived username/credential pairs for every turn:/turns: entry instead of shipping static passwords |
turn_rest.ttl |
48h |
Validity window of the derived TURN credentials (per-response freshness; the pair expires with the username's unix timestamp) |
contacts |
empty | Shared directory entries (name, number); a number with no dialable characters fails the boot naming the entry |
dial.cooldown |
0 (off) |
Advisory per-(extension, remote) redial cooldown (a duration, e.g. 2h): every dial asks POST /api/dials first; a remote inside its window gets the state line (last call age, time left) with a one-shot inline Dial anyway override. Off = no route, no ask, byte-identical product; the gate advises, it never traps (404/unreachable dials anyway) |
reports.weekly_talk_budget |
0 (no bar) |
Talk time the current week may spend, rendered as one bar under the Reports tab's week headline (a duration, e.g. 10h). Zero renders no bar — the tab still reports talk time |
identities |
empty | Extension → presented number (DID) shown as the user's own number (header, whoami, composers); display-only — a key that isn't a normalized extension fails the boot naming the key |
gateway.mode |
loopback |
loopback or webhook |
gateway.webhook_url |
empty | Provider base URL in webhook mode (required there) |
gateway.webhook_secret |
empty | Shared secret; also guards the inbound /hooks/* endpoints (fail-closed: hooks return 503 without it) |
gateway.webhook_secret_file |
empty | Read the shared secret from a runtime file at startup (single line) instead — one file both sides read beats keeping an env copy and the receiver's copy in sync; at most one of the two may be set |
fax.send |
true |
Deployment fact, not a code switch. Whether THIS deployment can send faxes (an outbound provider that accepts /fax). false removes the Fax panel's send form, replaces it with a plain notice saying sending is not configured, and adds a Fax row to Settings — instead of offering a form whose only possible outcome is a failed job. Unset = on (the zero-config product is unchanged) |
fax.receive |
true |
Whether THIS deployment can receive faxes (a fax number routed to the PBX). false keeps the panel and any history but says the list can never grow inwards. Both flags are independent; both false renders one combined "Fax is not available on this server" notice |
csrf.trusted_proxies |
empty | Local proxies whose X-Forwarded-Proto may be believed (the loopback front) — IP or CIDR entries |
csrf.trusted_origins |
empty | Browser-facing origins counted as same-origin (the TLS vhost, e.g. https://pbx.example.com) |
crm.url |
empty = disabled | Ledger CRM base URL for the optional integration (e.g. http://127.0.0.1:8080) |
crm.token |
empty | Bearer token of the CRM's machine API (-api-token there); both keys together or neither |
crm.token_file |
empty | Read the CRM bearer from a runtime file (the NixOS module's systemd LoadCredential lane) instead of crm.token; at most one of the two may be set |
crm.contact_url |
empty = no links | Deep-link template into the CRM's own UI; {id} is replaced with the CRM contact id (e.g. https://crm.example/contacts/{id}). Needs crm.url; a template without {id} refuses the boot |
crm.create_url |
empty = no affordance | Deep-link template into the CRM's NEW-CONTACT form for unknown callers; {phone} is replaced with the caller's dialable number (e.g. https://crm.example/contacts/new?phone={phone}). Needs crm.url; a template without {phone} refuses the boot. Opens in a new tab; the phone still stores no CRM record |
crm.ca_file |
empty = system roots | PEM bundle that vouches for the CRM vhost's TLS chain, trusted by the CRM client ALONE (a private-CA CRM without host-wide security.pki or SSL_CERT_FILE trust). Needs crm.url; a file holding no certificate refuses the boot |
paperless.url |
empty = disabled | Paperless-ngx base URL for the optional inbound-fax archive (e.g. http://127.0.0.1:2280); both keys together or neither |
paperless.token |
empty | Paperless-ngx API token (Profile → My Profile → API token) |
paperless.token_file |
empty | Read the Paperless bearer from a runtime file (the systemd LoadCredential lane, same as crm.token_file) instead of paperless.token; at most one of the two may be set |
asr.provider |
openai |
Provider kind: openai (any /v1/audio/transcriptions server), whispercpp (native whisper.cpp /inference server), or google (Cloud Speech-to-Text V2) |
asr.url |
empty = disabled | OpenAI wire: base URL of the provider (e.g. http://127.0.0.1:8081); a URL alone enables. Google wire: optional endpoint override (empty derives the europe-west3 regional endpoint) |
asr.token |
empty | OpenAI wire: optional bearer credential (a token WITHOUT a URL fails closed). Google wire: API key sent as x-goog-api-key |
asr.model |
whisper-1 / telephony |
Model name the provider expects (OpenAI wire: e.g. large-v3; Google wire defaults to the 8 kHz-tuned telephony) |
asr.project |
empty | Google wire: cloud project id — required when asr.provider=google, part of the recognizer path |
asr.location |
europe-west3 |
Google wire: region for the endpoint and recognizer path (EU residency default) |
asr.language |
de-DE |
Google wire: fallback BCP-47 code for segments without a language hint (V2 has no auto-detect); the per-request island language always wins |
push.ntfy.url |
empty = disabled | Ring-while-closed (native shells): base URL of the self-hosted ntfy server (e.g. https://ntfy.example.org); the URL alone enables the transport — per-device topics live in the registry, never here |
push.ntfy.token |
empty | Optional ntfy access token (bearer; a token WITHOUT a URL fails closed) — deliver via environmentFile |
push.fcm.credentials_file |
empty = disabled | FCM HTTP v1 service-account JSON key file (read + parsed at boot; a malformed file refuses the boot). The two transports are independent: either, both or neither |
textagent.url |
empty = disabled | Review-API base of the stack's supervised text agent (services.telephony.textagent, e.g. http://127.0.0.1:8071); both keys together or neither |
textagent.secret_file |
empty | Runtime file with the review API's bearer secret (the SAME file the agent authenticates against); with the seam on, the Messages tab gains the AI-drafts review panel and the compose Draft-with-AI buttons |
lens.url |
empty = disabled | Browser-facing origin of the pbx-lens analytics app (e.g. https://lens.example): every History row that carries the PBX call uuid gains an "Open in pbx-lens" deep link (new tab). Absolute http(s), no credentials, never a loopback host — the link opens in the operator's browser, so the stack's loopback lensUrl is dead by construction here |
matrix.homeserver |
empty = disabled | Matrix chat-network lane: Client-Server API base (e.g. https://matrix.example.org); all four matrix.* keys are one unit, a half configuration fails the boot |
matrix.user_id |
required | Bot account MXID (@webphone:example.org); v1 carries plaintext DMs only (encrypted and non-DM rooms are skipped with a WARN) |
matrix.access_token |
required | Long-lived token minted once via POST /login; deliver it through environmentFile, never the config file |
matrix.owner |
required | Extension whose Messages tab owns every matrix conversation (threads are owner-scoped everywhere and need their home) |
signal.socket_path |
empty = disabled | Signal lane: the signal-cli daemon's JSON-RPC unix socket (e.g. /run/signal-cli/socket); filesystem permissions are the trust boundary, and all three signal.* keys are one unit |
signal.account |
required | Linked number signal-cli sends from (+49...); the multi-account daemon needs it to pick the lane |
signal.owner |
required | Extension owning every signal conversation |
signal.attachments_dir |
empty = attachments fenced | signal-cli's received-attachment directory (e.g. /var/lib/signal-cli/attachments, files named by id); set, inbound Signal media lands in Messages like MMS (5/message, 10 MiB each) — empty keeps them skipped loudly. Read-only for webphone; the directory's permissions are the trust boundary |
auth.passkey.rp_id |
empty = disabled | WebAuthn relying-party ID (the registrable domain, e.g. pbx.example.com); setting the passkey keys enables the email-first login — all-or-nothing per validation |
auth.passkey.rp_display_name |
webphone |
Name the browser shows in the passkey prompt |
auth.passkey.rp_origins |
required | Browser-facing origins (https://…); each origin's host must equal rp_id |
auth.passkey.users |
required | Email → {extensions: ["1000"], display_name: "Lars"}: the mapping a verified passkey resolves to (first extension binds the session; every mapped extension's identities number shows in the whoami line) |
auth.passkey.extension_password_files |
required | Extension → runtime file carrying its SIP directory password (single line, read at login time, never cached; empty/missing fails closed) |
auth.users |
empty | Shared email → {extensions: [...], display_name, admin} mapping for EVERY passwordless mode (passkey and OIDC); auth.passkey.users stays supported but the two must agree — one mapping governs both modes. admin: true grants the account the read-only Admin tab (all messages, faxes, calls, users and numbers across every line; resolved per request from the live mapping, so removing the flag + restart revokes live sessions' admin on their next request) |
auth.extension_password_files |
empty | Shared extension → SIP-password file map (folded into the passkey shape); every extension a resolved login can bind needs one |
auth.oauth2.issuer |
empty = disabled | OIDC discovery base URL (bare https, no query/fragment — the iss claim is matched verbatim); any auth.oauth2.* key enables the mode, all-or-nothing per validation |
auth.oauth2.client_id |
webphone |
Registered OIDC client id (confidential client) |
auth.oauth2.client_secret_file |
required | Runtime file holding the client secret (single line, read per exchange so rotation needs no restart; missing/empty fails CLOSED) |
auth.oauth2.redirect_url |
required | Registered callback, absolute https (https://<host>/api/auth/oauth2/callback); must match the IdP registration verbatim |
auth.oauth2.scopes |
[openid email profile] |
OIDC scopes; MUST include openid (without it the IdP returns no id_token) |
auth.oauth2.allowed_groups |
empty | In-app IdP group allowlist; non-empty, every login must carry one of these groups in its claims (fail-closed: no groups claim = denied) — a second gate, not a replacement |
csrf.* matters whenever TLS ends at a proxy: a truthful browser POST
then arrives with Origin: https://host while the listener sees plain
HTTP, and unconfigured the CSRF middleware rejects it as a forged
same-origin attestation (403 on every POST, logins included). The
NixOS module sets both keys when caddy.enable is on.
Example file:
{
"addr": "127.0.0.1:8080",
"data_dir": "/var/lib/webphone",
"sip_domain": "pbx.example.com",
"websocket_path": "/sip",
"phone_api_url": "https://pbx.example.com",
"session_ttl": "168h",
"session_max_ttl": "720h",
"ice_servers": [{ "urls": ["stun:pbx.example.com:3478"] }],
"contacts": [{ "name": "Support", "number": "2000" }],
"identities": { "1001": "+49 30 12345678" },
"gateway": {
"mode": "webhook",
"webhook_url": "http://127.0.0.1:8090",
"webhook_secret": "long-random-string"
},
"csrf": {
"trusted_proxies": ["127.0.0.1"],
"trusted_origins": ["https://pbx.example.com"]
},
"auth": {
"passkey": {
"rp_id": "pbx.example.com",
"rp_origins": ["https://pbx.example.com"],
"users": {
"[email protected]": { "extensions": ["1000"], "display_name": "Lars" }
},
"extension_password_files": {
"1000": "/var/lib/telephony-secrets/ext_1000"
}
}
}
}History answers "what happened"; Reports answers "what is this adding
up to". It is a pure projection over the same call records the History
tab lists (GET /history on the operator phone API, one page of up to
500 records), folded by internal/reports: total talk time, call counts
split by direction (in/out) and outcome (answered/missed — two
independent axes, so an outbound call that never connected is neither),
the per-day ladder, the busiest hours, and the contacts that consumed
the most time. Top contacts are named through the CRM when the
integration is configured.
Nothing is stored: the numbers are reproducible from the same records, which is why the tab needs no read model and no rebuild step. Calls whose start timestamp cannot be parsed still count in the totals and the contact ranking and are reported as "records without a readable timestamp", so the time ladders are never silently short.
Set reports.weekly_talk_budget (e.g. 10h) to get the feedback a goal
gives: the week's talk time against the budget, flagged when the week
overspends instead of merely clamping the bar.
With crm.url + crm.token configured, the webphone talks to a
Ledger CRM instance's machine API (the
CRM must run with -api-token <same-token>):
- Caller names: numbers rendered in History, Messages, Fax and Voicemail are resolved against the CRM's contacts (matched by digits, tolerant of trunk-prefix and country-code variants); matches render the contact name, everything else stays the raw number. Lookups are cached in-process (6 h, misses 5 min) and every failure degrades to the raw number — the phone never depends on the CRM.
- Call journal: after every call the island reports the outcome to
POST /api/calls(session-gated); the server journals it on the matching CRM contact (call_logged: "Incoming call from +49… (2m 03s — answered)"). Unknown numbers are deliberately NOT logged — the integration never mints contacts. - Deep links (
crm.contact_url): a resolved caller's name becomes a link into the CRM's own contact page, opened in a new tab so the SIP island is never unloaded. Unset = plain names, byte-identical to a deployment without links; a number with no CRM match stays raw text. - Live call context (
GET /partials/live-context): while a call is up, the slot under the island shows who is on the line and the same outstanding-work line the conversation strip renders — company, open deals, the next follow-up, the last touch. The shell asks once per remote and empties the slot when the last call ends; every degraded answer (seam off, unknown number, CRM down or without the product) is an EMPTY body, so the slot never holds an empty shell, a spinner or an error. Session-gated: the answer is resolved with the server's CRM token, so it is never an anonymous enumeration surface for contact names. - Contact context (
GET /api/contacts/{id}/contexton the CRM): opening a conversation with a known contact shows one quiet line of what is outstanding, their company, the deals in flight with values, the open follow-up count with the next one due, and the last touch. Fetched for that ONE contact, cached two minutes, and silently absent when the CRM does not publish it or cannot be reached. Lists never fetch context (they show identity only), because N contacts of facts per page is a stampede for data nobody reads at list density.
The CRM owns the contact, the phone owns the conversation: webphone stores no CRM records (the in-process cache is a render-time memo, not a replica), never creates contacts, and renders each surface exactly as well as before when the CRM is unreachable.
- Private CA (
crm.ca_file): a CRM behind a certificate from a private authority (the usual*.cloudvhost) needs that CA to be trusted. Pointingcrm.ca_fileat the CA bundle extends the trust store for THIS client only — the webphone's other outbound TLS (the OIDC issuer, the Paperless archive, the ASR provider) keeps the system roots untouched, which host-widesecurity.pkior a process-wideSSL_CERT_FILEcannot promise. The bundle is additive (system roots stay valid), read and parsed at boot, and a path that is missing or certificate-free refuses the boot withcrm.ca_file.
Enable it on both sides: webphone gets crm.url + crm.token, the CRM
gets -api-token <same value> (its machine API is unmounted without
that flag). The NixOS module wires all three (plus crm.caFile) through
services.telephony.webphone.crm.
With paperless.url + paperless.token configured, every INBOUND fax
is additionally filed into a Paperless-ngx instance (the storage truth
stays webphone's blob store — Paperless is a downstream copy):
each document uploads tagged fax, typed Fax, titled
Fax from <number> <date>, and carries the webphone fax id in the
webphone-fax-id custom field (the provenance link back). A server-side
content-hash duplicate refusal is inert — Paperless keeps one copy.
Archiving is fire-and-forget after the fax is persisted: a slow or dead
Paperless never delays or fails a fax, and failures only WARN in the
log. Outbound faxes are not archived (v1 scope).
Fax is the one product area whose code can be complete while the deployment has nothing behind it, so the deployment declares its lanes and the UI obeys:
fax.send(defaulttrue) — an outbound provider accepts/faxin webhook mode. A Telnyx DID assigned to a SIP/voice connection cannot also be a Programmable Fax number (a number binds to one connection), so enabling outbound fax via Telnyx means a Telnyx Fax Application plus a fax-enabled number — or a bridge that implements/fax.fax.receive(defaulttrue) — a fax number is routed to the PBX (FreeSWITCHrxfax+ the stack's fax feed posting to/hooks/fax). That needs its OWN DID; the voice trunk's number carries no fax.
With a flag false the Fax tab keeps the stored history and document
links, drops the affordance it cannot honour, and states the missing
half in place; Settings grows a fax row naming it. Both false renders
one combined "Fax is not available on this server" notice. Misconfigured
the other way round — flags on, provider absent — is visible as a
failed job carrying the provider's own reason, never as a fake success
(only the loopback dev gateway resolves instantly, and that mode is
documented as a demo).
/login is the front door in every mode. An anonymous visit to the
app root redirects there (303); the page carries the extension +
password form in EVERY deployment — bare when the passkey identity
layer is off (the primary method), one "Use extension and password
instead" disclosure down when it is on (the break-glass lifeline: the
phone never depends on the IdP or on a passkey being present) — plus a
"Continue to Pocket ID" door when the OIDC seam is configured. The
form POSTs /api/session (which directory-verifies before minting;
loopback dev skips the verification) and lands back on the app, where
the phone REGISTERs — the same resume path every sign-in method takes.
The remembered extension (remember extension on this device) stores
the extension under localStorage — never the password. A live session
visiting /login bounces home (303 /). The page renders styled
without the shell (its own Tailwind build, /assets/login.css) and is
the single HTML surface with a per-request nonce CSP; everything else
keeps the strict no-inline-scripts policy.
With auth.passkey.* configured (OFF by default — the ceremony UI
joins the /login front door only when on), the webphone embeds the
cqrs-htmx/usermgmt identity layer in-process and offers email + passkey
sign-in on /login (the cqrs-htmx loginpage library page, pin
loginpage/v4 v4.18.0 — the release that made Service optional and
added the consumer sign-in section webphone hosts the extension form
in). The page carries the ceremony UI only — no registration
(enrollment stays CLI-token-gated at /enroll) and no library OAuth2
buttons (the Pocket ID door inside the same page's sign-in section is
the one SSO entry). Its theme script follows the OS
prefers-color-scheme — a user who forced a theme in the shell may see
the OS theme on /login.
- Login order is inverted:
POST /api/auth/webauthn/login/finish(the usermgmt-canonical path the library's embedded JS posts to; begin answers{options, session_key}identically) verifies the ceremony, resolves the configured email→extension mapping (auth.passkey.users), sources the extension's SIP directory password fromauth.passkey.extension_password_files(read per login, never cached — empty/missing fails CLOSED), verifies it against the PBX directory, and only then mints the session; the browser REGISTERs afterwards. The response is the typed session-identity shape (extension,did,display_name,numbers, plus exactly one credential field, served no-store) — the same structGET /api/sessionanswers on resume. With SIP credential brokering on (sip.credential_secret), that field is the session-derived REGISTER credential: the directory password never reaches the browser (the file read stays, feeding the/phone-apiproxy server-side). Without brokering, the legacy wire keeps the file-sourced password byte-identical. After finish the library page redirects to/, where the island's existing boot probe (GET /api/session) resumes the session and REGISTERs — the same proven mechanism the SSO lane uses, no new session-adoption path. - Enrollment is CLI-minted:
webphone -enroll-passkey <email>prints a one-time link (/enroll?token=…; the token is stored sha256-hashed, expires after 15 minutes, and burns at first verify — unknown, expired and used tokens all answer the same 503, so the page never leaks token state). The standalone/enrollpage runs verify → WebAuthn registration → finish without the island runtime. - Health: with the mode on,
/healthzgains auserauthleg probing the identity layer's ownusermgmt.db(kept separate fromwebphone.dbon purpose); a 503 naminguserauthmeans that database is the broken leg. - Anti-enumeration: unknown emails and credential-less accounts
answer the same 401; the login flood bucket is shared with the
extension login; operator-fixable rejections answer 503 with the
honest
userauth.*code in the journal (full table: docs/error-contract.md).
With auth.oauth2.* configured (OFF by default — the Pocket ID door on
the login page appears only when on), GET /api/auth/oauth2/begin
mints state + nonce + PKCE verifier
into short-lived path-scoped cookies and redirects to the IdP;
GET /api/auth/oauth2/callback verifies them, exchanges the code,
verifies the ID token (signature, issuer, audience, expiry, nonce), maps
the verified email through the SAME auth.users mapping the passkey
mode uses, verifies the sourced SIP directory password against the PBX
and mints the one webphone session. OIDC tokens are used once and never
reach the browser; discovery is lazy inside the app, so a dead IdP costs
a login (the callback redirects to /login?sso_error=<code> and the
login page renders the honest sentence in its alert) and never the boot.
The extension login stays one disclosure away on the same page, so the
phone is never locked by an IdP outage.
NixOS module: services.webphone.oauth2.* is the typed front. The
client secret is handed to systemd via LoadCredential — systemd copies
the operator's file into the unit's private credential directory (0400,
owned by the service user) at every start, and the app reads that copy,
so no host-side group grant is needed and a missing source file fails the
UNIT START instead of the first login. systemd snapshots the file at unit
start, so rotate the secret with a systemctl restart webphone. With
caddy.enable set, the callback and the passkey rp_id/rp_origins are
derived from caddy.hostName, so the vhost and the IdP registration
cannot drift.
Every half configuration fails at EVAL time (nixos-rebuild), naming
the missing key: issuer, secret file, openid scope, callback, the
shared auth.users mapping, or a mapped extension's SIP-password file.
Declaring the OIDC client shape in BOTH the typed options and raw
settings.auth.oauth2 is an eval conflict — one home per fact.
With sip.credential_secret (or sip.credential_secret_file) set, the
island no longer receives the directory password: GET /api/session and
the passkey finish answer a session-derived credential
(base64url(HMAC-SHA256(secret, session_token)), served no-store), the
island REGISTERs with it, and FreeSWITCH validates it dynamically via
the stack's directory bridge, which reads
GET /internal/directory/{extension} (loopback + Bearer — the same
secret; the derived credentials of every LIVE session; logout kills the
credential at the next REGISTER). Zero config keeps the historical
password-wire behavior byte-identical. Full contract: the error table in
docs/error-contract.md (the internal-directory
seam rows + the passkey revoke rows); the consuming stack side — the
bridge, the fail-closed posture, and the <2-minute rollback drill — is
documented in nix-international-telephony's docs/ops-runbook.md
§ "Dynamic SIP directory".
The server renders GET /config.js from its own config — same contract
the static-site era consumed:
window.PBX_CONFIG = {
sipDomain: "pbx.example.com",
websocketPath: "/sip",
iceServers: [{ urls: ["stun:pbx.example.com:3478"] }],
phoneApi: false,
contacts: [{ name: "Support", number: "2000" }],
};The server calls these with the signed-in extension's credentials (Basic
auth), both directly and through the transparent /phone-api/* proxy the
island uses:
| Method & path | Response |
|---|---|
GET /phone-api/history?limit=N |
{"entries":[{caller_id_number, destination_number, start, billsec, …}]} |
GET /phone-api/voicemail/{ext}/summary |
{"new":1,"old":0} |
GET /phone-api/voicemail/{ext}/messages |
{"messages":[{uuid, cid_number, cid_name, seconds, created, read, audio_url}]} |
DELETE /phone-api/voicemail/{ext}/messages/{uuid} |
(2xx) |
The webphone POSTs multipart/form-data to {webhook_url}/message and
{webhook_url}/fax with Authorization: Bearer {webhook_secret}:
- fields:
kind(message|fax),owner(sending extension),to,body(messages) - files: one part per attachment (
attachment) or the PDF (document)
The provider answers 2xx with {"provider_ref": "..."} — that reference
is what later status callbacks quote. Anything else marks the message/fax
failed.
All hooks require Authorization: Bearer {webhook_secret} and are
closed (503) when no secret is configured.
POST /hooks/message {"owner":"1001","from":"+441632960961","body":"hi",
"attachments":[{"name":"pic.jpg","mime_type":"image/jpeg","data_base64":"…"}]}
POST /hooks/fax {"owner":"1001","from":"+441700000000","pages":2,
"provider_ref":"gw-123","pdf_base64":"…"}
POST /hooks/fax/status {"provider_ref":"gw-123","status":"transmitted|failed","pages":2,"error":"…"}
POST /hooks/message/status {"provider_ref":"gw-123","status":"delivered|failed","error":"…"}
Providers may retry status callbacks: replays are deduped and answer
202 Accepted inertly (only successes are recorded, so failures stay
retryable).
Any component that can POST JSON bridges the PBX; the payloads above are the whole contract. A minimal two-way demo bridge (receives mod_sms traffic, forwards as SMS; receives the webphone's multipart, hands to the PBX) fits in ~30 lines of Python — this shape:
# inbound: chatplan/lua/HTTP-hook on the PBX side calls
POST http://webphone:8080/hooks/message
{"owner": "$to_ext", "from": "$from", "body": "$body"}
# outbound: receive the webphone's multipart at {bridge}/message and
# feed it into FreeSWITCH (event socket, mod_sms, or a carrier API),
# then answer {"provider_ref": "<id>"} and later call
# /hooks/fax/status or /hooks/message/status with that id.With asr.url set, every audio surface can be transcribed through one
session-gated endpoint. POST /api/transcribe takes the raw audio bytes
(any audio/* Content-Type) — optionally ?filename= and ?lang= — and
forwards them as a multipart file to the provider's OpenAI-compatible
/v1/audio/transcriptions, returning {"text": "…"}. The provider is any
OpenAI-compatible server; a disabled seam answers 404 and the UI hides
every affordance.
Where the audio goes: transcription POSTs raw caller audio to the configured provider — a loopback/self-hosted one keeps caller audio on your infrastructure; a hosted provider means caller audio leaves the box on every segment and every clip transcribed (see the provider choice below before enabling this on a production PBX).
- Live calls: the island mixes the remote party and the operator's own
voice through an
AudioContext(closed on stop) and records 4-second segments, appending each segment's text into the call card. Capture pauses while the call is on hold (no audio flows — no silence hallucinations) and each segment carries the UI language as the provider'slanguagehint. Text arrives in ~4-second steps — segmented near-live by design, not word-by-word streaming: the OpenAI-compatible wire takes whole files, and streaming one long file would need a stateful protocol the self-hosted providers do not share. - Voicemail & MMS audio: the Voicemail and Messages tabs render a transcribe button next to each playable clip (one delegated shell.js handler fetches the audio and posts it).
- Auto-start: with the seam on, transcription begins by itself — live capture starts when a call connects, and every rendered voicemail/MMS clip transcribes once per page life (morph re-renders never re-POST). The buttons stay as manual re-runs.
- Persistence: each live-call segment is also appended (fire-and-forget,
POST /api/transcripts) to an owner-scoped SQLite table (schema v3, capped at 5000 segments per extension AND 1500 per call — a long call can never eat the whole budget). Near-silent segments are never sent (a client-side RMS guard spares the provider hallucinations). The History tab renders the newest transcribed calls as their own "Call transcripts" section — deliberately NOT joined onto the CDR rows, which carry no call uuid to correlate with. - Findability & portability: the History search box (
?q=) also searches transcript text (matching lines, owner-scoped, with a hint saying so); every transcript section carries copy-to-clipboard (call card and History); the Settings export zip includes atranscripts.jsonleg; and Settings names the provider kind and model next to the on/off state.
Choosing a provider (2026 recommendation): run ASR LOCAL, not hosted. Call audio of real people is GDPR personal data; the US-inference APIs (OpenAI, Groq, AssemblyAI) offer no EU residency. The stack already keeps audio on your infrastructure — keep transcription there too.
- Primary: Speaches (ex
faster-whisper-server) with
large-v3-turbo— first-class OpenAI-compatible/v1/audio/transcriptions, ships a flake.nix, CPU-viable for 4-second segments, MIT. Setasr.urlto its base URL; no token needed. - Lightweight fallback: whisper.cpp's
whisper-serverwith a quantizedlarge-v3-turbo(single static binary; its endpoint is/inference, so rewrite the path in the reverse proxy). - Hosted (cloud) option: Google Cloud Speech-to-Text V2 — the one hosted API that clears the GDPR bar AND the cost bar. See the recipe below.
- Pass an explicit language where you can (
?lang=de— auto-detect misfires DE↔EN on short phone chunks); the island does this automatically from the session language.
Google Cloud STT v2 recipe (asr.provider: google): EU-resident by
construction (regional endpoint europe-west3 / Frankfurt — audio stays
in continental Europe, and speech logging is off by default), and V2 has
NO per-request minimum: billed per second rounded up to 1 s, so the
interactive 4-second island segments cost their actual duration
(telephony model: ~$0.96/audio-hour; standard recognition, not the
24-hour-SLA Dynamic Batch tier — that one is for offline backfills only).
# config: google kind needs a project id; token is an API key with the
# Speech-to-Text API enabled; location defaults to europe-west3.
WEBPHONE_ASR__PROVIDER=google
WEBPHONE_ASR__PROJECT=my-gcp-project
WEBPHONE_ASR__TOKEN=AIza… # x-goog-api-key
WEBPHONE_ASR__MODEL=telephony # default; 8 kHz-tuned for phone audio
WEBPHONE_ASR__LANGUAGE=de-DE # fallback for untagged segmentsOne-time Google-side setup: create (or pick) a project, enable the
Cloud Speech-to-Text API, create an API key (restrict it to the
Speech-to-Text API), and accept the Data Processing Terms/DPA for that
project. The wire is spoken directly (JSON recognize with base64 audio —
no adapter process); asr.url stays empty and the regional endpoint is
derived from the location. An explicit asr.url overrides the endpoint
(tests, or a local proxy that injects the credential).
Signed-in extensions get a per-extension feed at GET /events (HTMX SSE
extension). Events: threads (message list rows), thread (open
transcript bubbles), fax (fax list rows) — each carries an
innerHTML-safe fragment — and voicemail, a payload-less nudge that makes
an open voicemail tab re-fetch itself. The island's voicemail polls are
forwarded as nudges too, so finishing a call refreshes the tab.
The binary owns HTTP on addr; TLS, the WSS /sip proxy to the PBX, and
process supervision belong to the serving stack
(nix-international-telephony
today) or any reverse proxy in front:
handle /sip { # WebSocket → PBX sofia wss-binding
reverse_proxy https://pbx.internal:7443
}
handle /events { # SSE: unbuffered
reverse_proxy 127.0.0.1:8080 {
flush_interval -1
}
}
handle {
reverse_proxy 127.0.0.1:8080
}
request_body {
max_size 64MB # attachments (≤5×10 MiB) + PDFs (≤20 MiB)
}The state directory (data_dir, default /var/lib/webphone) holds
everything: webphone.db (SQLite: the remaining hand-ladder tables —
sessions and the transitional import markers), system.db (the
command/event journal: every domain aggregate's streams, projections,
checkpoints, dedup windows and the dead-letter store — the user-data
home since the SUPERB phases), and files/ (the content-addressed
blob tree for attachments and fax documents). Back up all of them
together. (readmodels.db is retired: deployments upgrading through
v2.10+ had their engine-side history imported into the journal once;
the leftover file is an inert orphan, is no longer backed up, and is
safe to delete — nothing reads it, on any version since v2.12.)
Online, per snapshot (no downtime — what services.webphone.backup.*
in the NixOS module wires as a daily timer):
sqlite3 /var/lib/webphone/webphone.db ".backup '/var/lib/webphone-backup/webphone.db'"
sqlite3 /var/lib/webphone/system.db ".backup '/var/lib/webphone-backup/system.db'"
rsync -a --delete /var/lib/webphone/files/ /var/lib/webphone-backup/files/Restore (drill-verified cold path — scripts/webphone-backup-drill.py
boots a real binary, loads a webhook message with a binary attachment,
tars the data dir, restores it to scratch and pulls the attachment back
byte-identical). Re-run the drill any time the store layout changes or
after an upgrade:
python3 scripts/webphone-backup-drill.py # end-to-end restore drill (boots a throwaway binary + dirs)- stop the service,
- copy
webphone.db,system.dbandfiles/back into the data directory, - start the service — tab sessions live in the SQLite database, so the restored session rows keep working (signed-in browsers stay signed in); the journal replays its projections on boot; everything else renders straight from the restored store.
Dated history (point-in-time restore): set
services.webphone.backup.retentionDays (default null = single
latest snapshot, the historical behavior). When set — e.g. 30 — each
daily run additionally writes destDir/snapshots/<date>/ (db + blob
tree, unchanged blobs hardlinked against the previous snapshot, so a
month of history typically costs little more than one snapshot) and
deletes snapshot directories older than the given days. Restore from a
specific day: stop the service, copy snapshots/<date>/webphone.db,
snapshots/<date>/system.db and snapshots/<date>/files/ back into
the data directory, start it.
Keep a copy OFF the machine: the snapshot directory (destDir) lives on
the same host as the service, so it is not a backup yet — a disk loss
takes both. Point an off-machine restic/borg repository (or any remote
rsync job) at destDir; the files are plain sqlite + blobs, so any
file-level backup tool handles them.
Every failure the server mints carries a stable <seam>.<op> code. Feed
the code (or the whole journal line) to the router and get the context
bundle — seam files, contract row, family-test pin, prior history:
python3 scripts/error-context.py "send failed: [gateway.http] provider 502"An event that fails one projection three times in a row (a payload a fold
cannot decode, a handler bug) is parked in the dead-letter table
(projection_dead_letters in system.db) and the worker moves on — the
app keeps serving, but that projection is silently missing data from that
event onward. Two journal lines are the operator surface:
WARN projection dead-lettered an event projection=... event_type=... error=... hint="fix the handler, then replay; the entry persists in system.db (projection_dead_letters)"
WARN projection dead-letter queue carries poison events from a previous run count=N oldest_age=2hThe first fires at the moment a projection rejects an event; the second
fires at every boot while entries remain (they survive restarts). See the
projection_dead_letters table for the full entries; entries carry the
original event for replay once the handler is fixed.
Symptom: every browser login (and every form POST) returns 403 once the
app is served behind a TLS-terminating proxy, while calls keep working and
/healthz is green. The server log names the cause exactly:
WARN httputil: CSRF rejected request with forged same-origin attestation method=POST path=/api/session origin=https://pbx.example.orgWhy: the browser truthfully sends Origin: https://… while the listener
sees plain HTTP; unless the proxy is trusted, that reads as a forged
attestation.
Fix: declare the fronting shape so the proxy's X-Forwarded-Proto is
believed and the https origin is trusted:
{
"csrf": {
"trusted_proxies": ["127.0.0.1"],
"trusted_origins": ["https://pbx.example.org"]
}
}The NixOS module ships exactly these defaults when caddy.enable is set
(derived from caddy.hostName); a startup log line csrf fronting trustedProxies=… trustedOrigins=… shows the effective shape at boot.
caddy.hsts.enable (default off) adds Strict-Transport-Security to
the generated vhost; keep it off until the deployment is genuinely
https-only — HSTS pins browsers to https for maxAge (default 2 years).
The flake ships nixosModules.default so the binary and its deployment
shape stay in sync:
inputs.webphone.nixosModules.default
services.webphone = {
enable = true;
package = inputs.webphone.packages."${pkgs.system}".webphone;
settings = {
sip_domain = "pbx.example.com";
phone_api_url = "https://pbx.example.com";
ice_servers = [{ urls = [ "stun:pbx.example.com:3478" ]; }];
};
environmentFile = "/run/secrets/webphone-env"; # WEBPHONE_GATEWAY__WEBHOOK_SECRET
caddy = {
enable = true;
hostName = "phone.example.org";
sipUpstream = "https://pbx.example.com:7443"; # bridge the SIP WebSocket to the PBX
};
};settings is the same JSON config the binary reads (rendered to a
WEBPHONE_CONFIG file); secrets belong in environmentFile, not the
world-readable config. The generated Caddy vhost terminates TLS
(automatic HTTPS) and proxies the app; with caddy.sipUpstream set it
also bridges the SIP WebSocket path to the PBX — without the bridge
the deployment must route that path itself. A flake check evaluates
the module, so nix flake check catches breakage, and a kvm-gated VM
test (checks.x86_64-linux.webphone-backup) proves the backup story
end to end.
Module options beyond enable/package/settings:
| Option | Default | Meaning |
|---|---|---|
dataDir |
/var/lib/webphone |
State directory (must stay under /var/lib/ — asserted) |
environmentFile |
none | systemd EnvironmentFile for secrets (WEBPHONE_GATEWAY__WEBHOOK_SECRET) |
environmentFiles |
[] |
Additional EnvironmentFiles loaded after environmentFile (later files win on dup keys) |
memoryMax |
uncapped | systemd MemoryMax for the service |
csrf.trustedProxies |
[] |
Typed front for settings.csrf.trusted_proxies; beats the caddy-derived default when set |
csrf.trustedOrigins |
[] |
Typed front for settings.csrf.trusted_origins; beats the caddy-derived default when set |
serverTiming.enable |
false |
Server-Timing response headers (sets WEBPHONE_DEBUG_TIMING=1) |
backup.enable |
false |
Daily online snapshot timer (sqlite .backup + blob rsync) |
backup.destDir |
/var/lib/webphone-backup |
Snapshot destination |
backup.calendar |
*-*-* 04:30:00 |
Timer schedule |
backup.retentionDays |
null |
When set (e.g. 30): daily dated snapshots/<date>/ history + prune older than N days |
caddy.enable / caddy.hostName |
off | Generated TLS vhost proxying the app (derives the csrf fronting defaults) |
caddy.sipUpstream |
null |
Bridge the SIP WebSocket path to the PBX (e.g. https://pbx:7443); null = deployment routes it |
caddy.hsts.enable / maxAge |
off / 2y | Strict-Transport-Security on the generated vhost |
oauth2.enable |
false |
Typed front for settings.auth.oauth2: OIDC/SSO login (also derives passkey rp_id/rp_origins) |
oauth2.issuer |
null |
IdP discovery base URL, bare https (required when enabled) |
oauth2.clientId |
webphone |
Registered OIDC client id |
oauth2.clientSecretFile |
null |
HOST path of the client secret — copied by systemd LoadCredential; the app reads the unit copy |
oauth2.redirectUrl |
null |
Callback; derived from caddy.hostName when null (explicit behind an external front) |
oauth2.scopes |
[openid email profile] |
OIDC scopes; must include openid |
oauth2.allowedGroups |
[] |
IdP group allowlist (non-empty = fail-closed admission gate) |
Health probes behind the vhost: /healthz (readiness), /livez
(process liveness) and /startupz (startup completion) ride the same
reverse proxy as the app. All three are session-free GETs whose bodies
name checks and statuses only, never secrets — safe to expose or
scrape. Fence a fleet health hub the Caddy way with a remote_ip
matcher in the vhost's extraConfig instead of per-location blocks;
/metrics (Prometheus text: stored-object counts, request-duration
histogram and status-class counter — aggregates only, never per-extension
data or request paths) fences the same way.
Readiness vs systemd: the service unit stays Type=simple by
DELIBERATE decision — the module does NOT wire Type=notify.
sd_notify would fire when the listener binds, which is a WEAKER
readiness signal than /startupz (503 until sqlite ping + blob-dir
write both first-pass, then latched 200), and a systemd watchdog
restart would kill live calls on a transient stall. Consumers that
need ordered startup should poll /startupz (or front it with a
one-shot ExecStart=curl --retry wait unit and After= ordering);
ongoing health belongs to /healthz, liveness to /livez. When the
boot itself fails, the binary prints a five-part operator report
(WHAT / REASSURE / WHY / FIX / ESCAPE, exit 1; a panic exits 2) —
the class table and fix hints live in
docs/error-contract.md § "Boot surface".
nix develop # Go, templ, golangci-lint, esbuild, …
templ generate ./internal/web/views/ # after editing .templ files
go test ./... # json/v2 stable since Go 1.27
buildflow # the quality gate (format, lint, audit, checks)
nix flake check # package build + tests in the sandbox + treefmt + island gates
tsc -p . --noEmit # the island/browser type gate (inside nix develop)
nix build .#webphone --system aarch64-linux # cross-builds (pure Go)
./update.sh [version] # repin vendored sip.js (esbuild IIFE bundle)The flake is a slim entry point; its packages, checks (incl. the KVM
backup-VM test), NixOS module checks, devShell and formatting live as
flake-parts modules under nix/.
The island sources live in internal/web/assets/island/app/ (ES modules,
served as-is, CSP-strict); their DOM element ids are a published contract
(see AGENTS.md) driven by the consuming stack's browser E2E.
Every served JavaScript file — the island modules, the shell glue, the theme
preload and the enrolment page, 26 of them — is type-checked by
tsconfig.json under --checkJs --strict: tsc -p . --noEmit must exit 0,
and nix flake check runs the same project as island-typecheck. The only
carve-out is the vendored sip.js bundle. Because the served tree is the
source tree (//go:embed all:island), no @ts-check pragma is allowed — it
would change a served byte; the project's include does the same job. Only
tsc counts: an editor's bundled compiler is a different version and will
report errors that do not exist. How to annotate a new file (the three
patterns, the two forbidden escapes): docs/type-gate.md.
Nothing here runs on make: the flake is the task runner. nix flake check
is the whole gate suite (build, tests, treefmt, island JS/lint/type checks,
the module eval), nix fmt the formatter, buildflow the lint/audit pass,
and nix develop prints the four commands a contributor needs on entry.
MIT — see LICENSE. The vendored sip.js keeps its own license
notice (internal/web/assets/vendor/sip.min.js.LEGAL.txt).