Cafe24 is the hosted commerce platform many Korean shops run on. A shop owner cannot edit the platform's server code, but the platform has an Admin API, and an installed app can edit a product's description and its search fields through it. This page covers the app's plumbing: getting installed safely, keeping tokens alive when the platform rotates them on every refresh, and writing to a shop without tripping its rate limit or touching what it should not.
Install
The install flow is standard OAuth with two decisions made for safety.
The shop id is validated before it is used as a hostname. Each shop has its own API host, formed from the shop’s id. A request to start an install supplies that id. If it were used as given, a crafted value could make the server issue requests to an arbitrary host. The id is checked against a strict pattern first: lowercase letters, digits and hyphens, bounded in length.
The shop id is trusted only from signed state. The state parameter sent to the platform carries the shop id, the issue time and a nonce, signed with HMAC-SHA256, valid for ten minutes and compared in constant time. On the callback the shop id is read from the verified state, and a shop id in the query string that differs is an error. An attacker cannot finish their own authorisation against someone else’s shop record.
After the callback the app exchanges the code for tokens, stores them encrypted, and creates the site record with its write scope set to off. Installing applies nothing. A shop that has just installed the app has granted permission, and that is a different thing from asking for changes.
When the app is opened from inside the platform’s admin, the platform signs the launch parameters. The app verifies that signature and rejects a launch older than two hours.
Tokens under rotation
The platform’s token rules make refresh the hard part.
| Rule | Consequence |
|---|---|
| An access token lives two hours | Every long job refreshes at least once |
| A refresh token lives two weeks and is replaced on every refresh | The old refresh token dies the moment a new pair is issued |
| Token requests are limited per two hours, and concurrent tokens per shop are limited | Refreshing more often than needed burns a scarce budget |
Rotation creates a race with a severe outcome. Suppose two processes notice at the same moment that the access token is about to expire. Both send the same refresh token. The platform answers the first with a new pair and invalidates the old refresh token. The second request is now presenting a dead token. If the two responses are stored in the wrong order, the database ends up holding a refresh token that no longer works, and the shop has to be reauthorised by its owner.

