Book a call
Menu

Refuse, Don’t Evict: Building a One-Desktop-Per-Account Lock with Laravel Sanctum

Happy Coders team5 Dec 202613 min read
Refuse, Don’t Evict: Building a One-Desktop-Per-Account Lock with Laravel Sanctum

Happy Tracker has a rule that sounds simple: one account can run the desktop tracker on only one computer at a time. The browser is exempt; the Mac, Windows and Ubuntu apps are not. The reason is evidence. The desktop app takes screenshots and records activity, and two machines tracking the same person produce two streams of evidence for one hour of work.

Saying “one at a time” is easy. Deciding what happens at the boundaries is the actual design work. What should a second laptop see? When does the first laptop stop counting as “present”? What if it was simply asleep? What if both log in within the same second? And how does a machine that has lost the lock sign out, when every authenticated route now refuses it?

This post walks through how we built the lock in a Laravel 11 API with Sanctum personal access tokens: the takeover flow, the stale timeout, why we refuse instead of evict, why the answer is HTTP 423, and one detail in our own code that we would write differently today.

The shape of it

There are three moving parts. Desktop tokens carry a stable per-machine device_id. A small table holds, per user, the one machine that currently holds the lock and when it was last seen. A middleware on every authenticated route refreshes that timestamp for desktop requests and refuses requests from any other desktop machine.

// The life of the lock, per user (one row in tracker_device_sessions)
//
//   desktop login ──► claim()  ── free / stale / same device ──► row written, token issued
//                         └────── another fresh device ─────────► 423, no token
//
//   every desktop request ──► middleware touch()  ── still ours ──► last_seen_at = now
//                                        └─────────── someone else's ──► 423
//
//   logout ──► release()  (row deleted, lock free at once)
//   silence > 180 s ──► holder() treats the row as stale (lock free, row still there)

A browser login sends no device_id, so it never touches any of this. That is the whole exemption: there is no list of allowed clients, just the absence of a device identity.

The table: one row per user, enforced by the schema

Schema::create('tracker_device_sessions', function (Blueprint $table) {
    $table->id();
    // One active desktop holder per user.
    $table->foreignId('user_id')->unique()->constrained()->cascadeOnDelete();
    $table->foreignId('organization_id')->nullable()->constrained()->nullOnDelete();
    $table->string('device_id');
    $table->string('device_name')->nullable();
    $table->string('platform')->nullable();
    $table->timestamp('last_seen_at');
    $table->timestamps();
    $table->index('last_seen_at');
});

The unique() on user_id is the most important line in the feature. It means “one holder per user” is not a convention the code has to remember. The database will not store two. Every write goes through updateOrCreate keyed on user_id, so a write from a second machine replaces the row instead of adding a competing one. We come back to why that matters when we get to races.

The row holds device_name and platform purely for the human-facing message. They play no part in deciding who holds the lock. Only device_id does. Device names are not unique; plenty of Macs report the same name.

Presence is a heartbeat, not a session

The hardest question is “is the holder still there?”. A desktop app can quit cleanly, crash, lose Wi-Fi, have its lid closed or have its battery die. Only the first of those tells the server anything. So the lock does not wait for a goodbye. It asks when it last heard hello.

public const STALE_AFTER_SECONDS = 180;

/** The current, non-stale desktop holder for a user (null = lock is free). */
public function holder(User $user): ?TrackerDeviceSession
{
    $session = TrackerDeviceSession::where('user_id', $user->id)->first();
    if (! $session) {
        return null;
    }
    return $this->isStale($session) ? null : $session;
}

public function isStale(TrackerDeviceSession $session): bool
{
    return $session->last_seen_at === null
        || $session->last_seen_at->lt(now()->subSeconds(self::STALE_AFTER_SECONDS));
}

A holder that has not made a request for 180 seconds is treated as gone. The desktop apps poll the API every 30 seconds while running, so a live machine refreshes its timestamp six times inside that window. Missing one or two polls on a flaky connection does not lose the lock.

