feat: Add live device screen sharing via WebSocket and FCM #209
tobiasmcnulty commented on Apr 28, 2026 20:12 UTC
The WebSocket URL construction can produce an invalid or insecure URL: if ANDROID_ENTERPRISE_CALLBACK_DOMAIN is empty and Site.get_current() fails/returns empty, cb_domain becomes "" and stream_url becomes wss:///.... Also, treating any domain containing ":" as needing ws will incorrectly downgrade example.com:443 to ws. Prefer deriving the host from request.get_host() as a fallback, and choose ws/wss based on request.is_secure() (or a dedicated setting) rather than string heuristics.
cb_domain = (getattr(settings, "ANDROID_ENTERPRISE_CALLBACK_DOMAIN", "") or "").strip()
if not cb_domain:
from django.contrib.sites.models import Site # noqa: PLC0415
try:
cb_domain = (Site.objects.get_current().domain or "").strip()
except Exception:
cb_domain = ""
if not cb_domain:
cb_domain = (request.get_host() or "").strip()
if cb_domain.startswith(("http://", "https://", "ws://", "wss://")):
cb_domain = cb_domain.split("://", 1)[1]
if cb_domain:
scheme = "wss" if request.is_secure() else "ws"
stream_url = (
f"{scheme}://{cb_domain}/ws/devices/screen-publish/{device.screen_stream_token}/"
)
sent = send_start_screen_share(
device.fcm_token,
screen_stream_url=stream_url,
screen_stream_token=device.screen_stream_token,
)
logger.info("device_screen_view: FCM send result", device_pk=device.pk, sent=sent)
else:
logger.warning(
"device_screen_view: no callback host available — cannot trigger screen share",
device_pk=device.pk,
)
screen_stream_token is used as a bearer-style authentication secret, but the model field has no uniqueness guarantee. If two rows ever share a token (accidentally, via data migration, or manual edits), lookups will be ambiguous and endpoints like FCM registration could update multiple devices. Consider enforcing uniqueness (e.g., a partial UniqueConstraint that excludes the empty-string default) and/or generating tokens in a loop until an unused value is found.
This endpoint authenticates by screen_stream_token but updates via Device.all_objects, so a soft-deleted device can still register/update an FCM token. For consistency with other device-ingest endpoints (which use Device.objects) and to prevent reactivating deleted devices, filter with the active manager (Device.objects) or explicitly exclude deleted rows.
updated = Device.objects.filter(screen_stream_token=screen_stream_token).update(
_lookup_device_pk uses Device.all_objects, so a soft-deleted device can still publish frames if it still has a token. If deleted devices should no longer be able to stream, use Device.objects (active manager) here. Also, if tokens aren’t guaranteed unique, .first() could map a token to the wrong device; enforcing uniqueness at the model/DB level would prevent that ambiguity.
try:
return Device.objects.get(screen_stream_token=token).pk
except (Device.DoesNotExist, Device.MultipleObjectsReturned):
return None
_increment_viewer_count is marked "Atomically" but it mutates a shared module-level dict without any locking, and it’s wrapped in database_sync_to_async even though no DB work happens. With concurrent connects/disconnects, counts can race and trigger premature device.stop messages. Consider managing the counter in-process with an asyncio.Lock (and keeping it async), or moving the counter to a shared store (Redis) if you expect multiple processes.
CHANNEL_LAYERS defaults to InMemoryChannelLayer in base settings and deploy.py doesn’t override it. This will break screen-share fanout (and any other Channels features) when running multiple ASGI workers or multiple pods, because groups won’t be shared across processes. Consider configuring a Redis-backed channel layer in deploy.py (and adding channels_redis as a dependency), or making the backend configurable via an env var so production deployments don’t accidentally run in-memory.
# Channels channel layer. Default to the in-memory layer for local development,
# but allow deployments to opt into a shared Redis-backed layer so group sends
# and fanout work correctly across multiple ASGI workers or pods.
_channel_layers_redis_url = os.getenv("CHANNEL_LAYERS_REDIS_URL")
if _channel_layers_redis_url:
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [_channel_layers_redis_url],
},
},
}
else:
CHANNEL_LAYERS = {
"default": {"BACKEND": "channels.layers.InMemoryChannelLayer"},
}
The docstring says this view "syncs the device's policy" after generating the token, but the implementation only calls ensure_screen_stream_token() and does not trigger a push_to_mdm/policy sync. Either update the docstring to match the actual behavior, or call the appropriate push/sync method so the managed configuration is actually propagated.
Ensures the per-device screen-stream token exists, then attempts to
trigger screen sharing via FCM so the firmware app can start the
MediaProjection consent flow.
device_fcm_token_view strips inputs but doesn’t validate max lengths. If the firmware posts an oversized fcm_token or screen_stream_token, the DB update can raise a DataError and return 500. Validate lengths against the model limits (e.g., <=256 for fcm_token and <=64 for screen_stream_token) and return 400 on invalid input.
return HttpResponse(status=400)
if len(fcm_token) > 256 or len(screen_stream_token) > 64:
return HttpResponse(status=400)
send_start_screen_share() docstring says "data-only" but the message includes a notification payload. Either remove the notification to make this truly data-only, or update the docstring to reflect that it sends a user-visible notification + data payload.
logger.info is using printf-style positional formatting here, while most of the codebase logs structured fields via keyword args. Using structured fields (e.g., message_id and token_prefix) will make logs more searchable/consistent with existing structlog usage.
"FCM screen-share trigger sent",
message_id=msg_id,
token_prefix=fcm_token[:8],
Pull request overview
Adds end-to-end live device screen sharing by introducing per-device auth tokens, an FCM “start screen share” trigger, and Channels WebSocket consumers to relay JPEG frames from device → server → browser, plus a simple viewer UI.
Changes:
Device.screen_stream_token and Device.fcm_token fields + token generation helper.Reviewed changes
Copilot reviewed 19 out of 20 changed files in this pull request and generated 10 comments.
<details>
<summary>Show a summary per file</summary>
| File | Description |
| ---- | ----------- |
| uv.lock | Locks new transitive deps (firebase-admin + google cloud libs, etc.). |
| pyproject.toml | Adds firebase-admin dependency. |
| config/settings/base.py | Adds default Channels CHANNEL_LAYERS configuration. |
| apps/mdm/models.py | Adds screen_stream_token/fcm_token fields + ensure_screen_stream_token(). |
| apps/mdm/migrations/0014_device_screen_sharing.py | Migration for the new Device fields. |
| apps/mdm/views.py | Adds device_fcm_token_view endpoint for firmware token registration. |
| apps/mdm/urls.py | Routes the new FCM token registration endpoint. |
| apps/mdm/fcm.py | Implements Firebase Admin SDK init + FCM “start screen share” sender. |
| apps/publish_mdm/screen_consumers.py | Adds publisher/viewer WebSocket consumers and frame relay logic. |
| apps/publish_mdm/routing.py | Adds websocket URL patterns for viewer and publisher sockets. |
| apps/publish_mdm/views.py | Adds device_screen_view to render the viewer page and trigger FCM. |
| apps/publish_mdm/urls.py | Adds URL route to the live screen viewer page. |
| config/templates/publish_mdm/device_screen.html | Viewer UI template + JS websocket client to render JPEG frames. |
| config/templates/publish_mdm/device_detail.html | Adds link to “View live device screen”. |
| docs/src/running/tutorial.rst | Documents FIREBASE_PROJECT_ID requirement for FCM. |
| docs/src/local-development/setup.rst | Adds local dev FCM setup instructions. |
| tests/publish_mdm/test_screen_consumers.py | Tests for publisher/viewer websocket consumers. |
| tests/mdm/test_screen_stream_token.py | Tests for ensure_screen_stream_token(). |
| tests/mdm/test_fcm_token_view.py | Tests for the FCM token registration endpoint. |
| tests/mdm/test_fcm.py | Tests for FCM helper payload/behavior. |
</details>
---
💡 <a href="/caktus/publish-mdm/new/main?filename=.github/instructions/*.instructions.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add Copilot custom instructions</a> for smarter, more guided reviews. <a href="https://docs.github.com/en/copilot/customizing-copilot/adding-repository-custom-instructions-for-github-copilot" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn how to get started</a>.
@copilot apply changes based on the comments in this thread
@copilot apply changes based on the comments in this thread
Applied all changes from the review thread in commits 320ebfd and c4c390c:
fcm.py): updated docstring to reflect notification+data payload; switched logger.info to structured keyword args (message_id=, token_prefix=)mdm/views.py): added length validation (400 if fcm_token > 256 or screen_stream_token > 64); switched Device.all_objects → Device.objects to exclude soft-deleted devicesmodels.py + migration 0014): added UniqueConstraint with condition=~Q(screen_stream_token="") so only non-empty tokens must be uniquescreen_consumers.py): _lookup_device_pk now uses Device.objects.get() (excludes soft-deleted, raises MultipleObjectsReturned defensively)screen_consumers.py): replaced @database_sync_to_async with an asyncio.Lock on the module-level dict — no DB work was happening anywaybase.py): added CHANNEL_LAYERS_REDIS_URL env var support; if set, uses channels_redis.core.RedisChannelLayer; otherwise falls back to in-memoryviews.py): fallback chain is now settings → Site.get_current() → request.get_host(); uses urlparse().netloc to safely strip any scheme/path; scheme derived from request.is_secure()views.py): corrected to reflect FCM trigger, not a policy sync[!WARNING]
> <details>
<summary>Firewall rules blocked me from connecting to one or more addresses (expand for details)</summary>
> #### I tried to connect to the following addresses, but was blocked by firewall rules:
> - astral.sh- Triggering command: /usr/bin/curl curl -LsSf REDACTED (dns block)> If you need me to access, download, or install something from one of these locations, you can either:
> - Configure Actions setup steps to set up my environment, which run before the firewall is enabled
- Add the appropriate URLs or hosts to the custom allowlist in this repository's Copilot coding agent settings (admins only)
> </details>
__str__ references self.device_id, but DeviceBindCode has no device_id field (it has a device FK). This will raise AttributeError when the object is stringified (e.g., in admin/logging). Use self.device.device_id (or self.device_id_id if you store an integer FK id) and handle device possibly being unset if needed.
__str__ references self.device_id, but DeviceAuthChallenge has no device_id field (it has a device FK). This will raise AttributeError when stringified. Use self.device.device_id (and consider also including self.device.pk for robustness if device_id can be blank).
__str__ references self.device_id, but ScreenShareSession has no device_id field (it has a device FK). This will raise AttributeError when stringified. Use self.device.device_id or self.device_id (the implicit FK id field) depending on what you want to display.
__str__ references self.device_id, but ScreenShareAuditLog has no device_id field (it has a nullable device FK). This will raise AttributeError when stringified. Use self.device.device_id if self.device else None (or the implicit device_id FK id field) to avoid crashing on null device logs.
This endpoint allows updating fcm_token with only a device_id (and the view is csrf_exempt). Since device_id is not a secret, anyone who knows/guesses it can overwrite the device’s FCM token, breaking screen-share triggers (and potentially redirecting future pushes). Consider requiring a signed request using the registered device key (e.g., signature over body + timestamp), or restrict token registration to the legacy screen_stream_token until signed requests are implemented.
Key registration succeeds when bind_code is omitted (commented as “dev mode”), which means any party that can identify a device (device_id/serial) can bind their own key and impersonate the device. This is a high-risk default for production. Consider enforcing bind-code requirement unless an explicit development setting is enabled (e.g., settings.DEBUG or ALLOW_UNAUTHENTICATED_DEVICE_KEY_REGISTRATION).
Challenge replay protection is not atomic: the code checks challenge.used_at and then sets it later. Two concurrent verify requests could both pass the used_at is None check and each create a session. Use an atomic update (e.g., filter(..., used_at__isnull=True).update(used_at=...) and verify rows-updated == 1) or a transaction with select_for_update() before issuing a session.
Single-use session enforcement isn’t guaranteed under concurrency: you get() a ScreenShareSession with used_at__isnull=True and then separately update() it, but you don’t check whether the update actually modified a row. Two concurrent connections can both obtain the same session and both be accepted. Consider making the “mark used” step atomic and only returning the device pk when exactly one row was updated.
Viewer tracking uses a process-local dict, but config/settings/base.py now supports a Redis channel layer intended for multi-worker deployments. In a multi-process setup, each worker will maintain its own viewer count, and one worker may send device.stop while viewers are still connected on another worker. Consider either (1) implementing a shared counter (e.g., Redis INCR/DECR) when using Redis channel layers, or (2) removing/guarding the “stop on last viewer” behavior for multi-worker deployments.
CHANNEL_LAYERS is configured to use channels_redis.core.RedisChannelLayer when CHANNEL_LAYERS_REDIS_URL is set, but channels-redis doesn’t appear in the project dependencies/lockfile. If someone sets this env var in a deployment, Django will crash on startup. Either add channels-redis as a dependency or guard this branch with an import check / clearer startup error message.
This debug log includes the full device_pks list. For large fleets this can create very large log lines and increase log ingestion costs/noise. Prefer logging only device_count (and possibly a truncated sample) rather than the full list.
Grammar: “you’ll be direct to” should be “you’ll be directed to”.
Minor punctuation/spacing: there’s an extra space before the comma in “FORCE_INSTALLED ,”.
This GET view has a significant side effect: it sends an FCM push every time the page is loaded/refreshed. That breaks the “safe/idempotent GET” expectation and can lead to accidental/spam triggers (e.g., link prefetchers, refreshes, crawlers hitting authenticated pages). Consider moving the FCM trigger behind an explicit POST action (or a separate endpoint called via JS) with CSRF protection, and keep the viewer page render side-effect-free.
Pull request overview
Copilot reviewed 34 out of 45 changed files in this pull request and generated 14 comments.
@copilot apply changes based on the comments in this thread
@copilot apply changes based on the comments in this thread
Applied all changes from the review thread in commits 4211dc0 and 834fdbc:
__str__ fixes (models.py): DeviceAuthChallenge, ScreenShareSession, and ScreenShareAuditLog now use self.device.device_id (the human-readable AMAPI ID) with null guards (self.device_id is not None) to match the nullable FK pattern used in ScreenShareAuditLog.device_id auth path from device_fcm_token_view — only screen_stream_token (a secret) is now accepted. FCM token can still be set during authenticated key registration via device_register_key_view. Removed test_fcm_token_via_device_id test and added oversized-token 400 tests.device_auth_verify_view): replaced non-atomic challenge.save() with filter(used_at__isnull=True).update(used_at=...) + row-count check._lookup_device_pk consumer): now checks that the update() actually modified a row before returning the device PK.screen_consumers.py): added a comment explaining the process-local counter limitation and when a Redis counter would be needed.channels-redis~=4.3 added to pyproject.toml (enables CHANNEL_LAYERS_REDIS_URL without a crash on startup).views.py): removed device_pks=device_pks from the log call; only device_count is logged.device_screen_trigger_view): the GET viewer page is now side-effect-free. The template calls the new POST endpoint via fetch() with X-CSRFToken on page load. URL: o/<slug>/devices/<pk>/screen/trigger/.[!WARNING]
> <details>
<summary>Firewall rules blocked me from connecting to one or more addresses (expand for details)</summary>
> #### I tried to connect to the following addresses, but was blocked by firewall rules:
> - accounts.google.com- Triggering command: /home/REDACTED/work/publish-mdm/publish-mdm/.venv/bin/pytest pytest tests/ -x -q --no-cov --noprofile (dns block)- Triggering command: /home/REDACTED/work/publish-mdm/publish-mdm/.venv/bin/pytest pytest tests/mdm/ tests/publish_mdm/test_screen_consumers.py -x -q --no-cov (dns block)> If you need me to access, download, or install something from one of these locations, you can either:
> - Configure Actions setup steps to set up my environment, which run before the firewall is enabled
- Add the appropriate URLs or hosts to the custom allowlist in this repository's Copilot coding agent settings (admins only)
> </details>
Mounting the Postgres data volume at /var/lib/postgresql changes the effective PGDATA path (default is /var/lib/postgresql/data). This will cause existing dev_pgdata volumes (previously storing the cluster root) to be ignored and Postgres to re-initialize a new cluster under /var/lib/postgresql/data, effectively “losing” persisted data. Mount the volume at /var/lib/postgresql/data (or explicitly set PGDATA to match the mount) to preserve existing data.
This issue also appears on line 49 of the same file.
This endpoint explicitly accepts requests without any signature/secret (it only takes a device_id). That makes it easy for anyone who can guess/learn a device identifier to trigger repeated mdm.push_device_config calls (operational abuse/DoS). Consider requiring a valid device auth signature (challenge/verify) or a per-device secret, and/or add rate limiting keyed by device as well as IP.
This issue also appears in the following locations of the same file:
The img tag includes width and height attributes set to empty strings. Empty dimension attributes are invalid HTML and can lead to layout/validation issues. Prefer omitting these attributes (or set numeric values) and rely on the existing CSS classes for sizing.
Pull request overview
Copilot reviewed 37 out of 48 changed files in this pull request and generated 3 comments.
<details>
<summary>Comments suppressed due to low confidence (3)</summary>
docker-compose.yaml:54
Same issue as the main db service: mounting infisical_pgdata at /var/lib/postgresql instead of /var/lib/postgresql/data will break existing volumes and trigger a fresh initdb under /var/lib/postgresql/data. Either mount at /var/lib/postgresql/data or set PGDATA to /var/lib/postgresql (and ensure init scripts use it). image: postgres:18-alpine
restart: always
env_file: .infisical.env
volumes:
- infisical_pgdata:/var/lib/postgresql
ports:
apps/mdm/views.py:202
This nonce issuance endpoint is unauthenticated (device_id in JSON is sufficient). Because the nonce is later used to bind a public key to the device, an attacker who knows/guesses a device identifier can obtain nonces for that device and attempt to register their own key. Require an authentication factor (e.g., per-device secret from managed config, or enrollment-specific secret) before issuing nonces.
a hardware-backed key pair. The nonce is valid for 10 minutes and can only
be used once.
Accepts ``device_id`` in the JSON body.
"""
apps/mdm/views.py:269
device_id = body.get("device_id", "").strip()
package_name = body.get("package_name", "").strip()
fcm_token = body.get("fcm_token", "").strip()
certificate_chain = body.get("certificate_chain")
public_key_pem = body.get("public_key_pem", "").strip()
</details>
device_screen_trigger_view returns HTTP 204 even when send_start_screen_share(...) returns False (FCM send failure). This makes the UI/API report success when the trigger wasn't actually delivered; consider returning an error status (e.g. 502) when sent is false, and only 204 on success.
The Postgres data volume is mounted at /var/lib/postgresql, but the official Postgres image’s default PGDATA is /var/lib/postgresql/data. Mounting the parent directory can lead to initdb/permission surprises and differs from the standard layout; consider mounting the volume at /var/lib/postgresql/data (or explicitly set PGDATA to match the mount).
This issue also appears on line 50 of the same file.
PUBLISH_MDM_AGENT_TRACK_IDS is hard-coded to a specific closed testing track ID. This will cause accessibleTrackIds to be included in all pushed policies by default, which can unintentionally restrict Play delivery in production. Consider defaulting this to an empty list and sourcing track IDs from an environment variable/config.
Pull request overview
Copilot reviewed 37 out of 48 changed files in this pull request and generated 6 comments.
<details>
<summary>Comments suppressed due to low confidence (2)</summary>
docker-compose.yaml:54
Same issue as the main DB service: infisical-db mounts the volume at /var/lib/postgresql instead of the default /var/lib/postgresql/data. This may break persistence or initialization unless PGDATA is adjusted accordingly. restart: always
env_file: .infisical.env
volumes:
- infisical_pgdata:/var/lib/postgresql
ports:
apps/mdm/models.py:844
Same as DeviceAuthChallenge.__str__: ScreenShareSession.__str__ checks self.device_id (FK integer) even though it will always be set, then reads self.device.device_id. Consider simplifying to avoid the misleading condition.
def __str__(self):
device_id = self.device.device_id if self.device_id is not None else None
return f"ScreenShareSession({self.session_id}, device={device_id})"
</details>
Pull request overview
Copilot reviewed 37 out of 48 changed files in this pull request and generated 4 comments.
Pull request overview
Copilot reviewed 40 out of 51 changed files in this pull request and generated 7 comments.