End-to-end flows
Which component does what in each flow, and which file to look at. Paths are relative to the repo
root; server/ = wonkru_mdm_server/lib/src/, panel/ = wonkru_mdm_flutter/lib/,
mobil/ = wonkru_mdm_mobil/lib/, kotlin/ =
wonkru_mdm_mobil/android/app/src/main/kotlin/com/wonkrumdm/.
7.1 Device enrollment
Section titled “7.1 Device enrollment”sequenceDiagram
participant A as Admin (panel)
participant S as Server
participant D as Android setup wizard
participant M as Agent
A->>S: Save provisioning profile (QR JSON)
S-->>A: profile + current enrollment key (added at read time)
A->>D: QR is shown, device scans it
D->>D: Connect to Wi-Fi, download APK and verify its checksum
D->>M: Make Device Owner, pass extras bundle
M->>M: Store server_url, device_code, enrollment_key
M->>S: device.register(device info, enrollmentKey)
S-->>M: {code, uuid, token}
M->>S: device.sync (full telemetry)
M->>S: device.config
S-->>M: default policy JSON
M->>M: apply policy
M->>S: device.connect (stream)
S-->>M: welcome
- Enrollment key.
settings.device_enrollment_keyis generated when first needed asWNKR-XXXX-XXXX-XXXX, with twelve Crockford Base32 characters (server/service/enrollment_key_service.dart). Lowercase, missing separators and the lettersI/L/Oare normalized before the constant-time comparison. It is visible in the panel under Settings, can be shown as a QR, and rotated. - QR. Open the Wonkru MDM profile. The server
(
server/service/provisioning_profile_service.dart) supplies the APK download URL, file checksum, API address and current enrollment key. The profile does not store the key. Regenerate PNGs after rotating it. - Android.
kotlin/core/provisioning/ProvisioningActivity.ktselects Android’s fully managed device mode; it writes theProvisioningExtrasbundle to SharedPreferences.mobil/Core/Utils/enrollment_key_store.dartmoves the key to secure storage. - Enrollment RPC.
mobil/Data/DataSources/Remote/device_register.dart→server/endpoints/device_endpoint.dartregister:- 120 / 10 min per IP, field lengths are checked.
- The key is compared in constant time; if wrong,
DeviceEnrollmentRejectedException. - A device code, a UUIDv7, and a 43-character token are generated. Only the SHA-256 of the token is written to the DB.
- If
settings.default_policypoints to a valid policy, it is assigned to the device.
- First sync. The agent sends a full sync, fetches and applies the policy, and opens the stream.
New devices receive the default policy from Settings. After enrollment, use Devices to assign a group or change the policy.
Enrollment without a QR: Device Owner is assigned via ADB. The server address and enrollment key
can then be scanned from the panel’s enrollment QR (a camera button next to the key field), pushed
over ADB with tool/adb_enroll.sh, baked into a controlled build with ENROLLMENT_KEY in
config.json, or entered manually on the agent’s setup screen.
Self-healing:
- If the token is rejected (
DeviceUnauthenticatedException), the agent (mobil/Core/Services/enrollment_recovery.dart) deletes the local identity and enrolls again. The server creates a new device record. Remove the previous record from the panel if it is no longer needed. - If the token is valid but the UUID is different (
DeviceIdentityMismatchException), the agent adopts the server’s identity; no new enrollment is opened.
7.2 Sending commands
Section titled “7.2 Sending commands”sequenceDiagram
participant P as Panel
participant S as Server
participant Q as device_commands
participant M as Agent
P->>S: adminDevice.sendCommand(ids, action, params)
S->>S: prepare (validate, default parameters)
S->>Q: enqueue (pending, bulkId)
S->>M: flush: command message (if connected)
S->>Q: sent, attempts+1
S-->>P: bulkId
M->>M: journal check, run in order
M->>S: ack {success, status, ...}
S->>Q: acked / error
loop every 2 s
P->>S: bulkStatus / bulkCommands
end
- Panel (
panel/Views/Pages/Devices/device_command_dialog.dart) collects the action, parameters, and devices; callsadminDevice.sendCommand. - Server (
server/endpoints/admin/admin_device_endpoint.dart,server/service/device_command_service.dart):preparerejects an unknown action, a multi-device send of a single-device action, and a missingpackage_name.- For
policy_change,policy_idis first assigned to the device. - For each device a
pendingrow (commandIdUUIDv7, sharedbulkId), then flush.
- Flush. If the device is connected to this server process, the row is set to
sentwith a conditional update and{type: command, commandId, payload: {"action":..,"params":{..}}}is written to the stream. If it is not connected, the row stayspending; when the device connects, it is sent right afterwelcome. - Agent (
mobil/Core/Managers/Stream/device_stream_manager.dart): commands are processed in order. If the samecommandIdarrives again,CommandJournaldoes not re-run the command. Jobs like reboot run 3 s after the ack. - Ack. If the response has
"success":falseor"error":true, it becomeserror, otherwiseacked. A successfulget_installed_appsresponse is written to the device’s app list. - Timeout. A job that runs once a minute sets a command in
sentstate with no ack for 2 min (15 min for long actions) totimeout; apendingolder than 7 days also becomestimeout.- A
timeoutcommand is not sent again. Resend it from the panel if needed. - A command left in
sentstate is sent again when the device reconnects (at most 3 attempts). - An ack that arrives after the timeout is still accepted.
- A
- Panel polls the bulk status every 2 s; it stops when
pending + sent = 0. The device’s command history is on the Commands tab of the detail page.
7.3 Policy
Section titled “7.3 Policy”Creation and assignment
Section titled “Creation and assignment”- The policy is created in the panel. The device has a single
policyId; a device group does not carry a policy. “Assigning a policy to a group” = filter the group, select the devices, and Assign policy. assignPolicysavespolicyId. To notify devices, use Send policy update or Send to devices in the policy list. To assign and send in one step, use thepolicy_changecommand.- A newly enrolled device gets
settings.default_policy.
Policy changes and device notifications
Section titled “Policy changes and device notifications”| Change | Does the version increase? | Automatic update notification |
|---|---|---|
| General/settings tabs in the policy editor | Yes (on a meaningful change) | Yes, after 5 s |
| Binding, updating, removing, ordering an app/file/certificate | Yes | No |
| The app, file, certificate record itself changed | Yes (in bound policies) | No |
| Default policy changed | Yes for both the old and new policy | No |
| Policy deleted | Devices switch to the default | No |
In the “No” rows, the device gets the new version on the next policy fetch (sync schedule, restart,
update_policy). To send it immediately, use Send to devices.
server/future_calls/send_policy_future_call.dart queues an update_policy command for each
target device and sends it to devices that are connected. adminPolicy.update also schedules a
check. After the configured delay (30 minutes by default), the server raises a
policy_update_pending alert for devices still on the previous version and lists up to 10 names.
Applying on the agent
Section titled “Applying on the agent”update_policyarrives →device.config→ the server builds the JSON withserver/service/policy_payload_service.dart. Public files are sent directly; private files use a 7-day signed link.mobil/Core/Managers/config_manager.dart: the same version is not applied again within 45 s; if the policy is passive or outside its active time window, it returnsinactive.- Phases: security/network/certificate → sound/battery/other/file → apps → launcher/screen → restrictions.
- The
policy_resultin the ack is shown in the panel in the command response (applied,partial,inactive,fetchFailed…). Thendevices.policyVersionis updated with a full sync; the “out of date” badge in the device list looks at this field.
For a broken or unfetchable policy, the agent keeps the last valid policy.
7.4 App deployment
Section titled “7.4 App deployment”- Panel → Apps → New: an APK is selected. The panel reads the manifest in the browser and fills
in the package name, versionCode, SDKs, and permissions (
panel/Core/Utils/apk_manifest_parser.dart). - Upload:
adminUpload.getUploadDescription('apk', ...)→ the server produces theapplications/<uuidv7>.apkpath and a signed token → the browserPOST /storage/upload?token=...(web port, per CORSallowedOrigins) →verifyUpload→fileChecksum(SHA-256 on the server). application_versionsrow: file path, checksum, versionCode (unique within the app).- Binding to a policy: the Apps tab of the editor. If no target version is selected, the default among the active versions, otherwise the highest versionCode. Then Send to devices.
- Agent (
mobil/Core/Managers/app_manager.dart): if it is not installed or the versionCode is higher, downloads the APK fromdownload_url, verifies the SHA-256, opens aPackageInstallersession and installs silently withkotlin/features/app/handlers/AppInstallerHandler.kt. During installationDISALLOW_INSTALL_APPSis temporarily removed, then put back. 5 min wait.start_after_installandrun_on_bootare supported.action=removeuninstalls the app.
APKs live on the public disk; webServer.publicHost must be reachable from the device.
7.5 Files
Section titled “7.5 Files”From the panel to the device
Section titled “From the panel to the device”Files are uploaded from the Files page (disk private or public) and bound with
download/open/delete in the Files tab of the policy editor. Target path formats:
Mobile agent. Private files reach
the device through a 7-day signed link.
From the device to the server
Section titled “From the device to the server”device.uploadFile (60 / 5 min per device) → server/service/device_upload_service.dart: size
limit device_upload_max_size_kb (50 MiB), extension allowlist, on the private disk
device-uploads/<40 characters>.<extension>, files row with deviceId. Because the bytes are
carried as base64 in the RPC body, they grow by ~1.33x.
The agent does not use this RPC to upload files. Device-to-server file uploads are not available through the agent app.
Signed links
Section titled “Signed links”GET /storage/file/<storageId>/<path>?token=.... The token is signed with HMAC-SHA256; it contains
the path, the operation, and the expiry. Panel links are valid for 10 min, device links for 7 days.
Certificates and device uploads are not served without a token even when they are on the public disk.
7.6 Online / offline
Section titled “7.6 Online / offline”| Signal | Source | Frequency |
|---|---|---|
heartbeat |
Agent stream | 60 s |
ack |
Command response | per command |
sync |
Full telemetry | per cron, after a policy, on command |
Every heartbeat/ack updates devices.lastSeenAt and writes device_state_cache.isOnline = true;
when the stream closes, it writes false. The battery and version information in the heartbeat is not
written; these fields come from sync.
The panel shows “Online” with now - lastSeenAt ≤ offline_timeout (default 5 min). The badge in the
list is computed with the client clock, while the filter and dashboard are computed with the server
clock; if the client clock is skewed, the two can give different results.
Offline alert: a job that runs every 15 minutes produces alerts for admins for devices not seen for
device_alerts_offline_minutes (default 1440 min); it does not repeat for the same device within
device_alerts_duplicate_prevention_hours (24).
The 2-second “liveness” signal inside the agent (HeartbeatService) is only for the local watchdog;
it does not go to the server.
7.7 Admin login and 2FA
Section titled “7.7 Admin login and 2FA”- The panel calls
adminAuth.login(email, password); the endpoint wraps the Email IDP. 20 / 10 min per IP, the IDP’s own limit is 5 failed attempts / 5 min. Successful and failed attempts are written to the audit. adminAuth.me(): status,hasAdminScope,totpEnabled,twoFactorRequired.- Every admin endpoint checks with
AdminAuthService.requireAdminthat the profile is active and, if 2FA is on, that this session is verified (admin_totp_sessions). Entering a code on one device does not open another session. - 2FA setup:
startTotpSetup→confirmTotpSetup(code)→ 10 recovery codes only in this response. Verification is valid for 12 hours. After 5 failed attempts, a lock is applied that increases from 30 s up to 15 min. - A password/email change requires 2FA.
2FA recovery
Section titled “2FA recovery”Enter an unused recovery code at the login prompt. If you lose access to both the authenticator and recovery codes, use the server terminal to reset the account password and clear 2FA. Sign in and enable 2FA again. Recover an admin account
7.8 Email
Section titled “7.8 Email”- Verification codes. For registration and password resets,
server/service/email_idp_sender.dartuses SMTP whensmtp_enabledis on andsmtp_hostis set. Otherwise, it writes the code to the log in development or uses Serverpod Cloud in production. Codes expire after 15 minutes. Password resets are limited to three per hour. The server waits up to 30 seconds for email delivery and logs any delivery error. - System alerts (
server/service/system_alert_dispatcher.dart):database(panel notification) and/ormailper alert type. Recipients are active admins. - Test: Settings → SMTP → test mail (sent with unsaved form values).