Skip to main content

Connect browsers to devices via WebRTC

Project description

BitBang Python

Tests PyPI Python License

Access your local web server from anywhere -- no account, no subscription, no cloud in the middle. BitBang uses WebRTC to connect browsers directly to your device, peer-to-peer.

This is part of the BitBang project.

Quick demo

Install:

pip install bitbang              # Linux / macOS
python -m pip install bitbang    # Windows (or any platform) 

Quick test:

bitbang-fileshare ~/Downloads            # Linux / macOS
python -m bitbang fileshare ~/Downloads  # Windows (or any platform)

bitbang-fileshare

Scan the QR code, which contains the BitBang URL. Anyone with the URL can browse and download files directly from your machine, or they can upload files to the specified directory. Note, you can verify it works outside your local network, by scanning the QR code from a phone on cellular (turn off WiFi).

Flask / FastAPI integration (or any WSGI / ASGI web framework)

Take an existing Flask or FastAPI app and add remote access.

# Flask 
from bitbang import BitBangWSGI
...
app = Flask(__name__)
adapter = BitBangWSGI(app)
adapter.run()  # Prints QR code and public URL
# FastAPI 
from bitbang import BitBangASGI
...
app = FastAPI()
adapter = BitBangASGI(app)
adapter.run() # Prints QR code and public URL

Comparison

ngrok Cloudflare Tunnel Tailscale BitBang
Account required Yes Yes Yes No
Free tunnels 1 Unlimited Unlimited Unlimited
Data path Their servers Their servers P2P P2P
Viewer needs install No No Yes No
Configuration CLI flags Config file + DNS Dashboard None

BitBang's data path is direct between peers. The signaling server brokers the initial connection, then steps aside.


Fileshare

Fileshare allows you to easily/quickly share local files without uploading them to a third-party service. It's intended to be an example of a simple (yet useful!) BitBang application. It's just a straightforward Flask app.

bitbang-fileshare big_sourcetree.tar.gz       # Share a single file
bitbang-fileshare ~/Documents/project         # Share a directory (uploads enabled)
python -m bitbang fileshare c:\ide\files      # Windows

Files transfer directly from your machine to the recipient. The recipient can also upload files to your machine.

Webcam

The Webcam app streams video from your webcam to a browser using WebRTC media channels and BitBang. It can be used as an easy-to-setup monitoring/security camera using your laptop, for example.

bitbang-webcam                  # Linux / macOS
python -m bitbang webcam        # Windows (or any platform)

Examples

The examples/ directory contains two simple examples which show how to integrate BitBang into your current Python web frameworks:

cd examples/simple_fastapi && python3 app.py
cd examples/simple_flask && python3 app.py

Python API

These options are available from the BitBang constructor (same options for BitBangASGI):

adapter = BitBangWSGI(app,
    program_name='BitBang',    # Identity name, shows in browser title
    server='bitba.ng',         # Signaling server (default: bitba.ng)
    ephemeral=False,           # Use a temporary identity (not saved to disk)
    identity_path=None,        # Use a specific identity file
    regenerate=False,          # Delete and regenerate identity
    debug=False,               # Verbose logging + browser debug UI (?debug)
    pin=None,                  # PIN string to protect access
    ice_servers=None,          # Custom TURN server config
)

For per-path custom auth, register a PIN checker as a decorator:

adapter = BitBangWSGI(app)

@adapter.pin_callback
def check(path, pin):
    """Return True if `pin` (may be '') is acceptable for `path`."""
    if path.startswith('/admin'):
        return pin == '1234'
    return True   # everything else is open

The decorator takes precedence over the simple pin= arg. Called once with pin='' to ask "is a PIN required for this path?", then with the entered PIN to validate.

If your app uses argparse, add_bitbang_args and bitbang_kwargs can wire up the standard CLI flags for you:

from bitbang.adapter import BitBangWSGI, add_bitbang_args, bitbang_kwargs

parser = argparse.ArgumentParser()
parser.add_argument('path')
add_bitbang_args(parser)
args = parser.parse_args()

adapter = BitBangWSGI(app, **bitbang_kwargs(args, program_name='myapp'))

These options appear like this on the command line:

--ephemeral              Use a temporary identity
--identity PATH          Use a specific identity file
--regenerate             Delete and regenerate identity
--server HOST            Signaling server hostname 
--turn-url URL           TURN server URL (e.g. turn:myserver.com:3478)
--turn-user USER         TURN server username
--turn-credential PASS   TURN server credential
--pin PIN                PIN to protect access
--debug                  Enable verbose logging and browser debug UI

