X OAuth2 refresh tokens are single-use: each refresh rotates the pair and invalidates the previous refresh_token, and reusing a rotated one kills the whole family. Three things made this fragile and disconnected accounts far more often than necessary: - The proactive refresh job called refreshToken() directly, bypassing the access-token-first guard in verify() and rotating on every run. - RefreshExpiringTokens used a 2h window on an hourly schedule — equal to the 2h access-token lifetime — so every X account was rotated every hour even while its token was still valid. - A single 4xx refresh failure disconnected the account without checking whether a concurrent refresh had already persisted a working token. Changes: - RefreshSocialToken now routes through verify() (access-token-first), so it only rotates when the access_token is actually invalid. - Shrink the proactive window to 30m and run the command every 15m, so the window still covers the run interval but rotation happens near real expiry. - verify() tolerates the lost-rotation race: on a 4xx refresh, reload and verify with a concurrently-refreshed token before marking TokenExpired. Refs #126
44 lines
1.3 KiB
PHP
44 lines
1.3 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Jobs;
|
|
|
|
use App\Exceptions\PlatformUnavailableException;
|
|
use App\Exceptions\TokenExpiredException;
|
|
use App\Models\SocialAccount;
|
|
use App\Services\Social\ConnectionVerifier;
|
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
|
use Illuminate\Foundation\Queue\Queueable;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Throwable;
|
|
|
|
class RefreshSocialToken implements ShouldQueue
|
|
{
|
|
use Queueable;
|
|
|
|
public int $tries = 1;
|
|
|
|
public function __construct(public SocialAccount $account) {}
|
|
|
|
public function handle(ConnectionVerifier $verifier): void
|
|
{
|
|
try {
|
|
$verifier->verify($this->account);
|
|
} catch (PlatformUnavailableException $e) {
|
|
Log::warning('Token refresh skipped: platform unavailable', [
|
|
'account_id' => $this->account->id,
|
|
'platform' => $this->account->platform->value,
|
|
'error' => $e->getMessage(),
|
|
]);
|
|
} catch (TokenExpiredException $e) {
|
|
$this->account->markAsTokenExpired($e->getMessage());
|
|
} catch (Throwable $e) {
|
|
Log::warning('Proactive token refresh failed', [
|
|
'account_id' => $this->account->id,
|
|
'platform' => $this->account->platform->value,
|
|
'error' => $e->getMessage(),
|
|
]);
|
|
}
|
|
}
|
|
}
|