The number is a trade-off between two complaints. Make it shorter, and a laptop on a bad train connection loses its lock and blocks itself. Make it longer, and the person whose old laptop died has to wait longer before the new one can take over. Three minutes is long enough to absorb ordinary network trouble, and short enough that “wait a moment and press Try again” is honest advice.

Notice that a stale row is not deleted. holder() simply returns null for it, and the next claim overwrites it. There is no cleanup job to schedule and nothing that can fall behind.

Login: refuse, never evict

When a desktop app logs in, the controller tries to claim the lock before it mints a token.

public function claim(User $user, string $deviceId, ?string $deviceName, ?string $platform): array
{
    $holder = $this->holder($user);

    if ($holder && $holder->device_id !== $deviceId) {
        return ['ok' => false, 'holder' => $holder];   // refuse, never evict
    }

    $session = TrackerDeviceSession::updateOrCreate(
        ['user_id' => $user->id],
        ['device_id' => $deviceId, 'device_name' => $deviceName,
         'platform' => $platform, 'last_seen_at' => now()],
    );

    return ['ok' => true, 'holder' => $session];
}
private function issueDeviceToken(User $user, Request $request): string|JsonResponse
{
    $deviceId = $request->input('device_id');

    if (empty($deviceId)) {
        // Browser login: plain token, never locked.
        return $user->createToken($request->input('device_name', 'web'))->plainTextToken;
    }

    $lock = app(DeviceLock::class);
    $result = $lock->claim($user, (string) $deviceId, $request->input('device_name'), $request->input('platform'));
    if (! $result['ok']) {
        return response()->json($lock->blockPayload($result['holder']), 423);
    }

    $new = $user->createToken($request->input('device_name'));
    $new->accessToken->forceFill(['device_id' => (string) $deviceId, 'client' => 'desktop'])->save();

    return $new->plainTextToken;
}

The design choice hides in the first branch of claim(). If another machine holds a fresh lock, the new login is refused. It is not allowed to kick the old machine out.

We considered “last login wins”, because it feels friendlier for the person on the new laptop. It falls apart in exactly the situation the lock exists for. If two machines are both running the tracker and both are allowed to take over, each one evicts the other on its next poll. You get a ping-pong where both machines alternate between tracking and blocked, and each switch produces a little burst of screenshots. Refusal is stable. Exactly one machine holds the lock, and it keeps it until it signs out or goes quiet.

The cost of refusal is that the person on the new laptop must deal with the old one. That cost is paid once, and the message tells them precisely what to do. The cost of eviction would be paid continuously, in the data.

Refusal also means a refused login gets no token. A machine that has never held the lock has nothing to retry with, so it just logs in again later. A machine that held the lock and then lost it is a different case, covered below.

Refusing a new login versus evicting the current holder
Eviction feels friendly and oscillates when both machines are running.

The middleware: every request is a heartbeat and a check

Claiming at login is not enough. The lock can change hands while an app is running: the old laptop slept, went stale, the new one claimed, and now the old one wakes up still holding a perfectly valid token. So the check has to happen on every request, not just at login.

public function handle(Request $request, Closure $next): Response
{
    $user = $request->user();
    $token = $user?->currentAccessToken();
    // Only real desktop tokens carry a device_id; browser tokens and
    // TransientToken (tests) pass straight through.
    $deviceId = $token instanceof PersonalAccessToken ? $token->device_id : null;

    if ($user && $deviceId && ! $this->lock->touch($user, $deviceId)) {
        $holder = $this->lock->holder($user);
        return response()->json(
            $holder ? $this->lock->blockPayload($holder)
                    : ['message' => 'Device lock lost.', 'code' => DeviceLock::CODE],
            423,
        );
    }

    return $next($request);
}

Putting it in middleware rather than in individual endpoints was deliberate. Clock-in, screenshot upload, activity upload, the dashboard poll: all of them are covered without a single line in their controllers. A new endpoint added next month is covered automatically because it sits in the same route group. With per-endpoint checks, the one you forget is always the one that uploads screenshots.

