sbuilder-mcp 0.105.0 → 0.107.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/CHANGELOG.md CHANGED
@@ -6,6 +6,29 @@ 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.0] - 2026-11-18
10
+
11
+ ### Added
12
+ - `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.
13
+ - `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.
14
+ - `sb_store` `site_template` dry run returns `already_template.categories` with the categories currently assigned to a site that is already a template.
15
+
16
+ ### Changed
17
+ - 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.
18
+
19
+ ## [0.106.0] - 2026-11-18
20
+
21
+ ### Added
22
+ - `sb_store` `site_template` offers the whole site as its organization's template with a `name`, `description` and gallery `categories`, attaching the site to `org_id` first when it has no organization.
23
+ - `sb_store` `site_template` refuses categories for an organization other than the platform organization before writing anything, and refuses `dry_run: false` without a `name`.
24
+ - `sb_store` `site_template_remove` withdraws a site that was offered as a template.
25
+ - `sb_store` `template_share` sends a saved section template to the organization's review.
26
+ - `sb_store` `template_save` accepts `description` and `categories` (slugs or ids), and its dry run returns `categories_available` with a prompt to name, describe and file the template under one or two categories.
27
+
28
+ ### Changed
29
+ - `sb_store` `template_save` with `template_id` now updates the template's name, description and categories as well as its content, and reports that the content was saved when only the metadata update fails.
30
+ - `sb_templates` lists `share` and `shareNote` for each template.
31
+
9
32
  ## [0.105.0] - 2026-11-13
10
33
 
11
34
  ### Added
package/CHANGELOG.vi.md CHANGED
@@ -6,6 +6,29 @@ 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.0] - 2026-11-18
10
+
11
+ ### Added
12
+ - `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.
13
+ - `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.
14
+ - 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.
15
+
16
+ ### Changed
17
+ - 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.
18
+
19
+ ## [0.106.0] - 2026-11-18
20
+
21
+ ### Added
22
+ - `sb_store` `site_template` đưa cả site làm mẫu của tổ chức với `name`, `description` và `categories` của thư viện, và gắn site vào `org_id` trước khi đánh dấu nếu site chưa thuộc tổ chức nào.
23
+ - `sb_store` `site_template` từ chối danh mục với tổ chức không phải tổ chức nền tảng trước khi ghi gì, và từ chối `dry_run: false` khi thiếu `name`.
24
+ - `sb_store` `site_template_remove` gỡ site đã được đưa làm mẫu.
25
+ - `sb_store` `template_share` gửi section template đã lưu lên hàng duyệt của tổ chức.
26
+ - `sb_store` `template_save` nhận `description` và `categories` (slug hoặc id), và bản chạy thử trả về `categories_available` kèm lời dặn đặt tên, mô tả và xếp mẫu vào một hoặc hai danh mục.
27
+
28
+ ### Changed
29
+ - `sb_store` `template_save` với `template_id` nay cập nhật cả tên, mô tả và danh mục chứ không chỉ nội dung, và báo rõ nội dung đã được lưu khi chỉ phần cập nhật metadata bị lỗi.
30
+ - `sb_templates` hiện `share` và `shareNote` cho từng mẫu.
31
+
9
32
  ## [0.105.0] - 2026-11-13
10
33
 
11
34
  ### 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';
@@ -761,20 +762,72 @@ export async function promoteGlobal(ctx, session, siteId, nodeId, kind, name, op
761
762
  `${gid}" — an edit inside it now lands on every page carrying it.`,
762
763
  };
763
764
  }
