aboutsummaryrefslogtreecommitdiffstats
path: root/packages
diff options
context:
space:
mode:
Diffstat (limited to 'packages')
-rw-r--r--packages/meshbay-android/.gitignore6
-rw-r--r--packages/meshbay-android/LICENSE-EXCEPTION.txt24
-rw-r--r--packages/meshbay-android/README.md66
-rw-r--r--packages/meshbay-android/app/build.gradle.kts88
-rw-r--r--packages/meshbay-android/app/src/main/AndroidManifest.xml43
-rw-r--r--packages/meshbay-android/app/src/main/assets/bridge/meshbay-bridge.js230
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/MainActivity.kt322
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Bridge.kt78
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Channels.kt107
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/KeyChannels.kt117
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Refused.kt4
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/BoxAccumulator.kt87
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastChannels.kt152
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastControl.kt405
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastRelay.kt596
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastService.kt74
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/hub/HubClient.kt130
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/DeviceKey.kt47
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Kdf.kt108
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Keyring.kt268
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/SecretStore.kt120
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Transcripts.kt185
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/save/SaveNames.kt75
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/save/SaveSinks.kt238
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/EngineCheck.kt57
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/NativeText.kt48
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/Pickers.kt40
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/ShellWebView.kt25
-rw-r--r--packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/UiAssets.kt93
-rw-r--r--packages/meshbay-android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml7
-rw-r--r--packages/meshbay-android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml7
-rw-r--r--packages/meshbay-android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.pngbin0 -> 17157 bytes
-rw-r--r--packages/meshbay-android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.pngbin0 -> 8754 bytes
-rw-r--r--packages/meshbay-android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.pngbin0 -> 28251 bytes
-rw-r--r--packages/meshbay-android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.pngbin0 -> 55758 bytes
-rw-r--r--packages/meshbay-android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.pngbin0 -> 87228 bytes
-rw-r--r--packages/meshbay-android/app/src/main/res/values/colors.xml5
-rw-r--r--packages/meshbay-android/app/src/main/res/values/themes.xml6
-rw-r--r--packages/meshbay-android/app/src/main/res/xml/data_extraction_rules.xml11
-rw-r--r--packages/meshbay-android/app/src/main/res/xml/network_security_config.xml11
-rw-r--r--packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/CastRelayTest.kt307
-rw-r--r--packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/ChannelsTest.kt39
-rw-r--r--packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/FakePrefs.kt30
-rw-r--r--packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/FakeSecrets.kt11
-rw-r--r--packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/HubClientTest.kt43
-rw-r--r--packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/KeyChannelsTest.kt81
-rw-r--r--packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/KeyringVectorsTest.kt151
-rw-r--r--packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/NativeTextTest.kt34
-rw-r--r--packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/SaveNamesTest.kt45
-rw-r--r--packages/meshbay-android/build.gradle.kts1
-rw-r--r--packages/meshbay-android/gradle.properties2
-rw-r--r--packages/meshbay-android/gradle/wrapper/gradle-wrapper.jarbin0 -> 47623 bytes
-rw-r--r--packages/meshbay-android/gradle/wrapper/gradle-wrapper.properties10
-rwxr-xr-xpackages/meshbay-android/gradlew248
-rw-r--r--packages/meshbay-android/gradlew.bat112
-rw-r--r--packages/meshbay-android/settings.gradle.kts9
-rw-r--r--packages/meshbay-client/package.json6
-rw-r--r--packages/meshbay-client/src/argon2-wasm.js2
-rw-r--r--packages/meshbay-client/src/cast-chromecast.js168
-rw-r--r--packages/meshbay-client/src/cast-relay.js151
-rw-r--r--packages/meshbay-client/src/keyring.js2
-rw-r--r--packages/meshbay-client/src/main.js103
-rw-r--r--packages/meshbay-client/src/preload.js23
-rw-r--r--packages/meshbay-client/src/transcripts.js18
-rw-r--r--packages/meshbay-common/COPYING674
-rw-r--r--packages/meshbay-common/COPYING.LESSER165
-rw-r--r--packages/meshbay-common/pyproject.toml6
-rw-r--r--packages/meshbay-common/src/meshbay_common/__init__.py16
-rw-r--r--packages/meshbay-common/src/meshbay_common/adminop.py45
-rw-r--r--packages/meshbay-common/src/meshbay_common/groupbox.py2
-rw-r--r--packages/meshbay-common/src/meshbay_common/protocol.py33
-rw-r--r--packages/meshbay-common/tests/test_admin_subject_parity.py47
-rw-r--r--packages/meshbay-common/tests/test_js_python_parity.py2
-rw-r--r--packages/meshbay-hub/LICENSE661
-rw-r--r--packages/meshbay-hub/pyproject.toml6
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/__init__.py2
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/api/admin.py7
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/api/federation.py2
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/api/groups.py8
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/api/health.py1
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/api/hub.py3
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/api/moderation.py5
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/api/nodes.py1
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/api/notifications.py1
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/api/revocation.py3
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/api/users.py15
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/app.js60
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/auth-page.js14
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/cast-session.js220
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/copy-link.js50
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/crypto.js12
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/file-utils.js4
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/files-app.js22
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/group-link.js95
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/group-page.js52
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/group-settings.js170
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/helloworld-app-settings.js3
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/helloworld-app.js3
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/icon.js6
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/index-dock.js10
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/keyderive.js2
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/licenses/AGPL-3.0.txt661
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/licenses/APPLICATION-EXCEPTION.txt65
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/licenses/GPL-3.0.txt674
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/licenses/LGPL-3.0.txt165
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/locales/de.js23
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/locales/en.js23
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/locales/es.js23
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js23
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/locales/it.js23
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/locales/ja.js23
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/locales/nl.js23
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/locales/pl.js23
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/locales/pt-BR.js23
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/locales/zh-CN.js23
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/music-app.js13
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/music-player.js296
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/note.js24
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/photos-app.js98
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/platform.js74
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/playlist-crypto.js2
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/profile-page.js25
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/search-page.js47
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/settings-page.js25
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/style.css238
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/transport-admin.js126
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/transport-chat.js4
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/transport-codec.js2
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/transport-devices.js7
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/transport-media.js4
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/transport-pins.js2
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/transport-rewrap.js2
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/transport-roster.js2
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/transport-upload.js2
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/transport.js27
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/vendor/LICENSES.txt268
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md22
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/video-app.js3
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/video-player.js279
-rw-r--r--packages/meshbay-hub/tests/harness/cast_session_probe.py521
-rw-r--r--packages/meshbay-hub/tests/harness/copy_link_probe.py270
-rw-r--r--packages/meshbay-hub/tests/harness/group_link_probe.py176
-rw-r--r--packages/meshbay-hub/tests/harness/invite_link_probe.py23
-rw-r--r--packages/meshbay-hub/tests/harness/window_leak.mjs7
-rw-r--r--packages/meshbay-hub/tests/test_android_cast.py137
-rw-r--r--packages/meshbay-hub/tests/test_android_downloads.py90
-rw-r--r--packages/meshbay-hub/tests/test_android_keys.py74
-rw-r--r--packages/meshbay-hub/tests/test_android_shell.py223
-rw-r--r--packages/meshbay-hub/tests/test_cast_discovery.py152
-rw-r--r--packages/meshbay-hub/tests/test_cast_files.py372
-rw-r--r--packages/meshbay-hub/tests/test_copy_link.py103
-rw-r--r--packages/meshbay-hub/tests/test_desktop_keyring.py22
-rw-r--r--packages/meshbay-hub/tests/test_desktop_shell.py11
-rw-r--r--packages/meshbay-hub/tests/test_downloads.py53
-rw-r--r--packages/meshbay-hub/tests/test_group_link.py170
-rw-r--r--packages/meshbay-hub/tests/test_group_link_flow.py67
-rw-r--r--packages/meshbay-hub/tests/test_http_api_doc.py30
-rw-r--r--packages/meshbay-hub/tests/test_invite_link_flow.py17
-rw-r--r--packages/meshbay-hub/tests/test_keyring_vectors.py142
-rw-r--r--packages/meshbay-hub/tests/test_search_unreachable_note.py33
-rw-r--r--packages/meshbay-hub/tests/test_spa_ordering.py4
-rw-r--r--packages/meshbay-hub/tests/test_upload_controls_hidden.py30
-rw-r--r--packages/meshbay-hub/tests/test_video_audio_track.py4
-rw-r--r--packages/meshbay-hub/tests/test_video_seek.py65
-rw-r--r--packages/meshbay-hub/tests/vectors/gen_keyring_vectors.js232
-rw-r--r--packages/meshbay-hub/tests/vectors/keyring.json342
-rw-r--r--packages/meshbay-node/LICENSE661
-rw-r--r--packages/meshbay-node/pyproject.toml6
-rw-r--r--packages/meshbay-node/src/meshbay_node/__init__.py2
-rw-r--r--packages/meshbay-node/src/meshbay_node/cli/status.py3
-rw-r--r--packages/meshbay-node/src/meshbay_node/daemon.py5
-rw-r--r--packages/meshbay-node/src/meshbay_node/indexer/cache.py14
-rw-r--r--packages/meshbay-node/src/meshbay_node/indexer/indexer.py80
-rw-r--r--packages/meshbay-node/src/meshbay_node/ops/chat.py2
-rw-r--r--packages/meshbay-node/src/meshbay_node/ops/roots.py15
-rw-r--r--packages/meshbay-node/src/meshbay_node/ops/settings.py6
-rw-r--r--packages/meshbay-node/src/meshbay_node/roots.py6
-rw-r--r--packages/meshbay-node/src/meshbay_node/roster.py20
-rw-r--r--packages/meshbay-node/src/meshbay_node/transport/webrtc/admin.py55
-rw-r--r--packages/meshbay-node/src/meshbay_node/transport/webrtc/chat.py6
-rw-r--r--packages/meshbay-node/src/meshbay_node/transport/webrtc/dispatch.py13
-rw-r--r--packages/meshbay-node/src/meshbay_node/transport/webrtc/group_ops.py84
-rw-r--r--packages/meshbay-node/src/meshbay_node/transport/webrtc/node_ops.py378
-rw-r--r--packages/meshbay-node/src/meshbay_node/ui/app.py62
-rw-r--r--packages/meshbay-node/tests/golden/dispatch.json4652
-rw-r--r--packages/meshbay-node/tests/test_admin_challenge_bounds.py45
-rw-r--r--packages/meshbay-node/tests/test_admin_ops_mnp.py174
-rw-r--r--packages/meshbay-node/tests/test_attach_from_the_hub.py4
-rw-r--r--packages/meshbay-node/tests/test_licensing.py257
-rw-r--r--packages/meshbay-node/tests/test_node_status.py305
-rw-r--r--packages/meshbay-node/tests/test_root_eject.py128
-rw-r--r--packages/meshbay-node/tests/test_root_writable_policy.py38
-rw-r--r--packages/meshbay-node/tests/test_security_regressions.py97
-rw-r--r--packages/meshbay-node/tests/test_sharing_is_local_only.py109
194 files changed, 15576 insertions, 6312 deletions
diff --git a/packages/meshbay-android/.gitignore b/packages/meshbay-android/.gitignore
new file mode 100644
index 0000000..8a50ec5
--- /dev/null
+++ b/packages/meshbay-android/.gitignore
@@ -0,0 +1,6 @@
+# Generated — the interface is copied from meshbay-hub/static at build time
+# and never committed (docs/MESHBAY_DESIGN.md §8.3).
+build/
+.gradle/
+local.properties
+.kotlin/
diff --git a/packages/meshbay-android/LICENSE-EXCEPTION.txt b/packages/meshbay-android/LICENSE-EXCEPTION.txt
new file mode 100644
index 0000000..bd526f6
--- /dev/null
+++ b/packages/meshbay-android/LICENSE-EXCEPTION.txt
@@ -0,0 +1,24 @@
+MeshBay for Android — additional permission under GNU AGPL version 3, section 7
+==============================================================================
+
+The MeshBay Android application is free software under the GNU Affero General
+Public License, version 3 or (at your option) any later version — see LICENSE
+at the root of the repository — with the following additional permission.
+(Its protocol files, those marked SPDX-License-Identifier: LGPL-3.0-or-later,
+are under the GNU Lesser GPL instead, which needs no such permission.)
+
+ If you modify this Program, or any covered work, by linking or combining
+ it with the Google Play services client libraries (the Maven group
+ com.google.android.gms, or a modified version of those libraries),
+ containing parts covered by the terms of the licence under which Google
+ distributes them, the licensors of this Program grant you additional
+ permission to convey the resulting work. Corresponding Source for a
+ non-source form of such a combination shall not include the source code
+ for the parts of those libraries used as well as that of the covered work.
+
+Why: casting to a television goes through Google's cast sender SDK, which is
+not free software and is linked into the application. Without this permission,
+nobody but the copyright holders could lawfully distribute the application as
+it is built, including from a fork. The permission covers those libraries only;
+nothing else in the application is exempt from the AGPL, and anybody who
+distributes a modified version may remove it (section 7).
diff --git a/packages/meshbay-android/README.md b/packages/meshbay-android/README.md
new file mode 100644
index 0000000..bfd82cf
--- /dev/null
+++ b/packages/meshbay-android/README.md
@@ -0,0 +1,66 @@
+# MeshBay — Android client
+
+A client, not a host: no node runs on a phone (`docs/MESHBAY_DESIGN.md` §11.3).
+
+The shell is a system WebView showing the interface **from the package** —
+`meshbay-hub/src/meshbay_hub/static/` copied at build time into
+`build/generated/`, never committed (§8.3) — with a bridge
+(`app/src/main/assets/bridge/meshbay-bridge.js`) that offers the page the same
+`window.meshbay` as the desktop preload, wherever it offers anything at all.
+Hub calls leave from native code, to the signed-in hub only. The device key,
+the bundle key and every node identity are held natively under an Android
+Keystore key; the page is told public keys and handed signatures, asked for by
+kind — never bytes. `meshbay-hub/tests/vectors/keyring.json` holds that keyring
+to the desktop's and to the specification.
+
+Downloads are written to disk as they arrive — into the folder chosen in
+Settings (a Storage Access Framework tree, as `<name>.part` until complete) or
+the system Downloads collection (a pending entry until complete) — and the
+page holds an opaque id, never a URI. Uploads come through the system picker.
+
+Casting: the page pushes the decrypted stream to a local HTTP relay (a port of
+the desktop's `cast-relay.js`, bound to the Wi-Fi address only); receivers are
+found and driven through the platform cast SDK with the default media receiver.
+While a cast runs, a media-playback foreground service holds the CPU and the
+Wi-Fi, and the WebView is kept reported visible — without that, Chromium
+freezes the page 60 s after the screen goes off. Where play services are
+absent, the page is offered no cast at all. Music playing on the phone itself
+holds the same service and the same visibility, for as long as it plays
+(`playback:keep-alive`), so the next track still loads with the screen off.
+
+```bash
+# needs JDK 17+ and an Android SDK (ANDROID_HOME, or sdk.dir in local.properties)
+./gradlew assembleDebug # app/build/outputs/apk/debug/app-debug.apk
+./gradlew testDebugUnitTest # JVM unit tests
+```
+
+The security contract is also pinned from the Python suite by reading this
+source: `packages/meshbay-hub/tests/test_android_shell.py`.
+
+Not built yet: phone-specific behaviour (back button, network handover,
+keeping a download alive with the screen off), signed releases.
+
+## Icon
+
+The desktop client's icon, `meshbay-client/build/icon-square.png`, placed in
+the adaptive icon's safe zone (72 dp of the 108 dp layer, which is what every
+launcher mask leaves visible) over its own edge colour, so no mask crops the
+M. The five `mipmap-*/ic_launcher_foreground.png` are generated from it:
+
+```python
+from PIL import Image, ImageDraw, ImageFilter
+src = Image.open("../meshbay-client/build/icon-square.png").convert("RGBA")
+for name, L in [("mdpi", 108), ("hdpi", 162), ("xhdpi", 216), ("xxhdpi", 324), ("xxxhdpi", 432)]:
+ S = L * 72 // 108; b = max(2, S // 25)
+ img = src.resize((S, S), Image.LANCZOS)
+ mask = Image.new("L", (S, S), 0)
+ ImageDraw.Draw(mask).rectangle([b, b, S - b - 1, S - b - 1], fill=255)
+ img.putalpha(mask.filter(ImageFilter.GaussianBlur(b)))
+ layer = Image.new("RGBA", (L, L), (0, 0, 0, 0))
+ layer.paste(img, ((L - S) // 2, (L - S) // 2), img)
+ layer.save(f"app/src/main/res/mipmap-{name}/ic_launcher_foreground.png", optimize=True)
+```
+
+No monochrome layer: a themed icon keeps only the layer's alpha, and this one
+would be a filled square.
+
diff --git a/packages/meshbay-android/app/build.gradle.kts b/packages/meshbay-android/app/build.gradle.kts
new file mode 100644
index 0000000..3f29ac0
--- /dev/null
+++ b/packages/meshbay-android/app/build.gradle.kts
@@ -0,0 +1,88 @@
+import groovy.json.JsonSlurper
+
+plugins { id("com.android.application") }
+
+// One version for every package (CLAUDE.md): read from the desktop client's
+// package.json rather than written a second time here.
+val packageVersion = (JsonSlurper().parse(rootDir.resolve("../meshbay-client/package.json"))
+ as Map<*, *>)["version"] as String
+val versionParts = packageVersion.split(".").map { it.toInt() }
+
+android {
+ namespace = "org.meshbay.client"
+ compileSdk = 37
+ defaultConfig {
+ applicationId = "org.meshbay.client"
+ minSdk = 26
+ targetSdk = 36
+ versionName = packageVersion
+ versionCode = versionParts[0] * 10000 + versionParts[1] * 100 + versionParts[2]
+ }
+ buildTypes {
+ getByName("release") {
+ isMinifyEnabled = false
+ // A stand-in until the release key exists (Stage D12): the debug
+ // key, so a release build installs over a debug one and back
+ // without losing the account. Not a key to publish anything with.
+ signingConfig = signingConfigs.getByName("debug")
+ }
+ }
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+ buildFeatures { buildConfig = true }
+ testOptions { unitTests.isReturnDefaultValues = false }
+}
+
+dependencies {
+ implementation("androidx.webkit:webkit:1.17.1")
+ implementation("com.squareup.okhttp3:okhttp:5.5.0")
+ // Ed25519, X25519, HKDF and Argon2id, identical on the JVM and every
+ // Android version: the platform has no Argon2 and its Ed25519 is recent.
+ implementation("org.bouncycastle:bcprov-jdk18on:1.86")
+ // Casting: discovery through MediaRouter, control through the cast sender
+ // SDK and the default media receiver. Needs the vendor's play services at
+ // run time; where they are absent the page is offered no cast at all.
+ implementation("com.google.android.gms:play-services-cast-framework:22.3.1")
+ implementation("androidx.mediarouter:mediarouter:1.8.1")
+ testImplementation("junit:junit:4.13.2")
+ // Android's org.json is a stub on the JVM; the unit tests need the real one.
+ testImplementation("org.json:json:20260814")
+}
+
+/**
+ * The interface, copied from its single source at build time (§8.3).
+ *
+ * `meshbay-hub/src/meshbay_hub/static/` is the interface for the web, the
+ * desktop application and this one. The copy lands in build/ and is never
+ * committed, so it cannot fork. The page itself is the desktop application's
+ * `scripts/index.html` — the hub builds its own with a /a/<hash>/ prefix that
+ * would point back at the hub — so an application loading from its package
+ * has one page, not two.
+ */
+abstract class SyncUi : DefaultTask() {
+ @get:InputDirectory abstract val staticDir: DirectoryProperty
+ @get:InputFile abstract val indexHtml: RegularFileProperty
+ @get:OutputDirectory abstract val outputDir: DirectoryProperty
+
+ @TaskAction
+ fun copy() {
+ val ui = outputDir.get().asFile.resolve("ui")
+ outputDir.get().asFile.deleteRecursively()
+ staticDir.get().asFile.copyRecursively(ui)
+ indexHtml.get().asFile.copyTo(ui.resolve("index.html"), overwrite = true)
+ }
+}
+
+val syncUi = tasks.register<SyncUi>("syncUi") {
+ staticDir.set(rootDir.resolve("../meshbay-hub/src/meshbay_hub/static"))
+ indexHtml.set(rootDir.resolve("../meshbay-client/scripts/index.html"))
+ outputDir.set(layout.buildDirectory.dir("generated/ui-assets"))
+}
+
+androidComponents {
+ onVariants { variant ->
+ variant.sources.assets?.addGeneratedSourceDirectory(syncUi, SyncUi::outputDir)
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/AndroidManifest.xml b/packages/meshbay-android/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..2eae3ea
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/AndroidManifest.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <!-- Casting: the relay's foreground service, and the locks that keep the
+ CPU and the Wi-Fi up while the screen is off. -->
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
+ <uses-permission android:name="android.permission.WAKE_LOCK" />
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+
+ <!-- No backup of any kind: the keys are wrapped by a Keystore key that a
+ restore cannot bring with it, so a backed-up store is one that silently
+ fails to open on the next device. -->
+ <application
+ android:label="MeshBay"
+ android:icon="@mipmap/ic_launcher"
+ android:roundIcon="@mipmap/ic_launcher_round"
+ android:allowBackup="false"
+ android:fullBackupContent="false"
+ android:dataExtractionRules="@xml/data_extraction_rules"
+ android:networkSecurityConfig="@xml/network_security_config"
+ android:theme="@style/Shell">
+ <activity
+ android:name=".MainActivity"
+ android:exported="true"
+ android:launchMode="singleTask"
+ android:windowSoftInputMode="adjustResize"
+ android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|uiMode|keyboard|keyboardHidden|density|navigation">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ <service
+ android:name=".cast.CastService"
+ android:exported="false"
+ android:foregroundServiceType="mediaPlayback" />
+ <meta-data
+ android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
+ android:value="org.meshbay.client.cast.CastOptionsProvider" />
+ </application>
+</manifest>
diff --git a/packages/meshbay-android/app/src/main/assets/bridge/meshbay-bridge.js b/packages/meshbay-android/app/src/main/assets/bridge/meshbay-bridge.js
new file mode 100644
index 0000000..b71b5e8
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/assets/bridge/meshbay-bridge.js
@@ -0,0 +1,230 @@
+/**
+ * The bridge, and the whole of it — the Android counterpart of
+ * meshbay-client/src/preload.js, with the same shape wherever it offers
+ * something at all.
+ *
+ * Injected at document start into documents of the packaged origin, before any
+ * page script. It takes the native port the listener injected, hides the
+ * global, and exposes `window.meshbay` frozen. There is no context isolation
+ * on Android: page script runs in the same world, so what this buys is that
+ * nothing can reach the raw port by name, not that this file is out of reach.
+ * The confinement that matters is native — the listener answers the packaged
+ * origin's top-level document only, and checks every argument.
+ *
+ * What the desktop offers and this build does not is ABSENT, not a function
+ * that refuses: `platform.js` decides what to show from whether an object
+ * exists (`platform.node.available`, `platform.folder.available`, …).
+ *
+ * `HUB_BASE`, `BINARY` and `CAST` are prepended by the shell when it injects
+ * this file: the interface asks for the hub while its modules load, before
+ * anything can await; BINARY says whether the WebView carries ArrayBuffer
+ * messages; CAST whether this device can cast at all.
+ */
+(function () {
+ 'use strict';
+ const port = window.meshbayNative;
+ try { delete window.meshbayNative; } catch (e) { /* already gone */ }
+ // A same-origin child frame gets the port too; it gets no bridge, and native
+ // refuses whatever it sends anyway.
+ if (!port || window.top !== window) return;
+
+ const pending = new Map();
+ let seq = 0;
+ port.onmessage = (event) => {
+ let reply;
+ try { reply = JSON.parse(event.data); } catch (e) { return; }
+ const waiter = pending.get(reply.id);
+ if (!waiter) return;
+ pending.delete(reply.id);
+ if (reply.ok) waiter.resolve(reply.value);
+ else waiter.reject(new Error(reply.error));
+ };
+ const call = (channel, ...args) => new Promise((resolve, reject) => {
+ const id = ++seq;
+ pending.set(id, { resolve, reject });
+ port.postMessage(JSON.stringify({ id, ch: channel, args }));
+ });
+
+ // A write is a binary message: "MBB1" | id | channel | 0 | handle | bytes,
+ // big-endian — one copy, no JSON, no base64 (spike S-3: 136 MB/s awaited
+ // per 48 KB chunk). Without ArrayBuffer messages, base64 over JSON.
+ const SAVE_WRITE = 1;
+ const CAST_PUSH = 2;
+ const CAST_FILE = 3;
+ // A file crosses in pieces this size: big enough to be few, small enough
+ // that no one message is a burden to the WebView or the bridge.
+ const FILE_PIECE = 1024 * 1024;
+ const bytesOf = (chunk) => (chunk instanceof Uint8Array ? chunk
+ : ArrayBuffer.isView(chunk) ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)
+ : new Uint8Array(chunk));
+ const base64Of = (bytes) => {
+ let s = '';
+ for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
+ return btoa(s);
+ };
+ const sendBinary = (channel, handle, bytes) => new Promise((resolve, reject) => {
+ const id = ++seq;
+ pending.set(id, { resolve, reject });
+ const frame = new ArrayBuffer(16 + bytes.length);
+ const head = new DataView(frame);
+ head.setUint32(0, 0x4d424231); // "MBB1"
+ head.setUint32(4, id);
+ head.setUint16(8, channel);
+ head.setUint32(12, handle);
+ new Uint8Array(frame, 16).set(bytes);
+ port.postMessage(frame);
+ });
+ const writeChunk = (handle, chunk) => {
+ const bytes = bytesOf(chunk);
+ return BINARY ? sendBinary(SAVE_WRITE, handle, bytes) : call('save:write', handle, base64Of(bytes));
+ };
+ const pushSegment = (chunk) => {
+ const bytes = bytesOf(chunk);
+ return BINARY ? sendBinary(CAST_PUSH, 0, bytes) : call('cast:push', base64Of(bytes));
+ };
+
+ const meshbay = {
+ hubBase: () => HUB_BASE,
+ setHubBase: (base) => call('hub:set', base),
+
+ capabilities: {
+ nodeAdmin: false, // no node runs on a phone (§11.3)
+ localFolders: false,
+ nativeSave: true,
+ lanCast: CAST, // false where the vendor's play services are absent
+ tray: false,
+ },
+
+ setLocale: (code) => call('ui:locale', code),
+
+ // The page's origin is refused by the hub's absent CORS, and is not a
+ // credential anyway: native goes, to the signed-in hub only.
+ fetch: (url, init) => call('hub:fetch', url, init),
+
+ resolveStun: (urls) => call('ice:resolve-stun', urls),
+
+ // The device's hub key: generated, held and used natively. The page asks
+ // for a signature and never sees a key — it parses hostile input.
+ device: {
+ ensure: () => call('device:ensure'),
+ publicKey: () => call('device:public'),
+ sign: (username) => call('device:sign', username),
+ forget: () => call('device:forget'),
+ },
+
+ // The bundle key and the identity on every node, held natively: the page
+ // is told public keys and handed signatures and agreements. A signature is
+ // asked for by kind and fields, never by bytes.
+ keys: {
+ available: () => call('keys:available'),
+ deriveSession: (o) => call('keys:derive-session', o),
+ commitPending: (u) => call('keys:commit-pending', u),
+ dropPending: (u) => call('keys:drop-pending', u),
+ hasSession: (u) => call('keys:has-session', u),
+ forgetSession: (u) => call('keys:forget-session', u),
+ identity: (u, n) => call('keys:identity', u, n),
+ openBundle: (u, n, o) => call('keys:open-bundle', u, n, o),
+ mint: (u, n) => call('keys:mint', u, n),
+ sealBundle: (u, n, o) => call('keys:seal-bundle', u, n, o),
+ sealRecovery: (u, n, m, name) => call('keys:seal-recovery', u, n, m, name),
+ markSealed: (u, n, fp) => call('keys:mark-sealed', u, n, fp),
+ fingerprint: (u) => call('keys:fingerprint', u),
+ sign: (u, n, kind, fields) => call('keys:sign', u, n, kind, fields),
+ shared: (u, n, peer) => call('keys:shared', u, n, peer),
+ playlistKey: (u) => call('keys:playlist-key', u),
+ browserAccess: (u) => call('keys:browser-access', u),
+ setBrowserAccess: (u, on) => call('keys:set-browser-access', u, on),
+ createdHere: (u) => call('keys:created-here', u),
+ },
+
+ // Whether the OS protects what is stored. The store itself is not
+ // reachable from here.
+ secrets: {
+ backend: () => call('secrets:backend'),
+ },
+
+ // LAN cast relay: the page feeds it decrypted segments, a receiver on the
+ // same Wi-Fi plays from the URL. Present only where casting can work —
+ // `platform.cast.available` is whether this object exists.
+ ...(CAST ? { cast: {
+ start: (opts) => {
+ const o = Object.assign({}, opts || {});
+ if (o.initSegment) o.initSegment = base64Of(bytesOf(o.initSegment));
+ return call('cast:start', o);
+ },
+ push: (data) => pushSegment(data),
+ stop: () => call('cast:stop'),
+ subtitle: (sub) => call('cast:subtitle', sub),
+ // A whole file — a photo, a track — in pieces: one message the size of a
+ // lossless track would be the WebView's to refuse.
+ file: async (f) => {
+ const bytes = bytesOf(f.bytes);
+ const cover = f.cover ? { bytes: base64Of(bytesOf(f.cover.bytes)), type: f.cover.type } : null;
+ await call('cast:file:begin', { type: f.type, size: bytes.length, cover,
+ title: f.title, artist: f.artist, album: f.album });
+ for (let at = 0; at < bytes.length; at += FILE_PIECE) {
+ const piece = bytes.subarray(at, at + FILE_PIECE);
+ await (BINARY ? sendBinary(CAST_FILE, 0, piece) : call('cast:file:write', base64Of(piece)));
+ }
+ return call('cast:file:end');
+ },
+ finish: () => call('cast:finish'),
+ status: () => call('cast:status'),
+ scan: () => call('cast:scan'),
+ devices: () => call('cast:devices'),
+ chromecastConnect: (opts) => call('cast:chromecast:connect', opts),
+ chromecastReload: (opts) => call('cast:chromecast:reload', opts),
+ chromecastDisconnect: () => call('cast:chromecast:disconnect'),
+ chromecastPause: () => call('cast:chromecast:pause'),
+ chromecastPlay: () => call('cast:chromecast:play'),
+ chromecastSeek: (seconds) => call('cast:chromecast:seek', seconds),
+ } } : {}),
+
+ // Music is playing: keep the process, the Wi-Fi and the page awake with
+ // the screen off, behind a notification, until told otherwise.
+ playback: {
+ keepAlive: (on) => call('playback:keep-alive', on === true),
+ },
+
+ // Where downloads go, chosen once. A display name comes back, never a URI.
+ folder: {
+ choose: () => call('folder:choose'),
+ get: () => call('folder:get'),
+ forget: () => call('folder:forget'),
+ },
+
+ // A sink that writes to disk as chunks arrive, never a buffer handed over
+ // at the end. The page holds an id. `open` exists only where the target
+ // says the file may be opened — a type that runs nothing.
+ saveFile: async (suggestedName, opts) => {
+ const handle = await call('save:begin', suggestedName, opts);
+ if (!handle) return null;
+ const sink = {
+ name: handle.name,
+ write: (chunk) => writeChunk(handle.id, chunk),
+ close: () => call('save:end', handle.id),
+ abort: () => call('save:abort', handle.id),
+ };
+ if (handle.openable) sink.open = () => call('save:open', handle.id);
+ return sink;
+ },
+ };
+
+ const freeze = (o) => {
+ Object.freeze(o);
+ for (const v of Object.values(o)) if (v && typeof v === 'object' && !Object.isFrozen(v)) freeze(v);
+ return o;
+ };
+ Object.defineProperty(window, 'meshbay', {
+ value: freeze(meshbay), writable: false, configurable: false, enumerable: false,
+ });
+
+ // The WebView exposes File System Access and cannot back it with anything a
+ // person can see. Left in place, `downloads.SUPPORTED` reads true and a
+ // download could take a path that fails — or reach the blob floor silently.
+ for (const name of ['showDirectoryPicker', 'showSaveFilePicker', 'showOpenFilePicker']) {
+ try {
+ Object.defineProperty(window, name, { value: undefined, writable: false, configurable: false });
+ } catch (e) { /* not definable: leave it, native save comes first anyway */ }
+ }
+})();
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/MainActivity.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/MainActivity.kt
new file mode 100644
index 0000000..0fa63d6
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/MainActivity.kt
@@ -0,0 +1,322 @@
+package org.meshbay.client
+
+import android.app.Activity
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.os.Build
+import android.os.Bundle
+import android.os.SystemClock
+import android.util.Log
+import android.view.View
+import android.view.ViewGroup
+import android.view.ViewTreeObserver
+import android.view.WindowInsets
+import android.webkit.ConsoleMessage
+import android.webkit.PermissionRequest
+import android.webkit.WebChromeClient
+import android.webkit.WebResourceRequest
+import android.webkit.WebResourceResponse
+import android.webkit.WebView
+import android.widget.FrameLayout
+import androidx.webkit.ScriptHandler
+import androidx.webkit.WebViewAssetLoader
+import androidx.webkit.WebViewClientCompat
+import androidx.webkit.WebViewCompat
+import androidx.webkit.WebViewFeature
+import org.json.JSONObject
+import org.meshbay.client.bridge.Bridge
+import org.meshbay.client.bridge.Channels
+import org.meshbay.client.bridge.KeyChannels
+import org.meshbay.client.cast.CastChannels
+import org.meshbay.client.cast.CastService
+import org.meshbay.client.hub.HubClient
+import org.meshbay.client.keys.SecretStore
+import org.meshbay.client.save.SaveSinks
+import org.meshbay.client.shell.Pickers
+import org.meshbay.client.shell.ShellWebView
+import org.meshbay.client.shell.EngineCheck
+import org.meshbay.client.shell.NativeText
+import org.meshbay.client.shell.UiAssets
+import java.util.concurrent.CountDownLatch
+
+/**
+ * The shell: one WebView showing the packaged interface, and the bridge.
+ *
+ * What this file must never do: load anything into the WebView that is not the
+ * package (the hub never becomes the document origin — T3), or hand the page a
+ * way to the hub other than the bridge.
+ */
+class MainActivity : Activity() {
+ private lateinit var root: FrameLayout
+ private lateinit var web: ShellWebView
+ private lateinit var cast: CastChannels
+ private lateinit var hub: HubClient
+ private lateinit var channels: Channels
+ private val pickers = Pickers(this)
+ private val text = NativeText { code ->
+ try { assets.open("ui/locales/$code.js").bufferedReader().use { it.readText() } } catch (e: java.io.IOException) { null }
+ }
+ private var shim: ScriptHandler? = null
+ private var casting = false
+ private var playing = false
+ private var fullscreen: View? = null
+ private var fullscreenCallback: WebChromeClient.CustomViewCallback? = null
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ root = FrameLayout(this)
+ setContentView(root)
+ applyInsets(root)
+ if (savedInstanceState == null && Build.VERSION.SDK_INT >= 31) holdSplash()
+
+ // A WebView too old for the page's crypto would fail at the first
+ // handshake; say so before loading anything.
+ EngineCheck.problem(this)?.let { setContentView(EngineCheck.screen(this, it)); return }
+
+ hub = HubClient(getSharedPreferences("shell", Context.MODE_PRIVATE))
+ web = ShellWebView(this)
+ root.addView(web, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
+ configure(web)
+
+ val keys = KeyChannels(SecretStore(this), confirm = ::confirmNatively,
+ declined = { text.get("native.declined", channels.locale) })
+ val saves = SaveSinks(this, getSharedPreferences("downloads", Context.MODE_PRIVATE), pickers,
+ startActivity = { intent -> runOnUiThread { startActivity(intent) } })
+ // A process killed mid-download left unfinished files; nothing else will.
+ Thread { saves.cleanUpAfterAKilledProcess() }.start()
+ cast = CastChannels(this, onCasting = { on -> runOnUiThread { casting = on; keepAlive() } },
+ tell = { m -> runOnUiThread { android.widget.Toast.makeText(this, m, android.widget.Toast.LENGTH_LONG).show() } })
+ channels = Channels(hub, onHubChanged = { runOnUiThread { reloadForHub() } },
+ hasCatalogue = { code -> hasAsset("ui/locales/$code.js") }, keys = keys, saves = saves,
+ cast = cast, onPlayback = { on -> runOnUiThread { playing = on; keepAlive() } })
+ WebViewCompat.addWebMessageListener(web, Bridge.PORT, setOf(UiAssets.ORIGIN), Bridge(channels))
+ cast.control.warmUp()
+ installShim()
+ web.loadUrl(UiAssets.START)
+ }
+
+ private fun configure(web: WebView) {
+ WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG)
+ web.settings.apply {
+ javaScriptEnabled = true
+ domStorageEnabled = true // IndexedDB and localStorage: session, resume positions
+ allowFileAccess = false
+ allowContentAccess = false
+ // The page is our own bundled UI. With `true`, WebView wants play() inside the tap
+ // handler itself, and the music player only calls it after fetching the track.
+ mediaPlaybackRequiresUserGesture = false
+ setSupportMultipleWindows(false)
+ mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW
+ }
+ android.webkit.CookieManager.getInstance().setAcceptThirdPartyCookies(web, false)
+
+ val loader = WebViewAssetLoader.Builder()
+ .setDomain(UiAssets.HOST)
+ .addPathHandler(UiAssets.PREFIX, UiAssets(this))
+ .build()
+ web.webViewClient = object : WebViewClientCompat() {
+ override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
+ val url = request.url
+ if (url.host == UiAssets.HOST) return loader.shouldInterceptRequest(url) ?: refused()
+ // reCAPTCHA (sign-up) and nothing else goes to the network from
+ // the page; the policy says the same, this is the second wall.
+ if (UiAssets.isRecaptcha(url.host) && url.scheme == "https") return null
+ if (url.scheme == "blob" || url.scheme == "data") return null
+ return refused()
+ }
+
+ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
+ val url = request.url
+ if (url.host == UiAssets.HOST) return false
+ // The hub must never become the document origin. A link out
+ // opens in the person's browser, not in a window holding keys.
+ if (request.isForMainFrame && (url.scheme == "https" || url.scheme == "http")) openExternally(url)
+ return !(UiAssets.isRecaptcha(url.host) && !request.isForMainFrame)
+ }
+ }
+ web.webChromeClient = object : WebChromeClient() {
+ // Grant by enumeration: nothing. Camera, microphone, MIDI and
+ // whatever Chromium adds next arrive refused.
+ override fun onPermissionRequest(request: PermissionRequest) = request.deny()
+
+ // Without this, a video's requestFullscreen() never settles — a
+ // refusal that never rejects (CLAUDE.md). Measured in the spike.
+ override fun onShowCustomView(view: View, callback: CustomViewCallback) {
+ fullscreen?.let { root.removeView(it) }
+ fullscreen = view
+ fullscreenCallback = callback
+ root.addView(view, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
+ web.visibility = View.INVISIBLE
+ setFullscreenBars(true)
+ }
+
+ override fun onHideCustomView() {
+ fullscreen?.let { root.removeView(it) }
+ fullscreen = null
+ fullscreenCallback = null
+ web.visibility = View.VISIBLE
+ setFullscreenBars(false)
+ }
+
+ // <input type=file>: the system picker; the page reads what it is
+ // given through the File objects the WebView makes of the URIs.
+ // The callback is always answered, or the next chooser never opens.
+ override fun onShowFileChooser(view: WebView, callback: android.webkit.ValueCallback<Array<Uri>>,
+ params: FileChooserParams): Boolean {
+ val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*")
+ .putExtra(Intent.EXTRA_ALLOW_MULTIPLE, params.mode == FileChooserParams.MODE_OPEN_MULTIPLE)
+ Thread {
+ val result = pickers.run(intent)
+ // A single pick in multiple mode can come back with an
+ // empty clipData and the file in `data`: take whichever
+ // carries it, or the page receives a selection of nothing.
+ val uris = result?.let { r ->
+ val clip = r.clipData?.takeIf { it.itemCount > 0 }
+ clip?.let { c -> (0 until c.itemCount).map { c.getItemAt(it).uri } } ?: listOfNotNull(r.data)
+ }?.takeIf { it.isNotEmpty() }?.toTypedArray()
+ runOnUiThread { callback.onReceiveValue(uris) }
+ }.start()
+ return true
+ }
+
+ override fun onConsoleMessage(m: ConsoleMessage): Boolean {
+ if (BuildConfig.DEBUG) Log.i("MeshBayPage", "${m.messageLevel()} ${m.message()} @${m.sourceId()}:${m.lineNumber()}")
+ return true
+ }
+ }
+ }
+
+ /**
+ * The shim, with the hub address in it: the page reads that synchronously
+ * while its modules load. Changing the hub replaces the shim and reloads —
+ * a page left running would go on talking to the old hub with no sign of it.
+ */
+ private fun installShim() {
+ shim?.remove()
+ val source = assets.open("bridge/meshbay-bridge.js").bufferedReader().use { it.readText() }
+ val binary = WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_ARRAY_BUFFER)
+ val prelude = "const HUB_BASE = ${JSONObject.quote(hub.base)};\nconst BINARY = $binary;\n" +
+ "const CAST = ${cast.control.available()};\n"
+ shim = WebViewCompat.addDocumentStartJavaScript(web, "(function(){$prelude$source\n})();", setOf(UiAssets.ORIGIN))
+ }
+
+ private fun reloadForHub() {
+ installShim()
+ web.loadUrl(UiAssets.START)
+ }
+
+ /**
+ * A confirmation this process draws (main.js confirmNatively). Called from
+ * a bridge worker, never the UI thread, which it waits on. The keyboard is
+ * handed back to the page afterwards: after a dialog the document can stay
+ * unfocused and every keystroke go nowhere (CLAUDE.md, ask.js).
+ */
+ private fun confirmNatively(key: String): Boolean {
+ val done = CountDownLatch(1)
+ var accepted = false
+ runOnUiThread {
+ android.app.AlertDialog.Builder(this)
+ .setMessage(text.get(key, channels.locale))
+ .setPositiveButton(text.get("dialog.ok", channels.locale)) { _, _ -> accepted = true }
+ .setNegativeButton(text.get("dialog.cancel", channels.locale), null)
+ .setOnDismissListener { web.requestFocus(); done.countDown() }
+ .show()
+ }
+ done.await()
+ return accepted
+ }
+
+ @Deprecated("Activity results for the system pickers; the platform API, kept for minSdk 26.")
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ if (!pickers.deliver(requestCode, resultCode, data)) super.onActivityResult(requestCode, resultCode, data)
+ }
+
+ /**
+ * A cast, or music playing here, keeps the process, the Wi-Fi and the page
+ * alive with the screen off (spike S-2a, scenario F): the foreground service
+ * holds the first two, the WebView reported visible holds the third.
+ */
+ private fun keepAlive() {
+ val on = casting || playing
+ web.keepVisible = on
+ val service = Intent(this, CastService::class.java)
+ if (!on) { stopService(service); return }
+ service.putExtra(CastService.EXTRA_TEXT,
+ if (casting) "Casting on this Wi-Fi" else text.get("music.queue_title", channels.locale))
+ // Refused from the background on Android 12+; the page is then simply
+ // frozen with the screen off, as it was before this existed.
+ try { startForegroundService(service) } catch (e: IllegalStateException) { Log.w(Bridge.TAG, "keep-alive refused: $e") }
+ }
+
+ private fun hasAsset(path: String) = try { assets.open(path).close(); true } catch (e: java.io.IOException) { false }
+
+ private fun refused() = WebResourceResponse("text/plain", "utf-8", 403, "Forbidden", emptyMap(), "".byteInputStream())
+
+ private fun openExternally(url: Uri) {
+ try { startActivity(Intent(Intent.ACTION_VIEW, url).addCategory(Intent.CATEGORY_BROWSABLE)) }
+ catch (e: android.content.ActivityNotFoundException) { Log.w(Bridge.TAG, "no browser for $url") }
+ }
+
+ /**
+ * Android 12+ shows the launcher icon until the first frame is drawn, which
+ * on a warm process is a flash. Holding that frame keeps it up long enough
+ * to be seen; the WebView loads underneath in the meantime.
+ */
+ private fun holdSplash() {
+ val until = SystemClock.uptimeMillis() + SPLASH_MS
+ root.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
+ override fun onPreDraw(): Boolean {
+ if (SystemClock.uptimeMillis() < until) return false
+ root.viewTreeObserver.removeOnPreDrawListener(this)
+ return true
+ }
+ })
+ }
+
+ /** Edge-to-edge is enforced from Android 15: keep the page clear of the bars and the keyboard. */
+ private fun applyInsets(view: View) {
+ view.setOnApplyWindowInsetsListener { v, insets ->
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ val bars = if (fullscreen != null) android.graphics.Insets.NONE
+ else insets.getInsets(WindowInsets.Type.systemBars() or WindowInsets.Type.ime() or WindowInsets.Type.displayCutout())
+ v.setPadding(bars.left, bars.top, bars.right, bars.bottom)
+ } else {
+ @Suppress("DEPRECATION")
+ v.setPadding(insets.systemWindowInsetLeft, insets.systemWindowInsetTop,
+ insets.systemWindowInsetRight, insets.systemWindowInsetBottom)
+ }
+ insets
+ }
+ }
+
+ private fun setFullscreenBars(on: Boolean) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ val c = window.insetsController ?: return
+ if (on) {
+ c.hide(WindowInsets.Type.systemBars())
+ c.systemBarsBehavior = android.view.WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
+ } else c.show(WindowInsets.Type.systemBars())
+ }
+ root.requestApplyInsets()
+ }
+
+ @Deprecated("Back is handed to the page in phase 4; until then it leaves fullscreen or backgrounds the app.")
+ override fun onBackPressed() {
+ if (fullscreen != null) { fullscreenCallback?.onCustomViewHidden(); return }
+ if (web.canGoBack()) { web.goBack(); return }
+ // Never finish(): that would tear down every connection and transfer.
+ moveTaskToBack(true)
+ }
+
+ override fun onDestroy() {
+ if (::cast.isInitialized && cast.relay.active) cast.relay.stop()
+ if (casting || playing) { casting = false; playing = false; keepAlive() }
+ if (::web.isInitialized) { root.removeView(web); web.destroy() }
+ super.onDestroy()
+ }
+
+ companion object {
+ private const val SPLASH_MS = 500L
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Bridge.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Bridge.kt
new file mode 100644
index 0000000..50552fa
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Bridge.kt
@@ -0,0 +1,78 @@
+package org.meshbay.client.bridge
+
+import android.net.Uri
+import android.os.Handler
+import android.os.Looper
+import android.util.Log
+import android.webkit.WebView
+import androidx.webkit.JavaScriptReplyProxy
+import androidx.webkit.WebMessageCompat
+import androidx.webkit.WebViewCompat
+import org.json.JSONArray
+import org.json.JSONObject
+import org.meshbay.client.save.BinaryFrame
+import org.meshbay.client.shell.UiAssets
+import java.util.concurrent.Executors
+
+/**
+ * Everything the interface may ask of the application, and the only way in.
+ *
+ * `addWebMessageListener` injects `meshbayNative` only into documents of the
+ * packaged origin; the shim (assets/bridge/meshbay-bridge.js) takes it at
+ * document start and hides it. But a same-origin child frame gets one too — the
+ * spike measured it — so what actually confines the bridge is the check here:
+ * **the packaged origin's top-level document, and nothing else** (main.js
+ * `fromOurPage`). The page parses decrypted content from nodes, which is
+ * attacker-controlled input, so every argument is checked again in Channels.
+ */
+class Bridge(private val channels: Channels) : WebViewCompat.WebMessageListener {
+
+ private val main = Handler(Looper.getMainLooper())
+ // Hub calls and key operations block; none may run on the UI thread.
+ private val work = Executors.newCachedThreadPool()
+ private val serial = Executors.newSingleThreadExecutor()
+
+ override fun onPostMessage(view: WebView, message: WebMessageCompat, sourceOrigin: Uri,
+ isMainFrame: Boolean, replyProxy: JavaScriptReplyProxy) {
+ if (!isMainFrame || sourceOrigin.toString() != UiAssets.ORIGIN) {
+ Log.w(TAG, "refused a message from $sourceOrigin (main frame: $isMainFrame)")
+ val id = if (message.type == WebMessageCompat.TYPE_STRING)
+ try { JSONObject(message.data ?: "").optLong("id", -1) } catch (e: Exception) { -1 } else -1
+ replyProxy.postMessage(error(id, "Refused: not the MeshBay interface"))
+ return
+ }
+ if (message.type == WebMessageCompat.TYPE_ARRAY_BUFFER) {
+ val frame = BinaryFrame.parse(message.arrayBuffer) ?: return
+ dispatch(frame.id, replyProxy, "binary ${frame.channel}", channels.ordered(frame)) { channels.binary(frame) }
+ return
+ }
+ val request = try { JSONObject(message.data ?: return) } catch (e: Exception) { return }
+ val id = request.optLong("id", -1)
+ val channel = request.optString("ch")
+ val args = request.optJSONArray("args") ?: JSONArray()
+ dispatch(id, replyProxy, channel, channels.ordered(channel)) { channels.call(channel, args) }
+ }
+
+ private fun dispatch(id: Long, replyProxy: JavaScriptReplyProxy, channel: String, ordered: Boolean,
+ call: () -> Any?) {
+ (if (ordered) serial else work).execute {
+ val reply = try {
+ JSONObject().put("id", id).put("ok", true).put("value", call() ?: JSONObject.NULL).toString()
+ } catch (e: Refused) {
+ error(id, e.message ?: "Refused")
+ } catch (e: Exception) {
+ Log.w(TAG, "$channel failed", e)
+ error(id, e.message ?: e.javaClass.simpleName)
+ }
+ main.post { replyProxy.postMessage(reply) }
+ }
+ }
+
+ private fun error(id: Long, message: String) =
+ JSONObject().put("id", id).put("ok", false).put("error", message).toString()
+
+ companion object {
+ const val TAG = "MeshBay"
+ const val PORT = "meshbayNative"
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Channels.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Channels.kt
new file mode 100644
index 0000000..f7094a0
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Channels.kt
@@ -0,0 +1,107 @@
+package org.meshbay.client.bridge
+
+import org.json.JSONArray
+import org.meshbay.client.cast.CastChannels
+import org.meshbay.client.hub.HubClient
+import org.meshbay.client.save.BinaryFrame
+import org.meshbay.client.save.SaveSinks
+import java.net.Inet4Address
+import java.net.InetAddress
+
+/**
+ * The enumerated channels, and nothing else (main.js `registerBridge`).
+ *
+ * A channel that takes a path, a URL to anywhere, or bytes to sign from the
+ * page is the shape to avoid. What the desktop offers and a phone does not —
+ * the local node, shared folders, the tray — is not here at all, and the shim
+ * does not offer it either: `platform.js` decides what to show from whether a
+ * bridge object exists, so an object that only refused would put screens on
+ * the page that fail when used.
+ */
+class Channels(
+ private val hub: HubClient,
+ private val onHubChanged: () -> Unit,
+ private val hasCatalogue: (String) -> Boolean,
+ private val keys: KeyChannels? = null,
+ private val saves: SaveSinks? = null,
+ private val cast: CastChannels? = null,
+ private val onPlayback: (Boolean) -> Unit = {},
+) {
+ @Volatile var locale = "en"
+ private set
+
+ fun call(channel: String, args: JSONArray): Any? = when (channel) {
+ "hub:set" -> hub.setBase(args.optString(0, "")).also { onHubChanged() }
+ "hub:fetch" -> hub.fetch(args.optString(0, ""), args.optJSONObject(1))
+ "ice:resolve-stun" -> resolveStun(args.optJSONArray(0) ?: JSONArray())
+ "ui:locale" -> setLocale(args.optString(0, ""))
+ "playback:keep-alive" -> { onPlayback(args.optBoolean(0, false)); true }
+
+ // Where downloads go, chosen once; a display name, never a URI.
+ "folder:choose" -> saves().chooseFolder()
+ "folder:get" -> saves().getFolder()
+ "folder:forget" -> saves().forgetFolder()
+ // A sink the page refers to by an opaque id.
+ "save:begin" -> saves().begin(args.optString(0, ""), args.optJSONObject(1)?.optBoolean("auto", false) ?: false)
+ "save:write" -> { // the base64 path, for a WebView without ArrayBuffer messages
+ val bytes = java.util.Base64.getDecoder().decode(args.optString(1, ""))
+ saves().write(args.optLong(0, -1), bytes, 0, bytes.size)
+ }
+ "save:end" -> saves().end(args.optLong(0, -1))
+ "save:abort" -> saves().abort(args.optLong(0, -1))
+ "save:open" -> saves().open(args.optLong(0, -1))
+ else -> when {
+ keys != null && keys.handles(channel) -> keys.call(channel, args)
+ cast != null && cast.handles(channel) -> cast.call(channel, args)
+ else -> throw Refused("Refused: no such channel")
+ }
+ }
+
+ private fun saves() = saves ?: throw Refused("Refused: no such channel")
+
+ /** A binary message: one write, its bytes left where the message put them. */
+ fun binary(frame: BinaryFrame): Any? = when (frame.channel) {
+ BinaryFrame.SAVE_WRITE -> saves().write(frame.handle, frame.bytes, frame.offset, frame.length)
+ BinaryFrame.CAST_PUSH -> (cast ?: throw Refused("Refused: no such channel")).push(frame.bytes, frame.offset, frame.length)
+ BinaryFrame.CAST_FILE -> (cast ?: throw Refused("Refused: no such channel")).writeFile(frame.bytes, frame.offset, frame.length)
+ else -> throw Refused("Refused: no such channel")
+ }
+
+ /**
+ * Calls whose order is part of their meaning: a relay start, the segments
+ * pushed after it, a stop. The page does not await each push, so on a pool
+ * they could overtake one another; these run on one thread, in arrival order.
+ */
+ fun ordered(channel: String) = cast?.ordered(channel) == true
+ fun ordered(frame: BinaryFrame) = frame.channel == BinaryFrame.CAST_PUSH || frame.channel == BinaryFrame.CAST_FILE
+
+ private fun setLocale(code: String): String {
+ // A code, never text, and only one the package has a catalogue for.
+ if (LOCALE.matches(code) && hasCatalogue(code)) locale = code
+ return locale
+ }
+
+ companion object {
+ private val LOCALE = Regex("^[a-z]{2}(-[A-Z]{2})?$")
+ private val STUN = Regex("^(stuns?):(\\[?[^\\]]+\\]?|[^:]+):(\\d+)$")
+
+ /**
+ * `stun:host:port` → `stun:ip:port`. Chromium's socket manager fails
+ * STUN hostnames outright behind some resolvers, and the page cannot do
+ * DNS. Unresolvable entries are dropped, literals pass through.
+ */
+ fun resolveStun(urls: JSONArray, lookup: (String) -> Array<InetAddress> = InetAddress::getAllByName): JSONArray {
+ val out = JSONArray()
+ for (i in 0 until urls.length()) {
+ val u = urls.optString(i)
+ val m = STUN.matchEntire(u)
+ if (m == null) { out.put(u); continue }
+ val (scheme, host, port) = m.destructured
+ if (Regex("^[\\d.]+$").matches(host) || host.contains(':')) { out.put(u); continue }
+ val ip = try { lookup(host).firstOrNull { it is Inet4Address }?.hostAddress } catch (e: Exception) { null }
+ if (ip != null) out.put("$scheme:$ip:$port")
+ }
+ return out
+ }
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/KeyChannels.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/KeyChannels.kt
new file mode 100644
index 0000000..f11b98c
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/KeyChannels.kt
@@ -0,0 +1,117 @@
+package org.meshbay.client.bridge
+
+import org.json.JSONArray
+import org.json.JSONObject
+import org.meshbay.client.keys.DeviceKey
+import org.meshbay.client.keys.Keyring
+import org.meshbay.client.keys.SecretStore
+import org.meshbay.client.keys.Secrets
+
+/**
+ * The device key, the account's bundle key and its identity on every node —
+ * held here, never in the page (§8.2, §14.1 #20). The page is answered with
+ * public keys, signatures and agreements; it names what it signs by kind and
+ * fields, never by bytes (Transcripts). Arguments are checked as main.js does:
+ * ids are ids, keys are keys.
+ *
+ * `confirm` is a dialog this process draws, worded from the interface's own
+ * catalogues: what widens what leaves this device is never answered by the
+ * page.
+ */
+class KeyChannels(
+ private val secrets: Secrets,
+ private val confirm: (String) -> Boolean,
+ private val declined: () -> String,
+) {
+ private val device = DeviceKey(secrets)
+ val keyring = Keyring(
+ load = {
+ val raw = secrets.read().optString(SecretStore.KEYRING_SLOT, "")
+ if (raw.isEmpty()) null else try { JSONObject(raw) } catch (e: Exception) { null }
+ },
+ save = { state -> secrets.update { it.put(SecretStore.KEYRING_SLOT, state.toString()) } },
+ )
+
+ // Only where the OS protects what is stored: an identity kept here and lost
+ // at the next start would leave a node pinning a key nobody holds, so
+ // without key storage the page keeps its keys the way a browser does.
+ private fun available() = secrets.backend() != "unavailable"
+ private fun needKeys() { if (!available()) throw Refused("No OS key storage") }
+
+ fun handles(channel: String) = channel.startsWith("keys:") || channel.startsWith("device:") ||
+ channel == "secrets:backend"
+
+ fun call(channel: String, a: JSONArray): Any? = when (channel) {
+ "secrets:backend" -> secrets.backend()
+
+ "device:ensure" -> device.ensure()
+ "device:public" -> device.publicKey()
+ "device:sign" -> device.sign(a.optString(0, ""))
+ "device:forget" -> device.forget()
+
+ "keys:available" -> available()
+ "keys:derive-session" -> {
+ needKeys()
+ val o = a.optJSONObject(0) ?: JSONObject()
+ keyring.deriveSession(
+ password = o.optString("password", ""), username = o.optString("username", ""),
+ userId = uid(o.opt("userId")), pepperB64 = o.optString("pepperB64", ""),
+ pepperVersion = o.optInt("pepperVersion", 1).takeIf { it != 0 } ?: 1,
+ pendingChange = o.optBoolean("pending", false))
+ }
+ "keys:commit-pending" -> keyring.commitPending(uid(a.opt(0)))
+ "keys:drop-pending" -> keyring.dropPending(uid(a.opt(0)))
+ "keys:has-session" -> available() && keyring.hasSession(uid(a.opt(0)))
+ "keys:forget-session" -> keyring.forgetSession(uid(a.opt(0)))
+ "keys:identity" -> keyring.identity(uid(a.opt(0)), npk(a.opt(1)))?.let {
+ JSONObject().put("pkEdB64", it.pkEdB64).put("pkXB64", it.pkXB64).put("sealedWith", it.sealedWith ?: JSONObject.NULL)
+ }
+ "keys:open-bundle" -> pub(keyring.openBundle(uid(a.opt(0)), npk(a.opt(1)),
+ bundleEnc = a.optJSONObject(2)?.optString("bundleEnc", "") ?: ""))
+ "keys:mint" -> { needKeys(); pub(keyring.mint(uid(a.opt(0)), npk(a.opt(1)))) }
+ "keys:seal-bundle" -> keyring.sealBundle(uid(a.opt(0)), npk(a.opt(1)),
+ usePending = a.optJSONObject(2)?.optBoolean("pending", false) ?: false).let {
+ JSONObject().put("bundle", it.bundle).put("fingerprint", it.fingerprint)
+ }
+ "keys:seal-recovery" -> keyring.sealRecovery(uid(a.opt(0)), npk(a.opt(1)), a.optString(2, ""), a.optString(3, ""))
+ "keys:mark-sealed" -> keyring.markSealed(uid(a.opt(0)), npk(a.opt(1)), a.optString(2, ""))
+ "keys:fingerprint" -> keyring.currentFingerprint(uid(a.opt(0)))
+ // By kind and fields: the page never names the bytes.
+ "keys:sign" -> keyring.signAs(uid(a.opt(0)), npk(a.opt(1)), a.optString(2, ""), a.optJSONObject(3) ?: JSONObject())
+ "keys:shared" -> keyring.shared(uid(a.opt(0)), npk(a.opt(1)), a.optString(2, ""))
+ "keys:playlist-key" -> keyring.playlistKey(uid(a.opt(0)))
+ "keys:browser-access" -> keyring.browserAccess(uid(a.opt(0)))
+ // Turning it on leaves this account's identities on every node, sealed
+ // for a browser: the person decides that here, in a dialog the page
+ // cannot answer. Turning it off only narrows.
+ "keys:set-browser-access" -> {
+ val id = uid(a.opt(0))
+ val on = a.optBoolean(1, false)
+ if (on && !keyring.browserAccess(id) && !confirm("native.browser_access_confirm")) throw Refused(declined())
+ keyring.setBrowserAccess(id, on)
+ }
+ // An account created on this device starts without browser access.
+ // Only ever narrows, so the page may say it.
+ "keys:created-here" -> keyring.setBrowserAccess(uid(a.opt(0)), false)
+ else -> throw Refused("Refused: no such channel")
+ }
+
+ private fun pub(p: Keyring.Pub) = JSONObject().put("pkEdB64", p.pkEdB64).put("pkXB64", p.pkXB64)
+
+ companion object {
+ private val UID = Regex("^[0-9a-f-]{36}$", RegexOption.IGNORE_CASE)
+ private val NPK = Regex("^[A-Za-z0-9+/=]{1,100}$")
+
+ fun uid(v: Any?): String {
+ val s = if (v == null || v == JSONObject.NULL) "" else v.toString()
+ if (!UID.matches(s)) throw Refused("Refused: not an account id")
+ return s
+ }
+
+ fun npk(v: Any?): String {
+ val s = if (v == null || v == JSONObject.NULL) "" else v.toString()
+ if (!NPK.matches(s)) throw Refused("Refused: not a node's key")
+ return s
+ }
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Refused.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Refused.kt
new file mode 100644
index 0000000..6f550a5
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Refused.kt
@@ -0,0 +1,4 @@
+package org.meshbay.client.bridge
+
+/** A refusal whose message is written for a person; it reaches the page as is. */
+class Refused(message: String) : Exception(message)
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/BoxAccumulator.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/BoxAccumulator.kt
new file mode 100644
index 0000000..f56d58a
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/BoxAccumulator.kt
@@ -0,0 +1,87 @@
+package org.meshbay.client.cast
+
+import android.util.Log
+import java.io.ByteArrayOutputStream
+
+/**
+ * Re-frames the page's byte stream into whole moof+mdat fragments, which is
+ * what a receiver needs. A port of cast-relay.js's BoxAccumulator: the chunks
+ * the page pushes are arbitrary slices of the fMP4 stream, not box-aligned.
+ */
+class BoxAccumulator {
+ private var buf = ByteArray(0)
+ private var synced = false
+ private var preambleSeen = false
+
+ /**
+ * Called once, with every byte before the first moof: the stream's header
+ * (ftyp, moov), however many pushes it came in. The node's first chunk can
+ * hold the 28-byte ftyp alone, with the moov in the next one (measured).
+ */
+ var onPreamble: ((ByteArray) -> Unit)? = null
+
+ fun push(data: ByteArray, offset: Int = 0, length: Int = data.size - offset): List<ByteArray> {
+ buf = buf + data.copyOfRange(offset, offset + length)
+ val fragments = ArrayList<ByteArray>()
+
+ if (!synced) {
+ val idx = findMoof()
+ if (idx == -1) return fragments
+ if (!preambleSeen) { preambleSeen = true; onPreamble?.invoke(buf.copyOfRange(0, idx)) }
+ buf = buf.copyOfRange(idx, buf.size)
+ synced = true
+ }
+
+ while (buf.size >= 8) {
+ val size = u32(buf, 0)
+ val type = u32(buf, 4)
+
+ if (size < 8) {
+ // The byte stream stopped being framed fMP4. It recovers by
+ // rescanning, and this line is the only trace that the picture
+ // on the television is missing a piece.
+ warn("box sync lost: invalid size $size, rescanning")
+ synced = false
+ val idx = findMoof()
+ if (idx == -1) return fragments
+ buf = buf.copyOfRange(idx, buf.size)
+ synced = true
+ continue
+ }
+
+ if (type == MOOF) {
+ if (buf.size < size + 8) break
+ val mdat = u32(buf, size.toInt())
+ val pair = size + mdat
+ if (buf.size < pair) break
+ fragments.add(buf.copyOfRange(0, pair.toInt()))
+ buf = buf.copyOfRange(pair.toInt(), buf.size)
+ } else {
+ if (buf.size < size) break
+ buf = buf.copyOfRange(size.toInt(), buf.size)
+ }
+ }
+ return fragments
+ }
+
+ fun reset() { buf = ByteArray(0); synced = false; preambleSeen = false }
+
+ private fun findMoof(): Int {
+ for (i in 0..buf.size - 8) {
+ if (u32(buf, i + 4) == MOOF) {
+ val size = u32(buf, i)
+ if (size >= 8 && size < 1_000_000) return i
+ }
+ }
+ return -1
+ }
+
+ companion object {
+ const val MOOF = 0x6d6f6f66L
+ var warn: (String) -> Unit = { try { Log.w("MeshBay", "[cast-relay] $it") } catch (e: RuntimeException) { System.err.println(it) } }
+
+ fun u32(b: ByteArray, at: Int): Long =
+ ((b[at].toLong() and 0xff) shl 24) or ((b[at + 1].toLong() and 0xff) shl 16) or
+ ((b[at + 2].toLong() and 0xff) shl 8) or (b[at + 3].toLong() and 0xff)
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastChannels.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastChannels.kt
new file mode 100644
index 0000000..edaec67
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastChannels.kt
@@ -0,0 +1,152 @@
+package org.meshbay.client.cast
+
+import android.content.Context
+import android.net.ConnectivityManager
+import android.net.NetworkCapabilities
+import org.json.JSONArray
+import org.json.JSONObject
+import org.meshbay.client.bridge.Refused
+import java.net.Inet4Address
+import java.net.InetAddress
+import java.util.Base64
+
+/**
+ * main.js `cast:*`: the relay, the receiver, and what keeps both alive.
+ *
+ * `onCasting(true)` is called once the relay is up (start the foreground
+ * service, keep the WebView visible), `onCasting(false)` once it is down.
+ */
+class CastChannels(
+ private val context: Context,
+ private val onCasting: (Boolean) -> Unit,
+ private val tell: (String) -> Unit = {},
+) {
+ val control = CastControl(context)
+ val relay = CastRelay(::lanAddress, java.io.File(context.cacheDir, "cast-relay"))
+
+ fun handles(channel: String) = channel.startsWith("cast:")
+
+ /** What must reach the relay in the order the page sent it: start, pushes, subtitle, a file's pieces, finish, stop. */
+ fun ordered(channel: String) = channel in setOf("cast:start", "cast:push", "cast:subtitle",
+ "cast:file:begin", "cast:file:write", "cast:file:end", "cast:finish", "cast:stop")
+
+ fun call(channel: String, a: JSONArray): Any? = when (channel) {
+ "cast:start" -> {
+ val o = a.optJSONObject(0) ?: JSONObject()
+ val init = o.optString("initSegment", "").takeIf { it.isNotEmpty() }?.let { Base64.getDecoder().decode(it) }
+ val started = relay.start(init, o.optJSONObject("subtitle"))
+ onCasting(true)
+ started
+ }
+ "cast:subtitle" -> relay.setSubtitle(a.optJSONObject(0))
+ // A whole file — a photo, a track — in pieces. No foreground service
+ // for one: a photo needs nothing once loaded, and music keeps the page
+ // alive through its own playback hold.
+ "cast:file:begin" -> {
+ val o = a.optJSONObject(0) ?: JSONObject()
+ val cover = o.optJSONObject("cover")
+ relay.beginFile(o.optString("type", ""), o.optLong("size", -1),
+ cover?.optString("bytes", "")?.takeIf { it.isNotEmpty() }?.let { Base64.getDecoder().decode(it) },
+ cover?.optString("type", ""), o)
+ }
+ "cast:file:write" -> { // the base64 path, for a WebView without ArrayBuffer messages
+ relay.writeFile(Base64.getDecoder().decode(a.optString(0, "")))
+ }
+ "cast:file:end" -> relay.endFile()
+ "cast:push" -> { // the base64 path, for a WebView without ArrayBuffer messages
+ relay.push(Base64.getDecoder().decode(a.optString(0, ""))); true
+ }
+ "cast:stop" -> { relay.stop(); onCasting(false); true }
+ "cast:finish" -> { relay.finish(); true }
+ "cast:status" -> JSONObject().put("active", relay.active).put("url", relay.url ?: JSONObject.NULL)
+ .put("subtitle", relay.subtitleInfo() ?: JSONObject.NULL).put("chromecast", control.status())
+
+ "cast:scan" -> { control.startScan(); true }
+ "cast:devices" -> control.devices()
+ "cast:chromecast:connect" -> {
+ val o = a.optJSONObject(0) ?: JSONObject()
+ val url = relayUrl(o)
+ reported { control.connect(o.optString("deviceId", ""), url, subtitleFor(url, o), fileOf(url), startOf(url, o)) }
+ }
+ "cast:chromecast:reload" -> {
+ val o = a.optJSONObject(0) ?: JSONObject()
+ val url = relayUrl(o)
+ reported { control.reload(url, subtitleFor(url, o), fileOf(url), startOf(url, o)) }
+ }
+ "cast:chromecast:pause" -> control.pause()
+ "cast:chromecast:play" -> control.play()
+ "cast:chromecast:seek" -> control.seek(a.optDouble(0, 0.0))
+ "cast:chromecast:disconnect" -> control.disconnect()
+ else -> throw Refused("Refused: no such channel")
+ }
+
+ /**
+ * A failed cast says why, on the screen. The player catches the error and
+ * stops the relay without a word, which leaves the television on the
+ * receiver's idle screen and nobody knowing whether it ever reached the
+ * phone — so the receiver's reason and that fact are shown here.
+ */
+ private fun <T> reported(block: () -> T): T = try { block() } catch (e: Exception) {
+ val reached = if (relay.streamRequests > 0) "the television did reach this phone"
+ else "the television never reached this phone at ${relay.url?.substringBefore("/stream") ?: "?"}"
+ tell("Cast failed: ${e.message} — $reached")
+ throw e
+ }
+
+ fun push(bytes: ByteArray, offset: Int, length: Int): Boolean { relay.push(bytes, offset, length); return true }
+
+ fun writeFile(bytes: ByteArray, offset: Int, length: Int): Boolean = relay.writeFile(bytes, offset, length)
+
+ /**
+ * The receiver is only ever pointed at this relay. A URL the page names is
+ * accepted when it is the relay's own stream or file, and refused
+ * otherwise — a page cannot use this application to make a television
+ * fetch anything else.
+ */
+ private fun relayUrl(o: JSONObject): String {
+ val asked = o.optString("mediaUrl", "")
+ val ours = relay.url ?: throw Refused("The cast relay is not running")
+ if (asked != ours && asked != relay.fileUrl) throw Refused("Refused: not this relay's stream")
+ return asked
+ }
+
+ /**
+ * The relay's file is loaded as what the relay says it is — its type, and
+ * the title, artist, album and cover it was given — and anything else as
+ * the stream (null here); the page does not say which.
+ */
+ private fun fileOf(url: String): JSONObject? =
+ if (url != relay.fileUrl) null
+ else JSONObject().put("contentType", relay.fileType).put("meta", relay.fileMeta() ?: JSONObject())
+
+ /** Where in a track to begin; a film starts where its relay does. */
+ private fun startOf(url: String, o: JSONObject): Double =
+ if (url == relay.fileUrl) maxOf(0.0, o.optDouble("startAt", 0.0)) else 0.0
+
+ /** As main.js: no subtitle named means the relay's current one; a file has none. */
+ private fun subtitleFor(url: String, o: JSONObject): JSONObject? = when {
+ url == relay.fileUrl -> null
+ o.has("subtitle") && o.get("subtitle") != JSONObject.NULL -> o.optJSONObject("subtitle")
+ else -> relay.subtitleInfo()
+ }
+
+ /**
+ * The Wi-Fi (or Ethernet) address, never the mobile network's: a TV cannot
+ * be reached there. Nor a VPN's: a VPN network carries the transports of
+ * the network under it, Wi-Fi included, and its address is a tunnel the
+ * television cannot route to.
+ */
+ private fun lanAddress(): InetAddress? {
+ val cm = context.getSystemService(ConnectivityManager::class.java)
+ for (network in cm.allNetworks) {
+ val caps = cm.getNetworkCapabilities(network) ?: continue
+ if (caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) continue
+ if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
+ !caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) continue
+ val addr = cm.getLinkProperties(network)?.linkAddresses?.map { it.address }
+ ?.firstOrNull { it is Inet4Address && !it.isLoopbackAddress }
+ if (addr != null) return addr
+ }
+ return null
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastControl.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastControl.kt
new file mode 100644
index 0000000..0d18a90
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastControl.kt
@@ -0,0 +1,405 @@
+package org.meshbay.client.cast
+
+import android.content.Context
+import android.graphics.Color
+import android.net.Uri
+import android.os.Handler
+import android.os.Looper
+import android.util.Log
+import androidx.mediarouter.media.MediaRouteSelector
+import androidx.mediarouter.media.MediaRouter
+import com.google.android.gms.cast.CastMediaControlIntent
+import com.google.android.gms.cast.MediaInfo
+import com.google.android.gms.cast.MediaLoadRequestData
+import com.google.android.gms.cast.MediaMetadata
+import com.google.android.gms.cast.MediaSeekOptions
+import com.google.android.gms.common.images.WebImage
+import com.google.android.gms.cast.MediaStatus
+import com.google.android.gms.cast.MediaTrack
+import com.google.android.gms.cast.TextTrackStyle
+import com.google.android.gms.cast.framework.CastContext
+import com.google.android.gms.cast.framework.CastOptions
+import com.google.android.gms.cast.framework.CastSession
+import com.google.android.gms.cast.framework.OptionsProvider
+import com.google.android.gms.cast.framework.SessionManagerListener
+import com.google.android.gms.common.ConnectionResult
+import com.google.android.gms.common.GoogleApiAvailability
+import org.json.JSONArray
+import org.json.JSONObject
+import org.meshbay.client.bridge.Refused
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+
+/**
+ * Discovery and control of a receiver — what cast-chromecast.js does with mDNS
+ * and the cast protocol client, done here with the platform's cast sender SDK
+ * and MediaRouter. The page keeps its own picker: it polls `devices()` while a
+ * scan runs and receivers are listed as they answer.
+ *
+ * The default media receiver: no receiver registration. Needs the vendor's
+ * play services; where they are absent `available()` is false and the page
+ * offers no cast button rather than one that fails.
+ */
+class CastControl(private val context: Context) {
+ private val main = Handler(Looper.getMainLooper())
+ private val devices = ConcurrentHashMap<String, String>()
+ @Volatile private var scanning = false
+ @Volatile private var deviceName: String? = null
+ private var router: MediaRouter? = null
+ private val selector by lazy {
+ MediaRouteSelector.Builder()
+ .addControlCategory(CastMediaControlIntent.categoryForCast(CastMediaControlIntent.DEFAULT_MEDIA_RECEIVER_APPLICATION_ID))
+ .build()
+ }
+
+ private val routes = object : MediaRouter.Callback() {
+ override fun onRouteAdded(r: MediaRouter, route: MediaRouter.RouteInfo) = note(route)
+ override fun onRouteChanged(r: MediaRouter, route: MediaRouter.RouteInfo) = note(route)
+ override fun onRouteRemoved(r: MediaRouter, route: MediaRouter.RouteInfo) { devices.remove(route.id) }
+ }
+
+ private fun note(route: MediaRouter.RouteInfo) {
+ if (!route.isDefault && route.isEnabled && route.matchesSelector(selector)) devices[route.id] = route.name
+ }
+
+ fun available(): Boolean = try {
+ GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS
+ } catch (e: Exception) { false }
+
+ private fun need() { if (!available()) throw Refused("Casting is not available on this device") }
+
+ /**
+ * Create the cast context at launch, as the SDK asks. Created only at the
+ * first connect, it was born in the same moment the route was selected,
+ * and the session started without the listener hearing of it: on a fresh
+ * start the first cast timed out, every time (measured).
+ */
+ fun warmUp() {
+ if (!available()) return
+ try { onMain { CastContext.getSharedInstance(context) } } catch (e: Exception) { Log.w(TAG, "cast context", e) }
+ }
+
+ private fun <T> onMain(timeoutS: Long = 10, block: () -> T): T {
+ if (Looper.myLooper() == Looper.getMainLooper()) return block()
+ val done = CountDownLatch(1)
+ var value: Result<T>? = null
+ main.post { value = runCatching(block); done.countDown() }
+ if (!done.await(timeoutS, TimeUnit.SECONDS)) throw IllegalStateException("the cast service did not answer")
+ return value!!.getOrThrow()
+ }
+
+ /** Start a scan and return at once; `devices()` reads what it has found so far. */
+ fun startScan() {
+ need()
+ onMain {
+ val r = router ?: MediaRouter.getInstance(context).also { router = it }
+ devices.clear()
+ r.removeCallback(routes)
+ r.addCallback(selector, routes, MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN)
+ r.routes.forEach(::note)
+ scanning = true
+ main.removeCallbacksAndMessages(SCAN_TOKEN)
+ main.postAtTime({
+ // Keep listening for changes, stop the active (radio-costly) scan.
+ r.addCallback(selector, routes, 0)
+ scanning = false
+ }, SCAN_TOKEN, android.os.SystemClock.uptimeMillis() + SCAN_DURATION_MS)
+ }
+ }
+
+ fun devices(): JSONObject {
+ val list = JSONArray()
+ for ((id, name) in devices) list.put(JSONObject().put("id", id).put("name", name))
+ return JSONObject().put("devices", list).put("scanning", scanning)
+ }
+
+ /** Connect, launch the default receiver, load; answers once the receiver has. */
+ fun connect(deviceId: String, mediaUrl: String, subtitle: JSONObject?, file: JSONObject? = null, startAt: Double = 0.0): JSONObject {
+ need()
+ val session = onMain {
+ val cast = CastContext.getSharedInstance(context)
+ val r = router ?: MediaRouter.getInstance(context).also { router = it }
+ val route = r.routes.firstOrNull { it.id == deviceId } ?: throw Refused("Unknown device: $deviceId")
+ cast.sessionManager.currentCastSession?.takeIf { it.isConnected }?.let { return@onMain it }
+ val started = CountDownLatch(1)
+ var result: CastSession? = null
+ val listener = object : SessionManagerListener<CastSession> {
+ override fun onSessionStarted(s: CastSession, id: String) { result = s; started.countDown() }
+ override fun onSessionStartFailed(s: CastSession, error: Int) {
+ Log.w(TAG, "session start failed: error=$error")
+ started.countDown()
+ }
+ override fun onSessionStarting(s: CastSession) {}
+ override fun onSessionEnding(s: CastSession) {}
+ override fun onSessionEnded(s: CastSession, error: Int) {}
+ override fun onSessionResuming(s: CastSession, id: String) {}
+ override fun onSessionResumed(s: CastSession, wasSuspended: Boolean) { result = s; started.countDown() }
+ override fun onSessionResumeFailed(s: CastSession, error: Int) {}
+ override fun onSessionSuspended(s: CastSession, reason: Int) {}
+ }
+ cast.sessionManager.addSessionManagerListener(listener, CastSession::class.java)
+ Log.i(TAG, "connect: selecting route '${route.name}'")
+ r.selectRoute(route)
+ deviceName = route.name
+ Pending(started, { result }, { cast.sessionManager.removeSessionManagerListener(listener, CastSession::class.java) })
+ }.let { s ->
+ when (s) {
+ is CastSession -> s
+ is Pending -> try {
+ // The listener, or the session manager itself: a started
+ // session the listener missed is still a started session.
+ val deadline = System.currentTimeMillis() + 15_000
+ var found: CastSession? = null
+ while (found == null && System.currentTimeMillis() < deadline) {
+ if (s.done.await(300, TimeUnit.MILLISECONDS)) {
+ found = s.session() ?: throw IllegalStateException("The receiver refused the connection")
+ } else {
+ found = onMain {
+ CastContext.getSharedInstance(context).sessionManager.currentCastSession
+ ?.takeIf { it.isConnected }
+ }
+ if (found != null) Log.i(TAG, "session found connected without its callback")
+ }
+ }
+ found ?: throw IllegalStateException("Connection timeout")
+ } finally { main.post { s.cleanup() } }
+ else -> throw IllegalStateException()
+ }
+ }
+ // The cast framework's objects answer on the main thread only, the
+ // device's name included: read it there, never from this worker.
+ val name = deviceName ?: onMain { session.castDevice?.friendlyName }
+ Log.i(TAG, "session up on '$name', loading the relay stream")
+ val state = load(session, mediaUrl, subtitle, file, startAt)
+ watch(session)
+ return JSONObject().put("deviceName", name ?: JSONObject.NULL).put("playerState", state)
+ }
+
+ private class Pending(val done: CountDownLatch, val session: () -> CastSession?, val cleanup: () -> Unit)
+
+ /**
+ * What the receiver does for the whole film, not only at the start: a
+ * freeze on the television is a BUFFERING the phone never hears about
+ * otherwise. Logged with the position, on the main thread the SDK wants.
+ */
+ private var watched: com.google.android.gms.cast.framework.media.RemoteMediaClient? = null
+ private val watcher = object : com.google.android.gms.cast.framework.media.RemoteMediaClient.Callback() {
+ private var last = -1
+ override fun onStatusUpdated() {
+ val c = watched ?: return
+ val state = c.playerState
+ if (state == last) return
+ last = state
+ Log.i(TAG, "receiver state ${stateName(state)} at ${c.approximateStreamPosition / 1000.0}s" +
+ (if (state == MediaStatus.PLAYER_STATE_IDLE) " (idle: ${idleName(c.idleReason)})" else ""))
+ }
+ }
+
+ private fun watch(session: CastSession) = onMain {
+ val c = session.remoteMediaClient ?: return@onMain
+ if (watched === c) return@onMain
+ watched?.unregisterCallback(watcher)
+ c.registerCallback(watcher)
+ watched = c
+ }
+
+ fun reload(mediaUrl: String, subtitle: JSONObject?, file: JSONObject? = null, startAt: Double = 0.0): JSONObject {
+ need()
+ val session = onMain { CastContext.getSharedInstance(context).sessionManager.currentCastSession }
+ ?: throw Refused("Not connected")
+ val state = load(session, mediaUrl, subtitle, file, startAt)
+ watch(session)
+ return JSONObject().put("playerState", state)
+ }
+
+ /**
+ * `file` is the relay's description of its file (type and what to show
+ * with it), or null for the stream. A photo is not a stream at all; a
+ * music track is an ordinary buffered file the receiver seeks in itself.
+ */
+ private fun load(session: CastSession, mediaUrl: String, subtitle: JSONObject?,
+ file: JSONObject?, startAt: Double): String {
+ val contentType = file?.optString("contentType", "") ?: "video/mp4"
+ val photo = file != null && contentType.startsWith("image/")
+ val subUrl = subtitle?.optString("url", "")?.takeIf { it.isNotEmpty() }
+ val info = if (photo) {
+ // A picture, not a stream: nothing to seek, nothing to buffer.
+ MediaInfo.Builder(mediaUrl).setContentType(contentType)
+ .setStreamType(MediaInfo.STREAM_TYPE_NONE)
+ .setMetadata(MediaMetadata(MediaMetadata.MEDIA_TYPE_PHOTO)).build()
+ } else if (file != null) {
+ val meta = file.optJSONObject("meta") ?: JSONObject()
+ MediaInfo.Builder(mediaUrl).setContentType(contentType)
+ .setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
+ .setMetadata(MediaMetadata(MediaMetadata.MEDIA_TYPE_MUSIC_TRACK).apply {
+ putString(MediaMetadata.KEY_TITLE, meta.optString("title", ""))
+ putString(MediaMetadata.KEY_ARTIST, meta.optString("artist", ""))
+ putString(MediaMetadata.KEY_ALBUM_TITLE, meta.optString("album", ""))
+ meta.optString("cover", "").takeIf { it.isNotEmpty() && it != "null" }
+ ?.let { addImage(WebImage(Uri.parse(it))) }
+ }).build()
+ } else MediaInfo.Builder(mediaUrl)
+ .setContentType("video/mp4")
+ // LIVE: the relay has no beginning to seek back to — the film's own
+ // timeline lives on this side, and a seek restarts the relay.
+ .setStreamType(MediaInfo.STREAM_TYPE_LIVE)
+ .apply {
+ if (subUrl != null) {
+ setMediaTracks(listOf(MediaTrack.Builder(TEXT_TRACK_ID, MediaTrack.TYPE_TEXT)
+ .setContentId(subUrl).setContentType("text/vtt")
+ .setSubtype(MediaTrack.SUBTYPE_SUBTITLES)
+ .setName(subtitle.optString("label", "").ifEmpty { "Subtitles" })
+ .setLanguage(subtitle.optString("language", "").ifEmpty { "und" })
+ .build()))
+ // White on nothing is unreadable over a bright scene; an outline costs no bandwidth.
+ setTextTrackStyle(TextTrackStyle().apply {
+ backgroundColor = Color.TRANSPARENT
+ foregroundColor = Color.WHITE
+ edgeType = TextTrackStyle.EDGE_TYPE_OUTLINE
+ edgeColor = Color.BLACK
+ fontScale = 1.0f
+ fontGenericFamily = TextTrackStyle.FONT_FAMILY_SANS_SERIF
+ })
+ }
+ }.build()
+ val request = MediaLoadRequestData.Builder().setMediaInfo(info).setAutoplay(true)
+ .apply { if (startAt > 0) setCurrentTime((startAt * 1000).toLong()) }
+ .apply { if (subUrl != null) setActiveTrackIds(longArrayOf(TEXT_TRACK_ID)) }.build()
+ val loaded = CountDownLatch(1)
+ var ok = false
+ var reason = ""
+ onMain {
+ val client = session.remoteMediaClient ?: throw IllegalStateException("The receiver has no media channel")
+ client.load(request).setResultCallback { r ->
+ ok = r.status.isSuccess
+ reason = "code ${r.status.statusCode}" + (r.status.statusMessage?.let { ", $it" } ?: "")
+ // The receiver's own reason, which is the only one there is:
+ // the page is told "refused" and nothing else.
+ Log.i(TAG, "load result: ok=$ok code=${r.status.statusCode} " +
+ "message=${r.status.statusMessage} state=${stateName(client.playerState)} " +
+ "idleReason=${client.idleReason} subtitles=${subUrl != null}")
+ loaded.countDown()
+ }
+ }
+ if (!loaded.await(20, TimeUnit.SECONDS)) {
+ Log.w(TAG, "load: no answer from the receiver in 20 s")
+ throw IllegalStateException("The receiver did not load the stream")
+ }
+ if (!ok) throw IllegalStateException("The receiver refused the stream ($reason)")
+ // A photo has no playing state to wait for: loaded is shown.
+ if (photo) return onMain { stateName(session.remoteMediaClient?.playerState ?: MediaStatus.PLAYER_STATE_UNKNOWN) }
+ // A load the receiver accepted is not a film on the screen: it answers
+ // IDLE, then fetches the stream, and only then plays — or gives up.
+ // So the answer waits for what the receiver actually did (measured
+ // against this receiver: OK/IDLE, then BUFFERING, then PLAYING).
+ val deadline = System.currentTimeMillis() + PLAY_WAIT_MS
+ while (System.currentTimeMillis() < deadline) {
+ val (state, idle) = onMain {
+ val c = session.remoteMediaClient
+ (c?.playerState ?: MediaStatus.PLAYER_STATE_UNKNOWN) to (c?.idleReason ?: MediaStatus.IDLE_REASON_NONE)
+ }
+ if (state == MediaStatus.PLAYER_STATE_PLAYING || state == MediaStatus.PLAYER_STATE_BUFFERING ||
+ state == MediaStatus.PLAYER_STATE_PAUSED) {
+ Log.i(TAG, "receiver is ${stateName(state)}")
+ return stateName(state)
+ }
+ if (state == MediaStatus.PLAYER_STATE_IDLE && idle != MediaStatus.IDLE_REASON_NONE) {
+ Log.w(TAG, "receiver gave up: idle reason ${idleName(idle)}")
+ throw IllegalStateException("The receiver gave up on the stream (${idleName(idle)})")
+ }
+ Thread.sleep(300)
+ }
+ Log.w(TAG, "receiver still not playing after ${PLAY_WAIT_MS / 1000} s")
+ return onMain { stateName(session.remoteMediaClient?.playerState ?: MediaStatus.PLAYER_STATE_UNKNOWN) }
+ }
+
+ /** The player as a remote: pause and play the receiver, answered once it has. */
+ fun pause(): JSONObject = command { it.pause() }
+ fun play(): JSONObject = command { it.play() }
+ /** Where in a track the receiver should be; a film seeks by restarting the relay instead. */
+ fun seek(seconds: Double): JSONObject = command {
+ it.seek(MediaSeekOptions.Builder().setPosition((maxOf(0.0, seconds) * 1000).toLong()).build())
+ }
+
+ private fun command(send: (com.google.android.gms.cast.framework.media.RemoteMediaClient) ->
+ com.google.android.gms.common.api.PendingResult<com.google.android.gms.cast.framework.media.RemoteMediaClient.MediaChannelResult>): JSONObject {
+ need()
+ val done = CountDownLatch(1)
+ var ok = false
+ onMain {
+ val c = CastContext.getSharedInstance(context).sessionManager.currentCastSession?.remoteMediaClient
+ ?: throw Refused("Not connected")
+ send(c).setResultCallback { r -> ok = r.status.isSuccess; done.countDown() }
+ }
+ if (!done.await(10, TimeUnit.SECONDS)) throw IllegalStateException("The receiver did not answer")
+ if (!ok) throw IllegalStateException("The receiver refused the command")
+ return JSONObject().put("playerState", onMain {
+ stateName(CastContext.getSharedInstance(context).sessionManager.currentCastSession?.remoteMediaClient?.playerState
+ ?: MediaStatus.PLAYER_STATE_UNKNOWN)
+ })
+ }
+
+ fun disconnect(): Boolean {
+ if (!available()) return true
+ onMain { CastContext.getSharedInstance(context).sessionManager.endCurrentSession(true) }
+ deviceName = null
+ return true
+ }
+
+ fun status(): JSONObject = try {
+ if (!available()) JSONObject().put("connected", false).put("deviceName", JSONObject.NULL)
+ else onMain {
+ val s = CastContext.getSharedInstance(context).sessionManager.currentCastSession
+ val on = s != null && s.isConnected
+ val c = if (on) s!!.remoteMediaClient else null
+ JSONObject().put("connected", on).put("deviceName", if (on) (deviceName ?: s!!.castDevice?.friendlyName) else JSONObject.NULL)
+ // Where the television is, on the stream's timeline (zero at
+ // the relay's start): the page adds that start. Not the local
+ // playhead, which started earlier and drifts.
+ .put("playerState", c?.let { stateName(it.playerState) } ?: JSONObject.NULL)
+ .put("idleReason", c?.takeIf { it.playerState == MediaStatus.PLAYER_STATE_IDLE }
+ ?.let { idleName(it.idleReason) } ?: JSONObject.NULL)
+ .put("position", c?.let { it.approximateStreamPosition / 1000.0 } ?: JSONObject.NULL)
+ }
+ } catch (e: Exception) {
+ Log.w("MeshBay", "cast status", e)
+ JSONObject().put("connected", false).put("deviceName", JSONObject.NULL)
+ }
+
+ companion object {
+ const val SCAN_DURATION_MS = 6000L
+ private const val TAG = "MeshBayCast"
+ // The one track the receiver is ever told about; changing subtitles
+ // reloads with a new URL under this same id.
+ const val TEXT_TRACK_ID = 1L
+ private val SCAN_TOKEN = Any()
+
+ private const val PLAY_WAIT_MS = 15000L
+
+ fun idleName(r: Int) = when (r) {
+ MediaStatus.IDLE_REASON_FINISHED -> "finished"
+ MediaStatus.IDLE_REASON_CANCELED -> "cancelled"
+ MediaStatus.IDLE_REASON_INTERRUPTED -> "interrupted"
+ MediaStatus.IDLE_REASON_ERROR -> "error"
+ else -> "reason $r"
+ }
+
+ fun stateName(s: Int) = when (s) {
+ MediaStatus.PLAYER_STATE_PLAYING -> "PLAYING"
+ MediaStatus.PLAYER_STATE_PAUSED -> "PAUSED"
+ MediaStatus.PLAYER_STATE_BUFFERING -> "BUFFERING"
+ MediaStatus.PLAYER_STATE_LOADING -> "LOADING"
+ MediaStatus.PLAYER_STATE_IDLE -> "IDLE"
+ else -> "UNKNOWN"
+ }
+ }
+}
+
+/** The cast framework asks the manifest for this: the default media receiver. */
+class CastOptionsProvider : OptionsProvider {
+ override fun getCastOptions(context: Context): CastOptions =
+ CastOptions.Builder().setReceiverApplicationId(CastMediaControlIntent.DEFAULT_MEDIA_RECEIVER_APPLICATION_ID).build()
+
+ override fun getAdditionalSessionProviders(context: Context) = null
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastRelay.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastRelay.kt
new file mode 100644
index 0000000..5b76f60
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastRelay.kt
@@ -0,0 +1,596 @@
+package org.meshbay.client.cast
+
+import android.util.Log
+import org.json.JSONObject
+import java.io.BufferedReader
+import java.io.File
+import java.io.InputStreamReader
+import java.io.RandomAccessFile
+import java.nio.ByteBuffer
+import java.nio.channels.FileChannel
+import java.io.OutputStream
+import java.net.InetAddress
+import java.net.InetSocketAddress
+import java.net.ServerSocket
+import java.net.Socket
+import java.net.SocketException
+import java.security.SecureRandom
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.AtomicLong
+
+/**
+ * Local HTTP relay for LAN casting — a port of meshbay-client/src/cast-relay.js,
+ * whose comments are the specification.
+ *
+ * The page decrypts the fMP4 stream from the node and pushes it here; a
+ * receiver on the same Wi-Fi plays it from the URL. Same mitigations:
+ *
+ * - bound to the LAN interface (the caller supplies it), never 0.0.0.0;
+ * - fixed port range 19550–19553, open only while casting;
+ * - an unguessable token in the URL (32 hex chars);
+ * - CORS on both served paths, both behind the token;
+ * - `Cache-Control: no-store` on every response;
+ * - the server closed when playback stops — zero residual surface.
+ *
+ * What a receiver has not read yet waits in a file, not in memory. The page
+ * runs ahead of the television by its whole read-ahead — tens of megabytes in
+ * the first seconds — and a fragment is a segment, megabytes at a film's
+ * bitrate (5 to 10 MB measured). Held in memory under the desktop's 8 MB
+ * bound, fragments were dropped and the picture froze for their length; held
+ * in memory without a bound, the heap went. A spool file per receiver holds
+ * the lead at no cost to either, and is deleted when the receiver goes.
+ *
+ * `java.net` and `java.nio` only, so the JVM tests run the real thing.
+ */
+class CastRelay(private val lanAddress: () -> InetAddress?, private val spoolDir: File) {
+
+ /**
+ * One receiver: the fragments it has been given, appended to its spool
+ * file, and how far it has read. Positional reads and writes on one
+ * channel, so the pusher and the reader never share a file pointer.
+ */
+ private class Client(val socket: Socket, val out: OutputStream, val file: File) {
+ val channel: FileChannel = RandomAccessFile(file, "rw").channel
+ val lock = Object()
+ var written = 0L // guarded by lock
+ var read = 0L // guarded by lock
+ var ended = false // guarded by lock
+ @Volatile var closed = false
+ val sent = AtomicLong()
+ val dropped = AtomicLong()
+ @Volatile var lastReport = System.currentTimeMillis()
+
+ fun waiting() = synchronized(lock) { written - read }
+
+ fun append(data: ByteArray) {
+ var at = synchronized(lock) { written }
+ val buf = ByteBuffer.wrap(data)
+ while (buf.hasRemaining()) at += channel.write(buf, at)
+ synchronized(lock) { written = at; lock.notifyAll() }
+ }
+
+ fun end() = synchronized(lock) { ended = true; lock.notifyAll() }
+
+ fun close() {
+ closed = true
+ synchronized(lock) { lock.notifyAll() }
+ try { channel.close() } catch (e: Exception) {}
+ file.delete()
+ }
+ }
+
+ private val spoolSeq = AtomicLong()
+
+ private class Subtitle(val vtt: ByteArray, val language: String, val label: String)
+ private class Cover(val bytes: ByteArray, val type: String)
+ /** A whole file on disk, served at `/file`: a photo, or a track with its cover. */
+ private class FileSlot(val path: File, val size: Long, val type: String, val cover: Cover?, val meta: JSONObject)
+ private class Incoming(val slot: FileSlot) {
+ val out = java.io.FileOutputStream(slot.path)
+ var received = 0L
+ }
+
+ @Volatile private var server: ServerSocket? = null
+ @Volatile private var port = 0
+ @Volatile private var token: String? = null
+ @Volatile private var host: String? = null
+ @Volatile private var initSegment: ByteArray? = null
+ private val headerLock = Object()
+ @Volatile private var headerReady = false
+ @Volatile private var subtitle: Subtitle? = null
+ @Volatile private var subtitleVersion = 0
+ @Volatile private var file: FileSlot? = null
+ @Volatile private var fileVersion = 0
+ private var incoming: Incoming? = null // guarded by this
+ private val fileSeq = AtomicLong()
+ /** How many times a receiver asked for the stream since the relay started. */
+ @Volatile var streamRequests = 0
+ private set
+ private val ring = ArrayDeque<ByteArray>()
+ private var ringBytes = 0L
+ private val clients = ConcurrentHashMap.newKeySet<Client>()
+ private var accum = BoxAccumulator()
+
+ val active get() = server != null
+ /** For the tests: what a receiver joining now would be sent before live fragments. */
+ fun backlogBytes() = synchronized(ring) { ringBytes }
+
+ val url get() = if (server == null) null else "http://${hostPart()}:$port/stream.mp4?t=$token"
+
+ private fun hostPart() = host?.let { if (it.contains(':')) "[$it]" else it }
+
+ /** Versioned: a receiver caches a side-loaded track by its address. */
+ val subtitleUrl get() =
+ if (server == null || subtitle == null) null
+ else "http://${hostPart()}:$port/subs.vtt?t=$token&v=$subtitleVersion"
+
+ /** Versioned like the subtitle: a receiver handed the same address twice shows what it has. */
+ val fileUrl get() =
+ if (server == null || file == null) null
+ else "http://${hostPart()}:$port/file?t=$token&v=$fileVersion"
+
+ val fileType get() = file?.type
+
+ /** What the receiver is told the file is: title, artist, album, and the cover's address. */
+ fun fileMeta(): JSONObject? = file?.let { f ->
+ JSONObject(f.meta.toString()).put("cover",
+ if (f.cover == null) JSONObject.NULL else "http://${hostPart()}:$port/cover?t=$token&v=$fileVersion")
+ }
+
+ /**
+ * A file arrives in three steps, so that a large one never crosses the
+ * bridge as one message: `beginFile` names it, `writeFile` appends, and
+ * `endFile` puts it up and answers its address. It is written to the spool
+ * directory rather than held: a long lossless track is a few hundred
+ * megabytes. The relay starts for it when nothing else has.
+ */
+ @Synchronized
+ fun beginFile(type: String, size: Long, cover: ByteArray?, coverType: String?, meta: JSONObject): Boolean {
+ if (type !in FILE_TYPES) throw IllegalArgumentException("Not something a receiver shows: $type")
+ if (size <= 0 || size > FILE_MAX_BYTES) throw IllegalArgumentException("Bad file size: $size")
+ if (cover != null && (coverType == null || !coverType.startsWith("image/") || coverType !in FILE_TYPES)) {
+ throw IllegalArgumentException("Bad cover type: $coverType")
+ }
+ if (server == null) start(null, null)
+ dropIncoming()
+ // At most the file being shown and the one arriving: anything older
+ // has been replaced on the television already.
+ spoolDir.listFiles()?.filter { it.name.startsWith("file-") && it != file?.path }?.forEach { it.delete() }
+ val text = { k: String -> meta.optString(k, "").take(500) }
+ val slot = FileSlot(File(spoolDir, "file-${fileSeq.incrementAndGet()}.bin"), size, type,
+ cover?.let { Cover(it, coverType!!) },
+ JSONObject().put("title", text("title")).put("artist", text("artist")).put("album", text("album")))
+ incoming = Incoming(slot)
+ return true
+ }
+
+ @Synchronized
+ fun writeFile(data: ByteArray, offset: Int = 0, length: Int = data.size - offset): Boolean {
+ val f = incoming ?: throw IllegalStateException("No file is being sent")
+ if (f.received + length > f.slot.size) { dropIncoming(); throw IllegalStateException("More bytes than announced") }
+ f.out.write(data, offset, length)
+ f.received += length
+ return true
+ }
+
+ @Synchronized
+ fun endFile(): JSONObject {
+ val f = incoming ?: throw IllegalStateException("No file is being sent")
+ incoming = null
+ f.out.close()
+ if (f.received != f.slot.size) {
+ f.slot.path.delete()
+ throw IllegalStateException("File cut short: ${f.received} of ${f.slot.size} bytes")
+ }
+ // The previous file stays on disk until the next one begins: a receiver
+ // may still be reading it.
+ file = f.slot
+ fileVersion++
+ log("file set: ${f.slot.size} bytes, ${f.slot.type}, v$fileVersion")
+ return JSONObject().put("url", fileUrl)
+ }
+
+ private fun dropIncoming() {
+ incoming?.let { try { it.out.close() } catch (e: Exception) {}; it.slot.path.delete() }
+ incoming = null
+ }
+
+ fun subtitleInfo(): JSONObject? = subtitle?.let {
+ JSONObject().put("url", subtitleUrl).put("language", it.language).put("label", it.label)
+ }
+
+ /** Cues already on the stream's timeline — the page shifts them; the relay serves bytes. */
+ fun setSubtitle(sub: JSONObject?): JSONObject? {
+ val vtt = sub?.optString("vtt", "") ?: ""
+ subtitle = if (vtt.isEmpty()) null
+ else Subtitle(vtt.toByteArray(Charsets.UTF_8), sub!!.optString("language", ""), sub.optString("label", ""))
+ subtitleVersion++
+ return subtitleInfo()
+ }
+
+ @Synchronized
+ fun start(init: ByteArray?, sub: JSONObject?): JSONObject {
+ if (server != null) stop()
+ val address = lanAddress() ?: throw IllegalStateException("Casting needs this device on Wi-Fi")
+ token = randomToken()
+ streamRequests = 0
+ pushes = 0
+ fragments = 0
+ host = address.hostAddress
+ initSegment = init?.let(::headerOnly)
+ // Nothing to wait for without a first chunk: no header is coming.
+ headerReady = init == null
+ synchronized(ring) { ring.clear(); ringBytes = 0 }
+ clients.clear()
+ accum = BoxAccumulator().also { a -> a.onPreamble = ::preamble }
+ // What a killed process left behind.
+ spoolDir.mkdirs()
+ spoolDir.listFiles()?.forEach { it.delete() }
+ subtitle = null
+ dropIncoming()
+ file = null
+ setSubtitle(sub)
+
+ var bound: ServerSocket? = null
+ for (i in 0 until PORT_COUNT) {
+ val s = ServerSocket()
+ try {
+ // As Node's server does (and so the desktop relay): a port just
+ // closed sits in TIME_WAIT, and every seek restarts the relay —
+ // without this, four quick seeks used all four ports. It does
+ // not let two live listeners share a port.
+ s.reuseAddress = true
+ s.bind(InetSocketAddress(address, PORT_BASE + i))
+ bound = s; port = PORT_BASE + i
+ break
+ } catch (e: java.net.BindException) {
+ s.close()
+ }
+ }
+ server = bound ?: throw IllegalStateException("All cast relay ports are in use")
+ Thread({ acceptLoop(bound) }, "cast-relay-accept").apply { isDaemon = true }.start()
+ log("started on ${hostPart()}:$port, init ${init?.size ?: 0} bytes, header ${initSegment?.size ?: 0} bytes")
+ return JSONObject().put("url", url).put("port", port).put("token", token)
+ .put("subtitle", subtitleInfo() ?: JSONObject.NULL)
+ }
+
+ /**
+ * The header is everything the page pushed before the first moof. The
+ * `init` the page hands to start() is only its first chunk, which may be
+ * the ftyp without the moov: served as the header, the receiver got no
+ * track description and gave up — the "fails the first time" of a fresh
+ * start, every time. The pushed stream carries the whole of it; `init` is
+ * the fallback when nothing came before the first moof.
+ */
+ private fun preamble(bytes: ByteArray) {
+ val header = headerOnly(bytes)
+ synchronized(headerLock) {
+ if (header.size >= 8 && BoxAccumulator.u32(header, 4) == FTYP) initSegment = header
+ headerReady = true
+ headerLock.notifyAll()
+ }
+ log("header complete: ${initSegment?.size ?: 0} bytes")
+ }
+
+ /** A receiver that connects before the first moof waits for the whole header, not a piece of it. */
+ private fun awaitHeader(): ByteArray? {
+ val deadline = System.currentTimeMillis() + HEADER_WAIT_MS
+ synchronized(headerLock) {
+ while (!headerReady) {
+ val left = deadline - System.currentTimeMillis()
+ if (left <= 0) break
+ headerLock.wait(left)
+ }
+ }
+ return initSegment
+ }
+
+ @Volatile private var pushes = 0
+ @Volatile private var fragments = 0
+
+ fun push(data: ByteArray, offset: Int = 0, length: Int = data.size - offset) {
+ if (server == null) return
+ pushes++
+ if (pushes <= 3 || pushes % 100 == 0) log("push #$pushes: $length bytes, $fragments fragments so far")
+ for (frag in accum.push(data, offset, length)) {
+ fragments++
+ // The backlog and the clients under one lock: a receiver joining
+ // gets each fragment exactly once, from the backlog or from here.
+ synchronized(ring) {
+ ring.addLast(frag); ringBytes += frag.size
+ // Bounded in fragments, as the desktop is, and in bytes too: a
+ // fragment is a whole segment, megabytes at a film's bitrate,
+ // and 64 of them outgrew a phone's heap — the app died of it.
+ while (ring.size > RING_CAP || (ringBytes > RING_MAX_BYTES && ring.size > 1)) {
+ ringBytes -= ring.removeFirst().size
+ }
+ for (c in clients) {
+ if (c.waiting() > spoolLimit()) {
+ // Only with the disk bound reached: the picture on the
+ // receiver freezes until the next fragment it gets.
+ val n = c.dropped.incrementAndGet()
+ if (n <= 3 || n % 20 == 0L) {
+ log("DROPPED fragment for ${c.socket.inetAddress?.hostAddress}: ${frag.size} bytes, " +
+ "${c.waiting() / 1048576} MiB already waiting, $n dropped so far")
+ }
+ continue
+ }
+ try { c.append(frag) } catch (e: Exception) { log("spool write failed: ${e.message}") }
+ }
+ }
+ }
+ }
+
+ /** End of film: every client's response is ended, the server stays until stop. */
+ fun finish() {
+ for (c in clients) c.end()
+ }
+
+ /** Half the free space, at most 2 GiB: a receiver this far behind is not coming back. */
+ private fun spoolLimit(): Long = minOf(SPOOL_MAX_BYTES, spoolDir.usableSpace / 2)
+
+ @Synchronized
+ fun stop() {
+ for (c in clients) { c.close(); try { c.socket.close() } catch (e: Exception) {} }
+ clients.clear()
+ server?.let { try { it.close() } catch (e: Exception) {} }
+ server = null
+ port = 0; token = null; initSegment = null; subtitle = null
+ dropIncoming()
+ file = null
+ spoolDir.listFiles()?.filter { it.name.startsWith("file-") }?.forEach { it.delete() }
+ synchronized(ring) { ring.clear(); ringBytes = 0 }
+ accum.reset()
+ }
+
+ // ── HTTP ────────────────────────────────────────────────────────────────
+
+ private fun acceptLoop(s: ServerSocket) {
+ while (!s.isClosed) {
+ val socket = try { s.accept() } catch (e: SocketException) { return }
+ Thread({ serve(socket) }, "cast-relay-client").apply { isDaemon = true }.start()
+ }
+ }
+
+ private fun serve(socket: Socket) {
+ try {
+ socket.soTimeout = 15000
+ val reader = BufferedReader(InputStreamReader(socket.getInputStream(), Charsets.ISO_8859_1))
+ val requestLine = reader.readLine() ?: return socket.close()
+ var range: String? = null
+ while (true) {
+ val line = reader.readLine() ?: break
+ if (line.isEmpty()) break
+ if (line.startsWith("range:", ignoreCase = true)) range = line.substringAfter(':').trim()
+ }
+ socket.soTimeout = 0
+ val parts = requestLine.split(' ')
+ val method = parts.getOrElse(0) { "" }
+ val target = parts.getOrElse(1) { "" }
+ val out = socket.getOutputStream()
+
+ if (method != "GET" && method != "OPTIONS") return respond(out, socket, 405, emptyMap())
+ // The preflight is answered before the token is examined: a
+ // receiver sends it without credentials, and refusing it would
+ // read on the receiver as a network failure, not a refusal.
+ if (method == "OPTIONS") return respond(out, socket, 204, CORS_HEADERS)
+
+ val path = target.substringBefore('?')
+ log("$method $path from ${socket.inetAddress?.hostAddress}")
+ val query = target.substringAfter('?', "").split('&').associate {
+ it.substringBefore('=') to it.substringAfter('=', "")
+ }
+ if (token == null || query["t"] != token) return respond(out, socket, 403, emptyMap())
+ when (path) {
+ "/subs.vtt" -> serveSubtitle(out, socket)
+ "/file" -> serveFile(out, socket, range)
+ "/cover" -> serveCover(out, socket)
+ "/stream.mp4" -> { streamRequests++; serveStream(out, socket) }
+ else -> respond(out, socket, 404, emptyMap())
+ }
+ } catch (e: Exception) {
+ try { socket.close() } catch (x: Exception) {}
+ }
+ }
+
+ private fun serveSubtitle(out: OutputStream, socket: Socket) {
+ val sub = subtitle ?: return respond(out, socket, 404, CORS_HEADERS)
+ respond(out, socket, 200, CORS_HEADERS + mapOf(
+ "Content-Type" to "text/vtt; charset=utf-8",
+ "Content-Length" to sub.vtt.size.toString(),
+ "Cache-Control" to "no-store",
+ ), sub.vtt)
+ }
+
+ /** The whole file, or the one range asked for: a receiver seeks in a track that way. */
+ private fun serveFile(out: OutputStream, socket: Socket, range: String?) {
+ val f = file ?: return respond(out, socket, 404, CORS_HEADERS)
+ val total = f.size
+ val base = CORS_HEADERS + mapOf("Content-Type" to f.type, "Cache-Control" to "no-store",
+ "Accept-Ranges" to "bytes", "Connection" to "close")
+ var from = 0L
+ var to = total - 1
+ var status = 200
+ val m = range?.let { Regex("^bytes=(\\d*)-(\\d*)$").matchEntire(it) }
+ if (m != null && (m.groupValues[1].isNotEmpty() || m.groupValues[2].isNotEmpty())) {
+ val a = m.groupValues[1]; val b = m.groupValues[2]
+ from = if (a.isEmpty()) total - b.toLong() else a.toLong()
+ to = if (a.isEmpty() || b.isEmpty()) total - 1 else minOf(b.toLong(), total - 1)
+ from = maxOf(0L, from)
+ if (from > to || from >= total) {
+ head(out, 416, base + ("Content-Range" to "bytes */$total") + ("Content-Length" to "0"))
+ out.flush(); socket.close(); return
+ }
+ status = 206
+ }
+ val length = to - from + 1
+ head(out, status, base + ("Content-Length" to length.toString()) +
+ (if (status == 206) mapOf("Content-Range" to "bytes $from-$to/$total") else emptyMap()))
+ RandomAccessFile(f.path, "r").use { raf ->
+ raf.seek(from)
+ val block = ByteArray(BLOCK)
+ var left = length
+ while (left > 0) {
+ val n = raf.read(block, 0, minOf(BLOCK.toLong(), left).toInt())
+ if (n <= 0) break
+ out.write(block, 0, n)
+ left -= n
+ }
+ }
+ out.flush()
+ socket.close()
+ }
+
+ private fun serveCover(out: OutputStream, socket: Socket) {
+ val c = file?.cover ?: return respond(out, socket, 404, CORS_HEADERS)
+ respond(out, socket, 200, CORS_HEADERS + mapOf(
+ "Content-Type" to c.type,
+ "Content-Length" to c.bytes.size.toString(),
+ "Cache-Control" to "no-store",
+ ), c.bytes)
+ }
+
+ private fun serveStream(out: OutputStream, socket: Socket) {
+ // Same headers as the subtitle: a receiver given a side-loaded track
+ // reads the media through the same CORS-checked path.
+ head(out, 200, CORS_HEADERS + mapOf(
+ "Content-Type" to "video/mp4",
+ "Cache-Control" to "no-store",
+ "Accept-Ranges" to "none",
+ "Connection" to "keep-alive",
+ "Transfer-Encoding" to "chunked",
+ ))
+ awaitHeader()?.let { chunk(out, it) }
+ out.flush()
+ val client = Client(socket, out, File(spoolDir, "client-${spoolSeq.incrementAndGet()}.spool"))
+ val backlog = synchronized(ring) {
+ for (frag in ring) client.append(frag)
+ clients.add(client)
+ ring.size
+ }
+ log("client ${socket.inetAddress?.hostAddress} served init + $backlog fragments")
+ val block = ByteBuffer.allocate(BLOCK)
+ try {
+ while (!client.closed) {
+ val at = synchronized(client.lock) {
+ while (client.read == client.written && !client.ended && !client.closed) client.lock.wait()
+ if (client.read == client.written) -1L else client.read
+ }
+ if (at < 0) {
+ if (!client.closed) { out.write("0\r\n\r\n".toByteArray()); out.flush() }
+ break
+ }
+ block.clear()
+ val n = client.channel.read(block, at)
+ if (n <= 0) continue
+ val t0 = System.currentTimeMillis()
+ chunk(out, block.array(), n)
+ out.flush()
+ val took = System.currentTimeMillis() - t0
+ synchronized(client.lock) { client.read += n }
+ client.sent.addAndGet(n.toLong())
+ // A write that blocks is the receiver not reading (or the
+ // Wi-Fi not carrying): the one place a stall downstream shows.
+ if (took > 5000) log("slow write to ${socket.inetAddress?.hostAddress}: $n bytes took $took ms")
+ val now = System.currentTimeMillis()
+ if (now - client.lastReport >= 10_000) {
+ client.lastReport = now
+ log("client ${socket.inetAddress?.hostAddress}: sent ${client.sent.get() / 1048576} MiB, " +
+ "${client.waiting() / 1048576} MiB waiting in the spool, ${client.dropped.get()} dropped")
+ }
+ }
+ } catch (e: Exception) {
+ // The receiver went away; nothing to tell anyone.
+ } finally {
+ log("client ${socket.inetAddress?.hostAddress} gone")
+ synchronized(ring) { clients.remove(client) }
+ client.close()
+ try { socket.close() } catch (e: Exception) {}
+ }
+ }
+
+ companion object {
+ /**
+ * The init segment is what comes before the first moof, and only that.
+ *
+ * The page hands over the first chunk it decrypted, which is a slice of
+ * the stream and not a box: on a real film it was 65536 bytes — ftyp,
+ * moov, then the first moof and the start of its mdat. Served whole,
+ * the receiver read that partial fragment, then the same fragment again
+ * from the accumulator (the page pushes that chunk too), and the box
+ * structure was broken from the first fragment: the receiver gave up
+ * within three seconds, on the television's idle screen. Whether the
+ * first chunk carries film depends on when the node read ffmpeg's
+ * output, so the same film can work once and not the next time.
+ */
+ fun headerOnly(init: ByteArray): ByteArray {
+ var at = 0
+ while (at + 8 <= init.size) {
+ if (BoxAccumulator.u32(init, at + 4) == BoxAccumulator.MOOF) return init.copyOfRange(0, at)
+ val size = BoxAccumulator.u32(init, at)
+ if (size < 8) break
+ at += size.toInt()
+ }
+ return init
+ }
+
+ const val RING_CAP = 64
+ // What a receiver is ever handed as a file: the page re-encodes every
+ // photo to JPEG, and plays a track in the format it is stored in.
+ val FILE_TYPES = setOf("image/jpeg", "image/png", "image/webp",
+ "audio/mpeg", "audio/mp4", "audio/aac", "audio/flac", "audio/ogg", "audio/opus",
+ "audio/wav", "audio/webm")
+ // Only stops a page from filling the phone: a long lossless track is a few hundred MB.
+ const val FILE_MAX_BYTES = 1024L * 1024 * 1024
+ const val RING_MAX_BYTES = 32L * 1024 * 1024
+ const val SPOOL_MAX_BYTES = 2L * 1024 * 1024 * 1024
+ private const val HEADER_WAIT_MS = 10_000L
+ private const val FTYP = 0x66747970L
+ private const val BLOCK = 256 * 1024
+ const val PORT_BASE = 19550
+ const val PORT_COUNT = 4
+
+ // Never the URL: it carries the token.
+ private fun log(m: String) = try { Log.i("MeshBayCast", "[relay] $m") } catch (e: RuntimeException) { /* JVM tests */ }
+
+ // A receiver reads a side-loaded subtitle with XHR from its own
+ // origin, so the headers it sends are allowed by name — Range included.
+ val CORS_HEADERS = mapOf(
+ "Access-Control-Allow-Origin" to "*",
+ "Access-Control-Allow-Methods" to "GET, OPTIONS",
+ "Access-Control-Allow-Headers" to "Content-Type, Accept-Encoding, Range",
+ "Access-Control-Expose-Headers" to "Content-Length, Content-Range",
+ )
+
+ private val REASONS = mapOf(200 to "OK", 204 to "No Content", 206 to "Partial Content",
+ 403 to "Forbidden", 404 to "Not Found", 405 to "Method Not Allowed",
+ 416 to "Range Not Satisfiable")
+
+ private fun randomToken(): String {
+ val b = ByteArray(16).also { SecureRandom().nextBytes(it) }
+ return b.joinToString("") { "%02x".format(it) }
+ }
+
+ private fun head(out: OutputStream, status: Int, headers: Map<String, String>) {
+ val sb = StringBuilder("HTTP/1.1 $status ${REASONS[status] ?: ""}\r\n")
+ for ((k, v) in headers) sb.append(k).append(": ").append(v).append("\r\n")
+ sb.append("\r\n")
+ out.write(sb.toString().toByteArray(Charsets.ISO_8859_1))
+ }
+
+ private fun respond(out: OutputStream, socket: Socket, status: Int, headers: Map<String, String>,
+ body: ByteArray = ByteArray(0)) {
+ val h = if (headers.containsKey("Content-Length")) headers else headers + ("Content-Length" to body.size.toString())
+ head(out, status, h + ("Connection" to "close"))
+ out.write(body)
+ out.flush()
+ socket.close()
+ }
+
+ private fun chunk(out: OutputStream, data: ByteArray, length: Int = data.size) {
+ out.write("${Integer.toHexString(length)}\r\n".toByteArray())
+ out.write(data, 0, length)
+ out.write("\r\n".toByteArray())
+ }
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastService.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastService.kt
new file mode 100644
index 0000000..3ea8f92
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastService.kt
@@ -0,0 +1,74 @@
+package org.meshbay.client.cast
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.app.Service
+import android.content.Context
+import android.content.Intent
+import android.content.pm.ServiceInfo
+import android.net.wifi.WifiManager
+import android.os.Build
+import android.os.IBinder
+import android.os.PowerManager
+
+/**
+ * Keeps a cast, or music playing on the phone itself, alive with the screen
+ * off: a media-playback foreground service with a partial wake lock and a
+ * Wi-Fi lock, for as long as either runs.
+ *
+ * Not sufficient alone — measured (spike S-2a): Chromium freezes a hidden page
+ * 60 s after the screen goes off whatever the process importance, and the
+ * pipeline (WebRTC → decrypt → relay) lives in the page. The shell also keeps
+ * the WebView reported visible while casting (ShellWebView); the two together
+ * held a full-rate stream through screen-off and forced Doze.
+ */
+class CastService : Service() {
+ private var wake: PowerManager.WakeLock? = null
+ private var wifi: WifiManager.WifiLock? = null
+
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ val nm = getSystemService(NotificationManager::class.java)
+ nm.createNotificationChannel(NotificationChannel(CHANNEL, "Playback", NotificationManager.IMPORTANCE_LOW))
+ val open = PendingIntent.getActivity(this, 0,
+ packageManager.getLaunchIntentForPackage(packageName), PendingIntent.FLAG_IMMUTABLE)
+ val n = Notification.Builder(this, CHANNEL)
+ .setContentTitle(intent?.getStringExtra(EXTRA_TITLE) ?: "MeshBay")
+ .setContentText(intent?.getStringExtra(EXTRA_TEXT) ?: "Casting on this Wi-Fi")
+ .setSmallIcon(android.R.drawable.ic_media_play)
+ .setContentIntent(open)
+ .setOngoing(true)
+ .build()
+ if (Build.VERSION.SDK_INT >= 29) startForeground(ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK)
+ else startForeground(ID, n)
+ if (wake == null) {
+ wake = getSystemService(PowerManager::class.java)
+ .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "meshbay:cast").apply { acquire(MAX_HOLD_MS) }
+ @Suppress("DEPRECATION")
+ val mode = if (Build.VERSION.SDK_INT >= 29) WifiManager.WIFI_MODE_FULL_LOW_LATENCY else WifiManager.WIFI_MODE_FULL_HIGH_PERF
+ wifi = (applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager)
+ .createWifiLock(mode, "meshbay:cast").apply { acquire() }
+ }
+ return START_NOT_STICKY
+ }
+
+ override fun onDestroy() {
+ wake?.let { if (it.isHeld) it.release() }
+ wifi?.let { if (it.isHeld) it.release() }
+ wake = null; wifi = null
+ super.onDestroy()
+ }
+
+ companion object {
+ private const val CHANNEL = "cast"
+ private const val ID = 7
+ const val EXTRA_TITLE = "title"
+ const val EXTRA_TEXT = "text"
+ // A bound on the wake lock, not on the cast: a process that is killed
+ // without stopping the service must not hold the CPU for ever.
+ private const val MAX_HOLD_MS = 6L * 3600 * 1000
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/hub/HubClient.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/hub/HubClient.kt
new file mode 100644
index 0000000..3b8517c
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/hub/HubClient.kt
@@ -0,0 +1,130 @@
+package org.meshbay.client.hub
+
+import android.content.SharedPreferences
+import okhttp3.HttpUrl
+import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
+import okhttp3.MediaType.Companion.toMediaTypeOrNull
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import org.json.JSONObject
+import org.meshbay.client.bridge.Refused
+import java.io.IOException
+import java.net.ConnectException
+import java.net.SocketTimeoutException
+import java.net.UnknownHostException
+import java.util.concurrent.TimeUnit
+import javax.net.ssl.SSLException
+
+/**
+ * Every call to the hub leaves from here, never from the page.
+ *
+ * Not a preference: the page's origin is `https://appassets.androidplatform.net`,
+ * which the hub's absent CORS refuses — and that posture is worth keeping, its
+ * API is reachable from no web origin at all. So the page asks and this goes,
+ * to the hub it is signed in to and nowhere else (main.js `hub:fetch`).
+ */
+class HubClient(private val prefs: SharedPreferences) {
+
+ private val http = OkHttpClient.Builder()
+ // The hub's longest call is signaling, which gives up at fifteen
+ // seconds; past this, no answer is still coming (HUB_FETCH_TIMEOUT_MS).
+ .callTimeout(FETCH_TIMEOUT_S, TimeUnit.SECONDS)
+ .followRedirects(false)
+ .build()
+
+ val base: String get() = prefs.getString(KEY_BASE, "") ?: ""
+
+ /** Check that the address answers as a hub before writing it down. */
+ fun setBase(raw: String): String {
+ val url = raw.trim().trimEnd('/')
+ // An empty address is not "no hub": main.js probes it like any other
+ // and it fails, so the first-run screen cannot be passed with nothing.
+ if (url.isEmpty()) throw Refused("Enter the address of a hub.")
+ if (!url.startsWith("https://") && !LOOPBACK_HTTP.containsMatchIn(url)) {
+ // http only to this device's loopback; anywhere else it would put
+ // the session token on the wire in clear.
+ throw Refused("The hub address must be https")
+ }
+ val probe = url.toHttpUrlOrNull()?.newBuilder()?.encodedPath("/v1/hub/version")?.build()
+ ?: throw Refused("$url is not an address")
+ val answer = try {
+ http.newBuilder().callTimeout(PROBE_TIMEOUT_S, TimeUnit.SECONDS).build()
+ .newCall(Request.Builder().url(probe).build()).execute().use { r ->
+ if (!r.isSuccessful) throw IOException("answered ${r.code}")
+ JSONObject(r.body.string())
+ }
+ } catch (e: Exception) {
+ throw Refused(describeUnreachable(url, e))
+ }
+ if (!answer.has("hub")) throw Refused(describeUnreachable(url, IOException("did not answer as a hub")))
+ prefs.edit().putString(KEY_BASE, url).apply()
+ return url
+ }
+
+ /** `{status, ok, headers, body}`, the shape main.js returns and platform.apiFetch reads. */
+ fun fetch(url: String, init: JSONObject?): JSONObject {
+ val target = url.toHttpUrlOrNull() ?: throw Refused("not an address")
+ val hub = base.toHttpUrlOrNull()
+ // The page may only reach the hub it is signed in to: a path it
+ // controls must not become a request to somewhere else.
+ if (hub == null || !sameOrigin(target, hub)) throw Refused("Refused: not this hub")
+
+ val method = (init?.optString("method").takeUnless { it.isNullOrEmpty() } ?: "GET").uppercase()
+ val builder = Request.Builder().url(target)
+ var contentType: String? = null
+ init?.optJSONObject("headers")?.let { h ->
+ for (name in h.keys()) {
+ val value = h.get(name).toString()
+ if (name.equals("content-type", ignoreCase = true)) contentType = value
+ builder.header(name, value)
+ }
+ }
+ val text = init?.opt("body")?.takeUnless { it == JSONObject.NULL }?.toString()
+ val body = when {
+ method == "GET" || method == "HEAD" -> null
+ else -> (text ?: "").toRequestBody(contentType?.toMediaTypeOrNull())
+ }
+ builder.method(method, body)
+
+ return try {
+ http.newCall(builder.build()).execute().use { r ->
+ val headers = JSONObject()
+ for (name in r.headers.names()) headers.put(name.lowercase(), r.headers.values(name).joinToString(", "))
+ JSONObject().put("status", r.code).put("ok", r.isSuccessful)
+ .put("headers", headers).put("body", r.body.string())
+ }
+ } catch (e: IOException) {
+ // OkHttp's call timeout is an InterruptedIOException("timeout"), a
+ // read timeout a SocketTimeoutException; both mean the same thing.
+ if (e is SocketTimeoutException || e.message?.contains("timeout", ignoreCase = true) == true) {
+ throw Refused("${originOf(hub)} accepted the connection but did not answer within ${FETCH_TIMEOUT_S}s.")
+ }
+ throw Refused(describeUnreachable(originOf(hub), e))
+ }
+ }
+
+ companion object {
+ private const val KEY_BASE = "hubBase"
+ const val FETCH_TIMEOUT_S = 30L
+ private const val PROBE_TIMEOUT_S = 10L
+ private val LOOPBACK_HTTP = Regex("^http://(localhost|127\\.)")
+
+ fun sameOrigin(a: HttpUrl, b: HttpUrl) = a.scheme == b.scheme && a.host == b.host && a.port == b.port
+
+ private fun originOf(u: HttpUrl): String {
+ val defaultPort = (u.scheme == "https" && u.port == 443) || (u.scheme == "http" && u.port == 80)
+ return "${u.scheme}://${u.host}" + if (defaultPort) "" else ":${u.port}"
+ }
+
+ /** Why the hub could not be reached, in words somebody can act on (main.js). */
+ fun describeUnreachable(url: String, e: Throwable): String = when {
+ url.startsWith("https:") && e is SSLException ->
+ "$url does not speak https. If this hub is on your own machine, it is probably http — try http:// instead."
+ e is ConnectException -> "Nothing is listening at $url. Is the hub running?"
+ e is UnknownHostException -> "$url could not be found. Check the address."
+ e is SocketTimeoutException || e.message?.contains("timeout", true) == true -> "$url did not answer in time."
+ else -> "Could not reach $url: ${e.message ?: e.javaClass.simpleName}"
+ }
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/DeviceKey.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/DeviceKey.kt
new file mode 100644
index 0000000..4cd840c
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/DeviceKey.kt
@@ -0,0 +1,47 @@
+package org.meshbay.client.keys
+
+import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters
+import org.bouncycastle.crypto.signers.Ed25519Signer
+import org.json.JSONObject
+import java.security.SecureRandom
+
+/**
+ * The device's key for signing in to the hub (E3): generated, held and used
+ * here, never handed to the page, which asks for a signature over
+ * `meshbay:user_auth:<username>:<ts>` — the bytes `POST /v1/users/auth`
+ * verifies. Not a per-node identity: nothing here correlates a person across
+ * operators (main.js `device:*`).
+ */
+class DeviceKey(private val store: Secrets, private val now: () -> Long = { System.currentTimeMillis() / 1000 }) {
+
+ private fun current(): Ed25519PrivateKeyParameters? {
+ val stored = store.read().optString(SecretStore.DEVICE_KEY, "")
+ return if (stored.isEmpty()) null else Kdf.edFromPkcs8(Kdf.unb64(stored))
+ }
+
+ private fun publicOf(k: Ed25519PrivateKeyParameters) = Kdf.b64(k.generatePublicKey().encoded)
+
+ fun ensure(): String {
+ current()?.let { return publicOf(it) }
+ val k = Ed25519PrivateKeyParameters(SecureRandom())
+ store.update { it.put(SecretStore.DEVICE_KEY, Kdf.b64(Kdf.edToPkcs8(k))) }
+ return publicOf(k)
+ }
+
+ fun publicKey(): String? = current()?.let { publicOf(it) }
+
+ fun sign(username: String): JSONObject? {
+ val k = current() ?: return null
+ val ts = now()
+ // The username is inside the signature, so one collected for another
+ // account is not usable.
+ val message = "meshbay:user_auth:$username:$ts".toByteArray(Charsets.UTF_8)
+ val s = Ed25519Signer().apply { init(true, k); update(message, 0, message.size) }
+ return JSONObject().put("timestamp", ts).put("signature", Kdf.b64(s.generateSignature()))
+ }
+
+ fun forget(): Boolean {
+ store.update { it.remove(SecretStore.DEVICE_KEY) }
+ return true
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Kdf.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Kdf.kt
new file mode 100644
index 0000000..404efcb
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Kdf.kt
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
+package org.meshbay.client.keys
+
+import org.bouncycastle.crypto.digests.SHA256Digest
+import org.bouncycastle.crypto.generators.Argon2BytesGenerator
+import org.bouncycastle.crypto.generators.HKDFBytesGenerator
+import org.bouncycastle.crypto.params.Argon2Parameters
+import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters
+import org.bouncycastle.crypto.params.HKDFParameters
+import org.bouncycastle.crypto.params.X25519PrivateKeyParameters
+import java.util.Base64
+import javax.crypto.Cipher
+import javax.crypto.spec.GCMParameterSpec
+import javax.crypto.spec.SecretKeySpec
+
+/**
+ * The primitives keyring.js takes from node:crypto and the vendored Argon2,
+ * with the same numbers. keyderive.js (the page), keyring.js (desktop) and this
+ * are one format: a mismatch looks like an account nobody can open, not like
+ * an error. meshbay-hub/tests/vectors/keyring.json holds them together.
+ */
+object Kdf {
+ // keyderive.js: the same numbers, or no bundle opens across the clients.
+ const val ARGON2_MEMORY_KIB = 131072
+ const val ARGON2_PASSES = 3
+ const val ARGON2_PARALLELISM = 1
+ const val ARGON2_TAG = 32
+
+ private val ED_PKCS8_PREFIX = hex("302e020100300506032b657004220420")
+ private val X_PKCS8_PREFIX = hex("302e020100300506032b656e04220420")
+
+ // One derivation at a time: 128 MiB each, on a phone. (Two concurrent
+ // lanes=4 derivations deadlock inside OpenSSL on the hub — CLAUDE.md; not
+ // this library, but there is no reason to find out.)
+ @Synchronized
+ fun argon2id(password: String, salt: ByteArray): ByteArray {
+ val params = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)
+ .withVersion(Argon2Parameters.ARGON2_VERSION_13)
+ .withIterations(ARGON2_PASSES)
+ .withMemoryAsKB(ARGON2_MEMORY_KIB)
+ .withParallelism(ARGON2_PARALLELISM)
+ .withSalt(salt)
+ .build()
+ val gen = Argon2BytesGenerator()
+ gen.init(params)
+ val out = ByteArray(ARGON2_TAG)
+ gen.generateBytes(password.toByteArray(Charsets.UTF_8), out)
+ return out
+ }
+
+ /** node:crypto hkdfSync('sha256', ikm, <empty salt>, info, 32). */
+ fun hkdf(ikm: ByteArray, info: String): ByteArray {
+ val gen = HKDFBytesGenerator(SHA256Digest())
+ gen.init(HKDFParameters(ikm, null, info.toByteArray(Charsets.UTF_8)))
+ val out = ByteArray(32)
+ gen.generateBytes(out, 0, 32)
+ return out
+ }
+
+ fun sha256(data: ByteArray): ByteArray {
+ val d = SHA256Digest()
+ d.update(data, 0, data.size)
+ val out = ByteArray(32)
+ d.doFinal(out, 0)
+ return out
+ }
+
+ /** AES-256-GCM, 16-byte tag appended — the layout node:crypto's getAuthTag gives. */
+ fun gcmSeal(key: ByteArray, nonce: ByteArray, plain: ByteArray, aad: ByteArray?): ByteArray {
+ val c = Cipher.getInstance("AES/GCM/NoPadding")
+ c.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
+ if (aad != null) c.updateAAD(aad)
+ return c.doFinal(plain)
+ }
+
+ fun gcmOpen(key: ByteArray, nonce: ByteArray, ctAndTag: ByteArray, aad: ByteArray?): ByteArray {
+ val c = Cipher.getInstance("AES/GCM/NoPadding")
+ c.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
+ if (aad != null) c.updateAAD(aad)
+ return c.doFinal(ctAndTag)
+ }
+
+ // Keys are stored as Node exports them: PKCS#8 DER, RFC 8410, 48 bytes, no
+ // public key attached. Written out by hand because a library's own PKCS#8
+ // encoder may add the optional public key, and the stored format is one.
+ fun edToPkcs8(k: Ed25519PrivateKeyParameters) = ED_PKCS8_PREFIX + k.encoded
+ fun xToPkcs8(k: X25519PrivateKeyParameters) = X_PKCS8_PREFIX + k.encoded
+
+ fun edFromPkcs8(der: ByteArray): Ed25519PrivateKeyParameters {
+ require(der.size == 48 && der.copyOfRange(0, 16).contentEquals(ED_PKCS8_PREFIX)) {
+ "not an Ed25519 PKCS#8 key"
+ }
+ return Ed25519PrivateKeyParameters(der, 16)
+ }
+
+ fun xFromPkcs8(der: ByteArray): X25519PrivateKeyParameters {
+ require(der.size == 48 && der.copyOfRange(0, 16).contentEquals(X_PKCS8_PREFIX)) {
+ "not an X25519 PKCS#8 key"
+ }
+ return X25519PrivateKeyParameters(der, 16)
+ }
+
+ fun b64(b: ByteArray): String = Base64.getEncoder().encodeToString(b)
+ fun unb64(s: String?): ByteArray = Base64.getDecoder().decode(s ?: "")
+ fun hex(s: String): ByteArray = ByteArray(s.length / 2) { s.substring(2 * it, 2 * it + 2).toInt(16).toByte() }
+ fun toHex(b: ByteArray): String = b.joinToString("") { "%02x".format(it) }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Keyring.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Keyring.kt
new file mode 100644
index 0000000..9a7dd9f
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Keyring.kt
@@ -0,0 +1,268 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
+package org.meshbay.client.keys
+
+import org.bouncycastle.crypto.agreement.X25519Agreement
+import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters
+import org.bouncycastle.crypto.params.X25519PrivateKeyParameters
+import org.bouncycastle.crypto.params.X25519PublicKeyParameters
+import org.bouncycastle.crypto.signers.Ed25519Signer
+import org.json.JSONObject
+import java.security.SecureRandom
+import org.meshbay.client.keys.Kdf.b64
+import org.meshbay.client.keys.Kdf.hkdf
+import org.meshbay.client.keys.Kdf.unb64
+
+/**
+ * The account's keys on Android: the bundle master key `M` and the identity on
+ * every node, held here and never handed to the page. A port of
+ * meshbay-client/src/keyring.js — same state shape (masters, identities,
+ * access), same formats, same refusals — so the two read side by side.
+ *
+ * Storage is injected (load/save of one JSON object), as on desktop; the app
+ * keeps it in SecretStore (Keystore-wrapped). `random` is injected so the
+ * vectors can pin a nonce.
+ */
+class Keyring(
+ private val load: () -> JSONObject?,
+ private val save: (JSONObject) -> Unit,
+ private val transcripts: Transcripts = Transcripts(),
+ private val random: (Int) -> ByteArray = { n -> ByteArray(n).also { SecureRandom().nextBytes(it) } },
+) {
+ class Pub(val pkEdB64: String, val pkXB64: String, val sealedWith: String? = null)
+ class Sealed(val bundle: String, val fingerprint: String)
+ class FormatRetired : IllegalStateException("bundle_format_retired")
+
+ private class Master(val m: ByteArray, val v: Int)
+ private class Identity(val ed: String, val x: String)
+
+ // In memory: the key of a passphrase change not yet accepted by the hub.
+ private val pending = HashMap<String, Master>()
+
+ private fun state(): JSONObject {
+ val s = load() ?: JSONObject()
+ for (k in listOf("masters", "identities", "access")) if (!s.has(k)) s.put(k, JSONObject())
+ return s
+ }
+
+ private fun master(userId: String, usePending: Boolean = false): Master {
+ if (usePending) pending[userId]?.let { return it }
+ val m = state().getJSONObject("masters").optJSONObject(userId)
+ ?: throw IllegalStateException("no bundle key in this session")
+ return Master(unb64(m.getString("m")), m.getInt("v"))
+ }
+
+ private fun fingerprint(m: ByteArray) = Kdf.toHex(Kdf.sha256(m)).substring(0, 16)
+
+ private fun stored(userId: String, nodePk: String): Identity {
+ val id = state().getJSONObject("identities").optJSONObject(userId)?.optJSONObject(nodePk)
+ ?: throw IllegalStateException("no identity for this node")
+ return Identity(id.getString("ed"), id.getString("x"))
+ }
+
+ private fun publicOf(id: Identity) = Pub(
+ b64(Kdf.edFromPkcs8(unb64(id.ed)).generatePublicKey().encoded),
+ b64(Kdf.xFromPkcs8(unb64(id.x)).generatePublicKey().encoded),
+ )
+
+ private fun accessOn(userId: String) = state().getJSONObject("access").opt(userId) != false
+ private fun needAccess(userId: String) {
+ if (!accessOn(userId)) throw IllegalStateException("Refused: browser access is off for this account")
+ }
+
+ private fun keep(userId: String, nodePk: String, put: (JSONObject) -> Unit) {
+ val s = state()
+ val ids = s.getJSONObject("identities")
+ val forUser = ids.optJSONObject(userId) ?: JSONObject().also { ids.put(userId, it) }
+ val entry = forUser.optJSONObject(nodePk) ?: JSONObject().also { forUser.put(nodePk, it) }
+ put(entry)
+ save(s)
+ }
+
+ private fun aad(userId: String, nodePk: String) =
+ "meshbay:bundle:v3|$userId|$nodePk".toByteArray(Charsets.UTF_8)
+
+ // Exactly JSON.stringify({ skEd, skX }): base64 needs no escaping, and the
+ // sealed bytes are then comparable with the desktop's in tests.
+ private fun plaintext(id: Identity) = "{\"skEd\":\"${id.ed}\",\"skX\":\"${id.x}\"}"
+
+ private fun seal(id: Identity, key: ByteArray, userId: String, nodePk: String, pepperVersion: Int): String {
+ val nonce = random(12)
+ val ct = Kdf.gcmSeal(key, nonce, plaintext(id).toByteArray(Charsets.UTF_8), aad(userId, nodePk))
+ return b64(MAGIC + byteArrayOf((pepperVersion and 0xff).toByte()) + nonce + ct)
+ }
+
+ private fun parse(plain: ByteArray): Identity {
+ val o = JSONObject(String(plain, Charsets.UTF_8))
+ return Identity(o.getString("skEd"), o.getString("skX"))
+ }
+
+ private fun open(bundleB64: String, key: ByteArray, userId: String, nodePk: String): Identity {
+ val raw = unb64(bundleB64)
+ if (raw.size < 4 || !raw.copyOfRange(0, 4).contentEquals(MAGIC)) throw FormatRetired()
+ return parse(Kdf.gcmOpen(key, raw.copyOfRange(5, 17), raw.copyOfRange(17, raw.size), aad(userId, nodePk)))
+ }
+
+ /** TRANSITIONAL — MBK2: "MBK2" ‖ nonce ‖ AES-GCM under the Argon2 key, no AAD. */
+ private fun openLegacy(bundleB64: String, key: ByteArray): Identity {
+ val raw = unb64(bundleB64)
+ return parse(Kdf.gcmOpen(key, raw.copyOfRange(4, 16), raw.copyOfRange(16, raw.size), null))
+ }
+
+ private fun fromMnemonic(mnemonic: String): ByteArray {
+ val clean = mnemonic.replace(Regex("[^A-Za-z2-7]"), "").uppercase()
+ var bits = 0
+ var value = 0
+ val out = ArrayList<Byte>()
+ for (ch in clean) {
+ value = (value shl 5) or B32.indexOf(ch)
+ bits += 5
+ if (bits >= 8) { out.add(((value ushr (bits - 8)) and 0xff).toByte()); bits -= 8 }
+ }
+ if (out.size < 32) throw IllegalArgumentException("recovery key too short")
+ return out.subList(0, 32).toByteArray()
+ }
+
+ // ── The API, in keyring.js order ────────────────────────────────────────
+
+ fun hasSession(userId: String) = state().getJSONObject("masters").has(userId)
+
+ /** `M` from the passphrase and the pepper — one Argon2 run, as in the page. */
+ fun deriveSession(password: String, username: String, userId: String, pepperB64: String?,
+ pepperVersion: Int?, pendingChange: Boolean = false): Boolean {
+ if (userId.isEmpty() || pepperB64.isNullOrEmpty()) {
+ throw IllegalStateException("the hub did not provide the bundle pepper")
+ }
+ val salt = Kdf.sha256("meshbay:bundle:v2:$username".toByteArray(Charsets.UTF_8)).copyOfRange(0, 16)
+ val a = Kdf.argon2id(password, salt)
+ val m = hkdf(a + unb64(pepperB64), "meshbay:bundle-master:v3|$userId")
+ val v = if (pepperVersion == null || pepperVersion == 0) 1 else pepperVersion
+ if (pendingChange) { pending[userId] = Master(m, v); return true }
+ val s = state()
+ // `legacy` (TRANSITIONAL): the Argon2 key MBK2 bundles were sealed under.
+ s.getJSONObject("masters").put(userId, JSONObject().put("m", b64(m)).put("v", v).put("legacy", b64(a)))
+ save(s)
+ return true
+ }
+
+ fun commitPending(userId: String): Boolean {
+ val p = pending[userId] ?: return false
+ val s = state()
+ val legacy = s.getJSONObject("masters").optJSONObject(userId)?.optString("legacy", "")
+ val entry = JSONObject().put("m", b64(p.m)).put("v", p.v)
+ if (!legacy.isNullOrEmpty()) entry.put("legacy", legacy)
+ s.getJSONObject("masters").put(userId, entry)
+ save(s)
+ pending.remove(userId)
+ return true
+ }
+
+ fun dropPending(userId: String) = pending.remove(userId) != null
+
+ /** Sign-out: `M` goes. The identities stay — they are this device's. */
+ fun forgetSession(userId: String): Boolean {
+ val s = state()
+ s.getJSONObject("masters").remove(userId)
+ save(s)
+ pending.remove(userId)
+ return true
+ }
+
+ fun identity(userId: String, nodePk: String): Pub? {
+ val id = state().getJSONObject("identities").optJSONObject(userId)?.optJSONObject(nodePk) ?: return null
+ val pub = publicOf(Identity(id.getString("ed"), id.getString("x")))
+ val sw = id.opt("sealedWith")
+ return Pub(pub.pkEdB64, pub.pkXB64, if (sw is String) sw else null)
+ }
+
+ fun openBundle(userId: String, nodePk: String, bundleEnc: String, recoveryEnc: String? = null,
+ recoveryMnemonic: String? = null, username: String? = null): Pub {
+ val raw = unb64(bundleEnc)
+ if (raw.size >= 4 && raw.copyOfRange(0, 4).contentEquals(LEGACY_MAGIC)) {
+ val legacy = state().getJSONObject("masters").optJSONObject(userId)?.optString("legacy", "")
+ if (legacy.isNullOrEmpty()) throw IllegalStateException("no_legacy_key")
+ val id = openLegacy(bundleEnc, unb64(legacy))
+ keepIdentity(userId, nodePk, id)
+ return publicOf(id)
+ }
+ val m = master(userId).m
+ val id = try {
+ open(bundleEnc, hkdf(m, "meshbay:bundle:v3|node|$nodePk"), userId, nodePk)
+ } catch (e: Exception) {
+ if (e is FormatRetired || recoveryEnc.isNullOrEmpty() || recoveryMnemonic.isNullOrEmpty()) throw e
+ val rk = hkdf(fromMnemonic(recoveryMnemonic), "meshbay:recovery:v1:${username ?: ""}")
+ open(recoveryEnc, rk, userId, nodePk)
+ }
+ keepIdentity(userId, nodePk, id)
+ return publicOf(id)
+ }
+
+ private fun keepIdentity(userId: String, nodePk: String, id: Identity) =
+ keep(userId, nodePk) { it.put("ed", id.ed).put("x", id.x).put("sealedWith", JSONObject.NULL) }
+
+ fun mint(userId: String, nodePk: String): Pub {
+ val rnd = SecureRandom()
+ val id = Identity(b64(Kdf.edToPkcs8(Ed25519PrivateKeyParameters(rnd))),
+ b64(Kdf.xToPkcs8(X25519PrivateKeyParameters(rnd))))
+ keepIdentity(userId, nodePk, id)
+ return publicOf(id)
+ }
+
+ /** The identity sealed for its node, under `M` (or the pending one). */
+ fun sealBundle(userId: String, nodePk: String, usePending: Boolean = false): Sealed {
+ needAccess(userId)
+ val m = master(userId, usePending)
+ val bundle = seal(stored(userId, nodePk), hkdf(m.m, "meshbay:bundle:v3|node|$nodePk"), userId, nodePk, m.v)
+ return Sealed(bundle, fingerprint(m.m))
+ }
+
+ /** The recovery copy: sealed under the recovery key, owing nothing to `M`. */
+ fun sealRecovery(userId: String, nodePk: String, mnemonic: String, username: String): String {
+ needAccess(userId)
+ val rk = hkdf(fromMnemonic(mnemonic), "meshbay:recovery:v1:$username")
+ return seal(stored(userId, nodePk), rk, userId, nodePk, 0)
+ }
+
+ fun markSealed(userId: String, nodePk: String, fp: String?): Boolean {
+ keep(userId, nodePk) { it.put("sealedWith", if (fp.isNullOrEmpty()) JSONObject.NULL else fp) }
+ return true
+ }
+
+ fun currentFingerprint(userId: String) = fingerprint(master(userId).m)
+
+ /** Sign what `kind` names, built from `fields` (Transcripts). */
+ fun signAs(userId: String, nodePk: String, kind: String, fields: JSONObject?): String {
+ val id = stored(userId, nodePk)
+ val pub = publicOf(id)
+ val transcript = transcripts.forKind(kind, fields, Transcripts.Ctx(userId, nodePk, pub.pkEdB64, pub.pkXB64))
+ val signer = Ed25519Signer()
+ signer.init(true, Kdf.edFromPkcs8(unb64(id.ed)))
+ signer.update(transcript, 0, transcript.size)
+ return b64(signer.generateSignature())
+ }
+
+ fun shared(userId: String, nodePk: String, peerPkB64: String): String {
+ val agreement = X25519Agreement()
+ agreement.init(Kdf.xFromPkcs8(unb64(stored(userId, nodePk).x)))
+ val out = ByteArray(32)
+ agreement.calculateAgreement(X25519PublicKeyParameters(unb64(peerPkB64), 0), out, 0)
+ return b64(out)
+ }
+
+ fun playlistKey(userId: String) = b64(hkdf(master(userId).m, "meshbay:playlists:v2"))
+
+ fun browserAccess(userId: String) = accessOn(userId)
+ fun setBrowserAccess(userId: String, on: Boolean): Boolean {
+ val s = state()
+ s.getJSONObject("access").put(userId, on)
+ save(s)
+ return on
+ }
+
+ companion object {
+ private val MAGIC = "MBK3".toByteArray()
+ // TRANSITIONAL — the format before MBK3, read once to be replaced.
+ private val LEGACY_MAGIC = "MBK2".toByteArray()
+ private const val B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/SecretStore.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/SecretStore.kt
new file mode 100644
index 0000000..5a2c1bb
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/SecretStore.kt
@@ -0,0 +1,120 @@
+package org.meshbay.client.keys
+
+import android.content.Context
+import android.security.keystore.KeyGenParameterSpec
+import android.security.keystore.KeyProperties
+import android.security.keystore.StrongBoxUnavailableException
+import android.util.Log
+import org.json.JSONObject
+import java.io.File
+import java.security.KeyStore
+import javax.crypto.Cipher
+import javax.crypto.KeyGenerator
+import javax.crypto.SecretKey
+import javax.crypto.spec.GCMParameterSpec
+
+/**
+ * The application's secrets, at rest: the desktop's safeStorage blob, here
+ * wrapped by an AES-256-GCM key that lives in Android Keystore and never leaves
+ * it (in StrongBox where the device has one).
+ *
+ * One file, `files/secrets.bin` = nonce ‖ ciphertext ‖ tag over the JSON of
+ * every slot (`device_key`, `keyring` — main.js's slots), replaced atomically.
+ * Nothing in it is reachable from the page: it holds the device's hub key.
+ *
+ * Honest without protection, as on desktop: if the Keystore cannot be used,
+ * `backend()` says `unavailable` and nothing is stored — the page then keeps
+ * its keys the way a browser does, rather than this downgrading silently.
+ */
+/** What the keys need of their storage; SecretStore on a device, a map in tests. */
+interface Secrets {
+ fun backend(): String
+ fun read(): JSONObject
+ fun update(fn: (JSONObject) -> Unit)
+}
+
+class SecretStore(private val context: Context) : Secrets {
+ private val file get() = File(context.filesDir, "secrets.bin")
+ @Volatile private var strongBox = false
+
+ private fun key(): SecretKey? = try {
+ val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ (ks.getKey(ALIAS, null) as SecretKey?) ?: generate()
+ } catch (e: Exception) {
+ Log.w(TAG, "Keystore unusable", e)
+ null
+ }
+
+ private fun generate(): SecretKey {
+ fun spec(strong: Boolean) = KeyGenParameterSpec.Builder(ALIAS,
+ KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .setKeySize(256)
+ // Usable without a prompt: the app answers the hub on its own, as
+ // the desktop keychain does once the session is unlocked.
+ .setUserAuthenticationRequired(false)
+ .setRandomizedEncryptionRequired(true)
+ .apply { if (strong) setIsStrongBoxBacked(true) }
+ .build()
+ val gen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
+ return try {
+ gen.init(spec(true)); gen.generateKey().also { strongBox = true }
+ } catch (e: StrongBoxUnavailableException) {
+ gen.init(spec(false)); gen.generateKey()
+ }
+ }
+
+ override fun backend(): String {
+ if (key() == null) return "unavailable"
+ return if (strongBox || isStrongBox()) "android_strongbox" else "android_keystore"
+ }
+
+ private fun isStrongBox(): Boolean = try {
+ val k = key() ?: return false
+ val info = javax.crypto.SecretKeyFactory.getInstance(k.algorithm, "AndroidKeyStore")
+ .getKeySpec(k, android.security.keystore.KeyInfo::class.java) as android.security.keystore.KeyInfo
+ if (android.os.Build.VERSION.SDK_INT >= 31) info.securityLevel == KeyProperties.SECURITY_LEVEL_STRONGBOX else false
+ } catch (e: Exception) { false }
+
+ @Synchronized
+ override fun read(): JSONObject {
+ val k = key() ?: return JSONObject()
+ val raw = try { file.readBytes() } catch (e: java.io.FileNotFoundException) { return JSONObject() }
+ return try {
+ val c = Cipher.getInstance("AES/GCM/NoPadding")
+ c.init(Cipher.DECRYPT_MODE, k, GCMParameterSpec(128, raw, 0, 12))
+ JSONObject(String(c.doFinal(raw, 12, raw.size - 12), Charsets.UTF_8))
+ } catch (e: Exception) {
+ // A store that does not open is reported, never overwritten: what
+ // is in it is a device key and identities nodes have pinned.
+ throw IllegalStateException("the key store does not open", e)
+ }
+ }
+
+ @Synchronized
+ fun write(all: JSONObject) {
+ val k = key() ?: throw IllegalStateException("No OS key storage")
+ val c = Cipher.getInstance("AES/GCM/NoPadding")
+ c.init(Cipher.ENCRYPT_MODE, k)
+ val sealed = c.iv + c.doFinal(all.toString().toByteArray(Charsets.UTF_8))
+ val tmp = File(context.filesDir, "secrets.bin.tmp")
+ tmp.writeBytes(sealed)
+ if (!tmp.renameTo(file)) throw IllegalStateException("could not replace the key store")
+ }
+
+ /** One slot, read and replaced under the same lock. */
+ @Synchronized
+ override fun update(fn: (JSONObject) -> Unit) {
+ val all = read()
+ fn(all)
+ write(all)
+ }
+
+ companion object {
+ private const val TAG = "MeshBay"
+ private const val ALIAS = "meshbay.secrets.v1"
+ const val DEVICE_KEY = "device_key"
+ const val KEYRING_SLOT = "keyring"
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Transcripts.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Transcripts.kt
new file mode 100644
index 0000000..cf20a0b
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Transcripts.kt
@@ -0,0 +1,185 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
+package org.meshbay.client.keys
+
+import org.json.JSONObject
+import java.io.ByteArrayOutputStream
+import java.util.Base64
+import kotlin.math.abs
+
+/**
+ * What a node identity signs, built here from named fields — never bytes the
+ * page chose. A port of meshbay-client/src/transcripts.js, byte for byte; the
+ * shapes it checks and the refusals it gives are the same, and
+ * meshbay-hub/tests/vectors/keyring.json is what holds them (and
+ * meshbay_common) together.
+ *
+ * `now` is injected so the vectors can pin the clock; production passes the
+ * system clock.
+ */
+class Transcripts(private val now: () -> Double = { System.currentTimeMillis() / 1000.0 }) {
+
+ class Refused(what: String) : IllegalArgumentException("Refused: $what")
+
+ data class Ctx(val userId: String, val nodePk: String, val pkEdB64: String, val pkXB64: String)
+
+ private fun refuse(what: String): Nothing = throw Refused(what)
+
+ private fun enc(s: String) = s.toByteArray(Charsets.UTF_8)
+
+ private fun lenPrefixed(prefix: String, parts: List<ByteArray>): ByteArray {
+ val out = ByteArrayOutputStream()
+ out.write(prefix.toByteArray(Charsets.UTF_8))
+ for (p in parts) {
+ out.write(byteArrayOf((p.size ushr 24).toByte(), (p.size ushr 16).toByte(),
+ (p.size ushr 8).toByte(), p.size.toByte()))
+ out.write(p)
+ }
+ return out.toByteArray()
+ }
+
+ // JavaScript's String(v ?? '') over a value that came through JSON.
+ private fun jsString(v: Any?): String = when (v) {
+ null, JSONObject.NULL -> ""
+ is String -> v
+ is Boolean -> v.toString()
+ is Int, is Long -> v.toString()
+ is Number -> {
+ val d = v.toDouble()
+ if (d == Math.floor(d) && !d.isInfinite() && abs(d) < 1e21) d.toLong().toString() else d.toString()
+ }
+ else -> v.toString()
+ }
+
+ // JavaScript's Number(v), for the values a timestamp or an epoch can arrive as.
+ private fun jsNumber(v: Any?): Double = when (v) {
+ null, JSONObject.NULL -> if (v == null) Double.NaN else 0.0
+ is Number -> v.toDouble()
+ is Boolean -> if (v) 1.0 else 0.0
+ is String -> v.trim().let { if (it.isEmpty()) 0.0 else it.toDoubleOrNull() ?: Double.NaN }
+ else -> Double.NaN
+ }
+
+ private fun isInteger(d: Double) = !d.isNaN() && !d.isInfinite() && d == Math.floor(d)
+
+ private val base64Shape = Regex("^[A-Za-z0-9+/]*={0,2}$")
+
+ private fun bytes(v: Any?, what: String, min: Int = 1, max: Int = 64): ByteArray {
+ val s = jsString(v)
+ if (!base64Shape.matches(s)) refuse("$what is not base64")
+ // Node's decoder is lenient where Java's throws (a lone trailing
+ // character). Both outcomes are a refusal: Node's yields a short
+ // buffer that the length check below refuses.
+ val b = try { Base64.getDecoder().decode(s) } catch (e: IllegalArgumentException) {
+ refuse("$what has the wrong length")
+ }
+ if (b.size < min || b.size > max) refuse("$what has the wrong length")
+ return b
+ }
+
+ private fun key32(v: Any?, what: String): String {
+ bytes(v, what, 32, 32)
+ return jsString(v)
+ }
+
+ private fun text(v: Any?, what: String, max: Int = 256): String {
+ val s = jsString(v)
+ if (s.length > max) refuse("$what is too long") // UTF-16 units, as JS counts
+ return s
+ }
+
+ private val groupShape = Regex("^[A-Za-z0-9_-]{1,64}$")
+ private fun groupId(v: Any?): String {
+ val s = jsString(v)
+ if (s.isNotEmpty() && !groupShape.matches(s)) refuse("not a group id")
+ return s
+ }
+
+ private fun timestamp(v: Any?): String {
+ val n = jsNumber(v)
+ if (!isInteger(n) || abs(n - now()) > TS_SLACK_S) refuse("the timestamp is not now")
+ return jsString(n.toLong())
+ }
+
+ fun forKind(kind: String, f: JSONObject?, ctx: Ctx): ByteArray {
+ val fields = f ?: JSONObject()
+ fun field(name: String): Any? = if (fields.has(name)) fields.get(name) else null
+ fun sameNode(): String {
+ if (jsString(field("nodePk")) != ctx.nodePk) refuse("another node")
+ return ctx.nodePk
+ }
+ fun sameUser(): String {
+ if (jsString(field("userId")) != ctx.userId) refuse("another account")
+ return ctx.userId
+ }
+ fun nonceNode() = bytes(field("nonceNode"), "the node nonce", 16, 64)
+
+ return when (kind) {
+ "join" -> lenPrefixed(PREFIX_JOIN, listOf(
+ enc(sameNode()), enc(groupId(field("groupId"))), enc(sameUser()),
+ enc(ctx.pkEdB64), enc(ctx.pkXB64), nonceNode(), enc(timestamp(field("ts")))))
+ "device_hello" -> lenPrefixed(PREFIX_DEVICE_HELLO, listOf(
+ enc(sameNode()), enc(groupId(field("groupId"))), enc(sameUser()),
+ enc(ctx.pkEdB64), nonceNode(), enc(timestamp(field("ts")))))
+ "device_request" -> {
+ val codeHash = jsString(field("codeHash"))
+ if (!Regex("^[0-9a-f]{64}$").matches(codeHash)) refuse("not a request hash")
+ lenPrefixed(PREFIX_DEVICE_REQUEST, listOf(
+ enc(sameNode()), enc(sameUser()), enc(ctx.pkEdB64), enc(ctx.pkXB64),
+ enc(codeHash), nonceNode(), enc(timestamp(field("ts")))))
+ }
+ "device_add" -> lenPrefixed(PREFIX_DEVICE_ADD, listOf(
+ enc(sameNode()), enc(sameUser()), enc(key32(field("pkEd"), "the device key")),
+ enc(key32(field("pkX"), "the device key")), nonceNode(), enc(timestamp(field("ts")))))
+ "device_revoke" -> lenPrefixed(PREFIX_DEVICE_REVOKE, listOf(
+ enc(sameNode()), enc(sameUser()), enc(key32(field("pkEd"), "the device key")),
+ nonceNode(), enc(timestamp(field("ts")))))
+ "chat" -> {
+ val epoch = jsNumber(field("epoch"))
+ if (!isInteger(epoch) || epoch < 0) refuse("not an epoch")
+ lenPrefixed(PREFIX_CHAT, listOf(
+ enc(groupId(field("groupId"))), enc(jsString(epoch.toLong())),
+ Base64.getDecoder().decode(ctx.pkEdB64),
+ bytes(field("nonce"), "the message nonce", 12, 24),
+ bytes(field("ct"), "the message", 1, 8 * 1024 * 1024)))
+ }
+ "admin" -> {
+ val op = jsString(field("op"))
+ if (op !in ADMIN_OPS) refuse("not an operation")
+ lenPrefixed(PREFIX_ADMIN, listOf(
+ enc(op), enc(sameNode()), enc(groupId(field("groupId"))),
+ enc(text(field("subject"), "the subject", 16384)),
+ bytes(field("nonce"), "the challenge nonce", 16, 64),
+ enc(timestamp(field("ts")))))
+ }
+ else -> refuse("nothing is signed as \"${kind.take(32)}\"")
+ }
+ }
+
+ companion object {
+ // The node's clock and ours: a signature for a moment far from now is one to keep for later.
+ const val TS_SLACK_S = 600
+
+ // The signed operations this application asks a node to perform
+ // (meshbay_common/adminop.py) — transcripts.js's list, held equal by
+ // test_android_keys.py. A list, not a pattern: what widens a node's
+ // sharing (root_add, root_update, group_attach — gone from MNP 6.0) is
+ // never signed here, so a script in the page cannot drive an older node
+ // into it either.
+ val ADMIN_OPS = setOf(
+ "file_delete", "dir_delete", "invite_create", "invite_link_create",
+ "invite_cancel", "member_revoke", "apps_enabled", "set_scan_settings",
+ "tmdb_config", "tmdb_enabled", "tmdb_override", "tmdb_rematch",
+ "musicbrainz_enabled", "root_remove", "root_eject", "root_plug",
+ "app_directories", "chat_directory", "chat_link_preview", "search_listed",
+ "chat_epoch",
+ )
+ const val PREFIX_JOIN = "meshbay:join:v1"
+ const val PREFIX_DEVICE_REQUEST = "meshbay:device_req:v1"
+ const val PREFIX_DEVICE_ADD = "meshbay:device_add:v1"
+ const val PREFIX_DEVICE_REVOKE = "meshbay:device_revoke:v1"
+ const val PREFIX_DEVICE_HELLO = "meshbay:device_hello:v1"
+ const val PREFIX_CHAT = "meshbay:chat:v1"
+ const val PREFIX_ADMIN = "meshbay:admin:v1"
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/save/SaveNames.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/save/SaveNames.kt
new file mode 100644
index 0000000..40250c7
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/save/SaveNames.kt
@@ -0,0 +1,75 @@
+package org.meshbay.client.save
+
+/** The pure part of saving: names, types and the binary frame. JVM-tested. */
+object SaveNames {
+ private val BIDI = Regex("[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]")
+
+ /**
+ * main.js `save:begin`: the basename only, bidirectional controls replaced
+ * — "invoice‮fdp.exe" would otherwise be listed as "invoiceexe.pdf".
+ */
+ fun sanitize(suggested: String?): String {
+ val base = (suggested ?: "").replace('\\', '/').substringAfterLast('/')
+ .replace(BIDI, "_").replace(Regex("[\\u0000-\\u001f]"), "_").trim()
+ return if (base.isEmpty() || base == "." || base == "..") "download" else base
+ }
+
+ /**
+ * downloads.js `OPENABLE`, entry for entry (test_android_downloads.py):
+ * what may be handed to another app to open, under a type chosen from the
+ * name — never one guessed from the bytes.
+ */
+ val OPENABLE = mapOf(
+ "pdf" to "application/pdf",
+ "png" to "image/png", "jpg" to "image/jpeg", "jpeg" to "image/jpeg", "gif" to "image/gif",
+ "webp" to "image/webp", "avif" to "image/avif", "bmp" to "image/bmp",
+ "mp3" to "audio/mpeg", "m4a" to "audio/mp4", "aac" to "audio/aac", "ogg" to "audio/ogg",
+ "oga" to "audio/ogg", "opus" to "audio/ogg", "flac" to "audio/flac", "wav" to "audio/wav",
+ "mp4" to "video/mp4", "m4v" to "video/mp4", "webm" to "video/webm", "ogv" to "video/ogg",
+ "mov" to "video/quicktime",
+ "txt" to "text/plain", "log" to "text/plain", "md" to "text/plain", "csv" to "text/plain",
+ )
+
+ fun extension(name: String): String? = Regex("\\.([A-Za-z0-9]+)$").find(name)?.groupValues?.get(1)?.lowercase()
+
+ fun openableType(name: String): String? = extension(name)?.let { OPENABLE[it] }
+
+ /** The type a file is created under: openable ones by name, the rest opaque. */
+ fun storedType(name: String): String = openableType(name) ?: "application/octet-stream"
+
+ /** "name (n).ext", as main.js `freeName` — never an overwrite. */
+ fun numbered(name: String, n: Int): String {
+ val ext = extension(name)?.let { ".$it" } ?: ""
+ val stem = if (ext.isEmpty()) name else name.dropLast(ext.length)
+ return "$stem ($n)$ext"
+ }
+}
+
+/**
+ * A binary bridge message: one write, no JSON, no base64.
+ *
+ * "MBB1" | u32 request id | u16 channel | u16 reserved | u32 handle | bytes
+ *
+ * all big-endian. The reply is an ordinary JSON reply carrying the id.
+ */
+class BinaryFrame(val id: Long, val channel: Int, val handle: Long, val bytes: ByteArray, val offset: Int) {
+ val length get() = bytes.size - offset
+
+ companion object {
+ const val HEADER = 16
+ const val SAVE_WRITE = 1
+ const val CAST_PUSH = 2
+ const val CAST_FILE = 3
+ private val MAGIC = byteArrayOf('M'.code.toByte(), 'B'.code.toByte(), 'B'.code.toByte(), '1'.code.toByte())
+
+ private fun u32(b: ByteArray, at: Int) =
+ ((b[at].toLong() and 0xff) shl 24) or ((b[at + 1].toLong() and 0xff) shl 16) or
+ ((b[at + 2].toLong() and 0xff) shl 8) or (b[at + 3].toLong() and 0xff)
+
+ fun parse(b: ByteArray): BinaryFrame? {
+ if (b.size < HEADER || !(0 until 4).all { b[it] == MAGIC[it] }) return null
+ val channel = ((b[8].toInt() and 0xff) shl 8) or (b[9].toInt() and 0xff)
+ return BinaryFrame(u32(b, 4), channel, u32(b, 12), b, HEADER)
+ }
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/save/SaveSinks.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/save/SaveSinks.kt
new file mode 100644
index 0000000..2da7ec7
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/save/SaveSinks.kt
@@ -0,0 +1,238 @@
+package org.meshbay.client.save
+
+import android.content.ContentResolver
+import android.content.ContentValues
+import android.content.Context
+import android.content.Intent
+import android.content.SharedPreferences
+import android.net.Uri
+import android.os.Build
+import android.provider.DocumentsContract
+import android.provider.MediaStore
+import android.util.Log
+import org.json.JSONObject
+import org.meshbay.client.bridge.Refused
+import org.meshbay.client.shell.Pickers
+import java.io.OutputStream
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.AtomicLong
+
+/**
+ * Downloads, written to disk as they arrive — never collected in the page and
+ * handed over at the end (§8.5; main.js `save:*`).
+ *
+ * The page never names a path or a URI: it asks, is told a display name, and
+ * holds an opaque id. Where a file lands:
+ *
+ * - **automatic**, a folder chosen in Settings → that folder (a Storage Access
+ * Framework tree), as `<name>.part`, renamed on completion;
+ * - **automatic**, no folder chosen → the system's Downloads collection, as a
+ * pending entry that only becomes visible when complete — the Android form
+ * of `.part`;
+ * - **asked**, or a chosen folder that has gone → the system save dialog.
+ * A folder that was chosen and has since gone is never silently replaced
+ * by Downloads: somebody who picked a card wants to know it is not there.
+ *
+ * An unfinished file never carries the final name where that can be avoided,
+ * an aborted one is deleted, and one left by a killed process is deleted at the
+ * next start — Android gives no reliable quit hook, so `before-quit`'s cleanup
+ * happens there.
+ */
+class SaveSinks(
+ private val context: Context,
+ private val prefs: SharedPreferences,
+ private val pickers: Pickers,
+ private val startActivity: (Intent) -> Unit,
+) {
+ private enum class Kind { TREE_PART, MEDIASTORE, PICKED }
+
+ private class Sink(val uri: Uri, val out: OutputStream, val kind: Kind, val finalName: String, val tree: Uri?)
+
+ private val resolver: ContentResolver get() = context.contentResolver
+ private val sinks = ConcurrentHashMap<Long, Sink>()
+ private val completed = ConcurrentHashMap<Long, Pair<Uri, String>>()
+ private val ids = AtomicLong()
+
+ // ── Where downloads go ──────────────────────────────────────────────────
+
+ private val configuredTree: Uri? get() = prefs.getString(KEY_TREE, null)?.let(Uri::parse)
+
+ /** The chosen folder, if it is still there and still ours to write. */
+ private fun usableTree(): Uri? {
+ val tree = configuredTree ?: return null
+ val held = resolver.persistedUriPermissions.any { it.uri == tree && it.isWritePermission }
+ return if (held && displayName(treeDocument(tree)) != null) tree else null
+ }
+
+ private fun treeDocument(tree: Uri) =
+ DocumentsContract.buildDocumentUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree))
+
+ private fun displayName(uri: Uri): String? = try {
+ resolver.query(uri, arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME), null, null, null)?.use {
+ if (it.moveToFirst()) it.getString(0) else null
+ }
+ } catch (e: Exception) { null }
+
+ fun chooseFolder(): String? {
+ val result = pickers.run(Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)) ?: return null
+ val tree = result.data ?: return null
+ resolver.takePersistableUriPermission(tree,
+ Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
+ configuredTree?.takeIf { it != tree }?.let { release(it) }
+ prefs.edit().putString(KEY_TREE, tree.toString()).apply()
+ return displayName(treeDocument(tree)) ?: "folder"
+ }
+
+ /** `{name, isDefault}`, which the Settings row renders; a name, never a URI. */
+ fun getFolder(): JSONObject {
+ val tree = usableTree()
+ val name = tree?.let { displayName(treeDocument(it)) }
+ return JSONObject().put("name", name ?: DEFAULT_NAME).put("isDefault", name == null)
+ }
+
+ fun forgetFolder(): Boolean {
+ configuredTree?.let { release(it) }
+ prefs.edit().remove(KEY_TREE).apply()
+ return true
+ }
+
+ private fun release(tree: Uri) {
+ try {
+ resolver.releasePersistableUriPermission(tree,
+ Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
+ } catch (e: SecurityException) { /* already gone */ }
+ }
+
+ // ── Writing ─────────────────────────────────────────────────────────────
+
+ fun begin(suggestedName: String?, auto: Boolean): JSONObject? {
+ val wanted = SaveNames.sanitize(suggestedName)
+ val type = SaveNames.storedType(wanted)
+ val tree = usableTree()
+ var target: Pair<Uri, Kind>? = null
+
+ if (auto && !(configuredTree != null && tree == null)) {
+ target = try {
+ when {
+ tree != null -> DocumentsContract.createDocument(resolver, treeDocument(tree),
+ "application/octet-stream", "$wanted.part")?.let { it to Kind.TREE_PART }
+ Build.VERSION.SDK_INT >= 29 -> resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI,
+ ContentValues().apply {
+ put(MediaStore.MediaColumns.DISPLAY_NAME, wanted)
+ put(MediaStore.MediaColumns.MIME_TYPE, type)
+ put(MediaStore.MediaColumns.IS_PENDING, 1)
+ })?.let { it to Kind.MEDIASTORE }
+ else -> null
+ }
+ } catch (e: Exception) {
+ Log.w(TAG, "automatic save target failed", e); null
+ }
+ }
+ if (target == null) {
+ val ask = Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE)
+ .setType(type).putExtra(Intent.EXTRA_TITLE, wanted)
+ tree?.let { ask.putExtra(DocumentsContract.EXTRA_INITIAL_URI, treeDocument(it)) }
+ val uri = pickers.run(ask)?.data ?: return null // dismissed: not an error
+ target = uri to Kind.PICKED
+ }
+
+ val (uri, kind) = target
+ val out = resolver.openOutputStream(uri, "wt") ?: throw Refused("Could not write the file")
+ val id = ids.incrementAndGet()
+ val shown = if (kind == Kind.TREE_PART) wanted else (displayName(uri) ?: wanted)
+ sinks[id] = Sink(uri, out, kind, wanted, tree)
+ rememberPending(uri, true)
+ return JSONObject().put("id", id).put("name", shown)
+ .put("openable", SaveNames.openableType(shown) != null)
+ }
+
+ /** Returns once the bytes are written: the await is the backpressure. */
+ fun write(id: Long, bytes: ByteArray, offset: Int, length: Int): Boolean {
+ val sink = sinks[id] ?: throw Refused("No such download")
+ synchronized(sink) { sink.out.write(bytes, offset, length) }
+ return true
+ }
+
+ fun end(id: Long): Boolean {
+ val sink = sinks.remove(id) ?: return false
+ synchronized(sink) { sink.out.flush(); sink.out.close() }
+ // Publishing the file is what makes it complete — only after the stream
+ // has flushed, or the final name would be on a short file.
+ val published: Uri = try {
+ when (sink.kind) {
+ Kind.MEDIASTORE -> {
+ resolver.update(sink.uri, ContentValues().apply { put(MediaStore.MediaColumns.IS_PENDING, 0) }, null, null)
+ sink.uri
+ }
+ Kind.TREE_PART -> renameFree(sink.uri, sink.finalName)
+ Kind.PICKED -> sink.uri
+ }
+ } catch (e: Exception) {
+ Log.e(TAG, "could not finalise a download", e)
+ return false
+ }
+ rememberPending(sink.uri, false)
+ completed[id] = published to (displayName(published) ?: sink.finalName)
+ return true
+ }
+
+ private fun renameFree(uri: Uri, name: String): Uri {
+ var candidate = name
+ for (n in 2 until 1000) {
+ try {
+ return DocumentsContract.renameDocument(resolver, uri, candidate) ?: uri
+ } catch (e: Exception) {
+ // Most providers refuse a name that exists; try the next one.
+ candidate = SaveNames.numbered(name, n)
+ }
+ }
+ throw IllegalStateException("No free name for $name")
+ }
+
+ fun abort(id: Long): Boolean {
+ val sink = sinks.remove(id) ?: return false
+ synchronized(sink) { try { sink.out.close() } catch (e: Exception) { /* already closed */ } }
+ // A cancelled download leaves nothing: a truncated file looks like a
+ // complete one to whoever opens it next.
+ delete(sink.uri)
+ rememberPending(sink.uri, false)
+ return true
+ }
+
+ /** Hand a finished file to the app that opens its type — only a type that runs nothing. */
+ fun open(id: Long): Boolean {
+ val (uri, name) = completed[id] ?: return false
+ val type = SaveNames.openableType(name) ?: throw Refused("This kind of file is not opened from here")
+ startActivity(Intent(Intent.ACTION_VIEW).setDataAndType(uri, type)
+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK))
+ return true
+ }
+
+ // ── What a killed process left behind ───────────────────────────────────
+
+ private fun rememberPending(uri: Uri, add: Boolean) = synchronized(prefs) {
+ val set = HashSet(prefs.getStringSet(KEY_PENDING, emptySet()) ?: emptySet())
+ if (add) set.add(uri.toString()) else set.remove(uri.toString())
+ prefs.edit().putStringSet(KEY_PENDING, set).commit()
+ }
+
+ fun cleanUpAfterAKilledProcess() {
+ val pending = prefs.getStringSet(KEY_PENDING, emptySet()) ?: emptySet()
+ for (u in pending) delete(Uri.parse(u))
+ prefs.edit().remove(KEY_PENDING).apply()
+ }
+
+ private fun delete(uri: Uri) {
+ try {
+ if (DocumentsContract.isDocumentUri(context, uri)) DocumentsContract.deleteDocument(resolver, uri)
+ else resolver.delete(uri, null, null)
+ } catch (e: Exception) { Log.w(TAG, "could not remove an unfinished download", e) }
+ }
+
+ companion object {
+ private const val TAG = "MeshBay"
+ private const val KEY_TREE = "downloadTree"
+ private const val KEY_PENDING = "pendingDownloads"
+ const val DEFAULT_NAME = "Downloads"
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/EngineCheck.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/EngineCheck.kt
new file mode 100644
index 0000000..6382182
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/EngineCheck.kt
@@ -0,0 +1,57 @@
+package org.meshbay.client.shell
+
+import android.content.ActivityNotFoundException
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.view.Gravity
+import android.view.View
+import android.widget.Button
+import android.widget.LinearLayout
+import android.widget.TextView
+import androidx.webkit.WebViewCompat
+import androidx.webkit.WebViewFeature
+
+/**
+ * The engine floor, checked before the page is loaded (design O6: verified,
+ * not assumed).
+ *
+ * The WebView updates through the store independently of Android, so the floor
+ * is a Chromium version, not an API level. What binds it: Ed25519 and X25519 in
+ * WebCrypto (the handshake, chat and the group envelope) — Chromium 137 — and
+ * the two androidx.webkit features the bridge is built on. Measured present on
+ * WebView 145 (spike S-1); the floor itself still has to be confirmed on the
+ * oldest real device to be supported.
+ */
+object EngineCheck {
+ const val MIN_CHROMIUM = 137
+
+ fun problem(context: Context): String? {
+ if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER) ||
+ !WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
+ return "This device's Android System WebView is too old for MeshBay."
+ }
+ val version = WebViewCompat.getCurrentWebViewPackage(context)?.versionName ?: return null
+ val major = version.substringBefore('.').toIntOrNull() ?: return null
+ return if (major < MIN_CHROMIUM) {
+ "MeshBay needs Android System WebView $MIN_CHROMIUM or newer; this device has $version."
+ } else null
+ }
+
+ fun screen(context: Context, problem: String): View = LinearLayout(context).apply {
+ orientation = LinearLayout.VERTICAL
+ gravity = Gravity.CENTER
+ setPadding(48, 48, 48, 48)
+ addView(TextView(context).apply { text = problem; textSize = 18f; gravity = Gravity.CENTER })
+ addView(Button(context).apply {
+ text = "Update Android System WebView"
+ setOnClickListener {
+ val id = "com.google.android.webview"
+ try { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$id"))) }
+ catch (e: ActivityNotFoundException) {
+ context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$id")))
+ }
+ }
+ })
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/NativeText.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/NativeText.kt
new file mode 100644
index 0000000..ae23e46
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/NativeText.kt
@@ -0,0 +1,48 @@
+package org.meshbay.client.shell
+
+/**
+ * A sentence from the interface's own catalogues, for the few things the
+ * application draws itself (main.js `nativeText`). The page chooses the
+ * language and nothing else: a confirmation it worded would be one it could
+ * answer for itself.
+ *
+ * The catalogues are `export default { 'key': '…', … }` with single-quoted
+ * strings; a plural entry is an object, of which `other` is taken.
+ */
+class NativeText(private val readCatalogue: (String) -> String?) {
+
+ fun get(key: String, locale: String, params: Map<String, String> = emptyMap()): String {
+ var text = pick(readCatalogue(locale), key) ?: pick(readCatalogue("en"), key) ?: key
+ // split/join, as i18n.js: a folder name may contain `$&`.
+ for ((k, v) in params) text = text.split("{$k}").joinToString(v)
+ return text
+ }
+
+ companion object {
+ fun pick(source: String?, key: String): String? {
+ source ?: return null
+ val k = Regex.escape(key)
+ Regex("""(?m)^\s*'$k'\s*:\s*'((?:[^'\\]|\\.)*)'""").find(source)?.let { return unescape(it.groupValues[1]) }
+ Regex("""(?ms)^\s*'$k'\s*:\s*\{.*?\bother\s*:\s*'((?:[^'\\]|\\.)*)'""").find(source)?.let { return unescape(it.groupValues[1]) }
+ return null
+ }
+
+ fun unescape(s: String): String {
+ val out = StringBuilder()
+ var i = 0
+ while (i < s.length) {
+ val c = s[i]
+ if (c == '\\' && i + 1 < s.length) {
+ val n = s[i + 1]
+ when (n) {
+ 'n' -> out.append('\n'); 't' -> out.append('\t')
+ 'u' -> if (i + 5 < s.length) { out.append(s.substring(i + 2, i + 6).toInt(16).toChar()); i += 4 }
+ else -> out.append(n)
+ }
+ i += 2
+ } else { out.append(c); i++ }
+ }
+ return out.toString()
+ }
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/Pickers.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/Pickers.kt
new file mode 100644
index 0000000..f54ef87
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/Pickers.kt
@@ -0,0 +1,40 @@
+package org.meshbay.client.shell
+
+import android.app.Activity
+import android.content.Intent
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.atomic.AtomicInteger
+
+/**
+ * A system picker (folder, save-as, open) started from a bridge worker and
+ * waited on there — the bridge never blocks the UI thread, and the page gets
+ * its answer as the reply to the call that asked.
+ */
+class Pickers(private val activity: Activity) {
+ private class Waiting { val done = CountDownLatch(1); @Volatile var result: Intent? = null }
+
+ private val waiting = ConcurrentHashMap<Int, Waiting>()
+ private val codes = AtomicInteger(4000)
+
+ /** The result intent, or null when the person dismissed the picker. */
+ fun run(intent: Intent): Intent? {
+ val code = codes.incrementAndGet()
+ val w = Waiting()
+ waiting[code] = w
+ activity.runOnUiThread {
+ try { activity.startActivityForResult(intent, code) }
+ catch (e: android.content.ActivityNotFoundException) { waiting.remove(code); w.done.countDown() }
+ }
+ w.done.await()
+ return w.result
+ }
+
+ /** From Activity.onActivityResult; true when the code was one of ours. */
+ fun deliver(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
+ val w = waiting.remove(requestCode) ?: return false
+ w.result = if (resultCode == Activity.RESULT_OK) data ?: Intent() else null
+ w.done.countDown()
+ return true
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/ShellWebView.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/ShellWebView.kt
new file mode 100644
index 0000000..731da69
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/ShellWebView.kt
@@ -0,0 +1,25 @@
+package org.meshbay.client.shell
+
+import android.content.Context
+import android.view.View
+import android.webkit.WebView
+
+/**
+ * While `keepVisible` is set, the WebView is told its window stayed visible
+ * when the screen turns off. Chromium then never marks the page hidden, and
+ * its freeze of hidden pages — exactly 60 s after hiding, measured (spike
+ * S-2a C) — never starts. Set only while a cast runs or music plays: a page that is never
+ * hidden is never throttled, which is the battery cost the freeze exists to
+ * avoid.
+ */
+class ShellWebView(context: Context) : WebView(context) {
+ var keepVisible = false
+
+ override fun onWindowVisibilityChanged(visibility: Int) {
+ super.onWindowVisibilityChanged(if (keepVisible) View.VISIBLE else visibility)
+ }
+
+ override fun onVisibilityChanged(changedView: View, visibility: Int) {
+ super.onVisibilityChanged(changedView, if (keepVisible) View.VISIBLE else visibility)
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/UiAssets.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/UiAssets.kt
new file mode 100644
index 0000000..2300668
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/shell/UiAssets.kt
@@ -0,0 +1,93 @@
+package org.meshbay.client.shell
+
+import android.content.Context
+import android.webkit.WebResourceResponse
+import androidx.webkit.WebViewAssetLoader
+import java.io.File
+
+/**
+ * Serves the packaged interface, and nothing else.
+ *
+ * The page's origin is `https://appassets.androidplatform.net` — a secure
+ * context, without which `crypto.subtle` does not exist — and every file comes
+ * out of the APK's `assets/ui/`, copied from the hub's static directory at build
+ * time (§8.3). The hub never becomes the document origin: that is the whole
+ * reason the application exists (T3).
+ *
+ * The stock asset handler sets no headers, so this one exists for three: the
+ * policy, sent as a header because a <meta> policy drops `frame-ancestors`;
+ * `nosniff`; and `no-store`, since every file is already local.
+ */
+class UiAssets(private val context: Context) : WebViewAssetLoader.PathHandler {
+
+ override fun handle(path: String): WebResourceResponse? {
+ // Asset paths are not a filesystem, but a `..` that reached
+ // AssetManager would still be a path the page chose; refuse it.
+ if (path.split('/').any { it == ".." || it == "." } || path.startsWith("/")) return notFound()
+ val asset = "ui/" + path.ifEmpty { "index.html" }
+ val stream = try { context.assets.open(asset) } catch (e: java.io.IOException) { return notFound() }
+ val headers = mapOf(
+ "Content-Security-Policy" to CSP,
+ "X-Content-Type-Options" to "nosniff",
+ "Cache-Control" to "no-store",
+ )
+ val type = contentType(asset)
+ val charset = if (type.startsWith("text/") || type == "application/json") "utf-8" else null
+ return WebResourceResponse(type, charset, 200, "OK", headers, stream)
+ }
+
+ private fun notFound() =
+ WebResourceResponse("text/plain", "utf-8", 404, "Not Found", emptyMap(), "".byteInputStream())
+
+ companion object {
+ const val HOST = "appassets.androidplatform.net"
+ const val ORIGIN = "https://$HOST"
+ const val PREFIX = "/ui/"
+ const val START = "$ORIGIN${PREFIX}index.html"
+
+ // reCAPTCHA gates sign-up here as it does in a browser and on the
+ // desktop; these two hosts and no others.
+ private const val RECAPTCHA_SRC = "https://www.google.com https://www.gstatic.com"
+
+ /**
+ * meshbay-client/src/main.js's CSP, directive for directive
+ * (test_android_shell.py holds them together). `'wasm-unsafe-eval'` is
+ * the Argon2 that opens bundles: without it nobody reaches their keys.
+ */
+ val CSP = listOf(
+ "default-src 'none'",
+ "script-src 'self' 'wasm-unsafe-eval' $RECAPTCHA_SRC",
+ "style-src 'self' 'unsafe-inline'",
+ "img-src 'self' data: blob: $RECAPTCHA_SRC",
+ "media-src 'self' blob:",
+ "font-src 'self'",
+ "connect-src 'self' $RECAPTCHA_SRC",
+ "worker-src 'self'",
+ "object-src blob:",
+ "frame-src blob: $RECAPTCHA_SRC",
+ "frame-ancestors 'none'",
+ "base-uri 'none'",
+ "form-action 'none'",
+ ).joinToString("; ")
+
+ fun isRecaptcha(host: String?) = host == "www.google.com" || host == "www.gstatic.com"
+
+ fun contentType(name: String): String = when (File(name).extension.lowercase()) {
+ "html" -> "text/html"
+ "js", "mjs" -> "text/javascript"
+ "css" -> "text/css"
+ "json" -> "application/json"
+ "wasm" -> "application/wasm"
+ "svg" -> "image/svg+xml"
+ "png" -> "image/png"
+ "jpg", "jpeg" -> "image/jpeg"
+ "ico" -> "image/x-icon"
+ "webp" -> "image/webp"
+ "woff2" -> "font/woff2"
+ "woff" -> "font/woff"
+ "txt" -> "text/plain"
+ "xml" -> "application/xml"
+ else -> "application/octet-stream"
+ }
+ }
+}
diff --git a/packages/meshbay-android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/packages/meshbay-android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 0000000..50c1c99
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- The desktop client's icon (meshbay-client/build/icon-square.png), placed
+ in the adaptive icon's safe zone so no launcher mask crops the M. -->
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@color/ic_launcher_background" />
+ <foreground android:drawable="@mipmap/ic_launcher_foreground" />
+</adaptive-icon>
diff --git a/packages/meshbay-android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/packages/meshbay-android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
new file mode 100644
index 0000000..50c1c99
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- The desktop client's icon (meshbay-client/build/icon-square.png), placed
+ in the adaptive icon's safe zone so no launcher mask crops the M. -->
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@color/ic_launcher_background" />
+ <foreground android:drawable="@mipmap/ic_launcher_foreground" />
+</adaptive-icon>
diff --git a/packages/meshbay-android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/packages/meshbay-android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..5b29801
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png
Binary files differ
diff --git a/packages/meshbay-android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/packages/meshbay-android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..4e211fb
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png
Binary files differ
diff --git a/packages/meshbay-android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/packages/meshbay-android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..d86c80b
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png
Binary files differ
diff --git a/packages/meshbay-android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/packages/meshbay-android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..2fdac24
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png
Binary files differ
diff --git a/packages/meshbay-android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/packages/meshbay-android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..6cc1a12
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png
Binary files differ
diff --git a/packages/meshbay-android/app/src/main/res/values/colors.xml b/packages/meshbay-android/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..515e694
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/res/values/colors.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <!-- The edge of icon-square.png, so the safe-zone image meets a seamless field. -->
+ <color name="ic_launcher_background">#010822</color>
+</resources>
diff --git a/packages/meshbay-android/app/src/main/res/values/themes.xml b/packages/meshbay-android/app/src/main/res/values/themes.xml
new file mode 100644
index 0000000..a7df056
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/res/values/themes.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <style name="Shell" parent="@android:style/Theme.DeviceDefault.NoActionBar">
+ <item name="android:windowBackground">@android:color/black</item>
+ </style>
+</resources>
diff --git a/packages/meshbay-android/app/src/main/res/xml/data_extraction_rules.xml b/packages/meshbay-android/app/src/main/res/xml/data_extraction_rules.xml
new file mode 100644
index 0000000..f0abf11
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/res/xml/data_extraction_rules.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<data-extraction-rules>
+ <cloud-backup>
+ <exclude domain="root" /><exclude domain="file" /><exclude domain="database" />
+ <exclude domain="sharedpref" /><exclude domain="external" />
+ </cloud-backup>
+ <device-transfer>
+ <exclude domain="root" /><exclude domain="file" /><exclude domain="database" />
+ <exclude domain="sharedpref" /><exclude domain="external" />
+ </device-transfer>
+</data-extraction-rules>
diff --git a/packages/meshbay-android/app/src/main/res/xml/network_security_config.xml b/packages/meshbay-android/app/src/main/res/xml/network_security_config.xml
new file mode 100644
index 0000000..8bf3e82
--- /dev/null
+++ b/packages/meshbay-android/app/src/main/res/xml/network_security_config.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Plain http only to a hub on this device's own loopback — the desktop rule
+ ("http only to localhost or 127.*"). Anywhere else a session token would
+ cross the network in clear. -->
+<network-security-config>
+ <base-config cleartextTrafficPermitted="false" />
+ <domain-config cleartextTrafficPermitted="true">
+ <domain includeSubdomains="false">localhost</domain>
+ <domain includeSubdomains="false">127.0.0.1</domain>
+ </domain-config>
+</network-security-config>
diff --git a/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/CastRelayTest.kt b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/CastRelayTest.kt
new file mode 100644
index 0000000..14f49cf
--- /dev/null
+++ b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/CastRelayTest.kt
@@ -0,0 +1,307 @@
+package org.meshbay.client
+
+import org.json.JSONObject
+import org.junit.After
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.meshbay.client.cast.BoxAccumulator
+import org.meshbay.client.cast.CastRelay
+import java.io.ByteArrayOutputStream
+import java.io.DataInputStream
+import java.net.InetAddress
+import java.net.Socket
+
+/** The real relay on loopback, read with a raw socket: what a receiver sees. */
+class CastRelayTest {
+ private val spool = java.nio.file.Files.createTempDirectory("relay-spool").toFile()
+ private val relay = CastRelay({ InetAddress.getByName("127.0.0.1") }, spool)
+
+ @After fun stop() { relay.stop(); spool.deleteRecursively() }
+
+ private class Reply(val status: Int, val headers: Map<String, String>, val body: ByteArray)
+
+ private fun get(url: String, method: String = "GET", readBytes: Int = -1): Reply {
+ val u = java.net.URI(url)
+ Socket(u.host, u.port).use { s ->
+ s.soTimeout = 5000
+ s.getOutputStream().write("$method ${u.rawPath}${u.rawQuery?.let { "?$it" } ?: ""} HTTP/1.1\r\nHost: x\r\n\r\n".toByteArray())
+ val input = DataInputStream(s.getInputStream())
+ val headLines = ArrayList<String>()
+ val line = StringBuilder()
+ while (true) {
+ val c = input.read()
+ if (c == -1) break
+ if (c == '\n'.code) { val l = line.toString().trimEnd('\r'); if (l.isEmpty()) break; headLines.add(l); line.clear() }
+ else line.append(c.toChar())
+ }
+ val status = headLines[0].split(' ')[1].toInt()
+ val headers = headLines.drop(1).associate { it.substringBefore(':').lowercase() to it.substringAfter(':').trim() }
+ val body = ByteArrayOutputStream()
+ if (headers["transfer-encoding"] == "chunked") {
+ while (readBytes < 0 || body.size() < readBytes) {
+ val sizeLine = StringBuilder()
+ while (true) { val c = input.read(); if (c == -1 || c == '\n'.code) break; sizeLine.append(c.toChar()) }
+ val size = sizeLine.toString().trim().toIntOrNull(16) ?: break
+ if (size == 0) break
+ val buf = ByteArray(size); input.readFully(buf); body.write(buf); input.read(); input.read()
+ }
+ } else {
+ val n = headers["content-length"]?.toInt() ?: 0
+ val buf = ByteArray(n); input.readFully(buf); body.write(buf)
+ }
+ return Reply(status, headers, body.toByteArray())
+ }
+ }
+
+ private fun box(type: String, payload: Int): ByteArray {
+ val size = 8 + payload
+ return byteArrayOf((size ushr 24).toByte(), (size ushr 16).toByte(), (size ushr 8).toByte(), size.toByte()) +
+ type.toByteArray() + ByteArray(payload) { (it % 251).toByte() }
+ }
+
+ private fun fragment(n: Int) = box("moof", 16 + n) + box("mdat", 1000 + n)
+
+ @Test fun `fragments are re-framed from arbitrary slices`() {
+ val acc = BoxAccumulator()
+ val stream = box("ftyp", 12) + fragment(1) + fragment(2) + fragment(3)
+ val out = ArrayList<ByteArray>()
+ var i = 0
+ while (i < stream.size) { val n = minOf(37, stream.size - i); out += acc.push(stream, i, n); i += n }
+ assertEquals(3, out.size)
+ assertArrayEquals(fragment(2), out[1])
+ }
+
+ @Test fun `a lost frame is recovered by rescanning for the next moof`() {
+ val acc = BoxAccumulator()
+ BoxAccumulator.warn = {}
+ val out = acc.push(fragment(1) + byteArrayOf(0, 0, 0, 1, 1, 2, 3, 4) + fragment(2))
+ assertEquals(2, out.size)
+ }
+
+ @Test fun `the stream is init then the backlog then what follows`() {
+ val init = box("ftyp", 20) + box("moov", 50)
+ val started = relay.start(init, null)
+ relay.push(fragment(1)); relay.push(fragment(2))
+ val reply = get(started.getString("url"), readBytes = init.size + fragment(1).size + fragment(2).size)
+ assertEquals(200, reply.status)
+ assertEquals("video/mp4", reply.headers["content-type"])
+ assertEquals("no-store", reply.headers["cache-control"])
+ assertArrayEquals(init + fragment(1) + fragment(2), reply.body)
+ }
+
+ @Test fun `a first chunk that carries film is served as its header only`() {
+ // As the page delivers it from a real film: a 64 KB slice holding the
+ // header, the first moof and the start of its mdat — pushed as well.
+ val header = box("ftyp", 20) + box("moov", 1200)
+ val stream = header + fragment(1) + fragment(2)
+ val firstChunk = stream.copyOfRange(0, header.size + 300)
+ val started = relay.start(firstChunk, null)
+ var at = 0
+ while (at < stream.size) { val n = minOf(300, stream.size - at); relay.push(stream, at, n); at += n }
+ val reply = get(started.getString("url"), readBytes = stream.size)
+ assertArrayEquals("header, then each fragment once", stream, reply.body)
+ }
+
+ @Test fun `a header split across chunks is served whole`() {
+ // Measured on a fresh start: the first chunk was the 28-byte ftyp
+ // alone, the moov came in the next push. Served as the header, the
+ // receiver had no moov and gave up — the first cast failed every time.
+ val ftyp = box("ftyp", 20)
+ val moov = box("moov", 2124)
+ val started = relay.start(ftyp, null)
+ val url = started.getString("url")
+ // The page pushes the first chunk too, then the rest.
+ relay.push(ftyp); relay.push(moov); relay.push(fragment(1)); relay.push(fragment(2))
+ val reply = get(url, readBytes = ftyp.size + moov.size + fragment(1).size + fragment(2).size)
+ assertArrayEquals(ftyp + moov + fragment(1) + fragment(2), reply.body)
+ }
+
+ @Test fun `a receiver early for the header waits for all of it`() {
+ val ftyp = box("ftyp", 20)
+ val moov = box("moov", 2124)
+ val url = relay.start(ftyp, null).getString("url")
+ relay.push(ftyp)
+ val late = Thread { Thread.sleep(400); relay.push(moov); relay.push(fragment(1)) }.apply { start() }
+ val reply = get(url, readBytes = ftyp.size + moov.size + fragment(1).size)
+ late.join()
+ assertArrayEquals(ftyp + moov + fragment(1), reply.body)
+ }
+
+ @Test fun `the token is required and unguessable`() {
+ val url = relay.start(null, null).getString("url")
+ val token = url.substringAfter("t=")
+ assertTrue(Regex("^[0-9a-f]{32}$").matches(token))
+ assertEquals(403, get(url.replace(token, "0".repeat(32))).status)
+ assertEquals(403, get(url.substringBefore("?")).status)
+ assertEquals(405, get(url, method = "POST").status)
+ assertEquals(404, get(url.replace("/stream.mp4", "/other")).status)
+ }
+
+ @Test fun `the subtitle is webvtt behind the token, readable cross-origin, re-addressed when it changes`() {
+ val r = relay.start(null, JSONObject().put("vtt", "WEBVTT\n\n00:00.000 --> 00:01.000\nhi\n").put("language", "fr").put("label", "Français"))
+ val sub = r.getJSONObject("subtitle")
+ val reply = get(sub.getString("url"))
+ assertEquals(200, reply.status)
+ assertEquals("text/vtt; charset=utf-8", reply.headers["content-type"])
+ assertEquals("*", reply.headers["access-control-allow-origin"])
+ assertTrue(String(reply.body).startsWith("WEBVTT"))
+ assertEquals(403, get(sub.getString("url").replace(Regex("t=[0-9a-f]+"), "t=x")).status)
+
+ val second = relay.setSubtitle(JSONObject().put("vtt", "WEBVTT\n"))!!
+ assertNotEquals(sub.getString("url"), second.getString("url"))
+ assertNull(relay.setSubtitle(null))
+ assertEquals(404, get(second.getString("url")).status)
+ assertEquals(200, get(r.getString("url"), readBytes = 0).status)
+ }
+
+ private fun send(bytes: ByteArray, type: String, meta: JSONObject = JSONObject(),
+ cover: ByteArray? = null): String {
+ relay.beginFile(type, bytes.size.toLong(), cover, cover?.let { "image/jpeg" }, meta)
+ var at = 0
+ while (at < bytes.size) { val n = minOf(3, bytes.size - at); relay.writeFile(bytes, at, n); at += n }
+ return relay.endFile().getString("url")
+ }
+
+ private fun getRange(url: String, range: String): Reply {
+ val u = java.net.URI(url)
+ Socket(u.host, u.port).use { s ->
+ s.soTimeout = 5000
+ s.getOutputStream().write("GET ${u.rawPath}?${u.rawQuery} HTTP/1.1\r\nHost: x\r\nRange: $range\r\n\r\n".toByteArray())
+ val input = DataInputStream(s.getInputStream())
+ val lines = ArrayList<String>()
+ val line = StringBuilder()
+ while (true) {
+ val c = input.read()
+ if (c == -1) break
+ if (c == '\n'.code) { val l = line.toString().trimEnd('\r'); if (l.isEmpty()) break; lines.add(l); line.clear() }
+ else line.append(c.toChar())
+ }
+ val headers = lines.drop(1).associate { it.substringBefore(':').lowercase() to it.substringAfter(':').trim() }
+ val body = ByteArray(headers["content-length"]?.toInt() ?: 0)
+ input.readFully(body)
+ return Reply(lines[0].split(' ')[1].toInt(), headers, body)
+ }
+ }
+
+ @Test fun `a file starts the relay and is served behind the token, re-addressed when it changes`() {
+ val jpeg = byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 1, 2, 3, 0xFF.toByte(), 0xD9.toByte())
+ val first = send(jpeg, "image/jpeg")
+ assertTrue(relay.active)
+ val reply = get(first)
+ assertEquals(200, reply.status)
+ assertEquals("image/jpeg", reply.headers["content-type"])
+ assertEquals("no-store", reply.headers["cache-control"])
+ assertArrayEquals(jpeg, reply.body)
+ assertEquals(403, get(first.replace(Regex("t=[0-9a-f]+"), "t=x")).status)
+ // A receiver handed the same address twice shows what it already has.
+ val second = send(byteArrayOf(9), "image/jpeg")
+ assertNotEquals(first, second)
+ assertArrayEquals(byteArrayOf(9), get(second).body)
+ }
+
+ @Test fun `a track is served with its cover, and by range`() {
+ val track = ByteArray(20) { it.toByte() }
+ val cover = byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 7)
+ val url = send(track, "audio/flac", JSONObject().put("title", "A Song").put("artist", "Some Band"), cover)
+ assertEquals("audio/flac", relay.fileType)
+ val meta = relay.fileMeta()!!
+ assertEquals("A Song", meta.getString("title"))
+ assertArrayEquals(cover, get(meta.getString("cover")).body)
+ val part = getRange(url, "bytes=5-9")
+ assertEquals(206, part.status)
+ assertEquals("bytes 5-9/20", part.headers["content-range"])
+ assertArrayEquals(track.copyOfRange(5, 10), part.body)
+ assertArrayEquals(track.copyOfRange(15, 20), getRange(url, "bytes=15-").body)
+ assertEquals(416, getRange(url, "bytes=50-60").status)
+ }
+
+ @Test fun `only a whole picture or sound is served as one`() {
+ val refused = try { relay.beginFile("text/html", 1, null, null, JSONObject()); false } catch (e: IllegalArgumentException) { true }
+ assertTrue(refused)
+ assertNull(relay.fileUrl)
+ relay.beginFile("audio/mpeg", 10, null, null, JSONObject())
+ relay.writeFile(byteArrayOf(1, 2, 3))
+ val short = try { relay.endFile(); false } catch (e: IllegalStateException) { true }
+ assertTrue(short)
+ assertNull(relay.fileUrl)
+ }
+
+ @Test fun `a film started over a file takes the file down`() {
+ send(byteArrayOf(1), "image/jpeg")
+ relay.start(null, null)
+ assertNull(relay.fileUrl)
+ }
+
+ @Test fun `the preflight is answered before the token is checked`() {
+ val url = relay.start(null, null).getString("url")
+ val reply = get(url.substringBefore("?"), method = "OPTIONS")
+ assertEquals(204, reply.status)
+ assertEquals("GET, OPTIONS", reply.headers["access-control-allow-methods"])
+ assertTrue(reply.headers["access-control-allow-headers"]!!.contains("Range"))
+ }
+
+ @Test fun `the stream carries the same CORS headers as its subtitle`() {
+ val url = relay.start(null, null).getString("url")
+ val reply = get(url, readBytes = 0)
+ for ((k, v) in CastRelay.CORS_HEADERS) assertEquals(k, v, reply.headers[k.lowercase()])
+ }
+
+ @Test fun `the backlog is bounded in bytes, not only in fragments`() {
+ relay.start(null, null)
+ // 40 fragments of 4 MB: under the fragment cap, far over a phone's heap.
+ val big = box("moof", 16) + box("mdat", 4 * 1024 * 1024)
+ repeat(40) { relay.push(big) }
+ assertTrue("backlog ${relay.backlogBytes()}", relay.backlogBytes() <= CastRelay.RING_MAX_BYTES)
+ assertTrue(relay.backlogBytes() >= CastRelay.RING_MAX_BYTES - big.size)
+ }
+
+ @Test fun `seek after seek, the relay restarts on its ports`() {
+ // A seek restarts the relay, and a receiver was connected each time:
+ // the ports it closed sit in TIME_WAIT.
+ repeat(8) {
+ val url = relay.start(null, null).getString("url")
+ relay.push(fragment(it))
+ get(url, readBytes = fragment(it).size)
+ relay.stop()
+ }
+ }
+
+ @Test fun `a receiver far behind loses nothing, and its spool goes with it`() {
+ // Fragments of 4 MB, ten of them pushed while the receiver has read
+ // none: far past the 8 MB the desktop drops at, which froze the TV.
+ val url = relay.start(null, null).getString("url")
+ val u = java.net.URI(url)
+ Socket(u.host, u.port).use { s ->
+ s.getOutputStream().write("GET ${u.rawPath}?${u.rawQuery} HTTP/1.1\r\nHost: x\r\n\r\n".toByteArray())
+ Thread.sleep(300)
+ val big = (0 until 10).map { box("moof", 16 + it) + box("mdat", 4 * 1024 * 1024 + it) }
+ big.forEach { relay.push(it) }
+ assertEquals("one spool file for the one receiver", 1, spool.listFiles()!!.size)
+ val input = DataInputStream(s.getInputStream())
+ while (true) { val l = StringBuilder(); while (true) { val c = input.read(); if (c == '\n'.code) break; l.append(c.toChar()) }; if (l.toString().trim().isEmpty()) break }
+ val body = ByteArrayOutputStream()
+ val want = big.sumOf { it.size }
+ while (body.size() < want) {
+ val size = StringBuilder().also { sb -> while (true) { val c = input.read(); if (c == '\n'.code) break; sb.append(c.toChar()) } }.toString().trim().toInt(16)
+ val buf = ByteArray(size); input.readFully(buf); body.write(buf); input.read(); input.read()
+ }
+ assertArrayEquals("every fragment, in order, none dropped", big.reduce { a, b -> a + b }, body.toByteArray())
+ }
+ Thread.sleep(300)
+ relay.stop()
+ assertEquals("the spool is deleted with the receiver", 0, spool.listFiles()!!.size)
+ }
+
+ @Test fun `stopping closes the port`() {
+ val url = relay.start(null, null).getString("url")
+ relay.stop()
+ val u = java.net.URI(url)
+ val refused = try { Socket(u.host, u.port).close(); false } catch (e: java.net.ConnectException) { true }
+ assertTrue(refused)
+ assertNull(relay.url)
+ }
+}
diff --git a/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/ChannelsTest.kt b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/ChannelsTest.kt
new file mode 100644
index 0000000..adc6366
--- /dev/null
+++ b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/ChannelsTest.kt
@@ -0,0 +1,39 @@
+package org.meshbay.client
+
+import org.json.JSONArray
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertThrows
+import org.junit.Test
+import org.meshbay.client.bridge.Channels
+import org.meshbay.client.bridge.Refused
+import org.meshbay.client.hub.HubClient
+import java.net.InetAddress
+import java.net.UnknownHostException
+
+class ChannelsTest {
+ private val channels = Channels(HubClient(FakePrefs()), onHubChanged = {}, hasCatalogue = { it == "fr" || it == "pt-BR" })
+
+ @Test fun `a channel that is not enumerated is refused`() {
+ for (ch in listOf("node:op", "root:choose", "window:minimize-to-tray", "keys:sign", "", "hub:fetch2")) {
+ assertThrows(ch, Refused::class.java) { channels.call(ch, JSONArray()) }
+ }
+ }
+
+ @Test fun `the locale is a code with a catalogue, never text`() {
+ assertEquals("fr", channels.call("ui:locale", JSONArray().put("fr")))
+ assertEquals("fr", channels.call("ui:locale", JSONArray().put("de"))) // no catalogue
+ assertEquals("fr", channels.call("ui:locale", JSONArray().put("../en"))) // not a code
+ assertEquals("pt-BR", channels.call("ui:locale", JSONArray().put("pt-BR")))
+ }
+
+ @Test fun `stun hostnames are resolved, literals kept, failures dropped`() {
+ val lookup: (String) -> Array<InetAddress> = { host ->
+ if (host == "stun.example") arrayOf(InetAddress.getByAddress(host, byteArrayOf(192.toByte(), 0, 2, 7)))
+ else throw UnknownHostException(host)
+ }
+ val out = Channels.resolveStun(JSONArray(listOf("stun:stun.example:3478", "stun:198.51.100.1:3478",
+ "stun:[2001:db8::1]:3478", "stun:gone.example:3478", "turn:x")), lookup)
+ assertEquals(listOf("stun:192.0.2.7:3478", "stun:198.51.100.1:3478", "stun:[2001:db8::1]:3478", "turn:x"),
+ (0 until out.length()).map { out.getString(it) })
+ }
+}
diff --git a/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/FakePrefs.kt b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/FakePrefs.kt
new file mode 100644
index 0000000..33d1c0f
--- /dev/null
+++ b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/FakePrefs.kt
@@ -0,0 +1,30 @@
+package org.meshbay.client
+
+import android.content.SharedPreferences
+
+/** SharedPreferences is an interface; a map is enough for the JVM tests. */
+class FakePrefs : SharedPreferences {
+ val map = HashMap<String, Any?>()
+ override fun getAll(): MutableMap<String, *> = map
+ override fun getString(key: String, defValue: String?) = map[key] as String? ?: defValue
+ override fun getStringSet(key: String, defValues: MutableSet<String>?) = defValues
+ override fun getInt(key: String, defValue: Int) = map[key] as Int? ?: defValue
+ override fun getLong(key: String, defValue: Long) = map[key] as Long? ?: defValue
+ override fun getFloat(key: String, defValue: Float) = map[key] as Float? ?: defValue
+ override fun getBoolean(key: String, defValue: Boolean) = map[key] as Boolean? ?: defValue
+ override fun contains(key: String) = map.containsKey(key)
+ override fun registerOnSharedPreferenceChangeListener(l: SharedPreferences.OnSharedPreferenceChangeListener?) {}
+ override fun unregisterOnSharedPreferenceChangeListener(l: SharedPreferences.OnSharedPreferenceChangeListener?) {}
+ override fun edit(): SharedPreferences.Editor = object : SharedPreferences.Editor {
+ override fun putString(k: String, v: String?) = apply { map[k] = v }
+ override fun putStringSet(k: String, v: MutableSet<String>?) = apply { map[k] = v }
+ override fun putInt(k: String, v: Int) = apply { map[k] = v }
+ override fun putLong(k: String, v: Long) = apply { map[k] = v }
+ override fun putFloat(k: String, v: Float) = apply { map[k] = v }
+ override fun putBoolean(k: String, v: Boolean) = apply { map[k] = v }
+ override fun remove(k: String) = apply { map.remove(k) }
+ override fun clear() = apply { map.clear() }
+ override fun commit() = true
+ override fun apply() {}
+ }
+}
diff --git a/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/FakeSecrets.kt b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/FakeSecrets.kt
new file mode 100644
index 0000000..86537bd
--- /dev/null
+++ b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/FakeSecrets.kt
@@ -0,0 +1,11 @@
+package org.meshbay.client
+
+import org.json.JSONObject
+import org.meshbay.client.keys.Secrets
+
+class FakeSecrets(var backendName: String = "android_keystore") : Secrets {
+ var all = JSONObject()
+ override fun backend() = backendName
+ override fun read() = JSONObject(all.toString())
+ override fun update(fn: (JSONObject) -> Unit) { val a = read(); fn(a); all = a }
+}
diff --git a/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/HubClientTest.kt b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/HubClientTest.kt
new file mode 100644
index 0000000..8211013
--- /dev/null
+++ b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/HubClientTest.kt
@@ -0,0 +1,43 @@
+package org.meshbay.client
+
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertThrows
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.meshbay.client.bridge.Refused
+import org.meshbay.client.hub.HubClient
+
+class HubClientTest {
+ private fun hub(base: String = "") = HubClient(FakePrefs().apply { map["hubBase"] = base })
+
+ @Test fun `an empty address is refused, not stored as no hub`() {
+ val e = assertThrows(Refused::class.java) { hub().setBase(" ") }
+ assertEquals("Enter the address of a hub.", e.message)
+ }
+
+ @Test fun `plain http is refused except to loopback`() {
+ for (url in listOf("http://example.org", "http://10.0.2.2:8770", "ftp://x", "http://192.168.1.2")) {
+ val e = assertThrows(Refused::class.java) { hub().setBase(url) }
+ assertEquals(url, "The hub address must be https", e.message)
+ }
+ }
+
+ @Test fun `the page reaches the signed-in hub and nowhere else`() {
+ val h = hub("https://hub.example")
+ for (url in listOf("https://other.example/v1/x", "http://hub.example/v1/x",
+ "https://hub.example:8443/v1/x", "https://hub.example.evil/v1/x", "not a url")) {
+ assertThrows(url, Refused::class.java) { h.fetch(url, JSONObject()) }
+ }
+ }
+
+ @Test fun `nothing is fetched before a hub is set`() {
+ assertThrows(Refused::class.java) { hub("").fetch("https://hub.example/v1/x", null) }
+ }
+
+ @Test fun `unreachable hubs are described in words somebody can act on`() {
+ assertTrue(HubClient.describeUnreachable("https://h", java.net.ConnectException()).startsWith("Nothing is listening at https://h"))
+ assertTrue(HubClient.describeUnreachable("https://h", java.net.UnknownHostException()).contains("could not be found"))
+ assertTrue(HubClient.describeUnreachable("https://h", javax.net.ssl.SSLHandshakeException("x")).contains("does not speak https"))
+ }
+}
diff --git a/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/KeyChannelsTest.kt b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/KeyChannelsTest.kt
new file mode 100644
index 0000000..c4333db
--- /dev/null
+++ b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/KeyChannelsTest.kt
@@ -0,0 +1,81 @@
+package org.meshbay.client
+
+import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters
+import org.bouncycastle.crypto.signers.Ed25519Signer
+import org.json.JSONArray
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertThrows
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.meshbay.client.bridge.KeyChannels
+import org.meshbay.client.bridge.Refused
+import org.meshbay.client.keys.Kdf
+
+class KeyChannelsTest {
+ private val user = "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0"
+ private val node = Kdf.b64(ByteArray(32) { 0x11 })
+ private var asked = 0
+ private var answer = false
+ private val secrets = FakeSecrets()
+ private val keys = KeyChannels(secrets, confirm = { asked++; answer }, declined = { "Cancelled" })
+
+ private fun call(ch: String, vararg args: Any?) = keys.call(ch, JSONArray(args.toList()))
+
+ @Test fun `ids and node keys are checked before anything is done`() {
+ for (bad in listOf("", "../x", "not-an-id", "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0x", null)) {
+ assertThrows("$bad", Refused::class.java) { call("keys:fingerprint", bad) }
+ }
+ for (bad in listOf("", "a/b c", "x".repeat(101), null)) {
+ assertThrows("$bad", Refused::class.java) { call("keys:identity", user, bad) }
+ }
+ }
+
+ @Test fun `the device key signs the bytes the hub verifies and never leaves`() {
+ val pub = call("device:ensure") as String
+ assertEquals(pub, call("device:ensure")) // once, then the same key
+ val s = call("device:sign", "alice") as JSONObject
+ val msg = "meshbay:user_auth:alice:${s.getLong("timestamp")}".toByteArray()
+ val v = Ed25519Signer().apply { init(false, Ed25519PublicKeyParameters(Kdf.unb64(pub), 0)); update(msg, 0, msg.size) }
+ assertTrue(v.verifySignature(Kdf.unb64(s.getString("signature"))))
+ call("device:forget")
+ assertNull(call("device:public"))
+ }
+
+ @Test fun `browser access is widened only by the person, natively`() {
+ call("keys:created-here", user)
+ assertEquals(false, call("keys:browser-access", user))
+ answer = false
+ val e = assertThrows(Refused::class.java) { call("keys:set-browser-access", user, true) }
+ assertEquals("Cancelled", e.message)
+ assertEquals(1, asked)
+ assertEquals(false, call("keys:browser-access", user))
+ answer = true
+ assertEquals(true, call("keys:set-browser-access", user, true))
+ // Narrowing asks nobody.
+ assertEquals(false, call("keys:set-browser-access", user, false))
+ assertEquals(2, asked)
+ }
+
+ @Test fun `without OS key storage nothing is minted or derived`() {
+ val none = KeyChannels(FakeSecrets("unavailable"), confirm = { true }, declined = { "" })
+ assertEquals(false, none.call("keys:available", JSONArray()))
+ assertThrows(Refused::class.java) { none.call("keys:mint", JSONArray(listOf(user, node))) }
+ assertEquals(false, none.call("keys:has-session", JSONArray(listOf(user))))
+ }
+
+ @Test fun `a minted identity answers with public keys only`() {
+ val r = call("keys:mint", user, node) as JSONObject
+ assertEquals(setOf("pkEdB64", "pkXB64"), r.keys().asSequence().toSet())
+ val id = call("keys:identity", user, node) as JSONObject
+ assertEquals(r.getString("pkEdB64"), id.getString("pkEdB64"))
+ assertEquals(JSONObject.NULL, id.get("sealedWith"))
+ }
+
+ @Test fun `channels outside the list are refused`() {
+ assertThrows(Refused::class.java) { call("keys:export") }
+ assertFalse(keys.handles("hub:fetch"))
+ }
+}
diff --git a/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/KeyringVectorsTest.kt b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/KeyringVectorsTest.kt
new file mode 100644
index 0000000..63edbde
--- /dev/null
+++ b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/KeyringVectorsTest.kt
@@ -0,0 +1,151 @@
+package org.meshbay.client
+
+import org.json.JSONObject
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.meshbay.client.keys.Kdf
+import org.meshbay.client.keys.Keyring
+import org.meshbay.client.keys.Transcripts
+import java.io.File
+
+/**
+ * The keyring and the transcripts against meshbay-hub/tests/vectors/keyring.json,
+ * which the desktop keyring writes and the specification reproduces
+ * (test_keyring_vectors.py). Every deterministic field byte for byte, every
+ * refusal with its message: a bundle this sealed is one the page and the
+ * desktop open, and the reverse.
+ */
+class KeyringVectorsTest {
+ private var passed = 0
+ private val failures = ArrayList<String>()
+ private fun check(label: String, ok: Boolean, detail: () -> String = { "" }) {
+ if (ok) passed++ else failures.add("$label ${detail()}")
+ }
+ private fun <T> eq(label: String, got: T, want: T) = check(label, got == want) { "got=$got want=$want" }
+
+ @Test fun `every vector is reproduced`() {
+
+ val v = JSONObject(VECTORS.readText())
+ val input = v.getJSONObject("input")
+ val kdf = v.getJSONObject("kdf")
+ val bundles = v.getJSONObject("bundles")
+ val now = input.getLong("now").toDouble()
+ val userId = input.getString("userId")
+ val nodePk = input.getString("nodePk")
+ val username = input.getString("username")
+
+ // The store, as SecretStore would hold it.
+ var store = JSONObject()
+ var nonces: ArrayDeque<ByteArray> = ArrayDeque()
+ fun ring() = Keyring(
+ load = { JSONObject(store.toString()) },
+ save = { store = JSONObject(it.toString()) },
+ transcripts = Transcripts { now },
+ random = { n -> nonces.removeFirstOrNull() ?: ByteArray(n).also { java.security.SecureRandom().nextBytes(it) } },
+ )
+ val ring = ring()
+
+ // 1. KDF chain.
+ val salt = Kdf.sha256("meshbay:bundle:v2:$username".toByteArray()).copyOfRange(0, 16)
+ eq("salt", Kdf.toHex(salt), kdf.getString("salt_hex"))
+ ring.deriveSession(input.getString("password"), username, userId,
+ input.getString("pepperB64"), input.getInt("pepperVersion"))
+ val masters = store.getJSONObject("masters").getJSONObject(userId)
+ eq("argon2id", Kdf.toHex(Kdf.unb64(masters.getString("legacy"))), kdf.getString("argon2_hex"))
+ eq("M", Kdf.toHex(Kdf.unb64(masters.getString("m"))), kdf.getString("master_hex"))
+ eq("pepper version", masters.getInt("v"), input.getInt("pepperVersion"))
+ eq("fingerprint", ring.currentFingerprint(userId), kdf.getString("master_fingerprint"))
+ eq("node key", Kdf.toHex(Kdf.hkdf(Kdf.unb64(masters.getString("m")), "meshbay:bundle:v3|node|$nodePk")),
+ kdf.getString("node_key_hex"))
+ eq("playlist key", ring.playlistKey(userId), kdf.getString("playlist_key_b64"))
+
+ // 2. Identity: placed in the store as keyring.js would leave it.
+ val ident = v.getJSONObject("identity")
+ store.getJSONObject("identities").put(userId, JSONObject().put(nodePk,
+ JSONObject().put("ed", ident.getString("ed_pkcs8_b64")).put("x", ident.getString("x_pkcs8_b64"))
+ .put("sealedWith", JSONObject.NULL)))
+ val pub = ring.identity(userId, nodePk)!!
+ eq("pkEd", pub.pkEdB64, ident.getJSONObject("public").getString("pkEdB64"))
+ eq("pkX", pub.pkXB64, ident.getJSONObject("public").getString("pkXB64"))
+
+ // 3. Bundles: sealed byte for byte, and opened.
+ val fixedNonce = Kdf.hex(input.getString("fixedNonceHex"))
+ nonces.addLast(fixedNonce)
+ val sealed = ring.sealBundle(userId, nodePk)
+ eq("bundle sealed with a fixed nonce", sealed.bundle, bundles.getString("fixed_nonce_bundle_b64"))
+ eq("bundle fingerprint", sealed.fingerprint, bundles.getString("fixed_nonce_fingerprint"))
+ nonces.addLast(fixedNonce)
+ eq("recovery bundle", ring.sealRecovery(userId, nodePk, input.getString("mnemonic"), username),
+ bundles.getString("recovery_fixed_nonce_b64"))
+
+ fun opensTo(label: String, block: (Keyring) -> Keyring.Pub) {
+ val saved = store
+ store = JSONObject().put("masters", JSONObject().put(userId, masters)).put("identities", JSONObject())
+ .put("access", JSONObject())
+ try {
+ val p = block(ring())
+ check(label, p.pkEdB64 == pub.pkEdB64 && p.pkXB64 == pub.pkXB64) { "opened to another identity" }
+ check("$label leaves the identity unsealed", ring().identity(userId, nodePk)?.sealedWith == null)
+ } catch (e: Exception) {
+ check(label, false) { e.toString() }
+ } finally { store = saved }
+ }
+ opensTo("desktop bundle (fixed nonce) opens") { it.openBundle(userId, nodePk, bundles.getString("fixed_nonce_bundle_b64")) }
+ opensTo("MBK2 legacy bundle opens") { it.openBundle(userId, nodePk, bundles.getString("legacy_mbk2_b64")) }
+ val bogus = Kdf.b64("MBK3".toByteArray() + ByteArray(30) { 1 })
+ opensTo("recovery copy opens through the fallback") {
+ it.openBundle(userId, nodePk, bogus, bundles.getString("recovery_fixed_nonce_b64"),
+ input.getString("mnemonic"), username)
+ }
+ // A bundle Kotlin seals (random nonce) must open — round trip.
+ val ours = ring.sealBundle(userId, nodePk).bundle
+ opensTo("a bundle sealed here opens here") { it.openBundle(userId, nodePk, ours) }
+ // A retired format is refused, never tried against the recovery key.
+ try {
+ ring.openBundle(userId, nodePk, Kdf.b64("MBK1xxxxxxxxxxxxxxxxxxxxxxxxxxxxx".toByteArray()))
+ check("retired format refused", false)
+ } catch (e: Keyring.FormatRetired) { check("retired format refused", true) }
+
+ // Browser access off: nothing sealed.
+ ring.setBrowserAccess(userId, false)
+ try { ring.sealBundle(userId, nodePk); check("no bundle while browser access is off", false) }
+ catch (e: IllegalStateException) { check("no bundle while browser access is off", e.message!!.startsWith("Refused")) }
+ ring.setBrowserAccess(userId, true)
+
+ // 4. Agreement.
+ val ag = v.getJSONObject("agreement")
+ eq("X25519 agreement", ring.shared(userId, nodePk, ag.getString("peer_x_pub_b64")), ag.getString("shared_b64"))
+
+ // 5. Transcripts and signatures.
+ val tr = Transcripts { now }
+ val ctx = Transcripts.Ctx(userId, nodePk, pub.pkEdB64, pub.pkXB64)
+ val kinds = v.getJSONObject("transcripts")
+ for (kind in kinds.keys()) {
+ val t = kinds.getJSONObject(kind)
+ eq("transcript $kind", Kdf.toHex(tr.forKind(kind, t.getJSONObject("fields"), ctx)), t.getString("transcript_hex"))
+ eq("signature $kind", ring.signAs(userId, nodePk, kind, t.getJSONObject("fields")), t.getString("signature_b64"))
+ }
+ val refusals = v.getJSONArray("refusals")
+ for (i in 0 until refusals.length()) {
+ val r = refusals.getJSONObject(i)
+ try {
+ tr.forKind(r.getString("kind"), r.getJSONObject("fields"), ctx)
+ check("refusal '${r.getString("label")}'", false) { "was signed" }
+ } catch (e: Transcripts.Refused) {
+ eq("refusal '${r.getString("label")}' message", e.message, r.getString("error"))
+ }
+ }
+
+ // Sign-out drops M and keeps the identities.
+ ring.forgetSession(userId)
+ check("sign-out drops M", !ring.hasSession(userId))
+ check("sign-out keeps the identity", ring.identity(userId, nodePk) != null)
+ assertTrue("vector failures:\n" + failures.joinToString("\n"), failures.isEmpty())
+ assertTrue("too few checks ran: $passed", passed >= 55)
+ }
+
+ companion object {
+ // Unit tests run with the module directory as working directory.
+ val VECTORS = File("../../meshbay-hub/tests/vectors/keyring.json")
+ }
+}
diff --git a/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/NativeTextTest.kt b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/NativeTextTest.kt
new file mode 100644
index 0000000..9e0bc7e
--- /dev/null
+++ b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/NativeTextTest.kt
@@ -0,0 +1,34 @@
+package org.meshbay.client
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotEquals
+import org.junit.Test
+import org.meshbay.client.shell.NativeText
+import java.io.File
+
+/** The application's own dialogs, worded from the real catalogues in every language. */
+class NativeTextTest {
+ private val locales = File("../../meshbay-hub/src/meshbay_hub/static/locales")
+ private val text = NativeText { code -> File(locales, "$code.js").takeIf { it.exists() }?.readText() }
+
+ @Test fun `every catalogue words the native dialogs`() {
+ val codes = locales.listFiles()!!.map { it.nameWithoutExtension }
+ assertEquals(10, codes.size)
+ for (code in codes) for (key in listOf("native.browser_access_confirm", "native.declined", "dialog.ok", "dialog.cancel")) {
+ assertNotEquals("$code $key", key, text.get(key, code))
+ }
+ }
+
+ @Test fun `escapes are read as the page reads them`() {
+ assertEquals("Annulé — rien n'a été modifié.", text.get("native.declined", "fr"))
+ }
+
+ @Test fun `an unknown language falls back to English, an unknown key to itself`() {
+ assertEquals("Cancel", text.get("dialog.cancel", "xx"))
+ assertEquals("no.such.key", text.get("no.such.key", "fr"))
+ }
+
+ @Test fun `plural entries give their other form and parameters are filled`() {
+ assertEquals("Use at least 12 characters", text.get("register.err_min_len", "en", mapOf("n" to "12")))
+ }
+}
diff --git a/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/SaveNamesTest.kt b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/SaveNamesTest.kt
new file mode 100644
index 0000000..d3b8450
--- /dev/null
+++ b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/SaveNamesTest.kt
@@ -0,0 +1,45 @@
+package org.meshbay.client
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+import org.meshbay.client.save.BinaryFrame
+import org.meshbay.client.save.SaveNames
+
+class SaveNamesTest {
+ @Test fun `a suggested name is a basename with no bidirectional tricks`() {
+ assertEquals("invoice_fdp.exe", SaveNames.sanitize("invoice\u202efdp.exe"))
+ assertEquals("passwd", SaveNames.sanitize("../../etc/passwd"))
+ assertEquals("x.txt", SaveNames.sanitize("C:\\Users\\x.txt"))
+ assertEquals("download", SaveNames.sanitize(""))
+ assertEquals("download", SaveNames.sanitize(".."))
+ assertEquals("a_b", SaveNames.sanitize("a\u0000b"))
+ }
+
+ @Test fun `only what runs nothing is opened, under a type from the name`() {
+ assertEquals("application/pdf", SaveNames.openableType("Report.PDF"))
+ assertEquals("video/mp4", SaveNames.openableType("clip.mp4"))
+ for (n in listOf("page.html", "image.svg", "run.apk", "script.js", "noext", "x.pdf.exe")) {
+ assertNull(n, SaveNames.openableType(n))
+ }
+ assertEquals("application/octet-stream", SaveNames.storedType("page.html"))
+ }
+
+ @Test fun `a taken name becomes name (n), never an overwrite`() {
+ assertEquals("film (2).mkv", SaveNames.numbered("film.mkv", 2))
+ assertEquals("README (3)", SaveNames.numbered("README", 3))
+ }
+
+ @Test fun `a binary frame is read as the shim writes it`() {
+ val payload = byteArrayOf(1, 2, 3, 4, 5)
+ val b = byteArrayOf(0x4d, 0x42, 0x42, 0x31, 0, 0, 1, 2, 0, 1, 0, 0, 0, 0, 0, 7) + payload
+ val f = BinaryFrame.parse(b)!!
+ assertEquals(258L, f.id)
+ assertEquals(BinaryFrame.SAVE_WRITE, f.channel)
+ assertEquals(7L, f.handle)
+ assertArrayEquals(payload, f.bytes.copyOfRange(f.offset, f.bytes.size))
+ assertNull(BinaryFrame.parse(byteArrayOf(0x4d, 0x42, 0x42, 0x32) + ByteArray(12)))
+ assertNull(BinaryFrame.parse(ByteArray(10)))
+ }
+}
diff --git a/packages/meshbay-android/build.gradle.kts b/packages/meshbay-android/build.gradle.kts
new file mode 100644
index 0000000..a4370dd
--- /dev/null
+++ b/packages/meshbay-android/build.gradle.kts
@@ -0,0 +1 @@
+plugins { id("com.android.application") version "9.4.1" apply false }
diff --git a/packages/meshbay-android/gradle.properties b/packages/meshbay-android/gradle.properties
new file mode 100644
index 0000000..660848f
--- /dev/null
+++ b/packages/meshbay-android/gradle.properties
@@ -0,0 +1,2 @@
+org.gradle.jvmargs=-Xmx2g
+android.useAndroidX=true
diff --git a/packages/meshbay-android/gradle/wrapper/gradle-wrapper.jar b/packages/meshbay-android/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..5097068
--- /dev/null
+++ b/packages/meshbay-android/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/packages/meshbay-android/gradle/wrapper/gradle-wrapper.properties b/packages/meshbay-android/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..9f3a241
--- /dev/null
+++ b/packages/meshbay-android/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,10 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-bin.zip
+networkTimeout=10000
+retries=0
+retryBackOffMs=500
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionSha256Sum=bafd5ce9cfaea0fbccfdc8439a1ac42fbd4cd9c89dc9a988228d8a2639a58e6c
diff --git a/packages/meshbay-android/gradlew b/packages/meshbay-android/gradlew
new file mode 100755
index 0000000..249efbb
--- /dev/null
+++ b/packages/meshbay-android/gradlew
@@ -0,0 +1,248 @@
+#!/bin/sh
+
+#
+# Copyright © 2015 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+# gradlew start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh gradlew
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/packages/meshbay-android/gradlew.bat b/packages/meshbay-android/gradlew.bat
new file mode 100644
index 0000000..3185a43
--- /dev/null
+++ b/packages/meshbay-android/gradlew.bat
@@ -0,0 +1,112 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem gradlew startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables, and ensure extensions are enabled
+setlocal EnableExtensions
+
+@rem Catch executions from older scripts and ensure they exit cleanly.
+@rem This can be removed once we can be reasonably confident that few people
+@rem will be migrating directly to this new wrapper.
+goto afterSafetyNet
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+goto exitWithErrorLevel
+:afterSafetyNet
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+1>&2 echo.
+1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+1>&2 echo.
+1>&2 echo Please set the JAVA_HOME variable in your environment to match the
+1>&2 echo location of your Java installation.
+
+"%COMSPEC%" /c exit 1
+goto exitWithErrorLevel
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+1>&2 echo.
+1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+1>&2 echo.
+1>&2 echo Please set the JAVA_HOME variable in your environment to match the
+1>&2 echo location of your Java installation.
+
+"%COMSPEC%" /c exit 1
+goto exitWithErrorLevel
+
+:execute
+@rem Setup the command line
+
+
+
+@rem Execute gradlew
+@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
+@rem which allows us to clear the local environment before executing the java command
+endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel
+
+@rem This label must not be changed. We rely on old scripts being able to jump to this point.
+:exitWithErrorLevel
+@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
+"%COMSPEC%" /c exit %ERRORLEVEL%
diff --git a/packages/meshbay-android/settings.gradle.kts b/packages/meshbay-android/settings.gradle.kts
new file mode 100644
index 0000000..cead413
--- /dev/null
+++ b/packages/meshbay-android/settings.gradle.kts
@@ -0,0 +1,9 @@
+pluginManagement {
+ repositories { google(); mavenCentral(); gradlePluginPortal() }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories { google(); mavenCentral() }
+}
+rootProject.name = "meshbay-android"
+include(":app")
diff --git a/packages/meshbay-client/package.json b/packages/meshbay-client/package.json
index 80c021f..a13c0ab 100644
--- a/packages/meshbay-client/package.json
+++ b/packages/meshbay-client/package.json
@@ -1,6 +1,6 @@
{
"name": "meshbay-client",
- "version": "0.17.0",
+ "version": "0.18.0",
"description": "MeshBay desktop client — the interface ships with the application, not from the hub",
"license": "AGPL-3.0-or-later",
"author": "MeshBay Team <team@meshbay.org>",
@@ -53,6 +53,10 @@
{
"from": "../../packaging/win/ensure-node-path.ps1",
"to": "ensure-node-path.ps1"
+ },
+ {
+ "from": "../../LICENSE",
+ "to": "LICENSE.txt"
}
]
},
diff --git a/packages/meshbay-client/src/argon2-wasm.js b/packages/meshbay-client/src/argon2-wasm.js
index c68e994..4660414 100644
--- a/packages/meshbay-client/src/argon2-wasm.js
+++ b/packages/meshbay-client/src/argon2-wasm.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
/**
* Argon2id for the main process, from the page's own WebAssembly build.
*
diff --git a/packages/meshbay-client/src/cast-chromecast.js b/packages/meshbay-client/src/cast-chromecast.js
index 1355cdd..8c6c9c6 100644
--- a/packages/meshbay-client/src/cast-chromecast.js
+++ b/packages/meshbay-client/src/cast-chromecast.js
@@ -41,12 +41,31 @@ const TEXT_TRACK_STYLE = Object.freeze({
});
/**
- * What to hand `player.load()` for a stream, with or without subtitles.
+ * What to hand `player.load()` for a stream, with or without subtitles, or
+ * for a whole file the relay serves.
*
* `streamType: 'LIVE'` because the relay has no beginning to seek back to —
* the film's own timeline lives on this side, and a seek restarts the relay.
+ * A file is the relay's to describe (`file`: its type and what to show with
+ * it), never the page's: a photo is not a stream at all, and a music track is
+ * an ordinary buffered file the receiver seeks in itself.
*/
-function mediaFor(mediaUrl, subtitle) {
+function mediaFor(mediaUrl, subtitle, file) {
+ if (file && file.contentType.startsWith('image/')) {
+ return { contentId: mediaUrl, contentType: file.contentType, streamType: 'NONE',
+ metadata: { metadataType: 4 } }; // PhotoMediaMetadata
+ }
+ if (file) {
+ const meta = file.meta || {};
+ return {
+ contentId: mediaUrl, contentType: file.contentType, streamType: 'BUFFERED',
+ metadata: {
+ metadataType: 3, // MusicTrackMediaMetadata
+ title: meta.title || '', artist: meta.artist || '', albumName: meta.album || '',
+ images: meta.cover ? [{ url: meta.cover }] : [],
+ },
+ };
+ }
const media = {
contentId: mediaUrl,
contentType: 'video/mp4',
@@ -67,30 +86,39 @@ function mediaFor(mediaUrl, subtitle) {
return media;
}
-function loadOptionsFor(subtitle) {
- return {
+function loadOptionsFor(subtitle, startAt) {
+ const options = {
autoplay: true,
activeTrackIds: subtitle && subtitle.url ? [TEXT_TRACK_ID] : [],
};
+ // Where in a track to begin: a cast started mid-song carries on from there.
+ if (startAt > 0) options.currentTime = startAt;
+ return options;
}
class CastChromecast {
constructor() {
this._bonjour = null;
this._browser = null;
+ this._scanTimer = null;
this._devices = new Map();
this._client = null;
this._player = null;
this._connectedDevice = null;
}
- async discover() {
+ /**
+ * Start a scan and return at once; `devices()` reads what it has found so far.
+ *
+ * The scan runs its full length because a receiver coming back from a reset
+ * can take several seconds to answer, but most answer within two, and a
+ * picker that waits the full length to show any of them is a picker that is
+ * slow every single time. So the page polls and lists each one as it lands.
+ * A scan started over an unfinished one replaces it, timer included.
+ */
+ startScan() {
this._devices.clear();
-
- if (this._browser) {
- this._browser.stop();
- this._browser = null;
- }
+ this._stopScan();
if (!this._bonjour) {
this._bonjour = new Bonjour();
@@ -98,33 +126,42 @@ class CastChromecast {
debug('[cast-chromecast] scanning for devices...');
- return new Promise((resolve) => {
- this._browser = this._bonjour.find({ type: 'googlecast' }, (service) => {
- const id = service.txt?.id || service.name;
- const name = service.txt?.fn || service.name;
- const host = service.addresses?.find((a) => /^\d+\.\d+\.\d+\.\d+$/.test(a))
- || (service.referer && service.referer.address);
- const port = service.port || 8009;
-
- if (host && id) {
- this._devices.set(id, { id, name, host, port });
- debug(`[cast-chromecast] discovered: "${name}" at ${host}:${port}`);
- }
- });
+ this._browser = this._bonjour.find({ type: 'googlecast' }, (service) => {
+ const id = service.txt?.id || service.name;
+ const name = service.txt?.fn || service.name;
+ const host = service.addresses?.find((a) => /^\d+\.\d+\.\d+\.\d+$/.test(a))
+ || (service.referer && service.referer.address);
+ const port = service.port || 8009;
- setTimeout(() => {
- if (this._browser) {
- this._browser.stop();
- this._browser = null;
- }
- const devices = Array.from(this._devices.values());
- debug(`[cast-chromecast] scan complete: ${devices.length} device(s)`);
- resolve(devices);
- }, SCAN_DURATION_MS);
+ if (host && id) {
+ this._devices.set(id, { id, name, host, port });
+ debug(`[cast-chromecast] discovered: "${name}" at ${host}:${port}`);
+ }
});
+
+ this._scanTimer = setTimeout(() => {
+ this._stopScan();
+ debug(`[cast-chromecast] scan complete: ${this._devices.size} device(s)`);
+ }, SCAN_DURATION_MS);
+ }
+
+ devices() {
+ return {
+ devices: Array.from(this._devices.values()),
+ scanning: this._browser !== null,
+ };
+ }
+
+ _stopScan() {
+ clearTimeout(this._scanTimer);
+ this._scanTimer = null;
+ if (this._browser) {
+ this._browser.stop();
+ this._browser = null;
+ }
}
- async connect(deviceId, mediaUrl, subtitle) {
+ async connect(deviceId, mediaUrl, subtitle, file, startAt) {
const device = this._devices.get(deviceId);
if (!device) throw new Error(`Unknown device: ${deviceId}`);
@@ -159,32 +196,35 @@ class CastChromecast {
player.on('status', (status) => {
debug(`[cast-chromecast] player status: ${status.playerState}`);
+ this._noteStatus(status);
});
debug(`[cast-chromecast] loading with ${subtitle?.url ? 'subtitles' : 'no subtitles'}`);
const status = await new Promise((resolve, reject) => {
- player.load(mediaFor(mediaUrl, subtitle), loadOptionsFor(subtitle),
+ player.load(mediaFor(mediaUrl, subtitle, file), loadOptionsFor(subtitle, startAt),
(err, s) => {
if (err) return reject(err);
resolve(s);
});
});
+ this._noteStatus(status);
debug(`[cast-chromecast] loaded on "${device.name}", state: ${status.playerState}`);
return { deviceName: device.name, playerState: status.playerState };
}
- async reload(mediaUrl, subtitle) {
+ async reload(mediaUrl, subtitle, file, startAt) {
if (!this._player) throw new Error('Not connected');
debug(`[cast-chromecast] reloading stream on "${this._connectedDevice?.name}"`
+ ` with ${subtitle?.url ? 'subtitles' : 'no subtitles'}`);
const status = await new Promise((resolve, reject) => {
- this._player.load(mediaFor(mediaUrl, subtitle), loadOptionsFor(subtitle),
+ this._player.load(mediaFor(mediaUrl, subtitle, file), loadOptionsFor(subtitle, startAt),
(err, s) => {
if (err) return reject(err);
resolve(s);
});
});
+ this._noteStatus(status);
debug(`[cast-chromecast] reloaded, state: ${status.playerState}`);
return { playerState: status.playerState };
}
@@ -200,10 +240,65 @@ class CastChromecast {
this._cleanup();
}
+ /**
+ * What the receiver last said, kept so the page can show where the
+ * *television* is: its playhead is not the local one, which started earlier
+ * and drifts. `currentTime` is on the stream's timeline — zero at the point
+ * the relay started — and the page adds that start.
+ */
+ _noteStatus(status) {
+ if (!status) return;
+ this._lastStatus = {
+ playerState: status.playerState || null,
+ idleReason: status.idleReason || null,
+ position: Number(status.currentTime) || 0,
+ at: Date.now(),
+ };
+ }
+
+ /** The receiver's position now: extrapolated while it plays, as its own clock does. */
+ _position() {
+ const s = this._lastStatus;
+ if (!s) return null;
+ return s.playerState === 'PLAYING' ? s.position + (Date.now() - s.at) / 1000 : s.position;
+ }
+
+ async pause() {
+ if (!this._player) throw new Error('Not connected');
+ const status = await new Promise((resolve, reject) => {
+ this._player.pause((err, s) => (err ? reject(err) : resolve(s)));
+ });
+ this._noteStatus(status);
+ return { playerState: status && status.playerState };
+ }
+
+ /** Where in a track the receiver should be; a film seeks by restarting the relay instead. */
+ async seek(seconds) {
+ if (!this._player) throw new Error('Not connected');
+ const status = await new Promise((resolve, reject) => {
+ this._player.seek(Math.max(0, Number(seconds) || 0), (err, s) => (err ? reject(err) : resolve(s)));
+ });
+ this._noteStatus(status);
+ return { playerState: status && status.playerState };
+ }
+
+ async play() {
+ if (!this._player) throw new Error('Not connected');
+ const status = await new Promise((resolve, reject) => {
+ this._player.play((err, s) => (err ? reject(err) : resolve(s)));
+ });
+ this._noteStatus(status);
+ return { playerState: status && status.playerState };
+ }
+
getStatus() {
+ const s = this._lastStatus;
return {
connected: this._client !== null,
deviceName: this._connectedDevice?.name || null,
+ playerState: s ? s.playerState : null,
+ idleReason: s ? s.idleReason : null,
+ position: this._client !== null ? this._position() : null,
};
}
@@ -214,6 +309,7 @@ class CastChromecast {
this._client = null;
this._player = null;
this._connectedDevice = null;
+ this._lastStatus = null;
}
}
diff --git a/packages/meshbay-client/src/cast-relay.js b/packages/meshbay-client/src/cast-relay.js
index 58eb9ac..ed20b33 100644
--- a/packages/meshbay-client/src/cast-relay.js
+++ b/packages/meshbay-client/src/cast-relay.js
@@ -15,6 +15,12 @@
* a media element, so unlike the stream it needs CORS headers to be readable
* at all.
*
+ * A whole file — a photo, or a music track with its cover at `/cover` — is
+ * served at `/file`, one at a time: the page decrypts it and hands it over in
+ * pieces (begin, writes, end), and the receiver loads it as a picture or as
+ * music. Ranges are honoured there, which is what a receiver seeks with. The
+ * relay starts for a file when it is not already running.
+ *
* Mitigations:
* · Bind to the LAN interface, never 0.0.0.0
* · Fixed port range (19550-19553), opened only during active cast
@@ -50,6 +56,16 @@ const util = require('node:util');
const debug = util.debuglog('cast-relay');
const RING_CAP = 64;
+// What the receiver is ever told a photo is. The page re-encodes every photo
+// to JPEG, so this list is a guard, not a menu.
+const FILE_TYPES = new Set([
+ 'image/jpeg', 'image/png', 'image/webp',
+ 'audio/mpeg', 'audio/mp4', 'audio/aac', 'audio/flac', 'audio/ogg', 'audio/opus',
+ 'audio/wav', 'audio/webm',
+]);
+// A track is a few megabytes, a long lossless one a few hundred; this only
+// stops a page from filling the machine's memory.
+const FILE_MAX_BYTES = 1024 * 1024 * 1024;
const BACKPRESSURE_HIGH = 8 * 1024 * 1024;
const MOOF = 0x6d6f6f66;
const PORT_BASE = 19550;
@@ -163,6 +179,9 @@ class CastRelay {
this._bytesSent = 0;
this._subtitle = null;
this._subtitleVersion = 0;
+ this._file = null;
+ this._fileVersion = 0;
+ this._incoming = null;
}
get active() { return this._server !== null; }
@@ -185,6 +204,70 @@ class CastRelay {
+ `?t=${this._token}&v=${this._subtitleVersion}`;
}
+ /**
+ * Where the current file can be fetched, or null when there is none.
+ * Versioned for the same reason as the subtitle: a receiver handed the same
+ * address twice shows what it already has.
+ */
+ get fileUrl() {
+ if (!this._server || !this._file) return null;
+ return `http://${this._lanIP}:${this._port}/file`
+ + `?t=${this._token}&v=${this._fileVersion}`;
+ }
+
+ get fileType() { return this._file ? this._file.type : null; }
+
+ /** What the receiver is told the file is: title, artist, album, cover. */
+ get fileMeta() {
+ if (!this._file) return null;
+ const { title, artist, album } = this._file.meta;
+ const cover = this._file.cover
+ ? `http://${this._lanIP}:${this._port}/cover?t=${this._token}&v=${this._fileVersion}`
+ : null;
+ return { title, artist, album, cover };
+ }
+
+ /**
+ * A file arrives in three steps, so that a large one never has to cross in
+ * a single message: `beginFile` names it, `writeFile` appends, `endFile`
+ * puts it up and answers its address. The relay starts if nothing has.
+ */
+ async beginFile({ type, size, cover, title, artist, album }) {
+ if (!FILE_TYPES.has(type)) throw new Error(`Not something a receiver shows: ${type}`);
+ if (!(size > 0 && size <= FILE_MAX_BYTES)) throw new Error(`Bad file size: ${size}`);
+ if (cover && !FILE_TYPES.has(cover.type)) throw new Error(`Bad cover type: ${cover.type}`);
+ if (!this._server) await this.start({});
+ const text = (v) => (typeof v === 'string' ? v.slice(0, 500) : '');
+ this._incoming = {
+ type, size, parts: [], received: 0,
+ cover: cover && cover.type.startsWith('image/')
+ ? { bytes: Buffer.from(cover.bytes), type: cover.type } : null,
+ meta: { title: text(title), artist: text(artist), album: text(album) },
+ };
+ return true;
+ }
+
+ writeFile(bytes) {
+ const f = this._incoming;
+ if (!f) throw new Error('No file is being sent');
+ const buf = Buffer.from(bytes);
+ if (f.received + buf.length > f.size) throw new Error('More bytes than announced');
+ f.parts.push(buf);
+ f.received += buf.length;
+ return true;
+ }
+
+ endFile() {
+ const f = this._incoming;
+ this._incoming = null;
+ if (!f) throw new Error('No file is being sent');
+ if (f.received !== f.size) throw new Error(`File cut short: ${f.received} of ${f.size} bytes`);
+ this._file = { bytes: Buffer.concat(f.parts), type: f.type, cover: f.cover, meta: f.meta };
+ this._fileVersion++;
+ debug(`[cast-relay] file set: ${f.size} bytes, ${f.type}, v${this._fileVersion}`);
+ return { url: this.fileUrl };
+ }
+
get subtitle() {
if (!this._subtitle) return null;
return {
@@ -232,6 +315,8 @@ class CastRelay {
this._chunkCount = 0;
this._bytesSent = 0;
this._subtitle = null;
+ this._file = null;
+ this._incoming = null;
this.setSubtitle(subtitle);
const server = http.createServer((req, res) => this._handle(req, res));
@@ -323,6 +408,8 @@ class CastRelay {
this._token = null;
this._initSegment = null;
this._subtitle = null;
+ this._file = null;
+ this._incoming = null;
this._ring = [];
this._accum.reset();
this._fragCount = 0;
@@ -366,6 +453,16 @@ class CastRelay {
return;
}
+ if (url.pathname === '/file') {
+ this._handleFile(req, res);
+ return;
+ }
+
+ if (url.pathname === '/cover') {
+ this._handleCover(res);
+ return;
+ }
+
if (url.pathname !== '/stream.mp4') {
res.writeHead(404);
res.end();
@@ -419,6 +516,60 @@ class CastRelay {
res.end(this._subtitle.vtt);
debug(`[cast-relay] subtitle served: ${this._subtitle.vtt.length} bytes`);
}
+
+ /**
+ * The whole file, or the one range asked for: a receiver seeks in a track
+ * by asking for the bytes from there on.
+ */
+ _handleFile(req, res) {
+ const f = this._file;
+ if (!f) {
+ res.writeHead(404, CORS_HEADERS);
+ res.end();
+ return;
+ }
+ const total = f.bytes.length;
+ const base = {
+ ...CORS_HEADERS,
+ 'Content-Type': f.type,
+ 'Cache-Control': 'no-store',
+ 'Accept-Ranges': 'bytes',
+ };
+ const m = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range || '');
+ if (m && (m[1] !== '' || m[2] !== '')) {
+ let from = m[1] === '' ? total - Number(m[2]) : Number(m[1]);
+ let to = m[1] === '' || m[2] === '' ? total - 1 : Math.min(Number(m[2]), total - 1);
+ from = Math.max(0, from);
+ if (from > to || from >= total) {
+ res.writeHead(416, { ...base, 'Content-Range': `bytes */${total}` });
+ res.end();
+ return;
+ }
+ res.writeHead(206, { ...base, 'Content-Range': `bytes ${from}-${to}/${total}`,
+ 'Content-Length': to - from + 1 });
+ res.end(f.bytes.subarray(from, to + 1));
+ return;
+ }
+ res.writeHead(200, { ...base, 'Content-Length': total });
+ res.end(f.bytes);
+ debug(`[cast-relay] file served: ${total} bytes`);
+ }
+
+ _handleCover(res) {
+ const c = this._file && this._file.cover;
+ if (!c) {
+ res.writeHead(404, CORS_HEADERS);
+ res.end();
+ return;
+ }
+ res.writeHead(200, {
+ ...CORS_HEADERS,
+ 'Content-Type': c.type,
+ 'Content-Length': c.bytes.length,
+ 'Cache-Control': 'no-store',
+ });
+ res.end(c.bytes);
+ }
}
module.exports = CastRelay;
diff --git a/packages/meshbay-client/src/keyring.js b/packages/meshbay-client/src/keyring.js
index ec37fd4..c9997aa 100644
--- a/packages/meshbay-client/src/keyring.js
+++ b/packages/meshbay-client/src/keyring.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
/**
* The account's keys in the desktop application: the bundle master key `M` and
* the identity on every node, held here and never handed to the page.
diff --git a/packages/meshbay-client/src/main.js b/packages/meshbay-client/src/main.js
index c1ff540..f582b57 100644
--- a/packages/meshbay-client/src/main.js
+++ b/packages/meshbay-client/src/main.js
@@ -20,8 +20,8 @@
'use strict';
-const { app, BrowserWindow, dialog, ipcMain, Menu, protocol, safeStorage,
- shell, Tray } =
+const { app, BrowserWindow, dialog, ipcMain, Menu, powerSaveBlocker, protocol,
+ safeStorage, shell, Tray } =
require('electron');
const { execFile, spawn } = require('node:child_process');
const crypto = require('node:crypto');
@@ -1144,19 +1144,12 @@ function registerBridge() {
return true;
});
- // A folder chosen here is one the person pointed at in a dialog this process
- // drew, which is the consent that sharing it needs: the node is given it
- // without asking again. A folder the page names that was not chosen here is
- // confirmed natively before the node hears of it (`node:op`).
- const pickedFolders = new Set();
-
handle('root:choose', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory', 'createDirectory'],
});
if (result.canceled || !result.filePaths.length) return null;
const chosen = result.filePaths[0];
- pickedFolders.add(path.resolve(chosen));
return { path: chosen, name: path.basename(chosen) };
});
@@ -1276,11 +1269,11 @@ function registerBridge() {
//
// The renderer never sees the session token. It names an operation and this
// process executes it — the same pattern as hub:fetch. The token is read
- // from the daemon's data directory, cached for the lifetime of this process,
- // and never exposed through the preload.
+ // from the daemon's data directory on every call and never exposed through
+ // the preload. Not cached: the daemon writes a new one each run and deletes
+ // it on stop, so a cached copy answered 401 after every node restart, and an
+ // operation asked before any page had called detect() had none at all.
- let _nodeToken = null;
- let _nodePort = 18000;
let _nodePairingCode = null;
function nodeConfigPath() {
@@ -1312,16 +1305,20 @@ function registerBridge() {
}
}
+ function nodeEndpoint() {
+ const nc = readNodeConfig();
+ const token = readNodeToken(nc ? nc.dataDir : meshbayDataDir());
+ return token ? { token, port: nc ? nc.uiPort : 18000 } : null;
+ }
+
handle('node:detect', async () => {
const nc = readNodeConfig();
if (!nc) return { detected: false, configured: false };
const token = readNodeToken(nc.dataDir);
if (!token) return { detected: false, configured: true };
- _nodeToken = token;
- _nodePort = nc.uiPort;
try {
const r = await fetch(
- `http://127.0.0.1:${_nodePort}/api/status?t=${_nodeToken}`,
+ `http://127.0.0.1:${nc.uiPort}/api/status?t=${token}`,
{ signal: AbortSignal.timeout(3000) });
if (!r.ok) return { detected: false, configured: true };
const status = await r.json();
@@ -1896,8 +1893,6 @@ function registerBridge() {
const READY = ['running', 'waiting_for_node_key', 'waiting_for_account',
'waiting_for_hub', 'starting'];
if (!READY.includes(status.status)) return null;
- _nodeToken = token;
- _nodePort = port;
return { pk_node_ed25519: status.pk_node_ed25519 || '', status: status.status,
version: status.version || '' };
} catch { return null; }
@@ -2185,38 +2180,28 @@ function registerBridge() {
const group = (a) => `/api/groups/${anId(a.groupId, 'the group')}`;
const root = (a) => `${group(a)}/roots/${encodeURIComponent(aText(a.rootName, 'the folder name'))}`;
- // Sharing a folder the person did not choose in this process's dialog.
- async function confirmFolder(folder) {
- if (!pickedFolders.has(path.resolve(folder))) {
- await confirmOrRefuse('native.folder_confirm', { path: folder });
- }
- }
-
const NODE_OPS = {
status: () => ['GET', '/api/status'],
groups: () => ['GET', '/api/groups'],
indexStatus: () => ['GET', '/api/index-status'],
groupIndexStatus: (a) => ['GET', `${group(a)}/index-status`],
reload: () => ['POST', '/api/reload'],
- attachGroup: async (a) => {
+ attachGroup: (a) => {
const body = { name: aText(a.name, 'the group name'),
shared_dir: aText(a.path, 'the folder', 4096),
writable: a.writable !== false,
// The person's choice on the creation form; the node never
// takes it from the hub.
join_policy: a.joinPolicy === 'open' ? 'open' : 'invite' };
- await confirmFolder(body.shared_dir);
return ['POST', '/api/groups/attach', body];
},
detachGroup: (a) => ['POST', '/api/groups/detach', { name: aText(a.name, 'the group name') }],
- addRoot: async (a) => {
+ addRoot: (a) => {
const body = { path: aText(a.path, 'the folder', 4096) };
if (a.name) body.name = aText(a.name, 'the folder name');
if (a.writable !== undefined) body.writable = Boolean(a.writable);
if (a.removable !== undefined) body.removable = Boolean(a.removable);
- const target = `${group(a)}/roots`;
- await confirmFolder(body.path);
- return ['POST', target, body];
+ return ['POST', `${group(a)}/roots`, body];
},
updateRoot: (a) => ['PATCH', root(a), anObject(a.updates)],
ejectRoot: (a) => ['PUT', `${root(a)}/eject`],
@@ -2252,10 +2237,11 @@ function registerBridge() {
handle('node:op', async (_e, name, args) => {
const op = Object.hasOwn(NODE_OPS, String(name)) ? NODE_OPS[String(name)] : null;
if (!op) throw new Error(`Refused: unknown node operation ${String(name)}`);
- if (!_nodeToken) throw new Error('Node not detected');
+ const endpoint = nodeEndpoint();
+ if (!endpoint) throw new Error('Node not detected');
const [method, apiPath, body] = await op(anObject(args));
const sep = apiPath.includes('?') ? '&' : '?';
- const url = `http://127.0.0.1:${_nodePort}${apiPath}${sep}t=${_nodeToken}`;
+ const url = `http://127.0.0.1:${endpoint.port}${apiPath}${sep}t=${endpoint.token}`;
const init = { method };
if (body !== undefined && body !== null) {
init.headers = { 'Content-Type': 'application/json' };
@@ -2321,6 +2307,19 @@ function registerBridge() {
return true;
});
+ // The screen may sleep while music plays; the machine may not, or the
+ // connection to the node goes with it.
+ let playbackBlocker = null;
+ handle('playback:keep-alive', async (_event, on) => {
+ if (on === true && playbackBlocker === null) {
+ playbackBlocker = powerSaveBlocker.start('prevent-app-suspension');
+ } else if (on !== true && playbackBlocker !== null) {
+ powerSaveBlocker.stop(playbackBlocker);
+ playbackBlocker = null;
+ }
+ return true;
+ });
+
handle('cast:status', async () => ({
active: castRelay.active,
url: castRelay.url,
@@ -2330,20 +2329,42 @@ function registerBridge() {
// ── Chromecast discovery + control ──────────────────────────────────────
- handle('cast:discover', async () => {
- return castChromecast.discover();
+ handle('cast:scan', async () => {
+ castChromecast.startScan();
+ return true;
});
- handle('cast:chromecast:connect', async (_e, { deviceId, mediaUrl, subtitle }) => {
- return castChromecast.connect(deviceId, mediaUrl,
- subtitle === undefined ? castRelay.subtitle : subtitle);
+ handle('cast:devices', async () => castChromecast.devices());
+
+ // A whole file for the receiver — a photo, a music track — in three steps,
+ // so that a large one never crosses in a single message.
+ handle('cast:file:begin', async (_e, f) => castRelay.beginFile(f || {}));
+ handle('cast:file:write', async (_e, data) => castRelay.writeFile(Buffer.from(data)));
+ handle('cast:file:end', async () => castRelay.endFile());
+
+ // The relay's file is loaded as what the relay says it is, anything else as
+ // the stream; the page does not get to say which.
+ const loadOf = (mediaUrl, subtitle) => (
+ mediaUrl && mediaUrl === castRelay.fileUrl
+ ? { subtitle: null, file: { contentType: castRelay.fileType, meta: castRelay.fileMeta } }
+ : { subtitle: subtitle === undefined ? castRelay.subtitle : subtitle, file: null });
+
+ handle('cast:chromecast:connect', async (_e, { deviceId, mediaUrl, subtitle, startAt }) => {
+ const l = loadOf(mediaUrl, subtitle);
+ return castChromecast.connect(deviceId, mediaUrl, l.subtitle, l.file, l.file ? startAt : 0);
});
- handle('cast:chromecast:reload', async (_e, { mediaUrl, subtitle }) => {
- return castChromecast.reload(mediaUrl,
- subtitle === undefined ? castRelay.subtitle : subtitle);
+ handle('cast:chromecast:reload', async (_e, { mediaUrl, subtitle, startAt }) => {
+ const l = loadOf(mediaUrl, subtitle);
+ return castChromecast.reload(mediaUrl, l.subtitle, l.file, l.file ? startAt : 0);
});
+ handle('cast:chromecast:seek', async (_e, seconds) => castChromecast.seek(seconds));
+
+ // The player becomes a remote while casting: these drive the receiver.
+ handle('cast:chromecast:pause', async () => castChromecast.pause());
+ handle('cast:chromecast:play', async () => castChromecast.play());
+
handle('cast:chromecast:disconnect', async () => {
await castChromecast.disconnect();
return true;
diff --git a/packages/meshbay-client/src/preload.js b/packages/meshbay-client/src/preload.js
index e9c34d2..0de76db 100644
--- a/packages/meshbay-client/src/preload.js
+++ b/packages/meshbay-client/src/preload.js
@@ -165,6 +165,11 @@ contextBridge.exposeInMainWorld('meshbay', {
serviceMode: (action) => ipcRenderer.invoke('node:service-mode', action),
},
+ // Music is playing: the machine must not idle-sleep under it.
+ playback: {
+ keepAlive: (on) => ipcRenderer.invoke('playback:keep-alive', on === true),
+ },
+
// LAN cast relay. The main process runs a local HTTP server and the
// renderer feeds it decrypted segments. A Chromecast or Smart TV on the
// same Wi-Fi plays from the URL.
@@ -173,12 +178,28 @@ contextBridge.exposeInMainWorld('meshbay', {
push: (data) => ipcRenderer.invoke('cast:push', data),
stop: () => ipcRenderer.invoke('cast:stop'),
subtitle: (sub) => ipcRenderer.invoke('cast:subtitle', sub),
+ // A file in pieces of a few megabytes, as the Android bridge sends it.
+ file: async (f) => {
+ const bytes = f.bytes;
+ await ipcRenderer.invoke('cast:file:begin', {
+ type: f.type, size: bytes.length, cover: f.cover || null,
+ title: f.title, artist: f.artist, album: f.album,
+ });
+ for (let at = 0; at < bytes.length; at += 4 * 1024 * 1024) {
+ await ipcRenderer.invoke('cast:file:write', bytes.subarray(at, at + 4 * 1024 * 1024));
+ }
+ return ipcRenderer.invoke('cast:file:end');
+ },
finish: () => ipcRenderer.invoke('cast:finish'),
status: () => ipcRenderer.invoke('cast:status'),
- discover: () => ipcRenderer.invoke('cast:discover'),
+ scan: () => ipcRenderer.invoke('cast:scan'),
+ devices: () => ipcRenderer.invoke('cast:devices'),
chromecastConnect: (opts) => ipcRenderer.invoke('cast:chromecast:connect', opts),
chromecastReload: (opts) => ipcRenderer.invoke('cast:chromecast:reload', opts),
chromecastDisconnect: () => ipcRenderer.invoke('cast:chromecast:disconnect'),
+ chromecastPause: () => ipcRenderer.invoke('cast:chromecast:pause'),
+ chromecastPlay: () => ipcRenderer.invoke('cast:chromecast:play'),
+ chromecastSeek: (seconds) => ipcRenderer.invoke('cast:chromecast:seek', seconds),
},
// A sink that writes to disk as chunks arrive, never a buffer handed over at
diff --git a/packages/meshbay-client/src/transcripts.js b/packages/meshbay-client/src/transcripts.js
index 0b6d0c0..a58cb24 100644
--- a/packages/meshbay-client/src/transcripts.js
+++ b/packages/meshbay-client/src/transcripts.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
/**
* What a node identity signs, built here from named fields — never bytes the
* page chose.
@@ -30,6 +32,20 @@ function lenPrefixed(prefix, parts) {
return Buffer.concat(chunks);
}
+// The signed operations this application asks a node to perform
+// (meshbay_common/adminop.py). A list, not a pattern: what widens a node's
+// sharing — `root_add`, `root_update`, `group_attach`, gone from MNP 6.0 — is
+// never signed here, so a node older than that cannot be driven into it by a
+// script in the page either.
+const ADMIN_OPS = new Set([
+ 'file_delete', 'dir_delete', 'invite_create', 'invite_link_create',
+ 'invite_cancel', 'member_revoke', 'apps_enabled', 'set_scan_settings',
+ 'tmdb_config', 'tmdb_enabled', 'tmdb_override', 'tmdb_rematch',
+ 'musicbrainz_enabled', 'root_remove', 'root_eject', 'root_plug',
+ 'app_directories', 'chat_directory', 'chat_link_preview', 'search_listed',
+ 'chat_epoch',
+]);
+
// ── Field checks ──────────────────────────────────────────────────────────
//
// Shapes, not trust: what is checked here is that a field is what its name
@@ -143,7 +159,7 @@ function transcriptFor(kind, f, ctx) {
}
case 'admin': {
const op = String(fields.op ?? '');
- if (!/^[a-z_]{1,32}$/.test(op)) refuse('not an operation');
+ if (!ADMIN_OPS.has(op)) refuse('not an operation');
return lenPrefixed(PREFIX.admin, [
enc(op), enc(sameNode()), enc(groupId(fields.groupId)),
enc(text(fields.subject, 'the subject', 16384)),
diff --git a/packages/meshbay-common/COPYING b/packages/meshbay-common/COPYING
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/packages/meshbay-common/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/packages/meshbay-common/COPYING.LESSER b/packages/meshbay-common/COPYING.LESSER
new file mode 100644
index 0000000..0a04128
--- /dev/null
+++ b/packages/meshbay-common/COPYING.LESSER
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/packages/meshbay-common/pyproject.toml b/packages/meshbay-common/pyproject.toml
index 188ccf6..dca3aa0 100644
--- a/packages/meshbay-common/pyproject.toml
+++ b/packages/meshbay-common/pyproject.toml
@@ -1,12 +1,14 @@
[build-system]
-requires = ["hatchling"]
+requires = ["hatchling>=1.27"] # PEP 639: SPDX `license` + `license-files`
build-backend = "hatchling.build"
[project]
name = "meshbay-common"
-version = "0.17.0"
+version = "0.18.0"
description = "MeshBay shared cryptographic primitives and protocol types"
requires-python = ">=3.12"
+license = "LGPL-3.0-or-later"
+license-files = ["COPYING", "COPYING.LESSER"]
dependencies = [
"cryptography>=43.0",
"PyJWT>=2.9",
diff --git a/packages/meshbay-common/src/meshbay_common/__init__.py b/packages/meshbay-common/src/meshbay_common/__init__.py
index b68e828..3ffb2b7 100644
--- a/packages/meshbay-common/src/meshbay_common/__init__.py
+++ b/packages/meshbay-common/src/meshbay_common/__init__.py
@@ -1,6 +1,6 @@
"""MeshBay common — shared crypto primitives and protocol types."""
-__version__ = "0.17.0"
+__version__ = "0.18.0"
# 0.2: added PING/PONG, and `before`/`has_more` on chat history. Both are
# additive — an 0.1 peer sends no `before` and gets the newest page, which is
# what it wanted — so this is a MINOR bump, not a MAJOR one.
@@ -260,5 +260,17 @@ __version__ = "0.17.0"
# a refusal, across the break. The break is confined to them, so the floor stays
# at 4.0: everything else a 4.x peer does still works, and nothing is left
# unsigned on either side — no node accepts the old subjects.
-MNP_VERSION = "5.0"
+#
+# 6.0 (2026-10-02) is a MAJOR — three signed operations are removed: `root_add`,
+# `root_update` and `group_attach`. What of the operator's disk is shared, and
+# whether members may write there, is decided on the node's own machine (the
+# desktop application over loopback, or the CLI), never
+# over the wire. A 5.x client that sends one gets no answer, as for any unknown
+# type; everything else it does still works, so the floor stays at 4.0.
+# The same version removes ten operator messages no client ever sent —
+# `gek_rotate`, `member_unpin`, `transfer_limits`, `group_detach` (signed) and
+# `node_status`, `node_settings_set`, `roster_read`, `denylist_read`,
+# `denylist_clear`, `node_reload` — whose work the Node page and the CLI do over
+# loopback.
+MNP_VERSION = "6.0"
MHP_VERSION = "0.1"
diff --git a/packages/meshbay-common/src/meshbay_common/adminop.py b/packages/meshbay-common/src/meshbay_common/adminop.py
index 4379519..bd7a439 100644
--- a/packages/meshbay-common/src/meshbay_common/adminop.py
+++ b/packages/meshbay-common/src/meshbay_common/adminop.py
@@ -47,14 +47,6 @@ OP_INVITE_LINK_CREATE = "invite_link_create"
# Taking back an unredeemed link, by the handle it was issued with.
OP_INVITE_CANCEL = "invite_cancel"
OP_MEMBER_REVOKE = "member_revoke"
-# Rotating the group key is what actually takes it away from a revoked member:
-# revocation stops the node serving the *next* key, and they still hold the
-# current one. The node generates the new key itself with its own CSPRNG, so
-# nothing arriving over MNP contributes key material — the C5b rule is about
-# key material from outside, not about the instruction.
-OP_GEK_ROTATE = "gek_rotate"
-# Forgetting a pinned identity, so someone can pair again after losing a device.
-OP_MEMBER_UNPIN = "member_unpin"
# Which group "applications" (Chat, Files, and whatever registers later) are
# shown to members. Signed like the rest: it decides what a member sees, not
# anything about key material, but an unsigned toggle would let any member
@@ -67,11 +59,6 @@ OP_APPS_ENABLED = "apps_enabled"
# security property in itself, but the pattern (every operator setting is
# signed) is what keeps the authorization model simple to reason about.
OP_SET_SCAN_SETTINGS = "set_scan_settings"
-# How many transfers one member may run at once in this group. Signed like the
-# rest: an unsigned cap is one any member can raise for themselves, which makes
-# the control a suggestion. The subject is "d=2,u=2" so what the operator is
-# shown before signing names the outcome and not the operation.
-OP_TRANSFER_LIMITS = "transfer_limits"
# Whether the node uses the operator's own API token/language instead of the
# shipped default — node-wide (docs/MESHBAY_DESIGN.md §9.7), one credential
# shared by every group. Signed like the rest: it turns on outbound
@@ -101,7 +88,6 @@ OP_TMDB_REMATCH = "tmdb_rematch"
# the lesson was already learned once). Signed for the same reason as
# tmdb_enabled.
OP_MUSICBRAINZ_ENABLED = "musicbrainz_enabled"
-OP_ROOT_ADD = "root_add"
OP_ROOT_REMOVE = "root_remove"
# One op for every application's directories. The subject is
# "<app>:<comma-joined sorted paths>" so what the operator is shown before
@@ -115,18 +101,26 @@ OP_CHAT_LINK_PREVIEW = "chat_link_preview"
# operator's, signed like the other per-group switches.
OP_SEARCH_LISTED = "search_listed"
# Open a new chat epoch for a group, by hand. The removals that matter open one
-# by themselves (member revoke/unpin, device revoke, gek_rotate); this is the
-# operator saying "do it anyway", which is the same shape as `gek_rotate` and
-# signed for the same reason.
+# by themselves (member revoke/unpin, device revoke, group key rotation); this is the
+# operator saying "do it anyway", and is signed like the rest.
#
# There is no op for *enabling* chat encryption. It is not a setting — MNP 2.0
# has no plaintext chat to fall back to.
OP_CHAT_EPOCH = "chat_epoch"
-OP_ROOT_UPDATE = "root_update"
OP_ROOT_EJECT = "root_eject"
OP_ROOT_PLUG = "root_plug"
-OP_GROUP_ATTACH = "group_attach"
-OP_GROUP_DETACH = "group_detach"
+# Also gone with 6.0, because no client ever sent them: `gek_rotate`,
+# `member_unpin`, `transfer_limits` and `group_detach`. Rotating the group key,
+# forgetting an identity, the per-member transfer caps and no longer hosting a
+# group are done on the node's machine — the desktop application's Node page
+# or the CLI. A door nobody uses is an untested way in.
+# OP_ROOT_ADD, OP_ROOT_UPDATE and OP_GROUP_ATTACH are gone (MNP 6.0). Each one
+# chose what of the operator's disk is shared and who may write there, and a
+# signature proves only that the operator's key signed — in a browser, through
+# code the hub serves; on the desktop, through a renderer that parses content
+# from nodes. Sharing a folder, hosting a group and opening a folder to writes
+# are done on the node's own machine (loopback) or with
+# the CLI, and a message that does not exist cannot be mis-authorized.
# OP_GEK_BUNDLE_STORE is gone. Members no longer hand the node key material at
# all: the node holds the GEK and wraps it itself, for a key the recipient proved
# they hold (see `join.py` and docs/MESHBAY_DESIGN.md §3.4). The operation existed
@@ -159,17 +153,6 @@ def secret_digest(value: str | None) -> str | None:
return "sha256:" + hashlib.sha256(value.encode()).hexdigest()
-def root_add_subject(path: str, name: str, kind: str, writable: bool,
- removable: bool) -> str:
- return structured_subject({"path": path, "name": name, "kind": kind,
- "writable": writable, "removable": removable})
-
-
-def group_attach_subject(name: str, shared_dir: str, writable: bool) -> str:
- return structured_subject({"name": name, "shared_dir": shared_dir,
- "writable": writable})
-
-
def invite_create_subject(user_id: str, username: str) -> str:
return structured_subject({"user_id": user_id, "username": username})
diff --git a/packages/meshbay-common/src/meshbay_common/groupbox.py b/packages/meshbay-common/src/meshbay_common/groupbox.py
index 260e362..ae79fcc 100644
--- a/packages/meshbay-common/src/meshbay_common/groupbox.py
+++ b/packages/meshbay-common/src/meshbay_common/groupbox.py
@@ -74,7 +74,7 @@ _INFO = {
# the bound that matters is birthday collision under `PURPOSE_UPLOAD` — the only
# purpose with real volume, one message per 48 KiB chunk. 2**32 chunks is 200 TB
# uploaded under a single GEK before the collision probability reaches 2**-32,
-# and `gek_rotate` exists. Deriving the nonce from the payload instead would be
+# and the group key can be rotated. Deriving the nonce from the payload instead would be
# worse, not better: two chunks of identical bytes are ordinary in a file.
NONCE_LEN = 12 # 96-bit, the WebCrypto AES-GCM standard
diff --git a/packages/meshbay-common/src/meshbay_common/protocol.py b/packages/meshbay-common/src/meshbay_common/protocol.py
index af2d93b..f8e56ec 100644
--- a/packages/meshbay-common/src/meshbay_common/protocol.py
+++ b/packages/meshbay-common/src/meshbay_common/protocol.py
@@ -154,12 +154,8 @@ class MNP:
INVITE_CANCEL = "invite_cancel" # operator → node: take back an unredeemed link
MEMBER_REVOKE = "member_revoke" # operator → node: stop serving the key
MEMBER_REVOKE_ACK = "member_revoke_ack"
- MEMBER_UNPIN = "member_unpin" # operator → node: forget an identity
- MEMBER_UNPIN_ACK = "member_unpin_ack"
APPS_ENABLED = "apps_enabled" # operator → node: which group apps to show
APPS_ENABLED_ACK = "apps_enabled_ack"
- TRANSFER_LIMITS = "transfer_limits" # operator → node: per-member caps here
- TRANSFER_LIMITS_ACK = "transfer_limits_ack" # node → this group: the new caps
SET_SCAN_SETTINGS = "set_scan_settings" # operator → node: reconcile/debounce timing
SET_SCAN_SETTINGS_ACK = "set_scan_settings_ack"
MEDIA_META_REQ = "media_meta_req" # client → node: TMDB metadata for a path
@@ -216,16 +212,8 @@ class MNP:
# where it was.
DEVICE_HELLO = "device_hello" # device → node: this is me
DEVICE_HELLO_ACK = "device_hello_ack"
- # Rotation is the half of revocation that revocation cannot do: the node
- # generates a fresh key itself, so no key material crosses the wire.
- GEK_ROTATE = "gek_rotate" # operator → node: new group key
- GEK_ROTATE_ACK = "gek_rotate_ack"
INVITE_RESULT = "invite_result" # node → operator: the code, once
INVITE_LINK_RESULT = "invite_link_result" # node → operator: link code + handle, once
- NODE_STATUS = "node_status" # operator → node: list all groups + roots
- NODE_STATUS_ACK = "node_status_ack" # node → operator: full status
- ROOT_ADD = "root_add" # operator → node: add a directory to a group
- ROOT_ADD_ACK = "root_add_ack" # node → operator: confirmed
ROOT_REMOVE = "root_remove" # operator → node: remove a root from a group
ROOT_REMOVE_ACK = "root_remove_ack" # node → operator: confirmed
# One message for every application's directories, keyed by the app's own
@@ -256,34 +244,17 @@ class MNP:
# key without having to reconnect.
CHAT_EPOCH = "chat_epoch"
CHAT_EPOCH_ACK = "chat_epoch_ack"
- ROOT_UPDATE = "root_update" # operator → node: a root's flags
- ROOT_UPDATE_ACK = "root_update_ack"
ROOT_EJECT = "root_eject" # operator → node: mark removable root as ejected
ROOT_EJECT_ACK = "root_eject_ack"
ROOT_PLUG = "root_plug" # operator → node: re-enable an ejected root
ROOT_PLUG_ACK = "root_plug_ack"
# Member → node: who is in this group and which device keys they hold, with
- # the countersignature that admitted each one. Distinct from ROSTER_READ
- # below, which is the operator's view of the whole node: this is scoped to
- # one group and answers any member of it, because the point is that a member
+ # the countersignature that admitted each one. Scoped to one group and
+ # answers any member of it, because the point is that a member
# verifies another member's device *for themselves* rather than trusting the
# node's `sender_id` (Tier 2, docs/MESHBAY_DESIGN.md §3.3).
GROUP_ROSTER_REQ = "group_roster_req"
GROUP_ROSTER_RESP = "group_roster_resp"
- ROSTER_READ = "roster_read" # operator → node: identities + members
- ROSTER_READ_ACK = "roster_read_ack"
- DENYLIST_READ = "denylist_read" # operator → node: show denylist entries
- DENYLIST_READ_ACK = "denylist_read_ack"
- DENYLIST_CLEAR = "denylist_clear" # operator → node: remove denylist entry(ies)
- DENYLIST_CLEAR_ACK = "denylist_clear_ack"
- GROUP_ATTACH = "group_attach" # operator → node: host a new group
- GROUP_ATTACH_ACK = "group_attach_ack"
- GROUP_DETACH = "group_detach" # operator → node: stop hosting a group
- GROUP_DETACH_ACK = "group_detach_ack"
- NODE_SETTINGS_SET = "node_settings_set" # operator → node: change daemon settings
- NODE_SETTINGS_SET_ACK = "node_settings_set_ack"
- NODE_RELOAD = "node_reload" # operator → node: re-read node.toml
- NODE_RELOAD_ACK = "node_reload_ack"
# ── Index entry ───────────────────────────────────────────────────────────────
diff --git a/packages/meshbay-common/tests/test_admin_subject_parity.py b/packages/meshbay-common/tests/test_admin_subject_parity.py
index 7a229a9..59deaab 100644
--- a/packages/meshbay-common/tests/test_admin_subject_parity.py
+++ b/packages/meshbay-common/tests/test_admin_subject_parity.py
@@ -18,9 +18,7 @@ from pathlib import Path
import pytest
from meshbay_common.adminop import (
- group_attach_subject,
invite_create_subject,
- root_add_subject,
secret_digest,
structured_subject,
tmdb_config_subject,
@@ -34,16 +32,13 @@ pytestmark = pytest.mark.skipif(
reason="node or crypto.js unavailable — parity cannot be checked",
)
-ROOT_ADD = [
- ("/srv/Films", "", "generic", False, False),
- ("/srv/Films", "Films", "video", True, True),
- ("C:\\Users\\me\\Share", "Partagé", "photo", True, False),
- ('/srv/a "quoted", odd:name|x', "名前", "audio", False, True),
- ("/srv/tab\there\nnewline\x01ctl", "é", "generic", True, False),
-]
-GROUP_ATTACH = [
- ("photos", "/srv/photos", True),
- ("famille-été", "/mnt/disque externe/Photos", False),
+# The canonical JSON itself, on the values that are hard to get identical:
+# separators, quotes, control characters, non-ASCII, and null/""/false.
+STRUCTURED = [
+ {"path": "/srv/Films", "name": "", "writable": False, "n": None},
+ {"path": "C:\\Users\\me\\Share", "name": "Partagé", "kind": "photo"},
+ {"path": '/srv/a "quoted", odd:name|x', "name": "名前", "removable": True},
+ {"path": "/srv/tab\there\nnewline\x01ctl", "name": "é", "z": "", "a": 0},
]
INVITE_CREATE = [
("0f8fad5b-d9cb-469f-a165-70867728950e", ""),
@@ -59,13 +54,12 @@ _HARNESS = r"""
const fs = require('fs');
globalThis.window = {};
const src = fs.readFileSync(process.argv[2], 'utf8');
-const M = new Function(src + '\nreturn { rootAddSubject, groupAttachSubject, '
+const M = new Function(src + '\nreturn { adminSubject, '
+ 'inviteCreateSubject, tmdbConfigSubject };')();
const v = JSON.parse(fs.readFileSync(process.argv[3], 'utf8'));
(async () => {
const out = {
- root_add: v.root_add.map((a) => M.rootAddSubject(...a)),
- group_attach: v.group_attach.map((a) => M.groupAttachSubject(...a)),
+ structured: v.structured.map((f) => M.adminSubject(f)),
invite_create: v.invite_create.map((a) => M.inviteCreateSubject(...a)),
tmdb_config: [],
};
@@ -80,7 +74,7 @@ def js(tmp_path_factory):
d = tmp_path_factory.mktemp("subject-parity")
(d / "harness.js").write_text(_HARNESS, encoding="utf-8")
(d / "vectors.json").write_text(json.dumps({
- "root_add": ROOT_ADD, "group_attach": GROUP_ATTACH,
+ "structured": STRUCTURED,
"invite_create": INVITE_CREATE, "tmdb_config": TMDB_CONFIG,
}), encoding="utf-8")
proc = subprocess.run(
@@ -95,14 +89,9 @@ def _bytes(s: str) -> bytes:
return s.encode("utf-8")
-@pytest.mark.parametrize("i,args", list(enumerate(ROOT_ADD)))
-def test_root_add_subject_parity(i, args, js):
- assert _bytes(js["root_add"][i]) == _bytes(root_add_subject(*args))
-
-
-@pytest.mark.parametrize("i,args", list(enumerate(GROUP_ATTACH)))
-def test_group_attach_subject_parity(i, args, js):
- assert _bytes(js["group_attach"][i]) == _bytes(group_attach_subject(*args))
+@pytest.mark.parametrize("i,fields", list(enumerate(STRUCTURED)))
+def test_structured_subject_parity(i, fields, js):
+ assert _bytes(js["structured"][i]) == _bytes(structured_subject(fields))
@pytest.mark.parametrize("i,args", list(enumerate(INVITE_CREATE)))
@@ -116,13 +105,13 @@ def test_tmdb_config_subject_parity(i, args, js):
def test_every_value_changes_the_subject():
- base = ("/srv/Films", "Films", "video", False, False)
- variants = {root_add_subject(*base)}
- for i, other in enumerate(("/srv/Other", "Other", "audio", True, True)):
+ base = ("0f8fad5b-d9cb-469f-a165-70867728950e", "Someone")
+ variants = {invite_create_subject(*base)}
+ for i, other in enumerate(("6a2f41a3-c54c-fce8-32d2-0324e1c32e22", "Somebody")):
args = list(base)
args[i] = other
- variants.add(root_add_subject(*args))
- assert len(variants) == 6
+ variants.add(invite_create_subject(*args))
+ assert len(variants) == 3
def test_unchanged_cleared_and_set_are_three_subjects():
diff --git a/packages/meshbay-common/tests/test_js_python_parity.py b/packages/meshbay-common/tests/test_js_python_parity.py
index f75d60a..bb52742 100644
--- a/packages/meshbay-common/tests/test_js_python_parity.py
+++ b/packages/meshbay-common/tests/test_js_python_parity.py
@@ -668,7 +668,7 @@ _KIND_FIELDS = {
"chat": {"groupId": "g" * 32, "epoch": 4,
"nonce": base64.b64encode(b"\x01" * 12).decode(),
"ct": base64.b64encode(b"ciphertext").decode()},
- "admin": {"op": "root_add", "nodePk": "Tk9ERVBL", "groupId": "g" * 32,
+ "admin": {"op": "root_remove", "nodePk": "Tk9ERVBL", "groupId": "g" * 32,
"subject": '{"path":"/café"}', "nonce": _NONCE, "ts": 1_700_000_000},
}
diff --git a/packages/meshbay-hub/LICENSE b/packages/meshbay-hub/LICENSE
new file mode 100644
index 0000000..be3f7b2
--- /dev/null
+++ b/packages/meshbay-hub/LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<https://www.gnu.org/licenses/>.
diff --git a/packages/meshbay-hub/pyproject.toml b/packages/meshbay-hub/pyproject.toml
index 7f1154c..643363e 100644
--- a/packages/meshbay-hub/pyproject.toml
+++ b/packages/meshbay-hub/pyproject.toml
@@ -1,12 +1,14 @@
[build-system]
-requires = ["hatchling"]
+requires = ["hatchling>=1.27"] # PEP 639: SPDX `license` + `license-files`
build-backend = "hatchling.build"
[project]
name = "meshbay-hub"
-version = "0.17.0"
+version = "0.18.0"
description = "MeshBay Hub — identity authority and group registry server"
requires-python = ">=3.12"
+license = "AGPL-3.0-or-later"
+license-files = ["LICENSE"]
dependencies = [
"meshbay-common>=0.10.0",
"fastapi>=0.115",
diff --git a/packages/meshbay-hub/src/meshbay_hub/__init__.py b/packages/meshbay-hub/src/meshbay_hub/__init__.py
index 4d3d6dd..cf6868d 100644
--- a/packages/meshbay-hub/src/meshbay_hub/__init__.py
+++ b/packages/meshbay-hub/src/meshbay_hub/__init__.py
@@ -1,3 +1,3 @@
"""MeshBay Hub — identity authority and group registry."""
-__version__ = "0.17.0"
+__version__ = "0.18.0"
diff --git a/packages/meshbay-hub/src/meshbay_hub/api/admin.py b/packages/meshbay-hub/src/meshbay_hub/api/admin.py
index dbda197..1cb8bf9 100644
--- a/packages/meshbay-hub/src/meshbay_hub/api/admin.py
+++ b/packages/meshbay-hub/src/meshbay_hub/api/admin.py
@@ -213,6 +213,7 @@ async def admin_stats(
current_user: User = Depends(require_moderator),
db: AsyncSession = Depends(get_db),
):
+ """Account, group and node counts."""
# Deleted accounts are tombstoned rather than dropped, so that the
# connection log stays readable. They are not users any more and must not be
# counted as any: a hub whose user count only ever rises is measuring its
@@ -244,6 +245,7 @@ async def admin_list_users(
offset: int = 0,
limit: int = Query(default=50, le=200),
):
+ """Search and list accounts."""
query = (select(User).where(User.status != "deleted")
.order_by(User.created_at.desc()))
if q:
@@ -279,6 +281,7 @@ async def admin_get_user(
current_user: User = Depends(require_moderator),
db: AsyncSession = Depends(get_db),
):
+ """One account, with its group count."""
user = await db.get(User, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
@@ -310,6 +313,7 @@ async def admin_patch_user(
current_user: User = Depends(require_moderator),
db: AsyncSession = Depends(get_db),
):
+ """Change an account's status, or its role (admin only)."""
user = await db.get(User, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
@@ -473,6 +477,7 @@ async def admin_list_groups(
offset: int = 0,
limit: int = Query(default=50, le=200),
):
+ """List groups with their member counts."""
query = (
select(
Group,
@@ -524,6 +529,7 @@ async def admin_patch_group(
current_user: User = Depends(require_moderator),
db: AsyncSession = Depends(get_db),
):
+ """Change a group's status."""
group = await db.get(Group, group_id)
if not group:
raise HTTPException(status_code=404, detail="Group not found")
@@ -624,6 +630,7 @@ async def admin_list_logs(
offset: int = 0,
limit: int = Query(default=50, le=200),
):
+ """The connection log, filtered by account and event."""
query = (
select(IPLog, User.username)
.outerjoin(User, IPLog.user_id == User.id)
diff --git a/packages/meshbay-hub/src/meshbay_hub/api/federation.py b/packages/meshbay-hub/src/meshbay_hub/api/federation.py
index 755639e..e737a1c 100644
--- a/packages/meshbay-hub/src/meshbay_hub/api/federation.py
+++ b/packages/meshbay-hub/src/meshbay_hub/api/federation.py
@@ -190,6 +190,7 @@ async def export_directory(
db: AsyncSession = Depends(get_db),
authorization: str = Header(...),
):
+ """This hub's public groups, for a peer hub presenting an MHP token."""
try:
await _verify_mhp_token(authorization.removeprefix("Bearer "), db)
except Exception as e:
@@ -232,6 +233,7 @@ async def receive_directory(
authorization: str = Header(...),
db: AsyncSession = Depends(get_db),
):
+ """A peer hub's public groups, pushed with a single-use MHP token."""
try:
payload = await _verify_mhp_token(
authorization.removeprefix("Bearer "), db, single_use=True)
diff --git a/packages/meshbay-hub/src/meshbay_hub/api/groups.py b/packages/meshbay-hub/src/meshbay_hub/api/groups.py
index fc117bf..d58e32c 100644
--- a/packages/meshbay-hub/src/meshbay_hub/api/groups.py
+++ b/packages/meshbay-hub/src/meshbay_hub/api/groups.py
@@ -120,6 +120,7 @@ async def accept_invitation(
current_user: User = Depends(require_user_scope),
db: AsyncSession = Depends(get_db),
):
+ """Accept an invitation: the account becomes a member of the group."""
inv = await db.get(GroupInvitation, (group_id, current_user.id))
group = await db.get(Group, group_id)
if inv is None or group is None or group.status != "active":
@@ -141,6 +142,7 @@ async def decline_invitation(
current_user: User = Depends(require_user_scope),
db: AsyncSession = Depends(get_db),
):
+ """Decline an invitation to a group."""
inv = await db.get(GroupInvitation, (group_id, current_user.id))
if inv is None:
raise HTTPException(status_code=404, detail="No such invitation")
@@ -281,6 +283,7 @@ async def group_members(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
+ """A group's members, for its members only."""
group = await db.get(Group, group_id)
if not group:
raise HTTPException(status_code=404, detail="Group not found")
@@ -319,6 +322,7 @@ async def join_group(
current_user: User = Depends(require_user_scope),
db: AsyncSession = Depends(get_db),
):
+ """Join an open group."""
group = await db.get(Group, group_id)
if not group:
raise HTTPException(status_code=404, detail="Group not found")
@@ -421,6 +425,7 @@ async def create_group(
current_user: User = Depends(require_user_scope),
db: AsyncSession = Depends(get_db),
):
+ """Create a group, owned by the caller. No node hosts it yet."""
# Being listed and being open are one question, not two.
#
# A public group that admits nobody is a contradiction: it is in the
@@ -643,6 +648,7 @@ async def add_group_member(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
+ """Add an account to a group the caller owns. Also called by the owner's node."""
# `get_current_user`, not `require_user_scope`: the node calls this after a
# CLI `member invite` so the group becomes visible in the invitee's SPA
# (commit 0443cf8). The node authenticates with a node-scoped token, and the
@@ -713,6 +719,7 @@ async def delete_group(
current_user: User = Depends(require_user_scope),
db: AsyncSession = Depends(get_db),
):
+ """Delete a group. Its owner only."""
group = await db.get(Group, group_id)
if not group:
raise HTTPException(status_code=404, detail="Group not found")
@@ -827,6 +834,7 @@ async def list_hosts(
current_user: User = Depends(require_user_scope),
db: AsyncSession = Depends(get_db),
):
+ """The nodes that host a group or asked to, for its owner."""
from meshbay_hub.api.revocation import is_node_connected
await _owned(db, group_id, current_user)
rows = (await db.execute(
diff --git a/packages/meshbay-hub/src/meshbay_hub/api/health.py b/packages/meshbay-hub/src/meshbay_hub/api/health.py
index 516856b..abb1b53 100644
--- a/packages/meshbay-hub/src/meshbay_hub/api/health.py
+++ b/packages/meshbay-hub/src/meshbay_hub/api/health.py
@@ -13,6 +13,7 @@ router = APIRouter(tags=["health"])
@router.get("/v1/health")
async def health(db: AsyncSession = Depends(get_db)):
+ """Liveness: database reachable, version, connected nodes."""
await db.execute(text("SELECT 1"))
return {
"status": "ok",
diff --git a/packages/meshbay-hub/src/meshbay_hub/api/hub.py b/packages/meshbay-hub/src/meshbay_hub/api/hub.py
index a1afe38..d1246a3 100644
--- a/packages/meshbay-hub/src/meshbay_hub/api/hub.py
+++ b/packages/meshbay-hub/src/meshbay_hub/api/hub.py
@@ -22,6 +22,7 @@ def set_config(cfg: HubConfig) -> None:
@router.get("/info")
async def hub_info(db: AsyncSession = Depends(get_db)):
+ """Versions and the instance policy a client needs before signing in."""
engine = get_engine()
return {
"hub_version": __version__,
@@ -88,7 +89,7 @@ async def hub_pubkey():
# reads MBK1/MBK2. An older client would still write them, and every such
# bundle is one no browser of the account can open again.
MIN_CLIENT_VERSION = "0.17.0"
-RECOMMENDED_CLIENT_VERSION = "0.17.0"
+RECOMMENDED_CLIENT_VERSION = "0.18.0"
@router.get("/version")
diff --git a/packages/meshbay-hub/src/meshbay_hub/api/moderation.py b/packages/meshbay-hub/src/meshbay_hub/api/moderation.py
index 038f310..ecca4df 100644
--- a/packages/meshbay-hub/src/meshbay_hub/api/moderation.py
+++ b/packages/meshbay-hub/src/meshbay_hub/api/moderation.py
@@ -244,6 +244,7 @@ async def admin_list_blocklist(
db: AsyncSession = Depends(get_db),
limit: int = 500,
):
+ """The content blocklist."""
result = await db.execute(
select(ContentBlocklist)
.order_by(ContentBlocklist.added_at.desc())
@@ -269,6 +270,7 @@ async def admin_add_blocklist(
current_user: User = Depends(require_admin),
db: AsyncSession = Depends(get_db),
):
+ """Add a content hash (BLAKE3) to the blocklist."""
if not _is_hash(body.content_hash):
raise HTTPException(status_code=422, detail="content_hash must be 64 hex chars (blake3)")
existing = await db.get(ContentBlocklist, body.content_hash)
@@ -291,6 +293,7 @@ async def admin_remove_blocklist(
current_user: User = Depends(require_admin),
db: AsyncSession = Depends(get_db),
):
+ """Remove a content hash from the blocklist."""
entry = await db.get(ContentBlocklist, content_hash)
if not entry:
raise HTTPException(status_code=404, detail="Hash not in blocklist")
@@ -344,6 +347,7 @@ async def admin_block_reported(
current_user: User = Depends(require_admin),
db: AsyncSession = Depends(get_db),
):
+ """Block reported content and close its reports."""
await _decide(db, content_hash, "blocked", current_user.username)
reasons = Counter((await db.execute(select(ContentReport.reason).where(
ContentReport.content_hash == content_hash))).scalars().all())
@@ -363,6 +367,7 @@ async def admin_dismiss_reported(
current_user: User = Depends(require_admin),
db: AsyncSession = Depends(get_db),
):
+ """Dismiss the reports on a piece of content."""
await _decide(db, content_hash, "dismissed", current_user.username)
await db.commit()
return {"status": "dismissed", "hash": content_hash}
diff --git a/packages/meshbay-hub/src/meshbay_hub/api/nodes.py b/packages/meshbay-hub/src/meshbay_hub/api/nodes.py
index decd20e..b158621 100644
--- a/packages/meshbay-hub/src/meshbay_hub/api/nodes.py
+++ b/packages/meshbay-hub/src/meshbay_hub/api/nodes.py
@@ -250,6 +250,7 @@ async def get_node(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
+ """A node's public record: owner, key, endpoint hint."""
node = await db.get(Node, node_id)
if not node:
raise HTTPException(status_code=404, detail="Node not found")
diff --git a/packages/meshbay-hub/src/meshbay_hub/api/notifications.py b/packages/meshbay-hub/src/meshbay_hub/api/notifications.py
index d96ec18..e4bac2e 100644
--- a/packages/meshbay-hub/src/meshbay_hub/api/notifications.py
+++ b/packages/meshbay-hub/src/meshbay_hub/api/notifications.py
@@ -43,6 +43,7 @@ async def list_notifications(
offset: int = Query(default=0, ge=0),
unread_only: bool = False,
):
+ """The account's notifications, newest first."""
query = select(Notification).where(Notification.user_id == current_user.id)
if unread_only:
query = query.where(Notification.read == False) # noqa: E712
diff --git a/packages/meshbay-hub/src/meshbay_hub/api/revocation.py b/packages/meshbay-hub/src/meshbay_hub/api/revocation.py
index 5a33d77..2499374 100644
--- a/packages/meshbay-hub/src/meshbay_hub/api/revocation.py
+++ b/packages/meshbay-hub/src/meshbay_hub/api/revocation.py
@@ -438,7 +438,8 @@ async def _authorize_node_ws(token: str, claimed_id: str, claimed_groups) -> tup
@router.websocket("/v1/nodes/ws")
async def node_websocket(ws: WebSocket):
"""
- Persistent WebSocket connection for nodes.
+ Persistent WebSocket connection for nodes, authenticated by the node's token in the
+ first message.
Finding C2: this used to take `node_id` and `group_ids` straight from the
client's first message, with no check that the authenticated user owned that
diff --git a/packages/meshbay-hub/src/meshbay_hub/api/users.py b/packages/meshbay-hub/src/meshbay_hub/api/users.py
index 9326bfb..795a902 100644
--- a/packages/meshbay-hub/src/meshbay_hub/api/users.py
+++ b/packages/meshbay-hub/src/meshbay_hub/api/users.py
@@ -183,6 +183,7 @@ async def register(
request: Request,
db: AsyncSession = Depends(get_db),
):
+ """Create an account. It stays inactive until its e-mail address is verified."""
eh = hash_email_blind(body.email)
# Unique regardless of case: invitations and member management name people
@@ -485,6 +486,10 @@ async def login(
request: Request,
db: AsyncSession = Depends(get_db),
):
+ """
+ Sign in with the auth key derived from the passphrase. Returns the session and the bundle
+ pepper.
+ """
ip = client_ip(request)
if not body.auth_key and not body.password:
@@ -662,6 +667,7 @@ async def list_devices(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
+ """The account's registered devices."""
result = await db.execute(
select(UserDevice).where(UserDevice.user_id == current_user.id)
.order_by(UserDevice.created_at))
@@ -777,6 +783,7 @@ async def token_refresh(
request: Request,
db: AsyncSession = Depends(get_db),
):
+ """Exchange a refresh token for a new session. Reusing a spent one revokes the whole family."""
rt_hash = hash_refresh_token(body.refresh_token)
result = await db.execute(
select(RefreshToken).where(RefreshToken.token_hash == rt_hash))
@@ -840,6 +847,7 @@ async def get_current_user_info(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
+ """The signed-in account: id, name, e-mail, role, status."""
email = ""
try:
email = decrypt_email(current_user.email) if current_user.email else ""
@@ -1144,6 +1152,7 @@ async def change_password(
current_user: User = Depends(require_user_scope),
db: AsyncSession = Depends(get_db),
):
+ """Change the passphrase, proving the current one."""
await _take_login_attempt(db, _session_counter(current_user))
if not await verify_password_off_loop(body.old_auth_key, current_user.pw_hash,
current_user.pw_salt, current_user.pw_version):
@@ -1231,6 +1240,7 @@ async def password_reset_request(
request: Request,
db: AsyncSession = Depends(get_db),
):
+ """Send a reset code by e-mail, when the username and the address match."""
if _cfg and _cfg.captcha.enabled:
await _verify_captcha_or_raise(body.captcha_token, request)
@@ -1310,6 +1320,7 @@ async def password_reset(
request: Request,
db: AsyncSession = Depends(get_db),
):
+ """Set a new passphrase with the code received by e-mail."""
now = datetime.now(UTC)
result = await db.execute(select(User).where(User.username == body.username))
user = result.scalar_one_or_none()
@@ -1407,6 +1418,7 @@ async def get_preferences(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
+ """The account's stored interface preferences."""
result = await db.execute(
select(UserPreference).where(UserPreference.user_id == current_user.id))
prefs = {p.key: p.value for p in result.scalars().all()}
@@ -1424,6 +1436,7 @@ async def set_preference(
current_user: User = Depends(require_user_scope),
db: AsyncSession = Depends(get_db),
):
+ """Store one interface preference."""
if not _valid_pref_key(key):
raise HTTPException(status_code=400, detail=f"Unknown preference key: {key[:80]}")
if len(body.value) > MAX_PREFERENCE_VALUE:
@@ -1454,6 +1467,7 @@ async def delete_preference(
current_user: User = Depends(require_user_scope),
db: AsyncSession = Depends(get_db),
):
+ """Remove one interface preference."""
result = await db.execute(
select(UserPreference).where(
UserPreference.user_id == current_user.id,
@@ -1624,6 +1638,7 @@ async def get_user_pubkeys(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
+ """Resolve a username to its account id, and its node's linking key. Not a key directory."""
result = await db.execute(select(User).where(User.username == username))
target = result.scalar_one_or_none()
if not target:
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/app.js b/packages/meshbay-hub/src/meshbay_hub/static/app.js
index 72dd123..bdab271 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/app.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/app.js
@@ -21,6 +21,7 @@ import {
} from './hub-client.js';
import { startIdleWatch, markActive } from './idle.js';
import { GroupPage } from './group-page.js';
+import { parseGroupLink, groupLinkRoute, findLinkedGroup } from './group-link.js';
import { lazy } from './lazy.js';
import { ConnectionPool } from './connection-pool.js';
import { MusicPlayerBar } from './music-player.js';
@@ -592,7 +593,10 @@ function HomePage({ groups, notifications, onMarkRead, onPurge, allowPublicGroup
const [setupDismissed, setSetupDismissed] = useState(false);
if (groups.length === 0) {
- if (platform.isNative && !setupDismissed) {
+ // Setting up a node needs one to administer: the desktop application, not
+ // any native shell. A phone has a bridge and no node, and what it needs
+ // with no groups is the invitations and the join link below.
+ if (platform.capabilities.nodeAdmin && !setupDismissed) {
return html`<${SetupWelcome}
onDismiss=${() => setSetupDismissed(true)} />`;
}
@@ -763,6 +767,9 @@ function App() {
const [needsHub, setNeedsHub] = useState(
platform.isNative && !platform.hubBase());
const [groups, setGroups] = useState([]);
+ // Whether `/mine` has answered for this sign-in. A `#/name@owner` link can
+ // only be called unknown once the list it is looked up in has arrived.
+ const [groupsLoaded, setGroupsLoaded] = useState(false);
const [menuOpen, setMenuOpen] = useState(false);
const [notifications, setNotifications] = useState([]);
const [unreadCount, setUnreadCount] = useState(0);
@@ -1005,11 +1012,13 @@ function App() {
if (!user) {
nodeKeyAskedForRef.current = null;
setGroups([]); setNotifications([]); setUnreadCount(0); setHasNodeKey(false);
+ setGroupsLoaded(false);
return;
}
hubFetch('/v1/groups/mine', { token: user.token })
.then(data => setGroups(data.groups || []))
- .catch(() => setGroups([]));
+ .catch(() => setGroups([]))
+ .finally(() => setGroupsLoaded(true));
hubFetch('/v1/users/me/preferences', { token: user.token })
.then(async (prefs) => {
setUserPrefs(prefs || {});
@@ -1230,11 +1239,36 @@ function App() {
// out as the only way back.
const refreshAuth = useCallback(() => refreshAccessToken(), []);
+ // A group is reached by its id (`#/group/<id>`, what every link inside the
+ // application uses) or by its handle (`#/name@owner[/path]`, the one a person
+ // types or shares — group-link.js). Both open the same page; `groupRoute` is
+ // the first form whichever was used, so the sidebar and the page see one.
+ const groupLink = route.startsWith('/group/') ? null : parseGroupLink(route);
+ const linkedGroup = groupLink ? findLinkedGroup(groups, groupLink) : null;
+ const groupId = route.startsWith('/group/') ? route.slice(7)
+ : linkedGroup ? linkedGroup.id : null;
+ const groupRoute = groupId ? '/group/' + groupId : route;
+ const shownGroup = groupId ? groups.find(g => g.id === groupId) : null;
+ const linkPath = groupLink && linkedGroup ? groupLink.path : '';
+ // The address shows the handle, which is the link worth copying. `replace`,
+ // so this is not a history entry; and only once the path a link named has
+ // been acted on (`onLinkOpened`), so a reload does not download the file a
+ // second time.
+ const shownGroupRoute = shownGroup ? groupLinkRoute(shownGroup) : null;
+ useEffect(() => {
+ if (shownGroupRoute && !linkPath && route !== shownGroupRoute) {
+ window.location.replace('#' + shownGroupRoute);
+ }
+ }, [route, shownGroupRoute, linkPath]);
+ const onLinkOpened = useCallback(() => {
+ if (shownGroupRoute) window.location.replace('#' + shownGroupRoute);
+ }, [shownGroupRoute]);
+
let page;
// A desktop build with no hub configured cannot do anything at all, so it
- // asks before showing a sign-in form that could not work. Deliberately not
- // defaulted to meshbay.org: a client that picks its own hub is a client that
- // can be pointed at one.
+ // asks before showing a sign-in form that could not work. The field comes
+ // filled with meshbay.org but is still asked: a client that picks its own hub
+ // is a client that can be pointed at one.
if (needsHub) {
page = html`<${FirstRunPage} onSet=${() => setNeedsHub(false)} />`;
} else if (!deviceTried) {
@@ -1279,17 +1313,23 @@ function App() {
}} />`;
} else if (route === '/node' && platform.capabilities.nodeAdmin && hasNodeKey) {
page = html`<${LazyNodePage} groups=${groups} token=${user.token} username=${user.username} />`;
- } else if (route.startsWith('/group/')) {
- const groupId = route.slice(7);
- const group = groups.find(g => g.id === groupId);
+ } else if (groupId) {
page = html`<${GroupPage}
- groupId=${groupId} group=${group} token=${user.token}
+ groupId=${groupId} group=${shownGroup} token=${user.token}
+ openPath=${linkPath} onLinkOpened=${onLinkOpened}
username=${user.username} userId=${user.userId}
userPrefs=${userPrefs}
onRefreshAuth=${refreshAuth} onJoined=${dismissGroupNotifications}
onGroupUpdated=${updateGroup} onPresence=${notePresence}
onLeft=${handleLeftGroup}
onPlayQueue=${handlePlayQueue} onStopMusic=${handleStopMusic} />`;
+ } else if (groupLink) {
+ // Not among this account's groups — or not yet known to be. The same words
+ // whether it does not exist or is someone else's: the list it was looked
+ // up in is this account's own, so there is nothing else to tell.
+ page = groupsLoaded
+ ? html`<div class="page-content"><p class="page-message">${t('group.link_unknown')}</p></div>`
+ : html`<div class="page-content"><p class="page-message"><span class="spinner"></span></p></div>`;
} else if (route === '/admin') {
page = (user.role === 'moderator' || user.role === 'admin')
? html`<${LazyAdminPage} token=${user.token} role=${user.role} />`
@@ -1331,7 +1371,7 @@ function App() {
groups=${groups}
presence=${presence}
indexProgressPct=${indexProgressPct}
- route=${route}
+ route=${groupRoute}
menuOpen=${menuOpen}
role=${user.role}
allowPublicGroups=${allowPublicGroups}
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/auth-page.js b/packages/meshbay-hub/src/meshbay_hub/static/auth-page.js
index d3d3bd7..57db475 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/auth-page.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/auth-page.js
@@ -130,7 +130,7 @@ function passwordBits(pw) {
}
export function FirstRunPage({ onSet }) {
- const [url, setUrl] = useState('');
+ const [url, setUrl] = useState('https://meshbay.org');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
@@ -161,7 +161,6 @@ export function FirstRunPage({ onSet }) {
</button>
</form>
${error && html`<div class="error-msg">${error}</div>`}
- <p class="settings-hint" style="margin-top:16px">${t('firstrun.note')}</p>
</div>
</div>
`;
@@ -186,8 +185,12 @@ export function LoginPage({ onLogin }) {
// Trimmed to match the hub's stored username and every client-side key
// derivation (auth_key, bundle_key, recovery_key all fold the username in).
await onLogin(name, password);
- // Back to the invitation that sent them here, if one is waiting.
- navigate(loadPending() ? '/invite' : '/');
+ // Back to the invitation that sent them here, if one is waiting. Otherwise
+ // nowhere: on `#/login` or `#/register` the router sends a signed-in
+ // person home itself, and anywhere else this form stood in for the page
+ // the address names — a group, a file in one — which is where they were
+ // going. Sending everyone home lost every link opened signed out.
+ if (loadPending()) navigate('/invite');
} catch (err) {
if (err.message === 'email_verification_required') {
setPendingVerif(true);
@@ -277,7 +280,8 @@ const WELCOME_DOCS = [
['welcome.docs_userguide', `${REPO}docs/USERGUIDE.md`]]],
['gear', 'welcome.docs_devel', [
['welcome.docs_design', `${REPO}docs/MESHBAY_DESIGN.md`],
- ['welcome.docs_protocol', `${REPO}docs/MESHBAY_NODE_PROTOCOL.md`]]],
+ ['welcome.docs_protocol', `${REPO}docs/MESHBAY_NODE_PROTOCOL.md`],
+ ['welcome.docs_api', `${REPO}docs/MESHBAY_HTTP_API.md`]]],
];
// Under the sign-in form rather than at the foot of the text: on a desktop the
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/cast-session.js b/packages/meshbay-hub/src/meshbay_hub/static/cast-session.js
new file mode 100644
index 0000000..9f93919
--- /dev/null
+++ b/packages/meshbay-hub/src/meshbay_hub/static/cast-session.js
@@ -0,0 +1,220 @@
+import { html, useState, useEffect, useRef } from './vendor/htm-preact.js';
+import { t } from './i18n.js';
+import { Icon } from './icon.js';
+import * as platform from './platform.js';
+
+// ── The television this session casts to ─────────────────────────────────────
+//
+// docs/MESHBAY_DESIGN.md §11.4. Chosen once, from any cast button — Videos'
+// toolbar, a photo album's bar, the lightbox, the player — and from then on a
+// film opened plays there with the player as its remote, and a photo opened
+// in the lightbox is shown there. In memory only: a television chosen
+// yesterday may be off today, and choosing it again is one tap.
+//
+// The receiver is the default media receiver, which shows one film, one
+// picture or one track at a time and nothing else; the interface itself stays
+// on this device. `owner` says which of the three the television is showing
+// now ('video', 'photo', 'music'), so that the music bar stops treating the
+// receiver as its own once a film or a photo has taken it.
+
+let current = null;
+let owner = null;
+const listeners = new Set();
+
+function notify() {
+ for (const fn of listeners) fn(current);
+}
+
+export const castSession = {
+ get device() { return current; },
+ get owner() { return owner; },
+ get supported() { return Boolean(platform.capabilities.lanCast && platform.cast.available); },
+ /** Whether a whole file (a photo, a track) can be sent: an older shell cannot. */
+ get canSendFiles() { return this.supported && platform.cast.canSendFiles; },
+ /** The television now shows what `who` sends it. */
+ claim(who) {
+ owner = who;
+ notify();
+ },
+ choose(device) {
+ current = device ? { id: device.id, name: device.name } : null;
+ notify();
+ },
+ /** Forget the television without touching it: whoever stopped it already has. */
+ forget() { this.choose(null); },
+ /** Stop casting: the television goes back to its idle screen. */
+ async end() {
+ owner = null;
+ this.choose(null);
+ photoGen++;
+ await platform.cast.chromecastDisconnect().catch(() => {});
+ await platform.cast.stop().catch(() => {});
+ },
+ subscribe(fn) {
+ listeners.add(fn);
+ return () => listeners.delete(fn);
+ },
+};
+
+export function useCastDevice() {
+ const [device, setDevice] = useState(castSession.device);
+ useEffect(() => castSession.subscribe(setDevice), []);
+ return device;
+}
+
+// ── A file on the television ─────────────────────────────────────────────────
+//
+// A photo or a music track, whole, handed to the relay and loaded on the
+// session's television — connected if it is not yet, reloaded if it is. The
+// relay, not the page, tells the receiver what the file is; the page only
+// names it (title, artist, album, cover) and says where in it to begin.
+
+export async function loadFile({ owner: who, startAt = 0, ...file }) {
+ const device = current;
+ if (!device || !castSession.canSendFiles) throw new Error('No television to cast to');
+ castSession.claim(who);
+ const sent = await platform.cast.file(file);
+ if (!sent) throw new Error('The cast relay did not take the file');
+ const status = await platform.cast.status();
+ if (status && status.chromecast && status.chromecast.connected) {
+ await platform.cast.chromecastReload({ mediaUrl: sent.url, startAt });
+ } else {
+ await platform.cast.chromecastConnect({ deviceId: device.id, mediaUrl: sent.url, startAt });
+ }
+}
+
+// ── A photo on the television ────────────────────────────────────────────────
+//
+// Scaled to fit 1920×1080 and re-encoded as JPEG before it leaves: a camera's
+// original is 20 MB and 6000 px wide, more than a receiver decodes in good
+// time, and some are formats it does not decode at all. EXIF orientation is
+// applied here, so a portrait photo arrives upright and the receiver centres
+// it. Photos asked for while one is still on its way are skipped to the
+// newest: paging quickly through an album shows where the reader stopped,
+// not every photo passed on the way.
+
+const TV_WIDTH = 1920;
+const TV_HEIGHT = 1080;
+const JPEG_QUALITY = 0.9;
+
+async function scaledForTv(blob) {
+ const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
+ try {
+ const scale = Math.min(1, TV_WIDTH / bitmap.width, TV_HEIGHT / bitmap.height);
+ const canvas = document.createElement('canvas');
+ canvas.width = Math.max(1, Math.round(bitmap.width * scale));
+ canvas.height = Math.max(1, Math.round(bitmap.height * scale));
+ canvas.getContext('2d').drawImage(bitmap, 0, 0, canvas.width, canvas.height);
+ const jpeg = await new Promise((resolve, reject) => canvas.toBlob(
+ (b) => (b ? resolve(b) : reject(new Error('JPEG encoding failed'))),
+ 'image/jpeg', JPEG_QUALITY));
+ return new Uint8Array(await jpeg.arrayBuffer());
+ } finally {
+ bitmap.close();
+ }
+}
+
+let photoGen = 0;
+let photoChain = Promise.resolve();
+
+/** Show `blob` on the session's television, if there is one. */
+export function showPhoto(blob) {
+ const gen = ++photoGen;
+ photoChain = photoChain.then(async () => {
+ if (gen !== photoGen || !current || !castSession.canSendFiles) return;
+ const bytes = await scaledForTv(blob);
+ if (gen !== photoGen) return;
+ await loadFile({ owner: 'photo', bytes, type: 'image/jpeg' });
+ }).catch((err) => console.warn('[cast] photo not shown:', err));
+ return photoChain;
+}
+
+// ── The cast button ──────────────────────────────────────────────────────────
+//
+// One button, wherever it is put: with no television chosen it lists the
+// receivers as they answer; with one, it says which and offers to stop.
+// `overlay` is for the dark full-screen views (lightbox), `page` for a
+// toolbar. `cls` and `iconCls` are the button's and its icon's own classes,
+// so it matches its neighbours.
+// `onChosen` runs after a television is picked, for the view that has
+// something to show on it straight away. `up` opens the menu above the
+// button, for one at the bottom of the window.
+
+export function CastButton({
+ variant = 'page', cls = 'tb-btn tb-btn-icon', iconCls = '', onChosen, up = false,
+}) {
+ const device = useCastDevice();
+ const [open, setOpen] = useState(false);
+ const [devices, setDevices] = useState([]);
+ const [scanning, setScanning] = useState(false);
+ const wrapRef = useRef(null);
+
+ useEffect(() => {
+ if (!open || device) return undefined;
+ setDevices([]);
+ setScanning(true);
+ return platform.cast.discover((list, still) => {
+ setDevices(list || []);
+ setScanning(still);
+ });
+ }, [open, device]);
+
+ // Closed by a press anywhere else, as any menu is.
+ useEffect(() => {
+ if (!open) return undefined;
+ const outside = (e) => {
+ if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
+ };
+ document.addEventListener('pointerdown', outside);
+ return () => document.removeEventListener('pointerdown', outside);
+ }, [open]);
+
+ if (!castSession.supported) return null;
+
+ const overlay = variant === 'overlay';
+ const menuCls = `${overlay ? 'cast-picker' : 'ctx-menu cast-menu'}${up ? ' cast-menu-up' : ''}`;
+ const itemCls = overlay ? 'cast-picker-item' : 'ctx-menu-item';
+ const title = device ? `${t('cast.casting_to')} ${device.name}` : t('cast.start');
+
+ return html`
+ <div class="cast-wrapper" ref=${wrapRef}>
+ <button class="${cls} cast-btn ${device ? 'casting' : ''}"
+ onClick=${() => setOpen(!open)} title=${title} aria-label=${title}
+ aria-expanded=${open ? 'true' : 'false'}>
+ <${Icon} name="cast" cls=${iconCls} /></button>
+ ${open && html`
+ <div class=${menuCls} role="menu">
+ ${device && html`
+ <div class="${itemCls} cast-menu-current">
+ <${Icon} name="cast" /> ${t('cast.casting_to')} ${device.name}
+ </div>
+ <button class=${itemCls} role="menuitem" onClick=${() => {
+ setOpen(false);
+ castSession.end();
+ }}>
+ <${Icon} name="close" /> ${t('cast.stop')}
+ </button>
+ `}
+ ${!device && devices.map((d) => html`
+ <button class=${itemCls} role="menuitem" key=${d.id} onClick=${() => {
+ setOpen(false);
+ castSession.choose(d);
+ if (onChosen) onChosen(d);
+ }}>
+ <${Icon} name="cast" /> ${d.name}
+ </button>
+ `)}
+ ${!device && scanning && html`
+ <div class="${itemCls} cast-picker-scanning">
+ <span class="spinner" style="width:14px;height:14px"></span>
+ ${t('cast.scanning')}
+ </div>
+ `}
+ ${!device && !scanning && devices.length === 0 && html`
+ <div class="${itemCls} cast-picker-empty">${t('cast.no_devices')}</div>
+ `}
+ </div>
+ `}
+ </div>
+ `;
+}
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/copy-link.js b/packages/meshbay-hub/src/meshbay_hub/static/copy-link.js
new file mode 100644
index 0000000..4cc3f30
--- /dev/null
+++ b/packages/meshbay-hub/src/meshbay_hub/static/copy-link.js
@@ -0,0 +1,50 @@
+import { t } from './i18n.js';
+import * as platform from './platform.js';
+import { groupLinkRoute } from './group-link.js';
+import { say } from './note.js';
+
+/**
+ * "Copy link": the `#/name@owner/path` address of a file or folder
+ * (group-link.js), on this hub, put on the clipboard.
+ *
+ * The hub's origin, never the page's: in the desktop application the page is
+ * `app://meshbay`, and a link that only opens inside one person's application
+ * is not a link.
+ */
+
+/** The full link to `path` inside `group` (`{ name, owner_username }`). */
+export function groupItemLink(group, path) {
+ return platform.hubOrigin() + '/#' + groupLinkRoute(group, path);
+}
+
+/** An entry's path inside its group: its folder, root first, then its name. */
+export function entryPath(entry, dir = entry.path) {
+ return [dir, entry.name].filter(Boolean).join('/');
+}
+
+// The async clipboard first; the old command where it is refused — a page
+// without focus, a WebView without the permission. Neither needs to read
+// anything back.
+async function _write(text) {
+ try {
+ await navigator.clipboard.writeText(text);
+ return true;
+ } catch { /* fall through */ }
+ const area = document.createElement('textarea');
+ area.value = text;
+ area.setAttribute('readonly', '');
+ area.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none';
+ document.body.appendChild(area);
+ area.select();
+ let ok = false;
+ try { ok = document.execCommand('copy'); } catch { ok = false; }
+ area.remove();
+ return ok;
+}
+
+/** Copy `url`, and say whether it worked. The link itself is shown if not. */
+export async function copyLink(url) {
+ if (!url) return;
+ const ok = await _write(url);
+ say(ok ? t('link.copied') : t('link.copy_failed', { url }));
+}
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/crypto.js b/packages/meshbay-hub/src/meshbay_hub/static/crypto.js
index c239cc8..11114d9 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/crypto.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/crypto.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
/**
* MeshBay Browser Crypto — AES-256-GCM, through WebCrypto's SubtleCrypto API.
* The one content cipher, for every client (meshbay_common/webcrypto.py).
@@ -328,14 +330,6 @@ async function secretDigest(value) {
.map((b) => b.toString(16).padStart(2, '0')).join('');
}
-function rootAddSubject(path, name, kind, writable, removable) {
- return adminSubject({ path, name, kind, writable, removable });
-}
-
-function groupAttachSubject(name, sharedDir, writable) {
- return adminSubject({ name, shared_dir: sharedDir, writable });
-}
-
function inviteCreateSubject(userId, username) {
return adminSubject({ user_id: userId, username });
}
@@ -625,7 +619,7 @@ window.MeshBayCrypto = {
importGEK, deriveChunkKey, decryptChunkBin,
openGroup, sealGroup,
unwrapGEK, b64encode, b64decode,
- adminTranscript, adminSubject, rootAddSubject, groupAttachSubject,
+ adminTranscript, adminSubject,
inviteCreateSubject, tmdbConfigSubject, handshakeTranscript, handshakeProof, webrtcBinding,
challengeTranscript, joinTranscript, verifyNodeSignature, constantTimeEqual,
deviceRequestTranscript, deviceAddTranscript, deviceHelloTranscript,
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/file-utils.js b/packages/meshbay-hub/src/meshbay_hub/static/file-utils.js
index aa45a25..2ff2bd4 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/file-utils.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/file-utils.js
@@ -392,6 +392,10 @@ async function pipelinedDownload(transport, gekKey, fileId, totalChunks, onChunk
throw err;
}
const chunkMsg = await inflight[nextRecv];
+ // Released as soon as it is read: a resolved promise left here holds its
+ // ciphertext, and the array holds every chunk of the file — so a download
+ // written straight to disk was also held whole in the page until it ended.
+ inflight[nextRecv] = undefined;
// One shape, and a refusal for anything else. There used to be two fallbacks
// below this: a base64 `ct_b64` chunk, which was the real wire format until
// the binary switch in Phase 9.15 and which no node has sent since, and a
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/files-app.js b/packages/meshbay-hub/src/meshbay_hub/static/files-app.js
index 38157b9..b3672c9 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/files-app.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/files-app.js
@@ -13,6 +13,7 @@ import {
import { useStickyBand } from './sticky.js';
import { Menu, useMenu } from './menu.js';
import { askReport } from './report.js';
+import { copyLink } from './copy-link.js';
// ── Files ────────────────────────────────────────────────────────────────────
//
@@ -142,12 +143,16 @@ function FilesPanel({
entries, nodeDirs, nodeRoots, setEntries, setNodeDirs, setNodeRoots, applyIndex,
isNodeAdmin, operatorPaired, userId, setError, onPreview,
showGroup, readOnly, getTransport, onRefreshIndex, showRefresh, onReport,
+ openDirectory, linkFor,
}) {
const [selected, setSelected] = useState(() => new Set());
const [sortKey, setSortKey] = useState('name');
const [sortAsc, setSortAsc] = useState(true);
const [filter, setFilter] = useState('');
- const [currentPath, setCurrentPath] = useState('');
+ const [currentPath, setCurrentPath] = useState(() => (openDirectory ? openDirectory.dir : ''));
+ // A link into the group named a folder (group-page.js); a new object each
+ // time, so the same folder linked twice is opened twice.
+ useEffect(() => { if (openDirectory) setCurrentPath(openDirectory.dir); }, [openDirectory]);
const [refreshing, setRefreshing] = useState(false);
// The toolbar pins below the page's own band and tells the column heads how
// far down to pin. Its height is not a constant — it wraps to three rows on
@@ -619,6 +624,14 @@ function FilesPanel({
onSelect: () => run(async () => {
for (const d of dirs) await downloadDirectory(d);
}, clear) },
+ // One file or one folder, ticked (the toolbar, which is also how a phone
+ // gets at it) or under the pointer. Absent rather than disabled where
+ // the view can name no link at all (`linkFor` returns null).
+ linkFor && { key: 'link', icon: 'link', label: t('link.copy'),
+ disabled: files.length + dirs.length !== 1
+ || !linkFor(files.length ? files[0] : dirs[0]),
+ onSelect: () => run(
+ () => copyLink(linkFor(files.length ? files[0] : dirs[0])), clear) },
mayEverDelete && !readOnly && { key: 'delete', icon: 'trash', danger: true,
label: deletableCount > 1 ? t('group.delete_n', { n: deletableCount }) : t('group.delete'),
disabled: status !== 'connected' || deletableCount === 0,
@@ -901,7 +914,7 @@ function FilesPanel({
const IMAGE_EXTS = /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i;
-function FilePreview({ entry, transportRef, gekRef, onClose, onDownload }) {
+function FilePreview({ entry, transportRef, gekRef, onClose, onDownload, onCopyLink }) {
const [phase, setPhase] = useState('loading');
const [progress, setProgress] = useState(0);
const [content, setContent] = useState(null);
@@ -996,6 +1009,11 @@ function FilePreview({ entry, transportRef, gekRef, onClose, onDownload }) {
}}>
<div class="video-top-bar">
<span class="video-title">${entry.name} (${formatSize(entry.size)})</span>
+ ${onCopyLink && html`
+ <button class="video-close" onClick=${onCopyLink}
+ title="${t('link.copy')}" aria-label="${t('link.copy')}">
+ <${Icon} name="link" /></button>
+ `}
${onDownload && html`
<button class="video-close ${downloading ? 'dl-active' : ''}"
onClick=${() => {
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/group-link.js b/packages/meshbay-hub/src/meshbay_hub/static/group-link.js
new file mode 100644
index 0000000..3c9063c
--- /dev/null
+++ b/packages/meshbay-hub/src/meshbay_hub/static/group-link.js
@@ -0,0 +1,95 @@
+/**
+ * A group named in the address: `#/name@owner`, optionally followed by a path
+ * inside it — `#/name@owner/root/folder/file.jpg`.
+ *
+ * The same handle `GroupName` shows under every group, so a link reads the way
+ * the group is labelled. It is resolved against the signed-in account's own
+ * group list and nothing else: no hub route answers "which group is this
+ * name", so a name says nothing to someone who is not already a member, and
+ * nobody can probe for one. The UUID stays the group's identity; a renamed
+ * group breaks its name links, never its `#/group/<id>` ones.
+ *
+ * In the fragment, never the path: what follows `#` is not sent to the server,
+ * so a group's name and a file's path appear in no hub or proxy log and in no
+ * Referer.
+ *
+ * The owner is everything after the *last* `@`: a username cannot contain one
+ * (users.py, RegisterRequest), a group name can. Each segment is
+ * percent-decoded on its own, so a `/` inside a name or a file name travels as
+ * `%2F` without splitting the path.
+ *
+ * No imports, so `test_group_link.py` can execute the module as it is.
+ */
+
+function _decode(segment) {
+ try { return decodeURIComponent(segment); } catch { return null; }
+}
+
+// `@` is legal in a fragment and the owner is found by the last one, so the
+// name's own need no escaping; everything else is escaped as a URI component.
+function _encode(segment) {
+ return encodeURIComponent(segment).replace(/%40/g, '@');
+}
+
+/**
+ * `{ name, owner, path }` for a route (the hash without its `#`), or null when
+ * the route does not name a group. `path` is '' for the group itself.
+ */
+function parseGroupLink(route) {
+ if (!route || route[0] !== '/') return null;
+ const parts = route.slice(1).split('/');
+ const head = _decode(parts[0]);
+ if (!head) return null;
+ const at = head.lastIndexOf('@');
+ if (at <= 0 || at === head.length - 1) return null;
+ const rest = parts.slice(1).filter(Boolean).map(_decode);
+ if (rest.some((s) => s === null || s === '.' || s === '..')) return null;
+ return { name: head.slice(0, at), owner: head.slice(at + 1), path: rest.join('/') };
+}
+
+/** The route naming `group`, and `path` inside it when one is given. */
+function groupLinkRoute(group, path = '') {
+ const head = `/${_encode(group.name)}@${_encode(group.owner_username || '')}`;
+ const tail = path ? '/' + path.split('/').filter(Boolean).map(_encode).join('/') : '';
+ return head + tail;
+}
+
+/**
+ * The group `link` names among `groups` (`/v1/groups/mine` rows), or null.
+ *
+ * Case-insensitively on the name, as the hub keeps it unique
+ * (`uq_groups_owner_name` is on `lower(name)`); the owner as typed first, then
+ * case-insensitively when that finds exactly one.
+ */
+function findLinkedGroup(groups, link) {
+ if (!link) return null;
+ const name = link.name.toLowerCase();
+ const named = (groups || []).filter((g) => (g.name || '').toLowerCase() === name);
+ const exact = named.find((g) => g.owner_username === link.owner);
+ if (exact) return exact;
+ const owner = link.owner.toLowerCase();
+ const loose = named.filter((g) => (g.owner_username || '').toLowerCase() === owner);
+ return loose.length === 1 ? loose[0] : null;
+}
+
+/**
+ * What `path` names in a group's index: `{ kind: 'file', entry }`,
+ * `{ kind: 'dir', dir }`, or null. An entry's `path` is its folder, root
+ * first, and `name` its file name — so a file is matched on both together.
+ * Folders come from the files under them and from the node's own listing,
+ * which is the only place an empty one appears.
+ */
+function resolveLinkedPath(entries, nodeDirs, path) {
+ if (!path) return null;
+ const cut = path.lastIndexOf('/');
+ const dir = cut < 0 ? '' : path.slice(0, cut);
+ const name = cut < 0 ? path : path.slice(cut + 1);
+ const entry = (entries || []).find((e) => (e.path || '') === dir && e.name === name);
+ if (entry) return { kind: 'file', entry };
+ const prefix = path + '/';
+ const isDir = (nodeDirs || []).includes(path)
+ || (entries || []).some((e) => (e.path || '') === path || (e.path || '').startsWith(prefix));
+ return isDir ? { kind: 'dir', dir: path } : null;
+}
+
+export { parseGroupLink, groupLinkRoute, findLinkedGroup, resolveLinkedPath };
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/group-page.js b/packages/meshbay-hub/src/meshbay_hub/static/group-page.js
index fe858b2..48b1c80 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/group-page.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/group-page.js
@@ -5,6 +5,8 @@ import { t } from './i18n.js';
import { Icon } from './icon.js';
import { transfers } from './transfers.js';
import { downloadEntry } from './file-utils.js';
+import { resolveLinkedPath } from './group-link.js';
+import { copyLink, entryPath, groupItemLink } from './copy-link.js';
import {
HUB, session, hubFetch, ensureFreshToken,
_loadBundleKey, _loadRecoveryKey, _storeBundleKey,
@@ -33,7 +35,8 @@ import { clearPending, nodePkFromLink, pendingFor } from './invite-link.js';
*/
function GroupPage({ groupId, group, token, username, userId, userPrefs,
onRefreshAuth, onJoined, onGroupUpdated, onPresence, onLeft,
- onPlayQueue: parentOnPlayQueue, onStopMusic }) {
+ onPlayQueue: parentOnPlayQueue, onStopMusic,
+ openPath = '', onLinkOpened }) {
const [status, setStatus] = useState('idle');
// The tab bar pins under the navigation bar and tells the application's own
// toolbar how far down to pin (style.css, "Sticky chrome").
@@ -313,12 +316,18 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs,
});
}, []);
+ // Which group `entries` is the index of. The page is not remounted between
+ // groups, so for one render after a switch `status` and `entries` are still
+ // the last group's — and a link into the new one must not be looked up there.
+ const indexGroupRef = useRef(null);
+
// One place that takes an index from the node and puts it everywhere it has to
// go. Deleting a file used to refresh the table and leave the cache alone, so
// the search page went on offering a file that no longer existed until the
// group was reconnected.
const applyIndex = useCallback((indexMsg) => {
const fresh = indexMsg.entries || [];
+ indexGroupRef.current = groupId;
setEntries(fresh);
if (indexMsg.dirs) setNodeDirs(indexMsg.dirs);
if (indexMsg.roots) setNodeRoots(indexMsg.roots);
@@ -731,6 +740,36 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs,
await downloadEntry(transfers, transport, gekRef.current, entry);
}, []);
+ // A link that named a path inside the group (`#/name@owner/root/dir/file`,
+ // group-link.js): a file is downloaded, and Files opens on its folder either
+ // way. Acted on once the index is in — before that, nothing can say whether
+ // the path is a file, a folder or nothing — and then handed back to the
+ // router, which takes the path out of the address so a reload does not
+ // download it again.
+ const [openDirectory, setOpenDirectory] = useState(null);
+ useEffect(() => { setOpenDirectory(null); }, [groupId]);
+ useEffect(() => {
+ if (!openPath || status !== 'connected' || indexGroupRef.current !== groupId) return;
+ const target = resolveLinkedPath(entries, nodeDirs, openPath);
+ if (!target) {
+ setError(t('group.link_path_unknown', { path: openPath }));
+ } else {
+ const dir = target.kind === 'file' ? (target.entry.path || '') : target.dir;
+ setOpenDirectory({ dir });
+ chooseTab('files');
+ if (target.kind === 'file') downloadFileForModal(target.entry);
+ }
+ if (onLinkOpened) onLinkOpened();
+ }, [openPath, status, groupId]);
+
+ // The link "Copy link" puts on the clipboard, for an entry or a folder path
+ // (group-link.js). Null until the hub's row for the group is in: the handle
+ // is its name and its owner's, and the node knows neither.
+ const linkFor = useCallback((target) => {
+ if (!group || !group.name || !group.owner_username || !target) return null;
+ return groupItemLink(group, typeof target === 'string' ? target : entryPath(target));
+ }, [group]);
+
const refreshIndex = useCallback(async () => {
const transport = transportRef.current;
if (!transport || !transport.connected) return;
@@ -861,7 +900,7 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs,
entries, availableEntries, nodeDirs, nodeRoots,
setEntries, setNodeDirs, setNodeRoots, applyIndex,
isNodeAdmin, operatorPaired, attachRoot, attachDir, userId, setError, onPreview,
- onRefreshIndex: refreshIndex, onActivity: touchActivity,
+ onRefreshIndex: refreshIndex, onActivity: touchActivity, linkFor,
// Plural everywhere, and built from the registry rather than a list of app
// names kept here: Videos and Music read a list, Photos always did, and an
// application added to `APPS` gets its own entry without this file
@@ -987,7 +1026,8 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs,
</div>
${apps.map(a => tab === a.key && html`
- <${a.Component} key=${a.key + '-' + groupId} ...${commonProps} />
+ <${a.Component} key=${a.key + '-' + groupId} ...${commonProps}
+ ...${a.key === 'files' ? { openDirectory } : {}} />
`)}
${tab === 'settings' && html`
@@ -1029,7 +1069,8 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs,
transportRef=${transportRef}
gekRef=${gekRef}
onClose=${() => setPreviewEntry(null)}
- onDownload=${() => downloadFileForModal(previewEntry)} />
+ onDownload=${() => downloadFileForModal(previewEntry)}
+ onCopyLink=${linkFor(previewEntry) && (() => copyLink(linkFor(previewEntry)))} />
`}
${videoEntry && html`
<${VideoPlayer}
@@ -1037,7 +1078,8 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs,
transportRef=${transportRef}
gekRef=${gekRef}
onClose=${() => setVideoEntry(null)}
- onDownload=${() => downloadFileForModal(videoEntry)} />
+ onDownload=${() => downloadFileForModal(videoEntry)}
+ onCopyLink=${linkFor(videoEntry) && (() => copyLink(linkFor(videoEntry)))} />
`}
</div>
`;
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/group-settings.js b/packages/meshbay-hub/src/meshbay_hub/static/group-settings.js
index bde218b..3ffa524 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/group-settings.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/group-settings.js
@@ -22,21 +22,23 @@ export const INVITE_EMAIL_PREF = 'invite_email';
* One component, two modes, because the Create Group wizard and the Settings
* page were drifting apart while showing the same thing:
*
- * mode="live" — a hosted group. Every change is a signed operator op sent
- * over MNP, or the loopback API when the node is on this
- * machine and there is no live connection.
+ * mode="live" — a hosted group. What widens the node's sharing — adding
+ * a directory, its `writable` and `removable` switches — goes
+ * through the loopback API only, so only on the node's own
+ * machine. Removing, ejecting and plugging are signed ops
+ * over MNP, or the loopback API when there is no connection.
* mode="local" — the wizard, before the group exists. Changes are held in
* an array the caller owns; nothing is persisted until the
* group is attached.
*
- * **Both paths matter and neither is optional.** The operator of a node is not
- * necessarily sitting at it: they may be signing in from any browser, and the
- * only thing that reaches their node from there is MNP. An earlier version of
- * this read its roots exclusively from the loopback API, which resolves to
- * "not available" in a browser — so the section rendered for nobody on the
- * web, while the controls it replaced had worked there. `mnpRoots` is the
- * source whenever a connection exists; the loopback list is the fallback for
- * a local node that is not currently connected (a group still scanning, say).
+ * **The list is shown wherever the operator is.** They may be signing in from
+ * any browser, and the only thing that reaches their node from there is MNP.
+ * An earlier version of this read its roots exclusively from the loopback API,
+ * which resolves to "not available" in a browser — so the section rendered for
+ * nobody on the web. `mnpRoots` is the source whenever a connection exists; the
+ * loopback list is the fallback for a local node that is not currently
+ * connected (a group still scanning, say). From a browser the table is read
+ * only where it would widen anything (MNP 6.0).
*
* Props:
* roots — the node's current roots: { name, path, writable,
@@ -75,8 +77,6 @@ function SharedDirectoriesTable({ roots, groupId, transport, signFn,
<p class=${msg.error ? 'error-msg' : 'settings-hint'}
role=${msg.error ? 'alert' : 'status'}
style="margin-top:10px">${msg.text}</p>`;
- const [pathDraft, setPathDraft] = useState('');
- const [addingByPath, setAddingByPath] = useState(false);
// A toggle has to move under the finger, and the answer only comes back
// when the node has signed, written node.toml and pushed the new table.
@@ -115,12 +115,20 @@ function SharedDirectoriesTable({ roots, groupId, transport, signFn,
// left out otherwise, rather than printing a row of blanks.
const hasPaths = displayRoots.some((r) => r.path);
- // Which door a change goes through. MNP first: it is the only one that
- // exists for an operator on the web, and it is signed, which the loopback
- // API is not (it is authorized by being on localhost with the run token).
+ // Which door a change goes through.
+ //
+ // Widening what the node shares — a new directory, `writable`, `removable` —
+ // only through the loopback API, which exists only on the node's own
+ // machine. Over MNP these were signed ops, and a
+ // signature proves that the operator's key signed, not that the operator
+ // meant it: in a browser that key is driven by code the hub serves.
+ //
+ // Narrowing — remove, eject, plug — MNP first, then loopback.
const overMnp = !isLocal && transport && transport.connected;
const overLoopback = !isLocal && !overMnp && nodeAvail;
+ const onNodeMachine = !isLocal && nodeAvail;
const canEdit = isLocal || overMnp || overLoopback;
+ const canWiden = isLocal || onNodeMachine;
// Deliberately no index refresh after a root change.
//
@@ -158,9 +166,8 @@ function SharedDirectoriesTable({ roots, groupId, transport, signFn,
...prev, [rootName]: { ...(prev[rootName] || {}), ...updates },
}));
const ok = await run(async () => {
- if (overMnp) await transport.updateRoot(groupId, rootName, updates, signFn);
- else if (overLoopback) await platform.node.op('updateRoot', { groupId, rootName, updates });
- else throw new Error(t('node.root_no_route'));
+ if (onNodeMachine) await platform.node.op('updateRoot', { groupId, rootName, updates });
+ else throw new Error(t('settings_node.roots_local_only_hint'));
});
// Only a failure clears the patch here; a success waits for the node's
// own table, so the switch never travels backwards on its way forwards.
@@ -169,8 +176,7 @@ function SharedDirectoriesTable({ roots, groupId, transport, signFn,
const next = { ...prev }; delete next[rootName]; return next;
});
}
- }, [isLocal, localRoots, onLocalRootsChange, overMnp, overLoopback,
- transport, groupId, signFn, run]);
+ }, [isLocal, localRoots, onLocalRootsChange, onNodeMachine, groupId, run]);
const doEjectRoot = useCallback((rootName) => run(async () => {
if (overMnp) await transport.ejectRoot(groupId, rootName, signFn);
@@ -203,10 +209,9 @@ function SharedDirectoriesTable({ roots, groupId, transport, signFn,
}, [isLocal, localRoots, onLocalRootsChange, overMnp, overLoopback,
transport, groupId, signFn, run]);
- // Adding a root needs a directory that exists on the *node's* filesystem.
- // With the node on this machine that is a native folder picker; from any
- // other browser the operator has to type the path, because nothing in a web
- // page can browse a remote disk. Both end at the same signed op.
+ // Adding a root: a native folder picker on the node's own machine, and
+ // nothing anywhere else — a path typed into a page is a path a script in the
+ // page could have typed.
const addRootAtPath = useCallback(async (path, name) => {
if (isLocal) {
if ((localRoots || []).some(r => r.path === path)) return true;
@@ -222,16 +227,12 @@ function SharedDirectoriesTable({ roots, groupId, transport, signFn,
}
setIndexProgress(null);
return run(async () => {
- if (overMnp) {
- await transport.addRoot(groupId, path, { name }, signFn);
- } else if (overLoopback) {
- await platform.node.op('addRoot', { groupId, path, name });
- await platform.node.op('reload');
- await platform.watchIndexProgress(groupId, setIndexProgress);
- } else throw new Error(t('node.root_no_route'));
+ if (!onNodeMachine) throw new Error(t('settings_node.roots_local_only_hint'));
+ await platform.node.op('addRoot', { groupId, path, name });
+ await platform.node.op('reload');
+ await platform.watchIndexProgress(groupId, setIndexProgress);
});
- }, [isLocal, localRoots, onLocalRootsChange, overMnp, overLoopback,
- transport, groupId, signFn, run]);
+ }, [isLocal, localRoots, onLocalRootsChange, onNodeMachine, groupId, run]);
const doPickRoot = useCallback(async () => {
const chosen = await platform.rootPicker.choose();
@@ -240,48 +241,23 @@ function SharedDirectoriesTable({ roots, groupId, transport, signFn,
if (ok && !isLocal) say(t('node.root_added'));
}, [addRootAtPath, isLocal]);
- const doAddByPath = useCallback(async () => {
- const path = pathDraft.trim();
- if (!path) return;
- // The name is the node's business — it derives the basename and refuses a
- // duplicate. Sending one guessed from a string typed here would be a
- // second opinion about something already decided in one place.
- const ok = await addRootAtPath(path, '');
- if (ok) { setPathDraft(''); setAddingByPath(false); if (!isLocal) say(t('node.root_added')); }
- }, [pathDraft, addRootAtPath, isLocal]);
-
- const addControls = !canEdit ? '' : html`
- ${platform.rootPicker.available ? html`
- <button class="btn btn-small btn-secondary" style="margin-top:8px"
- disabled=${busy} onClick=${doPickRoot}>
- <${Icon} name="folder-plus" /> ${t('node.add_root')}
- </button>
- ` : addingByPath ? html`
- <div class="sdt-add-row">
- <input class="sdt-add-input" type="text" value=${pathDraft}
- placeholder=${t('node.root_path_placeholder')}
- disabled=${busy}
- onInput=${(e) => setPathDraft(e.target.value)}
- onKeyDown=${(e) => { if (e.key === 'Enter') doAddByPath(); }} />
- <button class="btn btn-small btn-secondary" disabled=${busy || !pathDraft.trim()}
- onClick=${doAddByPath}>${t('node.add_root')}</button>
- <button class="btn btn-small" disabled=${busy}
- onClick=${() => { setAddingByPath(false); setPathDraft(''); }}>
- ${t('settings.cancel')}</button>
- </div>
- <p class="settings-hint">${t('node.root_path_hint')}</p>
- ` : html`
- <button class="btn btn-small btn-secondary" style="margin-top:8px"
- disabled=${busy} onClick=${() => setAddingByPath(true)}>
- <${Icon} name="folder-plus" /> ${t('node.add_root')}
- </button>
- `}
+ const addControls = !canWiden || !platform.rootPicker.available ? '' : html`
+ <button class="btn btn-small btn-secondary" style="margin-top:8px"
+ disabled=${busy} onClick=${doPickRoot}>
+ <${Icon} name="folder-plus" /> ${t('node.add_root')}
+ </button>
`;
+ // Said once, under the table, rather than as a tooltip on each switch: the
+ // switches are not broken, they are somewhere else.
+ const localOnlyHint = canEdit && !canWiden && html`
+ <p class="settings-hint" style="margin-top:8px">
+ ${t('settings_node.roots_local_only_hint')}</p>`;
if (!displayRoots.length) {
return html`
<div class="shared-directories-table">
<p class="settings-hint">${t('settings_node.shared_directories_hint')}</p>
+ ${localOnlyHint}
${addControls}
${message}
</div>
@@ -326,14 +302,15 @@ function SharedDirectoriesTable({ roots, groupId, transport, signFn,
doing the job. */''}
${canEdit && html`
<td class="sdt-col-toggle">
- <${ToggleSwitch} checked=${!!r.writable} disabled=${busy || !!r.ejected}
+ <${ToggleSwitch} checked=${!!r.writable}
+ disabled=${busy || !!r.ejected || !canWiden}
label=${t('node.root_rw')}
onChange=${(v) => doUpdateRoot(r.name, { writable: v })} />
</td>
`}
${canEdit && !isLocal && html`
<td class="sdt-col-toggle">
- <${ToggleSwitch} checked=${!!r.removable} disabled=${busy}
+ <${ToggleSwitch} checked=${!!r.removable} disabled=${busy || !canWiden}
label=${t('node.removable')}
onChange=${(v) => doUpdateRoot(r.name, { removable: v })} />
</td>
@@ -360,6 +337,7 @@ function SharedDirectoriesTable({ roots, groupId, transport, signFn,
`; })}
</tbody>
</table>
+ ${localOnlyHint}
${addControls}
${message}
${indexProgress && indexProgress.scanning && html`
@@ -426,6 +404,9 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef,
// Node loopback state (Electron-only)
const [nodeDetected, setNodeDetected] = useState(false);
+ // A node on this machine is not necessarily the one hosting this group, and
+ // the table's loopback door is only a door to *that* node.
+ const [nodeHostsGroup, setNodeHostsGroup] = useState(false);
const [nodeRoots, setNodeRoots] = useState([]);
const [nodeGroupName, setNodeGroupName] = useState('');
const [nodeBusy, setNodeBusy] = useState(false);
@@ -464,6 +445,7 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef,
const data = await platform.node.op('groups');
const groups = data.groups || [];
const ng = groups.find(g => g.id === groupId);
+ setNodeHostsGroup(Boolean(ng));
if (ng) {
setNodeRoots(ng.roots || []);
setNodeGroupName(ng.name || '');
@@ -801,6 +783,27 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef,
useEffect(() => { loadMembers(); }, [loadMembers]);
+ // Who the node has admitted to this group. The hub counts someone a member
+ // once they accept the invitation; the node, once they present their code.
+ // Until then they are not in the group, and are listed as waiting, to the
+ // owner only. Null when the roster cannot be read: the hub's list is shown.
+ const [admitted, setAdmitted] = useState(null);
+ useEffect(() => {
+ const transport = transportRef.current;
+ if (!connected || !transport || !transport.connected) { setAdmitted(null); return; }
+ let cancelled = false;
+ transport.groupRoster({ fresh: true })
+ .then((roster) => { if (!cancelled) setAdmitted(new Set(roster.byAccount.keys())); })
+ .catch(() => { if (!cancelled) setAdmitted(null); });
+ return () => { cancelled = true; };
+ }, [connected, transportRef, members]);
+ const joined = admitted
+ ? members.filter(m => m.user_id === adminId || admitted.has(m.user_id))
+ : members;
+ const awaitingCode = admitted
+ ? members.filter(m => m.user_id !== adminId && !admitted.has(m.user_id))
+ : [];
+
const ownsGroup = Boolean(group && group.is_admin);
const loadHosts = useCallback(() => {
if (!ownsGroup) return;
@@ -1182,7 +1185,7 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef,
groupId=${groupId}
transport=${transportRef.current}
signFn=${adminSignFn}
- nodeDetected=${nodeDetected}
+ nodeDetected=${nodeDetected && nodeHostsGroup}
onRootsChange=${loadNodeInfo}
onRefreshIndex=${onRefreshIndex} />
</${CollapsibleSection}>
@@ -1358,7 +1361,7 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef,
</${CollapsibleSection}>
`}
- <${CollapsibleSection} title=${`${t('group.tab_members')} (${members.length})`}>
+ <${CollapsibleSection} title=${`${t('group.tab_members')} (${joined.length})`}>
<table class="admin-table">
<thead>
<tr>
@@ -1368,7 +1371,7 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef,
</tr>
</thead>
<tbody>
- ${members.map(m => html`
+ ${joined.map(m => html`
<tr key=${m.user_id}>
<td>${m.username}</td>
<td>
@@ -1390,6 +1393,21 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef,
</td>
</tr>
`)}
+ ${isAdmin && awaitingCode.map(m => html`
+ <tr key=${m.user_id}>
+ <td>${m.username}</td>
+ <td><span class="badge">${t('members.awaiting_code')}</span></td>
+ <td class="admin-actions">
+ <button class="admin-btn danger" disabled=${removing === m.user_id}
+ onClick=${async () => {
+ if (!await ask(t('members.remove_confirm', { user: m.username }))) return;
+ removeMember(m);
+ }}>
+ ${removing === m.user_id ? '...' : t('members.remove')}
+ </button>
+ </td>
+ </tr>
+ `)}
${invited.map(m => html`
<tr key=${m.user_id}>
<td>${m.username}</td>
@@ -1409,7 +1427,7 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef,
`)}
</tbody>
</table>
- ${isAdmin && members.length > 1 && html`
+ ${isAdmin && joined.length > 1 && html`
<p class="settings-hint">${t('members.remove_hint')}</p>
`}
</${CollapsibleSection}>
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app-settings.js b/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app-settings.js
index be26fbc..f033915 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app-settings.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app-settings.js
@@ -1,3 +1,6 @@
+// SPDX-License-Identifier: 0BSD
+// The reference application: copy it to start one of your own, under any licence
+// (licenses/APPLICATION-EXCEPTION.txt).
import { html, useState, useEffect } from './vendor/htm-preact.js';
import { t } from './i18n.js';
import { useSaver } from './settings-ui.js';
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app.js b/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app.js
index 98ca8fa..8781d18 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app.js
@@ -1,3 +1,6 @@
+// SPDX-License-Identifier: 0BSD
+// The reference application: copy it to start one of your own, under any licence
+// (licenses/APPLICATION-EXCEPTION.txt).
import { html, useMemo } from './vendor/htm-preact.js';
import { t } from './i18n.js';
import { Icon } from './icon.js';
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/icon.js b/packages/meshbay-hub/src/meshbay_hub/static/icon.js
index c80258c..4d549f1 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/icon.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/icon.js
@@ -65,6 +65,8 @@ const ICON_PATHS = {
plus: ['M12 5v14', 'M5 12h14'],
refresh: ['M20 11a8 8 0 0 0-15.3-2', 'M4 5v4h4',
'M4 13a8 8 0 0 0 15.3 2', 'M20 19v-4h-4'],
+ link: ['M10 13.5a4.5 4.5 0 0 0 6.4.4l3-3a4.5 4.5 0 0 0-6.4-6.4l-1.6 1.6',
+ 'M14 10.5a4.5 4.5 0 0 0-6.4-.4l-3 3a4.5 4.5 0 0 0 6.4 6.4l1.6-1.6'],
clip: ['M20.5 11.8l-8.4 8.4a5.4 5.4 0 0 1-7.6-7.6l8.8-8.8a3.6 3.6 0 0 1 5.1 5.1l-8.8 8.8a1.8 1.8 0 0 1-2.5-2.5l8.1-8.1'],
pencil: ['M4 20h4l10.5-10.5a2.1 2.1 0 0 0-3-3L5 17v3',
'M14.5 6.5l3 3'],
@@ -73,6 +75,10 @@ const ICON_PATHS = {
'chevron-left': ['M14.5 6l-6 6 6 6'],
'chevron-right': ['M9.5 6l6 6-6 6'],
close: ['M6 6l12 12M18 6L6 18'],
+ // A circle nearly closed, its arrow at the top pointing the way it turns;
+ // the remote writes the seconds inside.
+ skipback: ['M12 4.5a8 8 0 1 1-6.93 4', 'M14.5 2l-2.5 2.5 2.5 2.5'],
+ skipfwd: ['M12 4.5a8 8 0 1 0 6.93 4', 'M9.5 2l2.5 2.5-2.5 2.5'],
chat: ['M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z'],
folder: ['M3.5 6.6a1 1 0 0 1 1-1h4.2l2 2.4h7.8a1 1 0 0 1 1 1v9.4a1 1 0 0 1-1 1h-14a1 1 0 0 1-1-1z'],
'bell-off': ['M18 9a6 6 0 0 0-12 0c0 6-2.5 7.5-2.5 7.5h17S18 15 18 9',
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/index-dock.js b/packages/meshbay-hub/src/meshbay_hub/static/index-dock.js
index 6730e60..6c89eb6 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/index-dock.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/index-dock.js
@@ -51,9 +51,18 @@ function useLoopbackActivity() {
let stopped = false;
let timer = null;
let last = '';
+ // Asked before the first operation and again after any failure: detect()
+ // answers "no node" as a value, where an operation on an absent node is a
+ // rejected IPC call that Electron prints to its terminal on every poll.
+ let present = false;
const poll = async () => {
let delay = IDLE_POLL_MS;
try {
+ if (!present) {
+ const found = await platform.node.detect();
+ if (!found || !found.detected) throw new Error('no node');
+ present = true;
+ }
const data = await platform.node.op('indexStatus');
const next = {};
for (const g of (data && data.groups) || []) next[g.group_id] = fromLoopback(g);
@@ -64,6 +73,7 @@ function useLoopbackActivity() {
if (!stopped && text !== last) { last = text; setLocal(next); }
} catch {
// No node on this machine, or one older than the route.
+ present = false;
if (!stopped && last !== '{}') { last = '{}'; setLocal({}); }
delay = ABSENT_POLL_MS;
}
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js b/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js
index 7bbcac5..edf4df9 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
/**
* MeshBay Browser Key Management — keyderive.js
*
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/licenses/AGPL-3.0.txt b/packages/meshbay-hub/src/meshbay_hub/static/licenses/AGPL-3.0.txt
new file mode 100644
index 0000000..be3f7b2
--- /dev/null
+++ b/packages/meshbay-hub/src/meshbay_hub/static/licenses/AGPL-3.0.txt
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<https://www.gnu.org/licenses/>.
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/licenses/APPLICATION-EXCEPTION.txt b/packages/meshbay-hub/src/meshbay_hub/static/licenses/APPLICATION-EXCEPTION.txt
new file mode 100644
index 0000000..5ab0921
--- /dev/null
+++ b/packages/meshbay-hub/src/meshbay_hub/static/licenses/APPLICATION-EXCEPTION.txt
@@ -0,0 +1,65 @@
+MeshBay interface — additional permission for group applications
+under GNU AGPL version 3, section 7
+==============================================================================
+
+The MeshBay interface is free software under the GNU Affero General Public
+License, version 3 or (at your option) any later version (AGPL-3.0.txt, beside
+this file), with the following additional permission. Its protocol layer, the
+files marked SPDX-License-Identifier: LGPL-3.0-or-later, is under the GNU
+Lesser GPL instead and needs no such permission.
+
+Definitions
+
+ "The Interface" is the MeshBay web interface: the files of
+ packages/meshbay-hub/src/meshbay_hub/static/ that are under the AGPL,
+ wherever they are conveyed — served by a hub, or carried by the desktop or
+ the Android application.
+
+ "The Application Interface" is:
+ 1. the properties the Interface passes to a group application's component
+ and to its settings pane, and the fields of an entry in its application
+ registry (apps.js), as docs/MESHBAY_DESIGN.md sections 9.2 to 9.4
+ describe them;
+ 2. the names exported by these modules of the Interface:
+ i18n.js
+ icon.js
+ file-utils.js
+ settings-ui.js
+ folder-tree.js
+ 3. the CSS class names style.css defines, and the message keys of the
+ catalogues under locales/.
+
+ "An Application" is a module, or a set of modules, that the Interface loads
+ as a group application and that interacts with the Interface only through
+ the Application Interface. It may also use the protocol layer and the
+ third-party files under vendor/, each under its own licence. It contains no
+ part of the Interface itself, copied or modified.
+
+Permission
+
+ As a special exception, the copyright holders of the Interface give you
+ permission to combine an Application with the Interface, and to convey the
+ resulting combination, with the Application under terms of your choice,
+ provided that the Interface itself — including any modification of it, of
+ which registering the Application in apps.js or adding its messages to the
+ catalogues is one — remains under the GNU AGPL with this permission, and
+ that you meet the AGPL's terms for it, section 13 included. An Application
+ does not become a work based on the Interface by using the Application
+ Interface, and conveyed on its own carries no obligation from the
+ Interface's licence.
+
+ This permission covers the Interface only. The hub, the node and the
+ desktop and Android shells keep their licence unchanged: code running there
+ on an Application's behalf is a modification of them.
+
+ If you modify the Interface, you may extend this permission to your version
+ of it, but you are not obliged to do so. If you do not wish to, delete this
+ permission from your version (section 7).
+
+Why: the point of the application store is that people other than MeshBay's
+authors write applications, under the licence they choose — free or not. An
+application runs in the same page as the Interface and calls into it, which
+without this permission would make it a work based on the Interface, under the
+AGPL. The permission is limited to a named, documented surface so that what an
+application may rely on is a deliberate commitment, not whatever happens to be
+importable.
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/licenses/GPL-3.0.txt b/packages/meshbay-hub/src/meshbay_hub/static/licenses/GPL-3.0.txt
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/packages/meshbay-hub/src/meshbay_hub/static/licenses/GPL-3.0.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/licenses/LGPL-3.0.txt b/packages/meshbay-hub/src/meshbay_hub/static/licenses/LGPL-3.0.txt
new file mode 100644
index 0000000..0a04128
--- /dev/null
+++ b/packages/meshbay-hub/src/meshbay_hub/static/licenses/LGPL-3.0.txt
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/de.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/de.js
index c650f75..6e42af9 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/locales/de.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/de.js
@@ -123,6 +123,7 @@ export default {
'welcome.docs_devel': 'Entwicklerdoku',
'welcome.docs_design': 'Architektur',
'welcome.docs_protocol': 'Protokoll',
+ 'welcome.docs_api': 'API',
'welcome.download': 'Herunterladen (Beta)',
'welcome.legal': 'Rechtliche Hinweise',
'register.err_mismatch': 'Die Passwörter stimmen nicht überein',
@@ -209,6 +210,11 @@ export default {
'group.mkdir_prompt': 'Name des neuen Ordners',
'group.mkdir_offline': 'Nicht mit dem Node verbunden.',
'group.download_offline': 'Keine Verbindung zum Node — der Download kann nicht starten. Die Verbindung wird automatisch wiederhergestellt; versuchen Sie es gleich erneut.',
+ 'group.link_unknown': "Dieser Link verweist auf eine Gruppe, in der Sie nicht Mitglied sind, oder die nicht mehr so heißt.",
+ 'group.link_path_unknown': "Unter {path} gibt es in dieser Gruppe nichts — die Datei wurde vielleicht verschoben, umbenannt oder gelöscht.",
+ 'link.copy': "Link kopieren",
+ 'link.copied': "Link kopiert",
+ 'link.copy_failed': "Kopieren nicht möglich — der Link lautet {url}",
'group.download_write_stalled': 'Die Datei wird nicht mehr auf die Festplatte geschrieben ({seconds} s ohne Fortschritt). Der Download wurde abgebrochen statt hängen gelassen; versuchen Sie es erneut.',
'device.add_title': 'This browser is not linked to this node yet',
'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.',
@@ -377,6 +383,8 @@ export default {
'photo.prev': 'Vorherige (←)',
'photo.next': 'Nächste (→)',
'photo.zip_album': 'Album als ZIP herunterladen',
+ 'photo.slideshow': 'Diashow',
+ 'photo.slideshow_stop': 'Diashow beenden',
'photo.zoom_in': 'Vergrößern',
'photo.zoom_out': 'Verkleinern',
'photo.zoom_fit_title': 'An Fenster anpassen',
@@ -390,6 +398,13 @@ export default {
'cast.copied': 'URL kopiert',
'cast.scanning': 'Suche nach Geräten…',
'cast.no_devices': 'Keine Geräte gefunden',
+ 'cast.casting_to': 'Wiedergabe auf',
+ 'cast.seek': 'Position im Film',
+ 'cast.waiting': 'Warten auf den Fernseher…',
+ 'cast.back30': '30 Sekunden zurück',
+ 'cast.fwd30': '30 Sekunden vor',
+ 'cast.play': 'Abspielen',
+ 'cast.pause': 'Pause',
// Settings
'settings.title': 'Einstellungen',
@@ -494,12 +509,11 @@ export default {
'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.',
'firstrun.btn': 'Continue',
'firstrun.checking': 'Checking…',
- 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.',
'device.this_device': 'This device',
'settings.keys_heading': 'Keys on this device',
'settings.hub_heading': 'Hub',
'settings.hub_current': 'Currently',
- 'settings.hub_hint': 'Changing this signs you out and restarts the window.',
+ 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.',
'settings.hub_change': 'Change',
'settings.keys_where': 'Protected by',
'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.',
@@ -956,8 +970,6 @@ export default {
'node.root_no_signing_key': 'Kein Signaturschlüssel verfügbar — koppeln Sie dieses Gerät zuerst mit dem Node',
'node.root_no_route': 'Keine Verbindung zum Node — verbinden Sie sich damit oder verwenden Sie die App auf dem Rechner, der ihn hostet',
'node.root_remove_last': 'Eine Gruppe braucht mindestens ein Verzeichnis',
- 'node.root_path_hint': 'Der Pfad, wie der Node ihn sieht, auf dem Rechner, der diese Gruppe hostet.',
- 'node.root_path_placeholder': '/home/user/Media',
'node.root_path': 'Pfad',
'node.directory': 'Verzeichnis',
'node.root_added': 'Verzeichnis hinzugefügt.',
@@ -1079,6 +1091,7 @@ export default {
'settings_app.tmdb_token_prompt': 'Registrieren Sie sich bei TMDB, um einen eigenen API-Schlüssel zu erzeugen.',
'settings_app.tmdb_token_link': 'Schlüssel holen',
'settings_node.roots_offline_hint': 'Nicht mit dem Node verbunden — Änderungen laufen über den lokalen Node und greifen beim nächsten Neuladen.',
+ 'settings_node.roots_local_only_hint': 'Ein Verzeichnis hinzufügen sowie Lesen/Schreiben oder Wechselmedium umschalten geht nur auf dem Rechner, auf dem der Node läuft — in der Desktop-Anwendung oder mit meshbay-node root.',
'settings_node.directories_title': 'App-Verzeichnisse',
'settings_node.directories_hint': 'Freigegebene Ordner und welchen davon die Videos-, Musik- und Fotos-Apps als eigene(n) Einstiegspunkt(e) nutzen.',
@@ -1229,6 +1242,7 @@ export default {
'home.accept': "Annehmen",
'home.decline': "Ablehnen",
'members.invited': "eingeladen",
+ 'members.awaiting_code': "waiting for their code",
'hosts.title': "Hosts",
'hosts.hint': "Ihre eigenen Nodes stellen diese Gruppe ohne Rückfrage bereit. Ein anderer Node tut es erst, wenn Sie ihn hier genehmigen; ein Node, der anfragt, steht unten.",
'hosts.none': "Kein anderer Node hat angefragt, diese Gruppe bereitzustellen.",
@@ -1251,7 +1265,6 @@ export default {
'settings.browser_access_off_in_browser': 'Der Browserzugang ist für dieses Konto ausgeschaltet. Er wird in der MeshBay-Desktopanwendung eingeschaltet, die diesen Browser auch für sich selbst freigeben kann.',
'group.browser_access_off': 'Der Browserzugang ist für dieses Konto ausgeschaltet. Schalten Sie ihn in der MeshBay-Desktopanwendung (Profil) ein oder geben Sie diesen Browser dort frei.',
// Worded by the desktop main process for its own dialogs (main.js).
- 'native.folder_confirm': 'Den Ordner {path} mit den Mitgliedern einer auf diesem Computer gehosteten Gruppe teilen? Er wurde nicht in der Ordnerauswahl gewählt.',
'native.node_account_confirm': 'Der Node auf diesem Computer ist für {current} eingerichtet. Stattdessen für {next} einrichten? Er stellt dann die Gruppen, die er für {current} hostet, nicht mehr bereit.',
'native.browser_access_confirm': 'Die Anmeldung über einen Browser erlauben? Die Anwendung legt Ihre Identität auf jedem genutzten Node ab, so versiegelt, dass nur Ihre Passphrase zusammen mit Ihrem Hub-Konto sie öffnen kann.',
'native.declined': 'Abgebrochen — nichts wurde geändert.',
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/en.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/en.js
index b4e4adf..f94b438 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/locales/en.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/en.js
@@ -126,6 +126,7 @@ export default {
'welcome.docs_devel': 'Developer docs',
'welcome.docs_design': 'Design',
'welcome.docs_protocol': 'Protocol',
+ 'welcome.docs_api': 'API',
'welcome.download': 'Download (beta)',
'welcome.legal': 'Legal information',
'register.err_mismatch': 'Passwords do not match',
@@ -209,6 +210,11 @@ export default {
'group.mkdir_prompt': 'New folder name',
'group.mkdir_offline': 'Not connected to the node.',
'group.download_offline': 'Not connected to the node — the download cannot start. It reconnects on its own; try again in a moment.',
+ 'group.link_unknown': "This link names a group you are not a member of, or one that no longer goes by that name.",
+ 'group.link_path_unknown': "Nothing at {path} in this group — the file may have been moved, renamed or deleted.",
+ 'link.copy': "Copy link",
+ 'link.copied': "Link copied",
+ 'link.copy_failed': "Could not copy — the link is {url}",
'group.download_write_stalled': 'The file stopped being written to disk ({seconds}s with no progress). The download was stopped rather than left hanging; try it again.',
'device.add_title': 'This browser is not linked to this node yet',
'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.',
@@ -375,6 +381,8 @@ export default {
'photo.prev': 'Previous (←)',
'photo.next': 'Next (→)',
'photo.zip_album': 'Download album as zip',
+ 'photo.slideshow': 'Slideshow',
+ 'photo.slideshow_stop': 'Stop slideshow',
'photo.zoom_in': 'Zoom in',
'photo.zoom_out': 'Zoom out',
'photo.zoom_fit_title': 'Fit to window',
@@ -388,6 +396,13 @@ export default {
'cast.copied': 'URL copied',
'cast.scanning': 'Scanning for devices…',
'cast.no_devices': 'No devices found',
+ 'cast.casting_to': 'Casting to',
+ 'cast.seek': 'Position in the film',
+ 'cast.waiting': 'Waiting for the television…',
+ 'cast.back30': 'Back 30 seconds',
+ 'cast.fwd30': 'Forward 30 seconds',
+ 'cast.play': 'Play',
+ 'cast.pause': 'Pause',
// Settings
'settings.title': 'Settings',
@@ -486,12 +501,11 @@ export default {
'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.',
'firstrun.btn': 'Continue',
'firstrun.checking': 'Checking…',
- 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.',
'device.this_device': 'This device',
'settings.keys_heading': 'Keys on this device',
'settings.hub_heading': 'Hub',
'settings.hub_current': 'Currently',
- 'settings.hub_hint': 'Changing this signs you out and restarts the window.',
+ 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.',
'settings.hub_change': 'Change',
'settings.keys_where': 'Protected by',
'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.',
@@ -778,6 +792,7 @@ export default {
'settings_app.tmdb_token_prompt': 'Sign up on TMDB to generate your own API key.',
'settings_app.tmdb_token_link': 'Get a key',
'settings_node.roots_offline_hint': 'Not connected to the node — changes go through the local node instead, and take effect on its next reload.',
+ 'settings_node.roots_local_only_hint': 'Adding a directory, and switching read-write or removable, are done on the machine running the node — in the desktop application, or with meshbay-node root.',
'settings_node.directories_title': 'App directories',
'settings_node.directories_hint': 'Which shared folders the Videos, Music and Photos apps use as their entry point(s).',
@@ -1030,8 +1045,6 @@ export default {
'node.root_no_signing_key': 'No signing key available — pair this device with the node first',
'node.root_no_route': 'No route to the node — connect to it, or use the app on the machine hosting it',
'node.root_remove_last': 'A group needs at least one directory',
- 'node.root_path_hint': 'The path as the node sees it, on the machine hosting this group.',
- 'node.root_path_placeholder': '/home/user/Media',
'node.root_path': 'Path',
'node.root_added': 'Directory added.',
'node.root_removed': 'Directory removed. Restart recommended to update the index.',
@@ -1210,6 +1223,7 @@ export default {
'home.accept': "Accept",
'home.decline': "Decline",
'members.invited': "invited",
+ 'members.awaiting_code': "waiting for their code",
'hosts.title': "Hosts",
'hosts.hint': "Your own nodes serve this group without asking. Another node serves it only once you approve it here; a node that asks is listed below.",
'hosts.none': "No other node has asked to host this group.",
@@ -1232,7 +1246,6 @@ export default {
'settings.browser_access_off_in_browser': 'Browser access is off for this account. It is turned on in the MeshBay desktop application, which can also approve this browser for itself.',
'group.browser_access_off': 'Browser access is off for this account. Turn it on in the MeshBay desktop application (Profile), or approve this browser from it.',
// Worded by the desktop main process for its own dialogs (main.js).
- 'native.folder_confirm': 'Share the folder {path} with the members of a group hosted on this computer? It was not chosen in the folder picker.',
'native.node_account_confirm': 'The node on this computer is set up for {current}. Set it up for {next} instead? It will stop serving the groups it hosts for {current}.',
'native.browser_access_confirm': 'Allow signing in from a browser? The application will leave your identity on every node you use, sealed so that only your passphrase together with your hub account can open it.',
'native.declined': 'Cancelled — nothing was changed.',
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/es.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/es.js
index 7422b13..6ff8be2 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/locales/es.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/es.js
@@ -122,6 +122,7 @@ export default {
'welcome.docs_devel': 'Docs de desarrollo',
'welcome.docs_design': 'Diseño',
'welcome.docs_protocol': 'Protocolo',
+ 'welcome.docs_api': 'API',
'welcome.download': 'Descargar (beta)',
'welcome.legal': 'Información legal',
'register.err_mismatch': 'Las contraseñas no coinciden',
@@ -207,6 +208,11 @@ export default {
'group.mkdir_prompt': 'Nombre de la nueva carpeta',
'group.mkdir_offline': 'Sin conexión con el nodo.',
'group.download_offline': 'Sin conexión con el nodo — la descarga no puede empezar. Se reconecta sola; inténtelo de nuevo en un momento.',
+ 'group.link_unknown': "Este enlace nombra un grupo del que no eres miembro, o que ya no se llama así.",
+ 'group.link_path_unknown': "No hay nada en {path} en este grupo: puede que el archivo se haya movido, renombrado o eliminado.",
+ 'link.copy': "Copiar enlace",
+ 'link.copied': "Enlace copiado",
+ 'link.copy_failed': "No se pudo copiar: el enlace es {url}",
'group.download_write_stalled': 'El archivo dejó de escribirse en el disco ({seconds} s sin avance). La descarga se detuvo en lugar de quedarse colgada; inténtelo de nuevo.',
'device.add_title': 'This browser is not linked to this node yet',
'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.',
@@ -375,6 +381,8 @@ export default {
'photo.prev': 'Anterior (←)',
'photo.next': 'Siguiente (→)',
'photo.zip_album': 'Descargar álbum como zip',
+ 'photo.slideshow': 'Presentación',
+ 'photo.slideshow_stop': 'Detener la presentación',
'photo.zoom_in': 'Acercar',
'photo.zoom_out': 'Alejar',
'photo.zoom_fit_title': 'Ajustar a la ventana',
@@ -388,6 +396,13 @@ export default {
'cast.copied': 'URL copiada',
'cast.scanning': 'Buscando dispositivos…',
'cast.no_devices': 'No se encontraron dispositivos',
+ 'cast.casting_to': 'Transmitiendo a',
+ 'cast.seek': 'Posición en la película',
+ 'cast.waiting': 'Esperando al televisor…',
+ 'cast.back30': 'Retroceder 30 segundos',
+ 'cast.fwd30': 'Avanzar 30 segundos',
+ 'cast.play': 'Reproducir',
+ 'cast.pause': 'Pausa',
// Settings
'settings.title': 'Ajustes',
@@ -490,12 +505,11 @@ export default {
'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.',
'firstrun.btn': 'Continue',
'firstrun.checking': 'Checking…',
- 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.',
'device.this_device': 'This device',
'settings.keys_heading': 'Keys on this device',
'settings.hub_heading': 'Hub',
'settings.hub_current': 'Currently',
- 'settings.hub_hint': 'Changing this signs you out and restarts the window.',
+ 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.',
'settings.hub_change': 'Change',
'settings.keys_where': 'Protected by',
'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.',
@@ -950,8 +964,6 @@ export default {
'node.root_no_signing_key': 'No hay clave de firma disponible: empareja primero este dispositivo con el nodo',
'node.root_no_route': 'No hay ruta al nodo: conéctate a él o usa la aplicación en la máquina que lo aloja',
'node.root_remove_last': 'Un grupo necesita al menos un directorio',
- 'node.root_path_hint': 'La ruta tal como la ve el nodo, en la máquina que aloja este grupo.',
- 'node.root_path_placeholder': '/home/user/Media',
'node.root_path': 'Ruta',
'node.directory': 'Directorio',
'node.root_added': 'Directorio añadido.',
@@ -1073,6 +1085,7 @@ export default {
'settings_app.tmdb_token_prompt': 'Regístrate en TMDB para generar tu propia clave de API.',
'settings_app.tmdb_token_link': 'Obtener una clave',
'settings_node.roots_offline_hint': 'Sin conexión con el nodo: los cambios pasan por el nodo local y se aplican en su próxima recarga.',
+ 'settings_node.roots_local_only_hint': 'Añadir una carpeta y cambiar lectura-escritura o extraíble se hace en la máquina del nodo: en la aplicación de escritorio o con meshbay-node root.',
'settings_node.directories_title': 'Directorios de apps',
'settings_node.directories_hint': 'Carpetas compartidas, y cuál de ellas usan las apps de Vídeos, Música y Fotos como su(s) propio(s) punto(s) de entrada.',
@@ -1223,6 +1236,7 @@ export default {
'home.accept': "Aceptar",
'home.decline': "Rechazar",
'members.invited': "invitado",
+ 'members.awaiting_code': "waiting for their code",
'hosts.title': "Anfitriones",
'hosts.hint': "Sus propios nodes sirven este grupo sin preguntar. Otro node lo sirve solo cuando usted lo aprueba aquí; un node que lo pide aparece abajo.",
'hosts.none': "Ningún otro node ha pedido alojar este grupo.",
@@ -1245,7 +1259,6 @@ export default {
'settings.browser_access_off_in_browser': 'El acceso desde el navegador está desactivado para esta cuenta. Se activa en la aplicación de escritorio de MeshBay, que también puede aprobar este navegador por sí mismo.',
'group.browser_access_off': 'El acceso desde el navegador está desactivado para esta cuenta. Actívelo en la aplicación de escritorio de MeshBay (Perfil) o apruebe este navegador desde ella.',
// Worded by the desktop main process for its own dialogs (main.js).
- 'native.folder_confirm': '¿Compartir la carpeta {path} con los miembros de un grupo alojado en este ordenador? No se eligió en el selector de carpetas.',
'native.node_account_confirm': 'El node de este ordenador está configurado para {current}. ¿Configurarlo para {next} en su lugar? Dejará de servir los grupos que aloja para {current}.',
'native.browser_access_confirm': '¿Permitir el acceso desde un navegador? La aplicación dejará su identidad en cada node que use, sellada de modo que solo su frase de contraseña, junto con su cuenta del hub, pueda abrirla.',
'native.declined': 'Cancelado: no se ha cambiado nada.',
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js
index d7d9228..9132bd2 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js
@@ -122,6 +122,7 @@ export default {
'welcome.docs_devel': 'Docs développeur',
'welcome.docs_design': 'Conception',
'welcome.docs_protocol': 'Protocole',
+ 'welcome.docs_api': 'API',
'welcome.download': 'Télécharger (bêta)',
'welcome.legal': 'Informations légales',
'register.err_mismatch': 'Les mots de passe ne correspondent pas',
@@ -208,6 +209,11 @@ export default {
'group.mkdir_prompt': 'Nom du nouveau dossier',
'group.mkdir_offline': 'Non connecté au nœud.',
'group.download_offline': 'Pas de connexion au node — le téléchargement ne peut pas démarrer. La reconnexion est automatique, réessayez dans un instant.',
+ 'group.link_unknown': "Ce lien désigne un groupe dont vous n'êtes pas membre, ou qui ne porte plus ce nom.",
+ 'group.link_path_unknown': "Rien à l'emplacement {path} dans ce groupe — le fichier a peut-être été déplacé, renommé ou supprimé.",
+ 'link.copy': "Copier le lien",
+ 'link.copied': "Lien copié",
+ 'link.copy_failed': "Copie impossible — le lien est {url}",
'group.download_write_stalled': 'L\'écriture du fichier sur le disque s\'est arrêtée ({seconds} s sans progression). Le téléchargement a été interrompu plutôt que laissé en suspens ; réessayez.',
'device.add_title': 'Ce navigateur n’est pas encore lié à ce nœud',
'device.add_hint': 'Votre compte est connu ici, mais ce navigateur détient une autre clé. Approuvez-le depuis un appareil déjà lié — sans passer par l’opérateur.',
@@ -376,6 +382,8 @@ export default {
'photo.prev': 'Précédent (←)',
'photo.next': 'Suivant (→)',
'photo.zip_album': "Télécharger l'album en zip",
+ 'photo.slideshow': 'Diaporama',
+ 'photo.slideshow_stop': 'Arrêter le diaporama',
'photo.zoom_in': 'Zoomer',
'photo.zoom_out': 'Dézoomer',
'photo.zoom_fit_title': 'Ajuster à la fenêtre',
@@ -389,6 +397,13 @@ export default {
'cast.copied': 'URL copiée',
'cast.scanning': "Recherche d'appareils…",
'cast.no_devices': 'Aucun appareil trouvé',
+ 'cast.casting_to': 'Diffusion sur',
+ 'cast.seek': 'Position dans le film',
+ 'cast.waiting': 'En attente de la télévision…',
+ 'cast.back30': 'Reculer de 30 secondes',
+ 'cast.fwd30': 'Avancer de 30 secondes',
+ 'cast.play': 'Lecture',
+ 'cast.pause': 'Pause',
// Settings
'settings.title': 'Paramètres',
@@ -493,12 +508,11 @@ export default {
'firstrun.hint': 'Un hub détient votre compte et vous met en relation avec les nœuds. Il ne voit ni vos fichiers, ni vos messages, ni vos clés.',
'firstrun.btn': 'Continuer',
'firstrun.checking': 'Vérification…',
- 'firstrun.note': 'Il n’y a volontairement pas de valeur par défaut : cette application ne fait confiance à un hub que pour son API, jamais pour l’interface, qui est livrée avec l’application.',
'device.this_device': 'Cet appareil',
'settings.keys_heading': 'Clés sur cet appareil',
'settings.hub_heading': 'Hub',
'settings.hub_current': 'Actuellement',
- 'settings.hub_hint': 'Changer cette adresse vous déconnecte et redémarre la fenêtre.',
+ 'settings.hub_hint': 'Le hub auquel cette application se connecte. En changer vous déconnecte : votre compte reste sur ce hub.',
'settings.hub_change': 'Changer',
'settings.keys_where': 'Protégées par',
'settings.keys_unprotected': 'Aucun trousseau système ne fonctionne : vos clés sont chiffrées avec une clé qui n’est pas secrète. Quiconque peut lire les fichiers de cette machine peut les lire. Démarrez un trousseau, ou considérez cet appareil comme non fiable.',
@@ -959,8 +973,6 @@ export default {
'node.root_no_signing_key': 'Aucune clé de signature disponible — appairez d\'abord cet appareil avec le nœud',
'node.root_no_route': 'Aucune route vers le nœud — connectez-vous à lui, ou utilisez l\'application sur la machine qui l\'héberge',
'node.root_remove_last': 'Un groupe a besoin d\'au moins un répertoire',
- 'node.root_path_hint': 'Le chemin tel que le nœud le voit, sur la machine qui héberge ce groupe.',
- 'node.root_path_placeholder': '/home/user/Media',
'node.root_path': 'Chemin',
'node.root_added': 'Répertoire ajouté.',
'node.root_remove_confirm': 'Retirer « {name} » de ce groupe ?',
@@ -1091,6 +1103,7 @@ export default {
'settings_app.tmdb_token_prompt': 'Créez un compte TMDB pour générer votre propre clé d\'API.',
'settings_app.tmdb_token_link': 'Obtenir une clé',
'settings_node.roots_offline_hint': 'Non connecté au nœud — les changements passent par le nœud local et prennent effet à son prochain rechargement.',
+ 'settings_node.roots_local_only_hint': 'L\'ajout d\'un dossier et le passage en lecture-écriture ou amovible se font sur la machine du nœud — dans l\'application de bureau, ou avec meshbay-node root.',
'settings_node.directories_title': 'Répertoires des applications',
'settings_node.directories_hint': 'Quel(s) dossier(s) partagés les applications Vidéos, Musique et Photos utilisent comme leur(s) propre(s) point(s) d\'entrée.',
@@ -1238,6 +1251,7 @@ export default {
'home.accept': "Accepter",
'home.decline': "Refuser",
'members.invited': "invité",
+ 'members.awaiting_code': "en attente du code",
'hosts.title': "Hôtes",
'hosts.hint': "Vos propres nodes servent ce groupe sans rien demander. Un autre node ne le sert qu'une fois approuvé ici ; un node qui le demande apparaît ci-dessous.",
'hosts.none': "Aucun autre node n'a demandé à héberger ce groupe.",
@@ -1260,7 +1274,6 @@ export default {
'settings.browser_access_off_in_browser': 'L\'accès depuis un navigateur est désactivé pour ce compte. Il s\'active dans l\'application de bureau MeshBay, qui peut aussi approuver ce navigateur pour lui-même.',
'group.browser_access_off': 'L\'accès depuis un navigateur est désactivé pour ce compte. Activez-le dans l\'application de bureau MeshBay (Profil), ou approuvez ce navigateur depuis celle-ci.',
// Worded by the desktop main process for its own dialogs (main.js).
- 'native.folder_confirm': 'Partager le dossier {path} avec les membres d\'un groupe hébergé sur cet ordinateur ? Il n\'a pas été choisi dans le sélecteur de dossier.',
'native.node_account_confirm': 'Le node de cet ordinateur est configuré pour {current}. Le configurer pour {next} à la place ? Il cessera de servir les groupes qu\'il héberge pour {current}.',
'native.browser_access_confirm': 'Autoriser la connexion depuis un navigateur ? L\'application déposera votre identité sur chaque node que vous utilisez, scellée de sorte que seule votre phrase secrète, avec votre compte sur le hub, puisse l\'ouvrir.',
'native.declined': 'Annulé — rien n\'a été modifié.',
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/it.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/it.js
index 5052378..f3ff714 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/locales/it.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/it.js
@@ -123,6 +123,7 @@ export default {
'welcome.docs_devel': 'Documentazione tecnica',
'welcome.docs_design': 'Architettura',
'welcome.docs_protocol': 'Protocollo',
+ 'welcome.docs_api': 'API',
'welcome.download': 'Scarica (beta)',
'welcome.legal': 'Note legali',
'register.err_mismatch': 'Le password non coincidono',
@@ -208,6 +209,11 @@ export default {
'group.mkdir_prompt': 'Nome della nuova cartella',
'group.mkdir_offline': 'Non connesso al nodo.',
'group.download_offline': 'Nessuna connessione al nodo — il download non può iniziare. La riconnessione è automatica, riprovi tra poco.',
+ 'group.link_unknown': "Questo link indica un gruppo di cui non sei membro, o che non ha più questo nome.",
+ 'group.link_path_unknown': "Non c'è nulla in {path} in questo gruppo: il file potrebbe essere stato spostato, rinominato o eliminato.",
+ 'link.copy': "Copia link",
+ 'link.copied': "Link copiato",
+ 'link.copy_failed': "Impossibile copiare — il link è {url}",
'group.download_write_stalled': 'Il file ha smesso di essere scritto su disco ({seconds} s senza progressi). Il download è stato interrotto invece di restare bloccato; riprovi.',
'device.add_title': 'This browser is not linked to this node yet',
'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.',
@@ -376,6 +382,8 @@ export default {
'photo.prev': 'Precedente (←)',
'photo.next': 'Successiva (→)',
'photo.zip_album': "Scarica l'album come zip",
+ 'photo.slideshow': 'Presentazione',
+ 'photo.slideshow_stop': 'Interrompi la presentazione',
'photo.zoom_in': 'Ingrandisci',
'photo.zoom_out': 'Riduci',
'photo.zoom_fit_title': 'Adatta alla finestra',
@@ -389,6 +397,13 @@ export default {
'cast.copied': 'URL copiato',
'cast.scanning': 'Ricerca dispositivi…',
'cast.no_devices': 'Nessun dispositivo trovato',
+ 'cast.casting_to': 'Trasmissione su',
+ 'cast.seek': 'Posizione nel film',
+ 'cast.waiting': 'In attesa del televisore…',
+ 'cast.back30': 'Indietro di 30 secondi',
+ 'cast.fwd30': 'Avanti di 30 secondi',
+ 'cast.play': 'Riproduci',
+ 'cast.pause': 'Pausa',
// Settings
'settings.title': 'Impostazioni',
@@ -493,12 +508,11 @@ export default {
'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.',
'firstrun.btn': 'Continue',
'firstrun.checking': 'Checking…',
- 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.',
'device.this_device': 'This device',
'settings.keys_heading': 'Keys on this device',
'settings.hub_heading': 'Hub',
'settings.hub_current': 'Currently',
- 'settings.hub_hint': 'Changing this signs you out and restarts the window.',
+ 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.',
'settings.hub_change': 'Change',
'settings.keys_where': 'Protected by',
'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.',
@@ -958,8 +972,6 @@ export default {
'node.root_no_signing_key': 'Nessuna chiave di firma disponibile: associa prima questo dispositivo al nodo',
'node.root_no_route': 'Nessuna via verso il nodo: connettiti a esso oppure usa l\'applicazione sulla macchina che lo ospita',
'node.root_remove_last': 'Un gruppo ha bisogno di almeno una directory',
- 'node.root_path_hint': 'Il percorso come lo vede il nodo, sulla macchina che ospita questo gruppo.',
- 'node.root_path_placeholder': '/home/user/Media',
'node.root_path': 'Percorso',
'node.directory': 'Directory',
'node.root_added': 'Directory aggiunta.',
@@ -1087,6 +1099,7 @@ export default {
'settings_app.tmdb_token_prompt': 'Registrati su TMDB per generare la tua chiave API.',
'settings_app.tmdb_token_link': 'Ottieni una chiave',
'settings_node.roots_offline_hint': 'Non connesso al nodo: le modifiche passano dal nodo locale e hanno effetto al successivo ricaricamento.',
+ 'settings_node.roots_local_only_hint': 'L\'aggiunta di una cartella e il passaggio a lettura-scrittura o rimovibile si fanno sulla macchina del nodo: nell\'applicazione desktop o con meshbay-node root.',
'settings_node.directories_title': 'Directory delle app',
'settings_node.directories_hint': 'Cartelle condivise, e quale di esse le app Video, Musica e Foto usano come proprio/i punto/i di ingresso.',
@@ -1237,6 +1250,7 @@ export default {
'home.accept': "Accetta",
'home.decline': "Rifiuta",
'members.invited': "invitato",
+ 'members.awaiting_code': "waiting for their code",
'hosts.title': "Host",
'hosts.hint': "I tuoi node servono questo gruppo senza chiedere. Un altro node lo serve solo dopo che lo approvi qui; un node che lo chiede compare qui sotto.",
'hosts.none': "Nessun altro node ha chiesto di ospitare questo gruppo.",
@@ -1259,7 +1273,6 @@ export default {
'settings.browser_access_off_in_browser': 'L\'accesso dal browser è disattivato per questo account. Si attiva nell\'applicazione desktop di MeshBay, che può anche approvare questo browser per sé.',
'group.browser_access_off': 'L\'accesso dal browser è disattivato per questo account. Attivalo nell\'applicazione desktop di MeshBay (Profilo) o approva questo browser da lì.',
// Worded by the desktop main process for its own dialogs (main.js).
- 'native.folder_confirm': 'Condividere la cartella {path} con i membri di un gruppo ospitato su questo computer? Non è stata scelta nel selettore di cartelle.',
'native.node_account_confirm': 'Il node di questo computer è configurato per {current}. Configurarlo invece per {next}? Smetterà di servire i gruppi che ospita per {current}.',
'native.browser_access_confirm': 'Consentire l\'accesso da un browser? L\'applicazione lascerà la tua identità su ogni node che usi, sigillata in modo che solo la tua passphrase, insieme al tuo account sull\'hub, possa aprirla.',
'native.declined': 'Annullato: non è stato modificato nulla.',
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/ja.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/ja.js
index 47a968c..0690034 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/locales/ja.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/ja.js
@@ -123,6 +123,7 @@ export default {
'welcome.docs_devel': '開発者向け',
'welcome.docs_design': '設計',
'welcome.docs_protocol': 'プロトコル',
+ 'welcome.docs_api': 'API',
'welcome.download': 'ダウンロード(ベータ版)',
'welcome.legal': '法的情報',
'register.err_mismatch': 'パスワードが一致しません',
@@ -206,6 +207,11 @@ export default {
'group.mkdir_prompt': '新しいフォルダー名',
'group.mkdir_offline': 'ノードに接続していません。',
'group.download_offline': 'ノードに接続していません — ダウンロードを開始できません。再接続は自動で行われます。少し待って再試行してください。',
+ 'group.link_unknown': "このリンクは、あなたがメンバーでないグループ、またはもうその名前ではないグループを指しています。",
+ 'group.link_path_unknown': "このグループの {path} には何もありません。ファイルが移動、名前変更、または削除された可能性があります。",
+ 'link.copy': "リンクをコピー",
+ 'link.copied': "リンクをコピーしました",
+ 'link.copy_failed': "コピーできませんでした。リンク: {url}",
'group.download_write_stalled': 'ファイルのディスクへの書き込みが止まりました({seconds} 秒間進みません)。ぶら下がったままにせず中止しました。もう一度お試しください。',
'device.add_title': 'This browser is not linked to this node yet',
'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.',
@@ -373,6 +379,8 @@ export default {
'photo.prev': '前へ(←)',
'photo.next': '次へ(→)',
'photo.zip_album': 'アルバムをzipでダウンロード',
+ 'photo.slideshow': 'スライドショー',
+ 'photo.slideshow_stop': 'スライドショーを停止',
'photo.zoom_in': '拡大',
'photo.zoom_out': '縮小',
'photo.zoom_fit_title': 'ウィンドウに合わせる',
@@ -386,6 +394,13 @@ export default {
'cast.copied': 'URLをコピーしました',
'cast.scanning': 'デバイスを検索中…',
'cast.no_devices': 'デバイスが見つかりません',
+ 'cast.casting_to': 'キャスト先',
+ 'cast.seek': '再生位置',
+ 'cast.waiting': 'テレビを待っています…',
+ 'cast.back30': '30秒戻る',
+ 'cast.fwd30': '30秒進む',
+ 'cast.play': '再生',
+ 'cast.pause': '一時停止',
// Settings
'settings.title': '設定',
@@ -487,12 +502,11 @@ export default {
'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.',
'firstrun.btn': 'Continue',
'firstrun.checking': 'Checking…',
- 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.',
'device.this_device': 'This device',
'settings.keys_heading': 'Keys on this device',
'settings.hub_heading': 'Hub',
'settings.hub_current': 'Currently',
- 'settings.hub_hint': 'Changing this signs you out and restarts the window.',
+ 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.',
'settings.hub_change': 'Change',
'settings.keys_where': 'Protected by',
'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.',
@@ -944,8 +958,6 @@ export default {
'node.root_no_signing_key': '署名鍵がありません — 先にこの端末をノードとペアリングしてください',
'node.root_no_route': 'ノードへの経路がありません — 接続するか、ノードを動かしているマシンでアプリを使ってください',
'node.root_remove_last': 'グループには少なくとも 1 つのディレクトリが必要です',
- 'node.root_path_hint': 'このグループをホストしているマシン上で、ノードから見たパスです。',
- 'node.root_path_placeholder': '/home/user/Media',
'node.root_path': 'パス',
'node.directory': 'ディレクトリ',
'node.root_added': 'ディレクトリを追加しました。',
@@ -1071,6 +1083,7 @@ export default {
'settings_app.tmdb_token_prompt': 'TMDB に登録して、自分の API キーを発行してください。',
'settings_app.tmdb_token_link': 'キーを取得',
'settings_node.roots_offline_hint': 'ノードに接続していません — 変更はローカルノード経由で行われ、次回の再読み込みで反映されます。',
+ 'settings_node.roots_local_only_hint': 'ディレクトリの追加と、読み書き・リムーバブルの切り替えは、ノードが動いているマシンで行います — デスクトップアプリ、または meshbay-node root で。',
'settings_node.directories_title': 'アプリのディレクトリ',
'settings_node.directories_hint': '共有フォルダと、動画・音楽・写真の各アプリがそれぞれの起点として使用するフォルダです。',
@@ -1221,6 +1234,7 @@ export default {
'home.accept': "承諾",
'home.decline': "辞退",
'members.invited': "招待中",
+ 'members.awaiting_code': "waiting for their code",
'hosts.title': "ホスト",
'hosts.hint': "あなた自身の node は確認なしでこのグループを提供します。他の node は、ここで承認した後にのみ提供します。申請した node は下に表示されます。",
'hosts.none': "このグループのホストを申請した node は他にありません。",
@@ -1243,7 +1257,6 @@ export default {
'settings.browser_access_off_in_browser': 'このアカウントではブラウザーからのアクセスがオフです。MeshBay デスクトップアプリでオンにできます。アプリからこのブラウザーだけを承認することもできます。',
'group.browser_access_off': 'このアカウントではブラウザーからのアクセスがオフです。MeshBay デスクトップアプリ(プロフィール)でオンにするか、アプリからこのブラウザーを承認してください。',
// Worded by the desktop main process for its own dialogs (main.js).
- 'native.folder_confirm': 'このコンピューターでホストしているグループのメンバーとフォルダー {path} を共有しますか?このフォルダーはフォルダー選択画面で選ばれたものではありません。',
'native.node_account_confirm': 'このコンピューターの node は {current} 用に設定されています。代わりに {next} 用に設定しますか?{current} のためにホストしているグループは提供されなくなります。',
'native.browser_access_confirm': 'ブラウザーからのサインインを許可しますか?アプリは、利用中のすべての node にあなたの ID を残します。これは、パスフレーズと hub のアカウントの両方がそろった場合にのみ開けるよう封印されます。',
'native.declined': 'キャンセルしました。何も変更されていません。',
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/nl.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/nl.js
index eaad700..ce6312c 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/locales/nl.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/nl.js
@@ -123,6 +123,7 @@ export default {
'welcome.docs_devel': 'Ontwikkelaarsdocs',
'welcome.docs_design': 'Ontwerp',
'welcome.docs_protocol': 'Protocol',
+ 'welcome.docs_api': 'API',
'welcome.download': 'Downloaden (bèta)',
'welcome.legal': 'Juridische informatie',
'register.err_mismatch': 'De wachtwoorden komen niet overeen',
@@ -209,6 +210,11 @@ export default {
'group.mkdir_prompt': 'Naam van de nieuwe map',
'group.mkdir_offline': 'Niet verbonden met de node.',
'group.download_offline': 'Geen verbinding met de node — de download kan niet starten. Er wordt automatisch opnieuw verbonden; probeer het zo weer.',
+ 'group.link_unknown': "Deze link verwijst naar een groep waarvan je geen lid bent, of die niet meer zo heet.",
+ 'group.link_path_unknown': "Er staat niets op {path} in deze groep — het bestand is misschien verplaatst, hernoemd of verwijderd.",
+ 'link.copy': "Link kopiëren",
+ 'link.copied': "Link gekopieerd",
+ 'link.copy_failed': "Kopiëren mislukt — de link is {url}",
'group.download_write_stalled': 'Het bestand wordt niet meer naar schijf geschreven ({seconds} s zonder voortgang). De download is gestopt in plaats van te blijven hangen; probeer het opnieuw.',
'device.add_title': 'This browser is not linked to this node yet',
'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.',
@@ -377,6 +383,8 @@ export default {
'photo.prev': 'Vorige (←)',
'photo.next': 'Volgende (→)',
'photo.zip_album': 'Album downloaden als zip',
+ 'photo.slideshow': 'Diavoorstelling',
+ 'photo.slideshow_stop': 'Diavoorstelling stoppen',
'photo.zoom_in': 'Inzoomen',
'photo.zoom_out': 'Uitzoomen',
'photo.zoom_fit_title': 'Passend maken',
@@ -390,6 +398,13 @@ export default {
'cast.copied': 'URL gekopieerd',
'cast.scanning': 'Apparaten zoeken…',
'cast.no_devices': 'Geen apparaten gevonden',
+ 'cast.casting_to': 'Casten naar',
+ 'cast.seek': 'Positie in de film',
+ 'cast.waiting': 'Wachten op de televisie…',
+ 'cast.back30': '30 seconden terug',
+ 'cast.fwd30': '30 seconden vooruit',
+ 'cast.play': 'Afspelen',
+ 'cast.pause': 'Pauzeren',
// Settings
'settings.title': 'Instellingen',
@@ -494,12 +509,11 @@ export default {
'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.',
'firstrun.btn': 'Continue',
'firstrun.checking': 'Checking…',
- 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.',
'device.this_device': 'This device',
'settings.keys_heading': 'Keys on this device',
'settings.hub_heading': 'Hub',
'settings.hub_current': 'Currently',
- 'settings.hub_hint': 'Changing this signs you out and restarts the window.',
+ 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.',
'settings.hub_change': 'Change',
'settings.keys_where': 'Protected by',
'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.',
@@ -960,8 +974,6 @@ export default {
'node.root_no_signing_key': 'Geen ondertekeningssleutel beschikbaar — koppel dit apparaat eerst aan de node',
'node.root_no_route': 'Geen route naar de node — maak verbinding, of gebruik de app op de machine die hem host',
'node.root_remove_last': 'Een groep heeft minstens één map nodig',
- 'node.root_path_hint': 'Het pad zoals de node het ziet, op de machine die deze groep host.',
- 'node.root_path_placeholder': '/home/user/Media',
'node.root_path': 'Pad',
'node.directory': 'Map',
'node.root_added': 'Map toegevoegd.',
@@ -1089,6 +1101,7 @@ export default {
'settings_app.tmdb_token_prompt': 'Meld u aan bij TMDB om uw eigen API-sleutel te maken.',
'settings_app.tmdb_token_link': 'Sleutel ophalen',
'settings_node.roots_offline_hint': 'Niet verbonden met de node — wijzigingen gaan via de lokale node en worden bij de volgende herlaadbeurt actief.',
+ 'settings_node.roots_local_only_hint': 'Een map toevoegen en lezen-schrijven of verwisselbaar omzetten gebeurt op de machine van de node — in de desktopapplicatie of met meshbay-node root.',
'settings_node.directories_title': 'App-mappen',
'settings_node.directories_hint': 'Gedeelde mappen, en welke daarvan de Video\'s-, Muziek- en Foto\'s-apps als eigen startpunt(en) gebruiken.',
@@ -1239,6 +1252,7 @@ export default {
'home.accept': "Accepteren",
'home.decline': "Weigeren",
'members.invited': "uitgenodigd",
+ 'members.awaiting_code': "waiting for their code",
'hosts.title': "Hosts",
'hosts.hint': "Uw eigen nodes bedienen deze groep zonder te vragen. Een andere node doet dat pas nadat u hem hier goedkeurt; een node die erom vraagt, staat hieronder.",
'hosts.none': "Geen andere node heeft gevraagd deze groep te hosten.",
@@ -1261,7 +1275,6 @@ export default {
'settings.browser_access_off_in_browser': 'Browsertoegang staat uit voor dit account. Die wordt aangezet in de MeshBay-desktoptoepassing, die deze browser ook voor zichzelf kan goedkeuren.',
'group.browser_access_off': 'Browsertoegang staat uit voor dit account. Zet die aan in de MeshBay-desktoptoepassing (Profiel), of keur deze browser daar goed.',
// Worded by the desktop main process for its own dialogs (main.js).
- 'native.folder_confirm': 'De map {path} delen met de leden van een groep die op deze computer wordt gehost? Hij is niet gekozen in de mapkiezer.',
'native.node_account_confirm': 'De node op deze computer is ingesteld voor {current}. In plaats daarvan instellen voor {next}? Hij stopt dan met het aanbieden van de groepen die hij voor {current} host.',
'native.browser_access_confirm': 'Aanmelden vanuit een browser toestaan? De toepassing laat je identiteit achter op elke node die je gebruikt, zo verzegeld dat alleen je wachtzin samen met je hub-account haar kan openen.',
'native.declined': 'Geannuleerd — er is niets gewijzigd.',
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/pl.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/pl.js
index 2635fb0..2737532 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/locales/pl.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/pl.js
@@ -126,6 +126,7 @@ export default {
'welcome.docs_devel': 'Dla programistów',
'welcome.docs_design': 'Architektura',
'welcome.docs_protocol': 'Protokół',
+ 'welcome.docs_api': 'API',
'welcome.download': 'Pobierz (beta)',
'welcome.legal': 'Informacje prawne',
'register.err_mismatch': 'Hasła nie są zgodne',
@@ -212,6 +213,11 @@ export default {
'group.mkdir_prompt': 'Nazwa nowego folderu',
'group.mkdir_offline': 'Brak połączenia z węzłem.',
'group.download_offline': 'Brak połączenia z węzłem — pobieranie nie może się rozpocząć. Połączenie wróci samo; proszę spróbować za chwilę.',
+ 'group.link_unknown': "Ten link wskazuje grupę, do której nie należysz, lub która nie nosi już tej nazwy.",
+ 'group.link_path_unknown': "W tej grupie nie ma niczego pod {path} — plik mógł zostać przeniesiony, zmieniony lub usunięty.",
+ 'link.copy': "Kopiuj link",
+ 'link.copied': "Link skopiowany",
+ 'link.copy_failed': "Nie udało się skopiować — link to {url}",
'group.download_write_stalled': 'Plik przestał być zapisywany na dysk ({seconds} s bez postępu). Pobieranie zostało przerwane, zamiast wisieć w nieskończoność; proszę spróbować ponownie.',
'device.add_title': 'This browser is not linked to this node yet',
'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.',
@@ -388,6 +394,8 @@ export default {
'photo.prev': 'Poprzednie (←)',
'photo.next': 'Następne (→)',
'photo.zip_album': 'Pobierz album jako zip',
+ 'photo.slideshow': 'Pokaz slajdów',
+ 'photo.slideshow_stop': 'Zatrzymaj pokaz slajdów',
'photo.zoom_in': 'Powiększ',
'photo.zoom_out': 'Pomniejsz',
'photo.zoom_fit_title': 'Dopasuj do okna',
@@ -401,6 +409,13 @@ export default {
'cast.copied': 'URL skopiowany',
'cast.scanning': 'Wyszukiwanie urządzeń…',
'cast.no_devices': 'Nie znaleziono urządzeń',
+ 'cast.casting_to': 'Przesyłanie do',
+ 'cast.seek': 'Pozycja w filmie',
+ 'cast.waiting': 'Czekam na telewizor…',
+ 'cast.back30': '30 sekund wstecz',
+ 'cast.fwd30': '30 sekund do przodu',
+ 'cast.play': 'Odtwórz',
+ 'cast.pause': 'Wstrzymaj',
// Settings
'settings.title': 'Ustawienia',
@@ -506,12 +521,11 @@ export default {
'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.',
'firstrun.btn': 'Continue',
'firstrun.checking': 'Checking…',
- 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.',
'device.this_device': 'This device',
'settings.keys_heading': 'Keys on this device',
'settings.hub_heading': 'Hub',
'settings.hub_current': 'Currently',
- 'settings.hub_hint': 'Changing this signs you out and restarts the window.',
+ 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.',
'settings.hub_change': 'Change',
'settings.keys_where': 'Protected by',
'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.',
@@ -982,8 +996,6 @@ export default {
'node.root_no_signing_key': 'Brak klucza podpisu — najpierw sparuj to urządzenie z węzłem',
'node.root_no_route': 'Brak połączenia z węzłem — połącz się z nim albo użyj aplikacji na komputerze, który go hostuje',
'node.root_remove_last': 'Grupa wymaga co najmniej jednego katalogu',
- 'node.root_path_hint': 'Ścieżka widziana przez węzeł, na komputerze hostującym tę grupę.',
- 'node.root_path_placeholder': '/home/user/Media',
'node.root_path': 'Ścieżka',
'node.directory': 'Katalog',
'node.root_added': 'Katalog dodany.',
@@ -1115,6 +1127,7 @@ export default {
'settings_app.tmdb_token_prompt': 'Zarejestruj się w TMDB, aby wygenerować własny klucz API.',
'settings_app.tmdb_token_link': 'Pobierz klucz',
'settings_node.roots_offline_hint': 'Brak połączenia z węzłem — zmiany przechodzą przez węzeł lokalny i zaczną działać po jego następnym przeładowaniu.',
+ 'settings_node.roots_local_only_hint': 'Dodanie katalogu oraz przełączenie odczytu-zapisu lub nośnika wymiennego odbywa się na komputerze węzła — w aplikacji desktopowej lub poleceniem meshbay-node root.',
'settings_node.directories_title': 'Katalogi aplikacji',
'settings_node.directories_hint': 'Katalogi udostępnione oraz to, który z nich aplikacje Wideo, Muzyka i Zdjęcia traktują jako własny punkt (punkty) wejścia.',
@@ -1265,6 +1278,7 @@ export default {
'home.accept': "Akceptuj",
'home.decline': "Odrzuć",
'members.invited': "zaproszony",
+ 'members.awaiting_code': "waiting for their code",
'hosts.title': "Hosty",
'hosts.hint': "Twoje własne node'y obsługują tę grupę bez pytania. Inny node robi to dopiero po Twojej akceptacji tutaj; node, który o to prosi, jest widoczny poniżej.",
'hosts.none': "Żaden inny node nie prosił o hostowanie tej grupy.",
@@ -1287,7 +1301,6 @@ export default {
'settings.browser_access_off_in_browser': 'Dostęp z przeglądarki jest wyłączony dla tego konta. Włącza się go w aplikacji desktopowej MeshBay, która może też zatwierdzić tę przeglądarkę dla niej samej.',
'group.browser_access_off': 'Dostęp z przeglądarki jest wyłączony dla tego konta. Włącz go w aplikacji desktopowej MeshBay (Profil) albo zatwierdź tę przeglądarkę w tej aplikacji.',
// Worded by the desktop main process for its own dialogs (main.js).
- 'native.folder_confirm': 'Udostępnić folder {path} członkom grupy hostowanej na tym komputerze? Nie został wybrany w oknie wyboru folderu.',
'native.node_account_confirm': 'Node na tym komputerze jest skonfigurowany dla {current}. Skonfigurować go zamiast tego dla {next}? Przestanie obsługiwać grupy, które hostuje dla {current}.',
'native.browser_access_confirm': 'Zezwolić na logowanie z przeglądarki? Aplikacja pozostawi Twoją tożsamość na każdym używanym node, zapieczętowaną tak, by otworzyć ją mogło tylko Twoje hasło wraz z kontem na hubie.',
'native.declined': 'Anulowano — nic nie zostało zmienione.',
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/pt-BR.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/pt-BR.js
index 207c1b7..c7cdf01 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/locales/pt-BR.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/pt-BR.js
@@ -124,6 +124,7 @@ export default {
'welcome.docs_devel': 'Docs de desenvolvimento',
'welcome.docs_design': 'Arquitetura',
'welcome.docs_protocol': 'Protocolo',
+ 'welcome.docs_api': 'API',
'welcome.download': 'Baixar (beta)',
'welcome.legal': 'Informações legais',
'register.err_mismatch': 'As senhas não coincidem',
@@ -209,6 +210,11 @@ export default {
'group.mkdir_prompt': 'Nome da nova pasta',
'group.mkdir_offline': 'Sem conexão com o nó.',
'group.download_offline': 'Sem conexão com o nó — o download não pode começar. Ele reconecta sozinho; tente de novo em instantes.',
+ 'group.link_unknown': "Este link aponta para um grupo do qual você não é membro, ou que não tem mais esse nome.",
+ 'group.link_path_unknown': "Não há nada em {path} neste grupo — o arquivo pode ter sido movido, renomeado ou excluído.",
+ 'link.copy': "Copiar link",
+ 'link.copied': "Link copiado",
+ 'link.copy_failed': "Não foi possível copiar — o link é {url}",
'group.download_write_stalled': 'O arquivo parou de ser gravado no disco ({seconds}s sem progresso). O download foi interrompido em vez de ficar travado; tente de novo.',
'device.add_title': 'This browser is not linked to this node yet',
'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.',
@@ -377,6 +383,8 @@ export default {
'photo.prev': 'Anterior (←)',
'photo.next': 'Próxima (→)',
'photo.zip_album': 'Baixar álbum como zip',
+ 'photo.slideshow': 'Apresentação de slides',
+ 'photo.slideshow_stop': 'Parar a apresentação',
'photo.zoom_in': 'Aumentar zoom',
'photo.zoom_out': 'Diminuir zoom',
'photo.zoom_fit_title': 'Ajustar à janela',
@@ -390,6 +398,13 @@ export default {
'cast.copied': 'URL copiada',
'cast.scanning': 'Procurando dispositivos…',
'cast.no_devices': 'Nenhum dispositivo encontrado',
+ 'cast.casting_to': 'Transmitindo para',
+ 'cast.seek': 'Posição no filme',
+ 'cast.waiting': 'Aguardando a TV…',
+ 'cast.back30': 'Voltar 30 segundos',
+ 'cast.fwd30': 'Avançar 30 segundos',
+ 'cast.play': 'Reproduzir',
+ 'cast.pause': 'Pausar',
// Settings
'settings.title': 'Configurações',
@@ -492,12 +507,11 @@ export default {
'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.',
'firstrun.btn': 'Continue',
'firstrun.checking': 'Checking…',
- 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.',
'device.this_device': 'This device',
'settings.keys_heading': 'Keys on this device',
'settings.hub_heading': 'Hub',
'settings.hub_current': 'Currently',
- 'settings.hub_hint': 'Changing this signs you out and restarts the window.',
+ 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.',
'settings.hub_change': 'Change',
'settings.keys_where': 'Protected by',
'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.',
@@ -951,8 +965,6 @@ export default {
'node.root_no_signing_key': 'Nenhuma chave de assinatura disponível — pareie este dispositivo com o nó primeiro',
'node.root_no_route': 'Sem rota até o nó — conecte-se a ele ou use o aplicativo na máquina que o hospeda',
'node.root_remove_last': 'Um grupo precisa de pelo menos um diretório',
- 'node.root_path_hint': 'O caminho como o nó o vê, na máquina que hospeda este grupo.',
- 'node.root_path_placeholder': '/home/user/Media',
'node.root_path': 'Caminho',
'node.directory': 'Diretório',
'node.root_added': 'Diretório adicionado.',
@@ -1074,6 +1086,7 @@ export default {
'settings_app.tmdb_token_prompt': 'Cadastre-se no TMDB para gerar sua própria chave de API.',
'settings_app.tmdb_token_link': 'Obter uma chave',
'settings_node.roots_offline_hint': 'Sem conexão com o nó — as alterações passam pelo nó local e entram em vigor no próximo recarregamento.',
+ 'settings_node.roots_local_only_hint': 'Adicionar uma pasta e alternar leitura-gravação ou removível são feitos na máquina do nó — no aplicativo de desktop ou com meshbay-node root.',
'settings_node.directories_title': 'Diretórios de apps',
'settings_node.directories_hint': 'Pastas compartilhadas, e qual delas os apps Vídeos, Música e Fotos tratam como seu(s) próprio(s) ponto(s) de entrada.',
@@ -1224,6 +1237,7 @@ export default {
'home.accept': "Aceitar",
'home.decline': "Recusar",
'members.invited': "convidado",
+ 'members.awaiting_code': "waiting for their code",
'hosts.title': "Hosts",
'hosts.hint': "Seus próprios nodes servem este grupo sem perguntar. Outro node só o serve depois que você o aprova aqui; um node que pede aparece abaixo.",
'hosts.none': "Nenhum outro node pediu para hospedar este grupo.",
@@ -1246,7 +1260,6 @@ export default {
'settings.browser_access_off_in_browser': 'O acesso pelo navegador está desativado para esta conta. Ele é ativado no aplicativo de desktop do MeshBay, que também pode aprovar este navegador para si.',
'group.browser_access_off': 'O acesso pelo navegador está desativado para esta conta. Ative-o no aplicativo de desktop do MeshBay (Perfil) ou aprove este navegador por ele.',
// Worded by the desktop main process for its own dialogs (main.js).
- 'native.folder_confirm': 'Compartilhar a pasta {path} com os membros de um grupo hospedado neste computador? Ela não foi escolhida no seletor de pastas.',
'native.node_account_confirm': 'O node deste computador está configurado para {current}. Configurá-lo para {next} em vez disso? Ele deixará de servir os grupos que hospeda para {current}.',
'native.browser_access_confirm': 'Permitir o acesso por um navegador? O aplicativo deixará sua identidade em cada node que você usa, selada de forma que apenas sua frase secreta, junto com sua conta no hub, possa abri-la.',
'native.declined': 'Cancelado — nada foi alterado.',
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/zh-CN.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/zh-CN.js
index 3ea8699..06f61ff 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/locales/zh-CN.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/zh-CN.js
@@ -123,6 +123,7 @@ export default {
'welcome.docs_devel': '开发文档',
'welcome.docs_design': '设计',
'welcome.docs_protocol': '协议',
+ 'welcome.docs_api': 'API',
'welcome.download': '下载(测试版)',
'welcome.legal': '法律信息',
'register.err_mismatch': '两次输入的密码不一致',
@@ -205,6 +206,11 @@ export default {
'group.mkdir_prompt': '新文件夹名称',
'group.mkdir_offline': '未连接到节点。',
'group.download_offline': '未连接到节点 — 无法开始下载。连接会自动恢复,请稍后重试。',
+ 'group.link_unknown': "此链接指向一个您不是其成员的群组,或该群组已不再使用此名称。",
+ 'group.link_path_unknown': "此群组中 {path} 处没有内容——文件可能已被移动、重命名或删除。",
+ 'link.copy': "复制链接",
+ 'link.copied': "链接已复制",
+ 'link.copy_failed': "无法复制——链接为 {url}",
'group.download_write_stalled': '文件停止写入磁盘({seconds} 秒无进展)。已中止下载而不是让它一直卡住,请重试。',
'device.add_title': 'This browser is not linked to this node yet',
'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.',
@@ -370,6 +376,8 @@ export default {
'photo.prev': '上一张(←)',
'photo.next': '下一张(→)',
'photo.zip_album': '将相册下载为 zip',
+ 'photo.slideshow': '幻灯片放映',
+ 'photo.slideshow_stop': '停止幻灯片放映',
'photo.zoom_in': '放大',
'photo.zoom_out': '缩小',
'photo.zoom_fit_title': '适应窗口',
@@ -383,6 +391,13 @@ export default {
'cast.copied': '链接已复制',
'cast.scanning': '正在搜索设备…',
'cast.no_devices': '未找到设备',
+ 'cast.casting_to': '投放到',
+ 'cast.seek': '播放位置',
+ 'cast.waiting': '正在等待电视…',
+ 'cast.back30': '后退 30 秒',
+ 'cast.fwd30': '前进 30 秒',
+ 'cast.play': '播放',
+ 'cast.pause': '暂停',
// Settings
'settings.title': '设置',
@@ -481,12 +496,11 @@ export default {
'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.',
'firstrun.btn': 'Continue',
'firstrun.checking': 'Checking…',
- 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.',
'device.this_device': 'This device',
'settings.keys_heading': 'Keys on this device',
'settings.hub_heading': 'Hub',
'settings.hub_current': 'Currently',
- 'settings.hub_hint': 'Changing this signs you out and restarts the window.',
+ 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.',
'settings.hub_change': 'Change',
'settings.keys_where': 'Protected by',
'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.',
@@ -932,8 +946,6 @@ export default {
'node.root_no_signing_key': '没有可用的签名密钥 — 请先将本设备与节点配对',
'node.root_no_route': '无法连接到节点 — 请先连接,或在运行该节点的机器上使用应用',
'node.root_remove_last': '每个群组至少需要一个目录',
- 'node.root_path_hint': '托管该群组的机器上,节点所看到的路径。',
- 'node.root_path_placeholder': '/home/user/Media',
'node.root_path': '路径',
'node.directory': '目录',
'node.root_added': '目录已添加。',
@@ -1059,6 +1071,7 @@ export default {
'settings_app.tmdb_token_prompt': '在 TMDB 注册以生成你自己的 API 密钥。',
'settings_app.tmdb_token_link': '获取密钥',
'settings_node.roots_offline_hint': '未连接到节点 — 变更将通过本地节点进行,并在其下次重新加载时生效。',
+ 'settings_node.roots_local_only_hint': '添加目录以及切换读写或可移除,只能在运行节点的机器上进行 — 在桌面应用中,或使用 meshbay-node root。',
'settings_node.directories_title': '应用目录',
'settings_node.directories_hint': '共享文件夹,以及“视频”“音乐”和“照片”应用各自使用哪个(些)作为入口。',
@@ -1210,6 +1223,7 @@ export default {
'home.accept': "接受",
'home.decline': "拒绝",
'members.invited': "已邀请",
+ 'members.awaiting_code': "waiting for their code",
'hosts.title': "主机",
'hosts.hint': "你自己的 node 无需询问即可提供此群组。其他 node 只有在你于此处批准后才会提供;提出申请的 node 列在下方。",
'hosts.none': "没有其他 node 申请托管此群组。",
@@ -1232,7 +1246,6 @@ export default {
'settings.browser_access_off_in_browser': '此账户已关闭浏览器访问。可在 MeshBay 桌面应用中开启,该应用也可以单独批准此浏览器。',
'group.browser_access_off': '此账户已关闭浏览器访问。请在 MeshBay 桌面应用(个人资料)中开启,或从该应用批准此浏览器。',
// Worded by the desktop main process for its own dialogs (main.js).
- 'native.folder_confirm': '与这台电脑上托管的群组成员共享文件夹 {path}?该文件夹不是在文件夹选择器中选择的。',
'native.node_account_confirm': '这台电脑上的 node 已为 {current} 设置。改为为 {next} 设置吗?它将不再为 {current} 提供其托管的群组。',
'native.browser_access_confirm': '允许从浏览器登录吗?应用会在您使用的每个 node 上留下您的身份,并加以封存,只有您的密码短语配合您的 hub 账户才能打开。',
'native.declined': '已取消,未做任何更改。',
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/music-app.js b/packages/meshbay-hub/src/meshbay_hub/static/music-app.js
index 67be344..9adb1e1 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/music-app.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/music-app.js
@@ -10,6 +10,8 @@ import { usePager, Pager, pageSizeFrom } from './pager.js';
import { Menu, MenuDots, useMenu } from './menu.js';
import { PlaylistMenuButton, NameModal, usePlaylists } from './playlist-menu.js';
import * as P from './playlists.js';
+import { CastButton } from './cast-session.js';
+import { copyLink } from './copy-link.js';
// -- Music --------------------------------------------------------------------
//
@@ -563,7 +565,7 @@ function FlatList({ items, onPlayQueue, onMenu }) {
function MusicApp({
groupId, transportRef, gekRef, status, entries, availableEntries,
musicDirectories, musicbrainzConfig, onPlayQueue, userId,
- hideFilter, userPrefs, pageResetKey,
+ hideFilter, userPrefs, pageResetKey, linkFor,
}) {
const [mode, setMode] = useState(loadViewMode);
const [filter, setFilter] = useState('');
@@ -617,6 +619,9 @@ function MusicApp({
// argument slot for one.
const onMenu = useCallback((e, tracks, startIndex) => {
if (!tracks || !tracks.length) return;
+ // One track's menu — a row's, whose dots are how a phone opens it. An
+ // album's carries all its tracks and gets no link: Files has the folder's.
+ const link = tracks.length === 1 && linkFor ? linkFor(tracks[0]) : null;
openAt(e, [
{ label: t('music.menu_play'), icon: 'play',
onSelect: () => onPlayQueue(tracks, startIndex || 0) },
@@ -649,8 +654,10 @@ function MusicApp({
},
],
},
+ ...(link ? [{ divider: true },
+ { label: t('link.copy'), icon: 'link', onSelect: () => copyLink(link) }] : []),
]);
- }, [openAt, onPlayQueue, playlists, addToPlaylist]);
+ }, [openAt, onPlayQueue, playlists, addToPlaylist, linkFor]);
useEffect(() => { setMode(loadViewMode()); }, [groupId]);
useEffect(() => { setFilter(''); }, [groupId]);
@@ -747,6 +754,8 @@ function MusicApp({
lists=${playlists} reload=${reloadPlaylists}
onPlayQueue=${onPlayQueue} onSync=${syncNow} />`}
<${Pager} pager=${pager} />
+ ${/* The television the music bar plays to (cast-session.js). */''}
+ <${CastButton} />
${!hideFilter && html`<div class="tb-search">
<${Icon} name="search" />
<input type="text" placeholder="${t('group.filter')}"
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/music-player.js b/packages/meshbay-hub/src/meshbay_hub/static/music-player.js
index e8124fa..4587990 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/music-player.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/music-player.js
@@ -6,6 +6,8 @@ import { t } from './i18n.js';
import { Icon } from './icon.js';
import { useStickyBand } from './sticky.js';
import { CHUNK_SIZE, pipelinedDownload } from './file-utils.js';
+import { playback, cast as castBridge } from './platform.js';
+import { castSession, useCastDevice, loadFile, CastButton } from './cast-session.js';
/**
* The Music app's persistent player bar (docs/MESHBAY_DESIGN.md §9.8).
@@ -29,6 +31,14 @@ import { CHUNK_SIZE, pipelinedDownload } from './file-utils.js';
* through `transport.requestAudioTranscode` first — a node-side,
* cached-after-once AAC/M4A conversion — before the same download/blob path
* runs.
+ *
+ * With a television chosen (cast-session.js), the same decrypted track is
+ * handed to the cast relay instead of the <audio> element, with its cover,
+ * and the bar becomes the receiver's remote: its play, pause, seek, previous
+ * and next drive the television, its clock is the television's, and the end
+ * of a track there moves the queue on as `ended` does here (docs/MESHBAY_DESIGN.md
+ * §11.4). The element keeps the track's source for its duration, and never
+ * plays while casting.
*/
const MIME_BY_EXT = {
@@ -217,6 +227,13 @@ function MusicPlayerBar({ getConnection, queue, onClose, userPrefs, onSaveQueue
// one of them being off is a property of that group rather than of each of
// its tracks in turn — see advancePastFailure below (docs/playlists.md §11.3).
const downGroupsRef = useRef(new Set());
+ // When the page last came back from hidden. A phone with its screen off
+ // drops every connection at once, so a track that fails for lack of one
+ // while the page sleeps, or just after it wakes, says nothing about its
+ // group: it is retried rather than skipped (see the load effect below).
+ const wokeAtRef = useRef(0);
+ const [retryNonce, setRetryNonce] = useState(0);
+ const WAKE_GRACE_MS = 30000;
const currentTrack = tracks[order[pos]] || null;
@@ -272,6 +289,23 @@ function MusicPlayerBar({ getConnection, queue, onClose, userPrefs, onSaveQueue
for (const { url } of blobCacheRef.current.values()) URL.revokeObjectURL(url);
}, []);
+ // Held for as long as a track plays or loads: without it a phone freezes the
+ // page a minute after the screen goes off, and the next track never loads.
+ // Let go a few seconds late, because skipping a track that failed passes
+ // through "not playing", and Android refuses to take the hold back from the
+ // background: a playlist would stop at its first bad file.
+ const keepAliveRef = useRef({ held: false, timer: null });
+ const active = playing || loading;
+ useEffect(() => {
+ const k = keepAliveRef.current;
+ if (!active) return;
+ clearTimeout(k.timer);
+ if (!k.held) { k.held = true; playback.keepAlive(true); }
+ return () => {
+ k.timer = setTimeout(() => { k.held = false; playback.keepAlive(false); }, 5000);
+ };
+ }, [active]);
+
// Screen Wake Lock, opt-in only (Settings → music_keep_screen_on) and only
// while a track is actually playing — off by default because the ordinary
// expectation, matching Spotify/Deezer, is that the phone locks on its own
@@ -326,6 +360,64 @@ function MusicPlayerBar({ getConnection, queue, onClose, userPrefs, onSaveQueue
}
}, []);
+ // ── Casting ──────────────────────────────────────────────────────────────
+ const castDevice = useCastDevice();
+ const remote = Boolean(castDevice) && castSession.canSendFiles;
+ const remoteRef = useRef(remote);
+ // Which track the television was last given, where it was when last
+ // polled, and which track's end has already moved the queue on: the
+ // receiver keeps reporting FINISHED until it is given something else.
+ const remoteTrackRef = useRef(null);
+ const remotePosRef = useRef(null);
+ const finishedRef = useRef(null);
+ // True while a track is on its way to the television: the receiver's
+ // status still describes the previous one until it lands.
+ const sendingRef = useRef(false);
+
+ // The track's cover, for the television to show beside it — found as the
+ // album card finds it (music-app.js): this track's own, else another queued
+ // track of the same album that carries one, else the cover the node found
+ // for the album. The node answers that last question from its cache, and
+ // asks MusicBrainz only where the group has it on and the track is tagged.
+ // A cover that cannot be had is no reason not to play the track.
+ const fetchCover = useCallback(async (entry) => {
+ try {
+ const { transport, gek } = await getConnection(entry.groupId);
+ if (!transport || !transport.connected) return null;
+ const sibling = entry.album && tracks.find((tr) => tr.thumb_hash
+ && tr.groupId === entry.groupId && tr.album === entry.album && tr.artist === entry.artist);
+ let hash = entry.thumb_hash || (sibling && sibling.thumb_hash) || null;
+ if (!hash && transport.fetchMusicMeta) {
+ const meta = await transport.fetchMusicMeta(entry.id).catch(() => null);
+ hash = (meta && meta.cover_thumb_hash) || null;
+ }
+ if (!hash) return null;
+ const chunks = await pipelinedDownload(transport, gek, hash, 1);
+ return { bytes: new Uint8Array(await new Blob(chunks).arrayBuffer()), type: 'image/jpeg' };
+ } catch {
+ return null;
+ }
+ }, [getConnection, tracks]);
+
+ const sendToTv = useCallback(async (entry, startAt = 0) => {
+ const cached = blobCacheRef.current.get(entry.id);
+ if (!cached) throw new Error(t('music.err_playback'));
+ sendingRef.current = true;
+ try {
+ const cover = await fetchCover(entry);
+ remoteTrackRef.current = entry.id;
+ remotePosRef.current = startAt;
+ finishedRef.current = null;
+ await loadFile({
+ owner: 'music', startAt,
+ bytes: new Uint8Array(await cached.blob.arrayBuffer()), type: cached.mime, cover,
+ title: entry.display_title || entry.name, artist: entry.artist || '', album: entry.album || '',
+ });
+ } finally {
+ sendingRef.current = false;
+ }
+ }, [fetchCover]);
+
const fetchTrackBlob = useCallback(async (entry) => {
const cached = blobCacheRef.current.get(entry.id);
if (cached) return cached.url;
@@ -345,7 +437,11 @@ function MusicPlayerBar({ getConnection, queue, onClose, userPrefs, onSaveQueue
}
if (!transport) throw groupDown();
if (!transport.connected) await transport.waitForReconnect();
- if (!transport.connected) throw groupDown();
+ if (!transport.connected) {
+ const e = groupDown();
+ e.transport = transport;
+ throw e;
+ }
let downloadId = entry.id;
let downloadSize = entry.size;
@@ -366,7 +462,8 @@ function MusicPlayerBar({ getConnection, queue, onClose, userPrefs, onSaveQueue
const chunks = await pipelinedDownload(transport, gek, downloadId, totalChunks);
const blob = new Blob(chunks, { type: mime });
const url = URL.createObjectURL(blob);
- blobCacheRef.current.set(entry.id, { url, order: blobInsertRef.current++ });
+ // The blob itself too: a cast hands its bytes to the relay.
+ blobCacheRef.current.set(entry.id, { url, blob, mime, order: blobInsertRef.current++ });
evictOldBlobs();
return url;
}, [getConnection, evictOldBlobs]);
@@ -441,8 +538,46 @@ function MusicPlayerBar({ getConnection, queue, onClose, userPrefs, onSaveQueue
// effect above (pos/order/tracks all just changed together) and also
// after skipNext/skipPrev/onEnded update `pos` alone.
useEffect(() => {
+ const onVisibility = () => {
+ if (document.visibilityState === 'visible') wokeAtRef.current = Date.now();
+ };
+ document.addEventListener('visibilitychange', onVisibility);
+ return () => document.removeEventListener('visibilitychange', onVisibility);
+ }, []);
+
+ const asleepOrJustWoke = () => document.visibilityState === 'hidden'
+ || Date.now() - wokeAtRef.current < WAKE_GRACE_MS;
+
+ // Retries the current track once the page is back and a connection may be:
+ // the screen coming on, the network coming back, or the track's own
+ // transport finishing its reconnect, whichever comes first. A visible page
+ // also retries on a timer, so a failure that outlives the grace window
+ // ends on the ordinary error path instead of a spinner nobody can clear.
+ const retryWhenAwake = (myToken, transport) => {
+ let stop = () => {};
+ let timer = null;
+ const fire = () => {
+ stop();
+ if (loadTokenRef.current === myToken) setRetryNonce((n) => n + 1);
+ };
+ const onVisibility = () => { if (document.visibilityState === 'visible') fire(); };
+ document.addEventListener('visibilitychange', onVisibility);
+ window.addEventListener('online', fire);
+ const unsubscribe = transport ? transport.addReconnectListener(fire) : () => {};
+ if (document.visibilityState === 'visible') timer = setTimeout(fire, 10000);
+ stop = () => {
+ clearTimeout(timer);
+ document.removeEventListener('visibilitychange', onVisibility);
+ window.removeEventListener('online', fire);
+ unsubscribe();
+ };
+ if (transport && transport.connected) fire();
+ };
+
+ useEffect(() => {
if (!currentTrack) return;
const myToken = ++loadTokenRef.current;
+ let waiting = false;
setLoading(true);
setError('');
(async () => {
@@ -453,23 +588,53 @@ function MusicPlayerBar({ getConnection, queue, onClose, userPrefs, onSaveQueue
if (!audio) return;
audio.src = url;
audio.currentTime = 0;
+ if (remoteRef.current) {
+ // To the television; the element keeps the source for its duration.
+ audio.pause();
+ setCurrentTime(0);
+ try {
+ await sendToTv(currentTrack, 0);
+ } catch (castErr) {
+ castErr.isCast = true;
+ throw castErr;
+ }
+ if (loadTokenRef.current !== myToken) return;
+ consecutiveFailuresRef.current = 0;
+ setPlaying(true);
+ prefetchNext(pos);
+ return;
+ }
await audio.play();
consecutiveFailuresRef.current = 0;
setPlaying(true);
prefetchNext(pos);
} catch (err) {
if (loadTokenRef.current !== myToken) return;
+ // Autoplay refused (no recent tap): the track is loaded and fine, it
+ // waits for the play button. Not an error, and no reason to skip it.
+ if (err && err.name === 'NotAllowedError') { setPlaying(false); prefetchNext(pos); return; }
+ // The television did not take it: that says nothing about the track,
+ // so the queue stays where it is, with the reason on screen.
+ if (err && err.isCast) { setError(err.message || String(err)); setPlaying(false); return; }
+ if (err && err.isGroupDown && asleepOrJustWoke()) {
+ // Our own connection is what went, not the group: keep the spinner
+ // and this track, and try it again once we are back.
+ waiting = true;
+ setPlaying(false);
+ retryWhenAwake(myToken, err.transport);
+ return;
+ }
setError(err.message || String(err));
setPlaying(false);
// `fetchTrackBlob` throws `err_transport` when no node answered for
// this track's group; anything else is about the file itself.
advancePastFailure(err.isGroupDown ? currentTrack.groupId : null);
} finally {
- if (loadTokenRef.current === myToken) setLoading(false);
+ if (loadTokenRef.current === myToken && !waiting) setLoading(false);
}
})();
// eslint-disable-next-line
- }, [currentTrack && currentTrack.id]);
+ }, [currentTrack && currentTrack.id, retryNonce]);
// Belt and suspenders alongside the catch block above: `.play()` rejecting
// is the common path for a source the browser can't decode at all, but a
@@ -479,6 +644,9 @@ function MusicPlayerBar({ getConnection, queue, onClose, userPrefs, onSaveQueue
// stream). Both paths converge on the same bounded advance, so whichever
// fires first, the queue moves on exactly once.
const handleMediaError = useCallback(() => {
+ // Casting, the element only holds the source for its duration: whether it
+ // could decode it says nothing about what the television is playing.
+ if (remoteRef.current) return;
const audio = audioRef.current;
const mediaError = audio && audio.error;
setError((mediaError && mediaError.message) || t('music.err_playback'));
@@ -505,27 +673,111 @@ function MusicPlayerBar({ getConnection, queue, onClose, userPrefs, onSaveQueue
if (order.length === 0) return;
// A few seconds in: restart the current track, the way most players do,
// rather than always jumping to the previous one.
+ if (remoteRef.current && castSession.owner === 'music' && (remotePosRef.current || 0) > 3) {
+ castBridge.chromecastSeek(0).catch(() => {});
+ remotePosRef.current = 0;
+ setCurrentTime(0);
+ return;
+ }
const audio = audioRef.current;
- if (audio && audio.currentTime > 3) { audio.currentTime = 0; return; }
+ if (!remoteRef.current && audio && audio.currentTime > 3) { audio.currentTime = 0; return; }
if (pos > 0) { skipTo(pos - 1); return; }
if (repeat === 'all') { skipTo(order.length - 1); }
}, [pos, order.length, repeat, skipTo]);
const onEnded = useCallback(() => {
if (repeat === 'one') {
+ if (remoteRef.current && currentTrack) {
+ sendToTv(currentTrack, 0).catch((e) => { setError(e.message || String(e)); setPlaying(false); });
+ return;
+ }
const audio = audioRef.current;
if (audio) { audio.currentTime = 0; audio.play().catch(() => {}); }
return;
}
skipNext();
- }, [repeat, skipNext]);
+ }, [repeat, skipNext, currentTrack, sendToTv]);
+ const onEndedRef = useRef(onEnded);
+ onEndedRef.current = onEnded;
const togglePlaying = useCallback(() => {
+ if (remoteRef.current && currentTrack) {
+ // A film or a photo has the television: playing again gives it back
+ // the track, from where it was.
+ if (castSession.owner !== 'music') {
+ sendToTv(currentTrack, remotePosRef.current || 0)
+ .then(() => { setError(''); setPlaying(true); })
+ .catch((e) => { setError(e.message || String(e)); setPlaying(false); });
+ return;
+ }
+ (playing ? castBridge.chromecastPause() : castBridge.chromecastPlay())
+ .then(() => setPlaying(!playing)).catch(() => {});
+ return;
+ }
const audio = audioRef.current;
if (!audio) return;
if (playing) { audio.pause(); setPlaying(false); }
- else { audio.play().then(() => setPlaying(true)).catch(() => {}); }
- }, [playing]);
+ else { audio.play().then(() => { setError(''); setPlaying(true); }).catch(() => {}); }
+ }, [playing, currentTrack, sendToTv]);
+
+ // A television chosen, or let go, in the middle of a track: the track goes
+ // on from where it was, on the other side.
+ useEffect(() => {
+ const was = remoteRef.current;
+ remoteRef.current = remote;
+ if (was === remote || !currentTrack) return;
+ const audio = audioRef.current;
+ if (remote) {
+ const at = audio ? audio.currentTime : 0;
+ const wasPlaying = playing;
+ if (audio) audio.pause();
+ // Still loading: the load effect sends it once it has it.
+ if (!blobCacheRef.current.has(currentTrack.id)) return;
+ sendToTv(currentTrack, at)
+ .then(async () => {
+ if (!wasPlaying) await castBridge.chromecastPause().catch(() => {});
+ setPlaying(wasPlaying);
+ })
+ .catch((e) => { setError(e.message || String(e)); setPlaying(false); });
+ } else {
+ const at = remotePosRef.current;
+ remoteTrackRef.current = null;
+ if (audio && at != null && isFinite(at)) audio.currentTime = at;
+ if (playing && audio) audio.play().catch(() => setPlaying(false));
+ }
+ // eslint-disable-next-line
+ }, [remote]);
+
+ // The television's clock and state, once a second, for as long as the
+ // track there is ours.
+ useEffect(() => {
+ if (!remote) return undefined;
+ let stopped = false;
+ const tick = async () => {
+ if (sendingRef.current || castSession.owner !== 'music' || !remoteTrackRef.current) return;
+ const s = await castBridge.status().catch(() => null);
+ const c = s && s.chromecast;
+ if (stopped || sendingRef.current || castSession.owner !== 'music' || !c) return;
+ if (!c.connected) { setPlaying(false); return; }
+ if (c.position != null) { remotePosRef.current = c.position; setCurrentTime(c.position); }
+ const state = c.playerState;
+ if (state === 'PLAYING' || state === 'BUFFERING') setPlaying(true);
+ else if (state === 'PAUSED') setPlaying(false);
+ else if (state === 'IDLE' && String(c.idleReason || '').toLowerCase() === 'finished'
+ && finishedRef.current !== remoteTrackRef.current) {
+ finishedRef.current = remoteTrackRef.current;
+ onEndedRef.current();
+ }
+ };
+ const id = setInterval(tick, 1000);
+ tick();
+ // A film or a photo took the television: the track there has stopped.
+ // Not when casting stops altogether — the track then carries on here.
+ const unsubscribe = castSession.subscribe(() => {
+ if (castSession.device && castSession.owner !== 'music') setPlaying(false);
+ });
+ return () => { stopped = true; clearInterval(id); unsubscribe(); };
+ }, [remote]);
// Reshuffling keeps the currently playing track in place — turning shuffle
// on mid-album must not interrupt what's already playing. Which track that
@@ -546,19 +798,36 @@ function MusicPlayerBar({ getConnection, queue, onClose, userPrefs, onSaveQueue
}, []);
const seek = useCallback((e) => {
+ const to = parseFloat(e.target.value);
+ if (remoteRef.current) {
+ if (castSession.owner !== 'music') return;
+ castBridge.chromecastSeek(to).catch(() => {});
+ remotePosRef.current = to;
+ setCurrentTime(to);
+ return;
+ }
const audio = audioRef.current;
- if (audio && isFinite(audio.duration)) audio.currentTime = parseFloat(e.target.value);
+ if (audio && isFinite(audio.duration)) audio.currentTime = to;
}, []);
const handleClose = useCallback(() => {
const audio = audioRef.current;
if (audio) audio.pause();
+ // The television stops with the bar; it stays chosen for what comes next.
+ if (remoteRef.current && castSession.owner === 'music') {
+ castSession.claim(null);
+ castBridge.chromecastDisconnect().catch(() => {});
+ castBridge.stop().catch(() => {});
+ }
if (onClose) onClose();
}, [onClose]);
if (!currentTrack) return null;
const title = currentTrack.display_title || currentTrack.name;
+ // The element's, once it has read the file; the index's until then — and
+ // while casting, a file this device cannot decode still has a length.
+ const shownDuration = (isFinite(duration) && duration > 0) ? duration : (currentTrack.duration || 0);
const repeatLabel = repeat === 'off' ? t('music.player_repeat_off')
: repeat === 'all' ? t('music.player_repeat_all') : t('music.player_repeat_one');
@@ -600,17 +869,18 @@ function MusicPlayerBar({ getConnection, queue, onClose, userPrefs, onSaveQueue
</div>
<div class="music-player-seek">
<span class="music-player-time">${formatTime(currentTime)}</span>
- <input type="range" min="0" max=${duration || 0} step="1" value=${currentTime}
- disabled=${!duration} onInput=${seek} />
- <span class="music-player-time">${formatTime(duration)}</span>
+ <input type="range" min="0" max=${shownDuration} step="1" value=${currentTime}
+ disabled=${!shownDuration} onInput=${seek} />
+ <span class="music-player-time">${formatTime(shownDuration)}</span>
</div>
<div class="music-player-volume">
<${Icon} name="volume" />
<input type="range" min="0" max="1" step="0.05" value=${volume}
- title=${t('music.player_volume')}
+ title=${t('music.player_volume')} disabled=${remote}
onInput=${(e) => setVolume(parseFloat(e.target.value))} />
</div>
<div class="music-player-extra">
+ <${CastButton} cls="music-player-btn" up />
<button class="music-player-btn" title=${t('music.player_queue')} onClick=${() => setShowQueue(true)}>
<${Icon} name="menu" />
</button>
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/note.js b/packages/meshbay-hub/src/meshbay_hub/static/note.js
new file mode 100644
index 0000000..f55c307
--- /dev/null
+++ b/packages/meshbay-hub/src/meshbay_hub/static/note.js
@@ -0,0 +1,24 @@
+/**
+ * A line said once and gone, in the playlists' note (style.css
+ * `.playlist-note`): "Link copied", "2 groups unreachable". Not a dialog —
+ * nothing here is anyone's to dismiss.
+ *
+ * Appended to the body rather than rendered by a view, because the views that
+ * speak include modals and a context menu that has already closed. One note
+ * at a time: a second replaces the first and restarts the clock.
+ */
+
+let _note = null;
+let _timer = null;
+
+export function say(text, ms = 2500) {
+ if (!_note) {
+ _note = document.createElement('div');
+ _note.className = 'playlist-note page-note';
+ _note.setAttribute('role', 'status');
+ }
+ _note.textContent = text;
+ document.body.appendChild(_note);
+ clearTimeout(_timer);
+ _timer = setTimeout(() => { if (_note) _note.remove(); }, ms);
+}
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/photos-app.js b/packages/meshbay-hub/src/meshbay_hub/static/photos-app.js
index 73b8c15..afc815a 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/photos-app.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/photos-app.js
@@ -9,6 +9,9 @@ import {
import { transfers } from './transfers.js';
import { MediaThumb, LazyTile } from './media-tiles.js';
import { SourceTag } from './group-name.js';
+import { CastButton, castSession, useCastDevice, showPhoto } from './cast-session.js';
+import { Menu, useMenu } from './menu.js';
+import { copyLink } from './copy-link.js';
// ── Photos ───────────────────────────────────────────────────────────────────
//
@@ -21,6 +24,8 @@ import { SourceTag } from './group-name.js';
// keyboard arrows, EXIF info when present) and a "zip this album" button
// that reuses Files' own zip mechanism unchanged (file-utils.js's
// downloadDirectory, lifted out of files-app.js for exactly this reuse).
+// With a television chosen (cast-session.js), the photo the lightbox shows
+// is the photo the television shows, and a slideshow pages through both.
function underAnyPhotoRoot(entry, photoRoots) {
const p = entry.path || '';
@@ -115,11 +120,11 @@ function AlbumLanding({ albums, transportRef, gekRef, onOpen }) {
// ── open album: grid of its own photos ──────────────────────────────────────
-function PhotoTile({ entry, transportRef, gekRef, onOpen }) {
+function PhotoTile({ entry, transportRef, gekRef, onOpen, onMenu }) {
const tRef = entry._tRef || transportRef;
const gRef = entry._gRef || gekRef;
return html`
- <div class="photo-tile" onClick=${onOpen}>
+ <div class="photo-tile" onClick=${onOpen} onContextMenu=${onMenu}>
<${MediaThumb} thumbHash=${entry.thumb_hash} alt=${entry.name}
cls="photo-tile-thumb" transportRef=${tRef} gekRef=${gRef}
emptyIcon="image" />
@@ -133,6 +138,10 @@ function PhotoTile({ entry, transportRef, gekRef, onOpen }) {
// _thumbBlobCache — clicking back and forth between two photos decrypts
// each once, not once per visit.
const _fullBlobCache = new Map();
+// The same photos as blobs, for the television: a cast scales the picture
+// itself, and reading it back through its URL would be a fetch the page's
+// content policy has no reason to allow.
+const _fullBlobs = new Map();
// Zoom is only ever meaningful for the lightbox's own full-resolution
// image — nowhere else in the app shows one, so there is nothing to gate
@@ -142,7 +151,11 @@ const ZOOM_STEP = 25;
const ZOOM_MIN = 25;
const ZOOM_MAX = 400;
-function Lightbox({ photos, index, transportRef, gekRef, onClose, onNav }) {
+// How long a slideshow stays on a photo, counted from when it has loaded:
+// a slow node must not skip a photo nobody saw.
+const SLIDESHOW_MS = 5000;
+
+function Lightbox({ photos, index, transportRef, gekRef, onClose, onNav, linkFor }) {
const entry = photos[index];
const tRef = entry._tRef || transportRef;
const gRef = entry._gRef || gekRef;
@@ -155,7 +168,9 @@ function Lightbox({ photos, index, transportRef, gekRef, onClose, onNav }) {
// same way the browser renders the <img> itself.
const [zoomPercent, setZoomPercent] = useState(null);
const [naturalSize, setNaturalSize] = useState(null);
+ const [slideshow, setSlideshow] = useState(false);
const slotRef = useRef(null);
+ const castDevice = useCastDevice();
useEffect(() => {
const cached = _fullBlobCache.get(entry.id);
@@ -171,8 +186,10 @@ function Lightbox({ photos, index, transportRef, gekRef, onClose, onNav }) {
const chunks = await pipelinedDownload(
transport, gRef.current, entry.id, totalChunks);
if (cancelled) return;
- const url = URL.createObjectURL(new Blob(chunks));
+ const blob = new Blob(chunks);
+ const url = URL.createObjectURL(blob);
_fullBlobCache.set(entry.id, url);
+ _fullBlobs.set(entry.id, blob);
setBlobUrl(url);
} catch {
/* leave the placeholder — a transient fetch failure isn't fatal, next/close still work */
@@ -187,6 +204,23 @@ function Lightbox({ photos, index, transportRef, gekRef, onClose, onNav }) {
// level chosen for one picture saying nothing about the next.
useEffect(() => { setZoomPercent(null); setNaturalSize(null); }, [entry.id]);
+ // The television follows the lightbox, from the moment one is chosen.
+ useEffect(() => {
+ const blob = _fullBlobs.get(entry.id);
+ if (castDevice && blobUrl && blob) showPhoto(blob);
+ }, [castDevice, blobUrl, entry.id]);
+
+ // Next photo once this one has been on screen for SLIDESHOW_MS; the last
+ // photo ends the slideshow rather than wrapping round.
+ useEffect(() => {
+ if (!slideshow || !blobUrl) return undefined;
+ const id = setTimeout(() => {
+ if (index < photos.length - 1) onNav(1);
+ else setSlideshow(false);
+ }, SLIDESHOW_MS);
+ return () => clearTimeout(id);
+ }, [slideshow, blobUrl, index, photos.length, onNav]);
+
useEffect(() => {
const onKey = (e) => {
if (e.key === 'Escape') onClose();
@@ -245,6 +279,17 @@ function Lightbox({ photos, index, transportRef, gekRef, onClose, onNav }) {
<button class="photo-icon-btn photo-icon-btn-text ${zoomPercent === 100 ? 'active' : ''}"
disabled=${!blobUrl} onClick=${zoomActual} title=${t('photo.zoom_100')}>100%</button>
</div>
+ <button class="video-close ${slideshow ? 'cast-active' : ''}"
+ disabled=${photos.length < 2}
+ onClick=${() => setSlideshow(!slideshow)}
+ title=${slideshow ? t('photo.slideshow_stop') : t('photo.slideshow')}
+ aria-pressed=${slideshow ? 'true' : 'false'}>
+ <${Icon} name=${slideshow ? 'pause' : 'play'} /></button>
+ <${CastButton} variant="overlay" cls="video-close" />
+ ${linkFor && linkFor(entry) && html`
+ <button class="video-close" onClick=${() => copyLink(linkFor(entry))}
+ title=${t('link.copy')} aria-label=${t('link.copy')}>
+ <${Icon} name="link" /></button>`}
<button class="video-close" onClick=${onClose} title=${t('video.close')}>
<${Icon} name="close" /></button>
</div>
@@ -272,8 +317,16 @@ function Lightbox({ photos, index, transportRef, gekRef, onClose, onNav }) {
`;
}
-function AlbumView({ album, entries, transportRef, gekRef, setError, onBack, readOnly }) {
+function AlbumView({ album, entries, transportRef, gekRef, setError, onBack, readOnly, linkFor }) {
const [lightboxIndex, setLightboxIndex] = useState(null);
+ // Right-click a photo for its link. A tile has no dots to press, so on a
+ // touchscreen the link is in the lightbox's bar instead.
+ const { menu, openAt, close: closeMenu } = useMenu();
+ const onTileMenu = (e, entry) => {
+ const link = linkFor ? linkFor(entry) : null;
+ if (!link) return;
+ openAt(e, [{ label: t('link.copy'), icon: 'link', onSelect: () => copyLink(link) }]);
+ };
const zip = useCallback(async () => {
const transport = transportRef.current;
@@ -300,22 +353,29 @@ function AlbumView({ album, entries, transportRef, gekRef, setError, onBack, rea
${year && html`<span class="photo-album-heading-year">${year}</span>`}
</div>
</div>
- ${!readOnly && html`<button class="photo-icon-btn" onClick=${zip} title=${t('photo.zip_album')}>
- <${Icon} name="archive" cls="photo-icon-btn-icon" /></button>`}
+ <div class="photo-album-actions">
+ ${/* Choosing a television from here shows the album on it: the first
+ photo opens, since nothing is on screen yet to send. */''}
+ <${CastButton} cls="photo-icon-btn" iconCls="photo-icon-btn-icon"
+ onChosen=${() => setLightboxIndex((i) => (i === null ? 0 : i))} />
+ ${!readOnly && html`<button class="photo-icon-btn" onClick=${zip} title=${t('photo.zip_album')}>
+ <${Icon} name="archive" cls="photo-icon-btn-icon" /></button>`}
+ </div>
</div>
<div class="photo-grid">
${album.photos.map((e, i) => html`
<${LazyTile} key=${e.id} cls="photo-tile-slot">
<${PhotoTile} entry=${e} transportRef=${transportRef} gekRef=${gekRef}
- onOpen=${() => setLightboxIndex(i)} />
+ onOpen=${() => setLightboxIndex(i)} onMenu=${(ev) => onTileMenu(ev, e)} />
</${LazyTile}>
`)}
</div>
${lightboxIndex !== null && html`
<${Lightbox} photos=${album.photos} index=${lightboxIndex}
transportRef=${transportRef} gekRef=${gekRef}
- onClose=${() => setLightboxIndex(null)} onNav=${navigate} />
+ onClose=${() => setLightboxIndex(null)} onNav=${navigate} linkFor=${linkFor} />
`}
+ ${menu && html`<${Menu} ...${menu} onClose=${closeMenu} />`}
`;
}
@@ -324,7 +384,7 @@ function AlbumView({ album, entries, transportRef, gekRef, setError, onBack, rea
function PhotosApp({
groupId, transportRef, gekRef, status, entries, availableEntries,
photoDirectories, setError,
- hideFilter, readOnly,
+ hideFilter, readOnly, linkFor,
}) {
const [openDir, setOpenDir] = useState(null);
const [filter, setFilter] = useState('');
@@ -353,17 +413,19 @@ function PhotosApp({
<p class="page-message">${t('photo.no_roots_configured')}</p>
`}
${status === 'connected' && (photoDirectories || []).length > 0 && !openAlbum && html`
- ${/* The filter is the only thing in it, so under `hideFilter` there is
- no toolbar rather than an empty one — an empty band still pins,
- and would hold a strip of the page open under the search field
- for nothing. */
- !hideFilter && html`
+ ${/* The filter and the cast button are all it holds, so with neither —
+ Search hides the filter, a browser cannot cast — there is no
+ toolbar rather than an empty one: an empty band still pins, and
+ would hold a strip of the page open under the search field for
+ nothing. */
+ (!hideFilter || castSession.supported) && html`
<div class="photo-toolbar">
- <div class="tb-search">
+ <${CastButton} />
+ ${!hideFilter && html`<div class="tb-search">
<${Icon} name="search" />
<input type="text" placeholder="${t('group.filter')}"
value=${filter} onInput=${(e) => setFilter(e.target.value)} />
- </div>
+ </div>`}
</div>
`}
${filteredAlbums.length === 0 && html`
@@ -376,7 +438,7 @@ function PhotosApp({
${status === 'connected' && openAlbum && html`
<${AlbumView} album=${openAlbum} entries=${entries}
transportRef=${transportRef} gekRef=${gekRef} setError=${setError}
- onBack=${() => setOpenDir(null)} readOnly=${readOnly} />
+ onBack=${() => setOpenDir(null)} readOnly=${readOnly} linkFor=${linkFor} />
`}
`;
}
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/platform.js b/packages/meshbay-hub/src/meshbay_hub/static/platform.js
index 19f12a6..28817c7 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/platform.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/platform.js
@@ -204,6 +204,16 @@ export const folder = {
async forget() { return bridge && bridge.folder ? bridge.folder.forget() : false; },
};
+/**
+ * Music is playing: the shell keeps what playback needs awake (on a phone, the
+ * page itself with the screen off). A no-op in a browser.
+ */
+export const playback = {
+ keepAlive(on) {
+ if (bridge && bridge.playback) bridge.playback.keepAlive(on).catch(() => {});
+ },
+};
+
/** Pick a directory to add as a group root. Returns { path, name } or null. */
export const rootPicker = {
available: Boolean(bridge && bridge.rootPicker),
@@ -430,6 +440,8 @@ export async function waitForRootsIndexed(groupId, onProgress,
* Absent in a browser, where the relay cannot run: there is no main process
* to bind a server socket in, and a page cannot open one.
*/
+const CAST_POLL_MS = 250;
+
export const cast = {
available: Boolean(bridge && bridge.cast),
async start(opts) {
@@ -448,6 +460,17 @@ export const cast = {
if (!bridge || !bridge.cast || !bridge.cast.subtitle) return null;
return bridge.cast.subtitle(sub);
},
+ // A whole file for the receiver — a photo already scaled to the television,
+ // a music track — as `{ bytes, type, cover?: { bytes, type }, title?,
+ // artist?, album? }`; answers `{ url }` to load. Absent from an older
+ // shell, so callers check `canSendFiles`.
+ get canSendFiles() {
+ return Boolean(bridge && bridge.cast && bridge.cast.file);
+ },
+ async file(f) {
+ if (!this.canSendFiles) return null;
+ return bridge.cast.file(f);
+ },
async finish() {
if (!bridge || !bridge.cast) return false;
return bridge.cast.finish();
@@ -456,9 +479,32 @@ export const cast = {
if (!bridge || !bridge.cast) return null;
return bridge.cast.status();
},
- async discover() {
- if (!bridge || !bridge.cast) return [];
- return bridge.cast.discover();
+ // Lists receivers as they answer rather than at the end of the scan: most
+ // answer within two seconds, and the scan runs on for the ones coming back
+ // from a reset. `onUpdate(devices, scanning)` is called on each poll until
+ // the scan ends; the returned function stops it being called at all.
+ discover(onUpdate) {
+ if (!bridge || !bridge.cast) {
+ onUpdate([], false);
+ return () => {};
+ }
+ let stopped = false;
+ let timer = null;
+ const poll = async () => {
+ const snap = await bridge.cast.devices().catch(() => null);
+ if (stopped) return;
+ if (!snap) {
+ onUpdate([], false);
+ return;
+ }
+ onUpdate(snap.devices, snap.scanning);
+ if (snap.scanning) timer = setTimeout(poll, CAST_POLL_MS);
+ };
+ bridge.cast.scan().then(poll, () => { if (!stopped) onUpdate([], false); });
+ return () => {
+ stopped = true;
+ clearTimeout(timer);
+ };
},
async chromecastConnect(opts) {
if (!bridge || !bridge.cast) return null;
@@ -472,6 +518,28 @@ export const cast = {
if (!bridge || !bridge.cast) return false;
return bridge.cast.chromecastDisconnect();
},
+ // Remote control of the receiver. Absent from an older bridge, so callers
+ // check `canControl` rather than catching a TypeError.
+ get canControl() {
+ return Boolean(bridge && bridge.cast && bridge.cast.chromecastPause && bridge.cast.chromecastPlay);
+ },
+ async chromecastPause() {
+ if (!this.canControl) return null;
+ return bridge.cast.chromecastPause();
+ },
+ async chromecastPlay() {
+ if (!this.canControl) return null;
+ return bridge.cast.chromecastPlay();
+ },
+ // Seeking inside a file the receiver plays (a track); a film seeks by
+ // restarting the relay instead.
+ get canSeek() {
+ return Boolean(bridge && bridge.cast && bridge.cast.chromecastSeek);
+ },
+ async chromecastSeek(seconds) {
+ if (!this.canSeek) return null;
+ return bridge.cast.chromecastSeek(seconds);
+ },
};
/**
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/playlist-crypto.js b/packages/meshbay-hub/src/meshbay_hub/static/playlist-crypto.js
index 6323b96..2a24160 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/playlist-crypto.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/playlist-crypto.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
/**
* Sealing a playlist blob, and opening one.
*
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/profile-page.js b/packages/meshbay-hub/src/meshbay_hub/static/profile-page.js
index 1800d72..aac3c14 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/profile-page.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/profile-page.js
@@ -27,6 +27,8 @@ async function lockedMessage(token) {
export function ProfilePage({ user, onLogout }) {
const [nodeKey, setNodeKey] = useState('');
+ const [hubInput, setHubInput] = useState('');
+ const [hubError, setHubError] = useState('');
const [currentNodeKey, setCurrentNodeKey] = useState(null);
const [nodeKeyStatus, setNodeKeyStatus] = useState('');
const [nodeKeyLoading, setNodeKeyLoading] = useState(false);
@@ -602,6 +604,29 @@ export function ProfilePage({ user, onLogout }) {
</button>
</div>
+ ${platform.isNative && html`
+ <div class="settings-section">
+ <h3 class="settings-heading">${t('settings.hub_heading')}</h3>
+ <div class="settings-row">
+ <span class="settings-label">${t('settings.hub_current')}</span>
+ <span class="settings-value">${platform.hubBase() || '—'}</span>
+ </div>
+ <p class="settings-hint">${t('settings.hub_hint')}</p>
+ <form onSubmit=${async (e) => {
+ e.preventDefault();
+ setHubError('');
+ try {
+ await window.meshbay.setHubBase(hubInput.trim());
+ } catch (err) { setHubError(platform.bridgeMessage(err)); }
+ }} style="display:flex;gap:8px">
+ <input type="text" placeholder=${platform.hubBase()}
+ value=${hubInput} onInput=${e => setHubInput(e.target.value)} />
+ <button class="admin-btn" type="submit">${t('settings.hub_change')}</button>
+ </form>
+ ${hubError && html`<p class="error-msg">${hubError}</p>`}
+ </div>
+ `}
+
<div class="settings-section">
<h3 class="settings-heading">${t('settings.danger')}</h3>
<p class="settings-hint">${t('settings.delete_hint')}</p>
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/search-page.js b/packages/meshbay-hub/src/meshbay_hub/static/search-page.js
index 874b7b0..ae8eac7 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/search-page.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/search-page.js
@@ -13,6 +13,8 @@ import { MusicApp, groupMusicEntries, foldKey } from './music-app.js';
import { PhotosApp, groupPhotoAlbums } from './photos-app.js';
import { VideoPlayer } from './video-player.js';
import { transfers } from './transfers.js';
+import { copyLink, entryPath, groupItemLink } from './copy-link.js';
+import { say } from './note.js';
import { mergeUnitEntries } from './source-merge.js';
import { useStickyBand } from './sticky.js';
import { ConnectionPool, MAX_IN_FLIGHT, MAX_POOL_SIZE } from './connection-pool.js';
@@ -21,6 +23,8 @@ const DEBOUNCE_MS = 200;
const SEARCH_VIDEO_ROOT = '__search__';
const SEARCH_AUDIO_ROOT = '__search__';
const SEARCH_PHOTO_ROOTS = ['__search_photos__'];
+// How long "N groups unreachable" stays up once a search pass is over.
+const UNREACHABLE_NOTE_MS = 5000;
// -- Index fetching -----------------------------------------------------------
@@ -312,13 +316,20 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs })
setProgress({ done: 0, total: groups.length, unreachable: [] });
if (!poolRef.current) return;
- await fetchAllIndexes(
+ const { unreachable } = await fetchAllIndexes(
poolRef.current, groups, token, username, userId,
(p) => { if (!cancelled) setProgress(p); },
(results) => { if (!cancelled) setIndexedGroups(new Map(results)); },
);
- if (!cancelled) setFetching(false);
+ if (cancelled) return;
+ setFetching(false);
+ // Said once the pass is over, for a few seconds, rather than left above
+ // the results: by then nothing more can be done about it here, and a
+ // line that stays is one more thing between the reader and the results.
+ if (unreachable.length) {
+ say(t('search.unreachable', { n: unreachable.length }), UNREACHABLE_NOTE_MS);
+ }
})();
return () => { cancelled = true; };
@@ -514,6 +525,7 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs })
result.push({
...e,
path: SEARCH_VIDEO_ROOT + '/' + e.path,
+ _origPath: e.path,
groupId,
groupName: data.groupName,
groupOwner: data.groupOwner,
@@ -540,6 +552,7 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs })
result.push({
...e,
path: SEARCH_AUDIO_ROOT + '/' + e.path,
+ _origPath: e.path,
groupId,
groupName: data.groupName,
groupOwner: data.groupOwner,
@@ -567,6 +580,7 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs })
result.push({
...e,
path: '__search_photos__/' + e.path,
+ _origPath: e.path,
groupId,
groupName: data.groupName,
groupOwner: data.groupOwner,
@@ -640,6 +654,19 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs })
// No-op setters for FilesPanel
const noop = useCallback(() => {}, []);
+
+ // "Copy link" for a result: its own group's handle and its path there, from
+ // `_origPath` — every view here prefixes `path` to merge groups into one tree.
+ // A merged entry is the source it was resolved to (source-merge.js), so the
+ // link names a group that has the file. A folder is a path in that merged
+ // tree, named by group name alone, which two owners may share: no link.
+ const linkFor = useCallback((target) => {
+ if (!target || typeof target === 'string' || !target.groupName || !target.groupOwner) {
+ return null;
+ }
+ return groupItemLink({ name: target.groupName, owner_username: target.groupOwner },
+ entryPath(target, target._origPath));
+ }, []);
// The search field and its view toggle are this page's equivalent of a
// group's tab bar: the same band, pinned the same way, publishing the same
// property for the toolbar underneath (style.css, "Sticky chrome").
@@ -698,11 +725,6 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs })
</div>
`}
- ${progress.unreachable.length > 0 && html`
- <p class="search-unreachable">
- ${t('search.unreachable', { n: progress.unreachable.length })}
- </p>
- `}
${viewMode === 'files' && hasResults && html`
<${FilesPanel}
@@ -726,6 +748,7 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs })
readOnly=${true}
getTransport=${getTransport}
showRefresh=${true}
+ linkFor=${linkFor}
onRefreshIndex=${() => setRefreshTick((n) => n + 1)} />
`}
@@ -754,7 +777,7 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs })
entries=${musicEntries}
musicDirectories=${[SEARCH_AUDIO_ROOT]}
musicbrainzConfig=${{ enabled: true }}
- onPlayQueue=${handleMusicPlay} userId=${userId}
+ onPlayQueue=${handleMusicPlay} userId=${userId} linkFor=${linkFor}
userPrefs=${userPrefs} pageResetKey=${q}
hideFilter=${true} />
`}
@@ -767,7 +790,7 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs })
status="connected"
entries=${photoEntries}
photoDirectories=${SEARCH_PHOTO_ROOTS}
- setError=${noop}
+ setError=${noop} linkFor=${linkFor}
hideFilter=${true}
readOnly=${true} />
`}
@@ -788,7 +811,8 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs })
transportRef=${modalTransportRef}
gekRef=${modalGekRef}
onClose=${() => setPreviewEntry(null)}
- onDownload=${() => downloadForModal(previewEntry)} />
+ onDownload=${() => downloadForModal(previewEntry)}
+ onCopyLink=${linkFor(previewEntry) && (() => copyLink(linkFor(previewEntry)))} />
`}
${videoEntry && html`
<${VideoPlayer}
@@ -796,7 +820,8 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs })
transportRef=${modalTransportRef}
gekRef=${modalGekRef}
onClose=${() => setVideoEntry(null)}
- onDownload=${() => downloadForModal(videoEntry)} />
+ onDownload=${() => downloadForModal(videoEntry)}
+ onCopyLink=${linkFor(videoEntry) && (() => copyLink(linkFor(videoEntry)))} />
`}
</div>
`;
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/settings-page.js b/packages/meshbay-hub/src/meshbay_hub/static/settings-page.js
index 9a52059..8755556 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/settings-page.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/settings-page.js
@@ -131,8 +131,6 @@ export function SettingsPage({ user, theme, onThemeChange, groups, onPrefsChange
// Changing the hub after the first run. Without this a typo on the first
// screen was permanent: the prompt only appears when no hub is set, so a
// wrong one left editing a JSON file by hand as the only way out.
- const [hubInput, setHubInput] = useState('');
- const [hubError, setHubError] = useState('');
useEffect(() => {
if (!platform.secrets.available) return;
platform.secrets.backend().then(setKeyBackend).catch(() => {});
@@ -287,29 +285,6 @@ export function SettingsPage({ user, theme, onThemeChange, groups, onPrefsChange
<p class="settings-hint">${t('settings.music_keep_screen_on_hint')}</p>
</div>
- ${platform.isNative && html`
- <div class="settings-section">
- <h3 class="settings-heading">${t('settings.hub_heading')}</h3>
- <div class="settings-row">
- <span class="settings-label">${t('settings.hub_current')}</span>
- <span class="settings-value">${platform.hubBase() || '—'}</span>
- </div>
- <p class="settings-hint">${t('settings.hub_hint')}</p>
- <form onSubmit=${async (e) => {
- e.preventDefault();
- setHubError('');
- try {
- await window.meshbay.setHubBase(hubInput.trim());
- } catch (err) { setHubError(platform.bridgeMessage(err)); }
- }} style="display:flex;gap:8px">
- <input type="text" placeholder=${platform.hubBase()}
- value=${hubInput} onInput=${e => setHubInput(e.target.value)} />
- <button class="admin-btn" type="submit">${t('settings.hub_change')}</button>
- </form>
- ${hubError && html`<p class="error-msg">${hubError}</p>`}
- </div>
- `}
-
${keyBackend && html`
<div class="settings-section">
<h3 class="settings-heading">${t('settings.keys_heading')}</h3>
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/style.css b/packages/meshbay-hub/src/meshbay_hub/static/style.css
index fc91596..21d92df 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/style.css
+++ b/packages/meshbay-hub/src/meshbay_hub/static/style.css
@@ -156,10 +156,6 @@ a:hover { text-decoration: underline; }
height: 100%; background: var(--accent);
transition: width 0.3s;
}
-.search-unreachable {
- font-size: 0.8em; color: var(--text-dim); margin-bottom: 8px;
-}
-
.view-toggle {
display: flex; gap: 0; flex-shrink: 0; margin-left: auto;
}
@@ -2043,7 +2039,23 @@ button:disabled { opacity: 0.5; cursor: not-allowed; }
cursor: text; outline: none;
}
.cast-url-input:focus { border-color: rgba(59, 130, 246, 0.6); }
-.cast-wrapper { display: inline-block; }
+.cast-wrapper { display: inline-block; position: relative; }
+.video-close:disabled { opacity: 0.4; cursor: default; }
+.video-close.cast-btn.casting { background: rgba(59, 130, 246, 0.35); }
+.video-close.cast-btn.casting:hover { background: rgba(59, 130, 246, 0.5); }
+.cast-picker-item.cast-menu-current { color: #94a3b8; cursor: default; }
+.cast-picker-item.cast-menu-current:hover { background: none; }
+
+/* The cast button in a page's toolbar (cast-session.js): the same panel as
+ any other menu there, hung under the button rather than at a point. */
+.cast-btn.casting { color: var(--accent); border-color: var(--accent); }
+.ctx-menu.cast-menu { position: absolute; top: calc(100% + 4px); right: 0; z-index: 150; }
+/* From the music bar, at the bottom of the window: the menu opens upward. */
+.cast-menu-up { top: auto !important; bottom: calc(100% + 4px); }
+.ctx-menu-item.cast-menu-current { color: var(--text-dim); cursor: default; }
+.ctx-menu-item.cast-menu-current:hover { background: none; }
+.ctx-menu-item svg { width: 16px; height: 16px; flex-shrink: 0; }
+.photo-album-actions { display: flex; align-items: center; gap: 4px; }
.cast-picker {
position: absolute; top: calc(100% + 4px); right: 0; z-index: 100;
background: rgba(28, 28, 32, 0.97); border: 1px solid rgba(255, 255, 255, 0.14);
@@ -2084,6 +2096,207 @@ button:disabled { opacity: 0.5; cursor: not-allowed; }
outline: none;
}
+/* The player as a remote while a television plays the film. Opaque, over
+ the local picture, which keeps running underneath only to pace the
+ download; the container is given room for it on a portrait phone, where
+ the picture alone would be a strip. */
+.video-container-remote { min-height: min(72vh, 560px); }
+
+.video-remote {
+ --remote-accent: #23b1f0;
+ position: absolute;
+ inset: 0;
+ z-index: 2;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 32px;
+ padding: 24px 20px;
+ border-radius: 12px;
+ background:
+ radial-gradient(120% 70% at 50% 0%, rgba(35, 177, 240, 0.16) 0%, rgba(35, 177, 240, 0) 60%),
+ #0a1224;
+ color: #e2e8f0;
+ overflow: hidden;
+}
+
+.video-remote-head {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 6px;
+ text-align: center;
+ max-width: 100%;
+}
+
+.video-remote-badge {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 64px;
+ height: 64px;
+ margin-bottom: 8px;
+ border-radius: 50%;
+ background: rgba(35, 177, 240, 0.14);
+ box-shadow: 0 0 0 1px rgba(35, 177, 240, 0.35), 0 0 32px rgba(35, 177, 240, 0.25);
+ color: var(--remote-accent);
+ font-size: 30px;
+}
+
+.video-remote-label {
+ font-size: 0.75rem;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ color: #94a3b8;
+}
+
+.video-remote-device {
+ font-size: 1.35rem;
+ font-weight: 600;
+ color: #f8fafc;
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.video-remote-state {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ min-height: 1.2em;
+ font-size: 0.85rem;
+ color: #94a3b8;
+}
+
+.video-remote-track { width: min(100%, 560px); }
+
+.video-remote-times {
+ display: flex;
+ justify-content: space-between;
+ margin-top: 8px;
+ font-size: 0.85rem;
+ font-variant-numeric: tabular-nums;
+ color: #94a3b8;
+}
+
+/* The track is drawn by hand so the part already played is filled: `--pct`
+ is set inline from the position. */
+.video-remote-seek {
+ --pct: 0%;
+ -webkit-appearance: none;
+ appearance: none;
+ display: block;
+ width: 100%;
+ height: 28px;
+ margin: 0;
+ background: transparent;
+ cursor: pointer;
+}
+.video-remote-seek:disabled { cursor: default; opacity: 0.5; }
+.video-remote-seek::-webkit-slider-runnable-track {
+ height: 6px;
+ border-radius: 3px;
+ background: linear-gradient(to right, var(--remote-accent) var(--pct), rgba(148, 163, 184, 0.25) var(--pct));
+}
+.video-remote-seek::-moz-range-track {
+ height: 6px;
+ border-radius: 3px;
+ background: linear-gradient(to right, var(--remote-accent) var(--pct), rgba(148, 163, 184, 0.25) var(--pct));
+}
+.video-remote-seek::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ width: 18px;
+ height: 18px;
+ margin-top: -6px;
+ border: 0;
+ border-radius: 50%;
+ background: #ffffff;
+ box-shadow: 0 0 0 4px rgba(35, 177, 240, 0.35), 0 2px 6px rgba(0, 0, 0, 0.4);
+}
+.video-remote-seek::-moz-range-thumb {
+ width: 18px;
+ height: 18px;
+ border: 0;
+ border-radius: 50%;
+ background: #ffffff;
+ box-shadow: 0 0 0 4px rgba(35, 177, 240, 0.35), 0 2px 6px rgba(0, 0, 0, 0.4);
+}
+
+.video-remote-buttons {
+ display: flex;
+ align-items: center;
+ gap: 36px;
+}
+
+.video-remote-skip,
+.video-remote-main {
+ position: relative;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ border: 0;
+ border-radius: 50%;
+ cursor: pointer;
+ -webkit-tap-highlight-color: transparent;
+ transition: transform 0.1s ease, background-color 0.15s ease;
+}
+.video-remote-skip:active:not(:disabled),
+.video-remote-main:active:not(:disabled) { transform: scale(0.92); }
+.video-remote-skip:disabled,
+.video-remote-main:disabled { opacity: 0.35; cursor: default; }
+
+.video-remote-skip {
+ width: 56px;
+ height: 56px;
+ background: transparent;
+ color: #e2e8f0;
+ font-size: 44px;
+}
+.video-remote-skip:hover:not(:disabled) { background: rgba(148, 163, 184, 0.12); }
+.video-remote-skip .icon { stroke-width: 1.4; }
+.video-remote-skip-n {
+ position: absolute;
+ left: 0;
+ right: 0;
+ top: 50%;
+ transform: translateY(-38%);
+ font-size: 12px;
+ font-weight: 700;
+ text-align: center;
+ pointer-events: none;
+}
+
+.video-remote-main {
+ width: 76px;
+ height: 76px;
+ background: var(--remote-accent);
+ color: #04121f;
+ font-size: 34px;
+ box-shadow: 0 8px 24px rgba(35, 177, 240, 0.35);
+}
+.video-remote-main:hover:not(:disabled) { background: #4cc3f5; }
+.video-remote-main .icon { stroke-width: 2.6; }
+/* The triangle is a closed path: filled, it reads as play at a glance. */
+.video-remote-main.is-paused .icon path { fill: currentColor; }
+.video-remote-main.is-paused .icon { transform: translateX(2px); }
+
+.video-remote-stop {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 10px 20px;
+ border: 1px solid rgba(148, 163, 184, 0.35);
+ border-radius: 999px;
+ background: transparent;
+ color: #cbd5e1;
+ font: inherit;
+ font-size: 0.9rem;
+ cursor: pointer;
+}
+.video-remote-stop:hover { border-color: #fca5a5; color: #fecaca; }
+
/* Where the film was picked up again. Sits over the picture rather than
pushing it down, and clears itself once the viewer is watching. */
.video-container { position: relative; }
@@ -3346,13 +3559,6 @@ h2 .gn-owner, h3 .gn-owner { font-size: 0.55em; }
max-width: 260px; overflow: hidden; text-overflow: ellipsis;
white-space: nowrap;
}
-.sdt-add-row { display: flex; gap: 6px; align-items: center; margin-top: 8px; }
-.sdt-add-input {
- flex: 1 1 auto; min-width: 0; padding: 5px 8px;
- border: 1px solid var(--border); border-radius: 4px;
- background: var(--bg-surface); color: var(--text);
- font-family: inherit; font-size: 0.9em;
-}
.sdt-col-toggle { width: 90px; text-align: center; }
.sdt-col-toggle th { text-align: center; }
.sdt-col-toggle .toggle-switch { justify-content: center; }
@@ -5403,6 +5609,14 @@ h2 .gn-owner, h3 .gn-owner { font-size: 0.55em; }
overflow: hidden;
text-overflow: ellipsis;
}
+/* The same note, said from anywhere (note.js). It can carry a link the
+ clipboard refused, which must be readable whole rather than cut. */
+.page-note.playlist-note {
+ white-space: normal;
+ overflow-wrap: anywhere;
+ border-radius: 12px;
+ text-align: center;
+}
/* A run of single-album artists, pooled into one grid so five of them fill one
row instead of spending five (music-app.js `albumSections`).
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-admin.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-admin.js
index 1a5a4c0..7bc77af 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/transport-admin.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-admin.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
// The operator's side: signed operations (the two-step challenge), the node's
// settings and roots, members and invitations.
//
@@ -241,37 +243,6 @@ extendTransport(class {
// ── Node management (D5) ───────────────────────────────────────────────
- async fetchNodeStatus() {
- const msg = await this._sendAndWait({ type: 'node_status', v: '0.1' });
- if (msg.type === 'error') throw new Error(msg.detail);
- return msg;
- }
-
- async updateNodeSettings(settings) {
- const msg = await this._sendAndWait({
- type: 'node_settings_set', v: '0.1', settings,
- });
- if (msg.type === 'error') throw new Error(msg.detail);
- return msg;
- }
-
- async addRoot(groupId, path, { name, kind, writable, removable } = {}, signFn) {
- const msg = await this._sendAndWait({
- type: 'root_add', v: '1.1',
- group_id: groupId, path,
- name: name || '', kind: kind || 'generic',
- writable: !!writable, removable: !!removable,
- });
- if (msg.type === 'error') throw new Error(msg.detail);
- if (msg.type === 'admin_challenge') {
- // Everything the node will act on is in the subject, `writable` included.
- const subject = window.MeshBayCrypto.rootAddSubject(
- path, name || '', kind || 'generic', !!writable, !!removable);
- return this._authorizeAdminOp(msg, 'root_add', subject, signFn);
- }
- return msg;
- }
-
async removeRoot(groupId, rootName, signFn) {
const msg = await this._sendAndWait({
type: 'root_remove', v: '0.1',
@@ -284,24 +255,6 @@ extendTransport(class {
return msg;
}
- async updateRoot(groupId, rootName, { writable, removable } = {}, signFn) {
- const updates = [];
- if (writable !== undefined) updates.push(`rw=${writable ? 'on' : 'off'}`);
- if (removable !== undefined) updates.push(`rem=${removable ? 'on' : 'off'}`);
- const subject = updates.length ? `${rootName}:${updates.join(',')}` : rootName;
- const msg = await this._sendAndWait({
- type: 'root_update', v: '1.1',
- group_id: groupId, root_name: rootName,
- ...(writable !== undefined && { writable }),
- ...(removable !== undefined && { removable }),
- });
- if (msg.type === 'error') throw new Error(msg.detail);
- if (msg.type === 'admin_challenge') {
- return this._authorizeAdminOp(msg, 'root_update', subject, signFn);
- }
- return msg;
- }
-
async ejectRoot(groupId, rootName, signFn) {
const msg = await this._sendAndWait({
type: 'root_eject', v: '1.1',
@@ -326,81 +279,6 @@ extendTransport(class {
return msg;
}
- async unpinMember(userId, signFn) {
- const msg = await this._sendAndWait({
- type: 'member_unpin', v: '0.1', user_id: userId,
- });
- if (msg.type === 'error') throw new Error(msg.detail);
- if (msg.type === 'admin_challenge') {
- return this._authorizeAdminOp(msg, 'member_unpin', userId, signFn);
- }
- return msg;
- }
-
- async rotateGek(groupId, signFn) {
- const msg = await this._sendAndWait({
- type: 'gek_rotate', v: '0.1', group_id: groupId,
- });
- if (msg.type === 'error') throw new Error(msg.detail);
- if (msg.type === 'admin_challenge') {
- return this._authorizeAdminOp(msg, 'gek_rotate', groupId, signFn);
- }
- return msg;
- }
-
- async fetchRoster(groupId) {
- const msg = await this._sendAndWait({
- type: 'roster_read', v: '0.1', group_id: groupId || '',
- });
- if (msg.type === 'error') throw new Error(msg.detail);
- return msg;
- }
-
- async fetchDenylist() {
- const msg = await this._sendAndWait({ type: 'denylist_read', v: '0.1' });
- if (msg.type === 'error') throw new Error(msg.detail);
- return msg;
- }
-
- async clearDenylist(subject) {
- const msg = await this._sendAndWait({
- type: 'denylist_clear', v: '0.1', subject: subject || '',
- });
- if (msg.type === 'error') throw new Error(msg.detail);
- return msg;
- }
-
- async attachGroup(name, sharedDir, uploadDir, signFn) {
- const msg = await this._sendAndWait({
- type: 'group_attach', v: '0.1',
- name, shared_dir: sharedDir, upload_dir: uploadDir || '', writable: true,
- });
- if (msg.type === 'error') throw new Error(msg.detail);
- if (msg.type === 'admin_challenge') {
- // The directory being exposed is signed, not only the group's name.
- const subject = window.MeshBayCrypto.groupAttachSubject(name, sharedDir, true);
- return this._authorizeAdminOp(msg, 'group_attach', subject, signFn);
- }
- return msg;
- }
-
- async detachGroup(name, signFn) {
- const msg = await this._sendAndWait({
- type: 'group_detach', v: '0.1', name,
- });
- if (msg.type === 'error') throw new Error(msg.detail);
- if (msg.type === 'admin_challenge') {
- return this._authorizeAdminOp(msg, 'group_detach', name, signFn);
- }
- return msg;
- }
-
- async reloadConfig() {
- const msg = await this._sendAndWait({ type: 'node_reload', v: '0.1' });
- if (msg.type === 'error') throw new Error(msg.detail);
- return msg;
- }
-
/**
* Ask the node for a one-time pairing code admitting `userId` to this group.
*
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-chat.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-chat.js
index e49eb4c..96e06d7 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/transport-chat.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-chat.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
// The group chat: history, sending, link previews, and the epoch keys that
// seal it.
//
@@ -57,7 +59,7 @@ extendTransport(class {
*
* Not a switch — there is nothing to turn on. The removals that matter open
* an epoch by themselves; this is the operator saying "move the key anyway",
- * the same instruction as `rotateGek` and signed for the same reason.
+ * signed like every operator instruction.
*/
async rotateChatEpoch(signFn) {
// This connection's own group, not a parameter. Every settings pane takes
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-codec.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-codec.js
index eba0461..b2356e8 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/transport-codec.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-codec.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
// The wire codec: the subset of msgpack MNP uses (maps, strings, integers,
// binary, arrays, null), and hex for the ids the transport mints.
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-devices.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-devices.js
index 1c6fc78..f079f80 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/transport-devices.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-devices.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
// An account's devices and what they hold: joining a group, linking a device,
// the identity bundles and the per-account blobs (playlists).
//
@@ -21,7 +23,10 @@ extendTransport(class {
* at first sight, where there is nothing to compare against — that boundary
* is `docs/MESHBAY_DESIGN.md` §3.2's and does not move.
*/
- async groupRoster() {
+ async groupRoster({ fresh = false } = {}) {
+ // `fresh`: read it again rather than keep this connection's copy, for a
+ // page that lists the members and must show who joined since.
+ if (fresh && !this._rosterInFlight) this._roster = null;
if (this._roster) return this._roster;
if (this._rosterInFlight) return this._rosterInFlight;
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-media.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-media.js
index cf53c08..ca015b9 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/transport-media.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-media.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
// What the media apps ask the node for: TMDB and MusicBrainz metadata, audio
// transcoding, subtitles, and the video stream.
//
@@ -99,7 +101,7 @@ extendTransport(class {
* queried in (e.g. "fr-FR") — one for the whole node, since both are one
* operator's shared credential/cache, not a per-group concern (see
* setTmdbEnabled below for the per-group on/off switch). Signed like
- * setAppsEnabled/updateRoot — an unsigned change would let any
+ * setAppsEnabled — an unsigned change would let any
* member alter outbound third-party network traffic the operator never
* agreed to (docs/MESHBAY_DESIGN.md §9.7, §6.5). `token: ''` explicitly clears
* a previously-set custom token; omit it (undefined/null), like
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-pins.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-pins.js
index c0699dc..c32901b 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/transport-pins.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-pins.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
// Which node this browser has met under which key (trust on first use), and
// the version range a node declares at the handshake.
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-rewrap.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-rewrap.js
index cdf86b0..fb2f5cf 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/transport-rewrap.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-rewrap.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
// A passphrase change, carried to every node that holds this account's
// identity bundle.
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-roster.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-roster.js
index ca0769d..cac3b52 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/transport-roster.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-roster.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
// What a node says about who is in a group, checked rather than trusted: the
// roster's signatures, and the keys this browser pinned for each account.
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-upload.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-upload.js
index 9f4b531..a8f039d 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/transport-upload.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-upload.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
// Uploads: a whole file, sealed chunk by chunk with several in flight, and the
// folders it lands in.
//
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport.js b/packages/meshbay-hub/src/meshbay_hub/static/transport.js
index f9e1370..5ed6fa9 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/transport.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/transport.js
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: LGPL-3.0-or-later
+// Part of MeshBay's protocol layer, under the LGPL so that any client may use it.
/**
* MeshBay Browser Transport — WebRTC DataChannel client.
*
@@ -193,8 +195,7 @@ function _aborted() {
// table, then on Chat's directory, where it meant the pane went on showing an
// unsaved-looking draft after a save that had worked.
const BROADCAST_ACK_TYPES = new Set([
- 'root_update_ack', 'root_eject_ack', 'root_plug_ack',
- 'root_add_ack', 'root_remove_ack',
+ 'root_eject_ack', 'root_plug_ack', 'root_remove_ack',
'app_directories_ack', 'chat_directory_ack', 'chat_link_preview_ack',
'chat_epoch_ack', 'search_listed_ack',
]);
@@ -220,10 +221,9 @@ const ADMIN_OP_TYPES = new Set([
'tmdb_override', 'tmdb_rematch', 'tmdb_config', 'tmdb_enabled',
'musicbrainz_enabled', 'file_delete', 'dir_delete',
'apps_enabled', 'set_scan_settings', 'member_revoke',
- 'root_add', 'root_remove', 'root_update', 'root_eject', 'root_plug',
+ 'root_remove', 'root_eject', 'root_plug',
'app_directories', 'chat_directory', 'chat_link_preview', 'chat_epoch',
- 'search_listed', 'member_unpin', 'gek_rotate', 'group_attach',
- 'group_detach', 'invite_create', 'invite_link_create', 'invite_cancel',
+ 'search_listed', 'invite_create', 'invite_link_create', 'invite_cancel',
]);
// ── Diagnostic trace (opt-in, off by default) ───────────────────────────────
@@ -367,9 +367,10 @@ window.addEventListener('hashchange', () => {
// The `v: '0.1'` on every other message in this file is the historical value
// and is read by nothing; it is left alone deliberately. The range is
// negotiated once, at the start, not restated per message.
-const MNP_V = '5.0';
-// Not raised with 5.0 (see meshbay_common/__init__.py): the break is confined to
-// four signed operations, which a peer on the other side of it refuses to sign.
+const MNP_V = '6.0';
+// Not raised with 5.0 or 6.0 (see meshbay_common/__init__.py): each break is
+// confined to a few signed operations — 5.0 changed four subjects, 6.0 removed
+// root_add, root_update and group_attach — and everything else still works.
// Set at 4.0, a flag day. A member now presents a short-lived
// MNP-audience token in the handshake, not its hub session token — a node
// older than 4.0 expected the session token, and one newer refuses it, so the
@@ -2030,11 +2031,11 @@ class MeshBayTransport {
this._onMusicbrainzEnabled(Boolean(msg.enabled));
}
- // A root's flags changed, or one was ejected, plugged, added or removed.
- // Broadcast by the node to every peer, so everyone's table updates without
- // waiting for the next index_sync.
- if (msg.type === 'root_update_ack' || msg.type === 'root_eject_ack'
- || msg.type === 'root_plug_ack' || msg.type === 'root_add_ack'
+ // A root was ejected, plugged or removed. Broadcast by the node to every
+ // peer, so everyone's table updates without waiting for the next index_sync.
+ // A root added or a flag changed — on the node's own machine, never over
+ // MNP — arrives in the index_delta the node pushes.
+ if (msg.type === 'root_eject_ack' || msg.type === 'root_plug_ack'
|| msg.type === 'root_remove_ack') {
if (this._onRootsChanged) this._onRootsChanged(msg);
}
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/vendor/LICENSES.txt b/packages/meshbay-hub/src/meshbay_hub/static/vendor/LICENSES.txt
new file mode 100644
index 0000000..aa2f6a9
--- /dev/null
+++ b/packages/meshbay-hub/src/meshbay_hub/static/vendor/LICENSES.txt
@@ -0,0 +1,268 @@
+Licences of the third-party files in this directory
+====================================================
+
+Each file below is redistributed unmodified; PROVENANCE.md records exactly
+which release it was taken from. This file travels with them wherever the
+interface is copied (hub, desktop client, Android application).
+
+htm-preact.js htm 3.1.1 (Apache-2.0), with Preact 10 bundled into it (MIT)
+argon2.min.js argon2-browser 1.18.0 (MIT), compiling the Argon2 reference
+argon2.wasm implementation (CC0-1.0 OR Apache-2.0; taken under CC0-1.0)
+
+
+==============================================================================
+htm — Apache License 2.0
+==============================================================================
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2018 Google Inc.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+==============================================================================
+Preact — MIT License
+==============================================================================
+
+The MIT License (MIT)
+
+Copyright (c) 2015-present Jason Miller
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+
+==============================================================================
+argon2-browser — MIT License
+==============================================================================
+
+Copyright © 2021 Antelle
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+
+
+==============================================================================
+Argon2 reference implementation — CC0-1.0
+==============================================================================
+
+The Argon2 reference implementation (https://github.com/P-H-C/phc-winner-argon2)
+is dual-licensed under CC0 1.0 Universal or the Apache License 2.0, at the
+recipient's choice. It is used here under CC0 1.0, which waives copyright and
+asks for no notice: https://creativecommons.org/publicdomain/zero/1.0/legalcode
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md b/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md
index 6935e91..53d4af3 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md
+++ b/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md
@@ -34,3 +34,25 @@ The browser never requests it — `argon2.min.js` carries the same bytes inline
a data URL. It is kept because the cross-language parity test drives the vendored
library under node, where the emscripten loader takes its file path instead of the
inline copy, and a test that cannot run is a test that stops being true.
+
+## htm-preact.js
+
+| | |
+|---|---|
+| Package | `htm` 3.1.1 (npm) — Apache-2.0 |
+| Source | https://registry.npmjs.org/htm/-/htm-3.1.1.tgz |
+| Tarball sha256 | `2425b9bee11409177bcabc7f32e319926fc6690c1701c0b257c88bdff2d5ba90` |
+| Tarball sha1 (npm dist.shasum) | `49266582be0dc66ed2235d5ea892307cc0c24b78` |
+| File taken | `package/preact/standalone.module.js` |
+| File sha256 | `72284e8e9079c87817145df1110f74e8a2aa040b2fc384922e18dfcb46fc1fd7` |
+
+htm's "standalone" build: htm and Preact 10 (MIT) with its hooks, in one ES
+module, so the SPA has a component model without a bundler or a second request.
+The same bytes ship in htm 3.1.0; this entry was identified after the fact, by
+matching the committed file against both releases.
+
+## Licences
+
+`LICENSES.txt`, beside these files, carries the licence text of each of them;
+the MIT and Apache licences both ask for it to travel with every copy. A file
+added here adds its licence there.
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/video-app.js b/packages/meshbay-hub/src/meshbay_hub/static/video-app.js
index 4757395..aa1edf2 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/video-app.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/video-app.js
@@ -7,6 +7,7 @@ import { formatSize } from './file-utils.js';
import { SourceTag } from './group-name.js';
import { usePager, Pager, pageSizeFrom } from './pager.js';
import { LazyTile, MediaThumb } from './media-tiles.js';
+import { CastButton } from './cast-session.js';
// ── Videos ───────────────────────────────────────────────────────────────────
//
@@ -1083,6 +1084,8 @@ function VideoApp({
</button>
</div>
<${Pager} pager=${pager} />
+ ${/* The television a film opened from here plays on (cast-session.js). */''}
+ <${CastButton} />
${!hideFilter && html`<div class="tb-search">
<${Icon} name="search" />
<input type="text" placeholder="${t('group.filter')}"
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/video-player.js b/packages/meshbay-hub/src/meshbay_hub/static/video-player.js
index fa10d15..21abe8e 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/video-player.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/video-player.js
@@ -6,6 +6,7 @@ import { Icon } from './icon.js';
import { formatSize, CHUNK_SIZE, pipelinedDownload } from './file-utils.js';
import { loadAuth } from './hub-client.js';
import * as platform from './platform.js';
+import { castSession } from './cast-session.js';
// Seconds of already-watched video kept in the SourceBuffer, and the queue depth
// past which we start making room before being forced to.
@@ -280,6 +281,64 @@ function formatClock(seconds) {
}
/**
+ * The player as a remote, while a television plays the film.
+ *
+ * Only what it is told: the receiver's position on the film's timeline (null
+ * until the receiver has answered), its state, and whether a seek is on its
+ * way. The scrubber reports a drag as it moves and a seek once let go.
+ */
+function CastRemote({ device, position, duration, playerState, moving,
+ onDrag, onSeek, onToggle, onStop }) {
+ const known = position !== null;
+ const paused = playerState === 'PAUSED';
+ const busy = !known || moving || playerState === 'BUFFERING' || playerState === 'LOADING';
+ const pct = known && duration > 0 ? Math.min(100, (position / duration) * 100) : 0;
+ return html`
+ <div class="video-remote">
+ <div class="video-remote-head">
+ <span class="video-remote-badge"><${Icon} name="cast" /></span>
+ <span class="video-remote-label">${t('cast.casting_to')}</span>
+ <span class="video-remote-device">${device}</span>
+ <span class="video-remote-state">
+ ${busy ? html`<span class="spinner"></span>${' '}${t('cast.waiting')}` : ''}
+ </span>
+ </div>
+ <div class="video-remote-track">
+ <input class="video-remote-seek" type="range" min="0" step="1"
+ style=${`--pct:${pct}%`}
+ max=${Math.max(1, Math.floor(duration))}
+ value=${Math.floor(position || 0)}
+ disabled=${!known || !(duration > 0)}
+ aria-label=${t('cast.seek')}
+ onInput=${(e) => onDrag(+e.target.value)}
+ onChange=${(e) => onSeek(+e.target.value)} />
+ <div class="video-remote-times">
+ <span>${known ? formatClock(position) : '–:––'}</span>
+ <span>${duration > 0 ? formatClock(duration) : '–:––'}</span>
+ </div>
+ </div>
+ <div class="video-remote-buttons">
+ <button class="video-remote-skip" disabled=${!known}
+ onClick=${() => onSeek(position - 30)}
+ title=${t('cast.back30')} aria-label=${t('cast.back30')}>
+ <${Icon} name="skipback" /><span class="video-remote-skip-n">30</span></button>
+ <button class="video-remote-main ${paused ? 'is-paused' : ''}" disabled=${!playerState}
+ onClick=${onToggle}
+ title=${paused ? t('cast.play') : t('cast.pause')}
+ aria-label=${paused ? t('cast.play') : t('cast.pause')}>
+ <${Icon} name=${paused ? 'play' : 'pause'} /></button>
+ <button class="video-remote-skip" disabled=${!known}
+ onClick=${() => onSeek(position + 30)}
+ title=${t('cast.fwd30')} aria-label=${t('cast.fwd30')}>
+ <${Icon} name="skipfwd" /><span class="video-remote-skip-n">30</span></button>
+ </div>
+ <button class="video-remote-stop" onClick=${onStop}>
+ <${Icon} name="close" /> ${t('cast.stop')}</button>
+ </div>
+ `;
+}
+
+/**
* Where *this account on this device* last left off in a given file.
*
* localStorage rather than the node: it needs no protocol, no storage anyone
@@ -344,7 +403,7 @@ function purgeUnscopedResumePositions() {
purgeUnscopedResumePositions();
-function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
+function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload, onCopyLink }) {
const [dlBusy, setDlBusy] = useState(false);
const [phase, setPhase] = useState('loading');
const [error, setError] = useState('');
@@ -426,18 +485,36 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
// Where the stream the node is sending begins, in film time. The same number
// the SourceBuffer gets as its `timestampOffset`.
const streamStartRef = useRef(0);
- const [castActive, setCastActive] = useState(false);
+ // A television already chosen this session (cast-session.js) takes the film
+ // from its first segment: the cast starts as a restart would, pending until
+ // the init segment arrives, and the player opens as its remote. Read once —
+ // a television chosen while this film plays is chosen here, by the picker.
+ const [autoCast] = useState(() => (castSession.supported ? castSession.device : null));
+ const [castActive, setCastActive] = useState(Boolean(autoCast));
const [castUrl, setCastUrl] = useState(null);
const [castPickerOpen, setCastPickerOpen] = useState(false);
const [castDevices, setCastDevices] = useState([]);
const [castScanning, setCastScanning] = useState(false);
- const [castDeviceName, setCastDeviceName] = useState(null);
- const castActiveRef = useRef(false);
+ const [castDeviceName, setCastDeviceName] = useState(autoCast ? autoCast.name : null);
+ const castActiveRef = useRef(Boolean(autoCast));
const castCodecRef = useRef(null);
const initSegmentRef = useRef(null);
- const castRestartPendingRef = useRef(false);
- const castDeviceRef = useRef(null);
+ const castRestartPendingRef = useRef(Boolean(autoCast));
+ const castDeviceRef = useRef(autoCast);
const castRestartGenRef = useRef(0);
+ // The receiver as last polled: { playerState, position } with the position
+ // on the film's timeline, or null before it has answered.
+ const [remote, setRemote] = useState(null);
+ // Where the viewer sent the television and it has not arrived yet. Shown in
+ // place of the receiver's position, which until the reload still belongs to
+ // the stream being abandoned and would make the scrubber jump back.
+ const [remoteTarget, setRemoteTarget] = useState(null);
+ const [remoteDrag, setRemoteDrag] = useState(null);
+ const remoteFilmPosRef = useRef(null);
+ // Segments of the *new* stream that arrive while its seek is still landing
+ // (`reinitAt`/`resumeAt` wait on the SourceBuffer). Null when not holding.
+ const heldRef = useRef(null);
+ const holdGenRef = useRef(0);
const landingPlayheadRef = useRef(false);
// The current Screen Wake Lock sentinel, if the browser granted one — see
// the effect below. Null on any platform/context that does not support it,
@@ -764,6 +841,7 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
ranges: describeRanges(),
});
awaitingInitRef.current = true;
+ heldRef.current = null; holdGenRef.current++;
// A seek supersedes a resume that had been asked for and not landed:
// this one empties the buffer, and taking the resume branch on its
// `stream_init` would leave the film we navigated away from in place.
@@ -798,6 +876,7 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
});
resumingRef.current = true;
awaitingInitRef.current = true;
+ heldRef.current = null; holdGenRef.current++;
seekTargetRef.current = null;
outstandingRef.current = STREAM_WINDOW;
console.log('[resume] request', +target.toFixed(1));
@@ -1064,7 +1143,23 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
castRestartPendingRef.current = true;
}
const land = resuming ? resumeAt : reinitAt;
- land(msg.start || 0).catch(() => {
+ // What follows this message on the ordered channel is the new
+ // stream, its header first. The landing waits on the SourceBuffer,
+ // and those segments used to arrive in that gap and be dropped as
+ // the old film's: the player kept its header from the start of the
+ // film and never noticed, but a cast relay restarted here got a
+ // stream beginning at a moof — no ftyp, no moov — and the receiver
+ // gave up on it within a second (measured on a phone). So they are
+ // held, and taken in order once the landing is done.
+ const hold = ++holdGenRef.current;
+ heldRef.current = [];
+ land(msg.start || 0).then(async () => {
+ while (holdGenRef.current === hold && heldRef.current && heldRef.current.length) {
+ await consumeSegment(heldRef.current.shift());
+ }
+ if (holdGenRef.current === hold) heldRef.current = null;
+ }).catch(() => {
+ if (holdGenRef.current === hold) heldRef.current = null;
setError(t('video.err_transport'));
setPhase('error');
});
@@ -1178,6 +1273,12 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
// for credit that cannot come. A race, which is why the same seek
// worked twice and hung on the third.
outstandingRef.current = Math.max(0, outstandingRef.current - 1);
+ // The new stream, arriving while its seek lands: kept, not dropped.
+ // Counted above already, so the replay must not count it again.
+ if (heldRef.current) {
+ if (!msg.file_id || msg.file_id === entry.id) heldRef.current.push(msg);
+ return;
+ }
if (awaitingInitRef.current) {
console.log('[seek] dropping segment (awaitingInit), outstanding:', outstandingRef.current);
}
@@ -1190,6 +1291,13 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
// would otherwise be decrypted against the wrong file — which fails,
// loudly, in the console, for something that is simply not ours.
if (msg.file_id && msg.file_id !== entry.id) return;
+ await consumeSegment(msg);
+ };
+
+ // Everything a segment goes through once it is known to belong to the
+ // stream being played: by arrival, or replayed after a landing.
+ const consumeSegment = async (msg) => {
+ if (cancelled) return;
try {
const plaintext = await window.MeshBayCrypto.decryptChunkBin(
gekRef.current, entry.id, msg.segment_index, msg.nonce, msg.ct);
@@ -1208,6 +1316,7 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
}).then(async (result) => {
if (castRestartGenRef.current !== gen) return;
if (!result) return;
+ if (device || castSession.device) castSession.claim('video');
setCastUrl(result.url);
const status = await platform.cast.status();
if (status && status.chromecast && status.chromecast.connected) {
@@ -1220,6 +1329,7 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
} else {
navigator.clipboard.writeText(result.url).catch(() => {});
}
+ if (castRestartGenRef.current === gen) setRemoteTarget(null);
}).catch((err) => {
if (castRestartGenRef.current !== gen) return;
console.error('[cast] restart failed:', err);
@@ -1433,6 +1543,37 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
}
}, [phase]);
+ // The scan lives as long as the picker is open: closing it, or picking a
+ // receiver, stops the updates. Receivers are listed as they answer, and the
+ // spinner sits below them so one landing never moves the row being aimed at.
+ // While casting, the film plays on the receiver; the local element keeps
+ // playing — its playhead is what paces the stream the relay forwards — but
+ // silently. It went on with its sound, so a phone in the room doubled the
+ // television's audio, screen off included. What the viewer had set comes
+ // back when the cast ends.
+ const mutedBeforeCastRef = useRef(null);
+ useEffect(() => {
+ const v = videoRef.current;
+ if (!v) return;
+ if (castActive) {
+ if (mutedBeforeCastRef.current === null) mutedBeforeCastRef.current = v.muted;
+ v.muted = true;
+ } else if (mutedBeforeCastRef.current !== null) {
+ v.muted = mutedBeforeCastRef.current;
+ mutedBeforeCastRef.current = null;
+ }
+ }, [castActive]);
+
+ useEffect(() => {
+ if (!castPickerOpen) return undefined;
+ setCastDevices([]);
+ setCastScanning(true);
+ return platform.cast.discover((devices, scanning) => {
+ setCastDevices(devices || []);
+ setCastScanning(scanning);
+ });
+ }, [castPickerOpen]);
+
useEffect(() => {
return () => {
if (blobUrlRef.current) {
@@ -1589,6 +1730,78 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
};
}, []);
+ // ── Remote ────────────────────────────────────────────────────────────
+ //
+ // While a television plays the film, this player is its remote. The phone
+ // and the receiver do not play in step — they start apart and drift — so a
+ // scrubber on the local playhead lied about where the film was, and a seek
+ // from it landed off by that much. Everything here reads the receiver and
+ // tells it what to do; seeking is the ordinary seek, which restarts the
+ // relay and reloads the receiver at the new position.
+ const remoteMode = castActive && castDeviceName !== null && platform.cast.canControl;
+ useEffect(() => {
+ if (!remoteMode) {
+ setRemote(null); setRemoteTarget(null); setRemoteDrag(null);
+ remoteFilmPosRef.current = null;
+ return undefined;
+ }
+ let stopped = false;
+ const poll = async () => {
+ try {
+ const s = await platform.cast.status();
+ const c = s && s.chromecast;
+ if (stopped) return;
+ if (c && c.connected && c.position != null && !castRestartPendingRef.current) {
+ const position = streamStartRef.current + c.position;
+ remoteFilmPosRef.current = position;
+ setRemote({ playerState: c.playerState, position });
+ } else {
+ setRemote((r) => (r && c && c.connected ? { ...r, playerState: c.playerState } : r));
+ }
+ } catch { /* asked again on the next tick */ }
+ };
+ poll();
+ const id = setInterval(poll, 1000);
+ return () => { stopped = true; clearInterval(id); };
+ }, [remoteMode]);
+
+ // Stopping here is stopping for the session: the next film or photo stays
+ // on this device until a television is chosen again.
+ const stopCast = async () => {
+ castSession.forget();
+ await platform.cast.chromecastDisconnect().catch(() => {});
+ await platform.cast.stop();
+ setCastActive(false); castActiveRef.current = false;
+ setCastUrl(null);
+ setCastDeviceName(null);
+ castDeviceRef.current = null;
+ };
+
+ const remoteShown = remoteDrag ?? remoteTarget ?? (remote ? remote.position : null);
+ const remoteSeek = (to) => {
+ const duration = durationRef.current;
+ const target = Math.max(0, duration > 0 ? Math.min(to, duration - 1) : to);
+ setRemoteTarget(target);
+ if (requestSeekRef.current) requestSeekRef.current(target);
+ };
+ const remoteToggle = async () => {
+ const v = videoRef.current;
+ try {
+ if (remote && remote.playerState === 'PAUSED') {
+ await platform.cast.chromecastPlay();
+ if (v) v.play().catch(() => {});
+ } else {
+ await platform.cast.chromecastPause();
+ // The local copy only paces the download: left running, it would go
+ // on fetching for a television that is not watching.
+ if (v) v.pause();
+ }
+ setRemote((r) => (r ? { ...r, playerState: r.playerState === 'PAUSED' ? 'PLAYING' : 'PAUSED' } : r));
+ } catch (err) {
+ console.warn('[cast] remote command failed:', err);
+ }
+ };
+
return html`
<div class="video-overlay video-player-overlay" onClick=${(e) => {
if (e.target.classList.contains('video-overlay')) onClose();
@@ -1617,7 +1830,10 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
setAudioTrack(track.i);
const v = videoRef.current;
const seek = requestSeekRef.current;
- if (v && seek) seek(v.currentTime);
+ // Where the television is, when one plays the film: the
+ // phone's playhead has drifted from it.
+ const at = remoteFilmPosRef.current ?? (v && v.currentTime);
+ if (at != null && seek) seek(at);
}}>
${track.i === audioTrack
? html`<${Icon} name="check" />`
@@ -1674,23 +1890,12 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
<button class="video-close ${castActive ? 'cast-active' : ''}"
onClick=${async () => {
if (castActive) {
- await platform.cast.chromecastDisconnect().catch(() => {});
- await platform.cast.stop();
- setCastActive(false); castActiveRef.current = false;
- setCastUrl(null);
- setCastDeviceName(null);
- castDeviceRef.current = null;
+ await stopCast();
} else if (castCodecRef.current && initSegmentRef.current) {
if (castPickerOpen) {
setCastPickerOpen(false);
} else {
setCastPickerOpen(true);
- setCastScanning(true);
- setCastDevices([]);
- platform.cast.discover().then((devices) => {
- setCastDevices(devices || []);
- setCastScanning(false);
- }).catch(() => setCastScanning(false));
}
}
}}
@@ -1698,15 +1903,10 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
<${Icon} name="cast" /></button>
${castPickerOpen && html`
<div class="cast-picker">
- ${castScanning && html`
- <div class="cast-picker-item cast-picker-scanning">
- <span class="spinner" style="width:14px;height:14px"></span>
- ${t('cast.scanning')}
- </div>
- `}
${castDevices.map(d => html`
<button class="cast-picker-item" onClick=${() => {
setCastPickerOpen(false);
+ castSession.choose(d);
setCastDeviceName(d.name);
setCastActive(true); castActiveRef.current = true;
castRestartPendingRef.current = true;
@@ -1718,6 +1918,12 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
<${Icon} name="cast" /> ${d.name}
</button>
`)}
+ ${castScanning && html`
+ <div class="cast-picker-item cast-picker-scanning">
+ <span class="spinner" style="width:14px;height:14px"></span>
+ ${t('cast.scanning')}
+ </div>
+ `}
${!castScanning && castDevices.length === 0 && html`
<div class="cast-picker-item cast-picker-empty">
${t('cast.no_devices')}
@@ -1751,6 +1957,11 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
}
</span>
`}
+ ${onCopyLink && html`
+ <button class="video-close" onClick=${onCopyLink}
+ title="${t('link.copy')}" aria-label="${t('link.copy')}">
+ <${Icon} name="link" /></button>
+ `}
${onDownload && html`
<button class="video-close ${dlBusy ? 'dl-active' : ''}" disabled=${dlBusy}
onClick=${() => {
@@ -1770,7 +1981,7 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
</div>
${(phase === 'streaming' || phase === 'loading') && html`
- <div class="video-container">
+ <div class="video-container ${remoteMode ? 'video-container-remote' : ''}">
<video ref=${videoRef} controls autoplay>
${subtitleUrl && html`
<track key=${subtitleUrl} kind="subtitles" src=${subtitleUrl}
@@ -1781,6 +1992,18 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
default />
`}
</video>
+ ${remoteMode && html`
+ <${CastRemote}
+ device=${castDeviceName}
+ position=${remoteShown}
+ duration=${durationRef.current}
+ playerState=${remote ? remote.playerState : null}
+ moving=${remoteTarget !== null}
+ onDrag=${setRemoteDrag}
+ onSeek=${(to) => { setRemoteDrag(null); remoteSeek(to); }}
+ onToggle=${remoteToggle}
+ onStop=${stopCast} />
+ `}
${phase === 'loading' && html`
<div class="video-loading">
<div class="video-loading-label">
@@ -1819,4 +2042,4 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
* live.
*/
-export { VideoPlayer };
+export { VideoPlayer, CastRemote };
diff --git a/packages/meshbay-hub/tests/harness/cast_session_probe.py b/packages/meshbay-hub/tests/harness/cast_session_probe.py
new file mode 100644
index 0000000..573dd95
--- /dev/null
+++ b/packages/meshbay-hub/tests/harness/cast_session_probe.py
@@ -0,0 +1,521 @@
+#!/usr/bin/env python3
+"""
+A television chosen once, then photos and a film sent to it.
+
+Casting a photo or opening a film on a television chosen elsewhere is a claim
+about four pieces at once: the cast button (cast-session.js), the lightbox
+that follows it, the player that opens as a remote, and the native bridge the
+page talks to. This renders the shipped `GroupPage` against a stub node and a
+stub bridge that records what the page asks of it, and walks it as a reader
+would: open an album, choose the television, page on, start a slideshow,
+then open a film from Videos and stop casting from its remote.
+
+A second case renders the same page with no bridge at all — a browser — where
+no cast button may appear.
+
+ cast_session_probe.py Chrome, then Firefox
+"""
+
+import http.server
+import json
+import shutil
+import socketserver
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+from pathlib import Path
+
+STATIC = Path(__file__).resolve().parents[2] / "src" / "meshbay_hub" / "static"
+PORT = 8763
+RECORDS = []
+FINISHED = threading.Event()
+socketserver.TCPServer.allow_reuse_address = True
+
+FRAME = r"""<!doctype html><html><head><meta charset=utf-8>
+<link rel="stylesheet" href="/style.css"></head><body>
+<nav class="nav"><div class="nav-left"><a class="nav-brand" href="#/">MeshBay</a></div></nav>
+<div class="layout"><main class="main"><div id="root"></div></main></div>
+<script>
+// A module that fails to load never reaches its own catch: say so.
+const report = (error) => parent.postMessage({ error }, '*');
+// Scripts only: the music case's stub track is three bytes no <audio>
+// element can decode, which is expected and is not the page failing.
+addEventListener('error', (e) => {
+ if (!(e instanceof ErrorEvent) && !(e.target && e.target.tagName === 'SCRIPT')) return;
+ report(`${e.message || 'load error'} ${e.filename || (e.target && e.target.src) || ''}`
+ + `:${e.lineno || ''}`);
+}, true);
+addEventListener('unhandledrejection',
+ (e) => report(String((e.reason && e.reason.stack) || e.reason)));
+const WITH_BRIDGE = !location.search.includes('nobridge');
+const ENTRIES = [];
+for (let i = 1; i <= 3; i++) {
+ ENTRIES.push({ id: 'p' + i, name: 'photo' + i + '.png', path: 'photos/Trip',
+ type: 'image', size: 1000, added_at: 1750000000 + i });
+}
+ENTRIES.push({ id: 'film', name: 'A.Film.mkv', display_title: 'A Film',
+ path: 'videos/films', type: 'video', duration: 6000, size: 1024, added_at: 1750000100 });
+
+const ACK = {
+ is_node_admin: false, enabled_apps: ['video', 'photo'],
+ tmdb_enabled: true, tmdb_language: 'en-US',
+ video_directories: ['videos'], music_directories: [], photo_directories: ['photos'],
+};
+
+// A camera-sized picture, made here: 4000×3000, which the television must
+// receive as 1440×1080.
+let PHOTO = null;
+async function photoBytes() {
+ if (PHOTO) return PHOTO;
+ const c = document.createElement('canvas');
+ c.width = 4000; c.height = 3000;
+ const g = c.getContext('2d');
+ g.fillStyle = '#3a7'; g.fillRect(0, 0, 4000, 3000);
+ const blob = await new Promise((r) => c.toBlob(r, 'image/png'));
+ PHOTO = new Uint8Array(await blob.arrayBuffer());
+ return PHOTO;
+}
+
+window.MeshBayCrypto = {
+ importGEK: async () => 'gek',
+ b64encode: (x) => String(x),
+ decryptChunkBin: async (_g, _f, _i, _n, ct) => ct,
+};
+
+window.MeshBayTransport = function () {
+ const self = {
+ connected: false, memberRole: 'member', supportsAppOps: true,
+ sessionKeys: null, gekRaw: 'k',
+ newNodeBundle: null, newNodeBundleRecovery: null,
+ async connect() { self.connected = true; return ACK; },
+ async fetchIndex() {
+ return { entries: ENTRIES, dirs: ['photos', 'videos'],
+ roots: [{ name: 'photos', available: true, writable: false, removable: false },
+ { name: 'videos', available: true, writable: false, removable: false }] };
+ },
+ async fetchMediaMeta() { return { confidence: 0 }; },
+ // One chunk per photo: every photo is the same picture.
+ async fetchChunk() { return { nonce: 'n', ct: await photoBytes() }; },
+ addReconnectListener() { return () => {}; },
+ close() {},
+ };
+ return new Proxy(self, {
+ get(target, prop) {
+ if (prop in target) return target[prop];
+ if (typeof prop === 'string' && prop.startsWith('on')) return undefined;
+ if (typeof prop === 'symbol') return undefined;
+ return () => new Promise(() => {});
+ },
+ set(target, prop, value) { target[prop] = value; return true; },
+ });
+};
+
+// The native side, as the Electron preload and the Android shim present it,
+// recording every cast call.
+window.CALLS = [];
+// What the stub receiver reports: the music case moves it along.
+window.TV = { state: 'IDLE', position: 0, idle: null };
+if (WITH_BRIDGE) {
+ let connected = false, v = 0;
+ const rec = (name, arg) => { CALLS.push({ name, arg }); };
+ window.meshbay = {
+ hubBase: () => '',
+ setLocale: async () => true,
+ capabilities: { lanCast: true, nodeAdmin: false, localFolders: false, nativeSave: false },
+ cast: {
+ start: async (o) => {
+ rec('start', o && { codec: o.codec });
+ return { url: 'http://tv/stream.mp4?t=x' };
+ },
+ push: async () => true,
+ stop: async () => { rec('stop'); return true; },
+ subtitle: async () => null,
+ finish: async () => true,
+ file: async (f) => {
+ let info = { type: f.type, size: f.bytes.length, title: f.title || null,
+ artist: f.artist || null, album: f.album || null, cover: !!f.cover };
+ if (f.type.startsWith('image/')) {
+ const bmp = await createImageBitmap(new Blob([f.bytes], { type: f.type }));
+ info = { ...info, width: bmp.width, height: bmp.height,
+ jpeg: f.bytes[0] === 0xff && f.bytes[1] === 0xd8 };
+ }
+ rec('file', info);
+ return { url: 'http://tv/file?t=x&v=' + (++v) };
+ },
+ status: async () => ({ active: true, url: null, chromecast: {
+ connected, playerState: TV.state, position: TV.position, idleReason: TV.idle } }),
+ scan: async () => { rec('scan'); return true; },
+ devices: async () => ({ devices: [{ id: 'tv1', name: 'Salon' }], scanning: false }),
+ chromecastConnect: async (o) => {
+ rec('connect', o); connected = true;
+ return { deviceName: 'Salon' };
+ },
+ chromecastReload: async (o) => { rec('reload', o); return { playerState: 'IDLE' }; },
+ chromecastDisconnect: async () => { rec('disconnect'); connected = false; return true; },
+ chromecastPause: async () => { rec('pause'); TV.state = 'PAUSED'; return {}; },
+ chromecastPlay: async () => { rec('play'); TV.state = 'PLAYING'; return {}; },
+ chromecastSeek: async (t) => { rec('seek', t); TV.position = t; return {}; },
+ },
+ };
+}
+</script>
+<script type="module">
+import { html, render } from '/vendor/htm-preact.js';
+import { initLocale } from '/i18n.js';
+import { GroupPage } from '/group-page.js';
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const $ = (sel) => document.querySelector(sel);
+const $$ = (sel) => [...document.querySelectorAll(sel)];
+async function until(pred, what, tries = 200) {
+ for (let i = 0; i < tries; i++) { if (pred()) return; await sleep(50); }
+ throw new Error('timed out waiting for ' + what);
+}
+const calls = (name) => CALLS.filter((c) => c.name === name);
+const files = () => calls('file').map((c) => c.arg);
+// Files is always first; then the enabled apps in their registry order.
+const videosTab = () => $$('.group-tab')[1];
+const count = () => (($('.photo-lightbox-count') || {}).textContent || '').trim();
+
+// The music bar, with a television already chosen: two tracks of one album.
+async function music() {
+ const { MusicPlayerBar } = await import('/music-player.js');
+ const { castSession } = await import('/cast-session.js');
+ const out = {};
+ castSession.choose({ id: 'tv1', name: 'Salon' });
+ // Which hashes were fetched, so a cover can be traced to where it came from.
+ window.FETCHED = [];
+ const transport = { connected: true, async waitForReconnect() {},
+ async fetchChunk(id) {
+ FETCHED.push(id);
+ return { nonce: 'n', ct: new Uint8Array([1, 2, 3]) };
+ },
+ // The node's MusicBrainz answer: a cover for the other album only.
+ async fetchMusicMeta(id) {
+ CALLS.push({ name: 'musicMeta', arg: id });
+ return id === 't3' ? { confidence: 1, cover_thumb_hash: 'mb-cover' }
+ : { confidence: 0 };
+ } };
+ const getConnection = async () => ({ transport, gek: 'gek' });
+ // One has no cover of its own but Two, of the same album, has; Three is of
+ // another album whose only cover is the one the node found.
+ const track = (n, title, album, hash) => ({ id: 't' + n, name: title + '.mp3', size: 3,
+ groupId: 'g1', display_title: title, artist: 'Some Band', album, duration: 200,
+ thumb_hash: hash });
+ const queue = { tracks: [track(1, 'One', 'An Album', null), track(2, 'Two', 'An Album', 'cover2'),
+ track(3, 'Three', 'Another Album', null)], startIndex: 0, nonce: 1 };
+ render(html`<${MusicPlayerBar} getConnection=${getConnection} queue=${queue}
+ userPrefs=${{}} onClose=${() => {}} />`, document.getElementById('root'));
+
+ await until(() => calls('connect').length === 1, 'the first track on the television');
+ out.first = { file: files()[0], connect: calls('connect')[0].arg,
+ coverFetched: FETCHED.includes('cover2') };
+ TV.state = 'PLAYING'; TV.position = 12;
+ await until(() => ($$('.music-player-time')[0] || {}).textContent === '0:12',
+ "the television's clock in the bar");
+ out.barButton = !!$('.music-player-bar .cast-btn.casting');
+ out.volumeDisabled = $('.music-player-volume input').disabled;
+
+ $('.music-player-play').click();
+ await until(() => calls('pause').length === 1, 'pause on the television');
+ const slider = $('.music-player-seek input');
+ slider.value = '30';
+ slider.dispatchEvent(new Event('input', { bubbles: true }));
+ await until(() => calls('seek').length === 1, 'a seek on the television');
+ out.seek = calls('seek')[0].arg;
+
+ // The television finishes the track: the next one goes, once.
+ TV.state = 'IDLE'; TV.idle = 'FINISHED';
+ await until(() => calls('reload').length === 1, 'the next track on the television');
+ out.second = { file: files()[1], reload: calls('reload')[0].arg,
+ title: $('.music-player-title').textContent.trim() };
+ TV.state = 'PLAYING'; TV.idle = null; TV.position = 1;
+ await sleep(2500);
+ out.filesAfterSettling = files().length;
+
+ // Three: the cover comes from the node's answer for its album.
+ TV.state = 'IDLE'; TV.idle = 'FINISHED';
+ await until(() => calls('reload').length === 2, 'the third track on the television');
+ out.third = { file: files()[2], mbCover: FETCHED.includes('mb-cover'),
+ metaAsked: calls('musicMeta').map((c) => c.arg) };
+ TV.state = 'PLAYING'; TV.idle = null;
+
+ // Stopping the cast lets the television go.
+ await castSession.end();
+ await sleep(200);
+ out.afterStop = { disconnects: calls('disconnect').length,
+ barCasting: !!$('.music-player-bar .cast-btn.casting') };
+ parent.postMessage(out, '*');
+}
+
+(async () => {
+ const out = { bridge: !!window.meshbay };
+ if (location.search.includes('music')) {
+ try { await initLocale(); await music(); }
+ catch (err) {
+ parent.postMessage({ calls: CALLS, error: String((err && err.stack) || err) }, '*');
+ }
+ return;
+ }
+ try {
+ await initLocale();
+ render(html`<${GroupPage} groupId="g1" token="t" username="me" userId="u1"
+ group=${{ id: 'g1', name: 'a group', owner_username: 'me', is_admin: false }}
+ userPrefs=${{ default_tab: 'photo', media_page_size: '50' }} />`,
+ document.getElementById('root'));
+
+ await until(() => $('.photo-album-card'), 'the album card');
+ out.landingButton = !!$('.photo-toolbar .cast-btn');
+ $('.photo-album-card').click();
+ await until(() => $('.photo-album-bar'), 'the album');
+ out.albumButton = !!$('.photo-album-bar .cast-btn');
+
+ if (!window.meshbay) {
+ videosTab().click();
+ await until(() => $('.video-toolbar'), 'the videos toolbar');
+ out.videosButton = !!$('.video-toolbar .cast-btn');
+ parent.postMessage(out, '*');
+ return;
+ }
+
+ // Choose the television from the album: the first photo opens and goes.
+ $('.photo-album-bar .cast-btn').click();
+ await until(() => $$('.cast-menu .ctx-menu-item').some((b) => b.textContent.includes('Salon')),
+ 'the receiver in the menu');
+ $$('.cast-menu .ctx-menu-item').find((b) => b.textContent.includes('Salon')).click();
+ await until(() => $('.photo-lightbox'), 'the lightbox to open on choosing');
+ await until(() => calls('connect').length === 1, 'the first photo to reach the television');
+ out.first = { count: count(), image: files()[0], connect: calls('connect')[0].arg,
+ lightboxCasting: !!$('.photo-lightbox .cast-btn.casting') };
+
+ // Next photo: the receiver is connected, so it is reloaded.
+ $('.photo-nav-next').click();
+ await until(() => calls('reload').length === 1, 'the second photo');
+ out.second = { count: count(), reload: calls('reload')[0].arg, images: files().length };
+
+ // Slideshow: on by itself to the last photo, then off.
+ const play = $$('.photo-lightbox .video-top-bar .video-close')
+ .find((b) => b.getAttribute('aria-pressed') !== null);
+ play.click();
+ await until(() => count() === '3 / 3', 'the slideshow to reach the last photo', 160);
+ await until(() => play.getAttribute('aria-pressed') === 'false', 'the slideshow to end', 160);
+ out.slideshow = { count: count(), images: files().length,
+ reloads: calls('reload').length };
+
+ // Close the lightbox; Videos shows the same television; a film opens as its remote.
+ $$('.photo-lightbox .video-top-bar .video-close').pop().click();
+ await until(() => !$('.photo-lightbox'), 'the lightbox to close');
+ videosTab().click();
+ await until(() => $('.video-toolbar'), 'the videos toolbar');
+ out.videosCasting = !!$('.video-toolbar .cast-btn.casting');
+ await until(() => $('.video-card'), 'the film card');
+ $('.video-card').click();
+ await until(() => $('.video-detail .admin-btn'), 'the film modal');
+ $('.video-detail .admin-btn').click();
+ await until(() => $('.video-remote'), 'the player as a remote');
+ out.remote = { device: $('.video-remote-device').textContent.trim(),
+ pickerOpen: !!$('.video-player-overlay .cast-picker') };
+
+ // Stop from the remote: forgotten for the session.
+ $$('.video-remote button').pop().click();
+ await until(() => !$('.video-remote'), 'the remote to go');
+ $$('.video-player-overlay .video-top-bar .video-close').pop().click();
+ await until(() => !$('.video-player-overlay'), 'the player to close');
+ await sleep(100);
+ out.afterStop = { videosCasting: !!$('.video-toolbar .cast-btn.casting'),
+ disconnects: calls('disconnect').length };
+ parent.postMessage(out, '*');
+ } catch (err) {
+ parent.postMessage({ ...out, calls: CALLS, error: String((err && err.stack) || err) }, '*');
+ }
+})();
+</script></body></html>"""
+
+# Firefox headless runs a page only while taking its screenshot, which is taken
+# once the page has loaded: an image that does not answer until the case has
+# reported keeps it loading (the same hold as invitation_probe.py).
+HOLD_TAG = '<img src="/hold" style="position:fixed;left:-4px;top:-4px;width:1px">'
+
+PAGE = r"""<!doctype html><html><head><meta charset=utf-8></head>
+<body style="margin:0">
+<iframe src="/case{query}" style="width:1100px;height:800px;border:0"></iframe>
+<script>
+addEventListener('message', (e) => fetch('/log', { method: 'POST', body: JSON.stringify(e.data) }));
+</script>{hold}</body></html>"""
+
+
+class H(http.server.BaseHTTPRequestHandler):
+ def log_message(self, *a):
+ pass
+
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length") or 0)
+ if self.path == "/log":
+ RECORDS.append(json.loads(self.rfile.read(length).decode()))
+ FINISHED.set()
+ else:
+ self.rfile.read(length)
+ self.send_response(204)
+ self.end_headers()
+
+ def _send(self, body: bytes, ctype: str) -> None:
+ self.send_response(200)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ path, _, query = self.path.partition("?")
+ if path == "/hold":
+ FINISHED.wait(90)
+ self._send(b"", "image/gif")
+ elif path == "/":
+ q = f"?{query.replace('engine=firefox', '').strip('&')}" if query else ""
+ hold = HOLD_TAG if "engine=firefox" in query else ""
+ page = PAGE.replace("{query}", q if q != "?" else "").replace("{hold}", hold)
+ self._send(page.encode(), "text/html; charset=utf-8")
+ elif path == "/case":
+ self._send(FRAME.encode(), "text/html; charset=utf-8")
+ elif path == "/v1/groups/g1/nodes":
+ self._send(b'{"nodes": [{"node_id": "n1"}]}', "application/json")
+ else:
+ asset = (STATIC / path.lstrip("/")).resolve()
+ if not str(asset).startswith(str(STATIC)) or not asset.is_file():
+ self.send_response(404)
+ self.end_headers()
+ return
+ self._send(asset.read_bytes(),
+ "text/css" if asset.suffix == ".css"
+ else "text/javascript" if asset.suffix == ".js"
+ else "application/octet-stream")
+
+
+def browse(engine: str, query: str) -> dict | None:
+ RECORDS.clear()
+ FINISHED.clear()
+ sep = "&" if query else "?"
+ url = f"http://127.0.0.1:{PORT}/{query}{sep + 'engine=firefox' if engine == 'firefox' else ''}"
+ # Firefox is a snap here, and needs its profile under $HOME (invitation_probe.py).
+ snap = Path.home() / "snap" / "firefox" / "common"
+ parent = (str(snap if snap.is_dir() else Path.home()) if engine == "firefox" else None)
+ with tempfile.TemporaryDirectory(ignore_cleanup_errors=True, prefix="meshbay-probe-",
+ dir=parent) as profile:
+ if engine == "chrome":
+ cmd = ["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox",
+ f"--user-data-dir={profile}", "--window-size=1100,900", url]
+ else:
+ cmd = ["firefox", "--headless", "--profile", profile, "--window-size=1100,900",
+ "--screenshot", str(Path(profile) / "shot.png"), url]
+ proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ deadline = time.time() + 90
+ while not RECORDS and time.time() < deadline:
+ time.sleep(0.2)
+ proc.terminate()
+ try:
+ proc.wait(timeout=20)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait()
+ return RECORDS[0] if RECORDS else None
+
+
+def check(engine: str, cast: dict, plain: dict) -> list[str]:
+ bad = []
+ if "error" in cast:
+ return [f"{engine}: {cast['error']}"]
+ if not cast["landingButton"]:
+ bad.append("no cast button on the Photos landing")
+ if not cast["albumButton"]:
+ bad.append("no cast button in the album bar")
+ first = cast["first"]
+ if first["count"] != "1 / 3":
+ bad.append(f"choosing a television did not open the first photo: {first['count']}")
+ img = first["image"]
+ if not (img["type"] == "image/jpeg" and img["jpeg"] and img["width"] == 1440
+ and img["height"] == 1080):
+ bad.append(f"the photo did not leave as a 1440x1080 JPEG: {img}")
+ if first["connect"] != {"deviceId": "tv1", "mediaUrl": "http://tv/file?t=x&v=1",
+ "startAt": 0}:
+ bad.append(f"connect: {first['connect']}")
+ if not first["lightboxCasting"]:
+ bad.append("the lightbox's cast button does not say it is casting")
+ if cast["second"]["count"] != "2 / 3" or cast["second"]["reload"] != {
+ "mediaUrl": "http://tv/file?t=x&v=2", "startAt": 0}:
+ bad.append(f"next photo: {cast['second']}")
+ if cast["slideshow"]["count"] != "3 / 3" or cast["slideshow"]["images"] != 3:
+ bad.append(f"slideshow: {cast['slideshow']}")
+ if not cast["videosCasting"]:
+ bad.append("Videos does not show the television chosen in Photos")
+ if cast["remote"]["device"] != "Salon" or cast["remote"]["pickerOpen"]:
+ bad.append(f"the film did not open as the television's remote: {cast['remote']}")
+ if cast["afterStop"]["videosCasting"] or cast["afterStop"]["disconnects"] < 1:
+ bad.append(f"stopping from the remote: {cast['afterStop']}")
+ if "error" in plain:
+ bad.append(f"no bridge: {plain['error']}")
+ elif plain["landingButton"] or plain["albumButton"] or plain["videosButton"]:
+ bad.append(f"a cast button without a bridge: {plain}")
+ return [f"{engine}: {b}" for b in bad]
+
+
+def check_music(engine: str, m: dict) -> list[str]:
+ if "error" in m:
+ return [f"{engine}: music: {m['error']}"]
+ bad = []
+ f = m["first"]["file"]
+ if not (f["type"] == "audio/mpeg" and f["title"] == "One" and f["artist"] == "Some Band"
+ and f["album"] == "An Album" and f["cover"] and m["first"]["coverFetched"]):
+ bad.append(f"the first track left without its album's cover: {m['first']}")
+ third = m["third"]
+ if not (third["file"]["title"] == "Three" and third["file"]["cover"] and third["mbCover"]):
+ bad.append(f"the node's cover did not reach the television: {third}")
+ if "t1" in third["metaAsked"] or "t2" in third["metaAsked"]:
+ bad.append(f"the node was asked for a cover a track already had: {third['metaAsked']}")
+ if m["first"]["connect"] != {"deviceId": "tv1", "mediaUrl": "http://tv/file?t=x&v=1",
+ "startAt": 0}:
+ bad.append(f"connect: {m['first']['connect']}")
+ if not m["barButton"]:
+ bad.append("the music bar's cast button does not say it is casting")
+ if not m["volumeDisabled"]:
+ bad.append("the volume slider still acts while casting")
+ if m["seek"] != 30:
+ bad.append(f"seek: {m['seek']}")
+ s = m["second"]
+ if s["file"]["title"] != "Two" or s["title"] != "Two" or s["reload"] != {
+ "mediaUrl": "http://tv/file?t=x&v=2", "startAt": 0}:
+ bad.append(f"the end of a track did not move the queue on: {s}")
+ if m["filesAfterSettling"] != 2:
+ bad.append(f"a finished track moved the queue on more than once: {m['filesAfterSettling']}")
+ if m["afterStop"]["disconnects"] < 1 or m["afterStop"]["barCasting"]:
+ bad.append(f"stopping: {m['afterStop']}")
+ return [f"{engine}: music: {b}" for b in bad]
+
+
+def main() -> int:
+ failures = []
+ with socketserver.ThreadingTCPServer(("127.0.0.1", PORT), H) as srv:
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ for engine in ("chrome", "firefox"):
+ if shutil.which("google-chrome" if engine == "chrome" else engine) is None:
+ print(f"{engine}: not installed, skipped")
+ continue
+ cast = browse(engine, "")
+ plain = browse(engine, "?nobridge")
+ music = browse(engine, "?music")
+ if cast is None or plain is None or music is None:
+ failures.append(f"{engine}: the page never reported")
+ continue
+ print(f"{engine}:", json.dumps({"photos-videos": cast, "music": music}, indent=1))
+ failures += check(engine, cast, plain)
+ failures += check_music(engine, music)
+ for f in failures:
+ print("FAIL", f, file=sys.stderr)
+ if not failures:
+ print("OK")
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/packages/meshbay-hub/tests/harness/copy_link_probe.py b/packages/meshbay-hub/tests/harness/copy_link_probe.py
new file mode 100644
index 0000000..564d277
--- /dev/null
+++ b/packages/meshbay-hub/tests/harness/copy_link_probe.py
@@ -0,0 +1,270 @@
+#!/usr/bin/env python3
+"""
+"Copy link" in Files, Music and Photos, in a real browser.
+
+Mounts the shipped `FilesPanel`, `MusicApp` and `PhotosApp` on a made-up
+index — no node, no transport — with the `linkFor` a group page gives them,
+built by the real `copy-link.js` for a group `demo@someowner`. Opens each
+menu the way a reader would (right-click; the dots on a phone; the Files
+toolbar with one row ticked), picks "Copy link", and reads back what reached
+the clipboard and what the page said.
+
+ copy_link_probe.py
+
+Prints JSON: one entry per case.
+"""
+
+import http.server
+import json
+import socketserver
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+from pathlib import Path
+
+STATIC = Path(__file__).resolve().parents[2] / "src" / "meshbay_hub" / "static"
+PORT = 8775
+RECORDS = []
+socketserver.TCPServer.allow_reuse_address = True
+
+FRAME = r"""<!doctype html><html><head><meta charset=utf-8>
+<link rel="stylesheet" href="/style.css"></head><body>
+<div id="files"></div><div id="music"></div><div id="photos"></div>
+<script type="module">
+import { html, render } from '/vendor/htm-preact.js';
+import { initLocale, setLocale } from '/i18n.js';
+import { FilesPanel } from '/files-app.js';
+import { MusicApp } from '/music-app.js';
+import { PhotosApp } from '/photos-app.js';
+import { groupItemLink, entryPath } from '/copy-link.js';
+
+const LOGS = [];
+addEventListener('error', (e) => LOGS.push('error: ' + (e.message || e)));
+addEventListener('unhandledrejection',
+ (e) => LOGS.push('rejection: ' + (e.reason && e.reason.message || e.reason)));
+const frame = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
+const wait = (ms) => new Promise((r) => setTimeout(r, ms));
+
+// What the clipboard was handed, and nothing else: a headless page has no
+// clipboard permission to test against.
+const COPIES = [];
+Object.defineProperty(navigator, 'clipboard', { configurable: true,
+ value: { writeText: async (text) => { COPIES.push(text); } } });
+
+const GROUP = { name: 'demo', owner_username: 'someowner' };
+const linkFor = (target) => (target
+ ? groupItemLink(GROUP, typeof target === 'string' ? target : entryPath(target)) : null);
+const noop = () => {};
+const ref = { current: null };
+
+const labels = () => [...document.querySelectorAll('.ctx-menu .ctx-menu-label')]
+ .map((el) => el.textContent);
+const pick = async (label) => {
+ const item = [...document.querySelectorAll('.ctx-menu .ctx-menu-item')]
+ .find((b) => b.querySelector('.ctx-menu-label').textContent === label);
+ if (!item) return false;
+ item.click();
+ await wait(50);
+ return true;
+};
+const note = () => (document.querySelector('.page-note') || {}).textContent || '';
+const closeMenus = async () => {
+ document.body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
+ await frame();
+};
+const rightClick = async (el) => {
+ await closeMenus();
+ const r = el.getBoundingClientRect();
+ el.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true,
+ clientX: r.left + 10, clientY: r.top + 5 }));
+ await frame();
+};
+const rowNamed = (name) => [...document.querySelectorAll('tr.file-row')]
+ .find((tr) => tr.querySelector('.file-name')
+ && tr.querySelector('.file-name').textContent.trim().startsWith(name));
+
+(async () => {
+ const cases = [];
+ try {
+ setLocale('en');
+ await initLocale();
+ try { localStorage.setItem('meshbay_music_view_mode', 'flat'); } catch {}
+
+ // -- Files --
+ const FILES = [
+ { id: 'f1', name: 'IMG 0001.JPG', path: 'Root/trip_2015', size: 10, type: 'image',
+ added_at: 1 },
+ { id: 'f2', name: 'notes.txt', path: 'Root/trip_2015', size: 5, type: 'document',
+ added_at: 2 },
+ ];
+ render(html`<${FilesPanel} groupId="g" transportRef=${ref} gekRef=${ref}
+ status="connected" entries=${FILES} nodeDirs=${['Root', 'Root/trip_2015']}
+ nodeRoots=${[{ name: 'Root', writable: false }]}
+ setEntries=${noop} setNodeDirs=${noop} setNodeRoots=${noop} applyIndex=${noop}
+ isNodeAdmin=${false} operatorPaired=${false} userId="me" setError=${noop}
+ onPreview=${noop} linkFor=${linkFor} />`, document.getElementById('files'));
+ await frame();
+
+ await rightClick(rowNamed('Root'));
+ const folderLabels = labels();
+ await pick('Copy link');
+ cases.push({ case: 'files folder', labels: folderLabels, copied: COPIES.at(-1), note: note() });
+
+ rowNamed('Root').click(); await frame();
+ rowNamed('trip_2015').click(); await frame();
+ await rightClick(rowNamed('IMG 0001.JPG'));
+ const fileLabels = labels();
+ await pick('Copy link');
+ cases.push({ case: 'files file', labels: fileLabels, copied: COPIES.at(-1), note: note() });
+
+ await closeMenus();
+ const linkBtn = () => document.querySelector('.tb-actions button[aria-label="Copy link"]');
+ rowNamed('notes.txt').querySelector('input[type=checkbox]').click(); await frame();
+ const oneTicked = linkBtn() ? !linkBtn().disabled : null;
+ if (linkBtn() && !linkBtn().disabled) { linkBtn().click(); await wait(50); }
+ const copiedFromToolbar = COPIES.at(-1);
+ for (const n of ['IMG 0001.JPG', 'notes.txt']) {
+ rowNamed(n).querySelector('input[type=checkbox]').click(); await frame();
+ }
+ const twoTicked = linkBtn() ? !linkBtn().disabled : null;
+ cases.push({ case: 'files toolbar', one_enabled: oneTicked, two_enabled: twoTicked,
+ copied: copiedFromToolbar });
+ render(null, document.getElementById('files'));
+
+ // -- Music: a loose track, its row's dots (what a phone has) --
+ const TRACKS = [
+ { id: 'a1', name: 'track 01.flac', path: 'Music/Some Album', size: 3, type: 'audio' },
+ { id: 'a2', name: 'track 02.flac', path: 'Music/Some Album', size: 3, type: 'audio' },
+ ];
+ render(html`<${MusicApp} groupId="g" transportRef=${ref} gekRef=${ref}
+ status="connected" entries=${TRACKS} musicDirectories=${['Music']}
+ musicbrainzConfig=${{ enabled: false }} onPlayQueue=${noop} userId=""
+ linkFor=${linkFor} />`, document.getElementById('music'));
+ await frame();
+ await closeMenus();
+ const dots = document.querySelector('.music-flat-track .ctx-dots');
+ if (dots) { dots.click(); await frame(); }
+ const trackLabels = labels();
+ await pick('Copy link');
+ cases.push({ case: 'music track', dots: Boolean(dots), labels: trackLabels,
+ copied: COPIES.at(-1) });
+ render(null, document.getElementById('music'));
+
+ // -- Photos: right-click a tile; the lightbox's button --
+ const PHOTOS = [
+ { id: 'p1', name: 'beach.jpg', path: 'Pics/Summer', size: 4, type: 'image', added_at: 1 },
+ ];
+ render(html`<${PhotosApp} groupId="g" transportRef=${ref} gekRef=${ref}
+ status="connected" entries=${PHOTOS} photoDirectories=${['Pics']}
+ setError=${noop} linkFor=${linkFor} />`, document.getElementById('photos'));
+ await frame();
+ const album = document.querySelector('.photo-album-card');
+ if (album) { album.click(); await frame(); }
+ const tile = document.querySelector('.photo-tile');
+ let tileLabels = [];
+ if (tile) {
+ await rightClick(tile);
+ tileLabels = labels();
+ await pick('Copy link');
+ }
+ const fromTile = COPIES.at(-1);
+ if (tile) { tile.click(); await frame(); }
+ const lb = document.querySelector('.photo-lightbox button[aria-label="Copy link"]');
+ COPIES.length = 0;
+ if (lb) { lb.click(); await wait(50); }
+ cases.push({ case: 'photos', tile: Boolean(tile), labels: tileLabels, copied: fromTile,
+ lightbox_button: Boolean(lb), lightbox_copied: COPIES.at(-1) || null });
+
+ // Said, then gone (note.js): still up just after, not 2.5 s later.
+ const upAfterCopy = Boolean(document.querySelector('.page-note'));
+ await wait(2700);
+ cases.push({ case: 'note goes', up_after_copy: upAfterCopy,
+ up_later: Boolean(document.querySelector('.page-note')) });
+
+ parent.postMessage({ cases, logs: LOGS, origin: location.origin }, '*');
+ } catch (err) {
+ parent.postMessage({ error: String(err && (err.stack || err)), logs: LOGS }, '*');
+ }
+})();
+</script></body></html>"""
+
+PAGE = r"""<!doctype html><html><head><meta charset=utf-8></head>
+<body style="margin:0"><div id="frames"></div><script>
+addEventListener('message', (e) => {
+ fetch('/log', { method: 'POST', body: JSON.stringify(e.data) });
+});
+const f = document.createElement('iframe');
+f.src = '/case';
+f.style.cssText = 'width:1100px;height:800px;border:0;display:block';
+document.getElementById('frames').appendChild(f);
+</script></body></html>"""
+
+
+class H(http.server.BaseHTTPRequestHandler):
+ def log_message(self, *a):
+ pass
+
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length") or 0)
+ if self.path == "/log":
+ RECORDS.append(json.loads(self.rfile.read(length).decode()))
+ else:
+ self.rfile.read(length)
+ self.send_response(204)
+ self.end_headers()
+
+ def _send(self, body: bytes, ctype: str) -> None:
+ self.send_response(200)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ path = self.path.split("?")[0]
+ if path == "/":
+ self._send(PAGE.encode(), "text/html; charset=utf-8")
+ elif path == "/case":
+ self._send(FRAME.encode(), "text/html; charset=utf-8")
+ else:
+ asset = (STATIC / path.lstrip("/")).resolve()
+ if not str(asset).startswith(str(STATIC)) or not asset.is_file():
+ self.send_response(404)
+ self.end_headers()
+ return
+ self._send(asset.read_bytes(),
+ "text/css" if asset.suffix == ".css"
+ else "text/javascript" if asset.suffix == ".js"
+ else "application/octet-stream")
+
+
+def main() -> int:
+ with socketserver.TCPServer(("127.0.0.1", PORT), H) as srv:
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as profile:
+ proc = subprocess.Popen(
+ ["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox",
+ f"--user-data-dir={profile}", "--window-size=1100,900",
+ f"http://127.0.0.1:{PORT}/"],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ for _ in range(300):
+ if RECORDS:
+ break
+ time.sleep(0.1)
+ proc.terminate()
+ try:
+ proc.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait()
+ if not RECORDS:
+ print(json.dumps({"error": "no measurement"}), file=sys.stderr)
+ return 1
+ print(json.dumps(RECORDS[0], indent=1))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/packages/meshbay-hub/tests/harness/group_link_probe.py b/packages/meshbay-hub/tests/harness/group_link_probe.py
new file mode 100644
index 0000000..2d7c0d7
--- /dev/null
+++ b/packages/meshbay-hub/tests/harness/group_link_probe.py
@@ -0,0 +1,176 @@
+#!/usr/bin/env python3
+"""
+A group link, `#/name@owner[/path]`, opened in the real application.
+
+`test_group_link.py` runs `group-link.js` on its own; this is where it meets
+the router, the account's group list and the sign-in state. Loads the shipped
+`app.js` in a real browser with `fetch` stubbed (no node answers, so a group
+page goes as far as "offline"), once per case:
+
+ handle — `#/demo@someowner`: the group page, the address left as it is
+ uuid — `#/group/<id>`: the same page, the address showing the handle
+ file — `#/demo@someowner/<path>`: the page, the path kept in the address
+ until the index can say what it is (no node here: never)
+ unknown — `#/demo@stranger1`: not among the account's groups
+ signed_out — `#/demo@someowner/<path>` with no session: the sign-in form, and
+ the address untouched under it
+
+ group_link_probe.py
+
+Prints JSON: one object per case.
+"""
+
+import http.server
+import json
+import socketserver
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+from pathlib import Path
+
+STATIC = Path(__file__).resolve().parents[2] / "src" / "meshbay_hub" / "static"
+PORT = 8774
+RECORDS = []
+socketserver.TCPServer.allow_reuse_address = True
+
+GROUP = "0f8fad5b-d9cb-469f-a165-70867728950e"
+FILE = "backup/city_2015/backup/IMG_0001.JPG"
+LINKS = {
+ "handle": "#/demo@someowner",
+ "uuid": f"#/group/{GROUP}",
+ "file": f"#/demo@someowner/{FILE}",
+ "unknown": "#/demo@stranger1",
+ "signed_out": f"#/demo@someowner/{FILE}",
+}
+CASES = list(LINKS)
+
+PAGE = r"""<!doctype html><html><head><meta charset=utf-8></head><body>
+<div id="app"></div>
+<script type="module">
+const CASE = new URLSearchParams(location.search).get('case');
+const LINKS = __LINKS__;
+const realFetch = window.fetch.bind(window);
+const post = (o) => realFetch('/log', { method: 'POST', body: JSON.stringify(o) });
+const calls = [];
+const json = (body, status = 200) => ({
+ ok: status < 400, status, statusText: '', headers: new Headers(),
+ json: async () => body, text: async () => JSON.stringify(body),
+});
+window.fetch = async (url, init = {}) => {
+ const u = String(url);
+ calls.push(u);
+ if (u.includes('/v1/users/me/preferences')) return json({});
+ if (u.includes('/v1/users/me')) return json({ user_id: 'u-1', role: 'user' });
+ if (u.includes('/v1/groups/mine')) return json({ groups: [
+ { id: '__GROUP__', name: 'demo', owner_username: 'someowner', visibility: 'private',
+ created_at: '2026-01-01T00:00:00+00:00', description: '' },
+ { id: 'other-group', name: 'demo', owner_username: 'otherowner', visibility: 'private',
+ created_at: '2026-01-01T00:00:00+00:00', description: '' },
+ ] });
+ if (u.includes('/nodes')) return json({ nodes: [] });
+ return json({});
+};
+if (CASE === 'signed_out') {
+ localStorage.removeItem('mb_auth');
+} else {
+ localStorage.setItem('mb_auth', JSON.stringify({
+ username: 'member-account', userId: 'u-1', token: 'tok', refreshToken: 'ref',
+ role: 'user' }));
+}
+sessionStorage.clear();
+history.replaceState(null, '', '/?case=' + CASE + LINKS[CASE]);
+
+const wait = (ms) => new Promise((r) => setTimeout(r, ms));
+(async () => {
+ const out = { case: CASE };
+ try {
+ await import('/app.js');
+ await wait(2000);
+ out.hash = decodeURI(location.hash);
+ out.history_length = history.length;
+ out.group_page = Boolean(document.querySelector('.group-header'));
+ out.group_title = (document.querySelector('.group-header h2') || {}).innerText || '';
+ out.active_sidebar = [...document.querySelectorAll('.sidebar-group.active')]
+ .map((a) => a.getAttribute('href'));
+ out.message = (document.querySelector('main .page-message') || {}).innerText || '';
+ out.spinner = Boolean(document.querySelector('main .page-message .spinner'));
+ out.login_form = Boolean(document.querySelector('input[type=password]'));
+ out.hub_calls = calls.map((c) => c.replace(/^https?:\/\/[^/]+/, ''));
+ } catch (e) {
+ out.error = String(e && e.stack || e);
+ }
+ post(out);
+})();
+</script></body></html>
+""".replace("__GROUP__", GROUP).replace("__LINKS__", json.dumps(LINKS))
+
+
+class H(http.server.SimpleHTTPRequestHandler):
+ def log_message(self, *a):
+ pass
+
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length") or 0)
+ body = self.rfile.read(length)
+ if self.path == "/log":
+ RECORDS.append(json.loads(body.decode()))
+ self.send_response(204)
+ self.end_headers()
+
+ def _send(self, body: bytes, ctype: str) -> None:
+ self.send_response(200)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ path = self.path.split("?")[0]
+ if path == "/":
+ self._send(PAGE.encode(), "text/html; charset=utf-8")
+ return
+ asset = (STATIC / path.lstrip("/")).resolve()
+ if not str(asset).startswith(str(STATIC)) or not asset.is_file():
+ self.send_response(404)
+ self.end_headers()
+ return
+ ctype = "text/javascript" if asset.suffix in (".js", ".mjs") else (
+ "application/wasm" if asset.suffix == ".wasm" else "application/octet-stream")
+ self._send(asset.read_bytes(), ctype)
+
+
+def _run(case: str) -> dict | None:
+ before = len(RECORDS)
+ with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as profile:
+ proc = subprocess.Popen(
+ ["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox",
+ f"--user-data-dir={profile}", f"http://127.0.0.1:{PORT}/?case={case}"],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ for _ in range(300):
+ if len(RECORDS) > before:
+ break
+ time.sleep(0.1)
+ proc.terminate()
+ try:
+ proc.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait()
+ return RECORDS[before] if len(RECORDS) > before else None
+
+
+def main() -> int:
+ with socketserver.TCPServer(("127.0.0.1", PORT), H) as srv:
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ results = [_run(case) for case in CASES]
+ if not all(results):
+ print(json.dumps({"error": "no measurement", "got": results}), file=sys.stderr)
+ return 1
+ print(json.dumps(results, indent=1))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/packages/meshbay-hub/tests/harness/invite_link_probe.py b/packages/meshbay-hub/tests/harness/invite_link_probe.py
index 97ee893..b0a833e 100644
--- a/packages/meshbay-hub/tests/harness/invite_link_probe.py
+++ b/packages/meshbay-hub/tests/harness/invite_link_probe.py
@@ -13,6 +13,9 @@ Loads the shipped `app.js` in a real browser with `fetch` stubbed, twice:
signed_out — a link, no session
signed_in — the same link, a session; then the Join button is clicked
+ signed_in_listed — the same, with the hub listing the group once joined, as
+ it does: the group page opens and the address shows its handle
+ (`#/name@owner`, group-link.js)
invite_link_probe.py
@@ -56,7 +59,15 @@ window.fetch = async (url, init = {}) => {
calls.push({ url: u, body: init.body ? String(init.body) : '' });
if (u.includes('/v1/users/me/preferences')) return json({});
if (u.includes('/v1/users/me')) return json({ user_id: 'u-1', role: 'user' });
- if (u.includes('/v1/groups/mine')) return json({ groups: [] });
+ // Joined, the hub lists the group — in the one case that says so. The others
+ // keep an empty list, so the address stays the `#/group/<id>` the Join
+ // button navigated to and is read before the router could rewrite it.
+ if (u.includes('/v1/groups/mine')) return json({ groups:
+ CASE === 'signed_in_listed' && calls.some((c) => c.url.includes('/redeem'))
+ ? [{ id: '__GROUP__', name: 'Some Group', owner_username: 'the-owner',
+ visibility: 'private', created_at: '2026-01-01T00:00:00+00:00',
+ description: '' }]
+ : [] });
if (u.includes('/v1/invite-links/preview')) return json({
group_id: '__GROUP__', group_name: 'Some Group', inviter: 'the-owner',
expires_at: '2099-01-01T00:00:00+00:00', already_member: false });
@@ -65,7 +76,7 @@ window.fetch = async (url, init = {}) => {
if (u.includes('/nodes')) return json({ nodes: [] });
return json({});
};
-if (CASE === 'signed_in') {
+if (CASE.startsWith('signed_in')) {
localStorage.setItem('mb_auth', JSON.stringify({
username: 'invitee-account', userId: 'u-1', token: 'tok', refreshToken: 'ref',
role: 'user' }));
@@ -98,6 +109,12 @@ const text = () => document.getElementById('app').innerText;
out.join_button = Boolean(join);
if (join) { join.click(); await wait(1500); }
out.hash_after_click = location.hash;
+ if (CASE === 'signed_in_listed') {
+ await wait(1500);
+ out.hash_settled = decodeURI(location.hash);
+ out.group_page = Boolean(document.querySelector('.group-header'));
+ out.history_length = history.length;
+ }
out.redeem_bodies = calls.filter((c) => c.url.includes('/redeem')).map((c) => c.body);
}
out.code_in_a_hub_request = calls.some(
@@ -169,7 +186,7 @@ def _run(case: str) -> dict | None:
def main() -> int:
with socketserver.TCPServer(("127.0.0.1", PORT), H) as srv:
threading.Thread(target=srv.serve_forever, daemon=True).start()
- results = [_run("signed_out"), _run("signed_in")]
+ results = [_run("signed_out"), _run("signed_in"), _run("signed_in_listed")]
if not all(results):
print(json.dumps({"error": "no measurement", "got": results}), file=sys.stderr)
return 1
diff --git a/packages/meshbay-hub/tests/harness/window_leak.mjs b/packages/meshbay-hub/tests/harness/window_leak.mjs
index d5185de..f05d8c0 100644
--- a/packages/meshbay-hub/tests/harness/window_leak.mjs
+++ b/packages/meshbay-hub/tests/harness/window_leak.mjs
@@ -41,20 +41,23 @@ let cancelled = false;
const pump = () => {};
const flushQueue = () => {};
const gekRef = { current: null };
+// Not holding: these are the abandoned stream's segments, before any stream_init.
+const heldRef = { current: null };
+const consumeSegment = async () => {};
const window_ = { MeshBayCrypto: { decryptChunkBin: async () => new Uint8Array(4) } };
const silentConsole = { log() {}, warn() {}, error() {} };
const handler = new Function(
'msg', 'cancelled', 'awaitingInitRef', 'outstandingRef', 'queueRef',
- 'entry', 'gekRef', 'pump', 'flushQueue', 'console', 'window',
+ 'entry', 'gekRef', 'pump', 'flushQueue', 'console', 'window', 'heldRef', 'consumeSegment',
`return (async () => {${source}})();`);
const deliver = (n) => Promise.all(
Array.from({ length: n }, (_, i) => handler(
{ file_id: entry.id, segment_index: i, nonce: 'n', ct: 'c' },
cancelled, awaitingInitRef, outstandingRef, queueRef, entry, gekRef,
- pump, flushQueue, silentConsole, window_)));
+ pump, flushQueue, silentConsole, window_, heldRef, consumeSegment)));
const run = async () => {
// The whole window arrives while reinitAt is still awaiting its updateends.
diff --git a/packages/meshbay-hub/tests/test_android_cast.py b/packages/meshbay-hub/tests/test_android_cast.py
new file mode 100644
index 0000000..ebcdec4
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_android_cast.py
@@ -0,0 +1,137 @@
+"""
+Casting in the Android application, pinned by reading the source.
+
+The relay is a port of meshbay-client/src/cast-relay.js and its mitigations are
+the same ones; the JVM tests (CastRelayTest) run it on loopback. What is held
+here is the wiring around it: the same bridge surface as the desktop, order
+kept where order is meaning, the receiver pointed at nothing but the relay, and
+what keeps a cast alive with the screen off switched on only while one runs.
+"""
+
+import re
+from pathlib import Path
+
+import pytest
+
+PACKAGES = Path(__file__).resolve().parents[2]
+MAIN = PACKAGES / "meshbay-android" / "app" / "src" / "main"
+SRC = MAIN / "kotlin" / "org" / "meshbay" / "client"
+CAST = SRC / "cast"
+SHIM = MAIN / "assets" / "bridge" / "meshbay-bridge.js"
+DESKTOP = PACKAGES / "meshbay-client" / "src"
+
+pytestmark = pytest.mark.skipif(not CAST.exists(), reason="android sources not present")
+
+
+def _read(path: Path) -> str:
+ return path.read_text(encoding="utf-8")
+
+
+def test_the_cast_channels_are_the_desktops():
+ def channels(text: str, call: str) -> set[str]:
+ return set(re.findall(rf"{call}\('(cast:[\w:-]+)'", text))
+
+ preload = channels(_read(DESKTOP / "preload.js"), r"ipcRenderer\.invoke")
+ shim = channels(_read(SHIM), "call")
+ kt = _read(CAST / "CastChannels.kt")
+ native = set(re.findall(r'^\s*"(cast:[\w:-]+)" ->', kt, flags=re.M))
+ assert preload and shim == preload, shim ^ preload
+ assert native == preload, native ^ preload
+
+
+def test_no_cast_object_where_casting_cannot_work():
+ """`platform.cast.available` is whether the object exists."""
+ shim = _read(SHIM)
+ assert "...(CAST ? { cast: {" in shim
+ assert "lanCast: CAST" in shim
+ assert "const CAST = ${cast.control.available()}" in _read(SRC / "MainActivity.kt")
+
+
+def test_the_relay_keeps_the_desktop_mitigations():
+ relay = _read(CAST / "CastRelay.kt")
+ desktop = _read(DESKTOP / "cast-relay.js")
+ for name in ("RING_CAP", "PORT_BASE", "PORT_COUNT"):
+ js = re.search(rf"const {name} = (\d+);", desktop).group(1)
+ assert re.search(rf"const val {name} = {js}\b", relay), name
+ assert "InetSocketAddress(address, PORT_BASE + i)" in relay, "bound to the LAN address"
+ # Code, not comments: the comment saying "never 0.0.0.0" is not a bind.
+ code = re.sub(r"/\*.*?\*/", "", relay, flags=re.S)
+ code = re.sub(r"(?m)//.*$", "", code)
+ assert "0.0.0.0" not in code
+ assert 'query["t"] != token' in relay
+ # The preflight before the token: a refusal there reads as a network error.
+ serve = relay.split("private fun serve(", 1)[1]
+ assert serve.index('method == "OPTIONS"') < serve.index('query["t"] != token')
+
+
+def test_what_a_receiver_has_not_read_waits_on_disk():
+ """The desktop drops a fragment once 8 MB wait for a receiver; a fragment
+ is 5 to 10 MB at a film's bitrate, so the television froze for its length
+ (measured: three dropped in the first fifteen seconds). Here the lead waits
+ in a spool file per receiver, deleted with it, and is dropped only past a
+ disk bound."""
+ relay = _read(CAST / "CastRelay.kt")
+ assert "BACKPRESSURE_HIGH" not in relay
+ assert "RandomAccessFile(file, \"rw\").channel" in relay
+ assert "c.waiting() > spoolLimit()" in relay
+ assert "SPOOL_MAX_BYTES = 2L * 1024 * 1024 * 1024" in relay
+ assert "file.delete()" in relay
+ assert 'java.io.File(context.cacheDir, "cast-relay")' in _read(CAST / "CastChannels.kt")
+
+
+def test_the_backlog_is_bounded_in_bytes():
+ """A fragment is a segment, megabytes at a film's bitrate: 64 of them killed
+ the application with an OutOfMemoryError on the emulator."""
+ relay = _read(CAST / "CastRelay.kt")
+ assert "RING_MAX_BYTES" in relay and "ringBytes > RING_MAX_BYTES" in relay
+
+
+def test_the_relay_is_on_wifi_never_the_mobile_network():
+ channels = _read(CAST / "CastChannels.kt")
+ lan = channels.split("private fun lanAddress()", 1)[1]
+ assert "TRANSPORT_WIFI" in lan and "TRANSPORT_ETHERNET" in lan
+ assert "TRANSPORT_CELLULAR" not in lan
+
+
+def test_the_receiver_is_pointed_at_the_relay_and_nothing_else():
+ channels = _read(CAST / "CastChannels.kt")
+ check = channels.split("private fun relayUrl(", 1)[1].split("\n }", 1)[0]
+ assert "asked != ours" in check and "throw Refused" in check
+ assert channels.count("relayUrl(o)") == 2, "connect and reload both go through the check"
+
+
+def test_relay_calls_keep_their_order():
+ """The page does not await each push; on a pool they could overtake."""
+ channels = _read(CAST / "CastChannels.kt")
+ assert '"cast:start", "cast:push", "cast:subtitle",' in channels
+ assert ('"cast:file:begin", "cast:file:write", "cast:file:end", "cast:finish", "cast:stop"'
+ in channels)
+ bridge = _read(SRC / "bridge" / "Bridge.kt")
+ assert "Executors.newSingleThreadExecutor()" in bridge
+ assert "(if (ordered) serial else work).execute" in bridge
+ assert ("fun ordered(frame: BinaryFrame) = frame.channel == BinaryFrame.CAST_PUSH"
+ " || frame.channel == BinaryFrame.CAST_FILE") in _read(SRC / "bridge" / "Channels.kt")
+
+
+def test_screen_off_survival_is_switched_on_only_while_casting_or_playing():
+ activity = _read(SRC / "MainActivity.kt")
+ keep = activity.split("private fun keepAlive()", 1)[1].split("\n }\n", 1)[0]
+ assert "val on = casting || playing" in keep
+ assert "web.keepVisible = on" in keep
+ assert "if (!on) { stopService(service); return }" in keep
+ assert "startForegroundService(service)" in keep
+ assert activity.count("keepVisible =") == 1, "the page is kept visible from one place only"
+ view = _read(SRC / "shell" / "ShellWebView.kt")
+ assert "var keepVisible = false" in view
+ manifest = _read(MAIN / "AndroidManifest.xml")
+ assert 'android:name=".cast.CastService"' in manifest
+ assert 'android:foregroundServiceType="mediaPlayback"' in manifest
+
+
+def test_the_receiver_is_given_what_the_desktop_gives_it():
+ control = _read(CAST / "CastControl.kt")
+ assert "DEFAULT_MEDIA_RECEIVER_APPLICATION_ID" in control
+ assert "MediaInfo.STREAM_TYPE_LIVE" in control
+ assert "TEXT_TRACK_ID = 1L" in control
+ assert "SCAN_DURATION_MS = 6000L" in control
+ assert re.search(r"const SCAN_DURATION_MS = 6000;", _read(DESKTOP / "cast-chromecast.js"))
diff --git a/packages/meshbay-hub/tests/test_android_downloads.py b/packages/meshbay-hub/tests/test_android_downloads.py
new file mode 100644
index 0000000..96da9a4
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_android_downloads.py
@@ -0,0 +1,90 @@
+"""
+Downloads in the Android application, pinned by reading the source.
+
+The page's contract with a native save target is platform.js `nativeSave`: a
+sink with write/close/abort, an `open` only when the target can open the file,
+and nothing that names a path. The Android sink keeps it; what it may open is
+downloads.js `OPENABLE`, held equal here because a second copy of a list of
+safe types is how an `.html` gets opened one day.
+"""
+
+import re
+from pathlib import Path
+
+import pytest
+from spa_source import STATIC
+
+PACKAGES = Path(__file__).resolve().parents[2]
+MAIN = PACKAGES / "meshbay-android" / "app" / "src" / "main"
+SAVE = MAIN / "kotlin" / "org" / "meshbay" / "client" / "save"
+SHIM = MAIN / "assets" / "bridge" / "meshbay-bridge.js"
+
+pytestmark = pytest.mark.skipif(not SAVE.exists(), reason="android sources not present")
+
+
+def _read(path: Path) -> str:
+ return path.read_text(encoding="utf-8")
+
+
+def test_what_may_be_opened_is_the_pages_list():
+ js = _read(STATIC / "downloads.js").split("const OPENABLE = {", 1)[1].split("};", 1)[0]
+ kt = _read(SAVE / "SaveNames.kt").split("val OPENABLE = mapOf(", 1)[1].split("\n )", 1)[0]
+ page = {k: v.split(";")[0] for k, v in re.findall(r"(\w+): '([^']+)'", js)}
+ android = dict(re.findall(r'"(\w+)" to "([^"]+)"', kt))
+ assert page and android == page, set(android.items()) ^ set(page.items())
+
+
+def test_open_is_offered_only_where_the_target_says_so():
+ shim = _read(SHIM)
+ save = shim.split("saveFile: async", 1)[1].split("\n },", 1)[0]
+ assert "if (handle.openable) sink.open" in save
+ sinks = _read(SAVE / "SaveSinks.kt")
+ assert '.put("openable", SaveNames.openableType(shown) != null)' in sinks
+ opening = sinks.split("fun open(id: Long)", 1)[1].split("\n }", 1)[0]
+ assert "SaveNames.openableType(name) ?: throw Refused" in opening
+
+
+def test_the_page_is_told_names_never_uris():
+ sinks = _read(SAVE / "SaveSinks.kt")
+ for fn in ("fun chooseFolder", "fun getFolder", "fun begin"):
+ body = sinks.split(fn, 1)[1].split("\n fun ", 1)[0]
+ returned = re.findall(r'put\("(\w+)"', body)
+ assert not {"uri", "path", "tree"} & set(returned), (fn, returned)
+ assert "return displayName(treeDocument(tree))" in sinks
+
+
+def test_the_save_channels_are_the_desktops():
+ preload = _read(PACKAGES / "meshbay-client" / "src" / "preload.js")
+ shim = _read(SHIM)
+
+ def channels(text: str, call: str) -> set[str]:
+ return set(re.findall(rf"{call}\('((?:save|folder):[\w:-]+)'", text))
+
+ assert channels(shim, "call") == channels(preload, r"ipcRenderer\.invoke")
+ assert "nativeSave: true" in shim
+
+
+def test_an_unfinished_file_never_carries_the_final_name():
+ sinks = _read(SAVE / "SaveSinks.kt")
+ assert '"$wanted.part"' in sinks
+ assert "MediaStore.MediaColumns.IS_PENDING, 1" in sinks
+ assert "MediaStore.MediaColumns.IS_PENDING, 0" in sinks
+ abort = sinks.split("fun abort(id: Long)", 1)[1].split("\n }", 1)[0]
+ assert "delete(sink.uri)" in abort
+ assert "fun cleanUpAfterAKilledProcess" in sinks
+ assert "saves.cleanUpAfterAKilledProcess()" in _read(
+ MAIN / "kotlin" / "org" / "meshbay" / "client" / "MainActivity.kt")
+
+
+def test_a_chosen_folder_that_has_gone_is_not_silently_replaced():
+ begin = _read(SAVE / "SaveSinks.kt").split("fun begin(", 1)[1].split("\n fun ", 1)[0]
+ assert "auto && !(configuredTree != null && tree == null)" in begin
+
+
+def test_writes_are_binary_and_awaited():
+ shim = _read(SHIM)
+ assert "head.setUint32(0, 0x4d424231)" in shim
+ assert "port.postMessage(frame)" in shim
+ bridge = _read(MAIN / "kotlin" / "org" / "meshbay" / "client" / "bridge" / "Bridge.kt")
+ before = bridge.split("TYPE_ARRAY_BUFFER", 1)[0]
+ assert "!isMainFrame" in before, "a binary message must pass the same sender check"
diff --git a/packages/meshbay-hub/tests/test_android_keys.py b/packages/meshbay-hub/tests/test_android_keys.py
new file mode 100644
index 0000000..a00b909
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_android_keys.py
@@ -0,0 +1,74 @@
+"""
+The Android keyring against the desktop's, where the shared vectors cannot see.
+
+`tests/vectors/keyring.json` holds the bytes (and the Android unit tests read
+it). What a vector cannot hold is a *list*: which admin operations may be
+signed at all, and the Argon2 parameters a format change would move. Two
+implementations of a list drift silently — an operation the desktop stopped
+signing at MNP 6.0 and Android still signs is a script in the page driving an
+older node into widening its sharing. So both are read from source and
+compared.
+"""
+
+import re
+from pathlib import Path
+
+import pytest
+
+PACKAGES = Path(__file__).resolve().parents[2]
+MAIN = PACKAGES / "meshbay-android" / "app" / "src" / "main"
+KEYS = MAIN / "kotlin" / "org" / "meshbay" / "client" / "keys"
+CLIENT = PACKAGES / "meshbay-client" / "src"
+SHIM = MAIN / "assets" / "bridge" / "meshbay-bridge.js"
+
+pytestmark = pytest.mark.skipif(not KEYS.exists(), reason="android sources not present")
+
+
+def _read(path: Path) -> str:
+ return path.read_text(encoding="utf-8")
+
+
+def test_the_same_admin_operations_are_signed():
+ js = _read(CLIENT / "transcripts.js")
+ js = js.split("const ADMIN_OPS = new Set([", 1)[1].split("]", 1)[0]
+ kt = _read(KEYS / "Transcripts.kt").split("val ADMIN_OPS = setOf(", 1)[1].split(")", 1)[0]
+ desktop = set(re.findall(r"'([a-z_]+)'", js))
+ android = set(re.findall(r'"([a-z_]+)"', kt))
+ assert desktop and android == desktop, android ^ desktop
+ # The ones MNP 6.0 took away must not come back on either side.
+ assert not {"root_add", "root_update", "group_attach"} & android
+
+
+def test_the_argon2_parameters_are_the_desktops():
+ js = _read(CLIENT / "keyring.js")
+ m = re.search(r"memory: (\d+), passes: (\d+), parallelism: (\d+), tagLength: (\d+)", js)
+ kt = _read(KEYS / "Kdf.kt")
+ want = dict(zip(("MEMORY_KIB", "PASSES", "PARALLELISM", "TAG"), m.groups()))
+ for name, value in want.items():
+ assert re.search(rf"const val ARGON2_{name} = {value}\b", kt), name
+
+
+def test_the_shim_offers_the_desktops_key_surface():
+ preload = _read(CLIENT / "preload.js")
+ shim = _read(SHIM)
+
+ def channels(text: str, call: str) -> set[str]:
+ return set(re.findall(rf"{call}\('((?:keys|device|secrets):[\w:-]+)'", text))
+
+ assert channels(shim, "call") == channels(preload, r"ipcRenderer\.invoke")
+
+
+def test_signing_is_by_kind_and_no_private_key_is_returned():
+ channels = _read(KEYS.parent / "bridge" / "KeyChannels.kt")
+ assert '"keys:sign" -> keyring.signAs(' in channels
+ # No channel hands the page a stored key: the store's slots are never a
+ # return value, and identity/mint/open answer with public keys.
+ assert "secrets.read()" in channels # the keyring's load, and nothing else
+ assert channels.count("secrets.read()") == 1
+ assert '"pkEdB64"' in channels and '"skEd"' not in channels
+
+
+def test_widening_browser_access_is_confirmed_natively():
+ channels = _read(KEYS.parent / "bridge" / "KeyChannels.kt")
+ branch = channels.split('"keys:set-browser-access" ->', 1)[1].split('"keys:created-here"', 1)[0]
+ assert 'confirm("native.browser_access_confirm")' in branch
diff --git a/packages/meshbay-hub/tests/test_android_shell.py b/packages/meshbay-hub/tests/test_android_shell.py
new file mode 100644
index 0000000..e569bb7
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_android_shell.py
@@ -0,0 +1,223 @@
+"""
+The Android shell's security contract, pinned by reading its source.
+
+The same treatment `test_desktop_shell.py` gives the Electron application, for
+the same reason: an emulator or a phone is what proves the shell runs, and the
+suite has neither. What this proves is that the properties the design depends
+on (docs/MESHBAY_DESIGN.md §8.2, as the Android plan restates them) are in the
+source, and it fails when one is removed. The JVM unit tests run too when an
+Android SDK is present.
+"""
+
+import os
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+PACKAGES = Path(__file__).resolve().parents[2]
+ANDROID = PACKAGES / "meshbay-android"
+APP = ANDROID / "app"
+SRC = APP / "src" / "main" / "kotlin" / "org" / "meshbay" / "client"
+SHIM = APP / "src" / "main" / "assets" / "bridge" / "meshbay-bridge.js"
+CLIENT = PACKAGES / "meshbay-client"
+
+pytestmark = pytest.mark.skipif(not ANDROID.exists(), reason="android sources not present")
+
+
+def _read(path: Path) -> str:
+ return path.read_text(encoding="utf-8")
+
+
+def _kotlin() -> str:
+ return "\n".join(_read(p) for p in sorted(SRC.rglob("*.kt")))
+
+
+def _strip_js_comments(source: str) -> str:
+ source = re.sub(r"/\*.*?\*/", "", source, flags=re.S)
+ return re.sub(r"(?m)//.*$", "", source)
+
+
+# ── The page comes from the package ──────────────────────────────────────────
+
+def test_the_interface_is_copied_from_its_single_source_and_never_committed():
+ build = _read(APP / "build.gradle.kts")
+ assert '"../meshbay-hub/src/meshbay_hub/static"' in build
+ # The desktop application's page: the hub's carries a /a/<hash>/ prefix
+ # that would point back at the hub.
+ assert '"../meshbay-client/scripts/index.html"' in build
+ assert "deleteRecursively()" in build, "a stale file could survive a rebuild"
+ assert "addGeneratedSourceDirectory" in build
+ assert "build/" in _read(ANDROID / ".gitignore")
+ assert not (APP / "src" / "main" / "assets" / "ui").exists(), \
+ "a copy of the interface is in the source tree, which is how a fork begins"
+
+
+def test_the_webview_loads_the_package_and_nothing_else():
+ activity = _read(SRC / "MainActivity.kt")
+ loads = re.findall(r"\.loadUrl\(([^)]*)\)", activity)
+ assert loads and set(loads) == {"UiAssets.START"}, loads
+ assert "loadDataWithBaseURL" not in activity and "loadData(" not in activity
+ # The hub never becomes the document origin; a link out leaves the app.
+ assert "shouldOverrideUrlLoading" in activity and "openExternally" in activity
+
+
+def test_the_policy_is_the_desktop_policy_sent_as_a_header():
+ """One interface, one policy for the packaged builds — and the desktop's
+ is already held to the hub's by test_the_two_policies_stay_in_step."""
+ def directives(text: str, start: str, end: str) -> dict[str, str]:
+ body = text.split(start, 1)[1].split(end, 1)[0]
+ out = {}
+ for d in re.findall(r"[`\"]([a-z-]+(?: [^`\"]*)?)[`\"]", body):
+ d = d.replace("${RECAPTCHA_SRC}", "$RECAPTCHA_SRC")
+ out[d.split()[0]] = d
+ return out
+
+ desktop = directives(_read(CLIENT / "src" / "main.js"), "const CSP = [", "].join")
+ kotlin = _read(SRC / "shell" / "UiAssets.kt")
+ android = directives(kotlin, "val CSP = listOf(", ").joinToString")
+ assert desktop and android == desktop, set(android.items()) ^ set(desktop.items())
+
+ assets = _read(SRC / "shell" / "UiAssets.kt")
+ assert '"Content-Security-Policy" to CSP' in assets
+ recaptcha = 'RECAPTCHA_SRC = "https://www.google.com https://www.gstatic.com"'
+ assert recaptcha in assets
+ markup = re.sub(r"<!--.*?-->", "", _read(CLIENT / "scripts" / "index.html"), flags=re.S)
+ assert "Content-Security-Policy" not in markup
+
+
+def test_the_asset_handler_cannot_be_walked_out_of():
+ assets = _read(SRC / "shell" / "UiAssets.kt")
+ assert '".."' in assets and 'val asset = "ui/"' in assets
+
+
+def test_plain_http_is_refused_except_to_loopback():
+ hub = _read(SRC / "hub" / "HubClient.kt")
+ assert "The hub address must be https" in hub
+ assert 'Regex("^http://(localhost|127\\\\.)")' in hub
+ config = _read(APP / "src" / "main" / "res" / "xml" / "network_security_config.xml")
+ assert '<base-config cleartextTrafficPermitted="false"' in config
+ allowed = re.findall(r"<domain[^>]*>([^<]+)</domain>", config)
+ assert set(allowed) == {"localhost", "127.0.0.1"}
+
+
+def test_the_page_reaches_the_signed_in_hub_only():
+ hub = _read(SRC / "hub" / "HubClient.kt")
+ assert "Refused: not this hub" in hub and "sameOrigin(target, hub)" in hub
+ assert ".followRedirects(false)" in hub, "a redirect would carry the token elsewhere"
+
+
+# ── The bridge ──────────────────────────────────────────────────────────────
+
+def test_no_javascript_interface_is_ever_added():
+ """addJavascriptInterface injects into every frame of every origin."""
+ for path in APP.rglob("*.kt"):
+ assert "addJavascriptInterface" not in _read(path), path
+
+
+def test_every_message_is_checked_for_our_top_level_document():
+ bridge = _read(SRC / "bridge" / "Bridge.kt")
+ check = bridge.split("override fun onPostMessage", 1)[1].split("work.execute", 1)[0]
+ assert "!isMainFrame" in check and "UiAssets.ORIGIN" in check
+ activity = _read(SRC / "MainActivity.kt")
+ assert "addWebMessageListener(web, Bridge.PORT, setOf(UiAssets.ORIGIN)" in activity
+ assert re.search(r"addDocumentStartJavaScript\(web, .*setOf\(UiAssets\.ORIGIN\)\)", activity)
+
+
+def _shim_channels() -> set[str]:
+ return set(re.findall(r"call\('([\w:-]+)'", _strip_js_comments(_read(SHIM))))
+
+
+def test_the_shim_offers_desktop_channels_and_native_answers_each():
+ preload_js = _read(CLIENT / "src" / "preload.js")
+ preload = set(re.findall(r"ipcRenderer\.invoke\('([\w:-]+)'", preload_js))
+ native = set()
+ for path in (SRC / "bridge" / "Channels.kt", SRC / "bridge" / "KeyChannels.kt",
+ SRC / "cast" / "CastChannels.kt"):
+ native |= set(re.findall(r'^\s*"([\w:-]+)" ->', _read(path), flags=re.M))
+ shim = _shim_channels()
+ assert shim, "no channel found in the shim"
+ assert shim <= preload, f"channels the desktop does not have: {shim - preload}"
+ assert shim == native, f"shim and native disagree: {shim ^ native}"
+
+
+def test_what_a_phone_does_not_have_is_absent_not_refusing():
+ """platform.js decides what to show from whether an object exists
+ (`platform.node.available`, `platform.folder.available`, …): an object that
+ only refused would put screens on the page that fail when used."""
+ shim = _strip_js_comments(_read(SHIM))
+ exposed = shim.split("const meshbay = {", 1)[1].split("\n };", 1)[0]
+ for absent in ("node:", "rootPicker:", "minimizeToTray:", "setTrayLabels:"):
+ assert absent not in exposed, absent
+ assert "nodeAdmin: false" in exposed and "localFolders: false" in exposed
+
+
+def test_the_bridge_is_frozen_and_the_port_hidden():
+ shim = _strip_js_comments(_read(SHIM))
+ assert "delete window.meshbayNative" in shim
+ assert "window.top !== window" in shim
+ assert "writable: false, configurable: false" in shim
+ assert "Object.freeze" in shim
+
+
+def test_file_system_access_is_removed_from_the_page():
+ """The WebView exposes it (spike S-1) and cannot back it with anything."""
+ shim = _strip_js_comments(_read(SHIM))
+ for name in ("showDirectoryPicker", "showSaveFilePicker", "showOpenFilePicker"):
+ assert f"'{name}'" in shim, name
+
+
+def test_the_hub_address_is_injected_not_fetched():
+ """platform.hubBase() is called while modules load, before anything can await."""
+ assert "HUB_BASE" in _strip_js_comments(_read(SHIM))
+ assert "const HUB_BASE = ${JSONObject.quote(hub.base)}" in _read(SRC / "MainActivity.kt")
+
+
+def test_the_node_setup_welcome_needs_a_node():
+ """A phone has a bridge and no node: with no groups yet it must see the
+ invitations and the join link, not a node wizard it cannot finish."""
+ from spa_source import STATIC
+ app = _read(STATIC / "app.js")
+ home = app.split("function HomePage(", 1)[1].split("\n}\n", 1)[0]
+ gate = home.split("<${SetupWelcome}", 1)[0]
+ assert "platform.capabilities.nodeAdmin" in gate
+ assert "platform.isNative" not in gate
+
+
+# ── The window ──────────────────────────────────────────────────────────────
+
+def test_nothing_is_granted_and_video_may_go_fullscreen():
+ activity = _read(SRC / "MainActivity.kt")
+ assert "onPermissionRequest(request: PermissionRequest) = request.deny()" in activity
+ # Without a custom view, requestFullscreen() never settles (CLAUDE.md).
+ assert "override fun onShowCustomView" in activity
+ assert "override fun onHideCustomView" in activity
+
+
+def test_no_backup_carries_the_keys_away():
+ manifest = _read(APP / "src" / "main" / "AndroidManifest.xml")
+ assert 'android:allowBackup="false"' in manifest
+ assert 'android:dataExtractionRules="@xml/data_extraction_rules"' in manifest
+
+
+def test_the_gradle_distribution_is_pinned_by_checksum():
+ props = _read(ANDROID / "gradle" / "wrapper" / "gradle-wrapper.properties")
+ assert re.search(r"^distributionSha256Sum=[0-9a-f]{64}$", props, flags=re.M)
+
+
+def test_the_version_is_the_packages_version():
+ """All packages share one version (CLAUDE.md); this one reads it rather
+ than writing it a second time."""
+ build = _read(APP / "build.gradle.kts")
+ assert 'rootDir.resolve("../meshbay-client/package.json")' in build
+ assert not re.search(r'versionName = "\d', build)
+
+
+@pytest.mark.skipif(not os.environ.get("ANDROID_HOME") or shutil.which("java") is None,
+ reason="no Android SDK in the environment")
+def test_the_jvm_unit_tests_pass():
+ result = subprocess.run(["./gradlew", "--no-daemon", "-q", "testDebugUnitTest"],
+ cwd=ANDROID, capture_output=True, text=True, timeout=900)
+ assert result.returncode == 0, result.stdout[-3000:] + result.stderr[-3000:]
diff --git a/packages/meshbay-hub/tests/test_cast_discovery.py b/packages/meshbay-hub/tests/test_cast_discovery.py
new file mode 100644
index 0000000..8d156ff
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_cast_discovery.py
@@ -0,0 +1,152 @@
+"""
+Cast receivers are listed as they answer, not at the end of the scan.
+
+The scan runs its full length because a receiver coming back from a reset can
+take several seconds to answer, but most answer within two; a picker that showed
+nothing until the end was slow every time it was opened. These tests run the real
+`CastChromecast` with mDNS replaced by a stub that answers on cue, and the clock
+shortened, so what they measure is what the page's poll would see.
+"""
+
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+CLIENT = Path(__file__).resolve().parents[2] / "meshbay-client"
+CHROMECAST = CLIENT / "src" / "cast-chromecast.js"
+
+pytestmark = pytest.mark.skipif(
+ shutil.which("node") is None or not CHROMECAST.exists(),
+ reason="node or the desktop client sources are not available")
+
+# Stubs the two dependencies at `require` time, and makes six seconds of scan
+# last sixty milliseconds by scaling every timer the module arms.
+SCRIPT = r"""
+const Module = require('node:module');
+const browsers = [];
+const realLoad = Module._load;
+Module._load = function (request, ...rest) {
+ if (request === 'bonjour-service') {
+ return { Bonjour: class {
+ find(_q, onUp) {
+ const b = { onUp, stopped: false, stop() { this.stopped = true; } };
+ browsers.push(b);
+ return b;
+ }
+ } };
+ }
+ if (request === 'castv2-client') return { Client: class {}, DefaultMediaReceiver: {} };
+ return realLoad.call(this, request, ...rest);
+};
+const realSetTimeout = global.setTimeout;
+global.setTimeout = (fn, ms, ...a) => realSetTimeout(fn, ms / 100, ...a);
+const wait = (ms) => new Promise((r) => realSetTimeout(r, ms));
+
+const CastChromecast = require(process.argv[2]);
+const tv = (id) => ({ name: id, txt: { id, fn: `TV ${id}` },
+ addresses: ['10.0.0.9'], port: 8009 });
+
+(async () => {
+ const cc = new CastChromecast();
+ const out = {};
+
+ cc.startScan();
+ out.atStart = cc.devices();
+ browsers[0].onUp(tv('a'));
+ out.afterFirstAnswer = cc.devices();
+ await wait(100);
+ out.afterScan = cc.devices();
+ out.firstBrowserStopped = browsers[0].stopped;
+
+ // A second scan started over a first: the first's timer must not end it.
+ cc.startScan();
+ await wait(40);
+ cc.startScan();
+ await wait(40);
+ out.restartedStillScanning = cc.devices().scanning;
+ out.restartClearedOldDevices = cc.devices().devices.length === 0;
+ await wait(60);
+ out.restartedEnds = !cc.devices().scanning;
+ console.log(JSON.stringify(out));
+})();
+"""
+
+
+@pytest.fixture(scope="module")
+def run(tmp_path_factory):
+ script = tmp_path_factory.mktemp("cd") / "discover.cjs"
+ script.write_text(SCRIPT, encoding="utf-8")
+ proc = subprocess.run(
+ ["node", str(script), str(CHROMECAST)],
+ capture_output=True, text=True, encoding="utf-8", timeout=60)
+ assert proc.returncode == 0, proc.stderr
+ return json.loads(proc.stdout)
+
+
+def test_a_receiver_is_listed_before_the_scan_ends(run):
+ assert run["atStart"] == {"devices": [], "scanning": True}
+ assert run["afterFirstAnswer"]["scanning"] is True
+ assert [d["name"] for d in run["afterFirstAnswer"]["devices"]] == ["TV a"]
+
+
+def test_the_scan_ends_on_its_own_and_keeps_what_it_found(run):
+ assert run["afterScan"]["scanning"] is False
+ assert [d["id"] for d in run["afterScan"]["devices"]] == ["a"]
+ assert run["firstBrowserStopped"] is True
+
+
+def test_a_new_scan_is_not_cut_short_by_the_one_it_replaced(run):
+ """
+ The old code left the first scan's timer armed, and it stopped whichever
+ browser was current when it fired — the new one, two thirds early.
+ """
+ assert run["restartedStillScanning"] is True
+ assert run["restartClearedOldDevices"] is True
+ assert run["restartedEnds"] is True
+
+
+def test_the_local_player_is_silent_while_casting():
+ """The local element keeps playing while casting — its playhead paces the
+ stream the relay forwards — so it must not keep its sound: a phone in the
+ room doubled the television's audio, screen off included. Whatever the
+ viewer had set comes back when the cast ends."""
+ from spa_source import STATIC
+ player = (STATIC / "video-player.js").read_text(encoding="utf-8")
+ effect = player.split("const mutedBeforeCastRef = useRef(null);", 1)[1]
+ effect = effect.split("}, [castActive]);", 1)[0]
+ assert "v.muted = true;" in effect
+ assert "mutedBeforeCastRef.current = v.muted;" in effect
+ assert "v.muted = mutedBeforeCastRef.current;" in effect
+ assert "pause()" not in effect, "pausing would stop the stream the receiver is playing"
+
+
+def test_the_player_is_a_remote_while_casting():
+ """Phone and television do not play in step, so while a receiver plays the
+ film the scrubber shows the receiver's position (stream time plus where
+ the stream started) and every seek goes through the ordinary seek, which
+ restarts the relay and reloads the receiver there. The copy-URL cast has
+ no receiver to read and keeps the local player."""
+ from spa_source import STATIC
+ player = (STATIC / "video-player.js").read_text(encoding="utf-8")
+ remote = player.split("// ── Remote ──", 1)[1].split("return html`", 1)[0]
+ assert "castDeviceName !== null && platform.cast.canControl" in remote
+ assert "streamStartRef.current + c.position" in remote
+ # Until the restart lands, the receiver's position is the old stream's.
+ assert "!castRestartPendingRef.current" in remote
+ assert "requestSeekRef.current(target)" in remote
+ assert "platform.cast.chromecastPause()" in remote
+ assert "platform.cast.chromecastPlay()" in remote
+ # A language change restarts the stream where the television is.
+ assert "remoteFilmPosRef.current ?? (v && v.currentTime)" in player
+
+
+def test_every_locale_names_the_remote_controls():
+ from spa_source import STATIC
+ keys = ["cast.casting_to", "cast.seek", "cast.waiting", "cast.back30", "cast.fwd30", "cast.play", "cast.pause"]
+ for f in sorted((STATIC / "locales").glob("*.js")):
+ text = f.read_text(encoding="utf-8")
+ for k in keys:
+ assert f"'{k}':" in text, f"{f.name} lacks {k}"
diff --git a/packages/meshbay-hub/tests/test_cast_files.py b/packages/meshbay-hub/tests/test_cast_files.py
new file mode 100644
index 0000000..8f51d80
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_cast_files.py
@@ -0,0 +1,372 @@
+"""
+Whole files on a cast receiver — photos and music tracks — and the television
+a session casts to.
+
+A file takes a different road to the television than a film: no stream, one
+file at a time, handed to the relay in pieces (begin, writes, end), served at
+`/file` with its cover at `/cover`, and loaded by the default media receiver
+as a picture or as a music track. The page scales and re-encodes a photo
+first (cast-session.js); a track goes as it is stored.
+
+The first half runs the desktop relay itself, as test_cast_subtitles.py does:
+it is plain Node with no dependencies. The file is behind the same token as
+the stream, its address changes with every file — a receiver handed the same
+URL twice shows what it already has — ranges are honoured, because that is how
+a receiver seeks in a track, and only a picture or a sound is served as one.
+
+The second half holds the wiring: what the receiver loads is the shell's to
+say, never the page's; Android accepts no URL but the relay's own; a
+television chosen anywhere is the one a film opens on, with the player as its
+remote from the start; and the music bar drives the television once one is
+chosen.
+"""
+
+import json
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+PACKAGES = Path(__file__).resolve().parents[2]
+STATIC = PACKAGES / "meshbay-hub" / "src" / "meshbay_hub" / "static"
+DESKTOP = PACKAGES / "meshbay-client" / "src"
+RELAY = DESKTOP / "cast-relay.js"
+CHROMECAST = DESKTOP / "cast-chromecast.js"
+ANDROID_MAIN = PACKAGES / "meshbay-android" / "app" / "src" / "main"
+ANDROID_SRC = ANDROID_MAIN / "kotlin"
+CLIENT = ANDROID_SRC / "org" / "meshbay" / "client"
+CAST = CLIENT / "cast"
+SHIM = ANDROID_MAIN / "assets" / "bridge" / "meshbay-bridge.js"
+
+
+def _read(path: Path) -> str:
+ return path.read_text(encoding="utf-8")
+
+
+RELAY_SCRIPT = r"""
+const http = require('node:http');
+const CastRelay = require(process.argv[2]);
+const get = (url, headers = {}) => new Promise((resolve, reject) => {
+ http.get(url, { headers }, (res) => {
+ const parts = [];
+ res.on('data', (c) => parts.push(c));
+ res.on('end', () => resolve({ status: res.statusCode, headers: res.headers,
+ body: Buffer.concat(parts).toString('hex') }));
+ }).on('error', reject);
+});
+const refused = async (f) => { try { await f(); return false; } catch { return true; } };
+const send = async (relay, bytes, opts) => {
+ await relay.beginFile({ size: bytes.length, ...opts });
+ for (let at = 0; at < bytes.length; at += 3) relay.writeFile(bytes.subarray(at, at + 3));
+ return relay.endFile();
+};
+(async () => {
+ const relay = new CastRelay();
+ const out = {};
+ out.activeBefore = relay.active;
+ out.htmlRefused = await refused(() => relay.beginFile({ type: 'text/html', size: 3 }));
+ out.activeAfterRefusal = relay.active;
+
+ const jpeg = Buffer.from([0xff, 0xd8, 1, 2, 0xff, 0xd9]);
+ const first = await send(relay, jpeg, { type: 'image/jpeg' });
+ out.activeAfterPhoto = relay.active;
+ out.firstUrl = first.url;
+ out.photo = await get(first.url);
+ out.badToken = (await get(first.url.replace(/t=[0-9a-f]+/, 't=x'))).status;
+ out.photoMeta = relay.fileMeta;
+
+ // A track, its cover and what to show with it; read back whole and by range.
+ const track = Buffer.from([...Array(20).keys()]);
+ const second = await send(relay, track, {
+ type: 'audio/flac', title: 'A Song', artist: 'Some Band', album: 'An Album',
+ cover: { bytes: Buffer.from([0xff, 0xd8, 7, 0xff, 0xd9]), type: 'image/jpeg' } });
+ out.secondUrl = second.url;
+ out.trackType = relay.fileType;
+ out.trackMeta = relay.fileMeta;
+ out.whole = await get(second.url);
+ out.range = await get(second.url, { Range: 'bytes=5-9' });
+ out.tail = await get(second.url, { Range: 'bytes=15-' });
+ out.beyond = (await get(second.url, { Range: 'bytes=50-60' })).status;
+ out.cover = await get(relay.fileMeta.cover);
+
+ // Fewer bytes than announced is not a file; more is refused as they come.
+ await relay.beginFile({ type: 'audio/mpeg', size: 10 });
+ relay.writeFile(Buffer.from([1, 2, 3]));
+ out.shortRefused = await refused(() => relay.endFile());
+ await relay.beginFile({ type: 'audio/mpeg', size: 2 });
+ out.longRefused = await refused(() => relay.writeFile(Buffer.from([1, 2, 3])));
+ out.stillServed = (await get(second.url)).status;
+
+ await relay.start({});
+ out.fileAfterFilm = relay.fileUrl;
+ await send(relay, jpeg, { type: 'image/jpeg' });
+ await relay.stop();
+ out.fileAfterStop = relay.fileUrl;
+ console.log(JSON.stringify(out));
+})().catch((e) => { console.error(e); process.exit(1); });
+"""
+
+
+@pytest.fixture(scope="module")
+def relay_run(tmp_path_factory):
+ if shutil.which("node") is None or not RELAY.exists():
+ pytest.skip("node or the desktop client sources are not available")
+ script = tmp_path_factory.mktemp("cf") / "relay.cjs"
+ script.write_text(RELAY_SCRIPT, encoding="utf-8")
+ proc = subprocess.run(["node", str(script), str(RELAY)],
+ capture_output=True, text=True, encoding="utf-8", timeout=30)
+ assert proc.returncode == 0, proc.stderr
+ return json.loads(proc.stdout)
+
+
+def test_a_file_starts_the_relay_and_is_served_behind_its_token(relay_run):
+ assert relay_run["activeBefore"] is False
+ assert relay_run["activeAfterPhoto"] is True
+ photo = relay_run["photo"]
+ assert photo["status"] == 200
+ assert photo["headers"]["content-type"] == "image/jpeg"
+ assert photo["headers"]["cache-control"] == "no-store"
+ assert photo["body"] == "ffd80102ffd9"
+ assert relay_run["badToken"] == 403
+ assert relay_run["photoMeta"]["cover"] is None
+
+
+def test_every_file_has_its_own_address(relay_run):
+ assert re.search(r"/file\?t=[0-9a-f]{32}&v=\d+$", relay_run["firstUrl"])
+ assert relay_run["secondUrl"] != relay_run["firstUrl"]
+
+
+def test_a_track_is_served_with_its_cover_and_what_it_is(relay_run):
+ assert relay_run["trackType"] == "audio/flac"
+ meta = relay_run["trackMeta"]
+ assert (meta["title"], meta["artist"], meta["album"]) == ("A Song", "Some Band", "An Album")
+ assert re.search(r"/cover\?t=[0-9a-f]{32}&v=\d+$", meta["cover"])
+ assert relay_run["cover"]["status"] == 200
+ assert relay_run["cover"]["body"] == "ffd807ffd9"
+ assert relay_run["whole"]["body"] == bytes(range(20)).hex()
+ assert relay_run["whole"]["headers"]["accept-ranges"] == "bytes"
+
+
+def test_a_receiver_seeks_in_a_track_by_range(relay_run):
+ r = relay_run["range"]
+ assert r["status"] == 206
+ assert r["headers"]["content-range"] == "bytes 5-9/20"
+ assert r["body"] == bytes(range(5, 10)).hex()
+ tail = relay_run["tail"]
+ assert tail["status"] == 206 and tail["body"] == bytes(range(15, 20)).hex()
+ assert relay_run["beyond"] == 416
+
+
+def test_only_a_whole_picture_or_sound_is_served(relay_run):
+ assert relay_run["htmlRefused"] is True
+ assert relay_run["activeAfterRefusal"] is False, "a refused file starts nothing"
+ assert relay_run["shortRefused"] is True
+ assert relay_run["longRefused"] is True
+ assert relay_run["stillServed"] == 200, "a failed send leaves the shown file alone"
+
+
+def test_a_film_or_a_stop_takes_the_file_down(relay_run):
+ assert relay_run["fileAfterFilm"] is None
+ assert relay_run["fileAfterStop"] is None
+
+
+def test_the_receiver_loads_a_photo_as_a_picture_and_a_track_as_music():
+ if shutil.which("node") is None or not CHROMECAST.exists():
+ pytest.skip("node or the desktop client sources are not available")
+ script = (
+ "const Module = require('node:module');"
+ "const real = Module._load;"
+ "Module._load = function (r, ...a) {"
+ " if (r === 'bonjour-service') return { Bonjour: class {} };"
+ " if (r === 'castv2-client') return { Client: class {}, DefaultMediaReceiver: {} };"
+ " return real.call(this, r, ...a); };"
+ f"const {{ mediaFor, loadOptionsFor }} = require({json.dumps(str(CHROMECAST))});"
+ "const meta = { title: 'A Song', artist: 'Some Band', album: 'An Album',"
+ " cover: 'http://x/cover?t=a&v=2' };"
+ "console.log(JSON.stringify({"
+ " photo: mediaFor('http://x/file?t=a&v=1', null,"
+ " { contentType: 'image/jpeg', meta: { cover: null } }),"
+ " track: mediaFor('http://x/file?t=a&v=2', null, { contentType: 'audio/flac', meta }),"
+ " from: loadOptionsFor(null, 42.5),"
+ " film: mediaFor('http://x/stream.mp4?t=a', null, null),"
+ " filmOptions: loadOptionsFor(null, 0),"
+ " legacy: mediaFor('http://x/stream.mp4?t=a', null) }));")
+ proc = subprocess.run(["node", "-e", script], capture_output=True, text=True,
+ encoding="utf-8", timeout=30)
+ assert proc.returncode == 0, proc.stderr
+ out = json.loads(proc.stdout)
+ assert out["photo"]["contentType"] == "image/jpeg"
+ assert out["photo"]["streamType"] == "NONE"
+ assert "tracks" not in out["photo"]
+ track = out["track"]
+ assert track["contentType"] == "audio/flac" and track["streamType"] == "BUFFERED"
+ assert track["metadata"] == {"metadataType": 3, "title": "A Song", "artist": "Some Band",
+ "albumName": "An Album",
+ "images": [{"url": "http://x/cover?t=a&v=2"}]}
+ assert out["from"]["currentTime"] == 42.5
+ assert "currentTime" not in out["filmOptions"]
+ assert out["film"] == out["legacy"], "a film is loaded exactly as before"
+ assert out["film"]["streamType"] == "LIVE" and out["film"]["contentType"] == "video/mp4"
+
+
+def test_the_shell_not_the_page_says_what_the_receiver_loads():
+ """The page names a URL; what it is, is the relay's to say. A page that
+ could name the content type could have a television load the stream as
+ anything at all."""
+ main = _read(DESKTOP / "main.js")
+ load_of = main.split("const loadOf = ", 1)[1].split("\n\n", 1)[0]
+ assert "mediaUrl === castRelay.fileUrl" in load_of
+ assert "contentType: castRelay.fileType, meta: castRelay.fileMeta" in load_of
+ assert "subtitle: null" in load_of, "a file carries no subtitle"
+ assert main.count("loadOf(mediaUrl, subtitle)") == 2, "connect and reload both"
+ # A start position means something for a file only; a film starts where
+ # its relay does.
+ assert main.count("l.file ? startAt : 0") == 2
+
+
+def test_android_accepts_the_relays_file_and_nothing_else():
+ if not CAST.exists():
+ pytest.skip("android sources not present")
+ channels = _read(CAST / "CastChannels.kt")
+ check = channels.split("private fun relayUrl(", 1)[1].split("\n }", 1)[0]
+ assert "asked != ours && asked != relay.fileUrl" in check
+ assert 'put("contentType", relay.fileType).put("meta", relay.fileMeta()' in channels
+ assert "url == relay.fileUrl -> null" in channels, "a file carries no subtitle"
+ assert 'if (url == relay.fileUrl) maxOf(0.0, o.optDouble("startAt", 0.0)) else 0.0' in channels
+ # A file is not a cast that has to survive the screen going off.
+ begin = channels.split('"cast:file:begin" ->', 1)[1].split('"cast:file:end"', 1)[0]
+ assert "onCasting" not in begin
+ relay = _read(CAST / "CastRelay.kt")
+ assert '"/file" -> serveFile(out, socket, range)' in relay
+ assert '"/cover" -> serveCover(out, socket)' in relay
+ serve = relay.split("private fun serve(", 1)[1]
+ assert serve.index('query["t"] != token') < serve.index('"/file"'), "behind the token"
+ # On disk, never held: a long lossless track is a few hundred megabytes.
+ assert 'File(spoolDir, "file-${fileSeq.incrementAndGet()}.bin")' in relay
+ assert "java.io.FileOutputStream(slot.path)" in relay
+ control = _read(CAST / "CastControl.kt")
+ assert "MediaInfo.STREAM_TYPE_NONE" in control
+ assert "MediaMetadata.MEDIA_TYPE_PHOTO" in control
+ assert "MediaMetadata.MEDIA_TYPE_MUSIC_TRACK" in control
+ assert "MediaInfo.STREAM_TYPE_BUFFERED" in control
+ assert "setCurrentTime((startAt * 1000).toLong())" in control
+ assert "MediaSeekOptions.Builder().setPosition(" in control
+ # Loaded is shown: a photo never reaches PLAYING, and waiting for it
+ # would hold every photo for the full fifteen seconds.
+ load = control.split("private fun load(", 1)[1]
+ assert load.index("if (photo) return") < load.index("PLAY_WAIT_MS")
+
+
+def test_a_file_crosses_the_android_bridge_in_binary_pieces():
+ """One message the size of a lossless track would be the WebView's to
+ refuse; a file goes in pieces of a megabyte, as binary frames where the
+ WebView has them."""
+ if not SHIM.exists():
+ pytest.skip("android sources not present")
+ shim = _read(SHIM)
+ assert "const CAST_FILE = 3;" in shim
+ assert "const FILE_PIECE = 1024 * 1024;" in shim
+ assert ("BINARY ? sendBinary(CAST_FILE, 0, piece) : call('cast:file:write', base64Of(piece))"
+ in shim)
+ assert "const val CAST_FILE = 3" in _read(CLIENT / "save" / "SaveNames.kt")
+ channels = _read(CLIENT / "bridge" / "Channels.kt")
+ assert "BinaryFrame.CAST_FILE -> " in channels and ".writeFile(frame.bytes" in channels
+
+
+def test_a_television_chosen_anywhere_takes_the_next_film():
+ """The player opens as the remote of a television chosen before it, the
+ cast pending until the first segment exactly as a restart is; choosing one
+ in the player keeps it for the session, and stopping there forgets it."""
+ player = _read(STATIC / "video-player.js")
+ assert ("const [autoCast] = useState(() => "
+ "(castSession.supported ? castSession.device : null));") in player
+ assert "useState(Boolean(autoCast))" in player
+ assert "castActiveRef = useRef(Boolean(autoCast))" in player
+ assert "castRestartPendingRef = useRef(Boolean(autoCast))" in player
+ assert "castDeviceRef = useRef(autoCast)" in player
+ assert "useState(autoCast ? autoCast.name : null)" in player
+ stop = player.split("const stopCast = async () => {", 1)[1].split("};", 1)[0]
+ assert "castSession.forget()" in stop
+ assert "castSession.choose(d);" in player
+ assert "castSession.claim('video')" in player
+
+
+def test_the_cast_button_is_where_the_media_are():
+ """Videos' toolbar, the Photos landing, a photo album's bar and Music's
+ toolbar are drawn by the group page and the search page alike, so one
+ button in each covers both. On the Photos landing the button keeps a
+ toolbar Search would otherwise hide. The music bar has its own, opening
+ upward from the bottom of the window."""
+ videos = _read(STATIC / "video-app.js")
+ assert "<${CastButton} />" in videos.split('<div class="video-toolbar">', 1)[1]
+ photos = _read(STATIC / "photos-app.js")
+ landing = photos.split("function PhotosApp(", 1)[1]
+ assert "(!hideFilter || castSession.supported) && html`" in landing
+ assert "<${CastButton} />" in landing.split('<div class="photo-toolbar">', 1)[1]
+ album = photos.split("function AlbumView(", 1)[1]
+ assert "<${CastButton}" in album
+ lightbox = photos.split("function Lightbox(", 1)[1].split("function AlbumView(", 1)[0]
+ assert '<${CastButton} variant="overlay"' in lightbox
+ assert "if (castDevice && blobUrl && blob) showPhoto(blob);" in lightbox
+ music = _read(STATIC / "music-app.js")
+ assert "<${CastButton} />" in music.split('<div class="video-toolbar">', 1)[1]
+ bar = _read(STATIC / "music-player.js")
+ assert '<${CastButton} cls="music-player-btn" up />' in bar
+ # The group page draws them through the app registry, the search page
+ # imports them: the same components either way.
+ registry = _read(STATIC / "apps.js")
+ search = _read(STATIC / "search-page.js")
+ for page in (registry, search):
+ for app in ("VideoApp", "PhotosApp", "MusicApp"):
+ assert app in page
+
+
+def test_the_music_bar_drives_the_television():
+ """With a television chosen, the decrypted track goes to the relay instead
+ of the element, and the bar's controls and clock are the receiver's. The
+ receiver keeps saying FINISHED until it is given something else, so the
+ end of a track moves the queue on once; and a television a film or a
+ photo has taken is not the bar's to read."""
+ bar = _read(STATIC / "music-player.js")
+ assert "const remote = Boolean(castDevice) && castSession.canSendFiles;" in bar
+ send = bar.split("const sendToTv = useCallback(", 1)[1].split("}, [fetchCover]);", 1)[0]
+ assert "owner: 'music', startAt," in send
+ assert "type: cached.mime, cover," in send
+ assert "sendingRef.current = true;" in send
+ load = bar.split("if (remoteRef.current) {\n // To the television", 1)[1]
+ assert "audio.pause();" in load.split("await audio.play();", 1)[0]
+ tick = bar.split("const tick = async () => {", 1)[1].split("const id = setInterval", 1)[0]
+ assert "castSession.owner !== 'music'" in tick
+ assert "sendingRef.current" in tick
+ assert "finishedRef.current !== remoteTrackRef.current" in tick
+ assert "String(c.idleReason || '').toLowerCase() === 'finished'" in tick
+ # The cover is found as the album card finds it, not only on the track.
+ cover = bar.split("const fetchCover = useCallback(", 1)[1]
+ cover = cover.split("}, [getConnection, tracks]);", 1)[0]
+ assert "entry.thumb_hash || (sibling && sibling.thumb_hash)" in cover
+ assert "transport.fetchMusicMeta(entry.id)" in cover
+ assert "meta.cover_thumb_hash" in cover
+ assert "castBridge.chromecastSeek(to)" in bar
+ assert "castBridge.chromecastPause() : castBridge.chromecastPlay()" in bar
+ # Stopping the cast carries the track on here; a film taking the
+ # television pauses the bar.
+ assert "if (castSession.device && castSession.owner !== 'music') setPlaying(false);" in bar
+
+
+def test_a_photo_leaves_scaled_and_upright():
+ session = _read(STATIC / "cast-session.js")
+ assert "imageOrientation: 'from-image'" in session
+ assert "const TV_WIDTH = 1920;" in session and "const TV_HEIGHT = 1080;" in session
+ assert "Math.min(1, TV_WIDTH / bitmap.width, TV_HEIGHT / bitmap.height)" in session
+ assert "await loadFile({ owner: 'photo', bytes, type: 'image/jpeg' });" in session
+ # Only the newest photo asked for is sent.
+ assert session.count("gen !== photoGen") >= 2
+
+
+def test_every_locale_names_the_slideshow():
+ for f in sorted((STATIC / "locales").glob("*.js")):
+ text = f.read_text(encoding="utf-8")
+ for key in ("photo.slideshow", "photo.slideshow_stop"):
+ assert f"'{key}':" in text, f"{f.name} lacks {key}"
diff --git a/packages/meshbay-hub/tests/test_copy_link.py b/packages/meshbay-hub/tests/test_copy_link.py
new file mode 100644
index 0000000..22e56e7
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_copy_link.py
@@ -0,0 +1,103 @@
+"""
+"Copy link": the `#/name@owner/path` address of a file or folder, from the
+views that show one (harness/copy_link_probe.py).
+
+Files offers it for one row — right-click, or the toolbar with one row ticked,
+which is how a phone reaches it; Music on one track's menu, whose dots are a
+phone's way in; Photos on a right-clicked tile and in the lightbox. The video
+player and the file preview carry a button. Search passes the same `linkFor`,
+naming each result's own group and its path there rather than the merged tree's.
+"""
+
+import json
+import re
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+HARNESS = Path(__file__).parent / "harness" / "copy_link_probe.py"
+STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static"
+ORIGIN = "http://127.0.0.1:8775"
+
+
+@pytest.fixture(scope="module")
+def cases():
+ if shutil.which("google-chrome") is None:
+ pytest.skip("Chrome is not available")
+ proc = subprocess.run([sys.executable, str(HARNESS)],
+ capture_output=True, text=True, timeout=180)
+ assert proc.returncode == 0, f"probe failed: {proc.stdout}{proc.stderr}"
+ out = json.loads(proc.stdout)
+ assert "error" not in out, out["error"]
+ assert out["logs"] == []
+ return {c["case"]: c for c in out["cases"]}
+
+
+def test_files_a_folder(cases):
+ c = cases["files folder"]
+ assert "Copy link" in c["labels"]
+ assert c["copied"] == f"{ORIGIN}/#/demo@someowner/Root"
+ assert c["note"] == "Link copied"
+
+
+def test_files_a_file(cases):
+ c = cases["files file"]
+ assert c["labels"].index("Copy link") > c["labels"].index("Download")
+ assert c["copied"] == f"{ORIGIN}/#/demo@someowner/Root/trip_2015/IMG%200001.JPG"
+
+
+def test_files_toolbar_one_ticked_row_only(cases):
+ c = cases["files toolbar"]
+ assert c["one_enabled"] is True and c["two_enabled"] is False
+ assert c["copied"] == f"{ORIGIN}/#/demo@someowner/Root/trip_2015/notes.txt"
+
+
+def test_music_a_track_from_its_dots(cases):
+ c = cases["music track"]
+ assert c["dots"] and c["labels"][-1] == "Copy link"
+ assert c["copied"] == f"{ORIGIN}/#/demo@someowner/Music/Some%20Album/track%2001.flac"
+
+
+def test_photos_tile_and_lightbox(cases):
+ c = cases["photos"]
+ link = f"{ORIGIN}/#/demo@someowner/Pics/Summer/beach.jpg"
+ assert c["labels"] == ["Copy link"] and c["copied"] == link
+ assert c["lightbox_button"] and c["lightbox_copied"] == link
+
+
+@pytest.mark.parametrize("module", ["video-player.js", "files-app.js"])
+def test_the_modals_carry_a_link_button(module):
+ source = (STATIC / module).read_text(encoding="utf-8")
+ assert re.search(r"function (VideoPlayer|FilePreview)\(\{[^}]*onCopyLink", source)
+ assert "${onCopyLink && html`" in source
+
+
+@pytest.mark.parametrize("page, n", [("group-page.js", 2), ("search-page.js", 2)])
+def test_both_pages_hand_the_modals_a_link(page, n):
+ source = (STATIC / page).read_text(encoding="utf-8")
+ assert source.count("onCopyLink=${linkFor(") == n
+
+
+def test_search_names_each_results_own_group_and_path():
+ source = (STATIC / "search-page.js").read_text(encoding="utf-8")
+ # Every view prefixes `path`; the link is built from the original.
+ assert source.count("_origPath: e.path,") == 4
+ assert "entryPath(target, target._origPath)" in source
+ for view in ("FilesPanel", "MusicApp", "PhotosApp"):
+ at = source.index(f"<${{{view}}}")
+ assert "linkFor=${linkFor}" in source[at:source.index("/>", at)], view
+
+
+def test_the_link_is_the_hubs_not_the_pages():
+ """In the desktop application the page is app://meshbay."""
+ source = (STATIC / "copy-link.js").read_text(encoding="utf-8")
+ assert "platform.hubOrigin() + '/#' + groupLinkRoute(" in source
+ assert "location.origin" not in source
+
+
+def test_the_note_goes_by_itself(cases):
+ c = cases["note goes"]
+ assert c["up_after_copy"] is True and c["up_later"] is False
diff --git a/packages/meshbay-hub/tests/test_desktop_keyring.py b/packages/meshbay-hub/tests/test_desktop_keyring.py
index e55e6d0..af7cc37 100644
--- a/packages/meshbay-hub/tests/test_desktop_keyring.py
+++ b/packages/meshbay-hub/tests/test_desktop_keyring.py
@@ -13,6 +13,7 @@ page, and a reference written from the specification in Python.
import base64
import hashlib
import json
+import re
import shutil
import subprocess
from pathlib import Path
@@ -93,6 +94,9 @@ const v = JSON.parse(fs.readFileSync(input, 'utf8'));
other_node: await refusal('join', { ...F.join, nodePk: 'T3RoZXJOb2Rl' }),
other_account: await refusal('join', { ...F.join, userId: 'someone-else' }),
stale: await refusal('join', { ...F.join, ts: ts - 3600 }),
+ root_add: await refusal('admin', { ...F.admin, op: 'root_add' }),
+ root_update: await refusal('admin', { ...F.admin, op: 'root_update' }),
+ group_attach: await refusal('admin', { ...F.admin, op: 'group_attach' }),
};
const eph = require('crypto').generateKeyPairSync('x25519');
@@ -268,6 +272,24 @@ def test_the_page_names_a_kind_and_never_the_bytes(out):
assert "not now" in r["stale"]
+def test_what_widens_a_nodes_sharing_is_never_signed(out):
+ """Gone from MNP 6.0, and refused here as well: a node older than that
+ still accepts them, and a script in the page must not be able to get one
+ signed for it."""
+ for op in ("root_add", "root_update", "group_attach"):
+ assert "not an operation" in out["refused"][op], op
+
+
+def test_the_application_signs_exactly_the_nodes_operations():
+ from meshbay_common import adminop
+ src = (Path(__file__).resolve().parents[2] / "meshbay-client" / "src"
+ / "transcripts.js").read_text(encoding="utf-8")
+ listed = set(re.findall(r"'([a-z_]+)'",
+ src.split("const ADMIN_OPS = new Set([")[1].split("]);")[0]))
+ catalogue = {v for k, v in vars(adminop).items() if k.startswith("OP_")}
+ assert listed == catalogue
+
+
def test_nothing_is_sealed_for_a_browser_while_browser_access_is_off(out):
for what, err in out["sealing_while_access_off"].items():
assert err and "browser access is off" in err, what
diff --git a/packages/meshbay-hub/tests/test_desktop_shell.py b/packages/meshbay-hub/tests/test_desktop_shell.py
index e80933c..c2ea4ca 100644
--- a/packages/meshbay-hub/tests/test_desktop_shell.py
+++ b/packages/meshbay-hub/tests/test_desktop_shell.py
@@ -425,13 +425,10 @@ def test_the_page_names_node_operations_not_routes():
assert defined <= used, f"defined but never called: {defined - used}"
-@pytest.mark.parametrize("op", ["attachGroup", "addRoot", "clearDenylist"])
-def test_what_widens_the_node_is_confirmed_natively(op):
- """Sharing a folder, hosting a group, re-admitting a revoked subject: asked
- by a dialog the main process draws, which a script in the page cannot
- answer. A folder chosen in the native picker is its own confirmation."""
- body = _node_ops()[op]
- assert "confirmOrRefuse(" in body or "confirmFolder(" in body
+def test_readmitting_a_revoked_subject_is_confirmed_natively():
+ """Asked by a dialog the main process draws, which a script in the page
+ cannot answer."""
+ assert "confirmOrRefuse(" in _node_ops()["clearDenylist"]
def test_the_native_dialogs_are_worded_in_every_language():
diff --git a/packages/meshbay-hub/tests/test_downloads.py b/packages/meshbay-hub/tests/test_downloads.py
index 3716f4c..7062d39 100644
--- a/packages/meshbay-hub/tests/test_downloads.py
+++ b/packages/meshbay-hub/tests/test_downloads.py
@@ -602,3 +602,56 @@ console.log(JSON.stringify(out));
f"resume at {out['resumeFrom']} — that gap is a hole in the file")
# The resumed run covers exactly the rest, and repeats nothing.
assert out["writtenAfterResume"] == list(range(out["resumeFrom"], 10)), out
+
+
+def test_a_written_chunk_is_not_held_until_the_download_ends(tmp_path):
+ """A file streamed to disk holds one pipeline window in the page, not the
+ whole file.
+
+ `pipelinedDownload` kept every chunk's resolved promise in `inflight` for
+ the length of the call, and each promise held its ciphertext — so a file
+ written straight to disk was also held whole in memory until the last
+ chunk landed. Measured in the Android application on a 2 GB download: the
+ page's JS heap tracked the bytes already written, 905 MB at 928 MB, and the
+ renderer reached 2.1 GB before dropping to 82 MB at the end. Every target
+ that writes as it goes (a granted folder, a service worker, the desktop's
+ native save) had the same cost. The real function runs here, with each
+ chunk message weakly referenced and the collector forced between writes.
+ """
+ src = (STATIC / "file-utils.js").read_text(encoding="utf-8")
+ fn = src[src.index("async function pipelinedDownload"):]
+ fn = fn[:fn.index("\n}\n") + 2]
+
+ script = tmp_path / "retention.mjs"
+ script.write_text("""
+const PIPELINE_WINDOW = 4;
+const TOTAL = 40;
+const refs = [];
+let worst = 0;
+const _fetchChunkResilient = async (transport, fileId, i) => {
+ const msg = { ct: new Uint8Array(64 * 1024), nonce: new Uint8Array(12) };
+ refs[i] = new WeakRef(msg);
+ return msg;
+};
+const _writeOrStall = async (w, bytes, index) => {
+ // A macrotask ends the job that keeps WeakRef targets alive; then collect.
+ await new Promise((r) => setTimeout(r, 0));
+ globalThis.gc();
+ let alive = 0;
+ for (let j = 0; j < index - PIPELINE_WINDOW; j++) if (refs[j] && refs[j].deref()) alive++;
+ worst = Math.max(worst, alive);
+};
+globalThis.window = { MeshBayCrypto: {
+ decryptChunkBin: async () => ({ byteLength: 64 * 1024 }),
+} };
+""" + fn + """
+await pipelinedDownload({}, 'k', 'file', TOTAL, () => {}, {}, { aborted: false }, '', 0);
+console.log(JSON.stringify({ worst }));
+""", encoding="utf-8")
+ proc = subprocess.run(["node", "--expose-gc", str(script)], capture_output=True,
+ text=True, encoding="utf-8", timeout=60)
+ assert proc.returncode == 0, proc.stderr
+ worst = json.loads(proc.stdout)["worst"]
+ assert worst == 0, (
+ f"{worst} chunks already written were still held when a later one was — "
+ "the download keeps the whole file in memory until it ends")
diff --git a/packages/meshbay-hub/tests/test_group_link.py b/packages/meshbay-hub/tests/test_group_link.py
new file mode 100644
index 0000000..e71df20
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_group_link.py
@@ -0,0 +1,170 @@
+"""
+A group named in the address: `#/name@owner[/path]`.
+
+The handle under every group's name is also a link to it, and a path after it
+names a folder to open or a file to download. `group-link.js` parses it,
+builds it, finds the group among the account's own and the entry in the
+group's index; the module is executed whole, as `test_search_source_merge.py`
+does with `source-merge.js`, so these rules are the ones the page runs.
+
+Also held here, at source level: the sign-in form no longer sends everyone
+home, which is what made any link opened signed out land on the home page.
+"""
+
+import json
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static"
+SRC = STATIC / "group-link.js"
+
+IMPORT = re.compile(r"^\s*import\b", re.M)
+EXPORT = re.compile(r"^export \{[^}]*\};?\s*$", re.M)
+
+needs_node = pytest.mark.skipif(
+ shutil.which("node") is None or not SRC.exists(),
+ reason="node or the SPA sources are not available")
+
+
+@pytest.fixture(scope="module")
+def module_source():
+ text = SRC.read_text(encoding="utf-8")
+ assert not IMPORT.search(text), (
+ "group-link.js has gained an import; this test runs it standalone")
+ stripped, n = EXPORT.subn("", text)
+ assert n == 1
+ return stripped
+
+
+def _run(tmp_path, module_source, expr):
+ script = tmp_path / "case.js"
+ script.write_text(f"{module_source}\nconsole.log(JSON.stringify({expr}));\n",
+ encoding="utf-8")
+ out = subprocess.run(["node", str(script)], capture_output=True, text=True,
+ encoding="utf-8", timeout=30)
+ assert out.returncode == 0, out.stderr
+ return json.loads(out.stdout)
+
+
+GROUPS = [
+ {"id": "g1", "name": "demo", "owner_username": "someowner"},
+ {"id": "g2", "name": "demo", "owner_username": "otherowner"},
+ {"id": "g3", "name": "trips@home", "owner_username": "someowner"},
+ {"id": "g4", "name": "a/b c", "owner_username": "someowner"},
+]
+
+ENTRIES = [
+ {"path": "backup/city_2015/backup", "name": "IMG_0001.JPG"},
+ {"path": "backup/city_2015", "name": "notes.txt"},
+ {"path": "music", "name": "track 01.flac"},
+]
+
+
+@needs_node
+@pytest.mark.parametrize("route, expected", [
+ ("/demo@someowner", {"name": "demo", "owner": "someowner", "path": ""}),
+ ("/demo@someowner/backup/city_2015/backup/IMG_0001.JPG",
+ {"name": "demo", "owner": "someowner",
+ "path": "backup/city_2015/backup/IMG_0001.JPG"}),
+ # The owner is after the last `@`: a group name may hold one, a username not.
+ ("/trips@home@someowner", {"name": "trips@home", "owner": "someowner", "path": ""}),
+ # Each segment decoded on its own: an escaped `/` stays inside its segment.
+ ("/a%2Fb%20c@someowner/music/track%2001.flac",
+ {"name": "a/b c", "owner": "someowner", "path": "music/track 01.flac"}),
+ ("/demo@someowner/music/", {"name": "demo", "owner": "someowner", "path": "music"}),
+ # Every other route, and anything that is not a well-formed handle.
+ ("/group/0f8fad5b-d9cb-469f-a165-70867728950e", None),
+ ("/login", None), ("/", None), ("", None),
+ ("/@someowner", None), ("/demo@", None),
+ ("/demo@someowner/%E0%A4%A", None),
+ ("/demo@someowner/music/../../etc", None),
+])
+def test_parse(tmp_path, module_source, route, expected):
+ assert _run(tmp_path, module_source, f"parseGroupLink({json.dumps(route)})") == expected
+
+
+@needs_node
+@pytest.mark.parametrize("group, path", [
+ (GROUPS[0], ""),
+ (GROUPS[0], "backup/city_2015/backup/IMG_0001.JPG"),
+ (GROUPS[2], ""),
+ (GROUPS[3], "music/track 01.flac"),
+ ({"name": "Été à la mer", "owner_username": "someowner"}, "photos/plage #1.jpg"),
+])
+def test_built_routes_parse_back(tmp_path, module_source, group, path):
+ out = _run(tmp_path, module_source,
+ f"(() => {{ const r = groupLinkRoute({json.dumps(group)}, {json.dumps(path)});"
+ f" return [r, parseGroupLink(r)]; }})()")
+ route, parsed = out
+ assert parsed == {"name": group["name"], "owner": group["owner_username"], "path": path}
+ # Nothing that ends or splits a fragment is left bare.
+ assert not re.search(r"[#?\s%](?![0-9A-F]{2})", route)
+
+
+@needs_node
+def test_a_plain_handle_stays_readable(tmp_path, module_source):
+ route = _run(tmp_path, module_source,
+ f"groupLinkRoute({json.dumps(GROUPS[0])}, 'backup/city_2015/IMG_1.JPG')")
+ assert route == "/demo@someowner/backup/city_2015/IMG_1.JPG"
+
+
+@needs_node
+@pytest.mark.parametrize("link, expected", [
+ ({"name": "demo", "owner": "someowner"}, "g1"),
+ ({"name": "demo", "owner": "otherowner"}, "g2"),
+ # The hub keeps names unique on lower(name).
+ ({"name": "DEMO", "owner": "someowner"}, "g1"),
+ ({"name": "demo", "owner": "SomeOwner"}, "g1"),
+ # Not among the account's groups: nothing, and nothing asked of the hub.
+ ({"name": "demo", "owner": "stranger1"}, None),
+ ({"name": "secret", "owner": "someowner"}, None),
+])
+def test_find_among_own_groups(tmp_path, module_source, link, expected):
+ out = _run(tmp_path, module_source,
+ f"(findLinkedGroup({json.dumps(GROUPS)}, {json.dumps(link)}) || {{}}).id || null")
+ assert out == expected
+
+
+@needs_node
+@pytest.mark.parametrize("path, expected", [
+ ("backup/city_2015/backup/IMG_0001.JPG",
+ {"kind": "file", "entry": ENTRIES[0]}),
+ ("backup/city_2015/notes.txt", {"kind": "file", "entry": ENTRIES[1]}),
+ ("backup/city_2015", {"kind": "dir", "dir": "backup/city_2015"}),
+ ("backup", {"kind": "dir", "dir": "backup"}),
+ # An empty folder exists only in the node's own listing.
+ ("backup/empty", {"kind": "dir", "dir": "backup/empty"}),
+ # A prefix of a folder name is not that folder.
+ ("backup/city", None),
+ ("backup/city_2015/backup/img_0001.jpg", None),
+ ("", None),
+])
+def test_resolve_in_index(tmp_path, module_source, path, expected):
+ out = _run(tmp_path, module_source,
+ f"resolveLinkedPath({json.dumps(ENTRIES)}, ['backup/empty'], {json.dumps(path)})")
+ assert out == expected
+
+
+def test_signing_in_keeps_the_page_the_address_names():
+ """A group or file link opened signed out shows the sign-in form in its
+ place; signing in must leave the address alone, not send everyone home."""
+ source = (STATIC / "auth-page.js").read_text(encoding="utf-8")
+ body = source[source.index("export function LoginPage"):]
+ body = body[:body.index("\n}\n")]
+ assert "navigate('/')" not in body and 'navigate("/")' not in body
+ assert "if (loadPending()) navigate('/invite');" in body
+
+
+def test_the_router_resolves_a_handle_and_shows_it():
+ source = (STATIC / "app.js").read_text(encoding="utf-8")
+ body = source[source.index("\nfunction App() {"):]
+ assert "parseGroupLink(route)" in body
+ assert "findLinkedGroup(groups, groupLink)" in body
+ # Rewritten with `replace`: showing the handle is not a history entry.
+ assert "window.location.replace('#' + shownGroupRoute)" in body
+ # The sidebar highlights the group whichever form opened it.
+ assert re.search(r"<\$\{Sidebar\}[\s\S]*?route=\$\{groupRoute\}", body)
diff --git a/packages/meshbay-hub/tests/test_group_link_flow.py b/packages/meshbay-hub/tests/test_group_link_flow.py
new file mode 100644
index 0000000..eb6a353
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_group_link_flow.py
@@ -0,0 +1,67 @@
+"""
+A group link, opened in the real application (harness/group_link_probe.py).
+
+`test_group_link.py` holds the parsing and the lookups; this is where they meet
+the router. A handle opens the group's page, and an id opens it with the handle
+in the address; a path waits in the address for the index to say what it is; a
+handle the account does not know is said to be unknown without the hub ever
+being asked about it; and signed out, the sign-in form stands in for the page
+with the address left alone, which is what lets signing in land there.
+"""
+
+import json
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+HARNESS = Path(__file__).parent / "harness" / "group_link_probe.py"
+GROUP_HREF = "#/group/0f8fad5b-d9cb-469f-a165-70867728950e"
+FILE_LINK = "#/demo@someowner/backup/city_2015/backup/IMG_0001.JPG"
+
+
+@pytest.fixture(scope="module")
+def cases():
+ if shutil.which("google-chrome") is None:
+ pytest.skip("Chrome is not available")
+ proc = subprocess.run([sys.executable, str(HARNESS)],
+ capture_output=True, text=True, timeout=240)
+ assert proc.returncode == 0, f"probe failed: {proc.stdout}{proc.stderr}"
+ out = {c["case"]: c for c in json.loads(proc.stdout)}
+ for c in out.values():
+ assert "error" not in c, c["error"]
+ return out
+
+
+@pytest.mark.parametrize("case", ["handle", "uuid", "file"])
+def test_a_handle_or_an_id_opens_the_group(cases, case):
+ c = cases[case]
+ assert c["group_page"] and c["group_title"] == "demo@someowner"
+ # Of two groups called "demo", the one whose owner the handle names.
+ assert c["active_sidebar"] == [GROUP_HREF]
+
+
+@pytest.mark.parametrize("case", ["handle", "uuid"])
+def test_the_address_shows_the_handle_without_a_history_entry(cases, case):
+ assert cases[case]["hash"] == "#/demo@someowner"
+ assert cases[case]["history_length"] == 1
+
+
+def test_a_path_stays_in_the_address_until_it_has_been_acted_on(cases):
+ assert cases["file"]["hash"] == FILE_LINK
+
+
+def test_an_unknown_handle_is_said_so_without_asking_the_hub(cases):
+ c = cases["unknown"]
+ assert not c["group_page"] and c["message"] and not c["spinner"]
+ assert c["hash"] == "#/demo@stranger1"
+ for case in cases.values():
+ assert not any("stranger1" in u or "@" in u for u in case["hub_calls"])
+
+
+def test_signed_out_the_form_stands_in_for_the_page(cases):
+ c = cases["signed_out"]
+ assert c["login_form"] and not c["group_page"]
+ assert c["hash"] == FILE_LINK
diff --git a/packages/meshbay-hub/tests/test_http_api_doc.py b/packages/meshbay-hub/tests/test_http_api_doc.py
new file mode 100644
index 0000000..5568e63
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_http_api_doc.py
@@ -0,0 +1,30 @@
+"""
+docs/MESHBAY_HTTP_API.md is generated from the routes of the hub and of the
+node's control API. A route added, removed or redescribed without running
+`python docs/generate_http_api.py` fails here.
+"""
+
+import importlib.util
+from pathlib import Path
+
+GENERATOR = Path(__file__).resolve().parents[3] / "docs" / "generate_http_api.py"
+
+
+def _generator():
+ spec = importlib.util.spec_from_file_location("generate_http_api", GENERATOR)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_the_api_listing_matches_the_routes():
+ gen = _generator()
+ assert gen.OUT.read_text(encoding="utf-8") == gen.render(), (
+ "docs/MESHBAY_HTTP_API.md is out of date: run python docs/generate_http_api.py")
+
+
+def test_every_route_says_what_it_does():
+ gen = _generator()
+ bare = [f"{gen.method(r)} {r.path}" for r in gen.hub_routes() + gen.node_routes()
+ if not gen.summary(r)]
+ assert not bare, f"give these routes a docstring, it is their line in the listing: {bare}"
diff --git a/packages/meshbay-hub/tests/test_invite_link_flow.py b/packages/meshbay-hub/tests/test_invite_link_flow.py
index 42f461c..cc8b432 100644
--- a/packages/meshbay-hub/tests/test_invite_link_flow.py
+++ b/packages/meshbay-hub/tests/test_invite_link_flow.py
@@ -33,14 +33,14 @@ def cases():
return out
-@pytest.mark.parametrize("case", ["signed_out", "signed_in"])
+@pytest.mark.parametrize("case", ["signed_out", "signed_in", "signed_in_listed"])
def test_the_code_is_out_of_the_address_and_kept_in_the_tab(cases, case):
c = cases[case]
assert c["hash_after_load"] == "#/invite"
assert c["pending"] and c["pending"]["c"] == "K7P2-9WQX"
-@pytest.mark.parametrize("case", ["signed_out", "signed_in"])
+@pytest.mark.parametrize("case", ["signed_out", "signed_in", "signed_in_listed"])
def test_the_code_never_reaches_the_hub(cases, case):
assert cases[case]["code_in_a_hub_request"] is False
@@ -59,3 +59,16 @@ def test_a_signed_in_reader_joins_with_one_click_and_lands_on_the_group(cases):
assert c["join_button"]
assert c["redeem_bodies"] == ['{"ticket":"AbCdEfGhIjKlMnOpQr-_12"}']
assert c["hash_after_click"] == "#/group/0f8fad5b-d9cb-469f-a165-70867728950e"
+
+
+def test_once_listed_the_joined_group_opens_under_its_handle(cases):
+ """The group links (group-link.js) rewrite `#/group/<id>` to the handle as
+ soon as the hub lists the group. Joining from an invitation must land on
+ the group page all the same, under that handle, with the rewrite adding
+ no history entry of its own — and still without the code reaching the hub."""
+ c = cases["signed_in_listed"]
+ assert c["join_button"]
+ assert c["hash_settled"] == "#/Some Group@the-owner"
+ assert c["group_page"] is True
+ # The page load, then the Join button's navigation; the rewrite replaces.
+ assert c["history_length"] == 2
diff --git a/packages/meshbay-hub/tests/test_keyring_vectors.py b/packages/meshbay-hub/tests/test_keyring_vectors.py
new file mode 100644
index 0000000..3928965
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_keyring_vectors.py
@@ -0,0 +1,142 @@
+"""
+The keypair-bundle and transcript vectors (`tests/vectors/keyring.json`).
+
+One file that every implementation of the bundle format and of the signed
+transcripts has to reproduce: the page (`keyderive.js`), the desktop keyring
+(`keyring.js`, `transcripts.js`), the Python reference below, and the Android
+keyring, whose unit tests read the same file. Pairwise parity tests grow with
+the square of the implementations; a shared file grows by one consumer.
+
+Two things are checked here. The file is what the shipped desktop code writes,
+so it cannot drift from the code it describes. And the specification
+(`docs/MESHBAY_DESIGN.md` §3.7, written out with argon2-cffi and
+`cryptography`, sharing nothing with the generator) arrives at the same bytes.
+"""
+
+import base64
+import hashlib
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+VECTORS = Path(__file__).resolve().parent / "vectors"
+FILE = VECTORS / "keyring.json"
+GENERATOR = VECTORS / "gen_keyring_vectors.js"
+KEYRING = Path(__file__).resolve().parents[2] / "meshbay-client" / "src" / "keyring.js"
+
+try:
+ from argon2.low_level import Type, hash_secret_raw
+ HAVE_ARGON2 = True
+except ImportError:
+ HAVE_ARGON2 = False
+
+
+def _vectors() -> dict:
+ return json.loads(FILE.read_text(encoding="utf-8"))
+
+
+@pytest.mark.skipif(shutil.which("node") is None or not KEYRING.exists(),
+ reason="node or the desktop client sources are unavailable")
+def test_the_file_is_what_the_shipped_keyring_writes():
+ """Regenerated from keyring.js and transcripts.js, byte for byte. A change
+ to either that alters a bundle or a transcript fails here first — which is
+ the moment to decide whether it is a format change every client must make."""
+ out = subprocess.run(["node", str(GENERATOR)], capture_output=True, text=True,
+ timeout=120, check=True).stdout
+ assert json.loads(out) == _vectors(), (
+ "keyring.js or transcripts.js no longer produce tests/vectors/keyring.json; "
+ "if the format change is deliberate, regenerate it and update every client")
+
+
+def _hkdf(ikm: bytes, info: str) -> bytes:
+ from cryptography.hazmat.primitives import hashes
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
+ return HKDF(hashes.SHA256(), 32, None, info.encode()).derive(ikm)
+
+
+@pytest.fixture(scope="module")
+def spec():
+ """The chain from the specification: passphrase → Argon2id → M → keys."""
+ if not HAVE_ARGON2:
+ pytest.skip("argon2-cffi is unavailable")
+ v = _vectors()
+ i, p = v["input"], v["kdf"]["argon2_params"]
+ salt = hashlib.sha256(f"meshbay:bundle:v2:{i['username']}".encode()).digest()[:16]
+ a = hash_secret_raw(i["password"].encode(), salt, time_cost=p["passes"],
+ memory_cost=p["memory"], parallelism=p["parallelism"],
+ hash_len=p["tagLength"], type=Type.ID)
+ m = _hkdf(a + base64.b64decode(i["pepperB64"]), f"meshbay:bundle-master:v3|{i['userId']}")
+ return {"v": v, "salt": salt, "a": a, "m": m,
+ "node_key": _hkdf(m, f"meshbay:bundle:v3|node|{i['nodePk']}"),
+ "recovery_key": _hkdf(bytes.fromhex(v["kdf"]["mnemonic_bytes_hex"]),
+ f"meshbay:recovery:v1:{i['username']}")}
+
+
+def test_the_specification_derives_the_same_keys(spec):
+ k = spec["v"]["kdf"]
+ assert spec["salt"].hex() == k["salt_hex"]
+ assert spec["a"].hex() == k["argon2_hex"]
+ assert spec["m"].hex() == k["master_hex"]
+ assert hashlib.sha256(spec["m"]).hexdigest()[:16] == k["master_fingerprint"]
+ assert spec["node_key"].hex() == k["node_key_hex"]
+ playlist = _hkdf(spec["m"], "meshbay:playlists:v2")
+ assert base64.b64encode(playlist).decode() == k["playlist_key_b64"]
+ assert spec["recovery_key"].hex() == k["recovery_key_hex"]
+
+
+def test_the_specification_seals_the_same_bundles(spec):
+ """MBK3 = magic ‖ pepper version ‖ nonce ‖ AES-GCM(JSON, aad). With the nonce
+ pinned, sealing is deterministic, so every client must write these bytes."""
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
+ v = spec["v"]
+ i, b = v["input"], v["bundles"]
+ nonce = bytes.fromhex(i["fixedNonceHex"])
+ plain, aad = b["sealed_json_plaintext"].encode(), b["aad"].encode()
+
+ def seal(key: bytes, version: int) -> str:
+ return base64.b64encode(b"MBK3" + bytes([version]) + nonce
+ + AESGCM(key).encrypt(nonce, plain, aad)).decode()
+
+ assert seal(spec["node_key"], i["pepperVersion"]) == b["fixed_nonce_bundle_b64"]
+ assert seal(spec["recovery_key"], 0) == b["recovery_fixed_nonce_b64"]
+ raw = base64.b64decode(b["legacy_mbk2_b64"]) # TRANSITIONAL: MBK2, no AAD
+ assert AESGCM(spec["a"]).decrypt(raw[4:16], raw[16:], None) == plain
+
+
+def test_the_identity_signs_and_agrees_as_recorded():
+ from cryptography.hazmat.primitives import serialization
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
+ from cryptography.hazmat.primitives.asymmetric.x25519 import (
+ X25519PrivateKey,
+ X25519PublicKey,
+ )
+ v = _vectors()
+ i = v["input"]
+ ed = Ed25519PrivateKey.from_private_bytes(bytes.fromhex(i["edSeedHex"]))
+ x = X25519PrivateKey.from_private_bytes(bytes.fromhex(i["xSeedHex"]))
+
+ def raw(k) -> str:
+ return base64.b64encode(k.public_key().public_bytes(
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw)).decode()
+
+ assert raw(ed) == v["identity"]["public"]["pkEdB64"]
+ assert raw(x) == v["identity"]["public"]["pkXB64"]
+ peer = X25519PublicKey.from_public_bytes(bytes.fromhex(i["peerXPubHex"]))
+ assert base64.b64encode(x.exchange(peer)).decode() == v["agreement"]["shared_b64"]
+ for kind, t in v["transcripts"].items():
+ sig = base64.b64encode(ed.sign(bytes.fromhex(t["transcript_hex"]))).decode()
+ assert sig == t["signature_b64"], kind
+
+
+def test_every_signed_kind_and_a_refusal_for_each_check_is_recorded():
+ """A consumer that passes an empty list proves nothing; pin what is there."""
+ v = _vectors()
+ assert set(v["transcripts"]) == {"join", "device_hello", "device_request",
+ "device_add", "device_revoke", "chat", "admin"}
+ labels = {r["label"] for r in v["refusals"]}
+ assert {"another node", "another account", "stale timestamp", "unknown kind",
+ "an op that widens sharing (gone from MNP 6.0)"} <= labels
+ assert all(r["error"].startswith("Refused: ") for r in v["refusals"])
diff --git a/packages/meshbay-hub/tests/test_search_unreachable_note.py b/packages/meshbay-hub/tests/test_search_unreachable_note.py
new file mode 100644
index 0000000..41ed25c
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_search_unreachable_note.py
@@ -0,0 +1,33 @@
+"""
+"N groups unreachable" on the cross-group Search page is said once a pass is
+over, for a few seconds, in the same passing note as "Link copied" (note.js) —
+not left above the results for as long as the page is open.
+
+Source-level, as the other Search wiring checks are: what is held is where the
+line is said and that nothing renders it in the page any more.
+"""
+
+import re
+from pathlib import Path
+
+STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static"
+
+
+def test_said_once_the_pass_is_over_and_not_rendered():
+ source = (STATIC / "search-page.js").read_text(encoding="utf-8")
+ assert "import { say } from './note.js';" in source
+ after = source[source.index("const { unreachable } = await fetchAllIndexes("):]
+ after = after[:after.index("})();")]
+ assert re.search(r"if \(cancelled\) return;\s*setFetching\(false\);", after)
+ assert "say(t('search.unreachable', { n: unreachable.length }), UNREACHABLE_NOTE_MS)" in after
+ assert "search-unreachable" not in source
+ ms = int(re.search(r"const UNREACHABLE_NOTE_MS = (\d+);", source).group(1))
+ assert 2000 <= ms <= 8000
+
+
+def test_one_note_for_the_whole_page():
+ note = (STATIC / "note.js").read_text(encoding="utf-8")
+ assert "export function say(text, ms = 2500)" in note
+ assert "clearTimeout(_timer)" in note
+ copy = (STATIC / "copy-link.js").read_text(encoding="utf-8")
+ assert "import { say } from './note.js';" in copy and "_say" not in copy
diff --git a/packages/meshbay-hub/tests/test_spa_ordering.py b/packages/meshbay-hub/tests/test_spa_ordering.py
index 6f28aaa..44f98db 100644
--- a/packages/meshbay-hub/tests/test_spa_ordering.py
+++ b/packages/meshbay-hub/tests/test_spa_ordering.py
@@ -162,7 +162,7 @@ def _component(name: str) -> str:
def test_the_group_settings_panel_renders_what_it_owns():
panel = _component("GroupSettingsPanel")
- assert "members.map(" in panel, "the member list is not rendered"
+ assert "joined.map(" in panel, "the member list is not rendered"
assert "onSubmit=${doInvite}" in panel, "the invite form is not rendered"
assert "onSubmit=${doPair}" in panel, "the pairing form is not rendered"
assert "device.mine_title" in panel, "the devices section is not rendered"
@@ -175,7 +175,7 @@ def test_the_roster_comes_last():
order is for — asked for in those terms.
"""
panel = _component("GroupSettingsPanel")
- listing = panel.index("members.map(")
+ listing = panel.index("joined.map(")
for name, marker in (("the invite form", "onSubmit=${doInvite}"),
("the pairing form", "onSubmit=${doPair}"),
("the devices section", "device.mine_title"),
diff --git a/packages/meshbay-hub/tests/test_upload_controls_hidden.py b/packages/meshbay-hub/tests/test_upload_controls_hidden.py
index 6316e44..947ba75 100644
--- a/packages/meshbay-hub/tests/test_upload_controls_hidden.py
+++ b/packages/meshbay-hub/tests/test_upload_controls_hidden.py
@@ -231,7 +231,7 @@ def test_the_notice_also_answers_the_operators_own_request():
def test_changing_a_root_is_signed():
transport = transport_source()
- for method in ("updateRoot", "ejectRoot", "plugRoot"):
+ for method in ("ejectRoot", "plugRoot", "removeRoot"):
body = transport[transport.index(f"async {method}("):]
body = body[:body.index("\n async ", 1)]
assert "admin_challenge" in body and "_authorizeAdminOp" in body, (
@@ -261,12 +261,34 @@ def test_the_operator_is_offered_it_on_the_web_too():
"the shared directories section still requires a local node")
table = _component(source, "SharedDirectoriesTable")
- for call in ("transport.updateRoot", "transport.ejectRoot",
- "transport.plugRoot", "transport.removeRoot",
- "transport.addRoot"):
+ for call in ("transport.ejectRoot", "transport.plugRoot", "transport.removeRoot"):
assert call in table, f"{call} has no MNP route from the table"
+def test_what_widens_the_sharing_never_crosses_mnp():
+ """
+ Adding a directory and switching `writable` or `removable` are done on the
+ node's own machine (MNP 6.0). Over MNP they were signed ops, and a signature
+ proves that the operator's key signed: in a browser that key is driven by
+ code the hub serves. The list stays visible from anywhere; those controls
+ are read-only there.
+ """
+ transport = transport_source()
+ for method in ("addRoot", "updateRoot", "attachGroup"):
+ assert f"async {method}(" not in transport, f"{method} is an MNP call again"
+ for mtype in ("'root_add'", "'root_update'", "'group_attach'"):
+ assert mtype not in transport, f"{mtype} is sent or expected again"
+
+ table = _component(GROUP_SETTINGS.read_text(encoding="utf-8"),
+ "SharedDirectoriesTable")
+ assert "platform.node.op('addRoot'" in table
+ assert "platform.node.op('updateRoot'" in table
+ assert "const canWiden = isLocal || onNodeMachine;" in table
+ assert table.count("!canWiden") >= 3, (
+ "a writable or removable switch is live where it cannot be honoured")
+ assert "settings_node.roots_local_only_hint" in table
+
+
def test_the_roots_shown_come_from_the_live_connection_when_there_is_one():
"""
The loopback list is a second source, and the two drift: it is read once on
diff --git a/packages/meshbay-hub/tests/test_video_audio_track.py b/packages/meshbay-hub/tests/test_video_audio_track.py
index 82d6e18..6515798 100644
--- a/packages/meshbay-hub/tests/test_video_audio_track.py
+++ b/packages/meshbay-hub/tests/test_video_audio_track.py
@@ -203,8 +203,8 @@ def test_changing_track_restarts_the_stream_where_the_film_already_was(app):
assert "audioTrackRef.current = track.i" in handler
assert "requestSeekRef.current" in handler, \
"a track change must go through the seek path"
- assert "seek(v.currentTime)" in handler, \
- "a track change must resume where the film already was"
+ assert "remoteFilmPosRef.current ?? (v && v.currentTime)" in handler, \
+ "a track change must resume where the film already was (on the television, when casting)"
def test_the_player_believes_the_node_about_which_track_is_playing(app):
diff --git a/packages/meshbay-hub/tests/test_video_seek.py b/packages/meshbay-hub/tests/test_video_seek.py
index 3289eda..3bcdb71 100644
--- a/packages/meshbay-hub/tests/test_video_seek.py
+++ b/packages/meshbay-hub/tests/test_video_seek.py
@@ -320,3 +320,68 @@ def test_the_resume_strings_exist_everywhere(locale):
text = (STATIC / "locales" / f"{locale}.js").read_text(encoding="utf-8")
for key in ("video.resumed_at", "video.from_start"):
assert key in text, f"{locale} is missing {key}"
+
+
+def test_a_seeks_first_segments_are_held_while_it_lands_not_dropped(tmp_path):
+ """What follows a `stream_init` is the new stream, its header first.
+
+ The landing (`reinitAt`/`resumeAt`) waits on the SourceBuffer, and those
+ segments used to arrive in that gap and be dropped as the old film's. The
+ player never noticed — its SourceBuffer kept the header from the start of
+ the film — but a cast relay restarted at that landing was handed a stream
+ beginning at a moof, and the receiver gave up within a second. Measured on
+ a phone: two segments dropped one millisecond after `stream_init`, a relay
+ header of 0 bytes; with them held, a 2 KB header and the film on the TV.
+
+ The real handler and the real drain run here: held while landing, counted
+ once, another file's segment refused, and replayed in arrival order.
+ """
+ import json
+ import subprocess
+
+ if shutil.which("node") is None:
+ pytest.skip("node is not available")
+ app = APP.read_text(encoding="utf-8")
+ start = app.index("transport.onStreamData = async (msg) => {")
+ handler = app[app.index("{", start) + 1:app.index("\n };", start)]
+ drain_at = app.index("land(msg.start || 0).then(async () => {")
+ drain = app[app.index("{", drain_at) + 1:app.index("}).catch(", drain_at)]
+
+ script = tmp_path / "hold.mjs"
+ script.write_text(
+ f"const handlerSrc = {json.dumps(handler)}, drainSrc = {json.dumps(drain)};\n" + """
+const consumed = [];
+const env = {
+ cancelled: false, entry: { id: 'film' },
+ outstandingRef: { current: 8 }, awaitingInitRef: { current: true },
+ heldRef: { current: [] }, holdGenRef: { current: 1 }, hold: 1,
+ consumeSegment: async (m) => { consumed.push(m.segment_index); },
+ console: { log() {} },
+};
+const names = Object.keys(env);
+const handler = new Function(...names, 'msg', `return (async () => {${handlerSrc}})();`);
+const drain = new Function(...names, `return (async () => {${drainSrc}})();`);
+const call = (fn, msg) => fn(...names.map((k) => env[k]), msg);
+
+// Landing: the new stream arrives, plus one stray segment from another file.
+for (const [i, file] of [[0, 'film'], [1, 'film'], [2, 'other'], [3, 'film']]) {
+ await call(handler, { file_id: file, segment_index: i });
+}
+const held = env.heldRef.current.map((m) => m.segment_index);
+const consumedWhileLanding = consumed.length;
+const outstanding = env.outstandingRef.current;
+// The landing completes.
+env.awaitingInitRef.current = false;
+await call(drain);
+console.log(JSON.stringify({ held, consumedWhileLanding, outstanding, consumed,
+ heldAfter: env.heldRef.current }));
+""", encoding="utf-8")
+ proc = subprocess.run(["node", str(script)], capture_output=True, text=True,
+ encoding="utf-8", timeout=60)
+ assert proc.returncode == 0, proc.stderr
+ out = json.loads(proc.stdout)
+ assert out["held"] == [0, 1, 3], "the new stream's segments were dropped or mixed"
+ assert out["consumedWhileLanding"] == 0, "a segment was taken before the landing finished"
+ assert out["outstanding"] == 4, "each arrival is counted once, held or not"
+ assert out["consumed"] == [0, 1, 3], "the replay must keep arrival order, header first"
+ assert out["heldAfter"] is None, "holding must stop once the landing has drained"
diff --git a/packages/meshbay-hub/tests/vectors/gen_keyring_vectors.js b/packages/meshbay-hub/tests/vectors/gen_keyring_vectors.js
new file mode 100644
index 0000000..055070f
--- /dev/null
+++ b/packages/meshbay-hub/tests/vectors/gen_keyring_vectors.js
@@ -0,0 +1,232 @@
+// Golden vectors for the keypair bundle and the transcripts, produced by the
+// code the desktop application ships: meshbay-client's keyring.js and
+// transcripts.js, with the vendored Argon2 the page also runs.
+//
+// node gen_keyring_vectors.js > keyring.json
+//
+// Every implementation of the bundle format and of the transcripts — the page,
+// the desktop keyring, the Python reference, the Android keyring — must
+// reproduce this file (test_keyring_vectors.py, and the Android unit tests).
+// It is regenerated deliberately, for a format change, never by a test. The
+// output is deterministic: nonces and the clock are pinned.
+
+'use strict';
+
+const path = require('node:path');
+const crypto = require('node:crypto');
+
+const REPO = path.resolve(__dirname, '..', '..', '..', '..');
+const CLIENT = path.join(REPO, 'packages/meshbay-client/src');
+const VENDOR = path.join(REPO, 'packages/meshbay-hub/src/meshbay_hub/static/vendor');
+
+const { createKeyring } = require(path.join(CLIENT, 'keyring.js'));
+const { transcriptFor } = require(path.join(CLIENT, 'transcripts.js'));
+const { wasmArgon2 } = require(path.join(CLIENT, 'argon2-wasm.js'));
+
+const b64 = (b) => Buffer.from(b).toString('base64');
+const hex = (b) => Buffer.from(b).toString('hex');
+const hkdf = (ikm, info) => Buffer.from(
+ crypto.hkdfSync('sha256', ikm, Buffer.alloc(0), Buffer.from(info), 32));
+
+// Fixed inputs. Invented values only.
+const NOW = 1790000000; // a fixed "now" for transcript timestamps
+const INPUT = {
+ username: 'vector-user',
+ userId: '0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0',
+ password: 'a passphrase used only for vectors',
+ pepperB64: b64(Buffer.alloc(32, 7)),
+ pepperVersion: 3,
+ nodePk: b64(Buffer.alloc(32, 0x11)),
+ otherNodePk: b64(Buffer.alloc(32, 0x22)),
+ groupId: 'grp_vector-01',
+ mnemonic: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
+ edSeedHex: '9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60',
+ xSeedHex: '77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a',
+ peerXPubHex: 'de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f',
+ fixedNonceHex: '000102030405060708090a0b',
+ legacyNonceHex: '0b0a09080706050403020100',
+ now: NOW,
+};
+
+const pkcs8 = (prefixHex, seedHex) =>
+ Buffer.concat([Buffer.from(prefixHex, 'hex'), Buffer.from(seedHex, 'hex')]);
+const ED_PKCS8 = pkcs8('302e020100300506032b657004220420', INPUT.edSeedHex);
+const X_PKCS8 = pkcs8('302e020100300506032b656e04220420', INPUT.xSeedHex);
+
+function withFixedRandom(bytesHex, fn) {
+ const real = crypto.randomBytes;
+ crypto.randomBytes = (n) => {
+ const b = Buffer.from(bytesHex, 'hex');
+ if (b.length !== n) throw new Error(`fixed random of ${b.length}, asked ${n}`);
+ return b;
+ };
+ try { return fn(); } finally { crypto.randomBytes = real; }
+}
+
+function withNow(seconds, fn) {
+ const real = Date.now;
+ Date.now = () => seconds * 1000;
+ try { return fn(); } finally { Date.now = real; }
+}
+
+(async () => {
+ const argon2 = wasmArgon2(VENDOR);
+ let store = {};
+ const ring = createKeyring({
+ argon2,
+ load: () => JSON.parse(JSON.stringify(store)),
+ save: (o) => { store = JSON.parse(JSON.stringify(o)); },
+ });
+
+ // 1. KDF chain.
+ const salt = crypto.createHash('sha256')
+ .update(`meshbay:bundle:v2:${INPUT.username}`).digest().subarray(0, 16);
+ const ARGON2 = { memory: 131072, passes: 3, parallelism: 1, tagLength: 32 };
+ await ring.deriveSession({
+ password: INPUT.password, username: INPUT.username, userId: INPUT.userId,
+ pepperB64: INPUT.pepperB64, pepperVersion: INPUT.pepperVersion,
+ });
+ const m = Buffer.from(store.masters[INPUT.userId].m, 'base64');
+ const a = Buffer.from(store.masters[INPUT.userId].legacy, 'base64');
+ const kdf = {
+ argon2_params: ARGON2,
+ salt_hex: hex(salt),
+ argon2_hex: hex(a),
+ master_hex: hex(m),
+ master_fingerprint: ring.currentFingerprint(INPUT.userId),
+ node_key_hex: hex(hkdf(m, `meshbay:bundle:v3|node|${INPUT.nodePk}`)),
+ playlist_key_b64: ring.playlistKey(INPUT.userId),
+ recovery_key_hex: null, // filled below
+ };
+
+ // 2. A fixed identity, placed in the store as mint() would leave it.
+ store.identities[INPUT.userId] = {
+ [INPUT.nodePk]: { ed: b64(ED_PKCS8), x: b64(X_PKCS8), sealedWith: null },
+ };
+ const identity = {
+ ed_pkcs8_b64: b64(ED_PKCS8),
+ x_pkcs8_b64: b64(X_PKCS8),
+ public: ring.identity(INPUT.userId, INPUT.nodePk),
+ };
+
+ // 3. Bundles.
+ const fixed = withFixedRandom(INPUT.fixedNonceHex,
+ () => ring.sealBundle(INPUT.userId, INPUT.nodePk));
+ const recovery = withFixedRandom(INPUT.fixedNonceHex,
+ () => ring.sealRecovery(INPUT.userId, INPUT.nodePk, INPUT.mnemonic, INPUT.username));
+
+ // The recovery key, re-derived the way keyring.js does (fromMnemonic + hkdf).
+ const B32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
+ let bits = 0; let value = 0; const raw = [];
+ for (const ch of INPUT.mnemonic.replace(/[^A-Za-z2-7]/g, '').toUpperCase()) {
+ value = (value << 5) | B32.indexOf(ch); bits += 5;
+ if (bits >= 8) { raw.push((value >>> (bits - 8)) & 0xff); bits -= 8; }
+ }
+ kdf.mnemonic_bytes_hex = hex(Buffer.from(raw.slice(0, 32)));
+ kdf.recovery_key_hex = hex(hkdf(Buffer.from(raw.slice(0, 32)),
+ `meshbay:recovery:v1:${INPUT.username}`));
+
+ // MBK2 (TRANSITIONAL): "MBK2" ‖ nonce ‖ AES-GCM(JSON) under the Argon2 key, no AAD.
+ const legacyNonce = Buffer.from(INPUT.legacyNonceHex, 'hex');
+ const c = crypto.createCipheriv('aes-256-gcm', a, legacyNonce);
+ const plain = JSON.stringify({ skEd: b64(ED_PKCS8), skX: b64(X_PKCS8) });
+ const legacy = b64(Buffer.concat([
+ Buffer.from('MBK2'), legacyNonce, c.update(plain), c.final(), c.getAuthTag()]));
+
+ // Each must open through the shipped keyring, into a fresh store.
+ const check = async (label, bundleEnc, extra = {}) => {
+ let s2 = {};
+ const r2 = createKeyring({ argon2, load: () => JSON.parse(JSON.stringify(s2)),
+ save: (o) => { s2 = JSON.parse(JSON.stringify(o)); } });
+ await r2.deriveSession({ password: INPUT.password, username: INPUT.username,
+ userId: INPUT.userId, pepperB64: INPUT.pepperB64, pepperVersion: INPUT.pepperVersion });
+ const pub = r2.openBundle(INPUT.userId, INPUT.nodePk, { bundleEnc, ...extra });
+ if (pub.pkEdB64 !== identity.public.pkEdB64 || pub.pkXB64 !== identity.public.pkXB64) {
+ throw new Error(`${label} opened to another identity`);
+ }
+ return true;
+ };
+ await check('fixed', fixed.bundle);
+ await check('legacy', legacy);
+ // The recovery copy, through the fallback: a passphrase copy that does not open.
+ await check('recovery', b64(Buffer.concat([Buffer.from('MBK3'), Buffer.alloc(30, 1)])), {
+ recoveryEnc: recovery, recoveryMnemonic: INPUT.mnemonic, username: INPUT.username });
+
+ const bundles = {
+ sealed_json_plaintext: plain,
+ aad: `meshbay:bundle:v3|${INPUT.userId}|${INPUT.nodePk}`,
+ fixed_nonce_bundle_b64: fixed.bundle,
+ fixed_nonce_fingerprint: fixed.fingerprint,
+ recovery_fixed_nonce_b64: recovery,
+ legacy_mbk2_b64: legacy,
+ };
+
+ // 4. Agreement.
+ const agreement = {
+ peer_x_pub_b64: b64(Buffer.from(INPUT.peerXPubHex, 'hex')),
+ shared_b64: ring.shared(INPUT.userId, INPUT.nodePk, b64(Buffer.from(INPUT.peerXPubHex, 'hex'))),
+ };
+
+ // 5. Transcripts: every kind, then refusals.
+ const ctx = { userId: INPUT.userId, nodePk: INPUT.nodePk, ...identity.public };
+ delete ctx.sealedWith;
+ const nonceNode = b64(Buffer.alloc(32, 0x33));
+ const kinds = {
+ join: { nodePk: INPUT.nodePk, groupId: INPUT.groupId, userId: INPUT.userId, nonceNode, ts: NOW },
+ device_hello: { nodePk: INPUT.nodePk, groupId: INPUT.groupId, userId: INPUT.userId, nonceNode, ts: NOW - 30 },
+ device_request: { nodePk: INPUT.nodePk, userId: INPUT.userId,
+ codeHash: 'ab'.repeat(32), nonceNode, ts: NOW + 30 },
+ device_add: { nodePk: INPUT.nodePk, userId: INPUT.userId,
+ pkEd: b64(Buffer.alloc(32, 0x44)), pkX: b64(Buffer.alloc(32, 0x55)), nonceNode, ts: NOW },
+ device_revoke: { nodePk: INPUT.nodePk, userId: INPUT.userId,
+ pkEd: b64(Buffer.alloc(32, 0x44)), nonceNode, ts: NOW },
+ chat: { groupId: INPUT.groupId, epoch: 4, nonce: b64(Buffer.alloc(24, 0x66)),
+ ct: b64(Buffer.from('ciphertext of a chat line, opaque here')) },
+ admin: { op: 'apps_enabled', nodePk: INPUT.nodePk, groupId: INPUT.groupId,
+ subject: '{"apps":["chat","videos"],"note":"é ü 漢"}',
+ nonce: b64(Buffer.alloc(16, 0x77)), ts: NOW },
+ };
+ const transcripts = {};
+ for (const [kind, fields] of Object.entries(kinds)) {
+ const bytes = withNow(NOW, () => transcriptFor(kind, fields, ctx));
+ const sig = withNow(NOW, () => ring.signAs(INPUT.userId, INPUT.nodePk, kind, fields));
+ transcripts[kind] = { fields, transcript_hex: hex(bytes), signature_b64: sig };
+ }
+
+ const refusals = [];
+ const refuse = (label, kind, fields) => {
+ try {
+ withNow(NOW, () => transcriptFor(kind, fields, ctx));
+ throw new Error(`vector "${label}" was NOT refused by transcripts.js`);
+ } catch (e) {
+ if (/NOT refused/.test(e.message)) throw e;
+ refusals.push({ label, kind, fields, error: e.message });
+ }
+ };
+ refuse('another node', 'join', { ...kinds.join, nodePk: INPUT.otherNodePk });
+ refuse('another account', 'join', { ...kinds.join, userId: '00000000-0000-4000-8000-000000000000' });
+ refuse('stale timestamp', 'join', { ...kinds.join, ts: NOW - 601 });
+ refuse('future timestamp', 'device_hello', { ...kinds.device_hello, ts: NOW + 601 });
+ refuse('fractional timestamp', 'join', { ...kinds.join, ts: NOW + 0.5 });
+ refuse('bad group id', 'join', { ...kinds.join, groupId: 'a/b' });
+ refuse('short node nonce', 'join', { ...kinds.join, nonceNode: b64(Buffer.alloc(15)) });
+ refuse('not base64', 'join', { ...kinds.join, nonceNode: 'not*base64' });
+ refuse('bad request hash', 'device_request', { ...kinds.device_request, codeHash: 'AB'.repeat(32) });
+ refuse('device key wrong length', 'device_add', { ...kinds.device_add, pkEd: b64(Buffer.alloc(31)) });
+ refuse('negative epoch', 'chat', { ...kinds.chat, epoch: -1 });
+ refuse('chat nonce too short', 'chat', { ...kinds.chat, nonce: b64(Buffer.alloc(11)) });
+ refuse('bad op', 'admin', { ...kinds.admin, op: 'Drop-Table' });
+ refuse('an op that widens sharing (gone from MNP 6.0)', 'admin', { ...kinds.admin, op: 'root_add' });
+ refuse('a well-formed op not on the list', 'admin', { ...kinds.admin, op: 'set_app_setting' });
+ refuse('subject too long', 'admin', { ...kinds.admin, subject: 'x'.repeat(16385) });
+ refuse('unknown kind', 'sign_anything', { bytes: 'AAAA' });
+
+ const out = {
+ _about: 'Generated by gen_keyring_vectors.js from meshbay-client keyring.js and '
+ + 'transcripts.js with the vendored Argon2. Every implementation of the bundle '
+ + 'format and the transcripts must reproduce every field.',
+ input: INPUT,
+ kdf, identity, bundles, agreement, transcripts, refusals,
+ };
+ process.stdout.write(JSON.stringify(out, null, 2) + '\n');
+})().catch((e) => { console.error(e); process.exit(1); });
diff --git a/packages/meshbay-hub/tests/vectors/keyring.json b/packages/meshbay-hub/tests/vectors/keyring.json
new file mode 100644
index 0000000..84ecff0
--- /dev/null
+++ b/packages/meshbay-hub/tests/vectors/keyring.json
@@ -0,0 +1,342 @@
+{
+ "_about": "Generated by gen_keyring_vectors.js from meshbay-client keyring.js and transcripts.js with the vendored Argon2. Every implementation of the bundle format and the transcripts must reproduce every field.",
+ "input": {
+ "username": "vector-user",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "password": "a passphrase used only for vectors",
+ "pepperB64": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=",
+ "pepperVersion": 3,
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "otherNodePk": "IiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiI=",
+ "groupId": "grp_vector-01",
+ "mnemonic": "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
+ "edSeedHex": "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
+ "xSeedHex": "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a",
+ "peerXPubHex": "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f",
+ "fixedNonceHex": "000102030405060708090a0b",
+ "legacyNonceHex": "0b0a09080706050403020100",
+ "now": 1790000000
+ },
+ "kdf": {
+ "argon2_params": {
+ "memory": 131072,
+ "passes": 3,
+ "parallelism": 1,
+ "tagLength": 32
+ },
+ "salt_hex": "2244e8b97822de2b9e210e22301700ff",
+ "argon2_hex": "95e8531f721421b13bba6e6585de932654d26e5428793f8734b4e7da74b14a7c",
+ "master_hex": "ecb972b6454304630cecffe115a9f679905ce98457c741f7d534f575322b1cef",
+ "master_fingerprint": "292fe17f616a1ef6",
+ "node_key_hex": "948aa161c470cd16e944cbc1dfc1a375a76a17761ad80014423d64cf2401bd2f",
+ "playlist_key_b64": "Gyd4KTER2IS4dHieFp9DkiHExSP3hjLT/SMXF0TBUno=",
+ "recovery_key_hex": "612b9cf5cc507ba1483555d7748dc7e20734374994baa092fca605df3600a8c3",
+ "mnemonic_bytes_hex": "00443214c74254b635cf84653a56d7c675be77df00443214c74254b635cf8465"
+ },
+ "identity": {
+ "ed_pkcs8_b64": "MC4CAQAwBQYDK2VwBCIEIJ1hsZ3v/VpguoRK9JLsLMREScVpezJpGXA7rAMcrn9g",
+ "x_pkcs8_b64": "MC4CAQAwBQYDK2VuBCIEIHcHbQpzGKV9PBbBclGyZkXfTC+H68CZKrF3+6UduSwq",
+ "public": {
+ "pkEdB64": "11qYAYKxCrfVS/7TyWQHOg7hcvPapiMlrwIaaPcHURo=",
+ "pkXB64": "hSDwCYkwp1R0i33ctD73Wg2/Og0mOBr066SpjqqbTmo=",
+ "sealedWith": null
+ }
+ },
+ "bundles": {
+ "sealed_json_plaintext": "{\"skEd\":\"MC4CAQAwBQYDK2VwBCIEIJ1hsZ3v/VpguoRK9JLsLMREScVpezJpGXA7rAMcrn9g\",\"skX\":\"MC4CAQAwBQYDK2VuBCIEIHcHbQpzGKV9PBbBclGyZkXfTC+H68CZKrF3+6UduSwq\"}",
+ "aad": "meshbay:bundle:v3|0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0|ERERERERERERERERERERERERERERERERERERERERERE=",
+ "fixed_nonce_bundle_b64": "TUJLMwMAAQIDBAUGBwgJCgu/0e64MEzT13AuLRE9rV3gw4cF1jPwKvIl8h0OsNnW1UsbNLdQcWg+SVVgNSOfR2SneoWBbieI1Gypb/9osJ7gkWHfOcvlMqa0AdjoS3ww/Tf0/hL/LLB5B04w1oujnfsvhCL6zaPZtjyPZ5PUc6Ks7AqXmJZtuqSN33qEjZoQH9xQKNb6LUVJrWTjSUl2NZ02Y1mIVOd6Y9Af421u/vn41FIxwg==",
+ "fixed_nonce_fingerprint": "292fe17f616a1ef6",
+ "recovery_fixed_nonce_b64": "TUJLMwAAAQIDBAUGBwgJCgvqVgf86f7WSRXeERiv5CqFqgsFVR5vXLcYOKVOWblJErRq4D3pWWM1UMSyWOEjv0Q88dukHmm/ncpvUV24rtrBwQ3a2o0O3Zu4QQxKispflVoCuYIakbwh8dSF5Qh7Pgdat2TpWO0/OekZpvXv6kUdiMFviB1qKSkzE0od+qgdh0Wokqb5cvD9Mxr5CQkrNlMVkGs+O73ITEIUkDlDHNNSr+2GMg==",
+ "legacy_mbk2_b64": "TUJLMgsKCQgHBgUEAwIBAOAz0yDaxedAe3ervmsyggv0fyDeHyTeMdfuBhO3mEHtfub86kZFyk6RG+SUuZHd2uReHxdA+6sZhexlTb32eK7Fg2MfsAhXlVdO6p0JS+LT2Dx4IV8KV7f8En1n5RE7ppy2QtMjqKzi56nzY0uihtNDmgnaQgas4anOMFJDzONfR6ek8f5DQWAKxDc/AKb8jf+DnhOY2F3J5NNzl4swIXe60FND"
+ },
+ "agreement": {
+ "peer_x_pub_b64": "3p7bfXt9wbTTW2HC7OQ1Nz+DQ8hbeGdNrfx+FG+IK08=",
+ "shared_b64": "Sl2dW6TOLeFyjjv0gDUPJeB+IclH0Z4zdvCbPB4WF0I="
+ },
+ "transcripts": {
+ "join": {
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "grp_vector-01",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "nonceNode": "MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM=",
+ "ts": 1790000000
+ },
+ "transcript_hex": "6d6573686261793a6a6f696e3a76310000002c455245524552455245524552455245524552455245524552455245524552455245524552455245524552453d0000000d6772705f766563746f722d30310000002430663165326433632d346235612d343936382d383737362d6135623463336432653166300000002c3131715941594b7843726656532f3754795751484f6737686376506170694d6c727749616150634855526f3d0000002c6853447743596b777031523069333363744437335767322f4f67306d4f427230363653706a717162546d6f3d0000002033333333333333333333333333333333333333333333333333333333333333330000000a31373930303030303030",
+ "signature_b64": "PjmA9stj7pqTWdaHGgNQjiouiC3V6YktCa7ebXy7aZVUIeeoKT5nf7hqhkkNV0hUUvYZoWsu9rD14TwVZI6pBw=="
+ },
+ "device_hello": {
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "grp_vector-01",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "nonceNode": "MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM=",
+ "ts": 1789999970
+ },
+ "transcript_hex": "6d6573686261793a6465766963655f68656c6c6f3a76310000002c455245524552455245524552455245524552455245524552455245524552455245524552455245524552453d0000000d6772705f766563746f722d30310000002430663165326433632d346235612d343936382d383737362d6135623463336432653166300000002c3131715941594b7843726656532f3754795751484f6737686376506170694d6c727749616150634855526f3d0000002033333333333333333333333333333333333333333333333333333333333333330000000a31373839393939393730",
+ "signature_b64": "IVOAHoLco3TvqaRdN4lvv8YGmE4PQu54njs23luu/j51vOdXmkbAVS9HYBrSmPhVPxc9UW5B/KY9vdzHYnMZBg=="
+ },
+ "device_request": {
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "codeHash": "abababababababababababababababababababababababababababababababab",
+ "nonceNode": "MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM=",
+ "ts": 1790000030
+ },
+ "transcript_hex": "6d6573686261793a6465766963655f7265713a76310000002c455245524552455245524552455245524552455245524552455245524552455245524552455245524552453d0000002430663165326433632d346235612d343936382d383737362d6135623463336432653166300000002c3131715941594b7843726656532f3754795751484f6737686376506170694d6c727749616150634855526f3d0000002c6853447743596b777031523069333363744437335767322f4f67306d4f427230363653706a717162546d6f3d00000040616261626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162616261620000002033333333333333333333333333333333333333333333333333333333333333330000000a31373930303030303330",
+ "signature_b64": "wi1DvdWqKYSvrmweN8U8E/IGe5akrEO1nXClVjBoKsr2geksMrxnOrkAFSO2Ecf7js4hT2OxoYgVBzjiRdV0AA=="
+ },
+ "device_add": {
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "pkEd": "REREREREREREREREREREREREREREREREREREREREREQ=",
+ "pkX": "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVU=",
+ "nonceNode": "MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM=",
+ "ts": 1790000000
+ },
+ "transcript_hex": "6d6573686261793a6465766963655f6164643a76310000002c455245524552455245524552455245524552455245524552455245524552455245524552455245524552453d0000002430663165326433632d346235612d343936382d383737362d6135623463336432653166300000002c524552455245524552455245524552455245524552455245524552455245524552455245524552455245513d0000002c565656565656565656565656565656565656565656565656565656565656565656565656565656565656553d0000002033333333333333333333333333333333333333333333333333333333333333330000000a31373930303030303030",
+ "signature_b64": "D+tRe/2fbscnA3wdhHsnEfUCu0U/JszfIhFvYC8lEy8AqiD7osn3GWotQIMGSO3FoQz62WJHZsAdUaelgQJUCg=="
+ },
+ "device_revoke": {
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "pkEd": "REREREREREREREREREREREREREREREREREREREREREQ=",
+ "nonceNode": "MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM=",
+ "ts": 1790000000
+ },
+ "transcript_hex": "6d6573686261793a6465766963655f7265766f6b653a76310000002c455245524552455245524552455245524552455245524552455245524552455245524552455245524552453d0000002430663165326433632d346235612d343936382d383737362d6135623463336432653166300000002c524552455245524552455245524552455245524552455245524552455245524552455245524552455245513d0000002033333333333333333333333333333333333333333333333333333333333333330000000a31373930303030303030",
+ "signature_b64": "NmVrQU3Fb0rms+wYQI9TIdc7Ry0H/G9CLU5stNNnGe6/WU29bSU8V81FXk6ze5dOfi0ezz4YmWrem7cRAR5MBg=="
+ },
+ "chat": {
+ "fields": {
+ "groupId": "grp_vector-01",
+ "epoch": 4,
+ "nonce": "ZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm",
+ "ct": "Y2lwaGVydGV4dCBvZiBhIGNoYXQgbGluZSwgb3BhcXVlIGhlcmU="
+ },
+ "transcript_hex": "6d6573686261793a636861743a76310000000d6772705f766563746f722d3031000000013400000020d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a000000186666666666666666666666666666666666666666666666660000002663697068657274657874206f6620612063686174206c696e652c206f70617175652068657265",
+ "signature_b64": "Ogv5d2lhr0ABJacfp0XEbUH7jO8lIplbCZLj1jL5bt8kHyPvKpRDruZkCg+vo9sOFWjMuAlIzQALuS6zE62JBA=="
+ },
+ "admin": {
+ "fields": {
+ "op": "apps_enabled",
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "grp_vector-01",
+ "subject": "{\"apps\":[\"chat\",\"videos\"],\"note\":\"é ü 漢\"}",
+ "nonce": "d3d3d3d3d3d3d3d3d3d3dw==",
+ "ts": 1790000000
+ },
+ "transcript_hex": "6d6573686261793a61646d696e3a76310000000c617070735f656e61626c65640000002c455245524552455245524552455245524552455245524552455245524552455245524552455245524552453d0000000d6772705f766563746f722d30310000002d7b2261707073223a5b2263686174222c22766964656f73225d2c226e6f7465223a22c3a920c3bc20e6bca2227d00000010777777777777777777777777777777770000000a31373930303030303030",
+ "signature_b64": "ocx6tu6SKu3U8mEQUWhNNIZieGDfYquLdtBfez0vqb2EkfFzPfD1yraP3OhlvZYTIZfnWfzJ1R9y/sRN6vZgAg=="
+ }
+ },
+ "refusals": [
+ {
+ "label": "another node",
+ "kind": "join",
+ "fields": {
+ "nodePk": "IiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiI=",
+ "groupId": "grp_vector-01",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "nonceNode": "MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM=",
+ "ts": 1790000000
+ },
+ "error": "Refused: another node"
+ },
+ {
+ "label": "another account",
+ "kind": "join",
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "grp_vector-01",
+ "userId": "00000000-0000-4000-8000-000000000000",
+ "nonceNode": "MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM=",
+ "ts": 1790000000
+ },
+ "error": "Refused: another account"
+ },
+ {
+ "label": "stale timestamp",
+ "kind": "join",
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "grp_vector-01",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "nonceNode": "MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM=",
+ "ts": 1789999399
+ },
+ "error": "Refused: the timestamp is not now"
+ },
+ {
+ "label": "future timestamp",
+ "kind": "device_hello",
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "grp_vector-01",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "nonceNode": "MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM=",
+ "ts": 1790000601
+ },
+ "error": "Refused: the timestamp is not now"
+ },
+ {
+ "label": "fractional timestamp",
+ "kind": "join",
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "grp_vector-01",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "nonceNode": "MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM=",
+ "ts": 1790000000.5
+ },
+ "error": "Refused: the timestamp is not now"
+ },
+ {
+ "label": "bad group id",
+ "kind": "join",
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "a/b",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "nonceNode": "MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM=",
+ "ts": 1790000000
+ },
+ "error": "Refused: not a group id"
+ },
+ {
+ "label": "short node nonce",
+ "kind": "join",
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "grp_vector-01",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "nonceNode": "AAAAAAAAAAAAAAAAAAAA",
+ "ts": 1790000000
+ },
+ "error": "Refused: the node nonce has the wrong length"
+ },
+ {
+ "label": "not base64",
+ "kind": "join",
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "grp_vector-01",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "nonceNode": "not*base64",
+ "ts": 1790000000
+ },
+ "error": "Refused: the node nonce is not base64"
+ },
+ {
+ "label": "bad request hash",
+ "kind": "device_request",
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "codeHash": "ABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABAB",
+ "nonceNode": "MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM=",
+ "ts": 1790000030
+ },
+ "error": "Refused: not a request hash"
+ },
+ {
+ "label": "device key wrong length",
+ "kind": "device_add",
+ "fields": {
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "userId": "0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0",
+ "pkEd": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",
+ "pkX": "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVU=",
+ "nonceNode": "MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM=",
+ "ts": 1790000000
+ },
+ "error": "Refused: the device key has the wrong length"
+ },
+ {
+ "label": "negative epoch",
+ "kind": "chat",
+ "fields": {
+ "groupId": "grp_vector-01",
+ "epoch": -1,
+ "nonce": "ZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm",
+ "ct": "Y2lwaGVydGV4dCBvZiBhIGNoYXQgbGluZSwgb3BhcXVlIGhlcmU="
+ },
+ "error": "Refused: not an epoch"
+ },
+ {
+ "label": "chat nonce too short",
+ "kind": "chat",
+ "fields": {
+ "groupId": "grp_vector-01",
+ "epoch": 4,
+ "nonce": "AAAAAAAAAAAAAAA=",
+ "ct": "Y2lwaGVydGV4dCBvZiBhIGNoYXQgbGluZSwgb3BhcXVlIGhlcmU="
+ },
+ "error": "Refused: the message nonce has the wrong length"
+ },
+ {
+ "label": "bad op",
+ "kind": "admin",
+ "fields": {
+ "op": "Drop-Table",
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "grp_vector-01",
+ "subject": "{\"apps\":[\"chat\",\"videos\"],\"note\":\"é ü 漢\"}",
+ "nonce": "d3d3d3d3d3d3d3d3d3d3dw==",
+ "ts": 1790000000
+ },
+ "error": "Refused: not an operation"
+ },
+ {
+ "label": "an op that widens sharing (gone from MNP 6.0)",
+ "kind": "admin",
+ "fields": {
+ "op": "root_add",
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "grp_vector-01",
+ "subject": "{\"apps\":[\"chat\",\"videos\"],\"note\":\"é ü 漢\"}",
+ "nonce": "d3d3d3d3d3d3d3d3d3d3dw==",
+ "ts": 1790000000
+ },
+ "error": "Refused: not an operation"
+ },
+ {
+ "label": "a well-formed op not on the list",
+ "kind": "admin",
+ "fields": {
+ "op": "set_app_setting",
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "grp_vector-01",
+ "subject": "{\"apps\":[\"chat\",\"videos\"],\"note\":\"é ü 漢\"}",
+ "nonce": "d3d3d3d3d3d3d3d3d3d3dw==",
+ "ts": 1790000000
+ },
+ "error": "Refused: not an operation"
+ },
+ {
+ "label": "subject too long",
+ "kind": "admin",
+ "fields": {
+ "op": "apps_enabled",
+ "nodePk": "ERERERERERERERERERERERERERERERERERERERERERE=",
+ "groupId": "grp_vector-01",
+ "subject": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
+ "nonce": "d3d3d3d3d3d3d3d3d3d3dw==",
+ "ts": 1790000000
+ },
+ "error": "Refused: the subject is too long"
+ },
+ {
+ "label": "unknown kind",
+ "kind": "sign_anything",
+ "fields": {
+ "bytes": "AAAA"
+ },
+ "error": "Refused: nothing is signed as \"sign_anything\""
+ }
+ ]
+}
diff --git a/packages/meshbay-node/LICENSE b/packages/meshbay-node/LICENSE
new file mode 100644
index 0000000..be3f7b2
--- /dev/null
+++ b/packages/meshbay-node/LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<https://www.gnu.org/licenses/>.
diff --git a/packages/meshbay-node/pyproject.toml b/packages/meshbay-node/pyproject.toml
index ce1f718..3dd1188 100644
--- a/packages/meshbay-node/pyproject.toml
+++ b/packages/meshbay-node/pyproject.toml
@@ -1,12 +1,14 @@
[build-system]
-requires = ["hatchling"]
+requires = ["hatchling>=1.27"] # PEP 639: SPDX `license` + `license-files`
build-backend = "hatchling.build"
[project]
name = "meshbay-node"
-version = "0.17.0"
+version = "0.18.0"
description = "MeshBay Node — local file host, streaming server, and group daemon"
requires-python = ">=3.12"
+license = "AGPL-3.0-or-later"
+license-files = ["LICENSE"]
dependencies = [
"meshbay-common>=0.10.0",
"fastapi>=0.115", # local web UI on localhost:18000
diff --git a/packages/meshbay-node/src/meshbay_node/__init__.py b/packages/meshbay-node/src/meshbay_node/__init__.py
index c3c18ff..c58bc8a 100644
--- a/packages/meshbay-node/src/meshbay_node/__init__.py
+++ b/packages/meshbay-node/src/meshbay_node/__init__.py
@@ -1,3 +1,3 @@
"""MeshBay Node — local file host, streaming server, and group daemon."""
-__version__ = "0.17.0"
+__version__ = "0.18.0"
diff --git a/packages/meshbay-node/src/meshbay_node/cli/status.py b/packages/meshbay-node/src/meshbay_node/cli/status.py
index 162bd46..ebc6c77 100644
--- a/packages/meshbay-node/src/meshbay_node/cli/status.py
+++ b/packages/meshbay-node/src/meshbay_node/cli/status.py
@@ -34,7 +34,8 @@ def status(args) -> None:
live = None
if live:
- print(f"daemon running — {live.get('status')}")
+ state = live.get("status")
+ print("daemon running" + (f" — {state}" if state and state != "running" else ""))
print(f"node_id {live.get('endpoint_hint') or '—'}")
print(f"groups {live.get('group_count', 0)}"
f" files {live.get('total_files', 0)}"
diff --git a/packages/meshbay-node/src/meshbay_node/daemon.py b/packages/meshbay-node/src/meshbay_node/daemon.py
index 1777bc3..d6293ee 100644
--- a/packages/meshbay-node/src/meshbay_node/daemon.py
+++ b/packages/meshbay-node/src/meshbay_node/daemon.py
@@ -1259,11 +1259,13 @@ class NodeDaemon(EnrichmentMixin):
specs = [asdict(r) for r in group_cfg.roots]
if self._roster:
ejected = await self._roster.ejected_roots(group_cfg.id)
+ auto = await self._roster.auto_ejected_roots(group_cfg.id)
if ejected:
for spec in specs:
name = spec.get("name") or Path(spec.get("path", "")).name
if fold(name) in ejected:
spec["ejected"] = True
+ spec["ejected_auto"] = fold(name) in auto
return RootSet.build(specs)
# Every application that keeps directories. This is the one list, and it
@@ -1305,9 +1307,10 @@ class NodeDaemon(EnrichmentMixin):
"""`on_root_ejected` bound to one group, for that group's indexer."""
async def persist(root_name: str, ejected: bool) -> None:
if self._roster:
+ # The indexer only reports the safety net's own changes.
await self._roster.set_root_ejected(
group_id, root_name, ejected,
- set_by=self._state.get("node_user_id", ""))
+ set_by=self._state.get("node_user_id", ""), auto=ejected)
return persist
async def _on_index_change(self, indexer: DirectoryIndexer) -> None:
diff --git a/packages/meshbay-node/src/meshbay_node/indexer/cache.py b/packages/meshbay-node/src/meshbay_node/indexer/cache.py
index 6c87f40..5e328ef 100644
--- a/packages/meshbay-node/src/meshbay_node/indexer/cache.py
+++ b/packages/meshbay-node/src/meshbay_node/indexer/cache.py
@@ -23,6 +23,7 @@ only daemon.py's wiring changed.
"""
import logging
+import os
import time
from dataclasses import dataclass
from pathlib import Path
@@ -191,6 +192,19 @@ class IndexCache:
row = await cur.fetchone()
return row[0] if row else 0
+ async def sample_under(self, directory: str, limit: int) -> list[tuple[str, int, float]]:
+ """Up to `limit` cached files under `directory`, as (path, size, mtime).
+
+ A prefix compared with `substr`, not `LIKE`: `_` and `%` are wildcards
+ there, and both are ordinary in a folder name.
+ """
+ prefix = directory.rstrip("/\\") + os.sep
+ async with self._db.execute(
+ "SELECT path, size, mtime FROM files WHERE substr(path, 1, ?) = ? LIMIT ?",
+ (len(prefix), prefix, limit)) as cur:
+ rows = await cur.fetchall()
+ return [(row[0], row[1], row[2]) for row in rows]
+
async def all_paths(self) -> list[str]:
"""Every cached path, for a caller that decides staleness itself —
this cache has no notion of which paths are still claimed by a
diff --git a/packages/meshbay-node/src/meshbay_node/indexer/indexer.py b/packages/meshbay-node/src/meshbay_node/indexer/indexer.py
index 4b619d7..5e139bb 100644
--- a/packages/meshbay-node/src/meshbay_node/indexer/indexer.py
+++ b/packages/meshbay-node/src/meshbay_node/indexer/indexer.py
@@ -389,6 +389,7 @@ class DirectoryIndexer:
async def _initial_scan(self) -> None:
await off_disk(self.roots, self.roots.refresh_availability)
+ await self._plug_back_recognised()
total = 0
waiting = [r.name for r in self.roots if r.available]
self._queue(waiting)
@@ -719,6 +720,21 @@ class DirectoryIndexer:
# The table now; the files when the scan ends.
await self.on_change(self)
+ async def publish_roots(self) -> None:
+ """
+ Tell every connected peer the table, after a root's flags were edited
+ in place (`ops.update_root`).
+
+ A reload compares the edited set with itself and finds nothing to do,
+ so without this a directory made writable from the operator's own
+ machine stayed read-only on every open page until something else
+ happened to push the index.
+ """
+ self._index.roots = self.roots.describe()
+ self._index.version = int(time.time())
+ if self.on_change:
+ await self.on_change(self)
+
def _holds(self, root: Root) -> bool:
return any(r.folded == root.folded and r.path == root.path for r in self.roots)
@@ -810,6 +826,8 @@ class DirectoryIndexer:
except Exception:
log.exception("Could not persist the auto-eject of root %r", name)
+ changed += [(root, True) for root in await self._plug_back_recognised()]
+
for root, available in changed:
if available:
log.info("Root %r is back — rescanning", root.name)
@@ -1017,6 +1035,65 @@ class DirectoryIndexer:
self._observer = None
self._start_observer()
+ # How many of a root's known files are looked for before it is plugged back
+ # automatically. One found is enough: another drive, or an empty mount
+ # point, holds none of them at the same path with the same size and mtime.
+ RECOGNISE_SAMPLE = 5
+
+ async def _plug_back_recognised(self) -> list[Root]:
+ """
+ Un-eject the roots the safety net ejected, once they hold their own files
+ again: a drive not mounted yet when the node started, or unplugged and
+ plugged back. An operator's eject is never undone here.
+ """
+ back = []
+ for root in [r for r in self.roots if r.ejected and r.auto]:
+ if not await off_disk(self.roots, self._recognises, root,
+ await self._known_files(root)):
+ continue
+ root.ejected = root.auto = False
+ root.available = True
+ log.info("Root %r is back with its files — plugged automatically", root.name)
+ if self.on_root_ejected:
+ try:
+ await self.on_root_ejected(root.name, False)
+ except Exception:
+ log.exception("Could not persist the return of root %r", root.name)
+ back.append(root)
+ return back
+
+ async def _known_files(self, root: Root) -> list[tuple[str, int, float | None]]:
+ """Files this root is known to hold, as (path, size, mtime or None).
+
+ The hash cache first: it survives a restart, when an ejected root has no
+ entry in the index at all. The index is the fallback for a node without
+ a cache.
+ """
+ if self._cache is not None:
+ known = await self._cache.sample_under(str(root.path), self.RECOGNISE_SAMPLE)
+ if known:
+ return known
+ return [(str(path), e.size, None)
+ for e in self._entries_under(root)[:self.RECOGNISE_SAMPLE]
+ if (path := self._entry_path(root, e)) is not None]
+
+ @staticmethod
+ def _recognises(root: Root, known: list[tuple[str, int, float | None]]) -> bool:
+ """Blocking: is this the root's own content, readable again?"""
+ if not root.is_live():
+ return False
+ if not known:
+ # Nothing known under it, so nothing a wrong disk could pass for.
+ return True
+ for path, size, mtime in known:
+ try:
+ st = Path(path).stat()
+ except OSError:
+ continue
+ if st.st_size == size and (mtime is None or st.st_mtime == mtime):
+ return True
+ return False
+
def eject_root(self, root_name: str) -> None:
"""Stop watching a root without touching its entries."""
from meshbay_common.paths import fold
@@ -1024,6 +1101,7 @@ class DirectoryIndexer:
for root in self.roots:
if fold(root.name) == target:
root.ejected = True
+ root.auto = False
root.available = False
frozen = len(self._entries_under(root))
log.info("Root %r ejected — %d entries frozen", root.name, frozen)
@@ -1043,7 +1121,7 @@ class DirectoryIndexer:
break
if root is None:
return
- root.ejected = False
+ root.ejected = root.auto = False
root.available = await off_disk(self.roots, root.is_live)
if not root.available:
await self._finish_plug(None)
diff --git a/packages/meshbay-node/src/meshbay_node/ops/chat.py b/packages/meshbay-node/src/meshbay_node/ops/chat.py
index 469e907..539284b 100644
--- a/packages/meshbay-node/src/meshbay_node/ops/chat.py
+++ b/packages/meshbay-node/src/meshbay_node/ops/chat.py
@@ -17,7 +17,7 @@ log = logging.getLogger("meshbay_node.ops")
#
# The key a group's chat archive is encrypted under. Generated here, by the
# node, and never by a member — the C5b rule is about key material arriving from
-# outside, and this is the same rule that lets `gek_rotate` be a signed
+# outside, and this is the same rule that lets a group key rotation be an
# instruction rather than a delivery.
#
# An *epoch* rather than a rotation, and the distinction is the whole design:
diff --git a/packages/meshbay-node/src/meshbay_node/ops/roots.py b/packages/meshbay-node/src/meshbay_node/ops/roots.py
index 480fe63..b976e8f 100644
--- a/packages/meshbay-node/src/meshbay_node/ops/roots.py
+++ b/packages/meshbay-node/src/meshbay_node/ops/roots.py
@@ -174,11 +174,14 @@ async def update_root(state: dict, group_id: str, root_name: str, *,
writable=match.writable, removable=match.removable)
# Update the live RootSet so GET /api/groups returns correct data
- # immediately, without waiting for the async reload to finish.
+ # immediately, without waiting for the async reload to finish — and the
+ # indexer's, which is normally the same object but need not be, since it
+ # is the one the table pushed to every peer is read from.
live_roots: RootSet | None = state.get("groups_ctx", {}).get(
group_id, {}).get("roots")
- if live_roots:
- for lr in live_roots.roots:
+ indexer = state.get("indexers", {}).get(group_id)
+ for rootset in {id(x): x for x in (live_roots, indexer and indexer.roots) if x}.values():
+ for lr in rootset.roots:
lr_name = lr.name or str(Path(lr.path).name)
if fold(lr_name) == target:
if writable is not None:
@@ -187,6 +190,9 @@ async def update_root(state: dict, group_id: str, root_name: str, *,
lr.removable = removable
break
+ if indexer:
+ await indexer.publish_roots()
+
# Built from config when there is no live set, never returned empty: an
# empty list is a *valid answer* meaning "this group has no directories",
# and the client cannot tell it from "the node could not say". It would
@@ -234,6 +240,7 @@ async def eject_root(state: dict, group_id: str, root_name: str) -> dict:
if indexer:
indexer.eject_root(root_name)
root.ejected = True
+ root.auto = False
root.available = False
await _roster(state).set_root_ejected(
@@ -282,7 +289,7 @@ async def plug_root(state: dict, group_id: str, root_name: str) -> dict:
indexer = state.get("indexers", {}).get(group_id)
if indexer:
await indexer.plug_root(root_name)
- root.ejected = False
+ root.ejected = root.auto = False
root.available = await off_disk(roots, root.is_live)
log.info("Root plugged: %s in group %s", root_name, group_id[:8])
diff --git a/packages/meshbay-node/src/meshbay_node/ops/settings.py b/packages/meshbay-node/src/meshbay_node/ops/settings.py
index eade6ca..906cd03 100644
--- a/packages/meshbay-node/src/meshbay_node/ops/settings.py
+++ b/packages/meshbay-node/src/meshbay_node/ops/settings.py
@@ -182,9 +182,9 @@ async def set_transfer_limits(state: dict, group_id: str,
Same shape as every other operator setting: lives on the node (roster.db,
not the hub and not node.toml, for the reason change 5 gives — a hub that
- decided this would have authority over someone else's machine), signed
- (webrtc_server checks the caller's admin authority before this runs), and
- live, so the pools are updated in place rather than at the next restart.
+ decided this would have authority over someone else's machine), set on the
+ node's own machine (loopback API, CLI), and live, so the pools are updated
+ in place rather than at the next restart.
"""
roster = _roster(state)
ctx = _group_ctx(state, group_id)
diff --git a/packages/meshbay-node/src/meshbay_node/roots.py b/packages/meshbay-node/src/meshbay_node/roots.py
index 2de0708..2b48292 100644
--- a/packages/meshbay-node/src/meshbay_node/roots.py
+++ b/packages/meshbay-node/src/meshbay_node/roots.py
@@ -178,6 +178,10 @@ class Root:
writable: bool = False
removable: bool = False
ejected: bool = False
+ # Ejected by the safety net in `refresh_availability`, not by the operator:
+ # such a root comes back on its own once its files are there again
+ # (`DirectoryIndexer._reconcile`). An operator's eject never does.
+ auto: bool = False
available: bool = True
@property
@@ -323,6 +327,7 @@ class RootSet:
writable=writable,
removable=bool(spec.get("removable", False)),
ejected=bool(spec.get("ejected", False)),
+ auto=bool(spec.get("ejected_auto", False)),
available=not bool(spec.get("ejected", False)))
_refuse_nesting(root, roots)
roots.append(root)
@@ -441,6 +446,7 @@ class RootSet:
live = root.is_live()
if not live and root.removable:
root.ejected = True
+ root.auto = True
# Recorded for the caller to persist. A flag that only lives
# in memory would be forgotten on the next restart, and the
# rescan that followed would read an empty mount point as an
diff --git a/packages/meshbay-node/src/meshbay_node/roster.py b/packages/meshbay-node/src/meshbay_node/roster.py
index 0116aaa..eb8c031 100644
--- a/packages/meshbay-node/src/meshbay_node/roster.py
+++ b/packages/meshbay-node/src/meshbay_node/roster.py
@@ -686,9 +686,11 @@ class Roster:
return cls.SETTING_ROOT_EJECTED_PREFIX + fold(root_name)
async def set_root_ejected(self, group_id: str, root_name: str,
- ejected: bool, set_by: str = "") -> None:
- await self.set_setting(group_id, self.root_ejected_key(root_name),
- "1" if ejected else "0", set_by)
+ ejected: bool, set_by: str = "",
+ auto: bool = False) -> None:
+ """`auto`: ejected by the safety net, not by the operator."""
+ value = ("auto" if auto else "1") if ejected else "0"
+ await self.set_setting(group_id, self.root_ejected_key(root_name), value, set_by)
async def ejected_roots(self, group_id: str) -> set[str]:
"""
@@ -705,7 +707,17 @@ class Roster:
(group_id,)) as cur:
rows = await cur.fetchall()
return {r["key"][len(prefix):] for r in rows
- if r["key"].startswith(prefix) and r["value"] == "1"}
+ if r["key"].startswith(prefix) and r["value"] in ("1", "auto")}
+
+ async def auto_ejected_roots(self, group_id: str) -> set[str]:
+ """The folded names of the roots the safety net ejected, a subset of the above."""
+ prefix = self.SETTING_ROOT_EJECTED_PREFIX
+ async with self._db.execute(
+ "SELECT key, value FROM group_settings WHERE group_id = ?",
+ (group_id,)) as cur:
+ rows = await cur.fetchall()
+ return {r["key"][len(prefix):] for r in rows
+ if r["key"].startswith(prefix) and r["value"] == "auto"}
async def get_setting(self, group_id: str, key: str,
default: str | None = None) -> str | None:
diff --git a/packages/meshbay-node/src/meshbay_node/transport/webrtc/admin.py b/packages/meshbay-node/src/meshbay_node/transport/webrtc/admin.py
index daaee62..9a6cbd1 100644
--- a/packages/meshbay-node/src/meshbay_node/transport/webrtc/admin.py
+++ b/packages/meshbay-node/src/meshbay_node/transport/webrtc/admin.py
@@ -17,27 +17,20 @@ from meshbay_common.adminop import (
OP_CHAT_LINK_PREVIEW,
OP_DIR_DELETE,
OP_FILE_DELETE,
- OP_GEK_ROTATE,
- OP_GROUP_ATTACH,
- OP_GROUP_DETACH,
OP_INVITE_CANCEL,
OP_INVITE_CREATE,
OP_INVITE_LINK_CREATE,
OP_MEMBER_REVOKE,
- OP_MEMBER_UNPIN,
OP_MUSICBRAINZ_ENABLED,
- OP_ROOT_ADD,
OP_ROOT_EJECT,
OP_ROOT_PLUG,
OP_ROOT_REMOVE,
- OP_ROOT_UPDATE,
OP_SEARCH_LISTED,
OP_SET_SCAN_SETTINGS,
OP_TMDB_CONFIG,
OP_TMDB_ENABLED,
OP_TMDB_OVERRIDE,
OP_TMDB_REMATCH,
- OP_TRANSFER_LIMITS,
admin_transcript,
)
from meshbay_common.crypto import pk_to_b64
@@ -62,28 +55,21 @@ _ADMIN_EXECUTORS = {
OP_INVITE_CREATE: "_admin_exec_invite_create",
OP_INVITE_LINK_CREATE: "_admin_exec_invite_link_create",
OP_INVITE_CANCEL: "_admin_exec_invite_cancel",
- OP_GEK_ROTATE: "_admin_exec_gek_rotate",
- OP_MEMBER_UNPIN: "_admin_exec_member_unpin",
OP_APPS_ENABLED: "_admin_exec_apps_enabled",
- OP_TRANSFER_LIMITS: "_admin_exec_transfer_limits",
OP_SET_SCAN_SETTINGS: "_admin_exec_set_scan_settings",
OP_TMDB_CONFIG: "_admin_exec_tmdb_config",
OP_TMDB_ENABLED: "_admin_exec_tmdb_enabled",
OP_TMDB_OVERRIDE: "_admin_exec_tmdb_override",
OP_TMDB_REMATCH: "_admin_exec_tmdb_rematch",
OP_MUSICBRAINZ_ENABLED: "_admin_exec_musicbrainz_enabled",
- OP_ROOT_ADD: "_admin_exec_root_add",
OP_ROOT_REMOVE: "_admin_exec_root_remove",
OP_APP_DIRECTORIES: "_admin_exec_app_directories",
OP_CHAT_DIRECTORY: "_admin_exec_chat_directory",
OP_CHAT_LINK_PREVIEW: "_admin_exec_chat_link_preview",
OP_SEARCH_LISTED: "_admin_exec_search_listed",
OP_CHAT_EPOCH: "_admin_exec_chat_epoch",
- OP_ROOT_UPDATE: "_admin_exec_root_update",
OP_ROOT_EJECT: "_admin_exec_root_eject",
OP_ROOT_PLUG: "_admin_exec_root_plug",
- OP_GROUP_ATTACH: "_admin_exec_group_attach",
- OP_GROUP_DETACH: "_admin_exec_group_detach",
}
@@ -180,49 +166,12 @@ class AdminMixin:
says "the hub says you are the owner", which is the one thing NS4 and
M3 rule out: a hub that can name the operator can install itself as
node administrator. It rides the handshake ack so a client knows whether
- to offer the Node page at all, and every operation is gated on
- `_operator_device()` below.
+ to offer operator controls at all; every operation is gated on a
+ signature (`_verify_admin_sig`).
"""
node_user_id = self._ctx.get("node_user_id")
return bool(node_user_id and self._user_id == node_user_id)
- async def _operator_device(self) -> bool:
- """
- Whether this connection may run the node's own controls.
-
- Two things, and the second is the one that cannot be forged:
-
- - the account is the one this node belongs to (`_is_node_admin`), which
- is what keeps node-wide controls with the machine's owner rather than
- with every paired operator of every group on it; and
- - **the device on this connection proved a key the node pinned as an
- operator**. `device_hello` is signed over a transcript naming this
- node, this group and this connection's nonce, and `operator_pks()` is
- rebuilt from the roster on each call, so an unpinned browser and a
- revoked one are both refused at once.
-
- The second clause is the fix for the door this used to leave open.
- `node_status`, `node_settings_set`, `roster_read`, `denylist_read`,
- `denylist_clear` and `node_reload` were gated on the account id alone —
- a value the hub chooses. An active hub that can also reach the group key
- (which §3.5 concedes it can in an open-join group) could therefore mint
- a token for the owner's account and read `node_status`, which lists
- every group on the node with the operator's **absolute paths**, or clear
- the denylist, which is the persisted revocation H4 exists to keep.
-
- It holds no user keys and cannot countersign anything, so it cannot
- produce a `device_hello` — which is the same property device linking
- rests on (§3.3), applied to the node's own surface.
- """
- if not self._is_node_admin():
- return False
- if not self._device_confirmed or not self._pinned_pk:
- return False
- roster = self._ctx.get("roster")
- if roster is None:
- return False
- return self._pinned_pk in await roster.operator_pks()
-
def _has_admin_authority(self) -> bool:
"""
Cheap synchronous pre-check: is there anyone who could authorize this?
diff --git a/packages/meshbay-node/src/meshbay_node/transport/webrtc/chat.py b/packages/meshbay-node/src/meshbay_node/transport/webrtc/chat.py
index 493d7f0..dc43ae2 100644
--- a/packages/meshbay-node/src/meshbay_node/transport/webrtc/chat.py
+++ b/packages/meshbay-node/src/meshbay_node/transport/webrtc/chat.py
@@ -198,9 +198,9 @@ class ChatMixin:
There is no switch to turn chat encryption on: MNP 2.0 has no plaintext
chat to fall back to. What an operator may want to do deliberately is
- move the key on — the same instruction as `gek_rotate`, and signed for
- the same reason. The removals that matter (member revoke, member unpin,
- device revoke, `gek_rotate`) already open one by themselves.
+ move the key on, which is signed like the rest. The removals that matter
+ (member revoke, member unpin, device revoke, a group key rotation)
+ already open one by themselves.
"""
group_id = str(msg.get("group_id", "")).strip() or self._group_id
if not group_id:
diff --git a/packages/meshbay-node/src/meshbay_node/transport/webrtc/dispatch.py b/packages/meshbay-node/src/meshbay_node/transport/webrtc/dispatch.py
index ee2e3a1..4bf9dbb 100644
--- a/packages/meshbay-node/src/meshbay_node/transport/webrtc/dispatch.py
+++ b/packages/meshbay-node/src/meshbay_node/transport/webrtc/dispatch.py
@@ -48,7 +48,6 @@ _HANDLERS = {
MNP.DEVICE_REVOKE: ("_do_device_revoke", SPAWNED),
MNP.DEVICE_HELLO: ("_do_device_hello", SPAWNED),
MNP.APPS_ENABLED: ("_do_apps_enabled", INLINE),
- MNP.TRANSFER_LIMITS: ("_do_transfer_limits", INLINE),
MNP.SET_SCAN_SETTINGS: ("_do_set_scan_settings", INLINE),
MNP.TMDB_CONFIG: ("_do_tmdb_config", INLINE),
MNP.TMDB_ENABLED: ("_do_tmdb_enabled", INLINE),
@@ -68,21 +67,9 @@ _HANDLERS = {
MNP.MUSIC_META_REQ: ("_do_music_meta_request", SPAWNED),
MNP.AUDIO_TRANSCODE_REQ: ("_do_audio_transcode_request", SPAWNED),
MNP.SUBTITLE_REQ: ("_do_subtitle_request", SPAWNED),
- MNP.MEMBER_UNPIN: ("_do_member_unpin", INLINE),
- MNP.GEK_ROTATE: ("_do_gek_rotate", INLINE),
- MNP.NODE_STATUS: ("_do_node_status", SPAWNED),
- MNP.ROOT_ADD: ("_do_root_add", INLINE),
MNP.ROOT_REMOVE: ("_do_root_remove", INLINE),
- MNP.ROOT_UPDATE: ("_do_root_update", INLINE),
MNP.ROOT_EJECT: ("_do_root_eject", INLINE),
MNP.ROOT_PLUG: ("_do_root_plug", INLINE),
- MNP.ROSTER_READ: ("_do_roster_read", SPAWNED),
- MNP.DENYLIST_READ: ("_do_denylist_read", SPAWNED),
- MNP.DENYLIST_CLEAR: ("_do_denylist_clear", SPAWNED),
- MNP.GROUP_ATTACH: ("_do_group_attach", INLINE),
- MNP.GROUP_DETACH: ("_do_group_detach", INLINE),
- MNP.NODE_SETTINGS_SET: ("_do_node_settings_set", SPAWNED),
- MNP.NODE_RELOAD: ("_do_node_reload", SPAWNED),
MNP.KEYPAIR_BUNDLE_STORE: ("_do_keypair_bundle_store", SPAWNED),
MNP.KEYPAIR_BUNDLE_DELETE: ("_do_keypair_bundle_delete", SPAWNED),
MNP.USER_BLOB_STORE: ("_do_user_blob_store", SPAWNED),
diff --git a/packages/meshbay-node/src/meshbay_node/transport/webrtc/group_ops.py b/packages/meshbay-node/src/meshbay_node/transport/webrtc/group_ops.py
index 3756eac..a94e2aa 100644
--- a/packages/meshbay-node/src/meshbay_node/transport/webrtc/group_ops.py
+++ b/packages/meshbay-node/src/meshbay_node/transport/webrtc/group_ops.py
@@ -5,9 +5,7 @@ from meshbay_common import MNP_VERSION
from meshbay_common.adminop import (
OP_APP_DIRECTORIES,
OP_APPS_ENABLED,
- OP_GEK_ROTATE,
OP_MEMBER_REVOKE,
- OP_MEMBER_UNPIN,
OP_SEARCH_LISTED,
)
from meshbay_common.groupbox import PURPOSE_ROSTER, seal
@@ -41,88 +39,6 @@ class GroupOpsMixin:
return
self._issue_admin_challenge(OP_MEMBER_REVOKE, user_id)
- def _do_gek_rotate(self, msg: dict) -> None:
- """
- Ask for a new group key. Operator only, and signed.
-
- This is what actually removes a revoked member's access: revocation
- stops the node serving the *next* key, and they still hold the current
- one. The node generates the replacement itself — nothing arriving here
- contributes key material, which is what the C5b rule is about.
- """
- group_id = str(msg.get("group_id", "")).strip() or self._group_id
- if not group_id:
- self._send({"type": "error", "detail": "No group on this connection"})
- return
- if not self._has_admin_authority():
- self._send({"type": "error", "detail": "No authorized key for this"})
- return
- self._issue_admin_challenge(OP_GEK_ROTATE, group_id, group_id=group_id)
-
- async def _admin_exec_gek_rotate(
- self, pending: dict, transcript: bytes, sig: bytes,
- ) -> None:
- if not await self._verify_admin_sig(transcript, sig):
- self._send({"type": "error", "detail": "Signature verification failed"})
- self._audit("admin_auth_failed", f"gek_rotate:{pending['subject'][:8]}")
- return
- try:
- result = await self._run_op(
- ops.set_gek, pending["subject"], rotate=True)
- except ops.OpError as e:
- self._send({"type": "error", "detail": e.message})
- return
- # The operator is rotating because somebody left, and the chat archive
- # key is not derived from the group key — so rotating that one does not
- # move this one. Doing both here is what makes "rotate after a removal"
- # mean the same thing for chat as it does for files.
- await self._new_chat_epoch(pending["subject"], "gek_rotate")
- self._audit("gek_rotate", pending["subject"])
- self._send({
- "type": MNP.GEK_ROTATE_ACK, "v": MNP_VERSION,
- "group_id": pending["subject"],
- "authorized_members": result.get("authorized_members", 0),
- # Said plainly, because rotating is the step people skip: content
- # already downloaded stays readable to whoever holds it.
- "note": "members re-receive the key on their next connect; content "
- "already downloaded is unaffected",
- })
-
- def _do_member_unpin(self, msg: dict) -> None:
- """Forget a pinned identity, so someone can pair again with a new key."""
- user_id = str(msg.get("user_id", "")).strip()
- if not user_id:
- self._send({"type": "error", "detail": "Missing user_id"})
- return
- if user_id == self._user_id:
- # Unpinning yourself over the connection your pin authorizes would
- # end that connection's authority mid-operation.
- self._send({"type": "error", "detail": "Cannot unpin yourself"})
- return
- if not self._has_admin_authority():
- self._send({"type": "error", "detail": "No authorized key for this"})
- return
- self._issue_admin_challenge(OP_MEMBER_UNPIN, user_id)
-
- async def _admin_exec_member_unpin(
- self, pending: dict, transcript: bytes, sig: bytes,
- ) -> None:
- user_id = pending["subject"]
- if not await self._verify_admin_sig(transcript, sig):
- self._send({"type": "error", "detail": "Signature verification failed"})
- self._audit("admin_auth_failed", f"member_unpin:{user_id[:8]}")
- return
- try:
- # The new chat epochs and the closed sessions are the op's own
- # (`ops.members._after_removal`), for every door alike.
- await self._run_op(ops.unpin_member, user_id)
- except ops.OpError as e:
- self._send({"type": "error", "detail": e.message})
- return
- self._audit("member_unpin", user_id)
- self._send({"type": MNP.MEMBER_UNPIN_ACK, "v": MNP_VERSION,
- "user_id": user_id})
-
# Every "application" a group can show. Photos joins this set (and
# apps.js's registry, client-side) when it lands; nothing else about
# this handler changes. DEFAULT_APPS (roster.py) deliberately does not
diff --git a/packages/meshbay-node/src/meshbay_node/transport/webrtc/node_ops.py b/packages/meshbay-node/src/meshbay_node/transport/webrtc/node_ops.py
index f7bbbfa..237a359 100644
--- a/packages/meshbay-node/src/meshbay_node/transport/webrtc/node_ops.py
+++ b/packages/meshbay-node/src/meshbay_node/transport/webrtc/node_ops.py
@@ -1,21 +1,16 @@
-"""The operator's controls over the node itself: status and settings, roster
-and denylist, roots, hosted groups, reload, scan pacing and transfer limits."""
+"""The operator's controls over a group's roots and scan pacing that MNP carries:
+removing, ejecting and plugging a root. What widens the sharing, and the node's
+own status, settings, roster and denylist, are the loopback API's and the CLI's
+(MNP 6.0)."""
import logging
from meshbay_common import MNP_VERSION
from meshbay_common.adminop import (
- OP_GROUP_ATTACH,
- OP_GROUP_DETACH,
- OP_ROOT_ADD,
OP_ROOT_EJECT,
OP_ROOT_PLUG,
OP_ROOT_REMOVE,
- OP_ROOT_UPDATE,
OP_SET_SCAN_SETTINGS,
- OP_TRANSFER_LIMITS,
- group_attach_subject,
- root_add_subject,
)
from meshbay_common.protocol import MNP
@@ -60,64 +55,6 @@ class NodeOpsMixin:
self._issue_admin_challenge(
OP_SET_SCAN_SETTINGS, f"{reconcile:g},{debounce:g}")
- MIN_TRANSFER_LIMIT = 1
- MAX_TRANSFER_LIMIT = 32
-
- def _do_transfer_limits(self, msg: dict) -> None:
- """How many transfers one member may run at once in this group.
-
- Zero is not "unlimited" and is refused: a member who may not transfer at
- all is a member the operator revokes, and reading 0 as no-limit would
- make the most dangerous value the easiest to type by accident.
- """
- try:
- downloads = int(msg.get("downloads"))
- uploads = int(msg.get("uploads"))
- except (TypeError, ValueError):
- self._send({"type": "error", "detail": "Invalid transfer limits"})
- return
- for value in (downloads, uploads):
- if not (self.MIN_TRANSFER_LIMIT <= value <= self.MAX_TRANSFER_LIMIT):
- self._send({"type": "error",
- "detail": f"transfer limits must be between "
- f"{self.MIN_TRANSFER_LIMIT} and "
- f"{self.MAX_TRANSFER_LIMIT}"})
- return
- if not self._has_admin_authority():
- self._send({"type": "error", "detail": "No authorized key for this"})
- return
- self._issue_admin_challenge(OP_TRANSFER_LIMITS,
- f"d={downloads},u={uploads}")
-
- async def _admin_exec_transfer_limits(
- self, pending: dict, transcript: bytes, sig: bytes,
- ) -> None:
- try:
- parts = dict(p.split("=") for p in pending["subject"].split(","))
- downloads, uploads = int(parts["d"]), int(parts["u"])
- except (ValueError, KeyError):
- self._send({"type": "error", "detail": "Invalid transfer limits"})
- return
- if not await self._verify_admin_sig(transcript, sig):
- self._send({"type": "error", "detail": "Signature verification failed"})
- self._audit("admin_auth_failed", f"transfer_limits:{pending['subject']}")
- return
- try:
- result = await self._run_op(
- ops.set_transfer_limits, self._group_id or "", downloads, uploads)
- except ops.OpError as e:
- self._send({"type": "error", "detail": e.message})
- return
- self._audit("transfer_limits", pending["subject"])
-
- notice = {"type": MNP.TRANSFER_LIMITS_ACK, "v": MNP_VERSION,
- "limits": result["limits"]}
- for session in list(self._peer_registry().values()):
- try:
- session._send(notice)
- except Exception:
- pass
-
async def _admin_exec_set_scan_settings(
self, pending: dict, transcript: bytes, sig: bytes,
) -> None:
@@ -146,245 +83,6 @@ class NodeOpsMixin:
except Exception:
pass
- # ── Node management (D5) ─────────────────────────────────────────────────
-
- async def _do_node_status(self, msg: dict) -> None:
- """All groups, roots, peers — the operator's overview.
-
- Including every root's absolute path, which is why this is gated on a
- proved operator device and not on an account the hub named.
- """
- node_uid = self._ctx.get("node_user_id")
- log.info("node_status: user=%s node_user=%s owner=%s device=%s",
- self._user_id, node_uid, self._is_node_admin(),
- "confirmed" if self._device_confirmed else "unidentified")
- if not await self._operator_device():
- self._send({"type": "error", "detail": "Not the node operator",
- "code": "not_operator"})
- return
- try:
- result = await self._run_op(ops.list_groups)
- self._send({"type": MNP.NODE_STATUS_ACK, "v": MNP_VERSION, **result})
- except ops.OpError as e:
- self._send({"type": "error", "detail": e.message})
- except Exception as e:
- log.error("node_status failed: %s", e, exc_info=True)
- self._send({"type": "error", "detail": "Internal error"})
-
- async def _do_node_settings_set(self, msg: dict) -> None:
- if not await self._operator_device():
- self._send({"type": "error", "detail": "Not the node operator",
- "code": "not_operator"})
- return
- settings = msg.get("settings", {})
- if not settings:
- self._send({"type": "error", "detail": "No settings provided"})
- return
- try:
- result = await self._run_op(ops.set_node_settings, settings)
- self._send({"type": MNP.NODE_SETTINGS_SET_ACK, "v": MNP_VERSION,
- **result})
- except ops.OpError as e:
- self._send({"type": "error", "detail": e.message})
- except Exception as e:
- log.error("node_settings_set failed: %s", e, exc_info=True)
- self._send({"type": "error", "detail": "Internal error"})
-
- async def _do_roster_read(self, msg: dict) -> None:
- if not await self._operator_device():
- self._send({"type": "error", "detail": "Not the node operator",
- "code": "not_operator"})
- return
- group_id = str(msg.get("group_id", "")).strip()
- try:
- result = await self._run_op(ops.read_roster, group_id)
- self._send({"type": MNP.ROSTER_READ_ACK, "v": MNP_VERSION, **result})
- except ops.OpError as e:
- self._send({"type": "error", "detail": e.message})
- except Exception as e:
- log.error("roster_read failed: %s", e, exc_info=True)
- self._send({"type": "error", "detail": "Internal error"})
-
- async def _do_denylist_read(self, msg: dict) -> None:
- if not await self._operator_device():
- self._send({"type": "error", "detail": "Not the node operator",
- "code": "not_operator"})
- return
- try:
- result = await self._run_op(ops.read_denylist)
- self._send({"type": MNP.DENYLIST_READ_ACK, "v": MNP_VERSION, **result})
- except ops.OpError as e:
- self._send({"type": "error", "detail": e.message})
- except Exception as e:
- log.error("denylist_read failed: %s", e, exc_info=True)
- self._send({"type": "error", "detail": "Internal error"})
-
- async def _do_denylist_clear(self, msg: dict) -> None:
- if not await self._operator_device():
- self._send({"type": "error", "detail": "Not the node operator",
- "code": "not_operator"})
- return
- subject = str(msg.get("subject", "")).strip()
- try:
- result = await self._run_op(ops.clear_denylist, subject=subject)
- self._audit("denylist_clear", subject or "all")
- self._send({"type": MNP.DENYLIST_CLEAR_ACK, "v": MNP_VERSION, **result})
- except ops.OpError as e:
- self._send({"type": "error", "detail": e.message})
- except Exception as e:
- log.error("denylist_clear failed: %s", e, exc_info=True)
- self._send({"type": "error", "detail": "Internal error"})
-
- def _do_group_attach(self, msg: dict) -> None:
- name = str(msg.get("name", "")).strip()
- shared_dir = str(msg.get("shared_dir", "")).strip()
- if not name or not shared_dir:
- self._send({"type": "error", "detail": "Missing name or shared_dir"})
- return
- if not self._has_admin_authority():
- self._send({"type": "error", "detail": "No authorized key for this"})
- return
- # `upload_dir` is not read here any more, and a client still sending it
- # is ignored rather than obeyed: on load it forces every other root
- # read-only, which is the model the RO/RW one replaced. A second
- # writable directory is `root_add` with `writable`.
- writable = bool(msg.get("writable", True))
- # The directory being exposed is signed, not only the group's name.
- self._issue_admin_challenge(
- OP_GROUP_ATTACH, group_attach_subject(name, shared_dir, writable),
- payload={"name": name, "shared_dir": shared_dir, "writable": writable},
- group_id="")
-
- async def _admin_exec_group_attach(
- self, pending: dict, transcript: bytes, sig: bytes,
- ) -> None:
- if not await self._verify_admin_sig(transcript, sig):
- self._send({"type": "error", "detail": "Signature verification failed"})
- self._audit("admin_auth_failed",
- f"group_attach:{pending['subject'][:16]}")
- return
- p = pending.get("payload") or {}
- try:
- result = await self._run_op(
- ops.attach_group, p["name"], p["shared_dir"],
- writable=bool(p.get("writable", True)))
- except ops.OpError as e:
- self._send({"type": "error", "detail": e.message})
- return
- self._audit("group_attach", pending["subject"])
- self._send({"type": MNP.GROUP_ATTACH_ACK, "v": MNP_VERSION, **result})
- state = self._ctx.get("daemon_state")
- reload_fn = state.get("reload_fn") if state else None
- if reload_fn:
- try:
- await reload_fn()
- except Exception as e:
- log.error("Reload after group_attach failed: %s", e)
-
- def _do_group_detach(self, msg: dict) -> None:
- name = str(msg.get("name", "")).strip()
- if not name:
- self._send({"type": "error", "detail": "Missing group name or id"})
- return
- if not self._has_admin_authority():
- self._send({"type": "error", "detail": "No authorized key for this"})
- return
- self._issue_admin_challenge(
- OP_GROUP_DETACH, name,
- payload={"name": name},
- group_id="")
-
- async def _admin_exec_group_detach(
- self, pending: dict, transcript: bytes, sig: bytes,
- ) -> None:
- if not await self._verify_admin_sig(transcript, sig):
- self._send({"type": "error", "detail": "Signature verification failed"})
- self._audit("admin_auth_failed",
- f"group_detach:{pending['subject'][:16]}")
- return
- p = pending.get("payload") or {}
- try:
- result = await self._run_op(ops.detach_group, p["name"])
- except ops.OpError as e:
- self._send({"type": "error", "detail": e.message})
- return
- self._audit("group_detach", pending["subject"])
- self._send({"type": MNP.GROUP_DETACH_ACK, "v": MNP_VERSION, **result})
- state = self._ctx.get("daemon_state")
- reload_fn = state.get("reload_fn") if state else None
- if reload_fn:
- try:
- await reload_fn()
- except Exception as e:
- log.error("Reload after group_detach failed: %s", e)
-
- async def _do_node_reload(self, msg: dict) -> None:
- if not await self._operator_device():
- self._send({"type": "error", "detail": "Not the node operator",
- "code": "not_operator"})
- return
- state = self._ctx.get("daemon_state")
- reload_fn = state.get("reload_fn") if state else None
- if not reload_fn:
- self._send({"type": "error", "detail": "Reload not available"})
- return
- try:
- await reload_fn()
- self._send({"type": MNP.NODE_RELOAD_ACK, "v": MNP_VERSION,
- "status": "reloaded"})
- except Exception as e:
- log.error("node_reload failed: %s", e, exc_info=True)
- self._send({"type": "error", "detail": "Reload failed"})
-
- def _do_root_add(self, msg: dict) -> None:
- target_group = str(msg.get("group_id", "")).strip()
- path = str(msg.get("path", "")).strip()
- if not target_group or not path:
- self._send({"type": "error", "detail": "Missing group_id or path"})
- return
- if not self._has_admin_authority():
- self._send({"type": "error", "detail": "No authorized key for this"})
- return
- payload = {
- "group_id": target_group, "path": path,
- "name": str(msg.get("name", ""))[:128],
- "kind": str(msg.get("kind", "generic"))[:16],
- "writable": bool(msg.get("writable", msg.get("upload", False))),
- "removable": bool(msg.get("removable", False)),
- }
- # Everything the executor acts on is signed — `writable` decides whether
- # every member may write there. The group is in the transcript itself.
- self._issue_admin_challenge(
- OP_ROOT_ADD,
- root_add_subject(path, payload["name"], payload["kind"],
- payload["writable"], payload["removable"]),
- payload=payload, group_id=target_group)
-
- async def _admin_exec_root_add(
- self, pending: dict, transcript: bytes, sig: bytes,
- ) -> None:
- if not await self._verify_admin_sig(transcript, sig):
- self._send({"type": "error", "detail": "Signature verification failed"})
- self._audit("admin_auth_failed", f"root_add:{pending['subject'][:24]}")
- return
- p = pending["payload"]
- try:
- result = await self._run_op(
- ops.add_root, p["group_id"], p["path"],
- name=p.get("name", ""), kind=p.get("kind", "generic"),
- writable=p.get("writable", False),
- removable=p.get("removable", False))
- except ops.OpError as e:
- self._send({"type": "error", "detail": e.message})
- return
- except Exception as e:
- log.error("root_add failed: %s", e, exc_info=True)
- self._send({"type": "error", "detail": "Internal error"})
- return
- self._audit("root_add", f"{p['path']}→{p['group_id'][:8]}")
- await self._retarget_indexer(p["group_id"])
- self._send({"type": MNP.ROOT_ADD_ACK, "v": MNP_VERSION, **result})
-
def _do_root_remove(self, msg: dict) -> None:
target_group = str(msg.get("group_id", "")).strip()
root_name = str(msg.get("root_name", "")).strip()
@@ -421,59 +119,6 @@ class NodeOpsMixin:
await self._retarget_indexer(p["group_id"])
self._send({"type": MNP.ROOT_REMOVE_ACK, "v": MNP_VERSION, **result})
- def _do_root_update(self, msg: dict) -> None:
- target_group = str(msg.get("group_id", self._group_id or "")).strip()
- root_name = str(msg.get("root_name", "")).strip()
- if not target_group or not root_name:
- self._send({"type": "error", "detail": "Missing group_id or root_name"})
- return
- if not self._has_admin_authority():
- self._send({"type": "error", "detail": "No authorized key for this"})
- return
- updates = []
- if "writable" in msg:
- updates.append(f"rw={'on' if msg['writable'] else 'off'}")
- if "removable" in msg:
- updates.append(f"rem={'on' if msg['removable'] else 'off'}")
- subject = f"{root_name}:{','.join(updates)}" if updates else root_name
- self._issue_admin_challenge(
- OP_ROOT_UPDATE, subject,
- payload={
- "group_id": target_group, "root_name": root_name,
- "writable": msg.get("writable"),
- "removable": msg.get("removable"),
- },
- group_id=target_group)
-
- async def _admin_exec_root_update(
- self, pending: dict, transcript: bytes, sig: bytes,
- ) -> None:
- if not await self._verify_admin_sig(transcript, sig):
- self._send({"type": "error", "detail": "Signature verification failed"})
- self._audit("admin_auth_failed",
- f"root_update:{pending['subject'][:24]}")
- return
- p = pending["payload"]
- try:
- result = await self._run_op(
- ops.update_root, p["group_id"], p["root_name"],
- writable=p.get("writable"), removable=p.get("removable"))
- except ops.OpError as e:
- self._send({"type": "error", "detail": e.message})
- return
- except Exception as e:
- log.error("root_update failed: %s", e, exc_info=True)
- self._send({"type": "error", "detail": "Internal error"})
- return
- self._audit("root_update", pending["subject"])
- await self._retarget_indexer(p["group_id"])
- notice = {"type": MNP.ROOT_UPDATE_ACK, "v": MNP_VERSION, **result}
- for uid, session in list(self._peer_registry().items()):
- try:
- session._send(notice)
- except Exception:
- pass
-
def _do_root_eject(self, msg: dict) -> None:
target_group = str(msg.get("group_id", self._group_id or "")).strip()
root_name = str(msg.get("root_name", "")).strip()
@@ -558,24 +203,21 @@ class NodeOpsMixin:
async def _retarget_indexer(self, group_id: str) -> None:
"""
- Pick up a root that was just added to or removed from node.toml.
+ Pick up a root that was just removed from node.toml.
Through the daemon's own reload, which is what the loopback API has
always done after the same operations (`ui/app.py`). This used to
re-point the indexer at `groups_ctx[gid]["roots"]` instead — the very
object the op had just edited — so `retarget` diffed a set against
- itself, found no new names, scanned nothing, and dropped nothing. A
- directory added over MNP reached node.toml and was invisible until a
- restart; one removed kept serving its files.
+ itself, found no new names, scanned nothing, and dropped nothing: a
+ directory removed over MNP kept serving its files until a restart.
Two front doors doing different things is the shape `ops.py` exists to
prevent, and this was it: the loopback path worked and the MNP path did
- not, which is why it survived until the operator added a directory from
- a browser.
+ not.
- Not awaited: a reload rescans, and a new library is minutes. The ack
- the caller sends carries the set the node is moving to, and the
- `index_sync` that follows the scan carries what it found.
+ Not awaited: a reload can be long. The ack the caller sends carries the
+ set the node is moving to.
"""
state = self._ctx.get("daemon_state")
if not state:
diff --git a/packages/meshbay-node/src/meshbay_node/ui/app.py b/packages/meshbay-node/src/meshbay_node/ui/app.py
index f810903..03db8b6 100644
--- a/packages/meshbay-node/src/meshbay_node/ui/app.py
+++ b/packages/meshbay-node/src/meshbay_node/ui/app.py
@@ -120,6 +120,10 @@ def create_ui_app(state: dict) -> FastAPI:
@app.get("/api/status")
async def api_status():
+ """
+ The daemon's state, and what it still needs: a linked key, a group, an operator, a group
+ key.
+ """
indexes = state.get("indexes", {})
total_files = sum(idx.count for idx in indexes.values())
groups_ctx = state.get("groups_ctx", {})
@@ -163,6 +167,7 @@ def create_ui_app(state: dict) -> FastAPI:
@app.delete("/api/unlink")
async def api_unlink():
+ """Unlink the node's key from its hub account."""
hub = state.get("hub")
if not hub:
raise HTTPException(status_code=503, detail="Hub not connected")
@@ -171,9 +176,13 @@ def create_ui_app(state: dict) -> FastAPI:
@app.get("/api/groups")
async def api_groups():
+ """The groups this node hosts, with live status, and whether an operator is paired."""
return await _op(lambda: ops.list_groups(state))
@app.post("/api/groups/attach")
async def attach_group(payload: dict):
+ """
+ Host a group that exists on the hub: add it to node.toml with its first folder, then reload.
+ """
result = await _op(lambda: ops.attach_group(
state,
(payload.get("name") or "").strip(),
@@ -188,6 +197,7 @@ def create_ui_app(state: dict) -> FastAPI:
@app.post("/api/groups/detach")
async def detach_group(payload: dict):
+ """Stop hosting a group: remove it from node.toml, then reload."""
result = await _op(lambda: ops.detach_group(
state,
(payload.get("name") or payload.get("group_id") or "").strip(),
@@ -199,31 +209,41 @@ def create_ui_app(state: dict) -> FastAPI:
@app.delete("/api/groups/{group_id}/files/{file_id}")
async def delete_file(group_id: str, file_id: str):
- """Milestone 14.11 — the last operator action that needed a browser."""
+ """
+ Delete a file from the group's folder on disk.
+
+ Milestone 14.11 — the last operator action that needed a browser.
+ """
return await _op(lambda: ops.delete_file(state, group_id, file_id))
@app.get("/api/denylist")
async def api_denylist():
+ """What the node currently refuses."""
return await _op(lambda: ops.read_denylist(state))
@app.post("/api/denylist/clear")
async def api_denylist_clear(subject: str = ""):
+ """Drop denylist entries: all of them, or one identifier."""
return await _op(lambda: ops.clear_denylist(state, subject=subject))
@app.get("/api/index-cache")
async def api_index_cache_stats():
+ """Size of the index cache."""
return await _op(lambda: ops.index_cache_stats(state))
@app.post("/api/index-cache/prune")
async def api_index_cache_prune():
+ """Drop index cache rows that no longer match a file on disk."""
return await _op(lambda: ops.prune_index_cache(state))
@app.post("/api/groups/{group_id}/video/rematch")
async def api_video_rematch(group_id: str):
+ """Forget the automatic matches of the group's videos, so they are looked up again."""
return await _op(lambda: ops.rematch_video(state, group_id))
@app.get("/api/groups/{group_id}/files")
async def api_group_files(group_id: str):
+ """The group's files, from its index."""
groups_ctx = state.get("groups_ctx", {})
ctx = groups_ctx.get(group_id)
if not ctx:
@@ -247,6 +267,7 @@ def create_ui_app(state: dict) -> FastAPI:
@app.get("/api/peers")
async def api_peers():
+ """The connected peers."""
webrtc = state.get("webrtc")
if not webrtc:
return {"peers": []}
@@ -275,6 +296,7 @@ def create_ui_app(state: dict) -> FastAPI:
user_id: str | None = Query(default=None),
event: str | None = Query(default=None),
):
+ """The audit log, filtered by time, account and event."""
audit = state.get("audit_store")
if not audit:
return {"entries": [], "offset": 0, "limit": limit, "has_more": False}
@@ -316,66 +338,80 @@ def create_ui_app(state: dict) -> FastAPI:
@app.post("/api/operator/pair")
async def operator_pair():
+ """A one-time code that pairs an application as this node's operator."""
return await _op(lambda: ops.pair_operator(state))
@app.get("/api/roster")
async def api_roster(group_id: str = ""):
+ """The pinned identities, for one group or all."""
return await _op(lambda: ops.read_roster(state, group_id))
@app.post("/api/groups/{group_id}/invites")
async def create_invite(group_id: str, username: str):
+ """An invitation code for one account, for this group."""
return await _op(lambda: ops.create_invite(state, group_id, username))
# Both halves, node and hub, for the CLI: an operator at the machine gets a
# whole link, not a code without a ticket.
@app.post("/api/groups/{group_id}/invite-links")
async def create_link_invite(group_id: str, email: str = ""):
+ """A whole invitation link: the node's code, then the hub's ticket."""
return await _op(lambda: ops.create_link_invitation(state, group_id, email))
@app.delete("/api/groups/{group_id}/invite-links/{invite_id}")
async def cancel_invite(group_id: str, invite_id: str):
+ """Take an invitation link back, on the node and on the hub."""
return await _op(lambda: ops.cancel_link_invitation(state, group_id, invite_id))
@app.get("/api/resolve")
async def resolve_user(username: str):
+ """Map a username to an account id, through the hub."""
return await _op(lambda: ops.resolve_user(state, username))
@app.post("/api/members/{user_id}/revoke")
async def revoke_member(user_id: str, group_id: str):
+ """Stop serving the group key to a member."""
return await _op(lambda: ops.revoke_member(state, user_id, group_id))
@app.post("/api/members/{user_id}/unpin")
async def unpin_member(user_id: str):
+ """Forget a pinned identity, so the person can pair again with a new key."""
return await _op(lambda: ops.unpin_member(state, user_id))
# ── Chat encryption (operator only, localhost) ─────────────────────────
@app.get("/api/groups/{group_id}/chat")
async def chat_status(group_id: str):
+ """What the operator needs to decide anything about the group's chat."""
return await _op(lambda: ops.chat_status(state, group_id))
@app.post("/api/groups/{group_id}/chat/epoch")
async def rotate_chat_epoch(group_id: str):
+ """Open a new chat epoch."""
return await _op(lambda: ops.open_chat_epoch(state, group_id))
@app.post("/api/groups/{group_id}/chat/encrypt-history")
async def encrypt_chat_history(group_id: str):
+ """Re-encrypt the messages written before the group's chat was encrypted."""
return await _op(lambda: ops.encrypt_chat_history(state, group_id))
@app.post("/api/groups/{group_id}/chat/prune")
async def prune_chat(group_id: str, max_age_days: int):
+ """Delete chat messages older than a number of days."""
return await _op(lambda: ops.prune_chat(state, group_id, max_age_days))
# ── GEK initialization (operator only, localhost) ──────────────────────
@app.post("/api/groups/{group_id}/gek")
async def init_gek(group_id: str, rotate: bool = False):
+ """Generate the group key, or rotate it with ?rotate=true."""
return await _op(lambda: ops.set_gek(state, group_id, rotate=rotate))
# ── Roots management (operator only, localhost) ────────────────────────
@app.post("/api/groups/{group_id}/roots")
async def add_root(group_id: str, payload: dict):
+ """Add a folder to a group."""
result = await _op(lambda: ops.add_root(
state, group_id,
(payload.get("path") or "").strip(),
@@ -392,6 +428,7 @@ def create_ui_app(state: dict) -> FastAPI:
@app.patch("/api/groups/{group_id}/roots/{root_name}")
async def update_root(group_id: str, root_name: str, payload: dict):
+ """Make a folder writable or removable, or not."""
result = await _op(lambda: ops.update_root(
state, group_id, root_name,
writable=payload.get("writable"),
@@ -404,14 +441,17 @@ def create_ui_app(state: dict) -> FastAPI:
@app.put("/api/groups/{group_id}/roots/{root_name}/eject")
async def eject_root(group_id: str, root_name: str):
+ """Eject a removable folder so its disk can be unplugged."""
return await _op(lambda: ops.eject_root(state, group_id, root_name))
@app.put("/api/groups/{group_id}/roots/{root_name}/plug")
async def plug_root(group_id: str, root_name: str):
+ """Bring an ejected folder back."""
return await _op(lambda: ops.plug_root(state, group_id, root_name))
@app.delete("/api/groups/{group_id}/roots/{root_name}")
async def remove_root(group_id: str, root_name: str):
+ """Remove a folder from a group. At least one must remain."""
result = await _op(lambda: ops.remove_root(state, group_id, root_name))
reload_fn = state.get("reload_fn")
if reload_fn:
@@ -427,6 +467,8 @@ def create_ui_app(state: dict) -> FastAPI:
@app.get("/api/groups/{group_id}/index-status")
async def index_status(group_id: str):
"""
+ One group's indexing progress.
+
Polled by the Create Group wizard and by "add a directory" in
Settings — the same source either way, since both just start a scan
on this group's indexer. `current_dir` is a basename only, and is
@@ -454,7 +496,9 @@ def create_ui_app(state: dict) -> FastAPI:
@app.get("/api/index-status")
async def index_status_all():
"""
- Every group's indexing at once, for the client's progress band — which
+ Every group's indexing progress.
+
+ All groups at once, for the client's progress band — which
is on screen whatever page the operator is on, so it cannot ask per
group. Names roots, like `current_dir` above: loopback only, the
operator's own screen. Reads state["indexers"] for the same reason.
@@ -488,6 +532,7 @@ def create_ui_app(state: dict) -> FastAPI:
@app.put("/api/groups/{group_id}/apps")
async def set_enabled_apps(group_id: str, payload: dict):
+ """Which applications members see for the group."""
apps = payload.get("apps")
if not isinstance(apps, list) or not apps:
raise HTTPException(400, "apps must be a non-empty list")
@@ -497,6 +542,7 @@ def create_ui_app(state: dict) -> FastAPI:
@app.post("/api/reload")
async def reload_config():
+ """Reload node.toml. Returns before the reload finishes."""
# start_reload, not reload_config: this must return before a
# brand-new group's synchronous initial scan finishes (minutes, not
# seconds, on a real library) — see ops.start_reload for why.
@@ -506,6 +552,7 @@ def create_ui_app(state: dict) -> FastAPI:
@app.post("/api/shutdown")
async def shutdown():
+ """Stop the daemon."""
# The graceful stop every front door tries first (the desktop app, the
# CLI, the installer): it reaches a node in any session -- a service
# node runs in session 0, where taskkill and CTRL_BREAK from the user's
@@ -521,24 +568,27 @@ def create_ui_app(state: dict) -> FastAPI:
@app.get("/api/node-settings")
async def get_node_settings():
+ """The node's effective settings."""
return await _op(lambda: ops.get_node_settings(state))
@app.put("/api/node-settings")
async def update_node_settings(payload: dict):
+ """Change node settings, written to roster.db and node.toml."""
return await _op(lambda: ops.set_node_settings(state, payload))
# ── Transfers (operator only, localhost) ───────────────────────────────
@app.get("/api/transfers")
async def get_transfers():
+ """Live transfer leases and queue depth."""
return await _op(lambda: ops.list_transfers(state))
@app.put("/api/groups/{group_id}/transfer-limits")
async def set_transfer_limits(group_id: str, payload: dict):
- # The same `ops.set_transfer_limits` the signed MNP handler calls. The
- # op existed with only that one door, and nothing anywhere opened it —
- # so the per-member cap sat at its default of 2 with no way to change
- # it, which from outside is indistinguishable from a hardcoded 2.
+ """How many transfers one member may run at once in this group."""
+ # The only door to `ops.set_transfer_limits` (the CLI uses it). It once
+ # had only a signed MNP message, which nothing anywhere sent — so the
+ # per-member cap sat at its default of 2 with no way to change it.
return await _op(lambda: ops.set_transfer_limits(
state, group_id,
int(payload.get("downloads", 0)), int(payload.get("uploads", 0))))
diff --git a/packages/meshbay-node/tests/golden/dispatch.json b/packages/meshbay-node/tests/golden/dispatch.json
index a7bb543..61bbc45 100644
--- a/packages/meshbay-node/tests/golden/dispatch.json
+++ b/packages/meshbay-node/tests/golden/dispatch.json
@@ -76,30 +76,6 @@
"_admin_exec_file_delete"
]
},
- "gek_rotate": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_admin_exec_gek_rotate"
- ]
- },
- "group_attach": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_admin_exec_group_attach"
- ]
- },
- "group_detach": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_admin_exec_group_detach"
- ]
- },
"invite_cancel": {
"audit": [],
"log": [],
@@ -132,14 +108,6 @@
"_admin_exec_member_revoke"
]
},
- "member_unpin": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_admin_exec_member_unpin"
- ]
- },
"musicbrainz_enabled": {
"audit": [],
"log": [],
@@ -160,14 +128,6 @@
],
"spawned": []
},
- "root_add": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_admin_exec_root_add"
- ]
- },
"root_eject": {
"audit": [],
"log": [],
@@ -192,14 +152,6 @@
"_admin_exec_root_remove"
]
},
- "root_update": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_admin_exec_root_update"
- ]
- },
"search_listed": {
"audit": [],
"log": [],
@@ -247,14 +199,6 @@
"spawned": [
"_admin_exec_tmdb_rematch"
]
- },
- "transfer_limits": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_admin_exec_transfer_limits"
- ]
}
},
"dispatch": {
@@ -2068,7 +2012,7 @@
"subject": "x",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -2391,7 +2335,7 @@
"subject": "gggggggggggggggggggggggggggggggg",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -2410,7 +2354,7 @@
"subject": "['x']",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -2429,7 +2373,7 @@
"subject": "7",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -2448,7 +2392,7 @@
"subject": "x",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -2718,7 +2662,7 @@
"messages": [],
"req_id": 4242,
"type": "chat_hist_resp",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -2732,7 +2676,7 @@
"messages": [],
"req_id": 4242,
"type": "chat_hist_resp",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -2746,7 +2690,7 @@
"messages": [],
"req_id": 4242,
"type": "chat_hist_resp",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -2760,7 +2704,7 @@
"messages": [],
"req_id": 4242,
"type": "chat_hist_resp",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -2774,7 +2718,7 @@
"messages": [],
"req_id": 4242,
"type": "chat_hist_resp",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -2788,7 +2732,7 @@
"messages": [],
"req_id": 4242,
"type": "chat_hist_resp",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -2802,7 +2746,7 @@
"messages": [],
"req_id": 4242,
"type": "chat_hist_resp",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -2816,7 +2760,7 @@
"messages": [],
"req_id": 4242,
"type": "chat_hist_resp",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -4029,646 +3973,6 @@
"sent": [],
"spawned": []
},
- "denylist_clear | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear | member | bare": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_clear"
- ]
- },
- "denylist_clear | member | lists": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_clear"
- ]
- },
- "denylist_clear | member | numbers": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_clear"
- ]
- },
- "denylist_clear | member | strings": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_clear"
- ]
- },
- "denylist_clear | operator | bare": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_clear"
- ]
- },
- "denylist_clear | operator | lists": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_clear"
- ]
- },
- "denylist_clear | operator | numbers": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_clear"
- ]
- },
- "denylist_clear | operator | strings": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_clear"
- ]
- },
- "denylist_clear_ack | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear_ack | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear_ack | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear_ack | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear_ack | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear_ack | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear_ack | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear_ack | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_clear_ack | member | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_clear_ack | member | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_clear_ack | member | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_clear_ack | member | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_clear_ack | operator | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_clear_ack | operator | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_clear_ack | operator | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_clear_ack | operator | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_read | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read | member | bare": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_read"
- ]
- },
- "denylist_read | member | lists": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_read"
- ]
- },
- "denylist_read | member | numbers": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_read"
- ]
- },
- "denylist_read | member | strings": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_read"
- ]
- },
- "denylist_read | operator | bare": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_read"
- ]
- },
- "denylist_read | operator | lists": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_read"
- ]
- },
- "denylist_read | operator | numbers": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_read"
- ]
- },
- "denylist_read | operator | strings": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_denylist_read"
- ]
- },
- "denylist_read_ack | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read_ack | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read_ack | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read_ack | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read_ack | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read_ack | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read_ack | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read_ack | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "denylist_read_ack | member | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_read_ack | member | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_read_ack | member | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_read_ack | member | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_read_ack | operator | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_read_ack | operator | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_read_ack | operator | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "denylist_read_ack | operator | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
"device_add | challenged | bare": {
"audit": [],
"log": [],
@@ -8377,1132 +7681,6 @@
"sent": [],
"spawned": []
},
- "gek_rotate | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate | member | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate | member | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate | member | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate | member | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate | operator | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "gggggggggggggggggggggggggggggggg",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "gek_rotate",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "gggggggggggggggggggggggggggggggg",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "gek_rotate | operator | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "['x']",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "gek_rotate",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "['x']",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "gek_rotate | operator | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "7",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "gek_rotate",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "7",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "gek_rotate | operator | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "x",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "gek_rotate",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "x",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "gek_rotate_ack | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate_ack | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate_ack | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate_ack | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate_ack | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate_ack | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate_ack | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate_ack | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "gek_rotate_ack | member | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "gek_rotate_ack | member | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "gek_rotate_ack | member | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "gek_rotate_ack | member | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "gek_rotate_ack | operator | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "gek_rotate_ack | operator | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "gek_rotate_ack | operator | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "gek_rotate_ack | operator | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_attach | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach | member | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Missing name or shared_dir",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach | member | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach | member | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach | member | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach | operator | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Missing name or shared_dir",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach | operator | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "group_attach",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "{\"name\":\"['x']\",\"shared_dir\":\"['x']\",\"writable\":true}",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "group_attach | operator | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "group_attach",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "{\"name\":\"7\",\"shared_dir\":\"7\",\"writable\":true}",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "group_attach | operator | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "group_attach",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "{\"name\":\"x\",\"shared_dir\":\"x\",\"writable\":true}",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "group_attach_ack | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach_ack | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach_ack | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach_ack | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach_ack | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach_ack | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach_ack | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach_ack | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_attach_ack | member | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_attach_ack | member | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_attach_ack | member | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_attach_ack | member | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_attach_ack | operator | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_attach_ack | operator | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_attach_ack | operator | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_attach_ack | operator | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_detach | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach | member | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Missing group name or id",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach | member | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach | member | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach | member | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach | operator | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Missing group name or id",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach | operator | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "group_detach",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "['x']",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "group_detach | operator | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "group_detach",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "7",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "group_detach | operator | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "group_detach",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "x",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "group_detach_ack | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach_ack | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach_ack | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach_ack | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach_ack | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach_ack | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach_ack | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach_ack | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "group_detach_ack | member | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_detach_ack | member | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_detach_ack | member | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_detach_ack | member | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_detach_ack | operator | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_detach_ack | operator | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_detach_ack | operator | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "group_detach_ack | operator | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
"group_roster_req | challenged | bare": {
"audit": [],
"log": [],
@@ -11641,7 +9819,7 @@
"subject": "link:gggggggggggggggggggggggggggggggg",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -13740,7 +11918,7 @@
"subject": "['x']",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -13759,7 +11937,7 @@
"subject": "7",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -13778,7 +11956,7 @@
"subject": "x",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -13943,379 +12121,6 @@
"sent": [],
"spawned": []
},
- "member_unpin | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin | member | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Missing user_id",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin | member | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin | member | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin | member | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin | operator | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Missing user_id",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin | operator | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "gggggggggggggggggggggggggggggggg",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "member_unpin",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "['x']",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "member_unpin | operator | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "gggggggggggggggggggggggggggggggg",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "member_unpin",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "7",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "member_unpin | operator | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "gggggggggggggggggggggggggggggggg",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "member_unpin",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "x",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "member_unpin_ack | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin_ack | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin_ack | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin_ack | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin_ack | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin_ack | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin_ack | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin_ack | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "member_unpin_ack | member | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "member_unpin_ack | member | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "member_unpin_ack | member | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "member_unpin_ack | member | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "member_unpin_ack | operator | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "member_unpin_ack | operator | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "member_unpin_ack | operator | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "member_unpin_ack | operator | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
"music_meta_req | challenged | bare": {
"audit": [],
"log": [],
@@ -15148,966 +12953,6 @@
"sent": [],
"spawned": []
},
- "node_reload | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload | member | bare": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_reload"
- ]
- },
- "node_reload | member | lists": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_reload"
- ]
- },
- "node_reload | member | numbers": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_reload"
- ]
- },
- "node_reload | member | strings": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_reload"
- ]
- },
- "node_reload | operator | bare": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_reload"
- ]
- },
- "node_reload | operator | lists": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_reload"
- ]
- },
- "node_reload | operator | numbers": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_reload"
- ]
- },
- "node_reload | operator | strings": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_reload"
- ]
- },
- "node_reload_ack | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload_ack | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload_ack | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload_ack | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload_ack | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload_ack | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload_ack | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload_ack | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_reload_ack | member | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_reload_ack | member | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_reload_ack | member | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_reload_ack | member | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_reload_ack | operator | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_reload_ack | operator | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_reload_ack | operator | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_reload_ack | operator | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_settings_set | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set | member | bare": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_settings_set"
- ]
- },
- "node_settings_set | member | lists": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_settings_set"
- ]
- },
- "node_settings_set | member | numbers": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_settings_set"
- ]
- },
- "node_settings_set | member | strings": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_settings_set"
- ]
- },
- "node_settings_set | operator | bare": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_settings_set"
- ]
- },
- "node_settings_set | operator | lists": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_settings_set"
- ]
- },
- "node_settings_set | operator | numbers": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_settings_set"
- ]
- },
- "node_settings_set | operator | strings": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_settings_set"
- ]
- },
- "node_settings_set_ack | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set_ack | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set_ack | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set_ack | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set_ack | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set_ack | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set_ack | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set_ack | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_settings_set_ack | member | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_settings_set_ack | member | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_settings_set_ack | member | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_settings_set_ack | member | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_settings_set_ack | operator | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_settings_set_ack | operator | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_settings_set_ack | operator | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_settings_set_ack | operator | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_status | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status | member | bare": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_status"
- ]
- },
- "node_status | member | lists": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_status"
- ]
- },
- "node_status | member | numbers": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_status"
- ]
- },
- "node_status | member | strings": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_status"
- ]
- },
- "node_status | operator | bare": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_status"
- ]
- },
- "node_status | operator | lists": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_status"
- ]
- },
- "node_status | operator | numbers": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_status"
- ]
- },
- "node_status | operator | strings": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_node_status"
- ]
- },
- "node_status_ack | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status_ack | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status_ack | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status_ack | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status_ack | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status_ack | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status_ack | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status_ack | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "node_status_ack | member | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_status_ack | member | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_status_ack | member | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_status_ack | member | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_status_ack | operator | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_status_ack | operator | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_status_ack | operator | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "node_status_ack | operator | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
"ping | challenged | bare": {
"audit": [],
"log": [],
@@ -16212,7 +13057,7 @@
"req_id": 4242,
"token": null,
"type": "pong",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -16227,7 +13072,7 @@
"x"
],
"type": "pong",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -16240,7 +13085,7 @@
"req_id": 4242,
"token": 7,
"type": "pong",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -16253,7 +13098,7 @@
"req_id": 4242,
"token": "x",
"type": "pong",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -16266,7 +13111,7 @@
"req_id": 4242,
"token": null,
"type": "pong",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -16281,7 +13126,7 @@
"x"
],
"type": "pong",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -16294,7 +13139,7 @@
"req_id": 4242,
"token": 7,
"type": "pong",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -16307,7 +13152,7 @@
"req_id": 4242,
"token": "x",
"type": "pong",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -16472,379 +13317,6 @@
"sent": [],
"spawned": []
},
- "root_add | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add | member | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Missing group_id or path",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add | member | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add | member | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add | member | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add | operator | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Missing group_id or path",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add | operator | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "['x']",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "root_add",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "{\"kind\":\"['x']\",\"name\":\"['x']\",\"path\":\"['x']\",\"removable\":true,\"writable\":true}",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "root_add | operator | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "7",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "root_add",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "{\"kind\":\"7\",\"name\":\"7\",\"path\":\"7\",\"removable\":true,\"writable\":true}",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "root_add | operator | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "x",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "root_add",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "{\"kind\":\"x\",\"name\":\"x\",\"path\":\"x\",\"removable\":true,\"writable\":true}",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "root_add_ack | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add_ack | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add_ack | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add_ack | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add_ack | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add_ack | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add_ack | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add_ack | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_add_ack | member | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_add_ack | member | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_add_ack | member | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_add_ack | member | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_add_ack | operator | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_add_ack | operator | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_add_ack | operator | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_add_ack | operator | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
"root_eject | challenged | bare": {
"audit": [],
"log": [],
@@ -17015,7 +13487,7 @@
"subject": "['x']",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -17034,7 +13506,7 @@
"subject": "7",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -17053,7 +13525,7 @@
"subject": "x",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -17388,7 +13860,7 @@
"subject": "['x']",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -17407,7 +13879,7 @@
"subject": "7",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -17426,7 +13898,7 @@
"subject": "x",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -17761,7 +14233,7 @@
"subject": "['x']",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -17780,7 +14252,7 @@
"subject": "7",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -17799,7 +14271,7 @@
"subject": "x",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -17964,699 +14436,6 @@
"sent": [],
"spawned": []
},
- "root_update | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update | member | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Missing group_id or root_name",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update | member | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update | member | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update | member | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update | operator | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Missing group_id or root_name",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update | operator | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "['x']",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "root_update",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "['x']:rw=on,rem=on",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "root_update | operator | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "7",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "root_update",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "7:rw=on,rem=on",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "root_update | operator | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "x",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "root_update",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "x:rw=on,rem=on",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "root_update_ack | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update_ack | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update_ack | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update_ack | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update_ack | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update_ack | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update_ack | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update_ack | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "root_update_ack | member | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_update_ack | member | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_update_ack | member | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_update_ack | member | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_update_ack | operator | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_update_ack | operator | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_update_ack | operator | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "root_update_ack | operator | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "roster_read | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read | member | bare": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_roster_read"
- ]
- },
- "roster_read | member | lists": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_roster_read"
- ]
- },
- "roster_read | member | numbers": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_roster_read"
- ]
- },
- "roster_read | member | strings": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_roster_read"
- ]
- },
- "roster_read | operator | bare": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_roster_read"
- ]
- },
- "roster_read | operator | lists": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_roster_read"
- ]
- },
- "roster_read | operator | numbers": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_roster_read"
- ]
- },
- "roster_read | operator | strings": {
- "audit": [],
- "log": [],
- "sent": [],
- "spawned": [
- "_do_roster_read"
- ]
- },
- "roster_read_ack | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read_ack | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read_ack | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read_ack | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read_ack | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read_ack | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read_ack | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read_ack | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "roster_read_ack | member | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "roster_read_ack | member | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "roster_read_ack | member | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "roster_read_ack | member | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "roster_read_ack | operator | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "roster_read_ack | operator | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "roster_read_ack | operator | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "roster_read_ack | operator | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
"search_listed | challenged | bare": {
"audit": [],
"log": [],
@@ -21119,7 +16898,7 @@
"subject": "{\"language\":null,\"token\":null}",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -21162,7 +16941,7 @@
"subject": "{\"language\":\"x\",\"token\":\"sha256:2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881\"}",
"ts": "<volatile>",
"type": "admin_challenge",
- "v": "5.0"
+ "v": "6.0"
}
],
"spawned": []
@@ -22867,365 +18646,6 @@
"sent": [],
"spawned": []
},
- "transfer_limits | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | member | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Invalid transfer limits",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | member | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Invalid transfer limits",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | member | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "No authorized key for this",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | member | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Invalid transfer limits",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | operator | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Invalid transfer limits",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | operator | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Invalid transfer limits",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits | operator | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "group_id": "gggggggggggggggggggggggggggggggg",
- "node_pk": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=",
- "nonce": "<volatile>",
- "op": "transfer_limits",
- "op_id": "<volatile>",
- "req_id": 4242,
- "subject": "d=7,u=7",
- "ts": "<volatile>",
- "type": "admin_challenge",
- "v": "5.0"
- }
- ],
- "spawned": []
- },
- "transfer_limits | operator | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Invalid transfer limits",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits_ack | challenged | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits_ack | challenged | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits_ack | challenged | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits_ack | challenged | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits_ack | fresh | bare": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits_ack | fresh | lists": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits_ack | fresh | numbers": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits_ack | fresh | strings": {
- "audit": [],
- "log": [],
- "sent": [
- {
- "detail": "Handshake required",
- "req_id": 4242,
- "type": "error"
- }
- ],
- "spawned": []
- },
- "transfer_limits_ack | member | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "transfer_limits_ack | member | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "transfer_limits_ack | member | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "transfer_limits_ack | member | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "transfer_limits_ack | operator | bare": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "transfer_limits_ack | operator | lists": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "transfer_limits_ack | operator | numbers": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
- "transfer_limits_ack | operator | strings": {
- "audit": [],
- "log": [
- "WARNING Unknown MNP message type on DataChannel: %s"
- ],
- "sent": [],
- "spawned": []
- },
"transfer_open | challenged | bare": {
"audit": [],
"log": [],
diff --git a/packages/meshbay-node/tests/test_admin_challenge_bounds.py b/packages/meshbay-node/tests/test_admin_challenge_bounds.py
index fd3b2f1..9dcb750 100644
--- a/packages/meshbay-node/tests/test_admin_challenge_bounds.py
+++ b/packages/meshbay-node/tests/test_admin_challenge_bounds.py
@@ -3,8 +3,9 @@ What a connection may leave waiting for a signature (docs/MESHBAY_DESIGN.md §13
Anyone authenticated can ask for an admin challenge — the signature is checked
later — so a member who never answers must not make the node keep every request.
-Measured before the bound: 200 `root_add` of 1 MiB each from a plain member held
-200 pending operations and ~400 MiB for the life of the connection.
+Measured before the bound: 200 `root_add` (an op since removed) of 1 MiB each
+from a plain member held 200 pending operations and ~400 MiB for the life of
+the connection.
"""
import struct
@@ -48,23 +49,24 @@ def _member_session():
return s
-def _root_add(s, path: str) -> dict:
- s._dispatch_message({"type": "root_add", "group_id": GROUP, "path": path})
+def _ask(s, path: str) -> dict:
+ """A signed op whose subject is whatever the caller sends."""
+ s._dispatch_message({"type": "chat_directory", "path": path})
return s._channel.sent[-1]
def test_a_member_cannot_pile_up_challenges():
s = _member_session()
for i in range(MAX_PENDING_ADMIN_OPS):
- assert _root_add(s, f"/srv/{i}")["type"] == "admin_challenge"
- refused = _root_add(s, "/srv/one-too-many")
+ assert _ask(s, f"/srv/{i}")["type"] == "admin_challenge"
+ refused = _ask(s, "/srv/one-too-many")
assert refused["type"] == "error" and refused["code"] == "too_many_pending"
assert len(s._admin_ops) == MAX_PENDING_ADMIN_OPS
def test_an_oversized_request_is_not_kept():
s = _member_session()
- refused = _root_add(s, "x" * (MAX_ADMIN_OP_BYTES + 1))
+ refused = _ask(s, "x" * (MAX_ADMIN_OP_BYTES + 1))
assert refused["type"] == "error" and refused["code"] == "too_large"
assert s._admin_ops == {}
@@ -72,21 +74,21 @@ def test_an_oversized_request_is_not_kept():
def test_an_expired_challenge_frees_its_place():
s = _member_session()
for i in range(MAX_PENDING_ADMIN_OPS):
- _root_add(s, f"/srv/{i}")
+ _ask(s, f"/srv/{i}")
for pending in s._admin_ops.values():
pending["ts"] -= 10_000
- assert _root_add(s, "/srv/after-expiry")["type"] == "admin_challenge"
+ assert _ask(s, "/srv/after-expiry")["type"] == "admin_challenge"
assert len(s._admin_ops) == 1
def test_answering_a_challenge_frees_its_place():
s = _member_session()
for i in range(MAX_PENDING_ADMIN_OPS):
- _root_add(s, f"/srv/{i}")
+ _ask(s, f"/srv/{i}")
op_id = next(iter(s._admin_ops))
s._dispatch_message({"type": "admin_response", "op_id": op_id, "signature": "!!"})
assert len(s._admin_ops) == MAX_PENDING_ADMIN_OPS - 1
- assert _root_add(s, "/srv/next")["type"] == "admin_challenge"
+ assert _ask(s, "/srv/next")["type"] == "admin_challenge"
assert all(time.time() - p["ts"] < 5 for p in s._admin_ops.values())
@@ -95,27 +97,6 @@ def test_answering_a_challenge_frees_its_place():
# The signature covers the subject and nothing else of a request, so every value
# the executor acts on has to be in it.
-def test_root_add_signs_whether_members_may_write():
- from meshbay_common.adminop import root_add_subject
- s = _member_session()
- s._dispatch_message({"type": "root_add", "group_id": GROUP, "path": "/srv/drop",
- "name": "Drop", "writable": True, "removable": False})
- challenge = s._channel.sent[-1]
- assert challenge["subject"] == root_add_subject("/srv/drop", "Drop", "generic",
- True, False)
- assert challenge["subject"] != root_add_subject("/srv/drop", "Drop", "generic",
- False, False)
-
-
-def test_group_attach_signs_the_directory_it_exposes():
- from meshbay_common.adminop import group_attach_subject
- s = _member_session()
- s._dispatch_message({"type": "group_attach", "name": "photos",
- "shared_dir": "/home/me/Photos"})
- assert s._channel.sent[-1]["subject"] == group_attach_subject(
- "photos", "/home/me/Photos", True)
-
-
def test_invite_create_signs_the_name_it_records():
from meshbay_common.adminop import invite_create_subject
s = _member_session()
diff --git a/packages/meshbay-node/tests/test_admin_ops_mnp.py b/packages/meshbay-node/tests/test_admin_ops_mnp.py
index 7fd1c2b..898228e 100644
--- a/packages/meshbay-node/tests/test_admin_ops_mnp.py
+++ b/packages/meshbay-node/tests/test_admin_ops_mnp.py
@@ -1,17 +1,14 @@
"""
-`gek_rotate` and `member_unpin` over MNP.
+Rotating the group key and forgetting a pinned identity — `ops.set_gek` and
+`ops.unpin_member`, which the Node page and the CLI reach over loopback — and
+the H5 rule every signed MNP operation lives under.
-Both are destructive and both are new, so the tests are negative assertions:
-nobody without the operator's pinned key can reach them, a signature over the
-wrong transcript does not count, and the operation cannot be triggered by the
-request message alone.
-
-The rule these live under is worth restating, because it is easy to read
-draft-v5 §5.1 as forbidding them: **"nothing arriving over MNP can activate a
-GEK" is about key material arriving from outside** (C5b — a member handing the
-node a key of their choosing). An operator-signed instruction where the node
-generates the key with its own CSPRNG is a different shape, and it is the only
-thing that finishes a revocation: the ex-member still holds the current key.
+`gek_rotate` and `member_unpin` were MNP messages until 6.0. No client sent
+them, so they went; what they did is still tested here, at the door that is
+used. **"Nothing arriving over MNP can activate a GEK" is about key material
+arriving from outside** (C5b): the node generates the new key with its own
+CSPRNG, which is the only thing that finishes a revocation — the ex-member
+still holds the current key.
"""
import base64
@@ -19,14 +16,10 @@ from pathlib import Path
import pytest
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
-from meshbay_common.adminop import (
- OP_GEK_ROTATE,
- OP_MEMBER_UNPIN,
- admin_transcript,
-)
+from meshbay_common.adminop import OP_CHAT_EPOCH, admin_transcript
from meshbay_common.crypto import pk_to_b64
from meshbay_common.join import ROLE_MEMBER, ROLE_OPERATOR
-from meshbay_common.protocol import MNP
+from meshbay_node import ops
from meshbay_node.indexer.group_index import GroupIndex
from meshbay_node.roster import open_roster
from meshbay_node.transport.webrtc_server import WebRTCPeerSession
@@ -127,58 +120,7 @@ async def _drain(session):
session.spawned.clear()
-async def _sign_and_exec(session, op: str, subject: str, sk, exec_fn):
- challenge = _last(session)
- assert challenge["type"] == "admin_challenge", challenge
- transcript = admin_transcript(
- op=op, node_pk_b64=session._node_pk_b64(), group_id=GROUP,
- subject=subject, nonce=base64.b64decode(challenge["nonce"]),
- ts=challenge["ts"])
- pending = session._admin_ops.get(challenge["op_id"]) or {
- "op": op, "subject": subject}
- await exec_fn(pending, transcript, sk.sign(transcript))
-
-
-# ── gek_rotate ───────────────────────────────────────────────────────────────
-
-async def test_rotation_needs_an_operator(tmp_path, roster):
- """Without a paired operator there is nobody who could sign, so the node
- fails closed and says why rather than issuing a challenge nobody can meet."""
- session = await _session(tmp_path, roster, operator=False)
-
- session._do_gek_rotate({})
-
- assert _last(session)["type"] == "error"
- assert "authorized key" in _last(session)["detail"]
- assert not session._admin_ops
-
-
-async def test_the_request_alone_rotates_nothing(tmp_path, roster):
- """The message asks; only a signature acts. A node that rotated here would
- let any member lock the group out."""
- session = await _session(tmp_path, roster, operator=True)
- before = session._ctx["groups"][GROUP]["gek"]
-
- session._do_gek_rotate({})
-
- assert _last(session)["type"] == "admin_challenge"
- assert session._ctx["groups"][GROUP]["gek"] == before
-
-
-async def test_a_members_signature_does_not_rotate(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=True)
- sk_mallory, pk_mallory = _keypair()
- await roster.pin_identity("mallory", "mallory", pk_mallory, pk_mallory, "code")
- await roster.set_member(GROUP, "mallory", ROLE_MEMBER, "active", "grenet")
- before = session._ctx["groups"][GROUP]["gek"]
-
- session._do_gek_rotate({})
- await _sign_and_exec(session, OP_GEK_ROTATE, GROUP, sk_mallory,
- session._admin_exec_gek_rotate)
-
- assert _last(session)["type"] == "error"
- assert session._ctx["groups"][GROUP]["gek"] == before
-
+# ── H5: a signature is for one operation ─────────────────────────────────────
async def test_a_signature_over_another_operation_does_not_count(tmp_path, roster):
"""
@@ -191,15 +133,18 @@ async def test_a_signature_over_another_operation_does_not_count(tmp_path, roste
control, and the test would pass while proving nothing.
"""
session = await _session(tmp_path, roster, operator=True)
- before = session._ctx["groups"][GROUP]["gek"]
+ _, pk_bob = _keypair()
+ await roster.pin_identity("bob", "bob", pk_bob, pk_bob, "code")
+ await roster.set_member(GROUP, "bob", ROLE_MEMBER, "active", "code")
- session._do_gek_rotate({})
+ session._do_member_revoke({"user_id": "bob"})
challenge = _last(session)
+ assert challenge["type"] == "admin_challenge", challenge
- # Signed over member_unpin, presented against the pending gek_rotate.
+ # Signed over chat_epoch, presented against the pending member_revoke.
wrong = admin_transcript(
- op=OP_MEMBER_UNPIN, node_pk_b64=session._node_pk_b64(), group_id=GROUP,
- subject=GROUP, nonce=base64.b64decode(challenge["nonce"]),
+ op=OP_CHAT_EPOCH, node_pk_b64=session._node_pk_b64(), group_id=GROUP,
+ subject="bob", nonce=base64.b64decode(challenge["nonce"]),
ts=challenge["ts"])
session._do_admin_response({
"op_id": challenge["op_id"],
@@ -208,19 +153,18 @@ async def test_a_signature_over_another_operation_does_not_count(tmp_path, roste
await _drain(session)
assert _last(session)["type"] == "error"
- assert session.state["groups_ctx"][GROUP]["gek"] == before
+ assert (await roster.get_member(GROUP, "bob"))["status"] == "active"
-async def test_the_operator_rotates_and_the_node_makes_the_key(tmp_path, roster):
+# ── Rotating the group key ───────────────────────────────────────────────────
+
+async def test_rotating_makes_a_new_key_on_the_node(tmp_path, roster):
session = await _session(tmp_path, roster, operator=True)
- before = session._ctx["groups"][GROUP]["gek"]
+ before = session.state["groups_ctx"][GROUP]["gek"]
- session._do_gek_rotate({})
- await _sign_and_exec(session, OP_GEK_ROTATE, GROUP, session.sk_op,
- session._admin_exec_gek_rotate)
+ result = await ops.set_gek(session.state, GROUP, rotate=True)
- ack = _last(session)
- assert ack["type"] == MNP.GEK_ROTATE_ACK, ack
+ assert result["rotated"] is True
after = session.state["groups_ctx"][GROUP]["gek"]
assert after != before, "the key did not change"
assert len(after) == 32
@@ -234,54 +178,21 @@ async def test_rotation_reaches_the_index(tmp_path, roster):
serve members a listing they cannot open."""
session = await _session(tmp_path, roster, operator=True)
- session._do_gek_rotate({})
- await _sign_and_exec(session, OP_GEK_ROTATE, GROUP, session.sk_op,
- session._admin_exec_gek_rotate)
+ await ops.set_gek(session.state, GROUP, rotate=True)
assert session.state["indexes"][GROUP].gek == \
session.state["groups_ctx"][GROUP]["gek"]
-# ── member_unpin ─────────────────────────────────────────────────────────────
-
-async def test_unpinning_needs_an_operator(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=False)
- session._do_member_unpin({"user_id": "bob"})
- assert _last(session)["type"] == "error"
-
-
-async def test_unpinning_yourself_is_refused(tmp_path, roster):
- """It would end the authority of the connection performing the operation,
- halfway through it."""
- session = await _session(tmp_path, roster, operator=True)
- session._do_member_unpin({"user_id": "grenet"})
- assert _last(session)["detail"] == "Cannot unpin yourself"
-
-
-async def test_a_members_signature_does_not_unpin(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=True)
- sk_bob, pk_bob = _keypair()
- await roster.pin_identity("bob", "bob", pk_bob, pk_bob, "code")
-
- session._do_member_unpin({"user_id": "bob"})
- await _sign_and_exec(session, OP_MEMBER_UNPIN, "bob", sk_bob,
- session._admin_exec_member_unpin)
-
- assert _last(session)["type"] == "error"
- assert await roster.get_identity("bob") is not None, (
- "a member removed their own pin — only the operator may")
-
+# ── Forgetting a pinned identity ─────────────────────────────────────────────
-async def test_the_operator_unpins(tmp_path, roster):
+async def test_unpinning_forgets_the_identity_and_its_bundle(tmp_path, roster):
session = await _session(tmp_path, roster, operator=True)
_, pk_bob = _keypair()
await roster.pin_identity("bob", "bob", pk_bob, pk_bob, "code")
- session._do_member_unpin({"user_id": "bob"})
- await _sign_and_exec(session, OP_MEMBER_UNPIN, "bob", session.sk_op,
- session._admin_exec_member_unpin)
+ await ops.unpin_member(session.state, "bob")
- assert _last(session)["type"] == MNP.MEMBER_UNPIN_ACK
assert await roster.get_identity("bob") is None
# The stored keypair bundle goes too — left behind it blocks the re-join
# the unpin exists to enable.
@@ -290,8 +201,21 @@ async def test_the_operator_unpins(tmp_path, roster):
async def test_unpinning_someone_unknown_says_so(tmp_path, roster):
session = await _session(tmp_path, roster, operator=True)
- session._do_member_unpin({"user_id": "nobody"})
- await _sign_and_exec(session, OP_MEMBER_UNPIN, "nobody", session.sk_op,
- session._admin_exec_member_unpin)
- assert _last(session)["type"] == "error"
- assert "No such pinned identity" in _last(session)["detail"]
+ with pytest.raises(ops.OpError, match="No such pinned identity"):
+ await ops.unpin_member(session.state, "nobody")
+
+
+# ── What MNP no longer carries ───────────────────────────────────────────────
+
+@pytest.mark.parametrize("op", ["gek_rotate", "member_unpin", "transfer_limits",
+ "group_detach"])
+def test_operations_no_client_sent_are_not_signed_ops_any_more(op):
+ """Gone with MNP 6.0: a door nobody uses is an untested way in. The Node
+ page and the CLI do the same work over loopback."""
+ from meshbay_common import adminop
+ from meshbay_node.transport.webrtc.admin import _ADMIN_EXECUTORS
+ from meshbay_node.transport.webrtc.dispatch import _HANDLERS
+
+ assert op not in _HANDLERS
+ assert op not in _ADMIN_EXECUTORS
+ assert op not in vars(adminop).values()
diff --git a/packages/meshbay-node/tests/test_attach_from_the_hub.py b/packages/meshbay-node/tests/test_attach_from_the_hub.py
index f4aaa25..acc9d18 100644
--- a/packages/meshbay-node/tests/test_attach_from_the_hub.py
+++ b/packages/meshbay-node/tests/test_attach_from_the_hub.py
@@ -10,6 +10,7 @@ group name chosen on the hub, a folder name — so none of it may end a TOML
string and write lines of its own.
"""
+import sys
import tomllib
from pathlib import Path
@@ -79,6 +80,9 @@ async def test_a_group_name_cannot_write_lines_into_node_toml(tmp_path):
assert hosted["node"]["ui_port"] == 18000
+@pytest.mark.skipif(sys.platform == "win32",
+ reason="Windows refuses a quote or a newline in a folder name, and a "
+ "path is written with `/`: there is no such folder to write")
async def test_a_folder_name_cannot_either(tmp_path):
state = _state(tmp_path, {"id": GID, "name": "Films"})
await ops.attach_group(state, "Films", str(tmp_path / "share"))
diff --git a/packages/meshbay-node/tests/test_licensing.py b/packages/meshbay-node/tests/test_licensing.py
new file mode 100644
index 0000000..6e50c80
--- /dev/null
+++ b/packages/meshbay-node/tests/test_licensing.py
@@ -0,0 +1,257 @@
+"""
+Licensing: meshbay-common under the LGPL, everything else under the AGPL, and
+every third-party piece a build ships accounted for.
+
+Reads files and installed metadata; builds nothing. What it guards against is
+drift — a licence field nobody updates, a vendored file without its licence, a
+GPL dependency creeping into the one package that must stay usable under the
+LGPL.
+"""
+
+import importlib.util
+import json
+import re
+import tomllib
+from importlib import metadata
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[3]
+PACKAGES = ROOT / "packages"
+STATIC = PACKAGES / "meshbay-hub" / "src" / "meshbay_hub" / "static"
+VENDOR = STATIC / "vendor"
+DESKTOP = PACKAGES / "meshbay-client" / "src"
+ANDROID = PACKAGES / "meshbay-android" / "app" / "src" / "main" / "kotlin"
+KEYS = ANDROID / "org" / "meshbay" / "client" / "keys"
+SPDX_LGPL = "// SPDX-License-Identifier: LGPL-3.0-or-later\n"
+# The protocol layer in the clients (README, "Licence"): what a program needs to
+# speak to a hub and a node, under the LGPL in every language it exists in.
+LGPL_FILES = sorted(
+ [STATIC / f for f in ("keyderive.js", "crypto.js", "playlist-crypto.js")]
+ + [STATIC / "transport.js"]
+ + sorted(STATIC.glob("transport-*.js"))
+ + [DESKTOP / f for f in ("keyring.js", "transcripts.js", "argon2-wasm.js")]
+ + [KEYS / f for f in ("Kdf.kt", "Keyring.kt", "Transcripts.kt")]
+)
+EXPECTED = {
+ "meshbay-common": ("LGPL-3.0-or-later", ["COPYING", "COPYING.LESSER"]),
+ "meshbay-hub": ("AGPL-3.0-or-later", ["LICENSE"]),
+ "meshbay-node": ("AGPL-3.0-or-later", ["LICENSE"]),
+}
+
+
+def _notices():
+ spec = importlib.util.spec_from_file_location(
+ "third_party_notices", ROOT / "packaging" / "third_party_notices.py"
+ )
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def test_each_python_package_declares_its_licence_and_ships_the_text():
+ for pkg, (expr, files) in EXPECTED.items():
+ project = tomllib.loads((PACKAGES / pkg / "pyproject.toml").read_text())["project"]
+ assert project["license"] == expr, pkg
+ assert project["license-files"] == files, pkg
+ for f in files:
+ assert (PACKAGES / pkg / f).is_file(), f"{pkg}/{f}"
+
+
+def test_licence_texts_are_the_right_ones():
+ agpl = (ROOT / "LICENSE").read_text()
+ assert "GNU AFFERO GENERAL PUBLIC LICENSE" in agpl and "Version 3" in agpl
+ # Copies, because a wheel's license-files cannot reach outside its package.
+ for pkg in ("meshbay-hub", "meshbay-node"):
+ assert (PACKAGES / pkg / "LICENSE").read_text() == agpl, pkg
+ common = PACKAGES / "meshbay-common"
+ assert "GNU LESSER GENERAL PUBLIC LICENSE" in (common / "COPYING.LESSER").read_text()
+ assert "GNU GENERAL PUBLIC LICENSE" in (common / "COPYING").read_text()
+
+
+def test_rpm_specs_and_the_client_agree_with_the_packages():
+ for pkg in ("meshbay-common", "meshbay-hub", "meshbay-node", "meshbay-client"):
+ spec = (ROOT / "packaging" / "rpm" / f"{pkg}.spec").read_text()
+ want = EXPECTED.get(pkg, ("AGPL-3.0-or-later",))[0]
+ assert re.search(rf"^License:\s+{re.escape(want)}\s*$", spec, re.M), pkg
+ assert "%license %{_licensedir}/%{name}" in spec, pkg
+ pkg_json = json.loads((PACKAGES / "meshbay-client" / "package.json").read_text())
+ assert pkg_json["license"] == "AGPL-3.0-or-later"
+
+
+def test_every_windows_target_ships_the_licence():
+ pkg_json = json.loads((PACKAGES / "meshbay-client" / "package.json").read_text())
+ assert {"from": "../../LICENSE", "to": "LICENSE.txt"} in pkg_json["build"]["win"][
+ "extraResources"
+ ]
+ for yml in ("electron-builder.light.yml", "electron-builder.msix.yml"):
+ text = (ROOT / "packaging" / "win" / yml).read_text()
+ assert "- from: ../../LICENSE\n to: LICENSE.txt" in text, yml
+ ps1 = (ROOT / "packaging" / "win" / "build-node-runtime.ps1").read_text()
+ assert "third_party_notices.py" in ps1 and "THIRD-PARTY-NOTICES.txt" in ps1
+
+
+def test_common_depends_on_nothing_copyleft():
+ """The LGPL is only worth something if the library can be taken alone."""
+ for req in metadata.distribution("meshbay-common").requires or []:
+ if "extra ==" in req:
+ continue
+ name = re.split(r"[\s\[<>=!~;(]", req, maxsplit=1)[0]
+ md = metadata.distribution(name).metadata
+ label = " ".join(
+ [md.get("License-Expression") or "", md.get("License") or ""]
+ + (md.get_all("Classifier") or [])
+ )
+ assert "GPL" not in label, f"{name}: {label[:120]}"
+
+
+def test_notices_follow_what_the_node_actually_ships():
+ mod = _notices()
+ dists = mod._closure(["meshbay-node"])
+ assert "mutagen" in dists and "guessit" in dists and "av" in dists
+ # Extras the node does not ask for, and dev tools, stay out.
+ assert "pytest" not in dists and "piexif" not in dists
+ text = mod.render(["meshbay-node"], [], with_python=False)
+ assert re.search(r"^ mutagen [\d.]+ — GPL", text, re.M)
+ libs = mod._native_libs(dists["av"])
+ if libs: # PyAV's FFmpeg is grafted in; the notice must say which
+ assert libs[0] in text
+
+
+def test_every_vendored_file_has_its_provenance_and_licence():
+ provenance = (VENDOR / "PROVENANCE.md").read_text()
+ licences = (VENDOR / "LICENSES.txt").read_text()
+ for f in VENDOR.iterdir():
+ if f.name in ("PROVENANCE.md", "LICENSES.txt"):
+ continue
+ assert f"## {f.name}" in provenance or f"### {f.name}" in provenance, f.name
+ assert f.name in licences, f.name
+
+
+def _sources():
+ for tree, pattern in ((STATIC, "*.js"), (DESKTOP, "*.js"), (ANDROID, "**/*.kt")):
+ for f in tree.glob(pattern):
+ if "vendor" not in f.parts and "locales" not in f.parts:
+ yield f
+
+
+def test_the_lgpl_files_are_exactly_the_ones_that_say_so():
+ marked = sorted(f for f in _sources() if f.read_text().startswith(SPDX_LGPL))
+ assert marked == LGPL_FILES
+
+
+def test_every_client_carries_the_licence_texts():
+ """static/ is the interface of the web, the desktop and Android alike."""
+ texts = STATIC / "licenses"
+ assert (texts / "AGPL-3.0.txt").read_text() == (ROOT / "LICENSE").read_text()
+ common = PACKAGES / "meshbay-common"
+ assert (texts / "LGPL-3.0.txt").read_text() == (common / "COPYING.LESSER").read_text()
+ assert (texts / "GPL-3.0.txt").read_text() == (common / "COPYING").read_text()
+
+
+def _strip_js(src: str) -> str:
+ src = re.sub(r"/\*[\s\S]*?\*/|//[^\n]*", "", src)
+ return re.sub(r"'(?:\\.|[^'\\\n])*'|\"(?:\\.|[^\"\\\n])*\"", "''", src)
+
+
+def test_the_lgpl_layer_depends_on_nothing_under_the_agpl():
+ """
+ One import of an AGPL module and a client built on the layer is under the
+ AGPL after all. What a host supplies (window.MeshBayPlatform, a Secrets
+ store) is an injected interface, and is not looked for here.
+ """
+ lgpl = set(LGPL_FILES)
+ top = re.compile(
+ r"^(?:export\s+)?(?:async\s+)?(?:function\*?\s+|(?:const|let|var|class)\s+)"
+ r"([A-Za-z_$][\w$]*)",
+ re.M,
+ )
+ defined_in_lgpl = {n for f in lgpl if f.suffix == ".js" for n in top.findall(f.read_text())}
+ agpl_globals = {
+ n: f.name
+ for f in STATIC.glob("*.js")
+ if f not in lgpl
+ for n in top.findall(f.read_text())
+ if n not in defined_in_lgpl
+ }
+ kt_decl = re.compile(r"^\s*(?:\w+\s+)*(?:class|object|interface)\s+(\w+)", re.M)
+ defined_in_lgpl_kt = {
+ n for f in lgpl if f.suffix == ".kt" for n in kt_decl.findall(f.read_text())
+ }
+ agpl_kotlin = {
+ n: f.name
+ for f in ANDROID.glob("**/*.kt")
+ if f not in lgpl
+ for n in kt_decl.findall(f.read_text())
+ if n not in defined_in_lgpl_kt
+ }
+ for f in LGPL_FILES:
+ src = f.read_text()
+ if f.suffix == ".kt":
+ for imp in re.findall(r"^import (org\.meshbay\.[\w.]+)", src, re.M):
+ owner = (
+ imp.split(".")[-2] if imp.split(".")[-1][0].islower() else imp.split(".")[-1]
+ )
+ assert owner in {g.stem for g in lgpl}, f"{f.name} imports {imp}"
+ code = _strip_js(src) # Kotlin's comments and strings take the same shapes
+ for name, owner in agpl_kotlin.items():
+ assert not re.search(rf"\b{name}\b", code), f"{f.name} uses {name} ({owner})"
+ continue
+ code = _strip_js(src)
+ uncommented = re.sub(r"/\*[\s\S]*?\*/|^\s*//[^\n]*", "", src, flags=re.M)
+ for spec in re.findall(
+ r"""(?:\bfrom|\bimport\(|\brequire\()\s*['"]([^'"\n]+)['"]""", uncommented
+ ):
+ if spec.startswith("node:") or "vendor" in spec:
+ continue
+ assert (f.parent / spec).resolve() in lgpl, f"{f.name} imports {spec}"
+ for name, owner in agpl_globals.items():
+ assert not re.search(rf"(?<![\w$.]){re.escape(name)}\s*\(", code), (
+ f"{f.name} calls {name}() from {owner}"
+ )
+
+
+APP_EXCEPTION = STATIC / "licenses" / "APPLICATION-EXCEPTION.txt"
+REFERENCE_APP = [STATIC / "helloworld-app.js", STATIC / "helloworld-app-settings.js"]
+
+
+def _interface_modules() -> set[str]:
+ """The modules the permission names — read from it, the one place they are listed."""
+ text = APP_EXCEPTION.read_text()
+ block = text.split("2. the names exported by these modules", 1)[1].split("3.", 1)[0]
+ return set(re.findall(r"^\s+([\w-]+\.js)\s*$", block, re.M))
+
+
+def test_the_application_interface_names_modules_that_exist():
+ modules = _interface_modules()
+ assert modules == {"i18n.js", "icon.js", "file-utils.js", "settings-ui.js", "folder-tree.js"}
+ for m in modules:
+ assert (STATIC / m).is_file(), m
+ assert not (STATIC / m).read_text().startswith(SPDX_LGPL), (
+ f"{m} is LGPL already; the permission is for the AGPL part"
+ )
+
+
+def test_the_reference_application_is_free_to_copy_and_stays_inside_the_interface():
+ """
+ Copying helloworld is how an application starts. Were it to import anything
+ outside the application interface, every application started from it would
+ be a work based on the AGPL interface without anybody having chosen that.
+ """
+ allowed = _interface_modules() | {f.name for f in LGPL_FILES if f.parent == STATIC}
+ for f in REFERENCE_APP:
+ src = f.read_text()
+ assert src.startswith("// SPDX-License-Identifier: 0BSD\n"), f.name
+ for spec in re.findall(r"""^import .* from ['"]\./([^'"]+)['"]""", src, re.M):
+ assert spec.startswith("vendor/") or spec in allowed, f"{f.name} imports {spec}"
+ assert "import(" not in _strip_js(src), f"{f.name}: a dynamic import escapes this check"
+
+
+def test_every_spdx_line_is_one_of_the_known_licences():
+ for f in _sources():
+ first = f.read_text().split("\n", 1)[0]
+ if "SPDX-License-Identifier" not in first:
+ continue
+ if f in REFERENCE_APP:
+ assert first.endswith(": 0BSD"), f.name
+ else:
+ assert f in LGPL_FILES, f"{f.name}: {first}"
diff --git a/packages/meshbay-node/tests/test_node_status.py b/packages/meshbay-node/tests/test_node_status.py
index bd63f8e..45a9710 100644
--- a/packages/meshbay-node/tests/test_node_status.py
+++ b/packages/meshbay-node/tests/test_node_status.py
@@ -1,24 +1,19 @@
"""
-node_status, root_add, root_remove over MNP.
+The node management panel's server-side behaviour.
-These test the D5 node management panel's server-side behaviour: the admin
-identity check on node_status, the list_groups operation, and the root
-add/remove flows through the MNP handlers.
+The `_is_node_admin` hint, root removal over MNP, and the operations the Node
+page and the CLI reach over loopback: listing groups, adding and updating
+roots, the roster, the denylist and unpinning. Their own MNP messages
+(`node_status`, `root_add`, `roster_read`, …) are gone since MNP 6.0.
"""
-import base64
from dataclasses import asdict
from pathlib import Path
import pytest
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
-from meshbay_common.adminop import (
- OP_MEMBER_UNPIN,
- admin_transcript,
-)
from meshbay_common.crypto import pk_to_b64
from meshbay_common.join import ROLE_OPERATOR
-from meshbay_common.protocol import MNP
from meshbay_node import ops
from meshbay_node.indexer.group_index import GroupIndex
from meshbay_node.roots import RootSet
@@ -133,19 +128,6 @@ async def _session(
return session
-async def _sign_and_exec(session, op: str, subject: str, sk, exec_fn,
- group_id: str = GROUP):
- challenge = _last(session)
- assert challenge["type"] == "admin_challenge", challenge
- transcript = admin_transcript(
- op=op, node_pk_b64=session._node_pk_b64(), group_id=group_id,
- subject=subject, nonce=base64.b64decode(challenge["nonce"]),
- ts=challenge["ts"])
- pending = session._admin_ops.get(challenge["op_id"]) or {
- "op": op, "subject": subject}
- await exec_fn(pending, transcript, sk.sign(transcript))
-
-
# ── _is_node_admin ──────────────────────────────────────────────────────────
async def test_is_node_admin_matches_user_id(tmp_path, roster):
@@ -167,62 +149,6 @@ async def test_is_node_admin_rejects_missing_node_user_id(tmp_path, roster):
assert not session._is_node_admin()
-# ── node_status ─────────────────────────────────────────────────────────────
-
-async def test_node_status_returns_groups_for_admin(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=True,
- node_user_id="grenet")
- session._spawn(session._do_node_status({}))
- await _drain(session)
- msg = _last(session)
- assert msg["type"] == MNP.NODE_STATUS_ACK
- assert len(msg["groups"]) == 1
- assert msg["groups"][0]["id"] == GROUP
-
-
-async def test_node_status_refused_for_non_admin(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=False,
- node_user_id="grenet")
- session._spawn(session._do_node_status({}))
- await _drain(session)
- msg = _last(session)
- assert msg["type"] == "error"
- assert "operator" in msg["detail"].lower()
-
-
-async def test_node_status_refused_when_user_is_operator_but_ids_mismatch(
- tmp_path, roster,
-):
- """A paired operator who is not the node owner cannot see node_status."""
- session = await _session(tmp_path, roster, operator=True,
- node_user_id="someone-else")
- session._spawn(session._do_node_status({}))
- await _drain(session)
- msg = _last(session)
- assert msg["type"] == "error"
-
-
-async def test_node_status_catches_send_failure(tmp_path, roster):
- """If _send itself throws (e.g. msgpack encoding fails), the error must
- not silently vanish — it used to, because _send was outside the try block."""
- session = await _session(tmp_path, roster, operator=True,
- node_user_id="grenet")
- sent = []
- call_count = [0]
-
- def _exploding_send(msg):
- call_count[0] += 1
- if msg.get("type") == "node_status_ack":
- raise TypeError("msgpack cannot encode this")
- sent.append(msg)
-
- session._send = _exploding_send
- session._spawn(session._do_node_status({}))
- await _drain(session)
- # The try/except around _send should catch the error and send an error reply
- assert any(m.get("type") == "error" for m in sent)
-
-
# ── ops.list_groups ─────────────────────────────────────────────────────────
async def test_list_groups_returns_group_metadata(tmp_path):
@@ -266,7 +192,7 @@ async def test_add_root_creates_directory_and_returns_info(tmp_path):
conf = tmp_path / "node.toml"
conf.write_text(f'[[groups]]\nid = "{GROUP}"\nname = "test"\n\n'
- f' [[groups.roots]]\n path = "{shared}"\n', encoding="utf-8")
+ f' [[groups.roots]]\n path = "{shared.as_posix()}"\n', encoding="utf-8")
node_cfg = NodeConfig.__new__(NodeConfig)
node_cfg.groups = [cfg]
@@ -308,7 +234,7 @@ async def test_remove_root_requires_at_least_one_remaining(tmp_path):
conf = tmp_path / "node.toml"
conf.write_text(f'[[groups]]\nid = "{GROUP}"\nname = "test"\n\n'
- f' [[groups.roots]]\n path = "{shared}"\n', encoding="utf-8")
+ f' [[groups.roots]]\n path = "{shared.as_posix()}"\n', encoding="utf-8")
index = GroupIndex(group_id=GROUP, sk_node=Ed25519PrivateKey.generate())
roots = one_root(shared)
state = {
@@ -343,8 +269,9 @@ async def test_removing_a_writable_root_is_allowed(tmp_path):
conf = tmp_path / "node.toml"
conf.write_text(
f'[[groups]]\nid = "{GROUP}"\nname = "test"\n\n'
- f' [[groups.roots]]\n path = "{d1}"\n name = "incoming"\n writable = true\n\n'
- f' [[groups.roots]]\n path = "{d2}"\n name = "shared"\n', encoding="utf-8")
+ f' [[groups.roots]]\n path = "{d1.as_posix()}"\n name = "incoming"\n'
+ ' writable = true\n\n'
+ f' [[groups.roots]]\n path = "{d2.as_posix()}"\n name = "shared"\n', encoding="utf-8")
roots = RootSet.build([asdict(r) for r in cfg.roots])
index = GroupIndex(group_id=GROUP, sk_node=Ed25519PrivateKey.generate())
state = {
@@ -380,7 +307,7 @@ async def test_update_root_rewrites_the_flags_in_node_toml(tmp_path):
f'[[groups]]\nid = "{GROUP}"\nname = "test"\n\n'
f' [[groups.roots]]\n'
f' # the operator explained this one to themselves\n'
- f' path = "{d1}"\n name = "media"\n', encoding="utf-8")
+ f' path = "{d1.as_posix()}"\n name = "media"\n', encoding="utf-8")
roots = RootSet.build([asdict(r) for r in cfg.roots])
index = GroupIndex(group_id=GROUP, sk_node=Ed25519PrivateKey.generate())
state = {
@@ -429,7 +356,7 @@ async def test_update_root_replaces_a_legacy_upload_line(tmp_path):
conf = tmp_path / "node.toml"
conf.write_text(
f'[[groups]]\nid = "{GROUP}"\nname = "test"\n\n'
- f' [[groups.roots]]\n path = "{d1}"\n name = "media"\n'
+ f' [[groups.roots]]\n path = "{d1.as_posix()}"\n name = "media"\n'
f' upload = true\n', encoding="utf-8")
roots = RootSet.build([asdict(r) for r in cfg.roots])
index = GroupIndex(group_id=GROUP, sk_node=Ed25519PrivateKey.generate())
@@ -462,8 +389,8 @@ async def test_remove_root_succeeds_with_two_roots(tmp_path):
conf = tmp_path / "node.toml"
conf.write_text(
f'[[groups]]\nid = "{GROUP}"\nname = "test"\n\n'
- f' [[groups.roots]]\n path = "{d1}"\n name = "dir1"\n\n'
- f' [[groups.roots]]\n path = "{d2}"\n name = "dir2"\n', encoding="utf-8")
+ f' [[groups.roots]]\n path = "{d1.as_posix()}"\n name = "dir1"\n\n'
+ f' [[groups.roots]]\n path = "{d2.as_posix()}"\n name = "dir2"\n', encoding="utf-8")
roots = RootSet.build([asdict(r) for r in cfg.roots])
index = GroupIndex(group_id=GROUP, sk_node=Ed25519PrivateKey.generate())
state = {
@@ -478,32 +405,6 @@ async def test_remove_root_succeeds_with_two_roots(tmp_path):
assert cfg.roots[0].name == "dir1"
-# ── root_add MNP handler ───────────────────────────────────────────────────
-
-async def test_root_add_issues_challenge(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=True,
- node_user_id="grenet")
- session._do_root_add({"group_id": GROUP, "path": "/tmp/test"})
- msg = _last(session)
- assert msg["type"] == "admin_challenge"
-
-
-async def test_root_add_refuses_without_authority(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=False)
- session._do_root_add({"group_id": GROUP, "path": "/tmp/test"})
- msg = _last(session)
- assert msg["type"] == "error"
- assert "authorized" in msg["detail"].lower()
-
-
-async def test_root_add_refuses_missing_fields(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=True,
- node_user_id="grenet")
- session._do_root_add({"group_id": GROUP})
- assert _last(session)["type"] == "error"
- assert "Missing" in _last(session)["detail"]
-
-
# ── root_remove MNP handler ────────────────────────────────────────────────
async def test_root_remove_issues_challenge(tmp_path, roster):
@@ -529,52 +430,32 @@ async def test_root_remove_refuses_missing_fields(tmp_path, roster):
assert "Missing" in _last(session)["detail"]
-# ── roster_read MNP handler ──────────────────────────────────────────────
+# ── The roster, the denylist and unpinning (loopback, CLI) ──────────────────
+#
+# Their MNP messages are gone (MNP 6.0, no client sent them); the operations are
+# what the Node page and the CLI call.
-async def test_roster_read_returns_members_for_admin(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=True,
- node_user_id="grenet")
- session._spawn(session._do_roster_read({"group_id": GROUP}))
- await _drain(session)
- msg = _last(session)
- assert msg["type"] == "roster_read_ack"
- assert "members" in msg
- assert "identities" in msg
-
-
-async def test_roster_read_refused_for_non_admin(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=False,
- node_user_id="grenet")
- session._spawn(session._do_roster_read({"group_id": GROUP}))
- await _drain(session)
- msg = _last(session)
- assert msg["type"] == "error"
-
-
-async def test_roster_read_filters_ghost_members(tmp_path, roster):
+async def test_read_roster_filters_ghost_members(tmp_path, roster):
"""Members whose identity was deleted (revoked then unpinned) are filtered
out by read_roster — the LEFT JOIN returns them with pk_ed25519 = NULL but
they should never reach the UI."""
session = await _session(tmp_path, roster, operator=True,
node_user_id="grenet")
- sk2, pk2 = _keypair()
+ _, pk2 = _keypair()
await roster.pin_identity("ghost", "ghost", pk2, pk2, "code")
await roster.set_member(GROUP, "ghost", "member", "revoked", "local-cli")
await roster._db.execute("DELETE FROM identities WHERE user_id = 'ghost'")
await roster._db.commit()
# Also add a real member so the roster isn't empty
- sk3, pk3 = _keypair()
+ _, pk3 = _keypair()
await roster.pin_identity("real", "real", pk3, pk3, "code")
await roster.set_member(GROUP, "real", "member", "active", "local-cli")
- session._spawn(session._do_roster_read({"group_id": GROUP}))
- await _drain(session)
- msg = _last(session)
- assert msg["type"] == "roster_read_ack"
- ghost = [m for m in msg["members"] if m["user_id"] == "ghost"]
- assert len(ghost) == 0, "ghost members must be filtered out"
- real = [m for m in msg["members"] if m["user_id"] == "real"]
- assert len(real) == 1
+ result = await ops.read_roster(session.state, GROUP)
+ assert "identities" in result
+ assert not [m for m in result["members"] if m["user_id"] == "ghost"], (
+ "ghost members must be filtered out")
+ assert len([m for m in result["members"] if m["user_id"] == "real"]) == 1
async def test_unpin_fails_for_ghost_member(tmp_path, roster):
@@ -582,145 +463,35 @@ async def test_unpin_fails_for_ghost_member(tmp_path, roster):
session = await _session(tmp_path, roster, operator=True,
node_user_id="grenet")
await roster.set_member(GROUP, "ghost", "member", "revoked", "local-cli")
- # ghost has no identity row
- session._do_member_unpin({"user_id": "ghost"})
- challenge = _last(session)
- assert challenge["type"] == "admin_challenge"
+ with pytest.raises(ops.OpError, match="No such pinned identity"):
+ await ops.unpin_member(session.state, "ghost")
- await _sign_and_exec(session, OP_MEMBER_UNPIN, "ghost",
- session.sk_op, session._admin_exec_member_unpin)
- msg = _last(session)
- assert msg["type"] == "error"
- assert "No such pinned identity" in msg["detail"]
-
-
-async def test_unpin_succeeds_for_real_identity(tmp_path, roster):
- """Full unpin flow: challenge → sign → exec → identity deleted."""
- session = await _session(tmp_path, roster, operator=True,
- node_user_id="grenet")
- sk2, pk2 = _keypair()
- await roster.pin_identity("target", "target", pk2, pk2, "code")
- await roster.set_member(GROUP, "target", "member", "active", "local-cli")
-
- session._do_member_unpin({"user_id": "target"})
- challenge = _last(session)
- assert challenge["type"] == "admin_challenge"
-
- await _sign_and_exec(session, OP_MEMBER_UNPIN, "target",
- session.sk_op, session._admin_exec_member_unpin)
- msg = _last(session)
- assert msg["type"] == "member_unpin_ack"
- assert msg["user_id"] == "target"
-
- idents = await roster.list_identities()
- assert not any(i["user_id"] == "target" for i in idents)
-
-
-# ── denylist_read MNP handler ────────────────────────────────────────────
-async def test_denylist_read_returns_entries_for_admin(tmp_path, roster):
+async def test_read_denylist_lists_entries(tmp_path, roster):
session = await _session(tmp_path, roster, operator=True,
node_user_id="grenet")
session.denylist.deny_user("bad-user")
- session._spawn(session._do_denylist_read({}))
- await _drain(session)
- msg = _last(session)
- assert msg["type"] == "denylist_read_ack"
- assert msg["count"] == 1
- assert "bad-user" in msg["users"]
+ result = await ops.read_denylist(session.state)
+ assert result["count"] == 1
+ assert "bad-user" in result["users"]
-async def test_denylist_read_refused_for_non_admin(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=False,
- node_user_id="grenet")
- session._spawn(session._do_denylist_read({}))
- await _drain(session)
- msg = _last(session)
- assert msg["type"] == "error"
-
-
-# ── denylist_clear MNP handler ───────────────────────────────────────────
-
-async def test_denylist_clear_removes_entry_for_admin(tmp_path, roster):
+async def test_clear_denylist_removes_one_entry(tmp_path, roster):
session = await _session(tmp_path, roster, operator=True,
node_user_id="grenet")
session.denylist.deny_user("bad-user")
session.denylist.deny_user("other-user")
- session._spawn(session._do_denylist_clear({"subject": "bad-user"}))
- await _drain(session)
- msg = _last(session)
- assert msg["type"] == "denylist_clear_ack"
- assert msg["removed"] == 1
+ result = await ops.clear_denylist(session.state, subject="bad-user")
+ assert result["removed"] == 1
assert "bad-user" not in session.denylist.entries()["users"]
assert "other-user" in session.denylist.entries()["users"]
-async def test_denylist_clear_all_for_admin(tmp_path, roster):
+async def test_clear_denylist_all(tmp_path, roster):
session = await _session(tmp_path, roster, operator=True,
node_user_id="grenet")
session.denylist.deny_user("a")
session.denylist.deny_user("b")
session.denylist.deny_jti("j")
- session._spawn(session._do_denylist_clear({"subject": ""}))
- await _drain(session)
- msg = _last(session)
- assert msg["type"] == "denylist_clear_ack"
- assert msg["removed"] == 3
-
-
-async def test_denylist_clear_refused_for_non_admin(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=False,
- node_user_id="grenet")
- session._spawn(session._do_denylist_clear({"subject": "bad-user"}))
- await _drain(session)
- msg = _last(session)
- assert msg["type"] == "error"
-
-
-# ── group_attach MNP handler ────────────────────────────────────────────
-
-async def test_group_attach_issues_challenge(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=True,
- node_user_id="grenet")
- session._do_group_attach({"name": "test-group", "shared_dir": "/tmp/share"})
- msg = _last(session)
- assert msg["type"] == "admin_challenge"
-
-
-async def test_group_attach_refused_without_authority(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=False)
- session._do_group_attach({"name": "test-group", "shared_dir": "/tmp/share"})
- msg = _last(session)
- assert msg["type"] == "error"
- assert "authorized" in msg["detail"].lower()
-
-
-async def test_group_attach_refuses_missing_fields(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=True,
- node_user_id="grenet")
- session._do_group_attach({"name": "test-group"})
- msg = _last(session)
- assert msg["type"] == "error"
- assert "Missing" in msg["detail"]
-
-
-# ── node_reload MNP handler ─────────────────────────────────────────────
-
-async def test_node_reload_runs_for_admin(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=True,
- node_user_id="grenet")
- session._spawn(session._do_node_reload({}))
- await _drain(session)
- msg = _last(session)
- assert msg["type"] == "node_reload_ack"
- assert msg["status"] == "reloaded"
- assert len(session.reload_called) == 1
-
-
-async def test_node_reload_refused_for_non_admin(tmp_path, roster):
- session = await _session(tmp_path, roster, operator=False,
- node_user_id="grenet")
- session._spawn(session._do_node_reload({}))
- await _drain(session)
- msg = _last(session)
- assert msg["type"] == "error"
+ result = await ops.clear_denylist(session.state, subject="")
+ assert result["removed"] == 3
diff --git a/packages/meshbay-node/tests/test_root_eject.py b/packages/meshbay-node/tests/test_root_eject.py
index d73e71c..b6b50aa 100644
--- a/packages/meshbay-node/tests/test_root_eject.py
+++ b/packages/meshbay-node/tests/test_root_eject.py
@@ -264,3 +264,131 @@ async def test_the_ejected_key_is_case_folded(tmp_path):
assert Roster.root_ejected_key("Films") == Roster.root_ejected_key("FILMS")
finally:
await roster.close()
+
+
+# ── The safety net's eject undoes itself; the operator's does not ───────────
+
+def _vanish(films: Path) -> None:
+ for f in films.iterdir():
+ f.unlink()
+ films.rmdir()
+
+
+async def test_an_auto_ejected_root_comes_back_with_its_own_files(tmp_path):
+ """
+ The drive that was not mounted yet when the node started (found on a node
+ started with the session, its USB drives mounted a minute later): the
+ safety net ejected it, and once the same files are readable at the same
+ place it is plugged back without anyone having to.
+ """
+ films = tmp_path / "Films"
+ films.mkdir()
+ (films / "a.mkv").write_bytes(b"a")
+ seen: list[tuple[str, bool]] = []
+
+ async def record(name: str, ejected: bool) -> None:
+ seen.append((name, ejected))
+
+ roots = _roots(films)
+ idx = await _indexer(roots, on_root_ejected=record)
+ hidden = tmp_path / "unmounted"
+ films.rename(hidden)
+ await idx.reconcile()
+ assert roots.roots[0].ejected is True
+
+ hidden.rename(films)
+ await idx.reconcile()
+ assert roots.roots[0].ejected is False
+ assert roots.roots[0].available is True
+ assert _names(idx) == {"a.mkv"}
+ assert seen == [("Films", True), ("Films", False)]
+
+
+@pytest.mark.parametrize("what_came_back", ["empty", "another drive"])
+async def test_an_auto_ejected_root_stays_out_when_its_files_are_not_there(
+ tmp_path, what_came_back):
+ """
+ What the safety net exists for: an empty mount point, or another drive
+ mounted at the same place, is not the library. Plugging it back would
+ rescan it, and the rescan would read the library as erased.
+ """
+ films = tmp_path / "Films"
+ films.mkdir()
+ (films / "a.mkv").write_bytes(b"a")
+ roots = _roots(films)
+ idx = await _indexer(roots)
+ _vanish(films)
+ await idx.reconcile()
+
+ films.mkdir()
+ if what_came_back == "another drive":
+ (films / "other.mkv").write_bytes(b"something else")
+ await idx.reconcile()
+ assert roots.roots[0].ejected is True
+ assert _names(idx) == {"a.mkv"}, "the library was treated as erased"
+
+
+async def test_an_operator_eject_is_never_undone_automatically(tmp_path):
+ films = tmp_path / "Films"
+ films.mkdir()
+ (films / "a.mkv").write_bytes(b"a")
+ roots = _roots(films)
+ idx = await _indexer(roots)
+
+ idx.eject_root("Films")
+ await idx.reconcile()
+ assert roots.roots[0].ejected is True
+
+
+async def test_after_a_restart_the_cache_recognises_the_drive(tmp_path):
+ """
+ A restarted node has no index entry for an ejected root: the index is
+ rebuilt by scanning, and an ejected root is not scanned. What it does have is
+ the hash cache, with the size and mtime of every file it read there.
+ """
+ import os
+
+ from meshbay_node.indexer.cache import IndexCache
+
+ films = tmp_path / "Films"
+ films.mkdir()
+ movie = films / "a.mkv"
+ movie.write_bytes(b"a")
+ st = movie.stat()
+
+ def restarted_ejected() -> RootSet:
+ return RootSet.build([{"path": str(films), "removable": True,
+ "ejected": True, "ejected_auto": True}])
+
+ async with IndexCache(tmp_path / "cache.db") as cache:
+ await _indexer(_roots(films), cache=cache)
+
+ # Another drive at the same place, with a file of the same name.
+ movie.write_bytes(b"another drive")
+ roots = restarted_ejected()
+ await _indexer(roots, cache=cache)
+ assert roots.roots[0].ejected is True
+
+ # The drive itself.
+ movie.write_bytes(b"a")
+ os.utime(movie, ns=(st.st_atime_ns, st.st_mtime_ns))
+ roots = restarted_ejected()
+ idx = await _indexer(roots, cache=cache)
+ assert roots.roots[0].ejected is False
+ assert _names(idx) == {"a.mkv"}
+
+
+async def test_the_roster_keeps_an_auto_eject_apart(tmp_path):
+ roster = Roster(db_path=tmp_path / "roster.db")
+ await roster.open()
+ try:
+ await roster.set_root_ejected("g1", "Films", True, set_by="op", auto=True)
+ await roster.set_root_ejected("g1", "Music", True, set_by="op")
+ assert await roster.ejected_roots("g1") == {"films", "music"}
+ assert await roster.auto_ejected_roots("g1") == {"films"}
+
+ # An operator eject of the same root replaces the safety net's.
+ await roster.set_root_ejected("g1", "Films", True, set_by="op")
+ assert await roster.auto_ejected_roots("g1") == set()
+ finally:
+ await roster.close()
diff --git a/packages/meshbay-node/tests/test_root_writable_policy.py b/packages/meshbay-node/tests/test_root_writable_policy.py
index 0cd9af8..0dc5d6d 100644
--- a/packages/meshbay-node/tests/test_root_writable_policy.py
+++ b/packages/meshbay-node/tests/test_root_writable_policy.py
@@ -12,8 +12,9 @@ The properties this holds:
A member with an old tab open, or one speaking MNP directly, gets the same
answer. That half is pinned in `test_security_regressions.py`, next to the
overwrite properties it belongs with;
-* the setting is changed by a **signed** operator instruction, or it is a
- suggestion any member can undo;
+* the setting is changed **on the node's own machine** — the desktop
+ application over loopback, or the CLI — and never over MNP, where a signature
+ proves only that the operator's key signed (`test_sharing_is_local_only.py`);
* it is stored on the **node**, never the hub. A hub that could decide who
writes to the operator's disk would have authority over the node.
@@ -26,7 +27,7 @@ from pathlib import Path
import pytest
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
-from meshbay_common.adminop import OP_ROOT_EJECT, OP_ROOT_PLUG, OP_ROOT_UPDATE
+from meshbay_common.adminop import OP_ROOT_EJECT, OP_ROOT_PLUG
from meshbay_common.crypto import generate_gek
from meshbay_common.protocol import MNP
from meshbay_node.indexer.group_index import GroupIndex
@@ -163,34 +164,6 @@ def _capture_challenges(session) -> list[tuple[str, str]]:
return issued
-async def test_changing_a_roots_flags_needs_a_signature(tmp_path):
- """The flags are not applied by the request — only by the signed response."""
- session = _session(tmp_path, "the-operator", operator="the-operator")
- issued = _capture_challenges(session)
-
- session._do_root_update({"group_id": "g" * 32, "root_name": "shared",
- "writable": False})
-
- assert [op for op, _ in issued] == [OP_ROOT_UPDATE]
- assert session._ctx["roots"].roots[0].writable is True, (
- "applied before it was signed")
-
-
-async def test_the_subject_names_the_outcome_not_the_operation(tmp_path):
- """
- The operator is shown the subject before signing, so it has to say what will
- be true afterwards. "shared" alone would have them authorize a change they
- cannot see the direction of.
- """
- session = _session(tmp_path, "op", operator="op")
- issued = _capture_challenges(session)
-
- session._do_root_update({"group_id": "g" * 32, "root_name": "shared",
- "writable": True, "removable": True})
-
- assert issued == [(OP_ROOT_UPDATE, "shared:rw=on,rem=on")]
-
-
async def test_eject_and_plug_are_signed_too(tmp_path):
"""
Hiding a group's whole library from every member is not a lesser act than
@@ -214,8 +187,7 @@ async def test_a_request_with_nobody_to_authorize_it_is_refused(tmp_path):
issued = _capture_challenges(session)
session._has_admin_authority = lambda: False
- session._do_root_update({"group_id": "g" * 32, "root_name": "shared",
- "writable": True})
+ session._do_root_eject({"group_id": "g" * 32, "root_name": "shared"})
assert issued == []
assert [m for m in session.sent if m.get("type") == "error"]
diff --git a/packages/meshbay-node/tests/test_security_regressions.py b/packages/meshbay-node/tests/test_security_regressions.py
index 43e88c2..26a3b1d 100644
--- a/packages/meshbay-node/tests/test_security_regressions.py
+++ b/packages/meshbay-node/tests/test_security_regressions.py
@@ -842,14 +842,11 @@ def test_node_control_api_serves_no_html():
# ── NS4 / M3: the node's own controls take no authority from the hub ─────────
-async def _owner_session(tmp_path, roster, *, device: str = "",
- confirmed: bool = False):
+async def _owner_session(tmp_path, roster):
"""A session whose token says it is the account this node belongs to.
Which is all a hub can decide: `_user_id` is the `sub` of a JWT it issued,
- so this is what an active hub forging a token arrives holding. Whether the
- *device* on the connection is one the node pinned as an operator is the
- other half, and no token can assert it.
+ so this is what an active hub forging a token arrives holding.
"""
from meshbay_node.indexer.group_index import GroupIndex
@@ -865,9 +862,6 @@ async def _owner_session(tmp_path, roster, *, device: str = "",
}
session._group_id = "g" * 32
session._user_id = "the-owner"
- session._username = "the-owner"
- session._pinned_pk = device
- session._device_confirmed = confirmed
session._pk_user = ""
session.sent = []
session._send = session.sent.append
@@ -876,18 +870,18 @@ async def _owner_session(tmp_path, roster, *, device: str = "",
@pytest.mark.asyncio
-async def test_a_token_naming_the_owner_is_not_node_authority(tmp_path):
+@pytest.mark.parametrize("mtype", ["node_status", "node_settings_set", "roster_read",
+ "denylist_read", "denylist_clear", "node_reload"])
+async def test_a_token_naming_the_owner_reaches_no_node_control(tmp_path, mtype):
"""
- The hub holds no user keys, so it cannot countersign a device — but it does
- choose what a token says. Six node-wide controls used to be gated on the
- account id alone, which is the hub's to decide: `node_status` (every group
- on the machine, with the operator's absolute paths), `node_settings_set`,
- `roster_read`, `denylist_read`, `denylist_clear` (the persisted revocation
- H4 exists to keep) and `node_reload`.
-
- An active hub reaches a completed handshake wherever it can also obtain the
- group key, which §3.5 concedes it can in an open-join group. From there,
- "the hub says you are the owner" was the whole of the check.
+ The hub holds no user keys, but it does choose what a token says. Six
+ node-wide controls were once gated on the account id alone: `node_status`
+ (every group on the machine, with the operator's absolute paths),
+ `node_settings_set`, `roster_read`, `denylist_read`, `denylist_clear` (the
+ persisted revocation H4 exists to keep) and `node_reload`. A device proof
+ closed that; MNP 6.0 removed the messages, since no client sent them. They
+ are the loopback API's and the CLI's — on the operator's own machine — and a
+ peer naming one over MNP is answered by nobody.
"""
from meshbay_node.roster import Roster
@@ -895,67 +889,8 @@ async def test_a_token_naming_the_owner_is_not_node_authority(tmp_path):
await roster.open()
try:
forged = await _owner_session(tmp_path, roster)
- await forged._do_node_status({})
- assert forged.sent[-1]["type"] == "error"
- assert forged.sent[-1]["code"] == "not_operator"
-
- forged.sent.clear()
- await forged._do_denylist_read({})
- assert forged.sent[-1]["type"] == "error"
-
- forged.sent.clear()
- await forged._do_denylist_clear({"subject": ""})
- assert forged.sent[-1]["type"] == "error", (
- "clearing the denylist undoes a revocation every node enforces")
- finally:
- await roster.close()
-
-
-@pytest.mark.asyncio
-async def test_an_identified_device_that_is_not_an_operator_is_refused(tmp_path):
- """Being a pinned member of the group is not being the node's operator.
-
- The device proof is real here; what it proves is an ordinary member's key,
- and `operator_pks()` is rebuilt from the roster on every call so a revoked
- one stops working at once.
- """
- from meshbay_common.crypto import pk_to_b64
- from meshbay_node.roster import Roster
-
- roster = Roster(db_path=tmp_path / "roster.db")
- await roster.open()
- try:
- sk = Ed25519PrivateKey.generate()
- member_pk = pk_to_b64(sk.public_key())
- await roster.pin_identity("the-owner", "the-owner", member_pk,
- member_pk, "code")
- session = await _owner_session(tmp_path, roster, device=member_pk,
- confirmed=True)
- await session._do_node_status({})
- assert session.sent[-1]["type"] == "error"
- finally:
- await roster.close()
-
-
-@pytest.mark.asyncio
-async def test_a_paired_operator_device_is_what_opens_it(tmp_path):
- """The positive case, so the test above is about authority and not about
- everything being refused."""
- from meshbay_common.crypto import pk_to_b64
- from meshbay_common.join import ROLE_OPERATOR
- from meshbay_node.roster import Roster
-
- roster = Roster(db_path=tmp_path / "roster.db")
- await roster.open()
- try:
- sk = Ed25519PrivateKey.generate()
- pk = pk_to_b64(sk.public_key())
- await roster.pin_identity("the-owner", "the-owner", pk, pk, "code")
- await roster.set_member("", "the-owner", ROLE_OPERATOR, "active",
- "local-cli")
- session = await _owner_session(tmp_path, roster, device=pk,
- confirmed=True)
- await session._do_denylist_read({})
- assert session.sent[-1]["type"] != "error", session.sent[-1]
+ forged._dispatch_message({"type": mtype, "subject": "", "group_id": "g" * 32,
+ "settings": {"max_peers": 1}})
+ assert forged.sent == [], f"{mtype} answered over MNP: {forged.sent}"
finally:
await roster.close()
diff --git a/packages/meshbay-node/tests/test_sharing_is_local_only.py b/packages/meshbay-node/tests/test_sharing_is_local_only.py
new file mode 100644
index 0000000..ac8bebb
--- /dev/null
+++ b/packages/meshbay-node/tests/test_sharing_is_local_only.py
@@ -0,0 +1,109 @@
+"""
+What of the operator's disk is shared, and who may write there, is decided on
+the node's own machine — never over MNP (MNP 6.0).
+
+A signed operation proves that the operator's key signed, not that the operator
+meant it: in a browser the key is driven by code the hub serves, and in the
+desktop application by a renderer that parses content from nodes. `root_add`,
+`root_update` and `group_attach` let either of them share any folder on the
+machine, or open one to writes, from anywhere. They are gone; the loopback API
+(the desktop application) and the CLI remain.
+
+And the consequence that has to hold for the operator's list to stay true: a
+flag changed through the loopback API reaches every connected page, which the
+MNP ack used to do.
+"""
+
+from dataclasses import asdict
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
+from meshbay_common import adminop
+from meshbay_common.protocol import MNP
+from meshbay_node import ops
+from meshbay_node.config import GroupConfig, RootSpec
+from meshbay_node.indexer.indexer import DirectoryIndexer
+from meshbay_node.roots import RootSet
+from meshbay_node.transport.webrtc.admin import _ADMIN_EXECUTORS
+from meshbay_node.transport.webrtc.dispatch import _HANDLERS
+from meshbay_node.transport.webrtc_server import WebRTCPeerSession
+from test_admin_challenge_bounds import _PC, _Channel
+
+GROUP = "g" * 32
+GONE = ("root_add", "root_update", "group_attach")
+
+
+@pytest.mark.parametrize("mtype", GONE)
+def test_no_message_widens_what_the_node_shares(mtype):
+ assert mtype not in _HANDLERS, f"{mtype} is dispatched again"
+ assert mtype not in _ADMIN_EXECUTORS, f"{mtype} can be executed again"
+ assert mtype not in vars(MNP).values(), f"{mtype} is back in the protocol"
+ assert mtype not in vars(adminop).values(), f"{mtype} is a signed op again"
+
+
+@pytest.mark.parametrize("mtype", GONE)
+def test_an_older_client_asking_is_issued_nothing_to_sign(mtype):
+ """A 5.x client still sends these. Nothing it sends may come back as a
+ challenge — a challenge is what a compromised page needs signed."""
+ ctx = {"sk_node": Ed25519PrivateKey.from_private_bytes(b"\x01" * 32),
+ "groups": {GROUP: {}}, "has_admin_authority": True}
+ s = WebRTCPeerSession(_PC(), ctx, peer_id="peer")
+ s._channel = _Channel()
+ s._audit = lambda *a, **k: None
+ s._user_id, s._group_id = "operator", GROUP
+
+ s._dispatch_message({"type": mtype, "group_id": GROUP, "path": "/home/someone",
+ "shared_dir": "/home/someone", "name": "x",
+ "root_name": "x", "writable": True})
+
+ assert s._admin_ops == {}
+ assert not [m for m in s._channel.sent if m.get("type") == "admin_challenge"]
+
+
+def _state(tmp_path: Path, indexer_roots: RootSet | None = None):
+ (tmp_path / "media").mkdir()
+ cfg = GroupConfig(id=GROUP, name="plop",
+ roots=[RootSpec(path=str(tmp_path / "media"), name="media")])
+ conf = tmp_path / "node.toml"
+ conf.write_text(
+ f'[[groups]]\nid = "{GROUP}"\nname = "plop"\n\n'
+ f' [[groups.roots]]\n path = "{(tmp_path / "media").as_posix()}"\n'
+ f' name = "media"\n', encoding="utf-8")
+ live = RootSet.build([asdict(r) for r in cfg.roots])
+ pushed: list[list[dict]] = []
+
+ async def on_change(indexer):
+ pushed.append(indexer.index.roots)
+
+ indexer = DirectoryIndexer(indexer_roots or live, GROUP,
+ Ed25519PrivateKey.generate(), None,
+ on_change=on_change)
+ state = {"config": SimpleNamespace(groups=[cfg]), "config_path": str(conf),
+ "groups_ctx": {GROUP: {"roots": live}},
+ "indexers": {GROUP: indexer}}
+ return state, pushed
+
+
+async def test_a_flag_changed_on_the_node_reaches_every_open_page(tmp_path):
+ state, pushed = _state(tmp_path)
+
+ await ops.update_root(state, GROUP, "media", writable=True)
+
+ assert pushed, "nothing was pushed — open pages keep the old flag"
+ assert pushed[-1][0]["writable"] is True
+
+
+async def test_the_pushed_table_is_right_when_the_indexer_holds_its_own_set(tmp_path):
+ """The indexer and the group context normally share one RootSet; when they
+ do not, the table peers receive is the indexer's, and must carry the flag."""
+ (tmp_path / "media").mkdir()
+ own = RootSet.build([{"path": str(tmp_path / "media"), "name": "media"}])
+ (tmp_path / "media").rmdir()
+ state, pushed = _state(tmp_path, indexer_roots=own)
+
+ await ops.update_root(state, GROUP, "media", removable=True)
+
+ assert pushed[-1][0]["removable"] is True
+ assert state["groups_ctx"][GROUP]["roots"].by_name("media").removable is True