API and contracts
HTTP endpoints, WebSocket messages, validation, persistence, and APK distribution in the tracking server.
tracking-server is a Cloudflare Worker with a central device registry and one SQLite Durable Object per device. The API receives positions, acknowledges persistence, provides history, and distributes configuration. The web dashboard uses the same contracts.
This page describes the code currently in the repository. Examples use fictional identities and synthetic coordinates; they do not represent an active device.
Available routes
On device routes, the administrator can access any ID. A device credential can access only its own ID. HTTP uses the Authorization: Bearer TOKEN header; WebSocket authentication uses a subprotocol. See Authentication and enrollment.
| Method and path | Access | Result |
|---|---|---|
GET /health | Public | Basic Worker health, without testing GPS or device synchronization. |
POST /api/enroll | Installation key | Enrolls or retrieves a device and returns its credential. |
GET /api/devices | Administrator | Lists the registry without tokens. |
POST /api/devices | Administrator | Creates a profile and credential; returns 201. |
POST /api/devices/:deviceId/provision | Administrator | Retrieves the deterministic credential and ensures a registry entry exists. |
GET /api/devices/:deviceId/config | Device or administrator | Current remote configuration. |
PUT /api/devices/:deviceId/config | Administrator | Replaces the settings and increments the version. |
POST /api/devices/:deviceId/locations | Device or administrator | Persists a batch and returns acknowledged IDs and configuration. |
GET /api/devices/:deviceId/locations?limit=200 | Device or administrator | A history window, total count, and latest position from each source. |
GET /api/devices/:deviceId/stream | Authenticated subprotocol | WebSocket updates. |
GET or HEAD /downloads/file.apk | Public | APK served from R2. |
GET or HEAD /downloads/file.apk.sha256 | Public | SHA-256 checksum for the APK. |
Paths that do not start with /api/ are served by static assets, except for health and downloads. The API does not provide device editing or deletion, registry pagination, history purging, or a full export.
Enrollment and provisioning
Enrollment from the app accepts only the device label:
{
"label": "Demo device"
}The administrator can also create an explicit ID through POST /api/devices:
{
"deviceId": "demo-device",
"label": "Demo device"
}Administrative creation accepts IDs containing 1–80 ASCII letters, digits, _, or -. Labels must contain 1–80 characters after trimming leading and trailing whitespace and cannot contain control characters. The legacy provision route accepts IDs up to 128 characters and uses the ID as the label when no profile exists yet.
The creation response contains device, with deviceId, label, createdAt, and updatedAt, plus token. The registry responds with { "devices": [...] }, sorted by enrollment date descending and ID ascending. Registry dates describe enrollment, not the first capture. An administrative request with an existing ID returns 409 device_exists, preserving the label, dates, and history.
Uploading positions and acknowledgments
A batch contains 1–100 positions:
{
"locations": [
{
"eventId": "demo-event-001",
"latitude": 0.001,
"longitude": 0.002,
"accuracyMeters": 5,
"capturedAt": "2026-10-15T12:00:00.000Z",
"provider": "test",
"configVersion": 1
}
]
}| Field | Rule |
|---|---|
eventId | String containing 1–128 characters with no control characters; unchanged on retries. |
latitude | Finite number between −90 and 90. |
longitude | Finite number between −180 and 180. |
accuracyMeters | Finite number between 0 and 10,000. |
capturedAt | Valid ISO 8601 timestamp with a time zone; normalized to UTC by the server. |
provider | native for native capture or test for a synthetic sample. |
configVersion | Positive safe integer identifying the version recorded at capture time. |
The server validates the format of configVersion; it does not require the current version because offline queues can deliver points captured under earlier versions. provider is a client declaration, not cryptographic attestation of the GPS source.
Successful response:
{
"acknowledgedEventIds": ["demo-event-001"],
"config": {
"version": 1,
"tracking": {
"enabled": true,
"distanceFilterMeters": 10,
"intervalSeconds": 5
}
}
}The entire batch is validated before insertion. Writes are transactional, with event_id as the primary key. Resending the same ID with identical normalized content acknowledges it again without duplicating history. The same ID with different content produces 409 event_conflict and rolls back the entire batch, including earlier insertions within that batch.
The acknowledgment and broadcast are held until the Durable Object's durable write is confirmed. The client removes only acknowledged IDs from its queue, never the whole batch merely because it received an HTTP response. Read Queue and synchronization.
History and position sources
GET /api/devices/demo-device/locations?limit=1000 responds with:
{
"locations": [],
"total": 0,
"latestByProvider": {
"native": null,
"test": null
}
}Each stored position includes the submitted fields plus receivedAt, set by the server. capturedAt is the device's capture time; receivedAt is the arrival time, which may be much later after an offline period.
The server selects the latest records by capturedAt, using eventId as a tie-breaker, then returns that window in ascending chronological order. limit is an integer from 1 to 1,000 and defaults to 200. total counts the entire persisted history.
latestByProvider queries the full history for each source, independently of the window. A thousand recent synthetic samples therefore cannot hide the latest native position. A late-arriving point also cannot replace one captured more recently. The dashboard merges HTTP and WebSocket responses by eventId.
WebSocket
The client opens /api/devices/:deviceId/stream with Upgrade: websocket and exactly one subprotocol matching geo-token.TOKEN. The token is not placed in the URL. When an Origin header is present, it must match the Worker's origin.
| Message | Content |
|---|---|
snapshot | config, the latest 200 locations, total, and latestByProvider. |
locations | Only newly inserted positions and total; idempotent retries do not generate new points. |
config | New config after an administrative update. |
The channel sends data from server to client. The runtime automatically replies to the text message ping with pong. Other client messages close the connection with code 1008. The class uses WebSocket hibernation and allows up to 32 simultaneous connections per device; an additional connection receives 429 connection_limit.
The native app receives configuration over HTTP, not through this WebSocket. The dashboard maintains one connection per registered device; there is no aggregated fleet stream.
Limits and error responses
JSON bodies require Content-Type: application/json, are limited to 256 KiB even without Content-Length, and reject unknown fields. Unsupported query parameters are also rejected. The only accepted data query parameter is limit on HTTP history requests.
| HTTP | Common codes | Meaning |
|---|---|---|
400 | invalid_request, invalid_query | Invalid data, fields, or parameters. |
401 | unauthorized, admin_required, invalid_installation | Missing or invalid credential, or incorrect scope. |
403 | forbidden, invalid_origin | Administrative operation or WebSocket origin rejected. |
404 | not_found | Endpoint does not exist. |
405 | method_not_allowed | Method not implemented for this resource. |
409 | event_conflict, device_exists | Event or enrollment conflict. |
413 | body_too_large | Body exceeds 256 KiB. |
415 | unsupported_media_type | Content type is not JSON. |
426 | websocket_required | WebSocket upgrade missing. |
429 | connection_limit, enrollment_limit | Connection limit or new enrollments per network exceeded. |
503 | not_configured | Server secrets missing or invalid. |
507 | device_capacity, registry_capacity | 100,000 events per device or 1,000 devices in the registry. |
500 | internal_error | Unexpected failure; preserve pending events for retry. |
Validated errors usually have the form { "error": { "status": 400, "code": "invalid_request", "message": "..." } }. Not every path includes error.status; also check the HTTP status. Download errors use plain text.
The event limit does not delete old data. Batches containing new IDs are rejected when capacity is reached; retries of existing IDs remain idempotent. There is no automatic retention policy to free space.
APKs and R2
The DOWNLOADS binding connects the Worker to the build bucket. Downloads are public and accept only APK filenames and their .apk.sha256 files, without exposing object listings. The code streams the body from R2.
APK downloads support HEAD, ETag, If-None-Match with a 304 response, a single Range with a 206 response, and resuming with If-Range. Invalid ranges return 416; an object changed during a read can return 412. Public caching lasts five minutes. A checksum is served only when its SHA-256 value and filename match the requested file's expected format.
tracking-server/scripts/publish-android.mjs computes the hash, creates a filename containing part of that hash, and publishes the APK and checksum. It takes an already prepared APK: it does not compile or sign the binary. Publishing Geo Tracking - Specs documentation is separate from this distribution process; see Deployment.
Native application API
The Expo module GeoMonitoring exposes asynchronous methods to React Native code. They require an Android or iOS build containing the local module; they are neither HTTP endpoints nor terminal commands. The nativeTracking wrapper in geo-demo/src/features/tracking/native-tracking.ts validates arguments and provides access to the bridge.
| Bridge method | Wrapper | Contract |
|---|---|---|
configureTracking(settingsJson) | nativeTracking.configure(settings) | Accepts the endpoint, device ID, and device token. The bridge takes serialized JSON; the wrapper takes an object. Configures transport without starting capture. |
getTrackingState() | nativeTracking.getState() | Returns the current local state without the token. |
startTracking() | nativeTracking.start() | Authorizes a local session and requests native startup. Permissions must already be granted; this method alone does not run the screen's permission dialogs. |
stopTracking() | nativeTracking.stop() | Revokes the local session and stops capture; preserves pending events. |
syncTracking() | nativeTracking.sync() | Triggers a native upload or configuration-fetch attempt. |
injectTrackingLocation(sample) | nativeTracking.inject(sample) | Persists a synthetic sample and attempts synchronization. Generates eventId, records the current version, and forces provider: test. |
requestTrackingNotificationPermission() | nativeTracking.requestNotificationPermission() | Requests notification permission on applicable Android versions. The wrapper returns granted permission on platforms without this request. |
Tracking operations return Promise<TrackingState>, except for the notification request. Resolution of sync() or inject() does not guarantee that all network activity has finished or the queue is empty: observe state and subsequent events. Remote configuration can still pause collection after a successful local start.
requestForegroundPermission() and requestBackgroundPermission() also exist on the bridge and return monitoring state with the permission field. The current UI flow coordinates these requests in start-tracking.ts. For normal use, start through the screen's button, which handles denial and cancellation; do not replace that flow with an automatic start() call when a component mounts.
The methods configure, startMonitoring, stopMonitoring, getMonitoringState, injectTestLocation, and simulateDelivery belong to the separate polygon domain. configure does not configure route-tracking transport; use configureTracking or its wrapper for that purpose.
Bridge state and events
TrackingState field | Meaning |
|---|---|
configured | A connection and credential are available locally. |
authorized | Session authorized by a local start; optional in the type for compatibility with older builds. |
enabled | Collection is actually enabled according to native state. |
pendingCount | Number of positions still in the local queue. |
uploadedCount | Acknowledgments counted locally; not a query of the server's total. |
configVersion | Applied remote version. |
distanceFilterMeters, intervalSeconds | Current collector settings. |
deviceId | Configured identity, when available. |
lastLocation | Latest locally recorded position, when present. |
lastSyncAt | Timestamp of the last recorded successful synchronization. |
lastError | Current diagnostic, when present. |
onTrackingStateChanged delivers this same state. nativeTracking.subscribe(listener) returns a subscription that must be removed when the consumer no longer needs it:
import { nativeTracking } from './native-tracking';
import type { TrackingState } from '../../../modules/geo-monitoring/src/GeoMonitoringModule';
export function observeTracking(
updateScreenState: (state: TrackingState) => void,
) {
const subscription = nativeTracking.subscribe(updateScreenState);
return () => subscription.remove();
}Pass the component's state updater as updateScreenState and use the returned function to clean up the subscription on unmount. The existing use-tracking.ts hook already integrates the current screen and polls state periodically. onMonitoringStateChanged, onDiagnosticLog, and onQueueChanged belong to the polygon monitor and do not replace onTrackingStateChanged.
Connecting a development build to the local backend
Automatic enrollment currently targets the deployed Worker. To test another destination without changing enrollment for every user, explicitly configure a development installation. First run the local server and secret initializer described in Installation.
In another terminal, obtain a credential dedicated to the local device. The example below silently reads the administrative value created in .dev.vars; type or paste it at the first instruction and press Enter. It is used only in the terminal, never embedded in app code:
read -r -s ADMIN_TOKEN
printf '\n'
curl --fail-with-body --request POST \
http://127.0.0.1:8787/api/devices/local-device/provision \
--header "Authorization: Bearer $ADMIN_TOKEN"
unset ADMIN_TOKENThe response contains deviceId and token. Use only this device token in the mobile configuration. local-device is a fictional ID: choose different IDs for installations that need isolated queues and histories.
For Android over USB, run adb reverse tcp:8787 tcp:8787; the app can then access http://127.0.0.1:8787. The Android emulator can also use http://10.0.2.2:8787. The iOS simulator reaches the host server through http://127.0.0.1:8787. These HTTP exceptions are for development; a remote service must use HTTPS.
The following example can be integrated into a temporary development control under geo-demo/src/features/tracking/. Receive the credential in memory through that control or the debugger; do not write its value into the source file. The import path is relative to that directory:
import { nativeTracking } from './native-tracking';
export async function connectToLocalServer(deviceToken: string) {
if (!__DEV__) {
throw new Error('This local connection is for development only.');
}
return nativeTracking.configure({
endpoint: 'http://127.0.0.1:8787',
deviceId: 'local-device',
token: deviceToken,
});
}Before changing the destination of an already configured installation, stop collection and confirm all pending events at the previous destination. The queue is not migrated between servers. Android also rejects a change while local authorization exists or synchronization is in progress; wait for that operation to finish. A separate development installation keeps the local test separate from a field device.
After configuration, use the Start tracking button to grant permissions and begin real collection, or inject a synthetic sample through the wrapper to test only queueing and transport:
await nativeTracking.inject({
latitude: 0.001,
longitude: 0.002,
accuracyMeters: 5,
capturedAt: new Date().toISOString(),
provider: 'test',
});Open the local dashboard with the local administrative token and enable Show simulations. Check the device ID, the test source, and queue acknowledgment. Subsequent automatic enrollment preserves an already configured native connection; switching back to the deployed destination is an explicit action, subject to the same queue and session precautions.
The wrapper accepts only the endpoint's origin, without a path, credentials in the URL, query, or fragment, and IDs up to 80 characters. It validates the token locally as a nonempty string without whitespace, but the server decides whether it is authorized. HTTP errors do not clear the queue or turn a synthetic sample into real GPS.
Sources and verification
Main sources: tracking-server/src/index.ts, tracking-server/src/validation.ts, tracking-server/src/registry.ts, tracking-server/src/downloads.ts, docs/tracking-contract.md, geo-demo/modules/geo-monitoring/src/GeoMonitoringModule.ts, geo-demo/src/features/tracking/native-tracking.ts, geo-demo/src/features/tracking/tracking-validation.ts, and geo-demo/src/features/tracking/use-tracking.ts.
Tests in tracking-server/test/server.test.mjs and tracking-server/test/registry.test.mjs exercise contracts in workerd/Miniflare with real SQLite, including concurrent replay, rollback, and runtime restart. This validates the server in the test environment without establishing GPS performance, battery life, or continuous collection on physical hardware. See Tests and evidence.