There are two layers.
Inside one process, concurrent callers share one in-flight refresh promise. Ten requests that all find the token stale produce one refresh.
Across processes, a lock. This is the method, reflowed to fit, with comments translated from Korean.
private async doRefresh(): Promise<TokenSet> {
const key = `cafe24:refresh:${this.credentials.mallId}`;
const before = await this.store.load(this.credentials.mallId);
const handle = await this.lock.acquire(key, REFRESH_LOCK_TTL_MS);
if (handle === null) {
const waited = await this.waitForOthersRefresh(before);
if (waited !== null) return waited;
return this.performRefresh(); // it never changed: the holder died or failed
}
try {
const current = await this.store.load(this.credentials.mallId); // look once more inside the lock
if (current !== null && before !== null && current.accessToken !== before.accessToken) return current;
return await this.performRefresh();
} finally { await this.lock.release(key, handle); }
}
The comment above this method in the source states the idea: the goal is not to get the lock, it is to get a new token. A process that fails to take the lock does not wait and retry the lock. It waits for the stored token to change, polling every 200 milliseconds for up to five seconds, and uses what the holder wrote. Retrying the lock would make it perform a refresh that someone else has already done.
Two more details close the gaps.
- The process that does refresh saves the rotated refresh token before it returns the new access token to its caller. A crash between receiving the pair and saving it would otherwise lose the only copy.
- An
invalid_grantanswer is not retried. It means the refresh token is dead, and the right response is to mark the shop as needing reauthorisation.
The lock
The lock is a row in MongoDB with a unique key, an owner and an expiry. The acquire method, reflowed to fit:
async acquire(key: string, ttlMs: number): Promise<LockHandle | null> {
const owner = randomUUID();
const now = new Date();
const expiresAt = new Date(now.getTime() + ttlMs);
// 1. Take over an expired lock. The expiry condition keeps us from stealing a live one.
const taken = await prisma.geoLock.updateMany({
where: { key, expiresAt: { lt: now } }, data: { owner, expiresAt, acquiredAt: now },
});
if (taken.count > 0) return { owner };
// 2. Otherwise create it. If two create at once, the unique index lets one through.
try {
await prisma.geoLock.create({ data: { key, owner, expiresAt, acquiredAt: now } });
return { owner };
} catch (error) { if (isDuplicateKey(error)) return null; throw error; }
}
Release deletes the row only if the owner matches. Without that condition, a process whose lock had already expired could delete the lock a second process had just taken.
The lock rests entirely on the unique index. If the index is missing, every create succeeds and the lock is silently a no-op. CI therefore runs the lock test against a real MongoDB replica set with the schema pushed, and one of its cases starts twenty acquisitions at once and asserts that exactly one wins.
Where tokens are kept
Tokens live in their own collection, apart from the site records, so that an admin screen that lists whole site documents cannot leak one. They are encrypted with AES-256-GCM under a key derived from an environment secret. There is no plaintext fallback: saving asserts that the value is ciphertext, and a missing or short key throws the first time a token is encrypted or decrypted. One token is enough to edit a client’s shop.
Staying under the rate limit
The platform meters API calls with a leaky bucket and reports the current level in a response header. The client keeps its own model of that bucket.
| Mechanism | Behaviour |
|---|---|
| Local bucket | Capacity 40, draining at 2 per second. A call waits its turn in order before it is sent |
| Header sync | After each response the local level is raised to the server’s reported level if that is higher. It is never lowered from a header |
| 401 | One forced token refresh and one retry |
| 429 or 5xx | Up to four retries, waiting the Retry-After the server gives or an exponential backoff, each capped at 30 seconds |
| Other 4xx | An error, with no retry |
| API version | Pinned in a header on every request |
The local bucket is there because of the arithmetic of a batch. Waiting a fraction of a second before each call is faster overall than sending freely, hitting the limit, and backing off for seconds at a time.
What is read and written
Reads ask for named fields only. The product endpoint returns the shop’s supply price by default, which is the shop’s cost. The client always sends a field list that leaves it out. Not receiving a sensitive value is the only reliable way of not leaking it.
Writes are narrow.
| Target | Rule |
|---|---|
| Product description | A specification table is inserted between a pair of marker comments. Running it again replaces the block between the markers, so the operation is idempotent and removable |
| Image alt text | Added only to images that have none. An existing alt is never overwritten, and values are escaped |
| Summary description | Limited to 255 characters by the platform, counted in code points and checked before the call. Replaces existing copy, so it needs its own grant |
| Search meta fields | Written through the product’s SEO endpoint |
Script tags are deliberately not written. AI crawlers do not run JavaScript, so a script would change nothing they read.
Every write passes a policy gate. Each item in a plan is checked against the site’s write scope. With the scope off, the function makes zero API calls. A dry-run mode returns the method, URL and body of each planned write without sending it, while reads still run.
Pagination has a hard stop. The list endpoint stops at an offset limit, and the client raises an error there instead of returning a truncated list that looks complete.
Uninstall
The platform sends a webhook when the app is deleted or expires. The handler removes the tokens, records the uninstall and sets the write scope to off. It is idempotent. It answers 200 for events it does not handle and 500 when the database fails, because the platform resends on failure and disables a webhook that fails too often.
Tests
| Area | What is asserted |
|---|---|
| Auth | No refresh while valid. Refresh five minutes before expiry. The rotated refresh token is saved. Concurrent refreshes make one token request. A dead refresh token leads to reauthorisation |
| Client | 401 refreshes once. 429 waits for Retry-After. 5xx backs off, then fails. 4xx is not retried. Dry run blocks writes and still reads |
| Throttle | No wait under capacity. Waits at the drain rate. A hundred calls converge on the drain rate. A higher server level is trusted |
| Products | Pagination stops. The offset limit raises. The 255-character check counts code points. Alt text is added only where missing. The field list leaves out sensitive fields |
| Lock | One acquirer. Another’s lock cannot be released. Expired locks can be taken. Twenty at once, one winner |
| Crypto | Round trip, a distinct IV per value, wrong key, tamper detection, a missing or short key refused |
| Install and webhook | State signing and expiry, launch signature and its two-hour limit, wrong or missing webhook key, events from another app rejected |
Failure modes
| What happens | What the system does |
|---|---|
| Two processes refresh at once | One takes the lock and refreshes. The other waits for the stored token to change |
| The lock holder dies | The lock expires after 30 seconds. A waiter gives up after five seconds and refreshes itself |
| The refresh token is dead | No retry. The shop is marked for reauthorisation |
| The API answers 429 | The client waits as told and retries, up to four times |
| A summary is too long | Refused before any call is made |
| The shop’s scope is off | Zero API calls |
| The app is uninstalled | Tokens are deleted and the scope is set to off |
Limits
- Applying from the console is not wired in. The write functions, the policy gate and the dry run are built and tested. The console does not yet call them for an approved page, so a platform apply is still a separate, manual step.
- Revocation has a fast path only. The webhook handles uninstall. A periodic check, and cleanup when a refresh fails for good, are not built.
- The lock’s wait path is covered indirectly. The lock itself is tested against a real database. The branch where a process waits for another’s refresh has no unit test of its own.
- Site-wide settings are out of reach. The app requests product read and write scopes only, so robots rules and head HTML at the shop level are not written.
