Skip to content

fix(tiktok): refresh expired access tokens on demand and share one refresh lock - #1756

Merged
sung17 merged 2 commits into
mainfrom
fix/tiktok-token-refresh-recovery
Nov 26, 2026
Merged

sung17 merged 2 commits into
mainfrom
fix/tiktok-token-refresh-recovery

Conversation

@sung17

@sung17 sung17 commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

Summary

Fixes #1754. A TikTok access token lives 24 hours. Once it expired, nothing refreshed it, and comment automation stopped without any error.

Why the token was never refreshed

  • The SDK refreshes and retries only on an AuthException. TikTok threw TiktokAPIException for everything, so this never ran on TikTok.
  • The commenter lookup called the API directly with the stored token. When the lookup failed, the automation was withheld, so nothing was sent and nothing else refreshed the token either.
  • Adding "has been revoked" to AUTH_FAILED_PATTERNS, as the issue suggests, would not fix this. Those patterns only label an error; they never turn it into an AuthException. The same list also decides whether a connection counts as revoked, so an ordinary expired token would push people to reconnect.

Changes

  • New TiktokAuthException (an AuthException), thrown when TikTok rejects the access token. It is recognized by Business API code 40105 or its wording, or an Open API 401. Every Business API rejection now keeps TikTok's own error code.
  • New listComments integration action. The worker's commenter lookup and the builder's missed-comments scan call it through runAction, so the SDK refreshes an expiring token first and retries once on a rejection.

Preparing for refresh-token rotation (TikTok, effective 2026-12-01)

From that date, each refresh returns a new refresh token and invalidates the old one, so a refresh that runs with the old token, or writes it back, leaves the connection dead.

  • One refreshTiktokAuth is now shared by the SDK refreshAuth, the scheduled job and both builder refresh actions. It always saves the returned refresh_token.
  • All of them now run under the SDK auth store's lock, through tiktokIntegrationService.withTokenRefreshLock, and read the auth inside it. Before this, the job and the builder buttons locked on auth:refresh:tiktok:<id>, while the SDK locked on auth:refresh:connection:<id>.
  • cacheCommentToMessageStatus now writes only auth.metadata.commentToMessage (with jsonb_set). It used to write back the whole auth it had read before calling TikTok, which could restore tokens replaced by a refresh in the meantime.

Out of scope

  • openId is unique, so one install cannot connect the same account twice. Two separate installs that share one TikTok account (for example staging and production) will still invalidate each other's tokens after 2026-12-01. Code cannot prevent that, so it belongs in the release notes.
  • Zalo has the same lock mismatch, but it does not rotate refresh tokens yet. Tracked separately.

Test plan

  • Worker: an expired-token rejection triggers one refresh, saves the rotated refresh token and retries with the new access token; a token about to expire is refreshed before the call; if the retry fails too, the lookup still returns undefined.
  • TikTok package: Business API code 40105 and its wording become TiktokAuthException; other rejections stay TiktokAPIException with their code.
  • Scheduled job: uses the shared lock and stores the new refresh token. Comment-to-Message: writes only the metadata field.
  • Full suites: integrations/tiktok (151 tests), packages/business, apps/worker and apps/builder all pass.
  • pnpm lint, type checks for integration-tiktok, business, worker and builder; invariant-guard clean.
  • Code 40105 is taken from TikTok's docs and has not been checked against a real expired token yet (the wording match covers it either way). Check it on staging: move expiresAt into the past, then comment on a video.

🤖 Generated with Claude Code

…fresh lock

