webcake-storefront-mcp 1.39.0 → 1.40.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() : 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,7 @@ 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 { getConfig, setConfig } from "../db.js";
9
9
  function parseArgs(argv) {
10
10
  const opts = { open: true };
11
11
  for (let i = 0; i < argv.length; i++) {
@@ -196,3 +196,24 @@ export async function runLogin(argv) {
196
196
  }, 180_000).unref();
197
197
  });
198
198
  }
199
+ // One browser Connect at a time; after a failed/abandoned one, wait before reopening so a
200
+ // looping agent doesn't spam tabs. ponytail: process-wide, fine for one stdio user.
201
+ let renewing = null;
202
+ let lastFail = 0;
203
+ /** Token expired mid-session (stdio): reopen the Connect page and hand back the new credentials. */
204
+ export function renewInBrowser() {
205
+ if (!renewing && Date.now() - lastFail > 120_000) {
206
+ console.error("[webcake-storefront] Token hết hạn — mở trình duyệt để Kết nối lại…");
207
+ renewing = runLogin([])
208
+ .then(() => ({ token: getConfig("token") || "", sessionId: getConfig("session_id") || "" }))
209
+ .catch((e) => {
210
+ lastFail = Date.now();
211
+ console.error("[webcake-storefront] gia hạn token thất bại:", e?.message || e);
212
+ return null;
213
+ })
214
+ .finally(() => {
215
+ renewing = null;
216
+ });
217
+ }
218
+ return renewing ?? Promise.resolve(null);
219
+ }
@@ -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";
@@ -332,6 +333,19 @@ export async function completeAuthorize(internalState, jwt, wsid) {
332
333
  });
333
334
  return { ok: true, redirectUri: p.redirect_uri, code, state: p.state };
334
335
  }
