# glass14 TikTok token-rotation patch: staging test report (2026-11-02)

Base: `postiz-glass:1.47.0-glass13` (Postiz v1.47.0). Patched image: `postiz-glass:1.47.0-glass14-staging`.
Why: from 2026-12-01 TikTok access tokens last 2 h, refresh tokens 180 d, and each refresh issues a new refresh token that
kills the old one (Nov 2 TikTok email, confirmed by the Engineer).

## What the patch changes (5 files)

| File | Change |
|---|---|
| `integrations/social/tiktok.provider.ts` | `expires_in` from TikTok (7200 fallback) instead of a fixed 23 h; `refreshCron = true`; clear error if the token call returns no access_token; the `/user/info` profile call after a refresh is best effort, so the rotated refresh token is never lost; test hooks `TIKTOK_API_BASE`, `TIKTOK_FORCE_EXPIRES_IN` (default off, remove for upstream) |
| `apps/orchestrator/src/workflows/refresh.token.workflow.ts` | refresh 15 min before expiry (half the remaining lifetime if shorter); a failed refresh ends the loop instead of retrying hot |
| `integrations/refresh.integration.service.ts` | whole refresh runs under a per-channel Postgres advisory lock; the stored row is re-read after the lock is taken and the refresh is skipped if another process already refreshed (stored refresh token differs from the caller's snapshot and is valid for more than 5 minutes); the stored token is always the one sent to TikTok, never the caller's snapshot; the rotated tokens are saved on the lock transaction last, after a best-effort full update, so a later failure cannot lose them; a failed refresh does not flag or disconnect the channel if the row meanwhile holds a newer token |
| `database/prisma/integrations/integration.repository.ts` | `withIntegrationLock()` (interactive transaction + `pg_advisory_xact_lock`, 90 s timeout); `profile` is only overwritten with a non-empty username |
| `database/prisma/integrations/integration.service.ts` | exposes `withIntegrationLock()` |

The lock and re-read apply to every provider's refresh. Other providers are otherwise unchanged.

## Defects found by the audit of v1.47.0 (all confirmed in source)

A. Fixed 23 h expiry in `refreshToken()` and `authenticate()`, so the stored expiry was wrong for a 2 h token.
B. A failed `/user/info` call after the token call threw away the rotated refresh token, and the channel was then flagged `refreshNeeded` and disconnected.
C. No `refreshCron`, so no timed refresh was ever scheduled for TikTok; the workflow slept until the exact expiry.
D. No lock; the post workflow passes a stale snapshot to the refresh, so two refreshes could use the same old refresh token and the loser disconnected the channel.

## Staging stack

Forge, `docker compose` project `ttstage` (`staging/docker-compose.yml`): patched Postiz image, throwaway Postgres 17, Redis 7.2,
Temporal dev server, and `mock_tiktok.py`, a mock TikTok OAuth server with the real rotation rule (a refresh token works once; reuse
returns `invalid_grant`). Fake tokens only. The channel row was seeded in the staging database.

## Results

| # | Test | Expected | Result |
|---|---|---|---|
| 1 | Forced 180 s access-token expiry, timed refresh workflow started the way a backfill would start it | refresh fires before expiry | PASS: 5 refreshes, one every 90 s (half the lifetime) |
| 2 | Old refresh token never reused over those 5 rotations | mock `refresh_reuse_rejected = 0` | PASS: 0 rejected; dead tokens REF-1..REF-5, DB holds REF-6, `refreshNeeded=false` |
| 3 | `/user/info` returns 503 once, mid-run | new refresh token still saved | PASS: refresh 3 to 4 ran with the 503; refresh 4 to 5 used REF-4 and succeeded |
| 4 | Picture re-upload throws ("Unsafe URL") inside the full channel update | new refresh token still saved | PASS: 5 logged "profile update failed, tokens still saved"; DB tokens current. (The first draft of the patch failed this test: it lost REF-2 and left the channel stuck. Fixed before this run.) |
| 5 | 4 workflows wake together on one channel, 900 s expiry | no rejected refresh, no disconnect | PASS: refreshes serialized by the lock, each used the latest token (REF-1 to REF-5), 0 rejected, channel healthy. Each workflow re-read the row after sleeping, so none held a stale snapshot; see test 6 |
| 6 | A caller holding a STALE snapshot (dead token REF-5) while another process has refreshed | skip, return stored tokens, no TikTok call | PASS: returned REF-6, 0 provider calls, 0 rejected |
| 7 | Stale snapshot and the stored token is within 5 min of expiry | refresh with the RE-READ token, not the snapshot | PASS: REF-6 to REF-7, 0 rejected, DB REF-7 |
| 8 | Forced 401 on a real post: a post created through the public API with the mock access token expired on the TikTok side while Postiz still believed it valid | 401, then refresh, then the post succeeds, rotated token saved | PASS: mock logged `publish_401` on `/v2/post/publish/video/init/`, `refresh_ok` REF-1 to REF-2, `publish_ok` with the new access token; post state PUBLISHED with a TikTok URL; DB holds REF-2, `refreshNeeded=false`, 0 reuses rejected. The real `post()` code ran unmodified: a staging-only preload (`staging/redirect_tiktok.js`) sends `open.tiktokapis.com` calls to the mock. (After a restart the first-queued post waited until the orchestrator worker came up, which took a container restart in staging; unrelated to the patch.) |

Eight tests, eight rows. Not tested against real TikTok: no real or sandbox TikTok channel was refreshed in staging. The unpatched image
was not run against the mock (it has no `TIKTOK_API_BASE` hook), so the "before" failures are from reading the source, not from a run.

## Deployed (2026-11-02, approved by David)

- 18:34 UTC: KVM2 `/opt/postiz/docker-compose.yaml` now uses `postiz-glass:1.47.0-glass14` (same bytes as the staging image, id `40591846dae5`, shipped from Forge with `docker save | gzip | ssh ... docker load`). `postiz-glass:1.47.0-glass13` (id `29f8eeacf800`) stays on KVM2 and stays tagged.
- Before the swap: compose backup `/opt/postiz/docker-compose.yaml.bak-20261102-183500-glass14`; Integration table dump `/root/backups/Integration-pre-glass14-20261102T1835Z.sql` (root only, mode 600, contains tokens: delete after the 48 h watch).
- Boot took about 70 s (backend and orchestrator). Verified from outside: `https://glass.unrivaledmarketingsolutions.com/` 200 after redirects; public API answers 401 to a bad key. The orchestrator re-registered as a poller on the `main` task queue; the 18 running workflows (11 queued posts and others) carried over. The next queued post is Nov 3 15:00 UTC.
- Backfill: only providers with `refreshCron` get a timed refresh workflow. In this image that is TikTok (new with glass14) and Instagram standalone (already has its workflow). The one TikTok channel (Local Theory) got `refresh_cmsufkds10001pk8rj770knmq` at 18:36:55 UTC. YouTube, Facebook, Bluesky and the rest do not use `refreshCron` and keep refreshing on 401 (now under the lock).
- Real TikTok accepted the refresh of the Local Theory channel (its access token had expired Aug 30): access token changed, expiry now +24 h (TikTok's current lifetime until Dec 1), `refreshNeeded=false`. The refresh token fingerprint did not change: TikTok returns the same refresh token until rotation starts, so the save of a rotated token cannot be confirmed against real TikTok before Dec 1.
- Reauth alert: `glass-tiktok-reauth-watch.timer` (Forge user timer, minutes :22 and :52) enabled 18:37 UTC; first run found nothing to file.
- Watch: `~/chief-of-staff/glass_tiktok_verify.py` prints fingerprints, expiry, flags and the refresh workflow, and compares with the previous run.

## Rollback

glass13 is still on KVM2. To go back (about 2 minutes plus 70 s to boot):

```
ssh kvm2 'cd /opt/postiz && cp docker-compose.yaml.bak-20261102-183500-glass14 docker-compose.yaml && docker compose up -d postiz'
ssh kvm2 'docker exec temporal-admin-tools temporal workflow terminate --address temporal:7233 --workflow-id refresh_cmsufkds10001pk8rj770knmq'
```

The second line stops the timed TikTok refresh, which glass13 does not know how to run. Tokens already saved in the database stay valid for glass13. The pre-deploy Integration dump is only for a bad-data case; do not restore it over newer tokens after Dec 1 (it would bring back refresh tokens TikTok has already invalidated).

## Open after Dec 1

Rotation itself (a different refresh token coming back) can only be seen once TikTok's change takes effect. Re-verify live on Dec 1 to 2 with `glass_tiktok_verify.py`: the refresh token fingerprint should CHANGE at each refresh and the channel must stay unflagged.
