How It Works

Inside the USB and VPN Monitoring Backend — Sessions, Alerts & Data Hygiene

How TIMO360's NestJS backend pairs USB and VPN events into idempotent MongoDB sessions, prevents alert spoofing and purges copied file names in 30 days.

TIMO360 logoTIMO360 Team3 min read
Inside the USB and VPN Monitoring Backend — Sessions, Alerts & Data Hygiene

Key takeaways

  • AgentController separates USB and VPN events before they ever reach the activity aggregator, keeping peripheral connections out of active/idle timelines.
  • A MongoDB partial unique index and atomic claim-first updates ensure replayed connects and racing background sweeps never duplicate sessions or alerts.
  • Per-device daily rate caps, cumulative monotonicity checks and Unicode bidi/control-character stripping protect admins from noisy or forged metadata.
  • Copied file names are accessible solely to organization admins, omitted from all alerts and automatically cleared after 30 days.

Capturing a USB plug-in or VPN connection on an endpoint is only half the problem. Once events hit the API, a multi-tenant backend has to keep peripheral telemetry out of working-time calculations, survive offline retries without duplicating sessions, guard against spoofed device strings, close orphaned connections after crashes and enforce strict retention windows.

Here is how TIMO360's NestJS DeviceUsageService and AgentController handle USB and VPN events from ingestion to cleanup.

1. Clean Separation From Attendance and Idle Time

Both activity heartbeats and peripheral events travel through the desktop agent's offline-capable batch queue to POST /agent/events. At the controller boundary, isDeviceUsageEvent() filters out USB_CONNECTED, USB_DISCONNECTED, VPN_CONNECTED, VPN_DISCONNECTED and USB_TRANSFER and routes them exclusively to DeviceUsageService.record().

As a result, the core activity aggregator never mistakes a pendrive or VPN event for keyboard/mouse presence or a shift boundary.

2. Server-Authoritative Policy Enforcement

Running agents refresh their organization's monitoringPolicy via GET /agent/settings roughly every 15 minutes (every 45 sync ticks). Rather than trusting the client alone, DeviceUsageService.record() re-reads the organization's policy on every batch:

  • If USB or VPN monitoring is turned off for that organization, incoming events for that kind are dropped immediately.
  • If trackTransfers is off, any USB_TRANSFER events are ignored.
  • If captureFileNames is off, parseTransfer() discards any file names before storing the update.

3. Idempotent Sessions and Atomic Alert Claims

Desktop agents retry batches across Wi-Fi drops, and backend cron jobs can run concurrently across instances. Two MongoDB patterns keep device_usage_sessions deterministic without heavy distributed locks:

  1. Partial unique open-session index: DeviceUsageSessionSchema defines a unique index on { deviceId, kind, deviceKey } constrained by { endedAt: null }. At most one open session can exist per drive or VPN on a machine, making replayed *_CONNECTED events safe no-ops.
  2. Claim-first alert flags: Before creating notifications for long connections (longUsageNotifiedAt), crossed transfer thresholds (transfer.notifiedAt) or final removal summaries (transfer.finalizedAt), the service executes an atomic updateOne filtering on null. Only the winner with modifiedCount > 0 emits an admin alert.

For transfer updates, cumulative totals are also checked for monotonicity (fileCount < previous.fileCount || bytes < previous.bytes) so an out-of-order retry never overwrites newer figures.

4. Hardening Against Noise and Forged Metadata

Because device labels, extensions and file names come from endpoints and can end up inside admin alerts, the backend enforces strict sanitization and volume bounds:

  • Control and bidi character stripping: cleanText() strips ASCII control characters and Unicode zero-width or bidirectional override characters (such as U+202E) so a malicious filename cannot visually disguise report.exe as report.txt in a UI or notification.
  • Per-device 24-hour ceilings: Session creation caps at 100 new sessions per device per day and transfer alerts cap at 20 per device per day, stopping buggy drivers or forged keys from flooding administrators.
  • Strict payload bounds: At most 20 extension counts and 50 filenames are retained per transfer summary.

5. Five-Minute Sweep, RBAC Isolation and 30-Day File-Name Purge

A @Cron(CronExpression.EVERY_5_MINUTES) sweep keeps session state honest when laptops lose power or policies change mid-shift:

  • Stale devices: Sessions open on devices silent for over 15 minutes close at the device's lastSeenAt timestamp.
  • Punch-out boundaries: Unless usb.trackTransfers or vpn.alwaysOn is enabled, any session left open after an employee punches out is closed automatically.
  • Disabled rules: Switching USB or VPN monitoring off ends open sessions immediately so they do not stay marked "Still connected."

Tightest access and shortest retention on file names

When file-name capture is enabled, DeviceUsageController returns copied file names solely when user.role === Role.ORG_ADMIN (managers see counts, byte totals and extensions only), file names are never placed into notification text or live socket broadcasts, and a daily 3:00 AM retention job clears transfer.files after 30 days while deleting ended sessions per your organization's session retention policy.

Read our Data Retention controls, explore Role-Based Access Control or start from the agent side in Implementing Cross-Platform VPN Detection in Rust.

Ready for Attendance & Presence Tracking That Respects Your Team?

Set up your organization, install the agent, and start seeing attendance and presence data in minutes — without a single keystroke or screenshot recorded.

Windows, macOS & Linux Pay per employee license Zero keystroke or screen capture
Chat with us