Two Questions, One Token: Why device_id Could Not Also Mean “Desktop App”

One morning a handful of people using our desktop time tracker could not start their timers. The app showed them a message from the server: “Your organization does not allow clocking in from the web. Open the desktop tracker and clock in there.” They were reading it inside the desktop tracker.
The message was correct about the setting. The organization had just unticked “Web Browser” in its Time Tracking settings, because it wanted every session to come from the desktop app, where screenshots and activity are recorded. The server was simply wrong about who was asking. It thought the desktop app was a browser.
The cause turned out to be a small, very common design mistake: one field on the API token was being used to answer two different questions. This post walks through how that happened in Happy Tracker’s Laravel API, why the obvious repair would have made things worse, and the fix, which was to give each question its own column and make sure each part of the code only reads the one it is entitled to.
The setup: one Sanctum token, two jobs
Happy Tracker has three desktop trackers (Windows, macOS and Ubuntu) and a web app. All four authenticate against the same Laravel API with Sanctum personal access tokens. We use a custom token model, registered with Sanctum::usePersonalAccessTokenModel(), so that a token can carry a few extra columns.
The first extra column was device_id. It came from the single-device lock: one account may run one desktop tracker at a time. When a tracker logs in it sends a stable identifier for the machine, the server claims a lock for that user and that device, and the token is stamped with the device_id. A middleware, EnforceDesktopDeviceLock, runs on every authenticated request. If the token has a device_id, it refreshes the lock’s heartbeat, and if a different desktop now holds the lock, it answers 423 Locked so the losing tracker can show the “log out of the other device” screen. Browser tokens carry no device_id and pass straight through, because the lock was never meant to apply to a browser tab.
public function handle(Request $request, Closure $next): Response
{
$user = $request->user();
$token = $user?->currentAccessToken();
$deviceId = $token instanceof PersonalAccessToken ? $token->device_id : null;
if ($user && $deviceId) {
if (! $this->lock->touch($user, $deviceId)) {
$holder = $this->lock->holder($user);
return response()->json($this->lock->blockPayload($holder), 423);
}
}
return $next($request);
}
That design is fine. device_id answers exactly one question: which machine holds this user’s desktop lock?
Where the second question crept in
A few days later we needed a different answer. Every time entry has a source, so a manager can tell a desktop session from a browser one, and the new desktop-only policy had to block a clock-in that came from a browser. Both needed to know: is this request coming from a desktop tracker at all?
There was a field right there that was null for browsers and set for trackers. So that is what got used:
private function entrySource(Request $request): string
{
$token = $request->user()?->currentAccessToken();
// "Does this token carry a device_id?" was used to mean
// "is this the desktop app?". It is not the same question.
return $token instanceof PersonalAccessToken && $token->device_id
? 'desktop'
: 'web';
}
It passed review, because on every machine anyone tested it on, it was right. A current tracker always sends a device_id, a browser never does, so “has a device_id” and “is a tracker” gave the same answer for every token created after the lock shipped.
Then the policy check was built on top of it:
private function assertMayClockInHere(Organization $organization, Request $request): void
{
if ($this->entrySource($request) !== 'web') {
return; // desktop tracker, always allowed
}
$member = $organization->users()->where('users.id', $request->user()->id)->first();
$override = $member?->pivot?->allow_web_clock_in;
abort_if($override !== null && ! (bool) $override, 422,
'Clocking in from the web is turned off for your account. Start the timer in the desktop app.');
abort_if($override === null && ClockInPolicy::orgRequiresDesktop($organization), 422,
'Your organization does not allow clocking in from the web. Open the desktop tracker and clock in there.');
}
Read that first line again. “Is this a desktop tracker?” is now decided by “does this token hold a device lock?”. The two questions had been merged, and nothing in the code said so.

