webcake-storefront-mcp 1.39.0 → 1.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api.js CHANGED
@@ -10,6 +10,16 @@ const parseMaybe = (v) => (typeof v === "string" ? (v ? JSON.parse(v) : null) :
10
10
  const globalsOf = (src) => (src?.sections || []).filter((s) => s && s.specials && s.specials.global);
11
11
  /** Key-order-independent JSON, so a re-serialised but equal node doesn't count as an edit. */
12
12
  const canon = (v) => JSON.stringify(v ?? null, (_k, x) => (x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => (a < b ? -1 : 1))) : x));
13
+ /** True when `token` is a JWT whose `exp` is past (with `skewSec` margin). Non-JWTs never count as expired. */
14
+ export function jwtExpired(token, skewSec = 30) {
15
+ try {
16
+ const exp = JSON.parse(Buffer.from(String(token).split(".")[1], "base64url").toString()).exp;
17
+ return typeof exp === "number" && exp * 1000 < Date.now() + skewSec * 1000;
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ }
13
23
  export class WebcakeCmsApi {
14
24
  /** Parse (if string) and guarantee settings.breakpoints is a usable object — an empty/missing
15
25
  * breakpoints would make the backend compile CSS without media queries. */
@@ -37,6 +47,18 @@ export class WebcakeCmsApi {
37
47
  _adminToken;
38
48
  _cmsApiKey;
39
49
  _siteBps = null; // cached site.settings (breakpoints, defaultGrid)
50
+ /** Called when the session JWT is expired or the backend rejects it. Stdio: reopens the browser
51
+ * Connect page and returns the new credentials (request is retried once). Remote: marks it dead. */
52
+ onAuthExpired;
53
+ async renewAuth() {
54
+ const fresh = this.onAuthExpired ? await this.onAuthExpired(this.token) : null;
55
+ if (!fresh?.token)
56
+ return false;
57
+ this.switchToken(fresh.token);
58
+ if (fresh.sessionId)
59
+ this.switchSession(fresh.sessionId);
60
+ return true;
61
+ }
40
62
  constructor({ baseUrl, token, siteId, sessionId }) {
41
63
  this.baseUrl = (baseUrl || "").replace(/\/$/, "");
42
64
  this.token = token;
@@ -60,7 +82,12 @@ export class WebcakeCmsApi {
60
82
  getBundleParams() {
61
83
  return { token: this._adminToken, x_cms_api_key: this._cmsApiKey };
62
84
  }
63
- async request(method, path, { body, query, timeout, headers: extraHeaders } = {}) {
85
+ async request(method, path, opts = {}, retried = false) {
86
+ const { body, query, timeout, headers: extraHeaders } = opts;
87
+ // Calls that bring their own Bearer (CMS admin token) can't be fixed by a new login.
88
+ const ownAuth = !extraHeaders?.Authorization;
89
+ if (ownAuth && !retried && jwtExpired(this.token) && (await this.renewAuth()))
90
+ return this.request(method, path, opts, true);
64
91
  const url = new URL(`${this.baseUrl}${path}`);
65
92
  if (query) {
66
93
  for (const [k, v] of Object.entries(query)) {
@@ -77,7 +104,7 @@ export class WebcakeCmsApi {
77
104
  const controller = new AbortController();
78
105
  const timer = setTimeout(() => controller.abort(), timeout || DEFAULT_TIMEOUT);
79
106
  let res;
80
- let json;
107
+ let raw;
81
108
  try {
82
109
  res = await fetch(url, {
83
110
  method,
@@ -86,16 +113,25 @@ export class WebcakeCmsApi {
86
113
  signal: controller.signal,
87
114
  });
88
115
  // Read the body under the same timer — clearing it after the headers left a stalled body unbounded.
89
- json = await res.json().catch((e) => {
90
- if (controller.signal.aborted)
91
- throw e; // timed out mid-body: an error, not an empty success
92
- return null;
93
- });
116
+ raw = await res.text();
94
117
  }
95
118
  finally {
96
119
  clearTimeout(timer);
97
120
  }
121
+ let json = null;
122
+ try {
123
+ json = raw ? JSON.parse(raw) : null;
124
+ }
125
+ catch {
126
+ /* non-JSON body (e.g. plain "Unauthorized") */
127
+ }
98
128
  if (!res.ok) {
129
+ // AuthPlug answers a bad/expired session with a plain-text 401 "Unauthorized".
130
+ if (res.status === 401 && ownAuth && (jwtExpired(this.token) || raw.trim() === "Unauthorized")) {
131
+ if (!retried && (await this.renewAuth()))
132
+ return this.request(method, path, opts, true);
133
+ throw new Error("API 401: phiên đăng nhập WebCake đã hết hạn (token expired). Bấm Kết nối (Connect) lại để gia hạn — stdio: chạy `npx -y webcake-storefront-mcp login`.");
134
+ }
99
135
  const msg = (json && json.message) || (json && json.error) || res.statusText;
100
136
  throw new Error(`API ${res.status}: ${msg}`);
101
137
  }
@@ -5,7 +5,10 @@ import { createServer } from "node:http";
5
5
  import { randomBytes } from "node:crypto";
6
6
  import { spawn, execFile } from "node:child_process";
7
7
  import { DEFAULT_ENV, resolveSettings } from "../config.js";
8
- import { setConfig } from "../db.js";
8
+ import { closeSync, openSync, statSync, unlinkSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { CONFIG_DIR, getConfig, reloadConfig, setConfig } from "../db.js";
11
+ import { jwtExpired } from "../api.js";
9
12
  function parseArgs(argv) {
10
13
  const opts = { open: true };
11
14
  for (let i = 0; i < argv.length; i++) {
@@ -196,3 +199,85 @@ export async function runLogin(argv) {
196
199
  }, 180_000).unref();
197
200
  });
198
201
  }
202
+ // One browser Connect at a time — across every stdio process on this machine (several IDE
203
+ // windows share ~/.webcake-storefront-mcp): the first takes a lock file and opens the
204
+ // browser, the others wait for the token it saves. After a failed/abandoned Connect, wait
205
+ // before reopening so a looping agent doesn't spam tabs.
206
+ const LOCK = join(CONFIG_DIR, "renew.lock");
207
+ const LOGIN_WAIT_MS = 185_000; // runLogin times out at 180s
208
+ let renewing = null;
209
+ let lastFail = 0;
210
+ /** A token in the config file newer than `stale` and not expired (another process renewed it). */
211
+ function savedFresh(stale) {
212
+ reloadConfig();
213
+ const token = getConfig("token") || "";
214
+ return token && token !== stale && !jwtExpired(token) ? { token, sessionId: getConfig("session_id") || "" } : null;
215
+ }
216
+ function takeLock() {
217
+ try {
218
+ closeSync(openSync(LOCK, "wx"));
219
+ return true;
220
+ }
221
+ catch {
222
+ try {
223
+ if (Date.now() - statSync(LOCK).mtimeMs > LOGIN_WAIT_MS) {
224
+ unlinkSync(LOCK); // left behind by a crashed process
225
+ return takeLock();
226
+ }
227
+ }
228
+ catch { /* raced with its owner releasing it */ }
229
+ return false;
230
+ }
231
+ }
232
+ async function renew(stale) {
233
+ const done = savedFresh(stale);
234
+ if (done)
235
+ return done;
236
+ if (!takeLock()) {
237
+ // Someone else has the browser open — wait for the token they save.
238
+ for (const until = Date.now() + LOGIN_WAIT_MS; Date.now() < until;) {
239
+ await new Promise((r) => setTimeout(r, 1000));
240
+ const t = savedFresh(stale);
241
+ if (t)
242
+ return t;
243
+ try {
244
+ statSync(LOCK);
245
+ }
246
+ catch {
247
+ return savedFresh(stale);
248
+ } // released without a token
249
+ }
250
+ return null;
251
+ }
252
+ try {
253
+ console.error("[webcake-storefront] Token hết hạn — mở trình duyệt để Kết nối lại…");
254
+ await runLogin([]);
255
+ return { token: getConfig("token") || "", sessionId: getConfig("session_id") || "" };
256
+ }
257
+ finally {
258
+ try {
259
+ unlinkSync(LOCK);
260
+ }
261
+ catch { /* already gone */ }
262
+ }
263
+ }
264
+ /** Token expired mid-session (stdio): reopen the Connect page and hand back the new credentials. */
265
+ export function renewInBrowser(staleToken = "") {
266
+ if (!renewing && Date.now() - lastFail > 120_000) {
267
+ renewing = renew(staleToken)
268
+ .then((r) => {
269
+ if (!r)
270
+ lastFail = Date.now();
271
+ return r;
272
+ })
273
+ .catch((e) => {
274
+ lastFail = Date.now();
275
+ console.error("[webcake-storefront] gia hạn token thất bại:", e?.message || e);
276
+ return null;
277
+ })
278
+ .finally(() => {
279
+ renewing = null;
280
+ });
281
+ }
282
+ return renewing ?? Promise.resolve(null);
283
+ }
@@ -22,6 +22,7 @@
22
22
  * All exported function names and signatures are IDENTICAL to the previous version
23
23
  * so http.ts requires no changes.
24
24
  */
25
+ import { jwtExpired } from "../api.js";
25
26
  import { randomBytes, createHash } from "node:crypto";
26
27
  import { getPg, ensureOAuthSchema } from "../persistence/postgres.js";
27
28
  import { getRedis } from "../persistence/redis.js";
@@ -97,6 +98,18 @@ class MemoryStore {
97
98
  return r && r.expiresAt >= now() ? r : undefined;
98
99
  }
99
100
  async revoke(t) { this.access.delete(t); this.refresh.delete(t); }
101
+ async revokeJwt(jwt) {
102
+ const dropped = [];
103
+ for (const [k, v] of this.access)
104
+ if (v.cred.jwt === jwt) {
105
+ this.access.delete(k);
106
+ dropped.push(k);
107
+ }
108
+ for (const [k, v] of this.refresh)
109
+ if (v.cred.jwt === jwt)
110
+ this.refresh.delete(k);
111
+ return dropped;
112
+ }
100
113
  }
101
114
  // ---- Postgres store (when DATABASE_URL is set) -----------------------------
102
115
  class PgStore {
@@ -199,6 +212,12 @@ class PgStore {
199
212
  await this.pool.query(`DELETE FROM oauth_access_tokens WHERE token=$1`, [t]);
200
213
  await this.pool.query(`DELETE FROM oauth_refresh_tokens WHERE token=$1`, [t]);
201
214
  }
215
+ // ponytail: no index on jwt — a seq scan, but this only runs when a JWT dies.
216
+ async revokeJwt(jwt) {
217
+ const { rows } = await this.pool.query(`DELETE FROM oauth_access_tokens WHERE jwt=$1 RETURNING token`, [jwt]);
218
+ await this.pool.query(`DELETE FROM oauth_refresh_tokens WHERE jwt=$1`, [jwt]);
219
+ return rows.map((r) => r.token);
220
+ }
202
221
  }
203
222
  // ---- Backend selection (memoized) ------------------------------------------
204
223
  const memoryStore = new MemoryStore();
@@ -332,6 +351,77 @@ export async function completeAuthorize(internalState, jwt, wsid) {
332
351
  });
333
352
  return { ok: true, redirectUri: p.redirect_uri, code, state: p.state };
334
353
  }
354
+ // ---- Dead WebCake sessions ---------------------------------------------------
355
+ // The OAuth tokens outlive the WebCake JWT they wrap. Once that JWT is expired (or the
356
+ // backend rejected it), refreshing would just re-issue the dead JWT; refusing it makes the
357
+ // client restart the full flow, i.e. open the Connect page again.
358
+ // Shared across instances: markJwtDead revokes every OAuth token wrapping the JWT in the
359
+ // store (Postgres = source of truth) and flags it in Redis for raw ?token= callers.
360
+ // Only a sha256 of the JWT is kept, never the token itself.
361
+ const DEAD_PREFIX = "wc:sf:deadjwt:";
362
+ const DEAD_MAX_TTL = 30 * 24 * 60 * 60 * 1000;
363
+ const deadLocal = new Map(); // hash → expiresAt (ms)
364
+ const jwtHash = (jwt) => createHash("sha256").update(jwt).digest("hex");
365
+ function deadTtl(jwt) {
366
+ try {
367
+ const exp = JSON.parse(Buffer.from(jwt.split(".")[1], "base64url").toString()).exp;
368
+ if (typeof exp === "number")
369
+ return Math.min(Math.max(exp * 1000 - now(), 60_000), DEAD_MAX_TTL);
370
+ }
371
+ catch { /* opaque token */ }
372
+ return DEAD_MAX_TTL;
373
+ }
374
+ function rememberDeadLocally(hash, ttl) {
375
+ if (deadLocal.size > 10_000)
376
+ for (const [k, exp] of deadLocal)
377
+ if (exp < now())
378
+ deadLocal.delete(k);
379
+ if (deadLocal.size > 10_000)
380
+ deadLocal.delete(deadLocal.keys().next().value); // still full: drop oldest
381
+ deadLocal.set(hash, now() + ttl);
382
+ }
383
+ /** Expired, or already marked dead here — no I/O. */
384
+ function isDeadLocally(jwt) {
385
+ if (jwtExpired(jwt))
386
+ return true;
387
+ const exp = deadLocal.get(jwtHash(jwt));
388
+ return exp !== undefined && exp >= now();
389
+ }
390
+ /** The backend rejected this JWT: make every instance treat it as dead. Never throws. */
391
+ export async function markJwtDead(jwt) {
392
+ if (!jwt)
393
+ return;
394
+ const hash = jwtHash(jwt);
395
+ const ttl = deadTtl(jwt);
396
+ rememberDeadLocally(hash, ttl);
397
+ const redis = getRedis();
398
+ try {
399
+ if (redis)
400
+ await redis.set(DEAD_PREFIX + hash, "1", "PX", ttl);
401
+ const dropped = await (await getStore()).revokeJwt(jwt);
402
+ if (redis)
403
+ for (const t of dropped)
404
+ redisCacheDel(redis, t);
405
+ }
406
+ catch (e) {
407
+ console.error("[oauth] markJwtDead:", e?.message ?? e);
408
+ }
409
+ }
410
+ /** True when the JWT is expired or any instance marked it dead. */
411
+ export async function isDeadJwt(jwt) {
412
+ if (!jwt)
413
+ return false;
414
+ if (isDeadLocally(jwt))
415
+ return true;
416
+ const redis = getRedis();
417
+ if (!redis)
418
+ return false;
419
+ const hash = jwtHash(jwt);
420
+ const hit = await redis.get(DEAD_PREFIX + hash).catch(() => null);
421
+ if (hit)
422
+ rememberDeadLocally(hash, deadTtl(jwt));
423
+ return !!hit;
424
+ }
335
425
  async function issueTokens(store, cred, client_id, scope) {
336
426
  const access = token(32);
337
427
  const refresh = token(32);
@@ -366,6 +456,9 @@ export async function exchangeToken(p) {
366
456
  if (!r) {
367
457
  return { ok: false, status: 400, error: "invalid_grant", error_description: "Unknown or expired refresh token." };
368
458
  }
459
+ if (await isDeadJwt(r.cred.jwt)) {
460
+ return { ok: false, status: 400, error: "invalid_grant", error_description: "WebCake session expired — sign in again (Connect)." };
461
+ }
369
462
  return { ok: true, body: await issueTokens(store, r.cred, r.client_id, r.scope) };
370
463
  }
371
464
  return { ok: false, status: 400, error: "unsupported_grant_type", error_description: "grant_type must be authorization_code or refresh_token." };
@@ -386,11 +479,11 @@ export async function resolveAccessToken(accessToken) {
386
479
  if (redis) {
387
480
  const cached = await redisCacheGet(redis, accessToken);
388
481
  if (cached)
389
- return cached;
482
+ return isDeadLocally(cached.jwt) ? undefined : cached;
390
483
  }
391
484
  // 2. Fall through to the store (Postgres or memory).
392
485
  const a = await (await getStore()).getAccess(accessToken);
393
- if (!a)
486
+ if (!a || isDeadLocally(a.cred.jwt))
394
487
  return undefined;
395
488
  // Backfill the Redis cache for next time.
396
489
  if (redis)
@@ -1,4 +1,18 @@
1
1
  [
2
+ {
3
+ "v": "1.41.0",
4
+ "d": "19/11/2026",
5
+ "type": "Changed",
6
+ "en": "When a session token expires in stdio mode, multiple IDE windows/processes on the same machine now coordinate through a shared lock so only one…",
7
+ "vi": "Khi token phiên hết hạn ở chế độ stdio, nhiều cửa sổ/process IDE trên cùng một máy nay phối hợp qua một khóa dùng chung để chỉ một process mở trang…"
8
+ },
9
+ {
10
+ "v": "1.40.0",
11
+ "d": "19/11/2026",
12
+ "type": "Added",
13
+ "en": "The stdio server now reopens the browser Connect page automatically when the session token expires or the backend rejects it with a 401, then…",
14
+ "vi": "Server stdio nay tự mở lại trang Connect trên trình duyệt khi token phiên hết hạn hoặc bị backend từ chối với lỗi 401, rồi tự chạy lại lệnh gọi tool…"
15
+ },
2
16
  {
3
17
  "v": "1.39.0",
4
18
  "d": "13/11/2026",
@@ -26,19 +40,5 @@
26
40
  "type": "Fixed",
27
41
  "en": "publish_site, create_global_section, delete_global_section, update_site_custom_code, and append_site_custom_code now fail with a clear error instead…",
28
42
  "vi": "publish_site, create_global_section, delete_global_section, update_site_custom_code và append_site_custom_code nay báo lỗi rõ ràng thay vì âm thầm…"
29
- },
30
- {
31
- "v": "1.36.1",
32
- "d": "27/10/2026",
33
- "type": "Changed",
34
- "en": "get_build_guide and the ingest_html tool description now state that embed is a last resort: build everything native elements can with new_section,…",
35
- "vi": "get_build_guide và mô tả tool ingest_html nay nêu rõ embed chỉ là phương án cuối: dựng native mọi thứ có thể bằng new_section, chỉ dùng embed cho…"
36
- },
37
- {
38
- "v": "1.36.0",
39
- "d": "22/10/2026",
40
- "type": "Added",
41
- "en": "New invoke_read_tool runs any read-only on-demand tool (list_*/get_*/search_*, i.e. tools with readOnlyHint) by name through the gateway, so clients…",
42
- "vi": "Tool mới invoke_read_tool chạy bất kỳ tool chỉ-đọc nào (list_*/get_*/search_*, tức tool có readOnlyHint) qua gateway theo tên, nhờ đó client nào bắt…"
43
43
  }
44
44
  ]
package/dist/config.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Central resolution of connection settings for every entry path (stdio, install,
2
2
  // login, remote HTTP). Precedence: explicit overrides > environment variables >
3
3
  // saved config in the local config file.
4
- import { WebcakeCmsApi } from "./api.js";
4
+ import { WebcakeCmsApi, jwtExpired } from "./api.js";
5
5
  import { getSavedConfig } from "./tools/context.js";
6
6
  // Per-environment endpoints so you can switch with `--env <name>` / WEBCAKE_ENV
7
7
  // instead of setting WEBCAKE_API_URL / WEBCAKE_APP_URL by hand. Default is prod.
@@ -87,9 +87,12 @@ export function resolveSettings(overrides = {}) {
87
87
  process.env.WEBCAKE_APP_URL ||
88
88
  preset?.appUrl ||
89
89
  ENVIRONMENTS[DEFAULT_ENV].appUrl;
90
- const token = overrides.token || process.env.WEBCAKE_TOKEN || saved.token || "";
90
+ // An expired env token (pinned in the IDE config) loses to a fresher one saved by a re-login.
91
+ const envToken = process.env.WEBCAKE_TOKEN;
92
+ const renewed = !!envToken && jwtExpired(envToken) && !!saved.token && !jwtExpired(saved.token);
93
+ const token = overrides.token || (renewed ? saved.token : envToken) || saved.token || "";
91
94
  const siteId = overrides.siteId || process.env.WEBCAKE_SITE_ID || saved.site_id || "";
92
- const sessionId = overrides.sessionId || process.env.WEBCAKE_SESSION_ID || saved.session_id || "";
95
+ const sessionId = overrides.sessionId || (renewed ? saved.session_id : process.env.WEBCAKE_SESSION_ID) || saved.session_id || "";
93
96
  return { apiUrl, appUrl, token, siteId, sessionId, env: envName };
94
97
  }
95
98
  /** Build a WebcakeCmsApi client from resolved settings. */
package/dist/db.js CHANGED
@@ -5,10 +5,11 @@
5
5
  // container restarts. A flat JSON file instead of SQLite — keeps the package light
6
6
  // and works in any runtime (Alpine, Docker `--ignore-scripts`, serverless) with no
7
7
  // native binding to build. The API is synchronous to match the call sites.
8
+ import { AsyncLocalStorage } from "node:async_hooks";
8
9
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
10
  import { homedir } from "node:os";
10
11
  import { join } from "node:path";
11
- const CONFIG_DIR = process.env.WEBCAKE_CONFIG_DIR || join(homedir(), ".webcake-storefront-mcp");
12
+ export const CONFIG_DIR = process.env.WEBCAKE_CONFIG_DIR || join(homedir(), ".webcake-storefront-mcp");
12
13
  mkdirSync(CONFIG_DIR, { recursive: true });
13
14
  const CONFIG_FILE = join(CONFIG_DIR, "config.json");
14
15
  function readJson(file, fallback) {
@@ -29,19 +30,44 @@ function writeJson(file, data) {
29
30
  }
30
31
  // ── Config (key/value) ───────────────────────────────────────────────────────
31
32
  const config = readJson(CONFIG_FILE, {});
33
+ const scopeStore = new AsyncLocalStorage();
34
+ export function runWithConfigScope(scope, fn) {
35
+ return scopeStore.run(scope, fn);
36
+ }
32
37
  export function getConfig(key) {
33
- return key in config ? config[key] : null;
38
+ const values = scopeStore.getStore()?.values ?? config;
39
+ return key in values ? values[key] : null;
34
40
  }
35
41
  export function setConfig(key, value) {
42
+ const scope = scopeStore.getStore();
43
+ if (scope) {
44
+ scope.values[key] = String(value);
45
+ scope.persist?.(key, String(value));
46
+ return;
47
+ }
36
48
  config[key] = String(value);
37
49
  writeJson(CONFIG_FILE, config);
38
50
  }
39
51
  export function delConfig(key) {
52
+ const scope = scopeStore.getStore();
53
+ if (scope) {
54
+ delete scope.values[key];
55
+ scope.persist?.(key, null);
56
+ return;
57
+ }
40
58
  delete config[key];
41
59
  writeJson(CONFIG_FILE, config);
42
60
  }
43
61
  export function getAllConfig() {
44
- return { ...config };
62
+ return { ...(scopeStore.getStore()?.values ?? config) };
63
+ }
64
+ /** Re-read the config file — another process (a second IDE window) may have renewed the token. */
65
+ export function reloadConfig() {
66
+ const fresh = readJson(CONFIG_FILE, {});
67
+ for (const k of Object.keys(config))
68
+ if (!(k in fresh))
69
+ delete config[k];
70
+ Object.assign(config, fresh);
45
71
  }
46
72
  // ── Image upload cache (source URL/path → WebCake CDN URL, per site) ──────────
47
73
  // Re-hosting the same stock photo / external image twice wastes an upload, so we
package/dist/http.js CHANGED
@@ -10,10 +10,12 @@ import { randomUUID } from "node:crypto";
10
10
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
11
11
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
12
12
  import { createServer } from "./server.js";
13
+ import { runWithConfigScope } from "./db.js";
14
+ import { accountOf, loadPrefs, savePref } from "./persistence/prefs.js";
13
15
  import { makeApi, resolveEnv, ENVIRONMENTS, DEFAULT_ENV } from "./config.js";
14
16
  import { landingHtml, faviconSvg, ogImageSvg, normalizeLang, ICON_PNG } from "./web-guide.js";
15
17
  import { privacyHtml, termsHtml } from "./legal.js";
16
- import { registerClient, startAuthorize, completeAuthorize, exchangeToken, resolveAccessToken, revokeToken, authServerMetadata, protectedResourceMetadata, } from "./auth/oauth-server.js";
18
+ import { registerClient, startAuthorize, completeAuthorize, exchangeToken, resolveAccessToken, revokeToken, isDeadJwt, markJwtDead, authServerMetadata, protectedResourceMetadata, } from "./auth/oauth-server.js";
17
19
  const MCP_PATH = "/mcp";
18
20
  // OAuth 2.1 endpoints.
19
21
  const WELL_KNOWN_PR = "/.well-known/oauth-protected-resource";
@@ -42,6 +44,10 @@ function header(req, name) {
42
44
  const v = req.headers[name];
43
45
  return Array.isArray(v) ? v[0] : v;
44
46
  }
47
+ function setHeader(req, name, value) {
48
+ req.headers[name] = value;
49
+ req.rawHeaders.push(name, value);
50
+ }
45
51
  /** Copy recognised query params onto request headers so downstream reads are uniform. */
46
52
  function applyQueryAuth(req) {
47
53
  const q = (req.url ?? "").indexOf("?");
@@ -287,7 +293,7 @@ async function handleOAuth(req, res, path) {
287
293
  return false;
288
294
  }
289
295
  export async function startHttpServer(port) {
290
- const transports = new Map();
296
+ const sessions = new Map();
291
297
  const httpServer = createHttpServer(async (req, res) => {
292
298
  const path = (req.url ?? "").split("?")[0];
293
299
  // ---- Favicon / brand icon ----
@@ -346,62 +352,103 @@ export async function startHttpServer(port) {
346
352
  // ---- /mcp handling ----
347
353
  // Accept credentials via query params for clients that can't set headers.
348
354
  applyQueryAuth(req);
349
- // Resolve an OAuth Bearer access token to { jwt, wsid } and inject both headers
350
- // so apiFromRequest picks them up — existing header/query paths remain untouched.
355
+ // Resolve an OAuth Bearer access token to { jwt, wsid }. It WINS over a ?token= /
356
+ // x-webcake-jwt pair: a Bearer from our OAuth flow is what the last Connect issued, so
357
+ // it's the renewed credential when the URL still carries an old, expired one.
351
358
  const bearer = bearerFrom(req);
352
359
  const oauthCred = await resolveAccessToken(bearer);
353
360
  if (oauthCred) {
354
- if (req.headers["x-webcake-jwt"] == null) {
355
- req.headers["x-webcake-jwt"] = oauthCred.jwt;
356
- req.rawHeaders.push("x-webcake-jwt", oauthCred.jwt);
357
- }
358
- if (oauthCred.wsid && req.headers["x-webcake-session-id"] == null) {
359
- req.headers["x-webcake-session-id"] = oauthCred.wsid;
360
- req.rawHeaders.push("x-webcake-session-id", oauthCred.wsid);
361
- }
361
+ setHeader(req, "x-webcake-jwt", oauthCred.jwt);
362
+ if (oauthCred.wsid)
363
+ setHeader(req, "x-webcake-session-id", oauthCred.wsid);
364
+ }
365
+ const sidHeader = header(req, "mcp-session-id");
366
+ const jwt = header(req, "x-webcake-jwt");
367
+ const session = sidHeader ? sessions.get(sidHeader) : undefined;
368
+ // Unknown session (server restarted, or the request landed on another instance): the
369
+ // spec says 404 so the client silently re-initializes — a 400 leaves it stuck.
370
+ if (sidHeader && !session) {
371
+ rpcError(res, 404, "Session not found (expired or server restarted) — send a new initialize request.");
372
+ return;
373
+ }
374
+ // An open session picks up a renewed credential in place (no re-initialize needed).
375
+ if (session && jwt && jwt !== session.api.token && !(await isDeadJwt(jwt))) {
376
+ session.api.switchToken(jwt);
377
+ const wsid = header(req, "x-webcake-session-id");
378
+ if (wsid)
379
+ session.api.switchSession(wsid);
362
380
  }
363
- // Enforce OAuth when enabled: a request with no recognised credential gets 401.
364
- if (OAUTH_ENFORCED && !oauthCred && req.headers["x-webcake-jwt"] == null) {
381
+ // Enforce OAuth when enabled: no credential, or an expired/rejected WebCake token, gets
382
+ // 401 + WWW-Authenticate so the client (re)opens the Connect page by itself.
383
+ const dead = await isDeadJwt(session ? session.api.token : jwt);
384
+ if (OAUTH_ENFORCED && (jwt == null || dead)) {
365
385
  res.writeHead(401, {
366
- "www-authenticate": `Bearer resource_metadata="${publicBase(req)}${WELL_KNOWN_PR}"`,
386
+ "www-authenticate": `Bearer error="invalid_token", resource_metadata="${publicBase(req)}${WELL_KNOWN_PR}"`,
367
387
  "content-type": "application/json",
368
388
  });
369
- res.end(JSON.stringify({ error: "invalid_token", error_description: "Authentication required — connect via OAuth." }));
389
+ const why = dead ? "WebCake session expired — reconnect (Connect) to renew it." : "Authentication required — connect via OAuth.";
390
+ res.end(JSON.stringify({ error: "invalid_token", error_description: why }));
370
391
  return;
371
392
  }
372
- const sidHeader = header(req, "mcp-session-id");
373
393
  try {
374
- // Reuse an existing session.
375
- if (sidHeader && transports.has(sidHeader)) {
376
- const transport = transports.get(sidHeader);
394
+ if (session) {
377
395
  const body = req.method === "POST" ? await readBody(req) : undefined;
378
- await transport.handleRequest(req, res, body);
396
+ await runWithConfigScope(session.scope, () => session.transport.handleRequest(req, res, body));
379
397
  return;
380
398
  }
381
399
  // New session: must be an initialize POST.
382
400
  if (req.method === "POST") {
383
401
  const body = await readBody(req);
384
- if (!sidHeader && isInitializeRequest(body)) {
385
- const transport = new StreamableHTTPServerTransport({
386
- sessionIdGenerator: () => randomUUID(),
387
- onsessioninitialized: (id) => {
388
- transports.set(id, transport);
402
+ if (isInitializeRequest(body)) {
403
+ // This session's config = its account's saved choices (site, confirm mode), shared
404
+ // by every instance; never the server's own config file.
405
+ const account = accountOf(jwt);
406
+ let api;
407
+ // Writes go to account_id only after /@me accepted the token (AuthPlug checks the
408
+ // signature), so a forged JWT can't write into someone else's preferences.
409
+ let verified;
410
+ const scope = {
411
+ values: account ? await loadPrefs(account) : {},
412
+ persist: (key, value) => {
413
+ const a = api;
414
+ if (!account || !a)
415
+ return;
416
+ if (verified?.token !== a.token) {
417
+ const t = a.token;
418
+ verified = { token: t, ok: a.getMe().then(() => accountOf(t) === account, () => false) };
419
+ }
420
+ void verified.ok.then((ok) => ok && savePref(account, key, value));
389
421
  },
390
- });
391
- transport.onclose = () => {
392
- if (transport.sessionId)
393
- transports.delete(transport.sessionId);
394
422
  };
395
- const api = apiFromRequest(req);
396
- const server = createServer(api, { allowLocalFiles: false, tools: header(req, "x-webcake-tools") }); // remote: never read server-side files
397
- await server.connect(transport);
398
- await transport.handleRequest(req, res, body);
423
+ await runWithConfigScope(scope, async () => {
424
+ const transport = new StreamableHTTPServerTransport({
425
+ sessionIdGenerator: () => randomUUID(),
426
+ onsessioninitialized: (id) => {
427
+ sessions.set(id, { transport, api: api, scope });
428
+ },
429
+ });
430
+ transport.onclose = () => {
431
+ if (transport.sessionId)
432
+ sessions.delete(transport.sessionId);
433
+ };
434
+ const sessionApi = apiFromRequest(req);
435
+ api = sessionApi;
436
+ // Backend rejected the token → mark it dead on every instance, so the next
437
+ // request 401s into Connect.
438
+ sessionApi.onAuthExpired = async () => {
439
+ await markJwtDead(sessionApi.token);
440
+ return null;
441
+ };
442
+ const server = createServer(sessionApi, { allowLocalFiles: false, tools: header(req, "x-webcake-tools") }); // remote: never read server-side files
443
+ await server.connect(transport);
444
+ await transport.handleRequest(req, res, body);
445
+ });
399
446
  return;
400
447
  }
401
448
  rpcError(res, 400, "Bad Request: send an initialize request first (no valid mcp-session-id).");
402
449
  return;
403
450
  }
404
- rpcError(res, 400, "Bad Request: missing or unknown mcp-session-id.");
451
+ rpcError(res, 400, "Bad Request: missing mcp-session-id.");
405
452
  }
406
453
  catch (e) {
407
454
  const msg = e instanceof Error ? e.message : String(e);
package/dist/index.js CHANGED
@@ -58,6 +58,8 @@ async function main() {
58
58
  // no env is required to start — auth (token + session) is set via env or `login`,
59
59
  // and the site is chosen at runtime with switch_site.
60
60
  const api = makeApi();
61
+ const { renewInBrowser } = await import("./auth/login.js");
62
+ api.onAuthExpired = renewInBrowser; // expired token → reopen Connect, then retry the call
61
63
  const server = createServer(api, { allowLocalFiles: true }); // stdio = user's own machine
62
64
  const transport = new StdioServerTransport();
63
65
  await server.connect(transport);
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Per-ACCOUNT preferences for the remote server (the saved site, confirm mode). In stdio
3
+ * these live in the local config file; on a shared server that file would be shared by
4
+ * every user, so remote sessions keep them here instead, keyed by the JWT's account_id.
5
+ * Postgres (durable, shared by every instance) → Redis → process memory.
6
+ *
7
+ * Only an allowlist is stored — never tokens or session ids.
8
+ */
9
+ import { getPg } from "./postgres.js";
10
+ import { getRedis } from "./redis.js";
11
+ const KEYS = new Set(["site_id", "site_name", "site_domain", "confirm_mode"]);
12
+ const REDIS_PREFIX = "wc:sf:prefs:";
13
+ const mem = new Map();
14
+ let tableReady;
15
+ function ensureTable() {
16
+ const pool = getPg();
17
+ if (!pool)
18
+ return Promise.resolve(false);
19
+ tableReady ??= pool
20
+ .query(`CREATE TABLE IF NOT EXISTS mcp_account_prefs (account_id text PRIMARY KEY, prefs jsonb NOT NULL, updated_at bigint NOT NULL)`)
21
+ .then(() => true)
22
+ .catch((e) => {
23
+ console.error("[prefs] table init failed, using redis/memory:", e?.message ?? e);
24
+ return false;
25
+ });
26
+ return tableReady;
27
+ }
28
+ /** The account a WebCake JWT belongs to (payload.account_id), unverified — the backend verifies the token itself. */
29
+ export function accountOf(jwt) {
30
+ try {
31
+ const id = JSON.parse(Buffer.from(String(jwt).split(".")[1], "base64url").toString()).account_id;
32
+ return typeof id === "string" && id ? id : undefined;
33
+ }
34
+ catch {
35
+ return undefined;
36
+ }
37
+ }
38
+ export async function loadPrefs(account) {
39
+ try {
40
+ if (await ensureTable()) {
41
+ const { rows } = await getPg().query(`SELECT prefs FROM mcp_account_prefs WHERE account_id=$1`, [account]);
42
+ return { ...(rows[0]?.prefs ?? {}) };
43
+ }
44
+ const redis = getRedis();
45
+ if (redis)
46
+ return JSON.parse((await redis.get(REDIS_PREFIX + account)) || "{}");
47
+ }
48
+ catch (e) {
49
+ console.error("[prefs] load failed:", e?.message ?? e);
50
+ }
51
+ return { ...(mem.get(account) ?? {}) };
52
+ }
53
+ /** Persist one allowlisted key (null = delete). Fire-and-forget; never throws. */
54
+ export function savePref(account, key, value) {
55
+ if (!KEYS.has(key))
56
+ return;
57
+ const patch = value === null ? {} : { [key]: value };
58
+ (async () => {
59
+ if (await ensureTable()) {
60
+ // Merge in SQL so two instances writing different keys don't clobber each other.
61
+ await getPg().query(`INSERT INTO mcp_account_prefs (account_id, prefs, updated_at) VALUES ($1, $2::jsonb, $3)
62
+ ON CONFLICT (account_id) DO UPDATE SET prefs = (mcp_account_prefs.prefs - $4) || $2::jsonb, updated_at = $3`, [account, JSON.stringify(patch), Date.now(), key]);
63
+ return;
64
+ }
65
+ const redis = getRedis();
66
+ if (redis) {
67
+ // ponytail: read-modify-write, last writer wins; Postgres path is the atomic one.
68
+ const cur = JSON.parse((await redis.get(REDIS_PREFIX + account)) || "{}");
69
+ if (value === null)
70
+ delete cur[key];
71
+ else
72
+ cur[key] = value;
73
+ await redis.set(REDIS_PREFIX + account, JSON.stringify(cur));
74
+ return;
75
+ }
76
+ const cur = mem.get(account) ?? {};
77
+ if (value === null)
78
+ delete cur[key];
79
+ else
80
+ cur[key] = value;
81
+ mem.set(account, cur);
82
+ })().catch((e) => console.error("[prefs] save failed:", e?.message ?? e));
83
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webcake-storefront-mcp",
3
- "version": "1.39.0",
3
+ "version": "1.41.0",
4
4
  "description": "MCP server for the WebCake/StoreCake storefront builder — page CRUD, page authoring, products, orders, and more",
5
5
  "mcpName": "io.github.vuluu2k/webcake-storefront-mcp",
6
6
  "license": "MIT",