765
+ /** The section-template category catalogue (enabled, named for `language`). */
766
+ async function sectionCategories(ctx, base, language) {
767
+ const got = (await request({
768
+ base: ctx.base,
769
+ method: 'GET',
770
+ path: `${base}/categories?locale=${encodeURIComponent(language)}`,
771
+ token: siteToken(ctx),
772
+ fetchImpl: ctx.fetchImpl,
773
+ }));
774
+ return got.categories ?? [];
775
+ }
776
+ /**
777
+ * Resolve what the agent wrote — an id OR a slug — to catalogue entries. An
778
+ * unknown one is refused with the whole list, never dropped: a template filed
779
+ * under nothing is one an operator has to file by hand, the chore this exists
780
+ * to remove.
781
+ */
782
+ function pickCategories(cats, wanted, what) {
783
+ return wanted.map((w) => {
784
+ const hit = cats.find((c) => c.id === w || c.slug === w);
785
+ if (!hit) {
786
+ const list = cats.map((c) => `${c.slug} (${c.name ?? c.slug})`).join(', ') || 'none — the catalogue is empty';
787
+ throw new Error(`sbuilder: no ${what} category "${w}". Choose from: ${list}.`);
788
+ }
789
+ return hit;
790
+ });
791
+ }
792
+ const catalogue = (cats) => cats.map((c) => ({ slug: c.slug, name: c.name ?? c.slug }));
764
793
  /**
765
794
  * Save a section on the OPEN page as a reusable section template — the editor's
766
795
  * "Save as template". The page is untouched; `sb_template_use` places a copy.
767
796
  *
797
+ * `description` and `categories` (slugs or ids from the dry run's catalogue)
798
+ * travel with it, so on a site of the PLATFORM organization the operator's only
799
+ * act in admin → Section templates is turning Listed on.
800
+ *
768
801
  * With `templateId` it REWRITES that template's content instead — the editor's
769
802
  * template edit mode. The agent's way in is the full toolset: place the template
770
803
  * on a page with sb_template_use, edit it there, save it back over the template.
771
804
  * The PUT is fenced on the template's `rev`, read from the list (there is no
772
805
  * single-template GET), so an edit somebody else saved in between is refused.
806
+ * Name/description/categories given alongside are PATCHed after it.
773
807
  */