When --debug is enabled, the printed URL includes ?debug, which activates a browser-side debug UI showing connection steps (connecting to server, waiting for device, establishing peer connection). Without it, the browser shows a simple "Loading..." while connecting.

Each app gets its own persistent RSA keypair and URL, stored in ~/.bitbang/<program_name>/identity.pem. This means the URL for each BitBang program stays the same across restarts. Use --regenerate to get a new URL, or --ephemeral for a one-time session.

bitba.ng provides a TURN server when a peer-to-peer connection isn't possible, but you can provide your own TURN server if you prefer via the command-line options or through the constructor by specifying ice_servers in browser-native WebRTC format. The defaults should work fine though, so you shouldn't need to provide these.


Background

The Internet is often thought of as a fully connected network -- every machine is accessible from every other machine. But there are rules governing accessibility on the Internet...

Rules of Internet Accessibility

  1. Machines on the Internet are accessible by other machines on the Internet -- and by machines on your local network.
  2. Machines on your local network are only accessible by other machines on your local network.

Because of rule 2, machines on your local network aren't reachable from outside -- nor are the resources they hold: files, cameras, sensors, compute, or the web app you're currently developing. Cloud services exist to fill this gap: Dropbox for files, AWS IoT for sensors, Tailscale for compute, and ngrok for web apps -- among others. These services apply rule 1, but each comes with the friction of account creation, fees, and your data living on someone else's server.

BitBang connects a browser directly to any machine on your local network, from anywhere on the Internet. No cloud intermediary, no account, no third party in the middle. It uses a novel application of the peer-to-peer technology WebRTC.

WebRTC?

WebRTC is the behind-the-scenes technology that makes Zoom and Google Meet video conferencing possible. WebRTC offers the highest bandwidth and lowest latency possible, which is good when you're streaming live video, or practically anything else. It's mature, well-tested, and has ubiquitous support across all browsers. In addition to delivering low-latency media, it can also deliver raw data over "data channels", which is what BitBang uses for proxying HTML and WebSockets.

How it works

Browsers normally connect to web servers over a TCP socket. BitBang replaces this with a WebRTC data channel.

BitBang Python Block Diagram

The signaling server (bitba.ng) brokers the WebRTC handshake, then has no further involvement and never sees application data.

Signaling server

The signaling server source is available here. It:

  1. Serves the BitBang browser runtime
  2. Authenticates connecting devices via RSA challenge
  3. Maintains WebSocket connections to active devices
  4. Brokers ICE candidate and SDP exchange between browsers and devices

After the P2P connection is established, the signaling server is not involved. We are providing a signaling server for testing, etc. at https://bitba.ng. It mostly brokers connections, so it doesn't need many resources.

Security

WebRTC mandates encryption:

  • Data channels: DTLS 1.2+
  • Media streams: SRTP
  • Signaling: HTTPS and WSS

Furthermore, each BitBang "device" generates an RSA keypair. The public key hash becomes its unique 128-bit ID, which is used in its BitBang public URL. A 64-bit access code rides in the URL fragment (after #) so the signaling server — which sees the path but never the fragment — can route connections but cannot initiate them. See SECURITY.md for the full trustless-signaling model.


License

MIT See LICENSE.

Contributing

Issues and PRs are welcome.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

bitbang-0.1.53.tar.gz (71.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

bitbang-0.1.53-py3-none-any.whl (63.6 kB view details)

Uploaded Python 3

File details

Details for the file bitbang-0.1.53.tar.gz.

File metadata

  • Download URL: bitbang-0.1.53.tar.gz
  • Upload date:
  • Size: 71.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for bitbang-0.1.53.tar.gz
Algorithm Hash digest
SHA256 f7af66c750f1e56e72684cea42cbe938bb4c17b9358d2f8522a2ce019128db56
MD5 34f0df2c009c945b2f884eaea74ac390
BLAKE2b-256 ed6c01d9000e61b431d8b2c9c1f9aab0a9fcc29f1696ff2b7878311f04c01015

See more details on using hashes here.

File details

Details for the file bitbang-0.1.53-py3-none-any.whl.

File metadata

  • Download URL: bitbang-0.1.53-py3-none-any.whl
  • Upload date:
  • Size: 63.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for bitbang-0.1.53-py3-none-any.whl
Algorithm Hash digest
SHA256 3daf7c6e440c0adc2317175d4195a9fe2beb091c9b0aa2a43d124a8a17c9c511
MD5 96cfc08dcde059281cf181d24e123d49
BLAKE2b-256 1bd53bf875fb8fc1707d7fc2f9b62435824d37e26a7ede85b4fdfb963641b22e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page