webcake-landing-mcp 1.8.0 → 1.9.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.
@@ -30,18 +30,72 @@
30
30
  import { randomBytes, createHash } from "node:crypto";
31
31
  import { getPg, ensureOAuthSchema } from "../persistence/postgres.js";
32
32
  import { jwtExpired } from "../persistence/config.js";
33
+ import { getRedis } from "../persistence/redis.js";
33
34
  // ---- Dead Webcake sessions -------------------------------------------------
34
35
  // The OAuth tokens outlive the Webcake JWT they wrap. Once that JWT is expired (or the
35
36
  // backend rejected it), refreshing would just re-issue the dead JWT; refusing it makes the
36
37
  // client restart the full flow, i.e. open the Connect page again.
37
- // ponytail: in-memory set, per process; move to Postgres/Redis if the server is scaled out.
38
- const deadJwts = new Set();
39
- export function markJwtDead(jwt) {
40
- if (jwt)
41
- deadJwts.add(jwt);
38
+ // Shared across instances: markJwtDead revokes every OAuth token wrapping the JWT in the
39
+ // store (Postgres = source of truth) and flags it in Redis for raw ?jwt= callers.
40
+ // Only a sha256 of the JWT is kept, never the token itself.
41
+ const DEAD_PREFIX = "wc:lp:deadjwt:";
42
+ const DEAD_MAX_TTL = 30 * 24 * 60 * 60 * 1000;
43
+ const deadLocal = new Map(); // hash → expiresAt (ms)
44
+ const jwtHash = (jwt) => createHash("sha256").update(jwt).digest("hex");
45
+ function deadTtl(jwt) {
46
+ try {
47
+ const exp = JSON.parse(Buffer.from(jwt.split(".")[1], "base64url").toString()).exp;
48
+ if (typeof exp === "number")
49
+ return Math.min(Math.max(exp * 1000 - Date.now(), 60_000), DEAD_MAX_TTL);
50
+ }
51
+ catch { /* opaque token */ }
52
+ return DEAD_MAX_TTL;
53
+ }
54
+ function rememberDeadLocally(hash, ttl) {
55
+ if (deadLocal.size > 10_000)
56
+ for (const [k, exp] of deadLocal)
57
+ if (exp < Date.now())
58
+ deadLocal.delete(k);
59
+ if (deadLocal.size > 10_000)
60
+ deadLocal.delete(deadLocal.keys().next().value); // still full: drop oldest
61
+ deadLocal.set(hash, Date.now() + ttl);
62
+ }
63
+ /** Expired, or already marked dead here — no I/O. */
64
+ function isDeadLocally(jwt) {
65
+ if (jwtExpired(jwt))
66
+ return true;
67
+ const exp = deadLocal.get(jwtHash(jwt));
68
+ return exp !== undefined && exp >= Date.now();
42
69
  }
43
- export function isDeadJwt(jwt) {
44
- return !!jwt && (deadJwts.has(jwt) || jwtExpired(jwt));
70
+ /** The backend rejected this JWT: make every instance treat it as dead. Never throws. */
71
+ export async function markJwtDead(jwt) {
72
+ if (!jwt)
73
+ return;
74
+ const hash = jwtHash(jwt);
75
+ const ttl = deadTtl(jwt);
76
+ rememberDeadLocally(hash, ttl);
77
+ try {
78
+ await getRedis()?.set(DEAD_PREFIX + hash, "1", "PX", ttl);
79
+ await (await getStore()).revokeJwt(jwt);
80
+ }
81
+ catch (e) {
82
+ console.error("[oauth] markJwtDead:", e?.message ?? e);
83
+ }
84
+ }
85
+ /** True when the JWT is expired or any instance marked it dead. */
86
+ export async function isDeadJwt(jwt) {
87
+ if (!jwt)
88
+ return false;
89
+ if (isDeadLocally(jwt))
90
+ return true;
91
+ const redis = getRedis();
92
+ if (!redis)
93
+ return false;
94
+ const hash = jwtHash(jwt);
95
+ const hit = await redis.get(DEAD_PREFIX + hash).catch(() => null);
96
+ if (hit)
97
+ rememberDeadLocally(hash, deadTtl(jwt));
98
+ return !!hit;
45
99
  }
46
100
  // ---- TTLs (override via env where useful) ---------------------------------
47
101
  const TEN_MIN = 10 * 60 * 1000;
@@ -127,6 +181,14 @@ class MemoryStore {
127
181
  this.access.delete(t);
128
182
  this.refresh.delete(t);
129
183
  }
184
+ async revokeJwt(ljwt) {
185
+ for (const [k, v] of this.access)
186
+ if (v.ljwt === ljwt)
187
+ this.access.delete(k);
188
+ for (const [k, v] of this.refresh)
189
+ if (v.ljwt === ljwt)
190
+ this.refresh.delete(k);
191
+ }
130
192
  }
131
193
  // ---- Postgres store (when DATABASE_URL is set) ----------------------------
132
194
  class PgStore {
@@ -220,6 +282,11 @@ class PgStore {
220
282
  await this.pool.query(`DELETE FROM oauth_access_tokens WHERE token=$1`, [t]);
221
283
  await this.pool.query(`DELETE FROM oauth_refresh_tokens WHERE token=$1`, [t]);
222
284
  }
285
+ // ponytail: no index on ljwt — a seq scan, but this only runs when a JWT dies.
286
+ async revokeJwt(ljwt) {
287
+ await this.pool.query(`DELETE FROM oauth_access_tokens WHERE ljwt=$1`, [ljwt]);
288
+ await this.pool.query(`DELETE FROM oauth_refresh_tokens WHERE ljwt=$1`, [ljwt]);
289
+ }
223
290
  }
224
291
  // ---- Backend selection (memoized) -----------------------------------------
225
292
  const memoryStore = new MemoryStore();
@@ -387,7 +454,7 @@ export async function exchangeToken(p) {
387
454
  if (!r) {
388
455
  return { ok: false, status: 400, error: "invalid_grant", error_description: "Unknown or expired refresh token." };
389
456
  }
390
- if (isDeadJwt(r.ljwt)) {
457
+ if (await isDeadJwt(r.ljwt)) {
391
458
  return { ok: false, status: 400, error: "invalid_grant", error_description: "Webcake session expired — sign in again (Connect)." };
392
459
  }
393
460
  return { ok: true, body: await issueTokens(store, r.ljwt, r.client_id, r.scope) };
@@ -400,7 +467,7 @@ export async function resolveAccessToken(accessToken) {
400
467
  if (!accessToken)
401
468
  return undefined;
402
469
  const a = await (await getStore()).getAccess(accessToken);
403
- return a && !isDeadJwt(a.ljwt) ? a.ljwt : undefined;
470
+ return a && !isDeadLocally(a.ljwt) ? a.ljwt : undefined;
404
471
  }
405
472
  /** Revoke an access or refresh token (best-effort; for /revoke). */
406
473
  export async function revokeToken(t) {
@@ -1,15 +1,76 @@
1
- import { configFromHeaders, jwtExpired, readConfig } from "../persistence/config.js";
1
+ import { closeSync, mkdirSync, openSync, statSync, unlinkSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { configDir, configFromHeaders, jwtExpired, readConfig, readSavedConfig } from "../persistence/config.js";
2
4
  import { markJwtDead } from "./oauth-server.js";
3
5
  import { runLogin } from "./login.js";
4
- // One browser Connect at a time; after a failed/abandoned one, wait before reopening so a
5
- // looping agent doesn't spam tabs. ponytail: process-wide, fine for one stdio user.
6
+ // One browser Connect at a time — across every stdio process on this machine (several IDE
7
+ // windows share ~/.webcake-landing-mcp): the first takes a lock file and opens the browser,
8
+ // the others wait for the token it saves. After a failed/abandoned Connect, wait before
9
+ // reopening so a looping agent doesn't spam tabs.
10
+ const LOGIN_WAIT_MS = 185_000; // runLogin times out at 180s
11
+ const lockPath = () => join(configDir(), "renew.lock");
6
12
  let renewing = null;
7
13
  let lastFail = 0;
8
- export function renewInBrowser() {
9
- if (!renewing && Date.now() - lastFail > 120_000) {
14
+ /** auth.json holds a token newer than `stale` and not expired (another process renewed it). */
15
+ const savedFresh = (stale) => {
16
+ const jwt = readSavedConfig().jwt;
17
+ return !!jwt && jwt !== stale && !jwtExpired(jwt);
18
+ };
19
+ function takeLock() {
20
+ try {
21
+ mkdirSync(configDir(), { recursive: true });
22
+ closeSync(openSync(lockPath(), "wx"));
23
+ return true;
24
+ }
25
+ catch {
26
+ try {
27
+ if (Date.now() - statSync(lockPath()).mtimeMs > LOGIN_WAIT_MS) {
28
+ unlinkSync(lockPath()); // left behind by a crashed process
29
+ return takeLock();
30
+ }
31
+ }
32
+ catch { /* raced with its owner releasing it */ }
33
+ return false;
34
+ }
35
+ }
36
+ async function renew(stale) {
37
+ if (savedFresh(stale))
38
+ return true;
39
+ if (!takeLock()) {
40
+ // Someone else has the browser open — wait for the token they save.
41
+ for (const until = Date.now() + LOGIN_WAIT_MS; Date.now() < until;) {
42
+ await new Promise((r) => setTimeout(r, 1000));
43
+ if (savedFresh(stale))
44
+ return true;
45
+ try {
46
+ statSync(lockPath());
47
+ }
48
+ catch {
49
+ return savedFresh(stale);
50
+ } // released without a token
51
+ }
52
+ return false;
53
+ }
54
+ try {
10
55
  console.error("[webcake-landing] Token hết hạn — mở trình duyệt để Kết nối lại…");
11
- renewing = runLogin([])
12
- .then(() => true)
56
+ await runLogin([]);
57
+ return true;
58
+ }
59
+ finally {
60
+ try {
61
+ unlinkSync(lockPath());
62
+ }
63
+ catch { /* already gone */ }
64
+ }
65
+ }
66
+ export function renewInBrowser(staleJwt) {
67
+ if (!renewing && Date.now() - lastFail > 120_000) {
68
+ renewing = renew(staleJwt)
69
+ .then((ok) => {
70
+ if (!ok)
71
+ lastFail = Date.now();
72
+ return ok;
73
+ })
13
74
  .catch((e) => {
14
75
  lastFail = Date.now();
15
76
  console.error("[webcake-landing] gia hạn token thất bại:", e?.message || e);
@@ -32,16 +93,18 @@ export function renewAuthOnExpiry(server, stdio) {
32
93
  const handler = args[args.length - 1];
33
94
  args[args.length - 1] = async (...call) => {
34
95
  const extra = call[call.length - 1];
35
- if (stdio && jwtExpired(jwtOf(extra)))
36
- await renewInBrowser();
96
+ const before = jwtOf(extra);
97
+ if (stdio && jwtExpired(before))
98
+ await renewInBrowser(before);
99
+ const used = jwtOf(extra);
37
100
  const result = await handler(...call);
38
101
  if (!isUnauthorized(result))
39
102
  return result;
40
103
  if (!stdio) {
41
- markJwtDead(jwtOf(extra));
104
+ await markJwtDead(used);
42
105
  return result;
43
106
  }
44
- return (await renewInBrowser()) ? handler(...call) : result;
107
+ return (await renewInBrowser(used)) ? handler(...call) : result;
45
108
  };
46
109
  return tool(...args);
47
110
  };
@@ -1,4 +1,11 @@
1
1
  [
2
+ {
3
+ "v": "1.9.0",
4
+ "d": "19/11/2026",
5
+ "type": "Changed",
6
+ "en": "A Webcake JWT the backend rejects is now marked dead in a shared store (Redis + Postgres) instead of a single process's memory, so every remote…",
7
+ "vi": "Một JWT Webcake bị backend từ chối nay được đánh dấu \"chết\" trong một store chung (Redis + Postgres) thay vì chỉ nằm trong bộ nhớ của một process,…"
8
+ },
2
9
  {
3
10
  "v": "1.8.0",
4
11
  "d": "19/11/2026",
@@ -33,12 +40,5 @@
33
40
  "type": "Added",
34
41
  "en": "The self-hosted screenshot route behind render_preview now caps concurrent Playwright captures at RENDER_SCREENSHOT_CONCURRENCY (default 2), queuing…",
35
42
  "vi": "Route screenshot self-hosted phía sau render_preview nay giới hạn số lượt chụp Playwright chạy đồng thời theo RENDER_SCREENSHOT_CONCURRENCY (mặc…"
36
- },
37
- {
38
- "v": "1.5.11",
39
- "d": "13/10/2026",
40
- "type": "Fixed",
41
- "en": "The HTTP server now answers HEAD requests the same way it answers GET on every public read-only route (/privacy, /privacy-policy, /terms, /tos,…",
42
- "vi": "HTTP server nay trả lời request HEAD giống như GET trên mọi route công khai chỉ-đọc (/privacy, /privacy-policy, /terms, /tos, /favicon.ico,…"
43
43
  }
44
44
  ]
package/dist/http.js CHANGED
@@ -488,7 +488,7 @@ export async function startHttpServer(port) {
488
488
  // enforced mode a raw JWT must use x-webcake-jwt / ?jwt=, since Bearer is reserved
489
489
  // for OAuth access tokens.
490
490
  const given = req.headers["x-webcake-jwt"];
491
- const dead = isDeadJwt(Array.isArray(given) ? given[0] : given);
491
+ const dead = await isDeadJwt(Array.isArray(given) ? given[0] : given);
492
492
  if (OAUTH_ENFORCED && (given == null || dead)) {
493
493
  res.writeHead(401, {
494
494
  "www-authenticate": `Bearer error="invalid_token", resource_metadata="${publicBase(req)}${WELL_KNOWN_PR}"`,
package/dist/smoke.js CHANGED
@@ -2556,9 +2556,9 @@ console.log("== auth: expired token → Connect again ==");
2556
2556
  const jwt = (dSec) => `h.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + dSec })).toString("base64url")}.s`;
2557
2557
  const OLD = jwt(-3600), NEW = jwt(3600);
2558
2558
  check("auth: jwtExpired reads exp; opaque tokens never expire", jwtExpired(OLD) && !jwtExpired(NEW) && !jwtExpired("opaque"));
2559
- check("auth: expired JWT is dead (OAuth refresh + resolve refuse it)", isDeadJwt(OLD) && !isDeadJwt(NEW));
2560
- markJwtDead("rejected-by-backend");
2561
- check("auth: backend-rejected JWT is dead", isDeadJwt("rejected-by-backend"));
2559
+ check("auth: expired JWT is dead (OAuth refresh + resolve refuse it)", (await isDeadJwt(OLD)) && !(await isDeadJwt(NEW)));
2560
+ await markJwtDead("rejected-by-backend");
2561
+ check("auth: backend-rejected JWT is dead", await isDeadJwt("rejected-by-backend"));
2562
2562
  check("auth: isUnauthorized spots a backend 401 in a tool result", isUnauthorized({ content: [{ type: "text", text: '{"ok":false,"error":"Backend returned 401: Unauthorized"}' }] }) && !isUnauthorized({ content: [{ type: "text", text: '{"error":"Backend returned 403"}' }] }));
2563
2563
  const saveEnv = process.env.WEBCAKE_JWT;
2564
2564
  process.env.WEBCAKE_JWT = OLD;
@@ -2572,7 +2572,7 @@ console.log("== auth: expired token → Connect again ==");
2572
2572
  renewAuthOnExpiry(fake, false);
2573
2573
  fake.tool("t", async () => ({ content: [{ type: "text", text: "Backend returned 401: Unauthorized" }] }));
2574
2574
  await fake.h({}, { requestInfo: { headers: { "x-webcake-jwt": "remote-rejected", "x-webcake-env": "prod" } } });
2575
- check("auth: remote 401 marks the session JWT dead", isDeadJwt("remote-rejected"));
2575
+ check("auth: remote 401 marks the session JWT dead", await isDeadJwt("remote-rejected"));
2576
2576
  }
2577
2577
  console.log("== server: MCP serverInfo.version follows package.json (no hardcoded constant) ==");
2578
2578
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webcake-landing-mcp",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "MCP server exposing Webcake landing-page element schemas + AI usage hints, and persisting LLM-generated page sources to a Webcake backend.",
5
5
  "mcpName": "io.github.vuluu2k/webcake-landing-mcp",
6
6
  "type": "module",