The tokens that broke the assumption
The equivalence only held for tokens minted after the device lock was released. Before that, trackers logged in without a device_id, because there was nothing to send it to. Those tokens did not expire on release day. People who had logged in weeks earlier and simply left the tracker running, which is what you want people to do with a time tracker, were still using them.
So a group of real, working desktop sessions had a token that looked exactly like a browser’s: no device_id. Every entry they recorded was filed with source = 'web'. Nobody noticed that part, because nothing acted on it. The moment an organization unticked “Web Browser”, assertMayClockInHere() started acting on it, and those people were told to go and use the desktop app they were already using.
When we counted, 28 desktop sessions on Happy Tracker were in that state. Small enough to look like a few odd support tickets. Large enough that, for the organizations affected, the desktop-only setting looked broken on the first day they turned it on.
The obvious fix, and why it would have been worse
The first instinct is a data fix. Those tokens are trackers, trackers have a device_id, so give them one. Write a migration that generates an identifier for every old tracker token, and the source detection is right again without touching the code.
Follow what happens next. The next request from that tracker reaches EnforceDesktopDeviceLock. The token now has a device_id, so the middleware calls $this->lock->touch($user, $deviceId). But no lock was ever claimed for that made-up device. If the user had since logged in on another machine with a current build, that machine holds the lock, and the old session gets a 423. The tracker shows the block screen and the person is signed out of a session that had been working fine for weeks. We would have traded “told to use the app you are using” for “signed out of the app you are using”, for the same people, on the same morning.
That is the useful test for this kind of bug. If repairing the data for question A changes the answer to question B, the field was never one thing. It was two facts sharing a column, and every write to it is a write to both.
The fix: a second column for the second question
The interesting part is that the information we needed was already being sent. All three trackers send client: "desktop" in the login payload, and had done for a long time. The server validated the request and threw that field away, because nothing stored it. So the fix is mostly “stop discarding something you already receive”.
A migration adds a nullable client column to personal_access_tokens, then fills it in for the tokens where we can prove the answer without guessing:
public function up(): void
{
Schema::table('personal_access_tokens', function (Blueprint $table) {
$table->string('client', 16)->nullable()->after('platform');
});
// Anything already carrying a device_id is a tracker by definition.
DB::table('personal_access_tokens')
->whereNotNull('device_id')
->where('device_id', '!=', '')
->update(['client' => 'desktop']);
// Older tracker builds that never sent a device_id. This records what the
// token's own name already says; it grants nothing new. device_id is left
// null on purpose, so the device lock keeps ignoring these sessions.
DB::table('personal_access_tokens')
->whereNull('client')
->whereIn('name', ['Windows tracker', 'macOS tracker', 'Ubuntu tracker'])
->update(['client' => 'desktop']);
}
Two details in there are deliberate.
The second update matches on the token’s name. Older tracker builds always named their token Windows tracker, macOS tracker or Ubuntu tracker, and the web app never used those names. That name is the only evidence an old token carries about where it came from, and it is enough. The migration is recording what the token already says about itself. It is not granting access to anything.
And device_id stays null. That is the whole point. The lock middleware still sees no device_id on those sessions and still leaves them alone, which is the correct behaviour for a session that never claimed a lock. The migration changes the answer to “is this a tracker?” and leaves “which machine holds the lock?” exactly as it was.
Two methods, named for what they mean
The token model now answers the two questions with two methods, and the doc comments say which is which:
class PersonalAccessToken extends SanctumPersonalAccessToken
{
public const LEGACY_TRACKER_NAMES = ['Windows tracker', 'macOS tracker', 'Ubuntu tracker'];
/** Holds the single-desktop device lock: a machine we can identify. */
public function isDesktop(): bool
{
return $this->device_id !== null && $this->device_id !== '';
}
/** Was this token minted for a desktop tracker? Deliberately broader. */
public function isDesktopClient(): bool
{
return $this->isDesktop() || $this->client === 'desktop';
}
public static function clientKindFor(?string $client, ?string $deviceId, string $deviceName): string
{
if ($client === 'desktop' || ! empty($deviceId)) {
return 'desktop';
}
return in_array($deviceName, self::LEGACY_TRACKER_NAMES, true) ? 'desktop' : 'web';
}
}
isDesktop() means “holds the lock”. isDesktopClient() means “is a tracker”, and it is deliberately broader: a current build proves it with a device_id, an older build proves it with client. Source detection switches to the broader one:
private function entrySource(Request $request): string
{
$token = $request->user()?->currentAccessToken();
return $token instanceof PersonalAccessToken && $token->isDesktopClient()
? 'desktop'
: 'web';
}
That one-word change fixes both the source column and the desktop-only check, because the policy guard asks entrySource() rather than looking at the token itself.

