sbuilder-mcp 0.106.0 → 0.107.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/CHANGELOG.md CHANGED
@@ -6,6 +6,22 @@ All notable changes to this project are documented in this file.
6
6
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
7
7
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
8
8
 
9
+ ## [0.107.1] - 2026-11-18
10
+
11
+ ### Fixed
12
+ - `sb_store` `site_template` works with only a site API key, reading the template's eligibility and assigned categories from the site's own template route instead of the session-only category list.
13
+ - `sb_store` `site_template` falls back to the shared category list when the server does not report `fileable`, so it no longer wrongly says the site is not in the platform organization.
14
+
15
+ ## [0.107.0] - 2026-11-18
16
+
17
+ ### Added
18
+ - `sb_store` `site_template` with `dry_run: false` captures a 1440×1080 screenshot of the published home page and uploads it as the template's gallery preview image, so templates built by an agent no longer appear without one.
19
+ - `sb_store` `site_template` refuses to upload a preview when the home page is a 404 or blank, and reports a failed capture as a note while keeping the template marking.
20
+ - `sb_store` `site_template` dry run returns `already_template.categories` with the categories currently assigned to a site that is already a template.
21
+
22
+ ### Changed
23
+ - Screenshot capture for template previews routes every browser request through a local egress proxy that resolves DNS itself and connects only to public unicast addresses, so a custom domain or authored page cannot reach loopback, private or metadata addresses; it allows https only, blocks service workers, and is skipped only when the API base is itself local.
24
+
9
25
  ## [0.106.0] - 2026-11-18
10
26
 
11
27
  ### Added
