Server (`wonkru_mdm_server`)
Serverpod 4.0.0-based backend. The panel and the mobile agent talk through this server; the two do
not connect to each other directly. Unless stated otherwise, the paths in this section are relative
to the wonkru_mdm_server/ root.
4.1 Package structure
Section titled “4.1 Package structure”| Package | Role |
|---|---|
wonkru_mdm_server |
Main server: tables, admin endpoints, device endpoint, services, web routes |
wonkru_mdm_client |
Generated client. Not edited by hand, serverpod generate rewrites it |
wonkru_core_server |
Serverpod module (nickname: wonkru_core). Contains no tables |
wonkru_core_client |
The module’s generated client |
wonkru_core_server defines what the server, panel and agent have in common:
- Shared enums (
DeviceAction,DeviceCommandStatusetc., allserialized: byName) - DTOs of the device protocol (
lib/src/models/device_api/*):DeviceRegisterRequest,DeviceStreamMessage,DeviceSyncRequest… - Catalogs:
lib/src/catalog/restriction_catalog.dart(38 AndroidUserManagerrestrictions) anddevice_action_metadata.dart(bulk/confirmation/default parameters per command) - Single endpoint:
CoreEndpoint.catalogs(). Does not require a session; the panel fetches the restriction catalog from here
The main server references module types in models as module:wonkru_core:DeviceAction.
Code layout:
lib/ server.dart → run() → ServerBootstrap src/server/server_bootstrap.dart startup order src/server/web_routes.dart HTTP routes src/server/recurring_future_calls.dart src/models/*.spy.yaml tables and DTOs src/endpoints/admin/* panel endpoints src/endpoints/device_endpoint.dart agent endpoint src/service/* business logic (endpoints are kept thin) src/storage/* local disk storage, signed token src/future_calls/* scheduled jobs src/web/* web routes and widgets src/generated/ generated code, do not touch4.2 Startup order
Section titled “4.2 Startup order”bin/main.dart → run() → ServerBootstrap(args).run():
TimezoneService.ensureInitialized(): the IANA time zone database is loaded.Serverpod(...)is set up with health config. Three readiness indicators are added on top of Serverpod’s DB/Redis checks:storage:local: writes and deletes a.health_probein both storage roots (2 s timeout).future_calls:overdue: fails if the number of rows overdue by more than 30 min among the three recurring jobs exceeds 2.smtp:configuration: if SMTP is on, validates host/port/sender address; does not attempt a connection.
- If
PASSWORD_HASH_PEPPER(orpasswordHashPepper) is missing, the server writes a TOTP warning to stderr. - Auth is set up: JWT token manager (
jwtHmacSha512PrivateKey,jwtRefreshTokenHashPepper) and Email IDP (emailSecretHashPepper). - The rate limiter is started; the client IP source is read from
CLIENT_IP_SOURCE. - Web routes are registered (see 4.6).
pod.start(). If the process was started with--apply-migrations, pending migrations are applied at this stage. In developmentserverpod startdoes this, in production the Docker image’sENTRYPOINTdoes it (Detailed deployment guide).AdminScopeService.syncAllProfiles: for eachAdminProfile, theadminscope is granted or revoked according to its status.- Recurring future calls are registered (each is first cancelled and then set up again):
| ID | Interval | Job |
|---|---|---|
device-command-timeouts |
1 min | Sets expired commands to timeout |
device-offline-alerts |
15 min | Produces alerts for devices not seen for a long time |
admin-totp-cleanup |
6 hours | Deletes expired 2FA session verifications |
Seed does not run on startup. Neither admin nor demo data is seeded. See operational guidance before first setup.
4.3 Data model
Section titled “4.3 Data model”All columns are camelCase ("userId", "lastSeenAt"). Double quotes are required when writing SQL.
Devices
Section titled “Devices”| Table | Contents |
|---|---|
devices |
code (unique; generated codes have six letters or digits), uuid (unique), name, authToken (SHA-256 of the token, serverOnly), policyId, policyVersion, lastPolicyUpdate, userId, hardware fields (manufacturer, model, serial no, Android/SDK version, agent version), batteryLevel, ipAddress, isRooted, isLauncherMode, storage, lastSeenAt, firstSeenAt, mustUseApplications (JSON), soft delete |
device_groups |
Name, description |
device_device_group |
Device ↔ group pivot (cascade in both directions) |
device_applications |
Installed apps on the device; unique (deviceId, packageName) |
device_syncs |
Raw JSON sections of each full sync (deviceInfo, appsInfo, batteryInfo, networkInfo, securityInfo, bsInfo, stInfo…) |
device_state_cache |
One row per device, a ~60-column flattened form of the latest state (battery, wifi, root/adb, encryption, storage percentage, CA status, isOnline…) |
device_reports |
Agent reports; type free text, payload JSON |
device_logs |
Agent logs; level 0 verbose … 5 fatal |
Commands and notifications
Section titled “Commands and notifications”| Table | Contents |
|---|---|
device_commands |
commandId (UUIDv7, unique), bulkId, action, params (JSON, all values strings), status, attempts, response, createdAt/sentAt/ackedAt |
device_notifications |
Notification sent to the device (title, message, type, extra) |
device_notification_devices |
Notification × device delivery status |
admin_notifications |
In-panel system alerts (offline, policy pending, security) |
Policy
Section titled “Policy”| Table | Contents |
|---|---|
policies |
name, slug (unique), version, isActive, defaultPolicy, adminPassword (hash), activeTimeRanges and JSON settings columns: battery, storage, audio, display, security, restriction, launcher, sync, other |
policy_applications |
Policy ↔ application: action (install/remove/configure), targetVersionId (null = the latest active version), show/position in launcher, run on boot, start after install… |
policy_files |
Policy ↔ file: usageType (download/delete/open), destinationPath, replaceIfExists, openAfterDownload. No file row is needed for delete |
policy_certificates |
Policy ↔ certificate: action (install/uninstall) |
Application, certificate, file
Section titled “Application, certificate, file”| Table | Contents |
|---|---|
applications |
packageName (unique), name, developer, category, sourceType |
application_versions |
versionCode (unique within the application), file path, size, checksumSha256, min/target SDK, isActive, isDefault |
certificates |
Type (CA/CLIENT/SERVER/USER/PKCS12), PEM data, private key, password, fingerprint (unique), validity |
files |
File metadata, disk (private/public), deviceId (filled if the agent uploaded it) |
file_groups, file_group_members |
File groups |
Admin, settings, provisioning
Section titled “Admin, settings, provisioning”| Table | Contents |
|---|---|
admin_profiles |
userId (auth user UUID), status (active/disabled, default disabled), encrypted totpSecret, hashed recoveryCodes, lock counters, lastLoginAt |
admin_totp_sessions |
Sessions where 2FA was verified (sessionId = authId), verifiedUntil |
admin_activities |
Immutable audit log (actor, <domain>.<operation>, target, IP) |
settings |
Key-value settings store (keys: Configuration reference) |
provisioning_profiles |
QR configuration (JSON). The enrollment key is not stored, it is added at read time |
Panel user = Serverpod auth user + UserProfile + EmailAccount + AdminProfile.
Anyone who opens an account via the email IDP becomes an auth user, but cannot enter the panel
without an active AdminProfile.
Migrations
Section titled “Migrations”When a model changes the database schema, create a migration with serverpod create-migration.
In development serverpod start applies migrations on startup. migration.sql may be edited by
hand only to prevent data loss, and the resulting schema must stay identical to definition.sql.
4.4 Admin endpoints (lib/src/endpoints/admin/)
Section titled “4.4 Admin endpoints (lib/src/endpoints/admin/)”Common protection. All admin endpoints other than adminAuth require requireLogin and
requiredScopes: {admin}. Each method additionally calls AdminAuthService.requireAdmin(session):
whether the profile exists, is active, and if 2FA is on, whether this session has been verified.
Write operations land in admin_activities via the AdminAudit mixin; an audit error does not
break the main operation.
Pagination: AdminListRequest (page 1-based, perPage defaults to 25, at most 200).
CSV export at most 50,000 rows.
| Endpoint | Main methods |
|---|---|
adminAuth |
me (also called without a session, returns needsBootstrap), login, bootstrap, startTotpSetup, confirmTotpSetup, verifyTotp, disableTotp, changePassword, changeEmail |
adminDashboard |
deviceStats, alertStats (battery <20, free storage <10%, launcher, root), deviceDistribution, syncTrend (30 days) |
adminDevice |
list, export, get, reportPdf (tr/en), stateCache, applications, reports, update, delete (also closes the open stream), assignPolicy (does not push), assignGroups, sendPolicyUpdate, sendCommand, bulkStatus, bulkCommands, commands, recentCommands, duplicatePolicy |
adminDeviceGroup |
CRUD; the list returns with device count |
adminDeviceLog |
list, get, create, delete, stats (24 hours), levelDistribution, trend, export |
adminDeviceSync |
list, export, get (row + state cache), applications |
adminDeviceNotification |
list, get, deliveries, create (send_notification command behind it), delete |
adminPolicy |
list, export, get, create, update, delete, setDefault, duplicate, preview (the JSON that will go to the device), sendToDevices, pivot operations (attach/update/detach application, file, certificate; reorderApplications) |
adminApplication |
Application CRUD, version CRUD, uploadVersion (the APK package name must match the application) |
adminCertificate |
list, get, parse (PEM/DER/PKCS7/PKCS12), create, update, delete, uploadFile, downloadUrl |
adminFile, adminFileGroup |
File and group CRUD, group assignment, downloadUrl |
adminUpload |
getUploadDescription, verifyUpload, fileChecksum, publicDownloadUrl (see 4.7) |
adminProvisioningProfile |
CRUD, defaultConfig |
adminSettings |
get, save, getTimezone, getEnrollmentKey, rotateEnrollmentKey, sendSmtpTestMail |
adminUser |
list, get, create, update (status ↔ scope sync), delete (own account cannot be deleted) |
adminNotification |
The admin’s own alerts: list, unreadCount, markRead, markAllRead |
adminActivity |
list, actions |
The Serverpod auth module provides emailIdp for login, registration, and password resets,
and jwtRefresh for renewing tokens.
Policy versions and update notifications. If any field of a policy other than
id/version/createdAt/updatedAt/deletedAt changes, version increases by one. Application, file,
certificate, pivot or default policy changes also increase the version via PolicyVersionService.
When adminPolicy.update changes the version, the server sends an automatic notification
after five seconds. To send changes to linked apps, files, or certificates immediately,
select Send to devices in the panel. Devices also get the current version the next time
they fetch their configuration.
update also sets up a check job after policy_devices_updated_check_delay_minutes minutes
(default 30): it produces a policy_update_pending alert for devices still on the old version.
4.5 Device endpoint (DeviceEndpoint)
Section titled “4.5 Device endpoint (DeviceEndpoint)”Serverpod user auth is not used. Every request body carries deviceUuid + token;
DeviceAuthService compares the SHA-256 of the token with devices.authToken. If the UUID does
not match the token’s device, DeviceIdentityMismatchException is thrown and the agent adopts the
identity reported by the server without re-enrolling.
| Method | What it does |
|---|---|
register |
No session. Compares the enrollment key in constant time; if wrong, DeviceEnrollmentRejectedException. Uses a valid, unique client code or generates a six-character alphanumeric code. It also creates a UUIDv7 and a 43-character token and assigns the default policy. The plain token is returned only in this response |
connect(token, inbound) |
Persistent bidirectional stream (see below) |
config |
The JSON payload of the device’s policy (PolicyPayloadService.buildJson) or null |
sync |
Full telemetry. At most 8 MiB. device_syncs row, security alert detection, device_state_cache, device_applications upsert (at most 2000, does not delete) and devices columns in a single transaction |
report |
device_reports row |
log |
Bulk device_logs insert |
passwordCheck |
Verifies the password of the IT page on the device against the policy’s adminPassword |
notificationAck |
Sets the notification delivery to received |
policyChange |
Writes nothing; returns true if the requested policy is already assigned |
uploadFile |
File upload from the device (private disk, device-uploads/) |
Stream protocol
Section titled “Stream protocol”Message type DeviceStreamMessage{type, commandId?, payload?, sentAt?}.
| Direction | type |
Content |
|---|---|---|
| Server → device | welcome |
Connection accepted; the agent only counts as “connected” once it receives this |
| Server → device | command |
payload = {"action":"<name>","params":{...}} |
| Device → server | heartbeat |
Carries battery and policy version, but the server only updates lastSeenAt/presence |
| Device → server | ack |
commandId + response JSON. If the payload contains "success":false or "error":true, the command becomes error |
connect order: token verification → rate limit (60/min per device) →
registration in DeviceConnectionRegistry (the old connection of the same device is closed) →
device_state_cache.isOnline = true → welcome → flush of pending commands
(redeliverSent: true). On every incoming message the server updates lastSeenAt conditionally;
if the device was deleted or the token changed, it closes the stream.
4.6 Web routes (web server, default port 8082)
Section titled “4.6 Web routes (web server, default port 8082)”| Route | Function |
|---|---|
/ |
Serves the compiled panel if web/app exists (with COOP/COEP headers for WASM). Otherwise a “build the panel” page |
GET /assets/assets/config.json |
The panel’s runtime configuration: {"apiUrl": "<apiServer public address>"} |
GET /downloads/local-ca |
Serves the LOCAL_CA_PATH file as PEM; 404 if the file is missing |
POST /storage/upload?token= |
File upload with a signed token |
GET /storage/file/<storageId>/<path>[?token=] |
File download. Public disk without a token; private disk requires a signed token |
/web/** |
Static files under web/static |
For /storage, the server allows browser requests only from origins in allowedOrigins.
4.7 Services
Section titled “4.7 Services”Command queue (service/device_command_service.dart)
Section titled “Command queue (service/device_command_service.dart)”States: pending → sent → acked | error, also pending/sent → timeout.
| Constant | Value |
|---|---|
| Default timeout | 2 min |
| Long timeout | 15 min: get_current_location, device_data, get_installed_apps, get_logs, uninstall_app, clear_app_data, update_policy, policy_change |
| Pending command lifetime | 7 days |
| Max delivery attempts | 3 |
prepare: rejects an unknown action, sending a non-bulk action to multiple devices, and a missing required parameter. Fills default parameters, converts all values to strings.enqueue: skips devices without a UUID, writes apendingrow.flushPending: does nothing if the device is not connected during this process. Claims rows with a conditional update (sent,attempts+1); if it cannot be written to the stream, the claim is rolled back.acknowledge: accepts the ack of a command inpending,sentandtimeoutstate (a late ack is also processed). A successfulget_installed_appsresponse is written todevice_applications.markTimeouts(once a minute): expiredsentrows andpendingrows older than 7 days becometimeout.
Retry: a command that is timeout is not sent again. Only commands left in sent state go
again on reconnect (at most 3 attempts).
Connection registry (DeviceConnectionRegistry)
Section titled “Connection registry (DeviceConnectionRegistry)”The registry is an in-memory Map<uuid, StreamController> and assumes a single process. If
multiple server instances run, a device connected to one instance cannot be pushed to from another;
the command stays in the DB and goes when the device reconnects.
Online concepts
Section titled “Online concepts”“online” is used in three different senses in the code:
- Registry connection: only for push.
device_state_cache.isOnline:trueon connect/heartbeat/ack,falseon close. The row is created after the first sync.lastSeenAtthreshold: the panel list and dashboard use this. The threshold issettings.offline_timeout, default 5 min.
The offline alert works with a separate threshold: device_alerts_offline_minutes (default 1440 =
24 hours), duplicate prevention device_alerts_duplicate_prevention_hours (24).
Policy payload (service/policy_payload_service.dart)
Section titled “Policy payload (service/policy_payload_service.dart)”The JSON going to the device is snake_case: identity fields, *_settings blocks (types corrected
with PolicyPayloadNormalizer), restriction_settings.restrictions[] (name/key/api_level/value
resolved from the catalog), launcher, applications.management_apps[] (each with
application_version{version_code, checksum_sha256, download_url}), files[], certificates[]
(including the signed download URL and password), wlog_config.
Tri-state values: 0 allow, 1 restrict, 2 do not touch. For an application with no target
version selected, the first of the active versions in isDefault desc, versionCode desc order is
taken.
Provisioning (service/provisioning_profile_service.dart)
Section titled “Provisioning (service/provisioning_profile_service.dart)”defaultConfig() generates the Android QR provisioning JSON (the panel draws the QR):
{ "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME": "com.wonkrumdm/com.wonkrumdm.core.receivers.MdmDeviceAdminReceiver", "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM": "<base64url SHA-256>", "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION": "<APK download URL>", "android.app.extra.PROVISIONING_TIME_ZONE": "Europe/Istanbul", "android.app.extra.PROVISIONING_LOCALE": "tr_TR", "android.app.extra.PROVISIONING_ORGANIZATION_NAME": "Wonkru MDM", "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE": { "server_url": "<APP_URL>", "device_code": "<new six-character code>", "enrollment_key": "<added at read time>" }}The default template takes the APK download URL and file checksum from the active agent version in the catalog. The server adds the current enrollment key each time the panel reads a profile. Regenerate any exported QR images after rotating the key. Detailed deployment guide
File storage and signed links
Section titled “File storage and signed links”LocalFileCloudStorage: files are stored underSTORAGE_PATH/<storageId>/<path>, alongside a.metaJSON (content-type, sha256, size)...and empty segments are rejected. If the server runs on Serverpod Cloud it uses that storage, otherwise it uses the local disk.StorageSignature: tokenbase64url(claims).hex(HMAC-SHA256). Claims: operation, storage, path, max size, length, no-overwrite, expiry. The key comes fromstorageSigningKey(at least 32 characters), otherwise fromjwtHmacSha512PrivateKey, otherwise the server generates a random per-process value.- Link lifetime: 10 min for the panel, 7 days for the device.
| Field | Folder | Disk |
|---|---|---|
| Applications (APK) | applications/ |
public |
| Certificates | certificates/ |
private, private only |
| Launcher backgrounds | launcher-backgrounds/ |
public |
| Device uploads | device-uploads/ |
private, private only |
| Files | files/ |
selectable, private by default |
Default upload limits: APK 256 MB, file 256 MB, certificate 10 MB, launcher background 2 MB, device
upload 50 MiB. Config’s maxRequestSize (301989888 bytes = 288 MB) is the ceiling above all of
these.
Panel upload flow: getUploadDescription (the server generates the <domain>/<uuidv7>.<extension>
path and the signed token) → browser POST /storage/upload → verifyUpload → fileChecksum.
The server computes the SHA-256.
Password and 2FA
Section titled “Password and 2FA”util/password_hasher.dart: new hashes use Argon2id. The pepper comes from thePASSWORD_HASH_PEPPERenvironment variable, falling back topasswordHashPepperinconfig/passwords.yaml. Verification only accepts Argon2 records. It is used for the policy admin password and 2FA recovery codes. Panel users’ passwords are managed by the Serverpod Email IDP with its own pepper (emailSecretHashPepper).- The TOTP secret is encrypted with AES-256-GCM; the key is derived from the pepper. If the pepper changes, existing TOTP secrets cannot be decrypted.
- TOTP: SHA1, 6 digits, 30 s, ±1 step window, replay prevention with the last used counter.
- 10 recovery codes (
XXXXX-XXXXX), single-use. - Verification window per session is 12 hours.
- Lockout after 5 failed attempts: starts at 30 s and doubles, at most 15 min.
Email and alerts
Section titled “Email and alerts”- With
settings.smtp_enabledon andsmtp_hostset,SmtpMailServicesends verification and password reset codes. Without SMTP, the code goes to the server log in development. In production, Serverpod Cloud requiresscloudAuthEmailKey. The server logs SMTP errors and continues processing the request. SystemAlertDispatcherroutes alerts according tosettings.system_alert_routingto thedatabase(panel notification) andmailchannels. Alerts can be sent to the panel or by email; SMS delivery is unavailable.- Alert types:
device_offline,policy_update_pending,security_info(if ADB, developer options or root were newly enabled during sync; if there is a reachable app outside the allowlist).
There is no FCM. All device communication is over the stream + DB queue.
Rate limit (service/rate_limiter.dart)
Section titled “Rate limit (service/rate_limiter.dart)”The limiter is in-process with a fixed window. It returns RateLimitExceededException for RPC and
429 + Retry-After for web routes.
| Scope | Limit | Key |
|---|---|---|
deviceRegister |
120 / 10 min | IP |
deviceConnect, deviceSync |
60 / 1 min | device |
deviceReport, deviceLog |
120 / 1 min | device |
deviceUploadFile |
60 / 5 min | device |
devicePasswordCheck |
10 / 1 min (device), 30 / 5 min (policy) | |
authLogin, authBootstrap |
20 / 10 min | IP |
webUpload |
120 / 5 min | IP |
webDownload |
600 / 1 min | IP |
webLocalCa |
300 / 10 min | IP |
If the server is behind a reverse proxy, you must provide CLIENT_IP_SOURCE=proxy (or
cloudflare); otherwise all clients appear to come from the proxy’s IP and IP-based limits cut off
everyone together.
4.8 Device commands
Section titled “4.8 Device commands”Definition: wonkru_core_server/lib/src/models/enums/device_action.spy.yaml, metadata:
.../catalog/device_action_metadata.dart. All parameter values are strings.
| Action | Multiple devices | Confirmation | Parameters |
|---|---|---|---|
send_notification |
✓ | title, body (the server adds notification_uuid, type) |
|
enable_power_save |
✓ | ||
reduce_brightness |
✓ | level |
|
disable_wifi |
✓ | ||
disable_bluetooth |
✓ | ||
disable_camera |
✓ | ||
lock_device |
✓ | ✓ | |
clear_cache |
✓ | ||
clear_app_data |
✓ | ✓ | package_name (required) |
launch_app |
package_name (required) |
||
launch_intent |
✓ | intent_action, intent_package, intent_component, intent_data, intent_type, intent_categories, intent_flags |
|
uninstall_app |
✓ | package_name (required) |
|
open_app_settings |
✓ | package_name (required) |
|
update_policy |
✓ | ||
policy_change |
✓ | policy_id (the server first assigns it to the device) |
|
get_installed_apps |
include_system_apps (0/1) |
||
get_logs |
|||
device_data |
|||
get_current_location |
|||
reboot |
✓ |
How the agent applies these commands: Mobile agent.