The same call is both the heartbeat and the guard. A request from the holder refreshes last_seen_at. A request from anyone else gets 423. There is no separate heartbeat endpoint for the apps to remember to call.

The instanceof PersonalAccessToken check matters in tests. Sanctum’s actingAs gives you a TransientToken with no columns, and without the check every feature test that does not care about devices would need to.

How each request path interacts with the desktop lock
The same middleware call is the heartbeat and the guard.

Why 423 Locked

We had three candidates. A 401 would make every client treat the user as logged out, throw away the token, and show the login form. That is wrong, because the credentials are fine. A 403 already meant “your account is suspended” in our apps, which shows a different screen. A 409 Conflict is close, but generic.

423 Locked is rarely used, which is exactly its value here. No other part of the API returns it, so a client can branch on the status code alone and know it means this one thing. The body carries a machine-readable code as well, for clients that prefer to check the body:

public function blockPayload(TrackerDeviceSession $holder): array
{
    return [
        'message' => 'Another device is already tracking on this account. '
            .'Log out of the other tracker first, then try again.',
        'code' => 'device_locked',
        'device' => [
            'name' => $holder->device_name ?: 'another device',
            'platform' => $holder->platform,
            'last_seen_at' => optional($holder->last_seen_at)->toIso8601String(),
        ],
    ];
}

The message is written for the person, not for the developer: what is happening, and the one thing to do about it. The device block lets a client say which machine holds the account, if it wants to.

Keep the token, stop the capture

On the client, a 423 does two things immediately: it stops capture, and it shows the block screen. It does not delete the token.

/// Enter the blocked state: stop all local tracking so no parallel screenshots or
/// activity are produced, and show the block screen. The token is kept so the user
/// can retry once they've logged out of the other device (or it goes stale).
private func enterDeviceLocked(_ error: ApiError) {
    deviceLocked = true
    deviceLockedMessage = error.message
    capturer.setTracking(false, onBreak: false)
    activityMonitor.setTracking(false, onBreak: false)
}

/// "Try again": one authenticated request. If the other device has logged out or
/// gone stale, the middleware hands this device the lock and we resume.
func retryDeviceLock() async {
    do {
        _ = try await ApiClient.shared.me()
        deviceLocked = false
        await refresh(full: true)
    } catch let error as ApiError where error.isDeviceLocked {
        deviceLockedMessage = error.message
    } catch { /* network etc. */ }
}

Stopping capture first is the point of the whole feature. A machine that has lost the lock must not keep producing screenshots while the user reads the message.

Keeping the token is what makes Try again work. Retrying is just one authenticated request. If the other machine has since signed out or gone stale, the middleware’s touch() finds the lock free and hands it to this machine on the spot. The app refreshes and the timer comes back. There is no second login, and no password to type again.

The session the user was clocked in to survives all of this. It lives on the server, attached to the user, not to the machine. When a new machine takes over, its first dashboard poll returns the open entry and the app shows it as running.

The way out has to stay open

Here is a trap we nearly built. The lock middleware sits on the whole authenticated group. Logout is in that group. So a machine that has lost the lock asks to log out and gets told it is locked. The user cannot even sign out of the machine they are trying to retire.

Route::middleware(['auth:sanctum', 'device.lock'])->group(function () {
    // Logout is exempt so a device that LOST the lock can still cleanly sign out.
    Route::post('auth/logout', [AuthController::class, 'logout'])
        ->withoutMiddleware('device.lock');
    Route::get('me', [AuthController::class, 'me']);
    // ... clock-in, screenshots, activity, everything else
});

Logout is exempt, and it deletes the lock row if this machine holds it. That makes logout the fast path for a clean handover: sign out on the old machine and the lock is free at that instant, with no three-minute wait. Setting a first password (for accounts created through Google sign-in) also sits outside the lock, for a similar reason: somebody doing that may be doing it precisely so they can sign in to a desktop tracker.

