webcake-storefront-mcp 1.40.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
@@ -51,7 +51,7 @@ export class WebcakeCmsApi {
51
51
  * Connect page and returns the new credentials (request is retried once). Remote: marks it dead. */
52
52
  onAuthExpired;
53
53
  async renewAuth() {
54
- const fresh = this.onAuthExpired ? await this.onAuthExpired() : null;
54
+ const fresh = this.onAuthExpired ? await this.onAuthExpired(this.token) : null;
55
55
  if (!fresh?.token)
56
56
  return false;
57
57
  this.switchToken(fresh.token);
@@ -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 { getConfig, 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,16 +199,77 @@ export async function runLogin(argv) {
196
199
  }, 180_000).unref();
197
200
  });
198
201
  }
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.
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
201
208
  let renewing = null;
202
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
+ }
203
264
  /** Token expired mid-session (stdio): reopen the Connect page and hand back the new credentials. */
204
- export function renewInBrowser() {
265
+ export function renewInBrowser(staleToken = "") {
205
266
  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") || "" }))
267
+ renewing = renew(staleToken)
268
+ .then((r) => {
269
+ if (!r)
270
+ lastFail = Date.now();
271
+ return r;
272
+ })
209
273
  .catch((e) => {
210
274
  lastFail = Date.now();
211
275
  console.error("[webcake-storefront] gia hạn token thất bại:", e?.message || e);
@@ -98,6 +98,18 @@ class MemoryStore {
98
98
  return r && r.expiresAt >= now() ? r : undefined;
99
99
  }
100
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
+ }
101
113
  }
102
114
  // ---- Postgres store (when DATABASE_URL is set) -----------------------------
103
115
  class PgStore {
@@ -200,6 +212,12 @@ class PgStore {
200
212
  await this.pool.query(`DELETE FROM oauth_access_tokens WHERE token=$1`, [t]);
201
213
  await this.pool.query(`DELETE FROM oauth_refresh_tokens WHERE token=$1`, [t]);
202
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
+ }
203
221
  }
204
222
  // ---- Backend selection (memoized) ------------------------------------------
205
223
  const memoryStore = new MemoryStore();
@@ -337,14 +355,72 @@ export async function completeAuthorize(internalState, jwt, wsid) {
337
355
  // The OAuth tokens outlive the WebCake JWT they wrap. Once that JWT is expired (or the
338
356
  // backend rejected it), refreshing would just re-issue the dead JWT; refusing it makes the
339
357
  // 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);
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();
345
389
  }
346
- export function isDeadJwt(jwt) {
347
- return !!jwt && (deadJwts.has(jwt) || jwtExpired(jwt));
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;
348
424
  }
349
425
  async function issueTokens(store, cred, client_id, scope) {
350
426
  const access = token(32);
@@ -380,7 +456,7 @@ export async function exchangeToken(p) {
380
456
  if (!r) {
381
457
  return { ok: false, status: 400, error: "invalid_grant", error_description: "Unknown or expired refresh token." };
382
458
  }
383
- if (isDeadJwt(r.cred.jwt)) {
459
+ if (await isDeadJwt(r.cred.jwt)) {
384
460
  return { ok: false, status: 400, error: "invalid_grant", error_description: "WebCake session expired — sign in again (Connect)." };
385
461
  }
386
462
  return { ok: true, body: await issueTokens(store, r.cred, r.client_id, r.scope) };
@@ -403,11 +479,11 @@ export async function resolveAccessToken(accessToken) {
403
479
  if (redis) {
404
480
  const cached = await redisCacheGet(redis, accessToken);
405
481
  if (cached)
406
- return isDeadJwt(cached.jwt) ? undefined : cached;
482
+ return isDeadLocally(cached.jwt) ? undefined : cached;
407
483
  }
408
484
  // 2. Fall through to the store (Postgres or memory).
409
485
  const a = await (await getStore()).getAccess(accessToken);
410
- if (!a || isDeadJwt(a.cred.jwt))
486
+ if (!a || isDeadLocally(a.cred.jwt))
411
487
  return undefined;
412
488
  // Backfill the Redis cache for next time.
413
489
  if (redis)
@@ -1,4 +1,11 @@
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
+ },
2
9
  {
3
10
  "v": "1.40.0",
4
11
  "d": "19/11/2026",
@@ -33,12 +40,5 @@
33
40
  "type": "Fixed",
34
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…",
35
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…"
36
- },
37
- {
38
- "v": "1.36.1",
39
- "d": "27/10/2026",
40
- "type": "Changed",
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,…",
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…"
43
43
  }
44
44
  ]
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,6 +10,8 @@ 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";
@@ -291,8 +293,7 @@ async function handleOAuth(req, res, path) {
291
293
  return false;
292
294
  }
293
295
  export async function startHttpServer(port) {
294
- const transports = new Map();
295
- const apis = new Map();
296
+ const sessions = new Map();
296
297
  const httpServer = createHttpServer(async (req, res) => {
297
298
  const path = (req.url ?? "").split("?")[0];
298
299
  // ---- Favicon / brand icon ----
@@ -363,17 +364,23 @@ export async function startHttpServer(port) {
363
364
  }
364
365
  const sidHeader = header(req, "mcp-session-id");
365
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
+ }
366
374
  // 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);
375
+ if (session && jwt && jwt !== session.api.token && !(await isDeadJwt(jwt))) {
376
+ session.api.switchToken(jwt);
370
377
  const wsid = header(req, "x-webcake-session-id");
371
378
  if (wsid)
372
- sessionApi.switchSession(wsid);
379
+ session.api.switchSession(wsid);
373
380
  }
374
381
  // Enforce OAuth when enabled: no credential, or an expired/rejected WebCake token, gets
375
382
  // 401 + WWW-Authenticate so the client (re)opens the Connect page by itself.
376
- const dead = isDeadJwt(sessionApi ? sessionApi.token : jwt);
383
+ const dead = await isDeadJwt(session ? session.api.token : jwt);
377
384
  if (OAUTH_ENFORCED && (jwt == null || dead)) {
378
385
  res.writeHead(401, {
379
386
  "www-authenticate": `Bearer error="invalid_token", resource_metadata="${publicBase(req)}${WELL_KNOWN_PR}"`,
@@ -384,45 +391,64 @@ export async function startHttpServer(port) {
384
391
  return;
385
392
  }
386
393
  try {
387
- // Reuse an existing session.
388
- if (sidHeader && transports.has(sidHeader)) {
389
- const transport = transports.get(sidHeader);
394
+ if (session) {
390
395
  const body = req.method === "POST" ? await readBody(req) : undefined;
391
- await transport.handleRequest(req, res, body);
396
+ await runWithConfigScope(session.scope, () => session.transport.handleRequest(req, res, body));
392
397
  return;
393
398
  }
394
399
  // New session: must be an initialize POST.
395
400
  if (req.method === "POST") {
396
401
  const body = await readBody(req);
397
- if (!sidHeader && isInitializeRequest(body)) {
398
- const transport = new StreamableHTTPServerTransport({
399
- sessionIdGenerator: () => randomUUID(),
400
- onsessioninitialized: (id) => {
401
- transports.set(id, transport);
402
- apis.set(id, api);
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));
403
421
  },
404
- });
405
- transport.onclose = () => {
406
- if (transport.sessionId) {
407
- transports.delete(transport.sessionId);
408
- apis.delete(transport.sessionId);
409
- }
410
422
  };
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
- };
417
- const server = createServer(api, { allowLocalFiles: false, tools: header(req, "x-webcake-tools") }); // remote: never read server-side files
418
- await server.connect(transport);
419
- 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
+ });
420
446
  return;
421
447
  }
422
448
  rpcError(res, 400, "Bad Request: send an initialize request first (no valid mcp-session-id).");
423
449
  return;
424
450
  }
425
- rpcError(res, 400, "Bad Request: missing or unknown mcp-session-id.");
451
+ rpcError(res, 400, "Bad Request: missing mcp-session-id.");
426
452
  }
427
453
  catch (e) {
428
454
  const msg = e instanceof Error ? e.message : String(e);
@@ -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.40.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",