The login path, so the rescue does not undo itself
A migration fixes the tokens that exist today. It does nothing for the token an old build will mint tomorrow when someone signs out and back in. If login still stamped those as web, the rescue would last exactly until the user’s next sign-out, and the bug would come back one person at a time, which is the hardest way to notice it.
So the login code decides the client kind with the same rule, through clientKindFor(), and stamps it on every new token:
$deviceName = (string) $request->input('device_name', 'web');
$deviceId = $request->input('device_id');
$client = PersonalAccessToken::clientKindFor($request->input('client'), $deviceId, $deviceName);
if (empty($deviceId)) {
$plain = $user->createToken($deviceName);
$plain->accessToken->forceFill(['client' => $client])->save();
return $plain->plainTextToken;
}
// A device_id means a lock claim first; a 423 and no token if another desktop holds it.
$result = $lock->claim($user, (string) $deviceId, $deviceName, $platform);
if (! $result['ok']) {
return response()->json($lock->blockPayload($result['holder']), 423);
}
A current tracker says client=desktop outright, or proves it with a device_id. An old build says neither, so the legacy name is the fallback. A browser login sends none of the three, and is stamped web. And only a token that actually sent a device_id goes through the lock claim, so the second question still has nothing to do with the first.
Pinning it down with tests
A bug like this comes back when someone, months later, sees device_id on the token, sees that it is null for browsers, and “simplifies” isDesktopClient() back to it. The regression test is written to fail loudly in exactly that case, and its doc block explains the two questions so the person reading the failure understands why:
it('lets a legacy tracker session clock in when the org is desktop-only', function () {
$org = ltOrg(desktopOnly: true);
$user = ltMember($org);
$headers = ltLegacyToken($user, 'Windows tracker'); // named, client=desktop, no device_id
$this->withHeaders($headers)
->postJson('/api/v1/time-entries/clock-in', ['organization_id' => $org->id])
->assertCreated();
});
it('still blocks a real browser when the org is desktop-only', function () {
// ... log in with email and password only, then:
$this->withHeaders(['Authorization' => "Bearer {$token}"])
->postJson('/api/v1/time-entries/clock-in', ['organization_id' => $org->id])
->assertStatus(422);
});
it('keeps a legacy tracker session out of the single-device lock', function () {
// No device_id means no lock claim, so the middleware must wave it through
// rather than 423 the user out of a session that has worked for weeks.
$this->withHeaders($headers)->getJson($url)->assertOk();
});
The tests cover each side of the line. A legacy-named token with client=desktop and no device_id can clock in when the organization is desktop-only, and its entry is recorded as desktop. A plain browser login is still blocked with a 422, so the fix did not quietly open the policy up. A desktop login stamps client=desktop, a browser login stamps web, and a fresh login from an old build, sending only its old device name, comes out as desktop. And a legacy session is not dragged into the device lock: a request with that token gets a normal response, not a 423.
That last test is the one that matters most. It guards against the “obvious fix” from earlier ever being applied, by anyone, for any reason.
The rule we took away: one reader per signal
The technical fix is a column and a method. The rule behind it is more useful, and it applies well beyond tokens.
Only EnforceDesktopDeviceLock reads device_id. Anything that wants to know “desktop or browser?” calls isDesktopClient(). If a new feature needs to know whether a request came from a tracker, it does not get to look at device_id, even though it is right there and even though it would give the right answer for every token you can test with today.
This is the general shape of the mistake:
- A field is introduced to answer question A.
- For every record anyone can see, it also happens to answer question B.
- Somebody uses it for B, because it is there and it works.
- A set of older records exists where the two answers differ, and nobody is looking at them.
- A new feature acts on answer B, and those records break.
- The obvious data repair for B silently changes A.
You will find it with deleted_at used to mean “inactive”, with email_verified_at used to mean “a real person”, with stripe_customer_id used to mean “a paying customer”, with last_login_at used to mean “an active user”. Each works until there is a record where the two meanings disagree: an archived account that was never deleted, a customer record created at checkout and never charged.
A few habits help.
Name the method after the question, not the column. $token->device_id !== null hides the question being asked. $token->isDesktopClient() states it, and gives you one place to change the answer.
Ask “what about the rows created before this column existed?” Every new nullable column has a population of old rows where null means “we did not know yet”, not “no”. Our tokens were exactly that.
Store what the client already tells you. We had the right answer in every login request for months and discarded it. If a client sends a field that describes itself, keeping it costs one column and can save a bad morning later.
Before a data fix, list every reader of the field you are writing. If anything other than the code you are fixing reads it, the fix is not a data fix. It is a behaviour change for that other reader.
Questions we were asked about the fix
Why not force everyone to update the tracker?
Because the people affected had done nothing wrong. Their tracker worked and their token was valid. Making a policy setting work should not require every user to reinstall, and a forced update would not have reached anyone until they read an email. Fixing it on the server fixed it for all 28 sessions on the next request.
Could a browser fake client=desktop?
Someone could send it, the same way someone could send any login field. The desktop-only policy exists because a browser session records no screenshots or activity, so a faked browser session would still show none, and that is visible to the manager. The value records what the client claims at login. It is not an authentication factor, and nothing that grants access depends on it.
How did you find the affected sessions?
By asking the two questions separately and looking for tokens where the answers disagreed. A token that was used recently, had a tracker’s name, and had no device_id was a tracker that the server believed was a browser. Their time entries give a second check: only the desktop tracker ever posts activity blocks, and a browser session cannot produce them. An entry filed as web that has activity blocks attached could only have come from the app. That disagreement is a quick way to spot this kind of bug in any system. Find two independent signals that should agree, and list the rows where they do not.
Why keep device_id at all now?
Because the lock still needs to know which machine it is. The point was never that device_id was bad. It was doing two jobs. Now it does one.
This came out of building Happy Tracker, our time tracking, leave and attendance system with desktop trackers for Windows, macOS and Ubuntu.