774
808
  export async function saveTemplate(ctx, session, siteId, nodeId, name, opts) {
775
809
  const doc = session.current();
776
810
  const id = liftable(doc.doc, nodeId, 'template_save');
777
811
  const base = `/api/sites/${encodeURIComponent(siteId)}/section-templates`;
812
+ // Read only when it is used: a plain save must not start failing because the
813
+ // catalogue read does.
814
+ const cats = opts.dryRun || opts.categories?.length ? await sectionCategories(ctx, base, opts.language ?? 'vi') : [];
815
+ const chosen = opts.categories?.length
816
+ ? [...new Map(pickCategories(cats, opts.categories, 'section-template').map((c) => [c.slug, c])).values()]
817
+ : undefined;
818
+ const categoryIds = chosen?.map((c) => c.id).filter((x) => !!x);
819
+ const description = opts.description?.trim();
820
+ const document = sectionDocument(doc.doc, id);
821
+ const nodes = Object.keys(document.nodes).length;
822
+ // The dry run is where the agent CHOOSES: it gets the catalogue and the brief.
823
+ const choose = {
824
+ categories_available: catalogue(cats),
825
+ ...(chosen ? { categories: chosen.map((c) => c.slug) } : {}),
826
+ ...(chosen && description ? {} : {
827
+ write: 'Before saving, name it for what the section IS ("Hero ảnh lớn + 2 nút", not "Section 3"), write a ' +
828
+ 'one-sentence description of what it is for, and pick 1–2 categories from categories_available that fit.',
829
+ }),
830
+ };
778
831
  if (opts.templateId) {
779
832
  const list = (await request({ base: ctx.base, method: 'GET', path: base, token: siteToken(ctx), fetchImpl: ctx.fetchImpl }));
780
833
  const t = (list.sectionTemplates ?? []).find((x) => x.id === opts.templateId);
@@ -783,42 +836,200 @@ export async function saveTemplate(ctx, session, siteId, nodeId, name, opts) {
783
836
  if (t.source && t.source !== 'site') {
784
837
  throw new Error(`sbuilder: template "${opts.templateId}" is a ${t.source} template, not this site's own — save a new one instead.`);
785
838
  }
786
- const document = sectionDocument(doc.doc, id);
787
- const nodes = Object.keys(document.nodes).length;
788
- const path = `${base}/${encodeURIComponent(opts.templateId)}/document`;
839
+ const patch = {
840
+ ...(name?.trim() ? { name: name.trim() } : {}),
841
+ ...(description ? { description } : {}),
842
+ ...(categoryIds ? { categoryIds } : {}),
843
+ };
789
844
  if (opts.dryRun) {
790
- return { dry_run: true, nodes, next: `Nothing was sent. Re-call with dry_run:false to replace "${t.name ?? opts.templateId}"'s content.` };
845
+ return { dry_run: true, nodes, ...(Object.keys(patch).length ? { would_patch: patch } : {}), ...choose, next: `Nothing was sent. Re-call with dry_run:false to replace "${t.name ?? opts.templateId}"'s content.` };
846
+ }
847
+ await request({ base: ctx.base, method: 'PUT', path: `${base}/${encodeURIComponent(opts.templateId)}/document`, token: siteToken(ctx), body: { document, rev: t.rev ?? 0 }, fetchImpl: ctx.fetchImpl });
848
+ // The content is saved now; a metadata failure must say so, or the agent
849
+ // retries the whole rewrite against a rev that has already moved.
850
+ let metaError;
851
+ if (Object.keys(patch).length) {
852
+ try {
853
+ await request({ base: ctx.base, method: 'PATCH', path: `${base}/${encodeURIComponent(opts.templateId)}`, token: siteToken(ctx), body: patch, fetchImpl: ctx.fetchImpl });
854
+ }
855
+ catch (e) {
856
+ metaError = e.message;
857
+ }
791
858
  }
792
- await request({ base: ctx.base, method: 'PUT', path, token: siteToken(ctx), body: { document, rev: t.rev ?? 0 }, fetchImpl: ctx.fetchImpl });
793
859
  return {
794
- template: { id: opts.templateId, name: t.name ?? '' },
860
+ template: { id: opts.templateId, name: metaError ? (t.name ?? '') : (patch.name ?? t.name ?? '') },
795
861
  nodes,
862
+ ...(metaError
863
+ ? { warning: `the CONTENT was saved, but name/description/categories were not: ${metaError}. Re-run with only those fields and no node change.` }
864
+ : chosen ? { categories: chosen.map((c) => c.slug) } : {}),
796
865
  next: 'Pages that placed this template earlier keep their own copy; only new placements get this content. ' +
797
- 'A template shared with the organization goes back to review after a content change.' +
798
- (name?.trim() ? ' `name` was not applied — a rewrite changes content only.' : ''),
866
+ 'A template shared with the organization goes back to review after a content change.',
799
867
  };
800
868
  }
801
869
  if (!name?.trim())
802
870
  throw new Error('sbuilder: action:"template_save" needs name — the template\'s name in the library.');
803
- const document = sectionDocument(doc.doc, id);
804
- const nodes = Object.keys(document.nodes).length;
805
871
  if (opts.dryRun) {
806
- return { dry_run: true, nodes, next: 'Nothing was sent. Re-call with dry_run:false to save it.' };
872
+ return { dry_run: true, nodes, would_save: { name: name.trim(), ...(description ? { description } : {}) }, ...choose, next: 'Nothing was sent. Re-call with dry_run:false to save it.' };
807
873
  }
808
874
  const made = (await request({
809
875
  base: ctx.base,
810
876
  method: 'POST',
811
877
  path: base,
812
878
  token: siteToken(ctx),
813
- body: { name: name.trim(), document },
879
+ body: { name: name.trim(), ...(description ? { description } : {}), document, ...(categoryIds ? { categoryIds } : {}) },
814
880
  fetchImpl: ctx.fetchImpl,
815
881
  }));
816
882
  const tid = made.sectionTemplate?.id;
817
883
  if (typeof tid !== 'string' || !tid)
818
884
  throw new Error('sbuilder: the platform created no section template.');
885
+ // The create answers what IS filed (a filing failure does not fail it), so a
886
+ // shortfall is read off the answer rather than assumed from the request.
887
+ const filed = made.sectionTemplate?.categoryIds ?? [];
888
+ const missed = categoryIds && filed.length < categoryIds.length;
819
889
  return {
820
890
  template: { id: tid, name: name.trim() },
821
891
  nodes,
822
- next: 'Place a copy with sb_template_use; sb_templates lists it.',
892
+ ...(chosen ? { categories: chosen.filter((c) => c.id && filed.includes(c.id)).map((c) => c.slug) } : {}),
893
+ ...(missed ? { warning: 'the template was saved but its categories were NOT filed — re-run with template_id and categories to file them.' } : {}),
894
+ next: 'Place a copy with sb_template_use; sb_templates lists it. On a site of the platform organization it now ' +
895
+ 'waits in admin → Section templates, where an operator turns Listed on.',
896
+ };
897
+ }
898
+ /**
899
+ * Offer the WHOLE SITE as its organization's starting template — every page it
900
+ * has comes along when someone starts from it. With `orgId` the site is first
901
+ * attached to that organization (owner only). `categories` are platform gallery
902
+ * slugs (the dry run lists them), filed with the mark, so an operator's only act
903
+ * in admin → Templates is the listing switch. The server refuses categories for
904
+ * a site outside the platform organization rather than filing them into nothing.
905
+ */
906
+ export async function markSiteTemplate(ctx, siteId, name, opts) {
907
+ const sitePath = `/api/sites/${encodeURIComponent(siteId)}`;
908
+ const get = async (path) => (await request({ base: ctx.base, method: 'GET', path, token: siteToken(ctx), fetchImpl: ctx.fetchImpl }));
909
+ const { site } = await get(sitePath);
910
+ const description = opts.description?.trim();
911
+ const orgId = site?.orgId || undefined;
912
+ if (opts.orgId && orgId && orgId !== opts.orgId) {
913
+ throw new Error(`sbuilder: this site already belongs to organization ${orgId}; detach it in the dashboard before offering it to ${opts.orgId}.`);
914
+ }
915
+ const attach = opts.orgId && !orgId ? opts.orgId : undefined;
916
+ if (!orgId && !attach) {
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).');
918
+ }
919
+ const org = (attach ?? orgId);
920
+ const listed = await get(`/api/templates/categories?locale=${encodeURIComponent(opts.language ?? 'vi')}&orgId=${encodeURIComponent(org)}`);
921
+ // The current filing, read behind the site's own membership check.
922
+ const filed = site?.isTemplate && listed.fileable
923
+ ? ((await get(`${sitePath}/template`).catch(() => ({ template: undefined }))).template?.categories ?? [])
924
+ : [];
925
+ const cats = listed.categories ?? [];
926
+ // Only the platform org's templates reach the gallery; refusing HERE keeps a
927
+ // mark from landing with a filing the server would then reject.
928
+ if (opts.categories?.length && !listed.fileable) {
929
+ 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).`);
930
+ }
931
+ const chosen = opts.categories?.length
932
+ ? [...new Map(pickCategories(cats, opts.categories, 'template').map((c) => [c.slug, c])).values()]
933
+ : undefined;
934
+ const pages = await get(`${sitePath}/pages`).catch(() => ({ pages: undefined }));
935
+ const state = {
936
+ site: site?.name,
937
+ organization: attach ?? orgId,
938
+ pages: pages.pages?.map((p) => p.name ?? p.slug),
939
+ ...(site?.isTemplate
940
+ ? { already_template: { name: site.templateName, description: site.templateDescription, ...(filed.length ? { categories: filed } : {}) } }
941
+ : {}),
942
+ };
943
+ if (!opts.dryRun && !name?.trim()) {
944
+ 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.');
945
+ }
946
+ if (opts.dryRun) {
947
+ return {
948
+ ...(opts.dryRun ? { dry_run: true } : {}),
949
+ ...state,
950
+ ...(attach ? { would_attach_to: attach } : {}),
951
+ would_mark: { name: name?.trim(), description, categories: chosen?.map((c) => c.slug) },
952
+ ...(listed.fileable
953
+ ? { categories_available: catalogue(cats) }
954
+ : { categories_available: [], note: 'not the platform organization — no gallery categories; the template goes on its members\' shelf' }),
955
+ write: 'Name the template for the business it starts ("Shop thời trang nữ", not "Template 1"), write ONE sentence ' +
956
+ 'on who it is for and what it comes with (read `pages`), and pick 1–2 categories from categories_available. ' +
957
+ 'Then re-call with dry_run:false.',
958
+ };
959
+ }
960
+ if (attach) {
961
+ await request({ base: ctx.base, method: 'PUT', path: `${sitePath}/org`, token: siteToken(ctx), body: { orgId: attach }, fetchImpl: ctx.fetchImpl });
962
+ }
963
+ try {
964
+ await request({
965
+ base: ctx.base,
966
+ method: 'POST',
967
+ path: `${sitePath}/template`,
968
+ token: siteToken(ctx),
969
+ body: { name: name.trim(), ...(description ? { description } : {}), ...(chosen ? { categories: chosen.map((c) => c.slug) } : {}) },
970
+ fetchImpl: ctx.fetchImpl,
971
+ });
972
+ }
973
+ catch (e) {
974
+ // Say what already happened: the attach (if any) stands, and a refused
975
+ // filing means the mark itself landed.
976
+ const msg = e.message;
977
+ const done = [attach ? `the site WAS attached to ${attach}` : '', /categories_not_filed|marked as a template/.test(msg) ? 'it IS marked as a template' : '']
978
+ .filter(Boolean)
979
+ .join('; ');
980
+ throw new Error(done ? `${msg} (${done} — re-run site_template to retry the rest)` : msg);
981
+ }
982
+ // THE CARD'S PICTURE. A screenshot is otherwise taken only when a person sits
983
+ // on the dashboard, so an agent-built template reached the gallery blank.
984
+ // Best effort: the mark already stands, so a failure is a note, not an error.
985
+ let picture;
986
+ try {
987
+ if (!site?.publicUrl)
988
+ throw new Error('the site has no public address yet');
989
+ // Private addresses are allowed only when the PLATFORM itself is local (dev,
990
+ // where every storefront is *.localhost) — never steered there by a domain.
991
+ const local = ['localhost', '127.0.0.1', '::1', '[::1]'].includes(new URL(ctx.base).hostname) || new URL(ctx.base).hostname.endsWith('.localhost');
992
+ const jpeg = await snapshot(new URL(site.publicUrl, ctx.base).toString(), { allowPrivate: local });
993
+ await request({
994
+ base: ctx.base,
995
+ method: 'PUT',
996
+ path: `${sitePath}/preview`,
997
+ token: siteToken(ctx),
998
+ body: new Blob([jpeg], { type: 'image/jpeg' }),
999
+ fetchImpl: ctx.fetchImpl,
1000
+ });
1001
+ picture = 'captured from the published homepage';
1002
+ }
1003
+ catch (e) {
1004
+ picture = `not captured (${e.message}) — publish the homepage, then re-run site_template`;
1005
+ }
1006
+ return {
1007
+ picture,
1008
+ template: { site_id: siteId, name: name.trim(), ...(description ? { description } : {}), ...(chosen ? { categories: chosen.map((c) => c.slug) } : {}) },
1009
+ ...(attach ? { attached_to: attach } : {}),
1010
+ next: 'Publish every page first — the gallery card shows the published storefront. On the platform organization an ' +
1011
+ 'operator now turns it on in admin → Templates (one switch); in any other organization it is on its members\' shelf already.',
823
1012
  };
824
1013
  }
1014
+ /** Withdraw the site from its organization's templates (gallery listing goes with it). */
1015
+ export async function unmarkSiteTemplate(ctx, siteId, dryRun) {
1016
+ const path = `/api/sites/${encodeURIComponent(siteId)}/template`;
1017
+ if (dryRun)
1018
+ return { dry_run: true, would_delete: path, next: 'Sites already started from it keep their copy. Re-call with dry_run:false.' };
1019
+ await request({ base: ctx.base, method: 'DELETE', path, token: siteToken(ctx), fetchImpl: ctx.fetchImpl });
1020
+ return { withdrawn: siteId, next: 'It is off the organization\'s shelf and the gallery; site_template marks it again.' };
1021
+ }
1022
+ /**
1023
+ * Offer one of this site's section templates to its ORGANIZATION's shelf — the
1024
+ * review queue a reviewer approves from. (The platform org's own templates need
1025
+ * no review: an operator lists them in admin.)
1026
+ */
1027
+ export async function shareTemplate(ctx, siteId, templateId, dryRun) {
1028
+ if (!templateId)
1029
+ throw new Error('sbuilder: action:"template_share" needs template_id — sb_templates lists them.');
1030
+ const path = `/api/sites/${encodeURIComponent(siteId)}/section-templates/${encodeURIComponent(templateId)}/share`;
1031
+ if (dryRun)
1032
+ return { dry_run: true, would_post: path, next: 'Re-call with dry_run:false to send it for review.' };
1033
+ const got = (await request({ base: ctx.base, method: 'POST', path, token: siteToken(ctx), fetchImpl: ctx.fetchImpl }));
1034
+ return { shared: templateId, share: got.sectionTemplate?.share ?? 'pending', next: 'A reviewer of the organization approves or rejects it; sb_templates shows its state.' };
1035
+ }
@@ -14,7 +14,7 @@ export const PAGE_FIELDS = [
14
14
  'id', 'name', 'slug', 'path', 'isHomepage', 'type', 'status', 'updatedAt', 'publishedAt',
15
15
  ];
16
16
  export const TEMPLATE_FIELDS = [
17
- 'id', 'name', 'description', 'categoryIds', 'source', 'listed', 'updatedAt',
17
+ 'id', 'name', 'description', 'categoryIds', 'source', 'listed', 'share', 'shareNote', 'updatedAt',
18
18
  ];
19
19
  export const MEDIA_FIELDS = [
20
20
  'id', 'name', 'url', 'mediaType', 'contentType', 'sizeBytes', 'width', 'height', 'folderId', 'state',
@@ -44,7 +44,7 @@ import { siteFor } from './context.js';
44
44
  import { withFreshIds } from '../domains/site/ids.js';
45
45
  import { addPlaced, saveRefusal, siteChrome, wearChrome } from './page.js';
46
46
  import { addSubtree } from '../domains/site/builder.js';
47
- import { attachGlobal, buildChrome, detachGlobal, promoteGlobal, saveTemplate } from './chrome.js';
47
+ import { attachGlobal, buildChrome, detachGlobal, markSiteTemplate, promoteGlobal, saveTemplate, shareTemplate, unmarkSiteTemplate, } from './chrome.js';
48
48
  import { bindMenu } from './menu.js';
49
49
  import { attachOverlay, ensureCartDrawer, relocalizeCartDrawer } from './overlay.js';
50
50
  import { installApp } from './app.js';
@@ -568,7 +568,9 @@ export function registerStoreTools(server, ctx, session) {
568
568
  'wrongly build a second one. action:"global_promote" turns a section on the open page ' +
569
569
  '(node_id) into a NEW shared section (global_kind header|footer|custom, default custom) and ' +
570
570
  'leaves the page referencing it; action:"template_save" saves one as a section template ' +
571
- '(name). Dry run returns the plan.',
571
+ '(name; template_share sends one to the org\'s review). site_template offers the whole site as its org\'s ' +
572
+ 'template (org_id attaches first; site_template_remove withdraws). ' +
573
+ 'Dry run returns the plan.',
572
574
  inputSchema: {
573
575
  action: z.enum([
574
576
  'checkout',
@@ -583,6 +585,9 @@ export function registerStoreTools(server, ctx, session) {
583
585
  'global_detach',
584
586
  'global_promote',
585
587
  'template_save',
588
+ 'site_template',
589
+ 'site_template_remove',
590
+ 'template_share',
586
591
  ]),
587
592
  site_id: z.string().optional(),
588
593
  language: z.enum(['vi', 'en']).optional().describe('Copy language, default vi'),
@@ -611,6 +616,15 @@ export function registerStoreTools(server, ctx, session) {
611
616
  .describe('action:"menu" — the menu node; "global_promote"/"template_save" — the section; "form" — a node of the open page to place it in'),
612
617
  global_kind: z.enum(['header', 'footer', 'custom']).optional(),
613
618
  template_id: z.string().optional().describe('action:"template_save" — overwrite this template\'s content'),
619
+ description: z
620
+ .string()
621
+ .optional()
622
+ .describe('template_save/site_template: one sentence, what it is for'),
623
+ categories: z
624
+ .array(z.string())
625
+ .optional()
626
+ .describe('template_save/site_template: slugs from the dry run'),
627
+ org_id: z.string().optional(),
614
628
  menu_id: z.string().optional(),
615
629
  kind: z
616
630
  .enum(['popup', 'quickview'])
@@ -642,7 +656,7 @@ export function registerStoreTools(server, ctx, session) {
642
656
  dry_run: z.boolean().optional(),
643
657
  },
644
658
  annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
645
- }, async ({ action, site_id: given, language, page_name, headline, template, name, footer, node_id, menu_id, kind, overlay_id, list_id, app_key, global_id, global_kind, template_id, relocalize, settings, dry_run, }) => {
659
+ }, async ({ action, site_id: given, language, page_name, headline, template, name, footer, node_id, menu_id, kind, overlay_id, list_id, app_key, global_id, global_kind, template_id, description, categories, org_id, relocalize, settings, dry_run, }) => {
646
660
  const siteId = siteFor(ctx, given);
647
661
  if (action === 'global_attach' || action === 'global_detach') {
648
662
  // THE COMPOSED STAMP IS NEVER THE CALLER'S TO WRITE. A page references
@@ -659,7 +673,20 @@ export function registerStoreTools(server, ctx, session) {
659
673
  return text(await promoteGlobal(ctx, session, siteId, node_id, global_kind ?? 'custom', name, { dryRun: dry_run !== false }));
660
674
  }
661
675
  if (action === 'template_save') {
662
- return text(await saveTemplate(ctx, session, siteId, node_id, name, { dryRun: dry_run !== false, templateId: template_id }));
676
+ return text(await saveTemplate(ctx, session, siteId, node_id, name, {
677
+ dryRun: dry_run !== false,
678
+ templateId: template_id,
679
+ description,
680
+ categories,
681
+ language,
682
+ }));
683
+ }
684
+ if (action === 'site_template_remove')
685
+ return text(await unmarkSiteTemplate(ctx, siteId, dry_run !== false));
686
+ if (action === 'template_share')
687
+ return text(await shareTemplate(ctx, siteId, template_id, dry_run !== false));
688
+ if (action === 'site_template') {
689
+ return text(await markSiteTemplate(ctx, siteId, name, { dryRun: dry_run !== false, description, categories, orgId: org_id, language }));
663
690
  }
664
691
  if (action === 'app') {
665
692
  if (!app_key) {
@@ -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.105.0",
3
+ "version": "0.107.0",
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",