Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
Stop Meta rate-limit errors from disconnecting Instagram/Threads tokens
Paulo Castellano83ba72ddc609
diff --git a/app/Services/Social/ConnectionVerifier.php b/app/Services/Social/ConnectionVerifier.phpindex 60513199f..b795eed0c 100644--- a/app/Services/Social/ConnectionVerifier.php+++ b/app/Services/Social/ConnectionVerifier.php@@ -9,6 +9,7 @@ use App\Exceptions\PlatformUnavailableException;use App\Exceptions\TokenExpiredException;use App\Models\SocialAccount;use App\Services\Social\Discord\DiscordClient;+use App\Services\Social\Meta\GraphError;use App\Services\Social\Telegram\TelegramApi;use Illuminate\Support\Facades\Cache;use Illuminate\Support\Facades\Http;@@ -311,10 +312,13 @@ class ConnectionVerifierprivate function refreshThreadsToken(SocialAccount $account): void{// Threads uses long-lived tokens that can be refreshed- $response = TokenRefreshClient::for(Platform::Threads)->send(fn () => Http::get(config('trypost.platforms.threads.auth_api').'/refresh_access_token', [- 'grant_type' => 'th_refresh_token',- 'access_token' => $account->access_token,- ]));+ $response = TokenRefreshClient::for(Platform::Threads)->send(+ fn () => Http::get(config('trypost.platforms.threads.auth_api').'/refresh_access_token', [+ 'grant_type' => 'th_refresh_token',+ 'access_token' => $account->access_token,+ ]),+ GraphError::indicatesInvalidToken(...),+ );$data = $response->json();$newToken = data_get($data, 'access_token');@@ -322,7 +326,7 @@ class ConnectionVerifier$account->update(['access_token' => $newToken,'refresh_token' => $newToken,- 'token_expires_at' => now()->addSeconds(data_get($data, 'expires_in', 5184000)),+ 'token_expires_at' => now()->addSeconds(data_get($data, 'expires_in', Platform::LONG_LIVED_TOKEN_TTL_SECONDS)),]);$account->refresh();@@ -330,10 +334,13 @@ class ConnectionVerifierprivate function refreshInstagramToken(SocialAccount $account): void{- $response = TokenRefreshClient::for(Platform::Instagram)->send(fn () => Http::get(config('trypost.platforms.instagram.auth_api').'/refresh_access_token', [- 'grant_type' => 'ig_refresh_token',- 'access_token' => $account->access_token,- ]));+ $response = TokenRefreshClient::for(Platform::Instagram)->send(+ fn () => Http::get(config('trypost.platforms.instagram.auth_api').'/refresh_access_token', [+ 'grant_type' => 'ig_refresh_token',+ 'access_token' => $account->access_token,+ ]),+ GraphError::indicatesInvalidToken(...),+ );$data = $response->json();$newToken = data_get($data, 'access_token');@@ -341,7 +348,7 @@ class ConnectionVerifier$account->update(['access_token' => $newToken,'refresh_token' => $newToken,- 'token_expires_at' => now()->addSeconds(data_get($data, 'expires_in', 5184000)),+ 'token_expires_at' => now()->addSeconds(data_get($data, 'expires_in', Platform::LONG_LIVED_TOKEN_TTL_SECONDS)),]);$account->refresh();@@ -408,13 +415,8 @@ class ConnectionVerifier$body = $response->json() ?? [];- if (isset($body['error'])) {- $errorCode = $body['error']['code'] ?? null;- $errorType = $body['error']['type'] ?? null;-- if ($errorType === 'OAuthException' || $errorCode === 190) {- throw new TokenExpiredException('Instagram access token is invalid or expired');- }+ if (GraphError::indicatesInvalidToken($body)) {+ throw new TokenExpiredException('Instagram access token is invalid or expired');}return $response->successful();@@ -429,13 +431,8 @@ class ConnectionVerifier$body = $response->json() ?? [];- if (isset($body['error'])) {- $errorCode = $body['error']['code'] ?? null;- $errorType = $body['error']['type'] ?? null;-- if ($errorType === 'OAuthException' || $errorCode === 190) {- throw new TokenExpiredException('Facebook access token is invalid or expired');- }+ if (GraphError::indicatesInvalidToken($body)) {+ throw new TokenExpiredException('Facebook access token is invalid or expired');}return $response->successful();@@ -450,13 +447,8 @@ class ConnectionVerifier$body = $response->json() ?? [];- if (isset($body['error'])) {- $errorCode = $body['error']['code'] ?? null;- $errorType = $body['error']['type'] ?? null;-- if ($errorType === 'OAuthException' || $errorCode === 190) {- throw new TokenExpiredException('Threads access token is invalid or expired');- }+ if (GraphError::indicatesInvalidToken($body)) {+ throw new TokenExpiredException('Threads access token is invalid or expired');}return $response->successful();diff --git a/app/Services/Social/Meta/GraphError.php b/app/Services/Social/Meta/GraphError.phpnew file mode 100644index 000000000..e0097e5bd--- /dev/null+++ b/app/Services/Social/Meta/GraphError.php@@ -0,0 +1,30 @@+<?php++declare(strict_types=1);++namespace App\Services\Social\Meta;++/**+ * Interprets Meta Graph API (Facebook / Instagram / Threads) error responses.+ *+ * Meta returns rate-limit and transient failures as an ordinary HTTP 4xx with+ * type "OAuthException" (e.g. code 4 / 17 "too many calls", code 1 / 2+ * "temporary problem"), so neither the HTTP status nor the error type can tell+ * a dead token from a throttle. Only error code 190 means the access token+ * itself is invalid or expired — the same signal the platform publish+ * exceptions already use to decide a disconnect.+ */+class GraphError+{+ /**+ * Whether the given Meta Graph error body means the access token is+ * genuinely invalid or expired (code 190), as opposed to a rate-limit or+ * transient error that must not disconnect a still-valid token.+ *+ * @param array<string, mixed>|null $body+ */+ public static function indicatesInvalidToken(?array $body): bool+ {+ return data_get($body, 'error.code') === 190;+ }+}diff --git a/app/Services/Social/TokenRefreshClient.php b/app/Services/Social/TokenRefreshClient.phpindex 70b023e2a..d20839e4a 100644--- a/app/Services/Social/TokenRefreshClient.php+++ b/app/Services/Social/TokenRefreshClient.php@@ -16,13 +16,18 @@ use Illuminate\Support\Facades\Log;* Normalizes the failure modes of an OAuth token-refresh request:** - ConnectionException (timeout / DNS / refused) → PlatformUnavailableException- * - HTTP 5xx → PlatformUnavailableException- * - HTTP 4xx → TokenExpiredException+ * - HTTP 5xx or 429 → PlatformUnavailableException+ * - other HTTP 4xx → TokenExpiredException+ *+ * Providers that return rate-limit or transient errors as an ordinary 4xx+ * (Meta: Instagram/Threads) can pass an `$isTokenInvalid` classifier to+ * `send()`; only a genuinely dead token then disconnects, while every other+ * 4xx is treated as transient (PlatformUnavailableException).** Callers configure the actual HTTP call through the closure passed to* `send()`, so platform-specific quirks (form vs JSON body, auth headers,* basic auth, etc.) stay where they belong — in the per-platform refresh- * method — while the failure semantics are uniform across providers.+ * method.*/class TokenRefreshClient{@@ -35,11 +40,14 @@ class TokenRefreshClient/*** @param Closure():Response $request+ * @param (Closure(array<string, mixed>|null):bool)|null $isTokenInvalid Given the parsed+ * response body, returns whether a non-5xx/429 failure means the token itself is dead.+ * When it returns false, the failure is treated as transient (PlatformUnavailableException).** @throws PlatformUnavailableException* @throws TokenExpiredException*/- public function send(Closure $request): Response+ public function send(Closure $request, ?Closure $isTokenInvalid = null): Response{$name = $this->platform->label();@@ -62,6 +70,14 @@ class TokenRefreshClient]);$body = $response->json();++ if ($isTokenInvalid !== null && ! $isTokenInvalid($body)) {+ throw new PlatformUnavailableException(+ "{$name} API returned {$response->status()} during token refresh",+ $response->status(),+ );+ }+$message = data_get($body, 'error_description')?? data_get($body, 'error.message')?? "Failed to refresh {$name} token";diff --git a/tests/Feature/Jobs/RefreshSocialTokenTest.php b/tests/Feature/Jobs/RefreshSocialTokenTest.phpindex bf9d02690..898950c30 100644--- a/tests/Feature/Jobs/RefreshSocialTokenTest.php+++ b/tests/Feature/Jobs/RefreshSocialTokenTest.php@@ -107,6 +107,28 @@ test('proactive refresh EXTENDS a still-valid Threads token (extension-model plaexpect($account->fresh()->access_token)->toBe('extended-threads-token');});+test('proactive refresh does NOT disconnect Instagram on a Meta rate-limit (400 OAuthException code 4)', function () {+ $account = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform' => Platform::Instagram,+ 'status' => Status::Connected,+ 'access_token' => 'valid-ig-token',+ 'token_expires_at' => now()->addMinutes(20),+ ]);++ Http::fake([+ config('trypost.platforms.instagram.auth_api').'/refresh_access_token*' => Http::response([+ 'error' => ['message' => 'Application request limit reached', 'type' => 'OAuthException', 'code' => 4],+ ], 400),+ ]);++ (new RefreshSocialToken($account))->handle(app(ConnectionVerifier::class));++ // A rate-limit is transient — the still-valid token must stay Connected.+ expect($account->fresh()->status)->toBe(Status::Connected);+ expect($account->fresh()->access_token)->toBe('valid-ig-token');+});+test('refresh job marks account as TokenExpired when refresh_token is rejected', function () {Queue::fake();diff --git a/tests/Feature/Services/Social/ConnectionVerifierTest.php b/tests/Feature/Services/Social/ConnectionVerifierTest.phpindex e5472b44d..29a38b995 100644--- a/tests/Feature/Services/Social/ConnectionVerifierTest.php+++ b/tests/Feature/Services/Social/ConnectionVerifierTest.php@@ -561,3 +561,65 @@ test('reports discord disconnected when the bot was removed from the guild', funexpect((new ConnectionVerifier)->verify($account))->toBeFalse();});++test('instagram refresh treats a Meta rate-limit (400 OAuthException code 4) as transient, not a dead token', function () {+ Http::fake([+ config('trypost.platforms.instagram.auth_api').'/refresh_access_token*' => Http::response([+ 'error' => ['message' => 'Application request limit reached', 'type' => 'OAuthException', 'code' => 4],+ ], 400),+ ]);++ $account = SocialAccount::factory()->instagram()->create([+ 'token_expires_at' => now()->subHour(),+ ]);++ expect(fn () => (new ConnectionVerifier)->refreshToken($account))+ ->toThrow(PlatformUnavailableException::class);+});++test('threads refresh treats a Meta rate-limit (400 OAuthException code 17) as transient, not a dead token', function () {+ Http::fake([+ config('trypost.platforms.threads.auth_api').'/refresh_access_token*' => Http::response([+ 'error' => ['message' => 'User request limit reached', 'type' => 'OAuthException', 'code' => 17],+ ], 400),+ ]);++ $account = SocialAccount::factory()->threads()->create([+ 'token_expires_at' => now()->subHour(),+ ]);++ expect(fn () => (new ConnectionVerifier)->refreshToken($account))+ ->toThrow(PlatformUnavailableException::class);+});++test('instagram refresh treats code 190 as a genuinely expired token', function () {+ Http::fake([+ config('trypost.platforms.instagram.auth_api').'/refresh_access_token*' => Http::response([+ 'error' => ['message' => 'Access token has expired', 'type' => 'OAuthException', 'code' => 190],+ ], 400),+ ]);++ $account = SocialAccount::factory()->instagram()->create([+ 'token_expires_at' => now()->subHour(),+ ]);++ expect(fn () => (new ConnectionVerifier)->refreshToken($account))+ ->toThrow(TokenExpiredException::class);+});++test('instagram verify treats a Meta rate-limit (OAuthException code 4) as still-valid, not a disconnect', function () {+ Http::fake([+ config('trypost.platforms.instagram.graph_api').'/me*' => Http::response([+ 'error' => ['message' => 'Application request limit reached', 'type' => 'OAuthException', 'code' => 4],+ ], 400),+ ]);++ // Not expired, so verify hits the endpoint directly (no refresh).+ $account = SocialAccount::factory()->instagram()->create([+ 'token_expires_at' => now()->addDays(30),+ ]);++ // A rate-limit must NOT raise TokenExpiredException (which would disconnect);+ // verify returns false and the caller leaves the account connected.+ expect((new ConnectionVerifier)->verify($account))->toBeFalse();+});diff --git a/tests/Unit/Services/Social/Meta/GraphErrorTest.php b/tests/Unit/Services/Social/Meta/GraphErrorTest.phpnew file mode 100644index 000000000..f1d79931b--- /dev/null+++ b/tests/Unit/Services/Social/Meta/GraphErrorTest.php@@ -0,0 +1,35 @@+<?php++declare(strict_types=1);++use App\Services\Social\Meta\GraphError;++test('code 190 indicates a genuinely invalid token', function () {+ expect(GraphError::indicatesInvalidToken([+ 'error' => ['message' => 'Access token has expired', 'type' => 'OAuthException', 'code' => 190],+ ]))->toBeTrue();+});++test('rate-limit codes carried as OAuthException do NOT indicate an invalid token', function () {+ // Meta returns rate limits as HTTP 4xx with type OAuthException — they must+ // stay transient so a throttle never disconnects a still-valid token.+ expect(GraphError::indicatesInvalidToken([+ 'error' => ['message' => 'Application request limit reached', 'type' => 'OAuthException', 'code' => 4],+ ]))->toBeFalse();++ expect(GraphError::indicatesInvalidToken([+ 'error' => ['message' => 'User request limit reached', 'type' => 'OAuthException', 'code' => 17],+ ]))->toBeFalse();+});++test('transient codes do NOT indicate an invalid token', function () {+ expect(GraphError::indicatesInvalidToken([+ 'error' => ['message' => 'Service temporarily unavailable', 'code' => 2],+ ]))->toBeFalse();+});++test('a body with no error, or a null body, does not indicate an invalid token', function () {+ expect(GraphError::indicatesInvalidToken(null))->toBeFalse();+ expect(GraphError::indicatesInvalidToken([]))->toBeFalse();+ expect(GraphError::indicatesInvalidToken(['data' => ['id' => '123']]))->toBeFalse();+});