webcake-landing-mcp 1.17.1 → 1.18.1
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/auth/login.js +6 -2
- package/dist/auth/oauth-server.js +46 -27
- package/dist/auth/token-crypto.js +49 -0
- package/dist/changelog.json +14 -14
- package/dist/http.js +150 -33
- package/dist/persistence/html-ingest.js +31 -69
- package/dist/persistence/ingest/browser-capture.js +4 -14
- package/dist/persistence/postgres.js +40 -0
- package/dist/persistence/rehost.js +41 -0
- package/dist/persistence/screenshot-playwright.js +129 -19
- package/dist/persistence/webcake-client.js +14 -31
- package/dist/smoke.js +87 -4
- package/dist/tools/media.js +10 -48
- package/package.json +1 -1
package/dist/auth/login.js
CHANGED
|
@@ -145,9 +145,13 @@ function resolveConnectUrl(opts, appBase) {
|
|
|
145
145
|
* openBrowser's Windows note) the state is what goes missing, and parseCallback
|
|
146
146
|
* rejects the round-trip. Pure + exported so smoke can pin the contract.
|
|
147
147
|
*/
|
|
148
|
-
export function buildConnectUrl(connectUrl, redirectUri, state) {
|
|
148
|
+
export function buildConnectUrl(connectUrl, redirectUri, state, extra = {}) {
|
|
149
149
|
const sep = connectUrl.includes("?") ? "&" : "?";
|
|
150
|
-
|
|
150
|
+
let url = `${connectUrl}${sep}redirect_uri=${encodeURIComponent(redirectUri)}&state=${state}`;
|
|
151
|
+
for (const [k, v] of Object.entries(extra))
|
|
152
|
+
if (v)
|
|
153
|
+
url += `&${k}=${encodeURIComponent(v)}`;
|
|
154
|
+
return url;
|
|
151
155
|
}
|
|
152
156
|
/** Decide what a loopback request means. Pure + exported so smoke can test it. */
|
|
153
157
|
export function parseCallback(reqUrl, expectedState) {
|
|
@@ -20,6 +20,8 @@
|
|
|
20
20
|
* layer resolves a Bearer access token to its ljwt and injects it as the normal
|
|
21
21
|
* `x-webcake-jwt` header, so the rest of the server (persistence/config.ts) is
|
|
22
22
|
* UNCHANGED and the legacy `?jwt=` / `x-webcake-jwt` paths keep working untouched.
|
|
23
|
+
* At rest, codes/access/refresh tokens are keyed by their sha256 and Postgres keeps the
|
|
24
|
+
* ljwt/wsid AES-GCM encrypted when WEBCAKE_TOKEN_KEY is set (see ./token-crypto.ts).
|
|
23
25
|
*
|
|
24
26
|
* STORE: Postgres when DATABASE_URL is set (tokens survive a `serve` restart and
|
|
25
27
|
* are shared across instances behind a load balancer), else in-memory maps
|
|
@@ -31,6 +33,7 @@ import { randomBytes, createHash } from "node:crypto";
|
|
|
31
33
|
import { getPg, ensureOAuthSchema } from "../persistence/postgres.js";
|
|
32
34
|
import { jwtExpired } from "../persistence/config.js";
|
|
33
35
|
import { getRedis } from "../persistence/redis.js";
|
|
36
|
+
import { sha256hex, sealCred, openCred, hasTokenKey } from "./token-crypto.js";
|
|
34
37
|
// ---- Dead Webcake sessions -------------------------------------------------
|
|
35
38
|
// The OAuth tokens outlive the Webcake JWT they wrap. Once that JWT is expired (or the
|
|
36
39
|
// backend rejected it), refreshing would just re-issue the dead JWT; refusing it makes the
|
|
@@ -41,7 +44,6 @@ import { getRedis } from "../persistence/redis.js";
|
|
|
41
44
|
const DEAD_PREFIX = "wc:lp:deadjwt:";
|
|
42
45
|
const DEAD_MAX_TTL = 30 * 24 * 60 * 60 * 1000;
|
|
43
46
|
const deadLocal = new Map(); // hash → expiresAt (ms)
|
|
44
|
-
const jwtHash = (jwt) => createHash("sha256").update(jwt).digest("hex");
|
|
45
47
|
function deadTtl(jwt) {
|
|
46
48
|
try {
|
|
47
49
|
const exp = JSON.parse(Buffer.from(jwt.split(".")[1], "base64url").toString()).exp;
|
|
@@ -64,14 +66,14 @@ function rememberDeadLocally(hash, ttl) {
|
|
|
64
66
|
function isDeadLocally(jwt) {
|
|
65
67
|
if (jwtExpired(jwt))
|
|
66
68
|
return true;
|
|
67
|
-
const exp = deadLocal.get(
|
|
69
|
+
const exp = deadLocal.get(sha256hex(jwt));
|
|
68
70
|
return exp !== undefined && exp >= Date.now();
|
|
69
71
|
}
|
|
70
72
|
/** The backend rejected this JWT: make every instance treat it as dead. Never throws. */
|
|
71
73
|
export async function markJwtDead(jwt) {
|
|
72
74
|
if (!jwt)
|
|
73
75
|
return;
|
|
74
|
-
const hash =
|
|
76
|
+
const hash = sha256hex(jwt);
|
|
75
77
|
const ttl = deadTtl(jwt);
|
|
76
78
|
rememberDeadLocally(hash, ttl);
|
|
77
79
|
try {
|
|
@@ -91,7 +93,7 @@ export async function isDeadJwt(jwt) {
|
|
|
91
93
|
const redis = getRedis();
|
|
92
94
|
if (!redis)
|
|
93
95
|
return false;
|
|
94
|
-
const hash =
|
|
96
|
+
const hash = sha256hex(jwt);
|
|
95
97
|
const hit = await redis.get(DEAD_PREFIX + hash).catch(() => null);
|
|
96
98
|
if (hit)
|
|
97
99
|
rememberDeadLocally(hash, deadTtl(jwt));
|
|
@@ -171,9 +173,11 @@ class MemoryStore {
|
|
|
171
173
|
async putRefresh(t, r) {
|
|
172
174
|
this.refresh.set(t, r);
|
|
173
175
|
}
|
|
174
|
-
async takeRefresh(t) {
|
|
176
|
+
async takeRefresh(t, clientId) {
|
|
175
177
|
this.sweep();
|
|
176
178
|
const r = this.refresh.get(t);
|
|
179
|
+
if (r && clientId && r.client_id !== clientId)
|
|
180
|
+
return undefined;
|
|
177
181
|
this.refresh.delete(t);
|
|
178
182
|
return r && r.expiresAt >= now() ? r : undefined;
|
|
179
183
|
}
|
|
@@ -233,7 +237,7 @@ class PgStore {
|
|
|
233
237
|
}
|
|
234
238
|
async putCode(code, c) {
|
|
235
239
|
await this.pool.query(`INSERT INTO oauth_codes (code, client_id, redirect_uri, code_challenge, scope, ljwt, wsid, expires_at)
|
|
236
|
-
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`, [code, c.client_id, c.redirect_uri, c.code_challenge, c.scope ?? null, c.ljwt, c.wsid, c.expiresAt]);
|
|
240
|
+
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`, [code, c.client_id, c.redirect_uri, c.code_challenge, c.scope ?? null, sealCred(c.ljwt), sealCred(c.wsid), c.expiresAt]);
|
|
237
241
|
}
|
|
238
242
|
async takeCode(code) {
|
|
239
243
|
const { rows } = await this.pool.query(`DELETE FROM oauth_codes WHERE code=$1 RETURNING client_id, redirect_uri, code_challenge, scope, ljwt, wsid, expires_at`, [code]);
|
|
@@ -245,13 +249,13 @@ class PgStore {
|
|
|
245
249
|
redirect_uri: r.redirect_uri,
|
|
246
250
|
code_challenge: r.code_challenge,
|
|
247
251
|
scope: r.scope ?? undefined,
|
|
248
|
-
ljwt: r.ljwt,
|
|
249
|
-
wsid: r.wsid ?? "",
|
|
252
|
+
ljwt: openCred(r.ljwt),
|
|
253
|
+
wsid: openCred(r.wsid ?? ""),
|
|
250
254
|
expiresAt: Number(r.expires_at),
|
|
251
255
|
};
|
|
252
256
|
}
|
|
253
257
|
async putAccess(t, a) {
|
|
254
|
-
await this.pool.query(`INSERT INTO oauth_access_tokens (token, ljwt, wsid, scope, expires_at) VALUES ($1,$2,$3,$4,$5)`, [t, a.ljwt, a.wsid, a.scope ?? null, a.expiresAt]);
|
|
258
|
+
await this.pool.query(`INSERT INTO oauth_access_tokens (token, ljwt, wsid, scope, expires_at, ljwt_sha) VALUES ($1,$2,$3,$4,$5,$6)`, [t, sealCred(a.ljwt), sealCred(a.wsid), a.scope ?? null, a.expiresAt, sha256hex(a.ljwt)]);
|
|
255
259
|
}
|
|
256
260
|
async getAccess(t) {
|
|
257
261
|
const { rows } = await this.pool.query(`SELECT ljwt, wsid, scope, expires_at FROM oauth_access_tokens WHERE token=$1`, [t]);
|
|
@@ -262,19 +266,19 @@ class PgStore {
|
|
|
262
266
|
await this.pool.query(`DELETE FROM oauth_access_tokens WHERE token=$1`, [t]);
|
|
263
267
|
return undefined;
|
|
264
268
|
}
|
|
265
|
-
return { ljwt: r.ljwt, wsid: r.wsid ?? "", scope: r.scope ?? undefined, expiresAt: Number(r.expires_at) };
|
|
269
|
+
return { ljwt: openCred(r.ljwt), wsid: openCred(r.wsid ?? ""), scope: r.scope ?? undefined, expiresAt: Number(r.expires_at) };
|
|
266
270
|
}
|
|
267
271
|
async putRefresh(t, r) {
|
|
268
|
-
await this.pool.query(`INSERT INTO oauth_refresh_tokens (token, ljwt, wsid, client_id, scope, expires_at) VALUES ($1,$2,$3,$4,$5,$6)`, [t, r.ljwt, r.wsid, r.client_id, r.scope ?? null, r.expiresAt]);
|
|
272
|
+
await this.pool.query(`INSERT INTO oauth_refresh_tokens (token, ljwt, wsid, client_id, scope, expires_at, ljwt_sha) VALUES ($1,$2,$3,$4,$5,$6,$7)`, [t, sealCred(r.ljwt), sealCred(r.wsid), r.client_id, r.scope ?? null, r.expiresAt, sha256hex(r.ljwt)]);
|
|
269
273
|
}
|
|
270
|
-
async takeRefresh(t) {
|
|
271
|
-
const { rows } = await this.pool.query(`DELETE FROM oauth_refresh_tokens WHERE token=$1 RETURNING ljwt, wsid, client_id, scope, expires_at`, [t]);
|
|
274
|
+
async takeRefresh(t, clientId) {
|
|
275
|
+
const { rows } = await this.pool.query(`DELETE FROM oauth_refresh_tokens WHERE token=$1 AND ($2::text IS NULL OR client_id=$2) RETURNING ljwt, wsid, client_id, scope, expires_at`, [t, clientId || null]);
|
|
272
276
|
const r = rows[0];
|
|
273
277
|
if (!r || Number(r.expires_at) < now())
|
|
274
278
|
return undefined;
|
|
275
279
|
return {
|
|
276
|
-
ljwt: r.ljwt,
|
|
277
|
-
wsid: r.wsid ?? "",
|
|
280
|
+
ljwt: openCred(r.ljwt),
|
|
281
|
+
wsid: openCred(r.wsid ?? ""),
|
|
278
282
|
client_id: r.client_id,
|
|
279
283
|
scope: r.scope ?? undefined,
|
|
280
284
|
expiresAt: Number(r.expires_at),
|
|
@@ -284,10 +288,12 @@ class PgStore {
|
|
|
284
288
|
await this.pool.query(`DELETE FROM oauth_access_tokens WHERE token=$1`, [t]);
|
|
285
289
|
await this.pool.query(`DELETE FROM oauth_refresh_tokens WHERE token=$1`, [t]);
|
|
286
290
|
}
|
|
287
|
-
//
|
|
291
|
+
// ljwt is encrypted with a random IV, so match its sha256; `ljwt=$2` catches a row an older
|
|
292
|
+
// instance wrote in plaintext. ponytail: no index — a seq scan, but this only runs when a JWT dies.
|
|
288
293
|
async revokeJwt(ljwt) {
|
|
289
|
-
|
|
290
|
-
await this.pool.query(`DELETE FROM
|
|
294
|
+
const args = [sha256hex(ljwt), ljwt];
|
|
295
|
+
await this.pool.query(`DELETE FROM oauth_access_tokens WHERE ljwt_sha=$1 OR ljwt=$2`, args);
|
|
296
|
+
await this.pool.query(`DELETE FROM oauth_refresh_tokens WHERE ljwt_sha=$1 OR ljwt=$2`, args);
|
|
291
297
|
}
|
|
292
298
|
}
|
|
293
299
|
// ---- Backend selection (memoized) -----------------------------------------
|
|
@@ -308,6 +314,16 @@ function getStore() {
|
|
|
308
314
|
});
|
|
309
315
|
return storePromise;
|
|
310
316
|
}
|
|
317
|
+
/**
|
|
318
|
+
* `serve` startup: fail on a malformed WEBCAKE_TOKEN_KEY, warn once when Postgres holds
|
|
319
|
+
* credentials without one, and run the schema + at-rest migration before the first request.
|
|
320
|
+
*/
|
|
321
|
+
export async function initOAuthStore() {
|
|
322
|
+
if (!hasTokenKey() && getPg()) {
|
|
323
|
+
console.error("[oauth] WARNING: WEBCAKE_TOKEN_KEY is not set — Webcake credentials are stored UNENCRYPTED in Postgres.");
|
|
324
|
+
}
|
|
325
|
+
await getStore();
|
|
326
|
+
}
|
|
311
327
|
// ---- PKCE -----------------------------------------------------------------
|
|
312
328
|
/** base64url( SHA256(verifier) ) — the S256 transform. */
|
|
313
329
|
export function s256(verifier) {
|
|
@@ -425,7 +441,7 @@ export async function startAuthorize(p) {
|
|
|
425
441
|
scope: p.scope ?? undefined,
|
|
426
442
|
expiresAt: now() + PENDING_TTL,
|
|
427
443
|
});
|
|
428
|
-
return { ok: true, internalState };
|
|
444
|
+
return { ok: true, internalState, clientName: client.client_name };
|
|
429
445
|
}
|
|
430
446
|
/**
|
|
431
447
|
* The login page (/mcp-connect) bounced back with the user's `ljwt` (+ optional
|
|
@@ -443,7 +459,8 @@ export async function completeAuthorize(internalState, ljwt, wsid) {
|
|
|
443
459
|
return { ok: false, error: "access_denied", error_description: "No Webcake token returned from login." };
|
|
444
460
|
}
|
|
445
461
|
const code = token(32);
|
|
446
|
-
|
|
462
|
+
// Bearer secrets are stored by sha256 only (both stores); the raw value goes to the client alone.
|
|
463
|
+
await store.putCode(sha256hex(code), {
|
|
447
464
|
client_id: p.client_id,
|
|
448
465
|
redirect_uri: p.redirect_uri,
|
|
449
466
|
code_challenge: p.code_challenge,
|
|
@@ -457,14 +474,14 @@ export async function completeAuthorize(internalState, ljwt, wsid) {
|
|
|
457
474
|
async function issueTokens(store, ljwt, wsid, client_id, scope) {
|
|
458
475
|
const access = token(32);
|
|
459
476
|
const refresh = token(32);
|
|
460
|
-
await store.putAccess(access, { ljwt, wsid, scope, expiresAt: now() + ACCESS_TTL });
|
|
461
|
-
await store.putRefresh(refresh, { ljwt, wsid, client_id, scope, expiresAt: now() + REFRESH_TTL });
|
|
477
|
+
await store.putAccess(sha256hex(access), { ljwt, wsid, scope, expiresAt: now() + ACCESS_TTL });
|
|
478
|
+
await store.putRefresh(sha256hex(refresh), { ljwt, wsid, client_id, scope, expiresAt: now() + REFRESH_TTL });
|
|
462
479
|
return { access_token: access, token_type: "Bearer", expires_in: Math.floor(ACCESS_TTL / 1000), refresh_token: refresh, scope };
|
|
463
480
|
}
|
|
464
481
|
export async function exchangeToken(p) {
|
|
465
482
|
const store = await getStore();
|
|
466
483
|
if (p.grant_type === "authorization_code") {
|
|
467
|
-
const c = p.code ? await store.takeCode(p.code) : undefined; // one-time use
|
|
484
|
+
const c = p.code ? await store.takeCode(sha256hex(p.code)) : undefined; // one-time use
|
|
468
485
|
if (!c) {
|
|
469
486
|
return { ok: false, status: 400, error: "invalid_grant", error_description: "Unknown or expired authorization code." };
|
|
470
487
|
}
|
|
@@ -480,9 +497,11 @@ export async function exchangeToken(p) {
|
|
|
480
497
|
return { ok: true, body: await issueTokens(store, c.ljwt, c.wsid, c.client_id, c.scope) };
|
|
481
498
|
}
|
|
482
499
|
if (p.grant_type === "refresh_token") {
|
|
483
|
-
|
|
500
|
+
// Rotate — but only for the client the token was issued to: another client_id finds nothing (and
|
|
501
|
+
// burns nothing); a request without client_id keeps the binding it already has.
|
|
502
|
+
const r = p.refresh_token ? await store.takeRefresh(sha256hex(p.refresh_token), p.client_id) : undefined;
|
|
484
503
|
if (!r) {
|
|
485
|
-
return { ok: false, status: 400, error: "invalid_grant", error_description: "Unknown or expired refresh token." };
|
|
504
|
+
return { ok: false, status: 400, error: "invalid_grant", error_description: "Unknown or expired refresh token, or not issued to this client_id." };
|
|
486
505
|
}
|
|
487
506
|
if (await isDeadJwt(r.ljwt)) {
|
|
488
507
|
return { ok: false, status: 400, error: "invalid_grant", error_description: "Webcake session expired — sign in again (Connect)." };
|
|
@@ -496,14 +515,14 @@ export async function exchangeToken(p) {
|
|
|
496
515
|
export async function resolveAccessToken(accessToken) {
|
|
497
516
|
if (!accessToken)
|
|
498
517
|
return undefined;
|
|
499
|
-
const a = await (await getStore()).getAccess(accessToken);
|
|
518
|
+
const a = await (await getStore()).getAccess(sha256hex(accessToken));
|
|
500
519
|
return a && !isDeadLocally(a.ljwt) ? { ljwt: a.ljwt, wsid: a.wsid } : undefined;
|
|
501
520
|
}
|
|
502
521
|
/** Revoke an access or refresh token (best-effort; for /revoke). */
|
|
503
522
|
export async function revokeToken(t) {
|
|
504
523
|
if (!t)
|
|
505
524
|
return;
|
|
506
|
-
await (await getStore()).revoke(t);
|
|
525
|
+
await (await getStore()).revoke(sha256hex(t));
|
|
507
526
|
}
|
|
508
527
|
// ---- Metadata documents (RFC 8414 / RFC 9728) -----------------------------
|
|
509
528
|
/** /.well-known/oauth-authorization-server */
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* At-rest protection for the OAuth store (see ./oauth-server.ts, ../persistence/postgres.ts).
|
|
3
|
+
*
|
|
4
|
+
* - Bearer secrets (access/refresh tokens, authorization codes) are stored and looked up by
|
|
5
|
+
* `sha256hex(token)` only: a leaked table row can't be replayed.
|
|
6
|
+
* - The wrapped Webcake credential (ljwt, wsid) is AES-256-GCM encrypted under
|
|
7
|
+
* WEBCAKE_TOKEN_KEY (base64 of 32 bytes) as `enc:v1:` + base64(iv(12) | tag(16) | ciphertext).
|
|
8
|
+
* A value without the prefix is legacy plaintext and passes through unchanged; with no key
|
|
9
|
+
* set, new values are stored as plaintext too, so a deploy works before the secret exists.
|
|
10
|
+
*/
|
|
11
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
|
|
12
|
+
export const ENC_PREFIX = "enc:v1:";
|
|
13
|
+
export const sha256hex = (s) => createHash("sha256").update(s).digest("hex");
|
|
14
|
+
/** Decode WEBCAKE_TOKEN_KEY. Unset → null; anything but canonical base64 of 32 bytes throws. */
|
|
15
|
+
export function parseTokenKey(raw) {
|
|
16
|
+
const s = (raw ?? "").trim();
|
|
17
|
+
if (!s)
|
|
18
|
+
return null;
|
|
19
|
+
const k = Buffer.from(s, "base64");
|
|
20
|
+
// Buffer.from silently skips junk, so require a canonical round trip, not just the length.
|
|
21
|
+
if (k.length !== 32 || k.toString("base64") !== s) {
|
|
22
|
+
throw new Error("WEBCAKE_TOKEN_KEY must be base64 of exactly 32 bytes (openssl rand -base64 32)");
|
|
23
|
+
}
|
|
24
|
+
return k;
|
|
25
|
+
}
|
|
26
|
+
let key;
|
|
27
|
+
const tokenKey = () => (key === undefined ? (key = parseTokenKey(process.env.WEBCAKE_TOKEN_KEY)) : key);
|
|
28
|
+
/** Throws on a malformed WEBCAKE_TOKEN_KEY — call at startup so a bad secret fails loudly. */
|
|
29
|
+
export const hasTokenKey = () => !!tokenKey();
|
|
30
|
+
/** Encrypt a credential for storage; "" and no-key pass through as plaintext. */
|
|
31
|
+
export function sealCred(v, k = tokenKey()) {
|
|
32
|
+
if (!k || !v)
|
|
33
|
+
return v;
|
|
34
|
+
const iv = randomBytes(12);
|
|
35
|
+
const c = createCipheriv("aes-256-gcm", k, iv);
|
|
36
|
+
const ct = Buffer.concat([c.update(v, "utf8"), c.final()]);
|
|
37
|
+
return ENC_PREFIX + Buffer.concat([iv, c.getAuthTag(), ct]).toString("base64");
|
|
38
|
+
}
|
|
39
|
+
/** Decrypt a stored credential; a value without the prefix is legacy plaintext. */
|
|
40
|
+
export function openCred(v, k = tokenKey()) {
|
|
41
|
+
if (!v || !v.startsWith(ENC_PREFIX))
|
|
42
|
+
return v;
|
|
43
|
+
if (!k)
|
|
44
|
+
throw new Error("stored credential is encrypted but WEBCAKE_TOKEN_KEY is not set");
|
|
45
|
+
const b = Buffer.from(v.slice(ENC_PREFIX.length), "base64");
|
|
46
|
+
const d = createDecipheriv("aes-256-gcm", k, b.subarray(0, 12));
|
|
47
|
+
d.setAuthTag(b.subarray(12, 28));
|
|
48
|
+
return Buffer.concat([d.update(b.subarray(28)), d.final()]).toString("utf8");
|
|
49
|
+
}
|
package/dist/changelog.json
CHANGED
|
@@ -1,4 +1,18 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"v": "1.18.1",
|
|
4
|
+
"d": "01/12/2026",
|
|
5
|
+
"type": "Fixed",
|
|
6
|
+
"en": "OAuth authorization codes and access/refresh tokens issued by the remote HTTP server (serve) are now looked up by their sha256 hash in both the…",
|
|
7
|
+
"vi": "Authorization code và access/refresh token OAuth do remote HTTP server (serve) cấp nay được tra cứu bằng sha256 hash của chúng ở cả in-memory store…"
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
"v": "1.18.0",
|
|
11
|
+
"d": "01/12/2026",
|
|
12
|
+
"type": "Fixed",
|
|
13
|
+
"en": "The remote HTTP server (serve) now blocks render_preview, ingest_url, clone_page, and image/font re-hosting (upload_images and the automatic re-host…",
|
|
14
|
+
"vi": "Remote HTTP server (serve) nay chặn render_preview, ingest_url, clone_page, và việc re-host ảnh/font (upload_images cùng lượt re-host tự động khi…"
|
|
15
|
+
},
|
|
2
16
|
{
|
|
3
17
|
"v": "1.17.1",
|
|
4
18
|
"d": "01/12/2026",
|
|
@@ -26,19 +40,5 @@
|
|
|
26
40
|
"type": "Fixed",
|
|
27
41
|
"en": "validate_page's text height estimate now matches the renderer's actual line-height: 1.5 default (previously assumed 1.4), so a text-block with no…",
|
|
28
42
|
"vi": "Công thức ước lượng chiều cao chữ của validate_page nay khớp với giá trị line-height: 1.5 thật của renderer (trước đó giả định 1.4), nên một…"
|
|
29
|
-
},
|
|
30
|
-
{
|
|
31
|
-
"v": "1.16.0",
|
|
32
|
-
"d": "25/11/2026",
|
|
33
|
-
"type": "Added",
|
|
34
|
-
"en": "list_pages, find_pages, get_page, update_page, add_section, patch_page, and publish_page now accept an organization_id argument (an organization id,…",
|
|
35
|
-
"vi": "list_pages, find_pages, get_page, update_page, add_section, patch_page và publish_page nay nhận thêm tham số organization_id (một id tổ chức, hoặc…"
|
|
36
|
-
},
|
|
37
|
-
{
|
|
38
|
-
"v": "1.15.0",
|
|
39
|
-
"d": "23/11/2026",
|
|
40
|
-
"type": "Added",
|
|
41
|
-
"en": "api_find/api_get/api_call's route catalog now includes get:/api/v1/pages/options, a slim, filterable page list endpoint on the Webcake backend.",
|
|
42
|
-
"vi": "Danh mục route của api_find/api_get/api_call nay có thêm get:/api/v1/pages/options, một endpoint lấy danh sách trang dạng gọn, lọc được, trên…"
|
|
43
43
|
}
|
|
44
44
|
]
|
package/dist/http.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
*
|
|
12
12
|
* All logging stays on stderr (console.error), same as stdio mode.
|
|
13
13
|
*/
|
|
14
|
-
import { randomUUID } from "node:crypto";
|
|
14
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
15
15
|
import { readFileSync } from "node:fs";
|
|
16
16
|
import { createServer as createHttpServer } from "node:http";
|
|
17
17
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
@@ -21,10 +21,11 @@ import { ICON_SVG, ICON_MIME } from "./branding.js";
|
|
|
21
21
|
import { guideHtml, ogImageSvg, normalizeLang } from "./web-guide.js";
|
|
22
22
|
import { privacyHtml, termsHtml } from "./legal.js";
|
|
23
23
|
import { searchPexels, resolvePexelsKey } from "./persistence/pexels-client.js";
|
|
24
|
-
import { captureWithPlaywright, captureTilesWithPlaywright,
|
|
25
|
-
import { resolveEnv, ENVIRONMENTS, stripTrailingSlash } from "./persistence/config.js";
|
|
24
|
+
import { captureWithPlaywright, captureTilesWithPlaywright, assertPublicUrl, setSsrfGuard } from "./persistence/screenshot-playwright.js";
|
|
25
|
+
import { resolveEnv, ENVIRONMENTS, stripTrailingSlash, readConfig, configFromHeaders } from "./persistence/config.js";
|
|
26
|
+
import { listOrganizations } from "./persistence/webcake-client.js";
|
|
26
27
|
import { buildConnectUrl } from "./auth/login.js";
|
|
27
|
-
import { registerClient, startAuthorize, completeAuthorize, exchangeToken, resolveAccessToken, isDeadJwt, revokeToken, pendingCookieName, authServerMetadata, protectedResourceMetadata, } from "./auth/oauth-server.js";
|
|
28
|
+
import { registerClient, startAuthorize, completeAuthorize, exchangeToken, resolveAccessToken, isDeadJwt, markJwtDead, revokeToken, initOAuthStore, pendingCookieName, authServerMetadata, protectedResourceMetadata, } from "./auth/oauth-server.js";
|
|
28
29
|
const MCP_PATH = "/mcp";
|
|
29
30
|
const IMAGES_PATH = "/api/images/search";
|
|
30
31
|
const RENDER_SCREENSHOT_PATH = "/api/render/screenshot";
|
|
@@ -94,11 +95,13 @@ function sendJson(res, status, body) {
|
|
|
94
95
|
function rpcError(res, status, message) {
|
|
95
96
|
sendJson(res, status, { jsonrpc: "2.0", error: { code: -32000, message }, id: null });
|
|
96
97
|
}
|
|
98
|
+
// Bodies are buffered whole, so cap them: create_page payloads are big (nginx allows 20m), OAuth forms tiny.
|
|
99
|
+
const MCP_BODY_MAX = 20 * 1024 * 1024;
|
|
100
|
+
const OAUTH_BODY_MAX = 64 * 1024;
|
|
101
|
+
class BodyTooLarge extends Error {
|
|
102
|
+
}
|
|
97
103
|
async function readBody(req) {
|
|
98
|
-
const
|
|
99
|
-
for await (const c of req)
|
|
100
|
-
chunks.push(c);
|
|
101
|
-
const raw = Buffer.concat(chunks).toString("utf8").trim();
|
|
104
|
+
const raw = await readRawBody(req, MCP_BODY_MAX);
|
|
102
105
|
return raw ? JSON.parse(raw) : undefined;
|
|
103
106
|
}
|
|
104
107
|
// Map credentials passed in the URL query (e.g. .../mcp?jwt=<token>) onto the
|
|
@@ -183,11 +186,33 @@ function connectPageUrl() {
|
|
|
183
186
|
const appBase = stripTrailingSlash(process.env.WEBCAKE_APP_BASE || preset.appBase);
|
|
184
187
|
return `${appBase}/mcp-connect`;
|
|
185
188
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
189
|
+
function readRawBody(req, max = OAUTH_BODY_MAX) {
|
|
190
|
+
return new Promise((resolve, reject) => {
|
|
191
|
+
// Over the cap: stop buffering but keep draining (resume) — destroying the stream resets the
|
|
192
|
+
// socket and the client never sees the 413.
|
|
193
|
+
const overflow = () => {
|
|
194
|
+
req.removeAllListeners("data");
|
|
195
|
+
req.resume();
|
|
196
|
+
reject(new BodyTooLarge());
|
|
197
|
+
};
|
|
198
|
+
if (Number(req.headers["content-length"]) > max)
|
|
199
|
+
return overflow();
|
|
200
|
+
const chunks = [];
|
|
201
|
+
let total = 0;
|
|
202
|
+
req.on("data", (c) => {
|
|
203
|
+
total += c.length;
|
|
204
|
+
if (total > max)
|
|
205
|
+
overflow();
|
|
206
|
+
else
|
|
207
|
+
chunks.push(c);
|
|
208
|
+
});
|
|
209
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8").trim()));
|
|
210
|
+
req.on("error", reject);
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
function tooLarge(res) {
|
|
214
|
+
res.writeHead(413, { "content-type": "application/json" });
|
|
215
|
+
res.end(JSON.stringify({ error: "payload_too_large" }));
|
|
191
216
|
}
|
|
192
217
|
/** Parse a request body that may be JSON or application/x-www-form-urlencoded. */
|
|
193
218
|
function parseBodyParams(raw, contentType) {
|
|
@@ -215,6 +240,11 @@ function htmlError(res, status, message) {
|
|
|
215
240
|
res.writeHead(status, { "content-type": "text/html; charset=utf-8" });
|
|
216
241
|
res.end(`<!doctype html><meta charset="utf-8"><body style="font-family:system-ui;padding:40px;max-width:520px;margin:auto"><h2>Webcake connector</h2><p>${message}</p></body>`);
|
|
217
242
|
}
|
|
243
|
+
// Moves token/wsid/state from the #fragment (query as fallback) into a same-origin POST form, so
|
|
244
|
+
// the SameSite=Lax pending cookie rides along, and wipes them from the address bar first.
|
|
245
|
+
const CALLBACK_SCRIPT = `var h=new URLSearchParams(location.hash.slice(1)),q=new URLSearchParams(location.search),f=document.forms[0];["token","wsid","state"].forEach(function(k){f.elements[k].value=h.get(k)||q.get(k)||""});history.replaceState(null,"",location.pathname);f.submit();`;
|
|
246
|
+
const CALLBACK_CSP = `default-src 'none'; script-src 'sha256-${createHash("sha256").update(CALLBACK_SCRIPT).digest("base64")}'; base-uri 'none'; frame-ancestors 'none'`;
|
|
247
|
+
const CALLBACK_PAGE = `<!doctype html><meta charset="utf-8"><title>Webcake connector</title><form method="post" action="${OAUTH_CALLBACK}"><input type="hidden" name="token"><input type="hidden" name="wsid"><input type="hidden" name="state"><noscript>Enable JavaScript to finish connecting.</noscript></form><script>${CALLBACK_SCRIPT}</script>`;
|
|
218
248
|
/**
|
|
219
249
|
* Handle every OAuth 2.1 endpoint. Returns true when the request was an OAuth
|
|
220
250
|
* route (and a response was sent), false to let the caller continue routing.
|
|
@@ -284,14 +314,29 @@ async function handleOAuth(req, res, path) {
|
|
|
284
314
|
}
|
|
285
315
|
// Send the user to the SPA login; it returns here with ?token=<ljwt>[&wsid=<lwsid>]&state=<internalState>.
|
|
286
316
|
const callback = `${issuer}${OAUTH_CALLBACK}`;
|
|
287
|
-
|
|
317
|
+
// client_host + client_name let the consent page show who is asking and where the code goes.
|
|
318
|
+
const loginUrl = buildConnectUrl(connectPageUrl(), callback, result.internalState, {
|
|
319
|
+
client_host: new URL(sp.get("redirect_uri")).hostname,
|
|
320
|
+
client_name: result.clientName ? Array.from(result.clientName).slice(0, 60).join("") : undefined,
|
|
321
|
+
});
|
|
288
322
|
const c = pendingCookie(issuer, result.internalState);
|
|
289
323
|
res.writeHead(302, { location: loginUrl, "set-cookie": `${c.name}=1; Max-Age=600${c.attrs}` });
|
|
290
324
|
return res.end(), true;
|
|
291
325
|
}
|
|
292
326
|
// ---- Login callback: the SPA handed back the user's ljwt → mint a code ----
|
|
293
|
-
|
|
294
|
-
|
|
327
|
+
// Legacy: GET ?token=&wsid=&state=. Preferred: the SPA puts them in the #fragment (never sent to a
|
|
328
|
+
// server or logged); GET then serves CALLBACK_PAGE, which re-POSTs them here from the same origin.
|
|
329
|
+
if (path === OAUTH_CALLBACK && (req.method === "GET" || req.method === "POST")) {
|
|
330
|
+
const sp = req.method === "POST" ? new URLSearchParams(await readRawBody(req)) : new URL(req.url ?? "/", "http://x").searchParams;
|
|
331
|
+
if (req.method === "GET" && !sp.get("token")) {
|
|
332
|
+
res.writeHead(200, {
|
|
333
|
+
"content-type": "text/html; charset=utf-8",
|
|
334
|
+
"cache-control": "no-store",
|
|
335
|
+
"referrer-policy": "no-referrer",
|
|
336
|
+
"content-security-policy": CALLBACK_CSP,
|
|
337
|
+
});
|
|
338
|
+
return res.end(CALLBACK_PAGE), true;
|
|
339
|
+
}
|
|
295
340
|
// Only the browser that opened /authorize may complete it — otherwise a link carrying
|
|
296
341
|
// someone else's state binds the victim's login to the attacker's client.
|
|
297
342
|
const state = sp.get("state");
|
|
@@ -306,7 +351,7 @@ async function handleOAuth(req, res, path) {
|
|
|
306
351
|
r.searchParams.set("code", done.code);
|
|
307
352
|
if (done.state)
|
|
308
353
|
r.searchParams.set("state", done.state);
|
|
309
|
-
res.writeHead(302, { location: r.toString(), "set-cookie": `${c.name}=; Max-Age=0${c.attrs}
|
|
354
|
+
res.writeHead(302, { location: r.toString(), "set-cookie": `${c.name}=; Max-Age=0${c.attrs}`, "referrer-policy": "no-referrer" });
|
|
310
355
|
return res.end(), true;
|
|
311
356
|
}
|
|
312
357
|
// ---- Token ----
|
|
@@ -404,15 +449,20 @@ async function handleRenderScreenshot(req, res) {
|
|
|
404
449
|
const target = sp.get("url")?.trim();
|
|
405
450
|
if (!target)
|
|
406
451
|
return sendErr(400, { ok: false, error: "Pass ?url=<public http(s) URL>." });
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
452
|
+
try {
|
|
453
|
+
await assertPublicUrl(target);
|
|
454
|
+
}
|
|
455
|
+
catch (e) {
|
|
456
|
+
return sendErr(400, { ok: false, error: e.message });
|
|
457
|
+
}
|
|
410
458
|
const fullPage = sp.get("full_page") !== "false";
|
|
411
|
-
|
|
459
|
+
// Clamped: a huge viewport / band is a cheap way to exhaust the host's memory.
|
|
460
|
+
const clamp = (v, lo, hi) => (v && Number.isFinite(Number(v)) ? Math.min(hi, Math.max(lo, Number(v))) : undefined);
|
|
461
|
+
const width = clamp(sp.get("width"), 320, 1920);
|
|
412
462
|
// Tiles mode: split a tall page into horizontal bands, returned as a JSON array
|
|
413
463
|
// of base64 images (top→bottom) so the model reads each slice at a readable size.
|
|
414
464
|
if (sp.get("tiles") === "1" || sp.get("tiles") === "true") {
|
|
415
|
-
const bandHeight = sp.get("band_height")
|
|
465
|
+
const bandHeight = clamp(sp.get("band_height"), 200, 4000);
|
|
416
466
|
const t = await captureTilesWithPlaywright(target, { width, bandHeight });
|
|
417
467
|
if (!t.ok)
|
|
418
468
|
return sendErr(t.reason === "not_installed" ? 503 : 502, { ok: false, error: t.error });
|
|
@@ -434,9 +484,37 @@ async function handleRenderScreenshot(req, res) {
|
|
|
434
484
|
res.writeHead(200, { "content-type": r.mimeType, "cache-control": "no-store", ...cors });
|
|
435
485
|
return res.end(r.data);
|
|
436
486
|
}
|
|
487
|
+
// Each session holds a whole McpServer in memory: close idle ones, cap the total, and cap each
|
|
488
|
+
// credential so one caller can't evict everyone else's sessions.
|
|
489
|
+
const SESSION_IDLE_MS = 30 * 60_000;
|
|
490
|
+
const MAX_SESSIONS = 500;
|
|
491
|
+
const MAX_SESSIONS_PER_CRED = 20;
|
|
437
492
|
export async function startHttpServer(port) {
|
|
438
|
-
//
|
|
493
|
+
setSsrfGuard(true); // hosted: caller-chosen URLs must not reach this host's private network
|
|
494
|
+
await initOAuthStore(); // a malformed WEBCAKE_TOKEN_KEY fails here; runs the at-rest migration
|
|
495
|
+
// mcp-session-id -> live session (each bound to its own McpServer instance), in least-recently-used
|
|
496
|
+
// order: a request re-inserts its session at the end, so the oldest idle ones sit first. `busy`
|
|
497
|
+
// counts open responses (incl. SSE streams); a busy session is never evicted.
|
|
439
498
|
const transports = new Map();
|
|
499
|
+
const evict = (id) => {
|
|
500
|
+
const s = transports.get(id);
|
|
501
|
+
transports.delete(id);
|
|
502
|
+
s?.transport.close().catch(() => { });
|
|
503
|
+
};
|
|
504
|
+
/** Oldest session that is not mid-request (of `cred` when given); undefined when all are busy. */
|
|
505
|
+
const oldestIdle = (cred) => {
|
|
506
|
+
for (const [id, s] of transports)
|
|
507
|
+
if (!s.busy && (cred === undefined || s.cred === cred))
|
|
508
|
+
return id;
|
|
509
|
+
};
|
|
510
|
+
setInterval(() => {
|
|
511
|
+
for (const [id, s] of transports) {
|
|
512
|
+
if (Date.now() - s.seen < SESSION_IDLE_MS)
|
|
513
|
+
break;
|
|
514
|
+
if (!s.busy)
|
|
515
|
+
evict(id);
|
|
516
|
+
}
|
|
517
|
+
}, 60_000).unref();
|
|
440
518
|
const httpServer = createHttpServer(async (req, res) => {
|
|
441
519
|
const path = (req.url ?? "").split("?")[0];
|
|
442
520
|
// Brand icon — clients (e.g. the claude.ai connector) fetch a favicon from the
|
|
@@ -505,8 +583,15 @@ export async function startHttpServer(port) {
|
|
|
505
583
|
if (path === RENDER_SCREENSHOT_PATH)
|
|
506
584
|
return handleRenderScreenshot(req, res);
|
|
507
585
|
// OAuth 2.1 endpoints (always served; see handleOAuth). Returns true if handled.
|
|
508
|
-
|
|
509
|
-
|
|
586
|
+
try {
|
|
587
|
+
if (await handleOAuth(req, res, path))
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
catch (err) {
|
|
591
|
+
if (err instanceof BodyTooLarge)
|
|
592
|
+
return tooLarge(res);
|
|
593
|
+
throw err;
|
|
594
|
+
}
|
|
510
595
|
if (path !== MCP_PATH)
|
|
511
596
|
return rpcError(res, 404, `Not found. Send MCP requests to ${MCP_PATH}.`);
|
|
512
597
|
// Accept credentials via ?jwt=/?env=/... (for clients that can't set headers).
|
|
@@ -530,24 +615,35 @@ export async function startHttpServer(port) {
|
|
|
530
615
|
// WWW-Authenticate so Claude/ChatGPT (re)open the Connect page by themselves. In
|
|
531
616
|
// enforced mode a raw JWT must use x-webcake-jwt / ?jwt=, since Bearer is reserved
|
|
532
617
|
// for OAuth access tokens.
|
|
533
|
-
const
|
|
534
|
-
const
|
|
535
|
-
|
|
618
|
+
const givenRaw = req.headers["x-webcake-jwt"];
|
|
619
|
+
const given = Array.isArray(givenRaw) ? givenRaw[0] : givenRaw;
|
|
620
|
+
const unauthorized = (why) => {
|
|
536
621
|
res.writeHead(401, {
|
|
537
622
|
"www-authenticate": `Bearer error="invalid_token", resource_metadata="${publicBase(req)}${WELL_KNOWN_PR}"`,
|
|
538
623
|
"content-type": "application/json",
|
|
539
624
|
});
|
|
540
|
-
|
|
541
|
-
|
|
625
|
+
res.end(JSON.stringify({ error: "invalid_token", error_description: why }));
|
|
626
|
+
};
|
|
627
|
+
const dead = await isDeadJwt(given);
|
|
628
|
+
if (OAUTH_ENFORCED && (!given || dead)) {
|
|
629
|
+
return unauthorized(dead ? "Webcake session expired — reconnect (Connect) to renew it." : "Authentication required — connect via OAuth.");
|
|
542
630
|
}
|
|
631
|
+
const cred = createHash("sha256").update(given ?? "").digest("hex");
|
|
543
632
|
const sidHeader = req.headers["mcp-session-id"];
|
|
544
633
|
const sessionId = Array.isArray(sidHeader) ? sidHeader[0] : sidHeader;
|
|
545
634
|
try {
|
|
546
635
|
// Existing session: delegate any method (POST/GET/DELETE) to its transport.
|
|
547
636
|
if (sessionId && transports.has(sessionId)) {
|
|
548
|
-
const
|
|
637
|
+
const s = transports.get(sessionId);
|
|
638
|
+
transports.delete(sessionId);
|
|
639
|
+
transports.set(sessionId, s);
|
|
640
|
+
s.busy++;
|
|
641
|
+
res.on("close", () => {
|
|
642
|
+
s.busy--;
|
|
643
|
+
s.seen = Date.now();
|
|
644
|
+
});
|
|
549
645
|
const body = req.method === "POST" ? await readBody(req) : undefined;
|
|
550
|
-
await transport.handleRequest(req, res, body);
|
|
646
|
+
await s.transport.handleRequest(req, res, body);
|
|
551
647
|
return;
|
|
552
648
|
}
|
|
553
649
|
// Unknown session (e.g. sessions are in-memory and the server restarted):
|
|
@@ -559,10 +655,29 @@ export async function startHttpServer(port) {
|
|
|
559
655
|
if (req.method === "POST") {
|
|
560
656
|
const body = await readBody(req);
|
|
561
657
|
if (!sessionId && isInitializeRequest(body)) {
|
|
658
|
+
// Presence is not proof: a made-up JWT must not open sessions (and evict real ones). Ask the
|
|
659
|
+
// backend once per credential — a live session of the same credential already proved it.
|
|
660
|
+
// Only a 401 refuses; a timeout / 5xx lets it through as before.
|
|
661
|
+
if (OAUTH_ENFORCED && ![...transports.values()].some((t) => t.cred === cred)) {
|
|
662
|
+
const { config } = readConfig(configFromHeaders(req.headers));
|
|
663
|
+
if (config && (await listOrganizations(config)).status === 401) {
|
|
664
|
+
await markJwtDead(given);
|
|
665
|
+
return unauthorized("Webcake rejected this token — reconnect (Connect) to renew it.");
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
let mine = 0;
|
|
669
|
+
for (const t of transports.values())
|
|
670
|
+
if (t.cred === cred)
|
|
671
|
+
mine++;
|
|
672
|
+
const victim = mine >= MAX_SESSIONS_PER_CRED ? oldestIdle(cred) : transports.size >= MAX_SESSIONS ? oldestIdle() : null;
|
|
673
|
+
if (victim === undefined)
|
|
674
|
+
return rpcError(res, 429, "Too many open sessions — close one and retry.");
|
|
675
|
+
if (victim)
|
|
676
|
+
evict(victim);
|
|
562
677
|
const transport = new StreamableHTTPServerTransport({
|
|
563
678
|
sessionIdGenerator: () => randomUUID(),
|
|
564
679
|
onsessioninitialized: (id) => {
|
|
565
|
-
transports.set(id, transport);
|
|
680
|
+
transports.set(id, { transport, seen: Date.now(), cred, busy: 0 });
|
|
566
681
|
},
|
|
567
682
|
});
|
|
568
683
|
transport.onclose = () => {
|
|
@@ -579,6 +694,8 @@ export async function startHttpServer(port) {
|
|
|
579
694
|
return rpcError(res, 400, "Bad Request: missing or unknown mcp-session-id.");
|
|
580
695
|
}
|
|
581
696
|
catch (err) {
|
|
697
|
+
if (err instanceof BodyTooLarge)
|
|
698
|
+
return tooLarge(res);
|
|
582
699
|
console.error("[webcake-http] request error:", err);
|
|
583
700
|
if (!res.headersSent)
|
|
584
701
|
rpcError(res, 500, "Internal server error.");
|