TikTok access tokens live 24 hours, and nothing refreshed them on demand.
Every TikTok failure was a TiktokAPIException, so the SDK's refresh-and-retry
(which only answers AuthException) never ran. The commenter identity lookup
also called the API directly with the stored token, so once it expired,
comment automation was withheld and no other call refreshed it (#1754).

- Throw TiktokAuthException (an AuthException) when TikTok rejects the access
  token (Business API code 40105 or its wording, Open API 401), and keep
  TikTok's error code on every Business API rejection.
- Add a `listComments` action and use it via runAction from the worker's
  commenter lookup and the builder's missed-comments scan.
- Share one refreshTiktokAuth across the SDK, the scheduled job and both
  builder refresh actions, and run all of them under the SDK auth store's
  lock. From 2026-12-01 TikTok rotates refresh tokens, so two refreshes racing
  on one would leave a revoked token behind.
- Cache Comment-to-Message by writing only auth.metadata.commentToMessage,
  so it can no longer write back tokens read before a refresh.

Closes #1754

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the bug Something isn't working as expected label Nov 20, 2026
@sung17

sung17 commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

Hi @rancaHoratiu
Thanks for the detailed report. You were right that the rejection was never mapped to AuthException, so the SDK's refresh-and-retry never kicked in. One more thing made it worse: the commenter lookup called the TikTok API with the stored token directly, so it skipped refresh entirely and stayed stuck.

Fix is in #1756. Every TikTok Business API call now throws a TiktokAuthException on error code 40105 or on the "access token is incorrect / expired" wording. The commenter lookup now goes through runAction, so it refreshes the token and retries once.

Could you test it before we merge? We haven't confirmed code 40105 against a real expired token yet, and your stuck connection is the ideal case:

Run the fix/tiktok-token-refresh-recovery branch (builder and worker, including the schedule worker).
Leave a comment on one of the connected account's videos.
Expected: the worker refreshes the token and processes the comment. If your refresh token has also expired (about 365 days), the connection can't recover and has to be reconnected. Please tell us which case you hit.
If you can share the raw TikTok error (code and message) from the logs, even better. We'll wait until Nov 27 and merge after that either way.

@sung17
sung17 merged commit cd4a006 into main Nov 26, 2026
14 checks passed
@rancaHoratiu

Copy link
Copy Markdown

Tested on our production install (Coolify, EEA account) with the main images at 29e848d, which include #1756.

Setup: I put back a genuinely expired access token (expired Nov 14) into IntegrationTiktok.auth and left expiresAt in the future, so nothing would refresh it ahead of time and the first API call had to fail. Refresh token still valid (until Nov 2027).

Result: case 1, it recovered on its own.

  • A comment came in at 09:57:18 UTC. By 09:57:19 the stored access token had been replaced, and expiresAt moved forward 24h.
  • The comment automation went through normally: CommentAutomationEvent status sent, public reply delivered at 09:59:13 (that delay is our automation's own setting). No reconnect needed.

Raw TikTok error for the expired token (I called GET /open_api/v1.3/business/get/ with it directly, because the worker doesn't log it at INFO level):

{"code":40105,"message":"Access token is incorrect or has been revoked."}

So 40105 is the right code to map to the auth exception. One small suggestion: logging the refresh at INFO level ("token rejected, refreshed") would make this easier to spot in production. Right now it's silent.

Thanks for the quick fix!

@sung17

sung17 commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks a lot for testing this on a real install, and for the raw TikTok response. That confirms 40105 is the right code to treat as a rejected token.

Good point about the logging. #1797 adds an info-level log line when a rejected token gets refreshed and the call is retried:

Access token rejected; refreshed it and retrying the call

It includes the integration name and the provider's rejection reason, but no token values. It's in the shared SDK refresh path, so every OAuth channel with a refresh handler (TikTok, Instagram, Messenger, LINE…) logs it, not just TikTok. Nothing changes when a refresh fails: it still errors, and a terminal failure still marks the connection offline.

@rancaHoratiu

Copy link
Copy Markdown

Thanks for #1797, that log line is exactly what I was missing. We are still on 29e848d (which has #1756 but not #1797) and will pick it up with the next release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TikTok: expired access token is never refreshed ("Access token is incorrect or has been revoked" not mapped to AuthException)

2 participants