336
+ // ---- Dead WebCake sessions ---------------------------------------------------
337
+ // The OAuth tokens outlive the WebCake JWT they wrap. Once that JWT is expired (or the
338
+ // backend rejected it), refreshing would just re-issue the dead JWT; refusing it makes the
339
+ // client restart the full flow, i.e. open the Connect page again.
340
+ // ponytail: in-memory set, per process; share it via Redis if the server is ever scaled out.
341
+ const deadJwts = new Set();
342
+ export function markJwtDead(jwt) {
343
+ if (jwt)
344
+ deadJwts.add(jwt);
345
+ }
346
+ export function isDeadJwt(jwt) {
347
+ return !!jwt && (deadJwts.has(jwt) || jwtExpired(jwt));
348
+ }
335
349
  async function issueTokens(store, cred, client_id, scope) {
336
350
  const access = token(32);
337
351
  const refresh = token(32);
@@ -366,6 +380,9 @@ export async function exchangeToken(p) {
366
380
  if (!r) {
367
381
  return { ok: false, status: 400, error: "invalid_grant", error_description: "Unknown or expired refresh token." };
368
382
  }
383
+ if (isDeadJwt(r.cred.jwt)) {
384
+ return { ok: false, status: 400, error: "invalid_grant", error_description: "WebCake session expired — sign in again (Connect)." };
385
+ }
369
386
  return { ok: true, body: await issueTokens(store, r.cred, r.client_id, r.scope) };
370
387
  }
371
388
  return { ok: false, status: 400, error: "unsupported_grant_type", error_description: "grant_type must be authorization_code or refresh_token." };
@@ -386,11 +403,11 @@ export async function resolveAccessToken(accessToken) {
386
403
  if (redis) {
387
404
  const cached = await redisCacheGet(redis, accessToken);
388
405
  if (cached)
389
- return cached;
406
+ return isDeadJwt(cached.jwt) ? undefined : cached;
390
407
  }
391
408
  // 2. Fall through to the store (Postgres or memory).
392
409
  const a = await (await getStore()).getAccess(accessToken);
393
- if (!a)
410
+ if (!a || isDeadJwt(a.cred.jwt))
394
411
  return undefined;
395
412
  // Backfill the Redis cache for next time.
396
413
  if (redis)
@@ -1,4 +1,11 @@
1
1
  [
2
+ {
3
+ "v": "1.40.0",
4
+ "d": "19/11/2026",
5
+ "type": "Added",
6
+ "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…",
7
+ "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…"
8
+ },
2
9
  {
3
10
  "v": "1.39.0",
4
11
  "d": "13/11/2026",
@@ -33,12 +40,5 @@
33
40
  "type": "Changed",
34
41
  "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
42
  "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/http.js CHANGED
@@ -13,7 +13,7 @@ import { createServer } from "./server.js";
13
13
  import { makeApi, resolveEnv, ENVIRONMENTS, DEFAULT_ENV } from "./config.js";
14
14
  import { landingHtml, faviconSvg, ogImageSvg, normalizeLang, ICON_PNG } from "./web-guide.js";
15
15
  import { privacyHtml, termsHtml } from "./legal.js";
16
- import { registerClient, startAuthorize, completeAuthorize, exchangeToken, resolveAccessToken, revokeToken, authServerMetadata, protectedResourceMetadata, } from "./auth/oauth-server.js";
16
+ import { registerClient, startAuthorize, completeAuthorize, exchangeToken, resolveAccessToken, revokeToken, isDeadJwt, markJwtDead, authServerMetadata, protectedResourceMetadata, } from "./auth/oauth-server.js";
17
17
  const MCP_PATH = "/mcp";
18
18
  // OAuth 2.1 endpoints.
19
19
  const WELL_KNOWN_PR = "/.well-known/oauth-protected-resource";
@@ -42,6 +42,10 @@ function header(req, name) {
42
42
  const v = req.headers[name];
43
43
  return Array.isArray(v) ? v[0] : v;
44
44
  }
45
+ function setHeader(req, name, value) {
46
+ req.headers[name] = value;
47
+ req.rawHeaders.push(name, value);
48
+ }
45
49
  /** Copy recognised query params onto request headers so downstream reads are uniform. */
46
50
  function applyQueryAuth(req) {
47
51
  const q = (req.url ?? "").indexOf("?");
@@ -288,6 +292,7 @@ async function handleOAuth(req, res, path) {
288
292
  }
289
293
  export async function startHttpServer(port) {
290
294
  const transports = new Map();
295
+ const apis = new Map();
291
296
  const httpServer = createHttpServer(async (req, res) => {
292
297
  const path = (req.url ?? "").split("?")[0];
293
298
  // ---- Favicon / brand icon ----
@@ -346,30 +351,38 @@ export async function startHttpServer(port) {
346
351
  // ---- /mcp handling ----
347
352
  // Accept credentials via query params for clients that can't set headers.
348
353
  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.
354
+ // Resolve an OAuth Bearer access token to { jwt, wsid }. It WINS over a ?token= /
355
+ // x-webcake-jwt pair: a Bearer from our OAuth flow is what the last Connect issued, so
356
+ // it's the renewed credential when the URL still carries an old, expired one.
351
357
  const bearer = bearerFrom(req);
352
358
  const oauthCred = await resolveAccessToken(bearer);
353
359
  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
- }
360
+ setHeader(req, "x-webcake-jwt", oauthCred.jwt);
361
+ if (oauthCred.wsid)
362
+ setHeader(req, "x-webcake-session-id", oauthCred.wsid);
362
363
  }
363
- // Enforce OAuth when enabled: a request with no recognised credential gets 401.
364
- if (OAUTH_ENFORCED && !oauthCred && req.headers["x-webcake-jwt"] == null) {
364
+ const sidHeader = header(req, "mcp-session-id");
365
+ const jwt = header(req, "x-webcake-jwt");
366
+ // An open session picks up a renewed credential in place (no re-initialize needed).
367
+ const sessionApi = sidHeader ? apis.get(sidHeader) : undefined;
368
+ if (sessionApi && jwt && jwt !== sessionApi.token && !isDeadJwt(jwt)) {
369
+ sessionApi.switchToken(jwt);
370
+ const wsid = header(req, "x-webcake-session-id");
371
+ if (wsid)
372
+ sessionApi.switchSession(wsid);
373
+ }
374
+ // Enforce OAuth when enabled: no credential, or an expired/rejected WebCake token, gets
375
+ // 401 + WWW-Authenticate so the client (re)opens the Connect page by itself.
376
+ const dead = isDeadJwt(sessionApi ? sessionApi.token : jwt);
377
+ if (OAUTH_ENFORCED && (jwt == null || dead)) {
365
378
  res.writeHead(401, {
366
- "www-authenticate": `Bearer resource_metadata="${publicBase(req)}${WELL_KNOWN_PR}"`,
379
+ "www-authenticate": `Bearer error="invalid_token", resource_metadata="${publicBase(req)}${WELL_KNOWN_PR}"`,
367
380
  "content-type": "application/json",
368
381
  });
369
- res.end(JSON.stringify({ error: "invalid_token", error_description: "Authentication required — connect via OAuth." }));
382
+ const why = dead ? "WebCake session expired — reconnect (Connect) to renew it." : "Authentication required — connect via OAuth.";
383
+ res.end(JSON.stringify({ error: "invalid_token", error_description: why }));
370
384
  return;
371
385
  }
372
- const sidHeader = header(req, "mcp-session-id");
373
386
  try {
374
387
  // Reuse an existing session.
375
388
  if (sidHeader && transports.has(sidHeader)) {
@@ -386,13 +399,21 @@ export async function startHttpServer(port) {
386
399
  sessionIdGenerator: () => randomUUID(),
387
400
  onsessioninitialized: (id) => {
388
401
  transports.set(id, transport);
402
+ apis.set(id, api);
389
403
  },
390
404
  });
391
405
  transport.onclose = () => {
392
- if (transport.sessionId)
406
+ if (transport.sessionId) {
393
407
  transports.delete(transport.sessionId);
408
+ apis.delete(transport.sessionId);
409
+ }
394
410
  };
395
411
  const api = apiFromRequest(req);
412
+ // Backend rejected the token → remember it, so the next request 401s into Connect.
413
+ api.onAuthExpired = async () => {
414
+ markJwtDead(api.token);
415
+ return null;
416
+ };
396
417
  const server = createServer(api, { allowLocalFiles: false, tools: header(req, "x-webcake-tools") }); // remote: never read server-side files
397
418
  await server.connect(transport);
398
419
  await transport.handleRequest(req, res, body);
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);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webcake-storefront-mcp",
3
- "version": "1.39.0",
3
+ "version": "1.40.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",