petaledge-bridge 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ https://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ https://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,9 @@
1
+ # What goes into the source distribution (the wheel only ever holds the petaledge_bridge package).
2
+ # The wire protocol document ships with the source; tests, release tooling and build output do not.
3
+ include LICENSE
4
+ include README.md
5
+ include PROTOCOL.md
6
+ prune tests
7
+ prune packaging
8
+ prune build
9
+ prune dist
@@ -0,0 +1,183 @@
1
+ Metadata-Version: 2.4
2
+ Name: petaledge-bridge
3
+ Version: 0.2.0
4
+ Summary: Petal Edge Camera Bridge: relays IP / CCTV cameras on a local network to the Petal Edge Model Playground (outbound only).
5
+ Author: Petal Edge
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://edge.petalsautomation.com
8
+ Project-URL: Documentation, https://edge.petalsautomation.com/docs/
9
+ Keywords: petal edge,cctv,ip camera,rtsp,mjpeg,edge ai,model playground
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: End Users/Desktop
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Operating System :: Microsoft :: Windows
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Multimedia :: Video
24
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: av>=12
29
+ Requires-Dist: numpy>=1.24
30
+ Requires-Dist: pillow>=9.5
31
+ Requires-Dist: websockets>=12
32
+ Requires-Dist: cryptography>=41
33
+ Requires-Dist: keyring>=24
34
+ Provides-Extra: test
35
+ Requires-Dist: pytest; extra == "test"
36
+ Dynamic: license-file
37
+
38
+ # Petal Edge Camera Bridge
39
+
40
+ A small program that runs on a computer on the same network as your IP / CCTV cameras and relays
41
+ their video to your **Model Playground** in Petal Edge, so you can try a model on a live camera.
42
+
43
+ - The bridge reads the camera (RTSP or HTTP MJPEG) on your local network, keeps only the newest
44
+ frame, shrinks it, and sends JPEG frames to Petal Edge over one outbound, encrypted WebSocket.
45
+ - Prediction runs on the Petal Edge server, in your Playground session. The bridge never gets
46
+ the model.
47
+ - It only makes **outbound** connections. It opens no listening port, needs no port forwarding,
48
+ no VPN and no admin rights.
49
+
50
+ The wire protocol is documented in `PROTOCOL.md` in the source distribution.
51
+
52
+ ## Install
53
+
54
+ Python 3.10 or newer.
55
+
56
+ ```bash
57
+ pip install petaledge-bridge
58
+ petaledge-bridge --version
59
+ ```
60
+
61
+ Or, to keep it out of your other Python projects, `pipx install petaledge-bridge`.
62
+
63
+ Dependencies (installed automatically): `av` (PyAV, bundles FFmpeg), `numpy`, `pillow`,
64
+ `websockets`, `cryptography` and `keyring`.
65
+
66
+ ## Pairing
67
+
68
+ 1. In the Model Playground choose the **CCTV** source. The page shows a command like
69
+ `petaledge-bridge connect K7Q4MPX2.AAISEM2EKVTHPCEZVK54ZXPO74 --server https://api.edge.petalsautomation.com`
70
+ 2. Run it on the computer next to your cameras. Spaces, dashes and lower case in the code are fine.
71
+ 3. The bridge prints a **key fingerprint** such as `2E1E·61CE`. Check that the Playground shows
72
+ the same one. If it doesn't, stop and pair again.
73
+ 4. Leave the bridge running. Add cameras in the Playground: the browser encrypts each camera's
74
+ address and password for this bridge only.
75
+
76
+ Later, after a restart: `petaledge-bridge run`.
77
+
78
+ | Command | What it does |
79
+ |---|---|
80
+ | `petaledge-bridge connect <code> [--server URL] [--name NAME] [--allow-public-cameras]` | Pair, save the pairing, then run |
81
+ | `petaledge-bridge run [--allow-public-cameras]` | Reconnect with the saved pairing |
82
+ | `petaledge-bridge status` | Show the saved pairing and its key fingerprint |
83
+ | `petaledge-bridge forget` | Delete the saved pairing (and any saved camera passwords) from this computer |
84
+ | `petaledge-bridge cameras` | List the cameras whose passwords this bridge keeps; `--forget <id>` or `--forget-all` removes them |
85
+
86
+ Add `-v` before the command for debug logs (`petaledge-bridge -v run`).
87
+
88
+ The server defaults to `$PETALEDGE_API_URL`, else `https://api.edge.petalsautomation.com`.
89
+ Only `https://` servers are accepted; `http://` is accepted for `localhost` and `127.0.0.1`
90
+ (development).
91
+
92
+ The pairing is saved in `~/.petaledge/bridge.json` (set `PETALEDGE_BRIDGE_HOME` to use another
93
+ folder). It holds the bridge id, the bridge token, the pairing secret and the server address,
94
+ **never camera addresses or passwords**. Camera passwords you choose to save ("Save the password on
95
+ the bridge" in the Playground) go to the operating system's password store (Windows Credential Manager,
96
+ macOS Keychain, Secret Service on Linux desktops) through `keyring`, bound to that camera's address;
97
+ `cameras.json` next to `bridge.json` lists them by name and host:port only. A computer without a secure
98
+ password store (a headless Raspberry Pi, say) simply doesn't offer saving. The server forgets bridge
99
+ tokens after 24 hours (30 days without use for a bridge you chose to remember); the
100
+ bridge then tells you to pair again.
101
+
102
+ ## Requirements for the bridge computer
103
+
104
+ **Host**
105
+ - An always-on computer on the **same network or VLAN as the camera** (or one that can route to it).
106
+ - Windows 10/11, macOS 12+, or Linux x86_64 / arm64 (including Raspberry Pi 4/5 with a 64-bit OS),
107
+ with Python 3.10+.
108
+ - About **1 CPU core and 300 MB RAM per stream at 720p**. Use the camera's **sub-stream**;
109
+ decoding a 4K main stream on a Raspberry Pi is not supported.
110
+ - Runs as a normal user. No admin rights, drivers or GPU.
111
+
112
+ **Network**
113
+ - Outbound HTTPS / WSS on **port 443** to the Petal Edge API host.
114
+ - From the bridge to the camera on the LAN: RTSP (554 / 8554) or HTTP (80 / 8080 / the camera's port).
115
+ - **No inbound ports**, no port forwarding, no VPN; works behind NAT.
116
+ - Upload per stream: about 0.25-0.6 Mbit/s at 5 fps / 640 px, 1-2.5 Mbit/s at 10 fps / 960 px.
117
+
118
+ **Camera**
119
+ - RTSP (H.264, H.265, MJPEG) over TCP (default) or UDP, or HTTP MJPEG. NVR channels are addressed
120
+ by their own RTSP path.
121
+ - Use the **sub-stream at 720p or below**.
122
+ - Create a **viewer-only camera account** for the bridge (least privilege).
123
+ - ONVIF discovery, PTZ and two-way audio are not supported.
124
+
125
+ ## Security properties
126
+
127
+ - **No listening socket.** Everything is outbound.
128
+ - **Sealed commands only.** Every camera command is encrypted and authenticated in your browser
129
+ (AES-256-GCM under a key derived from the pairing secret, which the server never sees). The
130
+ bridge refuses anything that doesn't open with its key, is for another bridge / operation /
131
+ stream, is more than 60 s old, or repeats a nonce. Only then does it contact the camera. The
132
+ camera address is inside the seal, so a compromised server can neither read the password nor
133
+ point the bridge somewhere else.
134
+ - **Local networks only by default.** The camera host is resolved once and must be a private
135
+ (10/8, 172.16/12, 192.168/16), loopback, link-local, CGNAT (100.64/10) or IPv6 ULA / link-local
136
+ address; the bridge then connects to that IP (no second lookup). Public addresses need
137
+ `--allow-public-cameras` (not saved; give it on each `run`).
138
+ - **Credentials stay in memory**, only for the stream's lifetime. The camera URL is built inside
139
+ the bridge; every log line, error and result is redacted (`rtsp://user:pass@host` becomes
140
+ `rtsp://***@host`). FFmpeg's own logging is turned off.
141
+ - The settings file is written atomically with mode 0600 (folder 0700) on macOS / Linux. On
142
+ Windows it relies on your user profile folder's default, user-only permissions.
143
+ - Revoke a bridge any time with **Disconnect bridge** in the Playground, and/or
144
+ `petaledge-bridge forget` on the computer.
145
+
146
+ ## Troubleshooting (error codes)
147
+
148
+ | Code | Meaning | What to do |
149
+ |---|---|---|
150
+ | `auth_failed` | The camera refused the username / password (401) or the account may not view this stream (403) | Check the credentials; use an account allowed to view the stream. The bridge does not retry, to avoid account lock-outs. |
151
+ | `not_found` | No stream at that path (404) | Check the RTSP path for your camera / NVR channel (often the sub-stream path). |
152
+ | `refused` | The camera refused the connection | Check the port and that RTSP / HTTP streaming is enabled on the camera. |
153
+ | `timeout` | No answer, or no picture in time | Check that this computer can reach the camera (same network, firewall, VPN routes). Try the TCP transport. |
154
+ | `unreachable` | Name not found or no route to the camera | Check the address; use the camera's IP address. |
155
+ | `unsupported` | Not a stream the bridge can decode | Use H.264 / H.265 / MJPEG over RTSP, or HTTP MJPEG. |
156
+ | `blocked_address` | The camera address is not on a local network | Use the camera's LAN address, or start the bridge with `--allow-public-cameras` if you really mean a public camera. |
157
+ | `bad_seal` | The bridge refused the command | Check that this computer's clock is correct (within 60 s). If the fingerprints don't match, pair again. |
158
+ | `bad_request` | The camera details are not valid | Check the scheme (rtsp / http), host, port and path. |
159
+ | `error` | Anything else, or the camera ended the stream | Run with `-v` for details (credentials are redacted). |
160
+
161
+ Other messages:
162
+ - *"Pairing failed"* / *"The server no longer accepts this bridge"*: the code was wrong, used or
163
+ expired (10 minutes), or the bridge token expired / was revoked. Get a new code in the
164
+ Playground and run `petaledge-bridge connect <code>`.
165
+ - *"Not connected to Petal Edge. Retrying..."*: the bridge reconnects by itself (1 s up to 30 s).
166
+ Check that outbound port 443 is allowed.
167
+ - A clock warning after connecting: sync this computer's clock, or sealed commands will be refused.
168
+
169
+ ## Development
170
+
171
+ The tests live in the Petal Edge repository, not in the PyPI package. From a checkout of it:
172
+
173
+ ```bash
174
+ pip install -e "camera_bridge[test]"
175
+ python -m pytest camera_bridge/tests -q
176
+ ```
177
+
178
+ They need no network and no camera: they generate a short video with PyAV and read it through an
179
+ internal test hook, and they run a tiny local WebSocket server that plays the Petal Edge API side.
180
+
181
+ ## License
182
+
183
+ Apache License 2.0. See `LICENSE`.
@@ -0,0 +1,172 @@
1
+ # Petal Edge Camera Bridge: protocol v1
2
+
3
+ The single source of truth for the three parties of Model Playground CCTV / IP camera input
4
+ (plan: `docs/New_implementation/playground.md` §7):
5
+
6
+ - **Browser**: the Model Playground page (`app/src/components/playground/sources/ip-camera/*`).
7
+ - **Server**: the Petal Edge API (`api/app/services/playground/{bridges,streams}.py`,
8
+ routes in `api/app/api/v1/endpoints/playground.py`).
9
+ - **Bridge**: this package, running on a computer on the camera's network. It only makes
10
+ **outbound** connections and never opens a listening socket.
11
+
12
+ Prediction always happens on the server, in the user's Playground model session, through the same
13
+ image handler as uploads and the webcam. The bridge only reads the camera and relays frames.
14
+
15
+ ---
16
+
17
+ ## 1. Pairing (user-scoped, no project)
18
+
19
+ 1. The browser generates a 16-byte random **pairing secret `S`** (WebCrypto). `S` is never sent to
20
+ the server.
21
+ 2. The browser calls `POST /api/v1/playground/bridges/pairing` and receives a **server code** `C`
22
+ (8 characters from `23456789ABCDEFGHJKLMNPQRSTUVWXYZ`, single use, 10 minutes, bound to the user).
23
+ 3. The browser shows the command
24
+ `petaledge-bridge connect <C>.<base32(S)> --server <API origin>`
25
+ where `base32` is RFC 4648, upper case, **no padding** (26 characters for 16 bytes).
26
+ The bridge ignores spaces and `-` in the code, and accepts lower case.
27
+ 4. The bridge opens the bridge WebSocket (§3) and sends `hello` with `pairing_code: C` (**never `S`**).
28
+ 5. The server binds the bridge to the user who created `C`, answers `hello_ack` with a new
29
+ `bridge_id` and a `bridge_token` (for reconnects; the server stores only its SHA-256).
30
+ 6. Browser and bridge both derive the command key `K` and a fingerprint (§2) and show the
31
+ fingerprint, so the user can confirm they match.
32
+
33
+ The bridge keeps `bridge_id`, `bridge_token`, `S` and the server origin in its config file
34
+ (`~/.petaledge/bridge.json`, mode 0600). It reconnects with `bridge_token` (not the code).
35
+ Bridge tokens expire after 24 h on the server; the bridge then asks the user to pair again.
36
+
37
+ ## 2. Keys and sealed commands
38
+
39
+ All binary values travelling in JSON are **standard base64 with padding**.
40
+
41
+ ```
42
+ K = HKDF-SHA256(ikm = S, salt = UTF-8(bridge_id), info = "pe-bridge-v1", L = 32 bytes)
43
+ fingerprint = HKDF-SHA256(ikm = S, salt = UTF-8(bridge_id), info = "pe-bridge-fingerprint-v1", L = 4 bytes)
44
+ shown as upper-case hex "AABB·CCDD" (two groups of 4, U+00B7 between them)
45
+ ```
46
+
47
+ A **sealed command** is authored by the browser and opened only by the bridge:
48
+
49
+ ```
50
+ plaintext = UTF-8(JSON) of
51
+ { "v": 1,
52
+ "op": "camera_test" | "stream_start",
53
+ "bridge_id": "<bridge_id>",
54
+ "stream_id": "<stream_id>" (stream_start only; omitted for camera_test)
55
+ "nonce": "<base64 of 16 random bytes>",
56
+ "issued_at": <unix seconds, integer>,
57
+ "camera": { "name": str, "scheme": "rtsp" | "http",
58
+ "host": str, "port": int | null, "path": str | null,
59
+ "transport": "tcp" | "udp" | null },
60
+ "username": str | null,
61
+ "password": str | null,
62
+ "profile": { "id": "pf_…", "save": bool } (optional, since 0.2; only to a bridge advertising "profiles") }
63
+
64
+ aad = UTF-8("<bridge_id>|<op>|<stream_id or empty string>")
65
+ iv = 12 random bytes
66
+ ct = AES-256-GCM(key = K, iv, aad, plaintext) ciphertext || 16-byte tag (WebCrypto / cryptography layout)
67
+ sealed = { "v": 1, "iv": base64(iv), "ct": base64(ct) }
68
+ ```
69
+
70
+ The bridge **refuses** (error code `bad_seal`) a sealed command when:
71
+ - it does not decrypt under its own `K` with the AAD built from its own `bridge_id` and the
72
+ envelope's `op` / `stream_id`;
73
+ - the plaintext `v` is not 1, or its `op`, `bridge_id` or `stream_id` differ from the envelope;
74
+ - `|now − issued_at| > 60` seconds;
75
+ - its `nonce` was already seen in the last 10 minutes.
76
+
77
+ The camera address is inside the seal, so a server can neither read credentials nor redirect the
78
+ bridge to another host. Test vectors: `camera_bridge/tests/vectors.json` (both implementations must
79
+ reproduce `K`, the fingerprint, and `ct` for the given `iv`).
80
+
81
+ **Saved camera profiles (0.2, optional).** A bridge whose OS keyring is usable advertises
82
+ `"capabilities": ["profiles"]` in its `hello`. The browser then names each camera's profile inside the
83
+ seal: `id = "pf_" + base64url(SHA-256(UTF-8("<bridge_id>|<scheme>|<host, lower case>|<port>|<path>")))[:24]`
84
+ (derived, so the browser stores nothing about the camera). With `"save": true` on a `camera_test` that
85
+ succeeds, the bridge stores `{username, password}` in its OS keyring under service `petaledge-bridge`,
86
+ bound to the camera address, and answers `"profile_saved": true|false`. A later command with no
87
+ `password` and the same profile id gets the saved credentials filled in by the bridge, but only for the
88
+ exact address they were saved for (otherwise `bad_request`) and only when its `username` is empty or the
89
+ same. Nothing saved is not an error (the camera may need no password). No plaintext fallback exists:
90
+ without a secure keyring the capability isn't advertised. `petaledge-bridge cameras` lists and forgets
91
+ profiles (names and host:port only); `forget` removes them all.
92
+
93
+ Credential hygiene: the browser clears the password from its state right after sealing. The bridge
94
+ keeps credentials in memory for the stream's lifetime only, builds the camera URL internally, and
95
+ redacts every string that leaves the process (logs, errors, results): `rtsp://user:pass@host`
96
+ becomes `rtsp://***@host`.
97
+
98
+ ## 3. Bridge ↔ server WebSocket
99
+
100
+ `wss://<api>/api/v1/playground/bridges/ws`. Text frames are JSON; binary frames are video frames.
101
+ The first message must be `hello` within 10 s, otherwise the server closes with 1008.
102
+
103
+ | Direction | Message | Notes |
104
+ |---|---|---|
105
+ | bridge → server | `{"type":"hello","pairing_code":C}` or `{"type":"hello","bridge_token":T,"bridge_id":B}` plus `"name"`, `"version"`, `"os"`, `"key_fingerprint"`, and since 0.2 `"capabilities":["profiles"]?` | `name` ≤ 64 chars (computer name by default); unknown capabilities are dropped |
106
+ | server → bridge | `{"type":"hello_ack","bridge_id":B,"bridge_token":T?,"server_time":unix}` | `bridge_token` only on pairing |
107
+ | bridge → server | `{"type":"key_fingerprint","key_fingerprint":"AABB·CCDD"}` | once, right after a **pairing** `hello_ack` (the pairing `hello` sends `key_fingerprint: null`, because the fingerprint needs `bridge_id`); the server keeps the first value |
108
+ | server → bridge | `{"type":"error","code":...,"message":...}` then close 1008 | bad code / token |
109
+ | server → bridge | `{"type":"camera_test","req_id":R,"sealed":{...}}` | |
110
+ | bridge → server | `{"type":"camera_test_result","req_id":R,"ok":true,"width":W,"height":H,"fps":F\|null,"codec":"h264"\|...,"thumbnail_jpeg_b64":"...","profile_saved":bool?}` or `{"type":"camera_test_result","req_id":R,"ok":false,"error_code":E,"message":M}` | thumbnail ≤ 50 KB; message already redacted |
111
+ | server → bridge | `{"type":"stream_start","stream_id":S,"stream_no":N,"sealed":{...},"max_fps":F,"max_side":P}` | `stream_no` is a u32 used in frame headers |
112
+ | server → bridge | `{"type":"stream_stop","stream_id":S}` | |
113
+ | server → bridge | `{"type":"credit","stream_id":S,"n":k}` | the bridge may send `k` more frames for S |
114
+ | bridge → server | `{"type":"stream_state","stream_id":S,"state":"connecting"\|"live"\|"reconnecting"\|"stopped"\|"error","attempt":n?,"error_code":E?,"message":M?}` | |
115
+ | bridge → server | **binary frame** (§4) | only while it holds a credit; at most `max_fps` per second |
116
+ | both | `{"type":"ping"}` / `{"type":"pong"}` | server pings every 20 s; a bridge silent for 45 s is offline |
117
+
118
+ Error codes the bridge reports (camera test and stream state): `auth_failed`, `not_found`,
119
+ `refused`, `timeout`, `unreachable`, `unsupported`, `blocked_address`, `bad_seal`, `bad_request`,
120
+ `error`. Messages are plain language and contain the user's host and port but never credentials.
121
+
122
+ Credits: the server grants 2 credits (a separate `credit` message) right after `stream_start`, one
123
+ more each time it has taken a frame, and 2 again when a bridge reconnects while the stream is still
124
+ running. A bridge keeps its streams across a dropped connection (60 s, camera open, credits reset to
125
+ 0) and resumes them on the server's credits; it stops a stream itself after 120 s without credits. The bridge keeps only the newest decoded frame (no queue); when it has a credit and its
126
+ `max_fps` interval has passed, it encodes and sends the newest frame.
127
+
128
+ ## 4. Binary frame
129
+
130
+ ```
131
+ offset size field
132
+ 0 4 magic "PGF1"
133
+ 4 4 stream_no u32 little-endian
134
+ 8 4 seq u32 little-endian (per stream, starts at 0)
135
+ 12 8 ts_ms u64 little-endian (bridge wall clock, ms since epoch)
136
+ 20 2 width u16 little-endian
137
+ 22 2 height u16 little-endian
138
+ 24 … JPEG bytes (≤ 512 KB; long side ≤ max_side; quality ≈ 80)
139
+ ```
140
+
141
+ The server forwards the same frame format to the browser (§5), with its own `stream_no`.
142
+
143
+ ## 5. Browser ↔ server
144
+
145
+ REST (all require the user's JWT; another user's ids are 404):
146
+
147
+ | Method & path | Body | Returns |
148
+ |---|---|---|
149
+ | `POST /playground/bridges/pairing` | — | `{"server_code","expires_at"}` |
150
+ | `GET /playground/bridges` | — | `[{"bridge_id","name","online","version","os","key_fingerprint","pairing_code","connected_at","last_seen","remembered","expires_at","capabilities"}]` |
151
+ | `PUT /playground/bridges/{bridge_id}/remember` | `{"remember": bool}` | the bridge as listed. On: its token lives 30 days without use (each reconnect restarts the period) and its record (no secrets; the token only as a SHA-256) is persisted, so it survives API restarts; the browser keeps K, non-extractable, in IndexedDB. Off: back to the 24 h lifetime, not persisted. |
152
+ | `DELETE /playground/bridges/{bridge_id}` | — | 204; revokes the token and closes the bridge socket |
153
+ | `POST /playground/bridges/{bridge_id}/camera-test` | `{"sealed":{...}}` | the bridge's `camera_test_result` minus `type`/`req_id` (504 `bridge_timeout` after 12 s, 409 `bridge_offline`) |
154
+ | `POST /playground/streams` | `{"stream_id","session_id","bridge_id","sealed","preview_fps","inference_fps"}` | `{"stream_id","state"}`; `stream_id` is client-generated (22-64 chars `[A-Za-z0-9_-]`) because it is bound into the seal |
155
+ | `PATCH /playground/streams/{stream_id}` | `{"inference": bool?, "threshold": number\|null?}` | `{"stream_id","inference","threshold"}` |
156
+ | `DELETE /playground/streams/{stream_id}` | — | 204 |
157
+ | `POST /playground/streams/{stream_id}/ws-token` | — | `{"token","expires_at"}` (single use, 60 s) |
158
+
159
+ Browser stream WebSocket: `wss://<api>/api/v1/playground/streams/{stream_id}/ws?token=...`
160
+
161
+ | Direction | Message |
162
+ |---|---|
163
+ | server → browser | binary frame (§4) for preview, while the browser holds a credit, at most `preview_fps` |
164
+ | server → browser | `{"type":"result","seq":n,"ts_ms":t,"result":<PlaygroundPrediction>}` when inference is on |
165
+ | server → browser | `{"type":"state","state":"waiting_for_bridge"\|"connecting"\|"live"\|"reconnecting"\|"bridge_offline"\|"stopped","reason":str?,"error_code":E?,"message":M?}` |
166
+ | server → browser | `{"type":"stats","preview_fps":x,"model_fps":y,"latency_ms":z}` every 2 s |
167
+ | browser → server | `{"type":"ack","n":1}` (one credit per frame drawn; the server starts with 2) |
168
+ | browser → server | `{"type":"pause"}` / `{"type":"resume"}` (stop / restart preview frames, e.g. tab hidden) |
169
+
170
+ A stream stops on: `DELETE`, the browser socket closed for more than 30 s, `pause` held for more
171
+ than 60 s, the model session removed or expired, the bridge offline for more than 60 s, 30 minutes
172
+ of total time, or server shutdown. Limits: 1 live stream per user, 3 per API process.