The general rule we took from this: when you put a guard on a whole route group, list the routes that a guarded-out client still needs. There are usually one or two.

Races

claim() reads the holder and then writes. Two machines logging in within the same few milliseconds could both read “free”, and both could write. We did not add a database lock around this, and here is why we did not need one.

The unique index means both writes land on the same row. The last write wins, so the row ends up naming one of the two machines. Both machines receive a token, but only one of them is the holder. The other machine’s very next request, at most 30 seconds later, goes through touch(), finds a different fresh holder, and gets 423. That 423 stops its capture.

So the race is not prevented. It is made harmless and short-lived. In the worst case the losing machine may capture for a few seconds before its first poll. We judged that acceptable for a scenario that requires one person to sign in on two laptops in the same instant.

The detail we would write differently

Reading our own code for this post turned up something worth admitting. Here is touch():

public function touch(User $user, string $deviceId): bool
{
    $holder = $this->holder($user);

    if (! $holder) {
        // Free or stale: this device (re)claims it.
        TrackerDeviceSession::updateOrCreate(
            ['user_id' => $user->id],
            ['device_id' => $deviceId, 'last_seen_at' => now()],
        );
        return true;
    }
    if ($holder->device_id !== $deviceId) {
        return false;
    }
    $holder->update(['last_seen_at' => now()]);
    return true;
}

When the lock is free or stale, touch() re-claims it by writing device_id and last_seen_at. Unlike claim(), it does not write device_name or platform. Because updateOrCreate only updates the attributes you pass, the row keeps the previous holder’s name.

When can this happen? A machine took the lock through touch() rather than at login. That is exactly the Try-again path: an app that was blocked, kept its token, and retried once the old holder went stale. After that, if a third machine is refused, the block message can name the old laptop instead of the one actually holding the account. Nothing about who holds the lock is wrong, because that is decided by device_id alone. Only the label is.

The fix is small: give touch() the token’s device name and platform and write them too, or clear them when re-claiming. The lesson is general. When a row has several paths that “take ownership” of it, every path should write the whole identity, not just the field the decision depends on. Otherwise the fields you show to humans quietly drift from the field you trust.

Testing it without real laptops

The lock is all about time and identity, and both are easy to fake in feature tests. Each “machine” is just a login request with a different device_id. Each “three minutes later” is a jump of the test clock with $this->travel(181)->seconds(). The cases worth a test each are the boundaries described above.

  • A second device’s login gets 423 and no token while the first is fresh.
  • After 181 seconds of silence, the second device’s login succeeds.
  • After that takeover, the first device’s next API call gets 423.
  • Logout from the losing device still returns 200.
  • A browser login is never refused, however many desktop logins exist.

One gotcha cost us time in a sibling codebase with the same lock. Inside a single test, sending requests with two different bearer tokens does not behave like two clients. Sanctum’s guard remembers the user it resolved for the first request, so the second request quietly runs as the first device. Calling $this->app['auth']->forgetGuards() between requests makes each request resolve its own token, the way production does. Production is unaffected because every HTTP request starts fresh; only tests share the guard.

What we would tell someone building the same thing

  • Let the database enforce “one holder”. A unique index turns races from a correctness problem into a few seconds of inconvenience.
  • Decide presence by recent requests, not by sessions. Clients rarely get to say goodbye.
  • Pick a stale timeout from your clients’ poll interval: several polls long, so one dropped request does not lose the lock.
  • Refuse the newcomer instead of evicting the holder. Eviction looks friendly and oscillates.
  • Enforce in middleware, so new endpoints are covered on the day they are written.
  • Use a status code nothing else returns, and a message a person can act on.
  • Exempt logout. A locked-out client must always be able to leave.
  • On the client, stop the side effects first and keep the credentials, so a retry is one request.

Happy Tracker is our time tracking, leave and attendance system for service businesses, with desktop apps for macOS, Windows and Ubuntu. See how it works.

Keep reading

Related articles