package/CHANGELOG.vi.md CHANGED
@@ -6,6 +6,22 @@ Mọi thay đổi đáng chú ý của dự án được ghi lại trong file n
6
6
  Định dạng dựa trên [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
7
7
  và dự án tuân theo [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
8
8
 
9
+ ## [0.107.1] - 2026-11-18
10
+
11
+ ### Fixed
12
+ - `sb_store` `site_template` chạy được chỉ với API key của site, đọc khả năng đánh dấu mẫu và các danh mục đang gán từ route template của chính site thay vì danh sách danh mục chỉ nhận phiên đăng nhập.
13
+ - `sb_store` `site_template` quay về danh sách danh mục chung khi máy chủ chưa trả `fileable`, nên không còn báo nhầm site không thuộc tổ chức nền tảng.
14
+
15
+ ## [0.107.0] - 2026-11-18
16
+
17
+ ### Added
18
+ - `sb_store` `site_template` với `dry_run: false` chụp khung 1440×1080 của trang chủ đã xuất bản và tải lên làm ảnh xem trước của mẫu trong thư viện, nên mẫu do agent dựng không còn thiếu ảnh.
19
+ - `sb_store` `site_template` từ chối tải ảnh xem trước khi trang chủ là 404 hoặc trống, và báo lỗi chụp như một ghi chú trong khi vẫn giữ việc đánh dấu mẫu.
20
+ - Bản chạy thử của `sb_store` `site_template` trả về `already_template.categories` với các danh mục đang gán cho site vốn đã là mẫu.
21
+
22
+ ### Changed
23
+ - Việc chụp ảnh xem trước của mẫu cho mọi request của trình duyệt đi qua một proxy egress cục bộ tự tra DNS và chỉ nối tới địa chỉ unicast công khai, nên tên miền riêng hay trang do tác giả viết không thể truy cập địa chỉ loopback, mạng nội bộ hay metadata; proxy chỉ cho phép https, chặn service worker, và chỉ được bỏ qua khi API base chính là máy local.
24
+
9
25
  ## [0.106.0] - 2026-11-18
10
26
 
11
27
  ### Added
@@ -1,4 +1,5 @@
1
1
  import { request } from '../transport/http.js';
2
+ import { snapshot } from '../vision/shoot.js';
2
3
  import { siteToken } from './credentialpick.js';
3
4
  import { siteFor } from './context.js';
4
5
  import { addSubtree, removeNode } from '../domains/site/builder.js';
@@ -916,11 +917,40 @@ export async function markSiteTemplate(ctx, siteId, name, opts) {
916
917
  throw new Error('sbuilder: this site belongs to no organization, and a template is an organization\'s — pass org_id (the platform organization\'s, for the public gallery).');
917
918
  }
918
919
  const org = (attach ?? orgId);
919
- const listed = await get(`/api/templates/categories?locale=${encodeURIComponent(opts.language ?? 'vi')}&orgId=${encodeURIComponent(org)}`);
920
- const cats = listed.categories ?? [];
920
+ const locale = encodeURIComponent(opts.language ?? 'vi');
921
+ // Already in its org: ONE site-scoped read answers the catalogue, whether it
922
+ // files, and the current filing — and it takes the site's API key, which the
923
+ // session-only /api/templates/categories refuses (an agent of the platform org
924
+ // connected by key could not mark at all). Attaching needs a session anyway (a
925
+ // key cannot move a site between orgs), so only that path reads the global list.
926
+ let cats = [];
927
+ let fileable = false;
928
+ let filed = [];
929
+ const global = async () => {
930
+ const listed = await get(`/api/templates/categories?locale=${locale}&orgId=${encodeURIComponent(org)}`);
931
+ cats = listed.categories ?? [];
932
+ fileable = !!listed.fileable;
933
+ };
934
+ if (attach) {
935
+ await global();
936
+ }
937
+ else {
938
+ const { template: t } = await get(`${sitePath}/template?locale=${locale}`);
939
+ if (site?.isTemplate)
940
+ filed = t?.categories ?? [];
941
+ if (typeof t?.fileable === 'boolean') {
942
+ cats = t.available ?? [];
943
+ fileable = t.fileable;
944
+ }
945
+ else {
946
+ // A platform older than web_builder v1.0.275 does not say: ask the global
947
+ // list rather than call a platform author "not the platform organization".
948
+ await global();
949
+ }
950
+ }
921
951
  // Only the platform org's templates reach the gallery; refusing HERE keeps a
922
952
  // mark from landing with a filing the server would then reject.
923
- if (opts.categories?.length && !listed.fileable) {
953
+ if (opts.categories?.length && !fileable) {
924
954
  throw new Error(`sbuilder: organization ${org} is not the platform organization, so its templates have no gallery categories — drop categories (its members see the template on their own shelf).`);
925
955
  }
926
956
  const chosen = opts.categories?.length
@@ -931,7 +961,9 @@ export async function markSiteTemplate(ctx, siteId, name, opts) {
931
961
  site: site?.name,
932
962
  organization: attach ?? orgId,
933
963
  pages: pages.pages?.map((p) => p.name ?? p.slug),
934
- ...(site?.isTemplate ? { already_template: { name: site.templateName, description: site.templateDescription } } : {}),
964
+ ...(site?.isTemplate
965
+ ? { already_template: { name: site.templateName, description: site.templateDescription, ...(filed.length ? { categories: filed } : {}) } }
966
+ : {}),
935
967
  };
936
968
  if (!opts.dryRun && !name?.trim()) {
937
969
  throw new Error('sbuilder: action:"site_template" needs name — run it as a dry run first to read the pages and the categories, then name it.');
@@ -942,7 +974,7 @@ export async function markSiteTemplate(ctx, siteId, name, opts) {
942
974
  ...state,
943
975
  ...(attach ? { would_attach_to: attach } : {}),
944
976
  would_mark: { name: name?.trim(), description, categories: chosen?.map((c) => c.slug) },
945
- ...(listed.fileable
977
+ ...(fileable
946
978
  ? { categories_available: catalogue(cats) }
947
979
  : { categories_available: [], note: 'not the platform organization — no gallery categories; the template goes on its members\' shelf' }),
948
980
  write: 'Name the template for the business it starts ("Shop thời trang nữ", not "Template 1"), write ONE sentence ' +
@@ -972,7 +1004,32 @@ export async function markSiteTemplate(ctx, siteId, name, opts) {
972
1004
  .join('; ');
973
1005
  throw new Error(done ? `${msg} (${done} — re-run site_template to retry the rest)` : msg);
974
1006
  }
1007
+ // THE CARD'S PICTURE. A screenshot is otherwise taken only when a person sits
1008
+ // on the dashboard, so an agent-built template reached the gallery blank.
1009
+ // Best effort: the mark already stands, so a failure is a note, not an error.
1010
+ let picture;
1011
+ try {
1012
+ if (!site?.publicUrl)
1013
+ throw new Error('the site has no public address yet');
1014
+ // Private addresses are allowed only when the PLATFORM itself is local (dev,
1015
+ // where every storefront is *.localhost) — never steered there by a domain.
1016
+ const local = ['localhost', '127.0.0.1', '::1', '[::1]'].includes(new URL(ctx.base).hostname) || new URL(ctx.base).hostname.endsWith('.localhost');
1017
+ const jpeg = await snapshot(new URL(site.publicUrl, ctx.base).toString(), { allowPrivate: local });
1018
+ await request({
1019
+ base: ctx.base,
1020
+ method: 'PUT',
1021
+ path: `${sitePath}/preview`,
1022
+ token: siteToken(ctx),
1023
+ body: new Blob([jpeg], { type: 'image/jpeg' }),
1024
+ fetchImpl: ctx.fetchImpl,
1025
+ });
1026
+ picture = 'captured from the published homepage';
1027
+ }
1028
+ catch (e) {
1029
+ picture = `not captured (${e.message}) — publish the homepage, then re-run site_template`;
1030
+ }
975
1031
  return {
1032
+ picture,
976
1033
  template: { site_id: siteId, name: name.trim(), ...(description ? { description } : {}), ...(chosen ? { categories: chosen.map((c) => c.slug) } : {}) },
977
1034
  ...(attach ? { attached_to: attach } : {}),
978
1035
  next: 'Publish every page first — the gallery card shows the published storefront. On the platform organization an ' +
@@ -0,0 +1,131 @@
1
+ import { createServer } from 'node:http';
2
+ import { connect, isIP, BlockList } from 'node:net';
3
+ import { lookup } from 'node:dns/promises';
4
+ /**
5
+ * EGRESS POLICY for a headless browser pointed at a page someone else controls.
6
+ *
7
+ * A custom domain is DNS its owner controls and a page is markup its author
8
+ * controls, so either can aim the operator's local Chrome at their own network
9
+ * (127.0.0.1, 10.x, 169.254.169.254…) — and a screenshot of that would be
10
+ * uploaded to the author's site. Checking a URL before navigating is not enough:
11
+ * a redirect, a subresource, a service worker or a DNS answer that changes
12
+ * between the check and the connect (rebinding) all walk past it.
13
+ *
14
+ * So the browser context talks ONLY to this proxy, and the proxy resolves the
15
+ * name itself, checks the address it is about to dial, and dials THAT address.
16
+ * Deny by default: only global unicast passes.
17
+ */
18
+ const v4Reserved = new BlockList();
19
+ for (const [net, bits] of [
20
+ ['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16],
21
+ ['172.16.0.0', 12], ['192.0.0.0', 24], ['192.0.2.0', 24], ['192.88.99.0', 24], ['192.168.0.0', 16],
22
+ ['198.18.0.0', 15], ['198.51.100.0', 24], ['203.0.113.0', 24], ['224.0.0.0', 4], ['240.0.0.0', 4],
23
+ ]) {
24
+ v4Reserved.addSubnet(net, bits, 'ipv4');
25
+ }
26
+ /** The 8 hextets of an IPv6 address, or undefined when it does not parse. */
27
+ function hextets(ip) {
28
+ let s = ip.toLowerCase();
29
+ // A dotted tail (::ffff:1.2.3.4) becomes two hextets.
30
+ const dotted = /(\d+\.\d+\.\d+\.\d+)$/.exec(s);
31
+ if (dotted) {
32
+ const o = dotted[1].split('.').map(Number);
33
+ s = s.slice(0, -dotted[1].length) + ((o[0] << 8) | o[1]).toString(16) + ':' + ((o[2] << 8) | o[3]).toString(16);
34
+ }
35
+ const halves = s.split('::');
36
+ if (halves.length > 2)
37
+ return undefined;
38
+ const head = halves[0] ? halves[0].split(':') : [];
39
+ const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
40
+ const fill = halves.length === 2 ? 8 - head.length - tail.length : 0;
41
+ const all = [...head, ...Array(Math.max(fill, 0)).fill('0'), ...tail];
42
+ if (all.length !== 8)
43
+ return undefined;
44
+ const out = all.map((h) => parseInt(h, 16));
45
+ return out.some((n) => Number.isNaN(n) || n < 0 || n > 0xffff) ? undefined : out;
46
+ }
47
+ /**
48
+ * True only for a GLOBAL UNICAST address. IPv6 must be 2000::/3 and not one of
49
+ * the prefixes that tunnel an IPv4 address (6to4, Teredo, NAT64) — those are
50
+ * refused outright rather than unwrapped, as is every IPv4-mapped/compatible form
51
+ * (they fall outside 2000::/3). Anything unparseable is refused.
52
+ */
53
+ export function publicAddress(ip) {
54
+ if (isIP(ip) === 4)
55
+ return !v4Reserved.check(ip, 'ipv4');
56
+ if (isIP(ip) !== 6)
57
+ return false;
58
+ const h = hextets(ip);
59
+ if (!h)
60
+ return false;
61
+ if ((h[0] & 0xe000) !== 0x2000)
62
+ return false; // not 2000::/3
63
+ if (h[0] === 0x2002)
64
+ return false; // 6to4
65
+ if (h[0] === 0x2001 && h[1] === 0x0000)
66
+ return false; // Teredo
67
+ if (h[0] === 0x2001 && h[1] === 0x0db8)
68
+ return false; // documentation
69
+ if (h[0] === 0x0064 && h[1] === 0xff9b)
70
+ return false; // NAT64 (outside 2000::/3 anyway)
71
+ return true;
72
+ }
73
+ /** The address to dial for `host`, or why there is none. Resolves once; the caller dials exactly this. */
74
+ export async function resolvePublic(host) {
75
+ const bare = host.replace(/^\[|\]$/g, '');
76
+ if (bare === 'localhost' || bare.endsWith('.localhost'))
77
+ return { refused: `private host ${bare}` };
78
+ const addrs = isIP(bare) ? [bare] : (await lookup(bare, { all: true }).catch(() => [])).map((a) => a.address);
79
+ if (addrs.length === 0)
80
+ return { refused: `unresolvable host ${bare}` };
81
+ // EVERY answer must be public: a name that also resolves privately is one a
82
+ // second lookup (Chrome's, a retry's) could land on.
83
+ const bad = addrs.find((a) => !publicAddress(a));
84
+ return bad ? { refused: `private address ${bad} (${bare})` } : { address: addrs[0] };
85
+ }
86
+ let proxy;
87
+ /**
88
+ * The process-wide egress proxy (lazy, loopback-bound). HTTPS goes through
89
+ * CONNECT and is dialled to the checked address; a plain-HTTP request is
90
+ * refused — a public storefront is served over https, and refusing http closes
91
+ * the absolute-URI path a redirect to http://127.0.0.1 would take.
92
+ */
93
+ export function egressProxy() {
94
+ proxy ??= new Promise((resolve, reject) => {
95
+ const server = createServer((req, res) => {
96
+ res.writeHead(403, { 'content-type': 'text/plain' }).end('sbuilder snapshot: plain http is not fetched');
97
+ });
98
+ server.on('connect', (req, client, head) => {
99
+ const m = /^(.+):(\d+)$/.exec(req.url ?? '');
100
+ if (!m) {
101
+ client.end('HTTP/1.1 400 Bad Request\r\n\r\n');
102
+ return;
103
+ }
104
+ void resolvePublic(m[1]).then((r) => {
105
+ if ('refused' in r) {
106
+ client.end(`HTTP/1.1 403 Forbidden\r\nX-Refused: ${r.refused}\r\n\r\n`);
107
+ return;
108
+ }
109
+ const upstream = connect(Number(m[2]), r.address, () => {
110
+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
111
+ if (head.length)
112
+ upstream.write(head);
113
+ upstream.pipe(client);
114
+ client.pipe(upstream);
115
+ });
116
+ const drop = () => {
117
+ upstream.destroy();
118
+ client.destroy();
119
+ };
120
+ upstream.on('error', drop);
121
+ client.on('error', drop);
122
+ });
123
+ });
124
+ server.on('error', reject);
125
+ server.listen(0, '127.0.0.1', () => {
126
+ server.unref();
127
+ resolve({ server, url: `http://127.0.0.1:${server.address().port}` });
128
+ });
129
+ });
130
+ return proxy.then((p) => p.url);
131
+ }
@@ -1,4 +1,5 @@
1
1
  import { setTimeout as sleep } from 'node:timers/promises';
2
+ import { egressProxy, resolvePublic } from './egress.js';
2
3
  import { chromium } from 'playwright-core';
3
4
  /** The three widths the platform's own breakpoints care about. */
4
5
  export const DEFAULT_WIDTHS = [1440, 768, 390];
@@ -293,6 +294,81 @@ async function shootWith(b, url, opts) {
293
294
  }
294
295
  }));
295
296
  }
297
+ /**
298
+ * Why `url` may not be photographed from this machine, or undefined. The cheap
299
+ * up-front answer for a clear error; the ENFORCEMENT is the egress proxy, which
300
+ * re-checks the address it actually dials for every request (egress.ts).
301
+ */
302
+ export async function blockedUrl(url) {
303
+ let u;
304
+ try {
305
+ u = new URL(url);
306
+ }
307
+ catch {
308
+ return 'not a URL';
309
+ }
310
+ if (u.protocol !== 'https:')
311
+ return `scheme ${u.protocol} (only https is photographed)`;
312
+ const r = await resolvePublic(u.hostname);
313
+ return 'refused' in r ? r.refused : undefined;
314
+ }
315
+ /**
316
+ * ONE VIEWPORT of a page as JPEG — the dashboard/gallery thumbnail shape (the top
317
+ * of the homepage, not the whole scroll), small enough for the 2 MB preview cap.
318
+ * Same pooled browser, same bounded settle, same stall recovery as `shoot`.
319
+ */
320
+ export async function snapshot(url, opts = {}) {
321
+ if (!opts.allowPrivate) {
322
+ const why = await blockedUrl(url);
323
+ if (why)
324
+ throw new Error(`refusing to photograph ${why}`);
325
+ }
326
+ const once = async (b) => {
327
+ // ITS OWN CONTEXT, every byte through the egress proxy: redirects, frames,
328
+ // images, sockets and re-resolved names all meet the address check at the
329
+ // moment of the connect (measured: a local server saw 0 hits from 127.0.0.1,
330
+ // localhost, [::1], <img>, <iframe> and fetch; 1 hit with no proxy).
331
+ // `<-loopback>` is belt and braces: Chrome documents an implicit "never proxy
332
+ // localhost" rule, which this Chromium did NOT apply to a context proxy
333
+ // (also measured) — the flag keeps it that way if a version starts to. A
334
+ // service worker could fetch outside the page's view, so none may register.
335
+ const context = await deadline(b.newContext({
336
+ viewport: { width: opts.width ?? 1440, height: opts.height ?? 1080 },
337
+ serviceWorkers: 'block',
338
+ ...(opts.allowPrivate ? {} : { proxy: { server: await egressProxy(), bypass: '<-loopback>' } }),
339
+ }), 'open a context');
340
+ const page = await deadline(context.newPage(), 'open a tab');
341
+ try {
342
+ // A 404/500 page is not the site — photographing it would make a broken
343
+ // card look like a real one.
344
+ const res = await page.goto(url, { waitUntil: 'load', timeout: 30_000 });
345
+ if (res && !res.ok())
346
+ throw new Error(`the page answered HTTP ${res.status()}`);
347
+ await settleDom(page);
348
+ // A blank page photographs as a white card, which hides the "no picture"
349
+ // gap an operator would otherwise see. Refuse it instead.
350
+ const shows = await deadline(page.evaluate(() => {
351
+ const d = document;
352
+ return !!d.body && (d.body.innerText.trim().length > 0 || d.querySelector('img,picture,video,svg,canvas') !== null);
353
+ }), 'read the page');
354
+ if (!shows)
355
+ throw new Error('the page shows nothing yet');
356
+ return new Uint8Array(await deadline(page.screenshot({ type: 'jpeg', quality: JPEG_QUALITY }), 'take the screenshot'));
357
+ }
358
+ finally {
359
+ await deadline(context.close(), 'close a tab').catch(() => undefined);
360
+ }
361
+ };
362
+ try {
363
+ return await once(await browser());
364
+ }
365
+ catch (e) {
366
+ if (!(e instanceof ChromeStalled))
367
+ throw e;
368
+ await closeBrowser();
369
+ return once(await browser());
370
+ }
371
+ }
296
372
  /**
297
373
  * WAIT FOR THE PAGE TO STOP CHANGING, not for the network to go quiet.
298
374
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sbuilder-mcp",
3
- "version": "0.106.0",
3
+ "version": "0.107.1",
4
4
  "description": "MCP server that designs and operates a Store Builder site — pages, data, theme and publish — through the platform's own API and live-edit protocol.",
5
5
  "mcpName": "io.github.vuluu2k/sbuilder-mcp",
6
6
  "type": "module",