sbuilder-mcp 0.108.0 → 0.109.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,26 @@ 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.109.1] - 2026-11-19
10
+
11
+ ### Fixed
12
+ - `sb_site_use` is no longer marked read-only, so clients that auto-approve read-only tools now ask before it changes the site every later write lands on.
13
+
14
+ ## [0.109.0] - 2026-11-19
15
+
16
+ ### Added
17
+ - `sb_login` signs in with a platform account through the browser device-code flow from inside the chat, returning the code on the first call, waiting for approval on the next, and signing the machine out with `action:"logout"`.
18
+ - `sb_site_use` switches the default site among the account's sites, and the new `--site` option picks the starting site.
19
+ - `install --login` runs the device-code login in the terminal and writes the client config without any key or password, skipping the browser when already signed in.
20
+
21
+ ### Changed
22
+ - The login session is stored in `~/.config/sb/credentials.json`, shared with `sb login` under the same lock and re-read-before-rotate protocol, so one approval signs in the CLI and every agent window.
23
+ - A site API key is used only on its own site while the account session covers every other site.
24
+
25
+ ### Fixed
26
+ - `/api/v1` calls, including the `/api/v1/media` upload retry, are refused after switching away from the key's site instead of silently writing to the key's store while reporting success.
27
+ - The browser opened for login only accepts http and https URLs and is launched without a shell.
28
+
9
29
  ## [0.108.0] - 2026-11-19
10
30
 
11
31
  ### Added
package/CHANGELOG.vi.md CHANGED
@@ -6,6 +6,26 @@ 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.109.1] - 2026-11-19
10
+
11
+ ### Fixed
12
+ - `sb_site_use` không còn được đánh dấu chỉ-đọc, nên các client tự động duyệt công cụ chỉ-đọc giờ sẽ hỏi trước khi nó đổi site mà mọi lệnh ghi sau đó rơi vào.
13
+
14
+ ## [0.109.0] - 2026-11-19
15
+
16
+ ### Added
17
+ - `sb_login` đăng nhập bằng tài khoản nền tảng qua luồng nhập mã trên trình duyệt ngay trong cuộc chat, lần gọi đầu trả mã, lần sau chờ duyệt, và đăng xuất máy bằng `action:"logout"`.
18
+ - `sb_site_use` đổi site mặc định trong các site của tài khoản, và tùy chọn `--site` mới chọn site bắt đầu.
19
+ - `install --login` chạy luồng đăng nhập nhập mã ngay trong terminal và ghi cấu hình client không có khoá hay mật khẩu, bỏ qua trình duyệt khi đã đăng nhập.
20
+
21
+ ### Changed
22
+ - Phiên đăng nhập được lưu ở `~/.config/sb/credentials.json`, dùng chung với `sb login` cùng giao thức khoá và đọc lại trước khi xoay, nên một lần duyệt đăng nhập cả CLI lẫn mọi cửa sổ agent.
23
+ - API key của site chỉ dùng trên site của nó, còn phiên tài khoản dùng ở mọi site khác.
24
+
25
+ ### Fixed
26
+ - Các lệnh gọi `/api/v1`, kể cả bước thử lại upload qua `/api/v1/media`, bị từ chối sau khi rời site của khoá, thay vì âm thầm ghi vào cửa hàng của khoá mà vẫn báo thành công.
27
+ - Trình duyệt mở khi đăng nhập chỉ nhận URL http và https và được chạy không qua shell.
28
+
9
29
  ## [0.108.0] - 2026-11-19
10
30
 
11
31
  ### Added
package/README.md CHANGED
@@ -14,6 +14,21 @@ One command writes this server into every agent client on your machine:
14
14
  npx -y sbuilder-mcp install --token wbk_… --api https://your-host --site site_…
15
15
  ```
16
16
 
17
+ ### Or sign in the whole account in the browser
18
+
19
+ ```bash
20
+ npx -y sbuilder-mcp@latest install --login --api https://your-host --site site_…
21
+ ```
22
+
23
+ It prints a code and opens the platform's sign-in page: type the code, check it matches, press
24
+ **Approve**. No key and no password is written anywhere — the login is kept in
25
+ `~/.config/sb/credentials.json` (owner-only), **the same file `sb login` uses**, so one approval
26
+ signs in the CLI and every agent window together, and survives restarts. `--site` is the site
27
+ the agent starts on; with the account it can reach every site you can, and `sb_site_use` moves
28
+ it. Already signed in? The command says so and skips the browser. Inside a chat, `sb_login`
29
+ does the same thing (the first call returns the code, the next one waits for the approval), and
30
+ `sb_login action:"logout"` signs the machine out.
31
+
17
32
  It knows Claude Code, Claude Desktop, Cursor, Windsurf, VS Code and Codex, and installs into
18
33
  the ones it finds. Name them with `--client cursor,codex`, or rehearse with `--dry-run`. An
19
34
  option it does not know is **refused**, not ignored — a flag that silently does nothing is
@@ -62,9 +77,12 @@ site API, including the page document and the live-edit socket, and it is bounde
62
77
  on every request: its own scopes, the live role of the member who created it, and the single
63
78
  store it belongs to.
64
79
 
65
- `SB_EMAIL` + `SB_PASSWORD` remain optional, and buy exactly one thing: **account-level**
66
- calls — listing your sites, managing members and roles — which a key deliberately cannot
67
- make, because those mean "this person's account".
80
+ Account-level calls — listing your sites, managing members and roles, working on another
81
+ site — are what a key deliberately cannot make, because those mean "this person's account".
82
+ For those, sign in with `install --login` / `sb_login` (above). `SB_EMAIL` + `SB_PASSWORD`
83
+ still work, but put a password in every config file the installer touches. With both a key
84
+ and the account login, the key is used on its own site and the account everywhere else;
85
+ `/api/v1` (which names no site) is refused once the agent moved off the key's site.
68
86
 
69
87
  `SB_API` defaults to `http://localhost:8080`. Secrets are read from the environment only.
70
88
 
@@ -82,6 +100,8 @@ in this client: one would put the very key the platform exists to hold back into
82
100
  | --- | --- |
83
101
  | `sb_connect` | Log in, list the sites this account can operate, report which credentials are present |
84
102
  | `sb_site_list` | List the sites this account can operate |
103
+ | `sb_login` | Sign the whole account in through the browser (a code to type + Approve); remembered on this machine, shared with `sb login`; `action:"logout"` signs out |
104
+ | `sb_site_use` | Switch the site every tool defaults to, among the account's sites |
85
105
  | `sb_api_find` | Find API operations by intent — one line per match — then read one operation's call sheet by id: real parameter schemas, the credential it needs, and the body's fields read off the handler that decodes them, each carrying the trap its own doc comment records |
86
106
  | `sb_api_call` | Execute an operation, or any route by method+path; dry run by default. Field selection (dotted paths, on lists and single-object write answers) and local result pagination; `merge` for whole-record PUTs, `If-Match`, multipart `file` |
87
107
  | `sb_page_open` | Open a page for editing and return its outline — or, with `form_id`, a form's field document (fields, defaults, dependent-field rules) |
package/README.vi.md CHANGED
@@ -14,6 +14,21 @@ Một lệnh ghi server này vào mọi agent client trên máy bạn:
14
14
  npx -y sbuilder-mcp install --token wbk_… --api https://your-host --site site_…
15
15
  ```
16
16
 
17
+ ### Hoặc đăng nhập cả tài khoản bằng trình duyệt
18
+
19
+ ```bash
20
+ npx -y sbuilder-mcp@latest install --login --api https://your-host --site site_…
21
+ ```
22
+
23
+ Lệnh in ra một mã và mở trang đăng nhập của nền tảng: gõ mã, kiểm tra khớp, bấm **Đồng ý**.
24
+ Không khoá, không mật khẩu nào bị ghi ra — phiên đăng nhập được giữ trong
25
+ `~/.config/sb/credentials.json` (chỉ chủ máy đọc được), **cùng file với `sb login`**, nên một lần
26
+ đồng ý là CLI và mọi cửa sổ agent đều đăng nhập, và vẫn còn sau khi khởi động lại. `--site` là
27
+ site agent bắt đầu làm; với cả tài khoản nó với tới mọi site bạn có quyền, và `sb_site_use`
28
+ chuyển site. Đã đăng nhập rồi thì lệnh báo và bỏ qua trình duyệt. Ngay trong cuộc chat,
29
+ `sb_login` làm việc tương tự (lần gọi đầu trả mã, lần sau chờ bạn đồng ý), và
30
+ `sb_login action:"logout"` đăng xuất máy.
31
+
17
32
  Nó biết Claude Code, Claude Desktop, Cursor, Windsurf, VS Code và Codex, và cài vào những
18
33
  cái nó tìm thấy. Chỉ định bằng `--client cursor,codex`, hoặc diễn thử với `--dry-run`. Một
19
34
  tuỳ chọn nó không biết sẽ bị **từ chối**, không phải bỏ qua — một cờ âm thầm không làm gì
@@ -59,9 +74,12 @@ Một khoá là đủ. Nó với tới cả bề mặt đối tác (`/api/v1`) l
59
74
  trang và socket live-edit, và bị chặn ba lớp ở mỗi request: scope của chính nó, role sống của
60
75
  thành viên đã tạo ra nó, và đúng một cửa hàng nó thuộc về.
61
76
 
62
- `SB_EMAIL` + `SB_PASSWORD` vẫn tuỳ chọn, và mua đúng một thứ: các lệnh **cấp tài khoản** —
63
- liệt kê site, quản lý thành viên và role — mà khoá cố ý không làm được, vì những thứ đó nghĩa
64
- là "tài khoản của người này".
77
+ Các lệnh **cấp tài khoản** — liệt kê site, quản lý thành viên và role, làm việc trên site
78
+ khác — là thứ khoá cố ý không làm được, vì chúng nghĩa là "tài khoản của người này". Muốn có
79
+ thì đăng nhập bằng `install --login` / `sb_login` (ở trên). `SB_EMAIL` + `SB_PASSWORD` vẫn
80
+ dùng được, nhưng ghi mật khẩu vào mọi file cấu hình. Có cả khoá lẫn đăng nhập tài khoản thì
81
+ khoá dùng trên site của nó, tài khoản dùng ở mọi site khác; `/api/v1` (không ghi site) bị từ
82
+ chối khi agent đã chuyển khỏi site của khoá.
65
83
 
66
84
  `SB_API` mặc định `http://localhost:8080`. Bí mật chỉ đọc từ biến môi trường.
67
85
 
@@ -79,6 +97,8 @@ nhét ngược lại vào mọi bản cài.
79
97
  | --- | --- |
80
98
  | `sb_connect` | Đăng nhập, liệt kê site tài khoản vận hành được, báo đang có credential nào |
81
99
  | `sb_site_list` | Liệt kê site tài khoản vận hành được |
100
+ | `sb_login` | Đăng nhập cả tài khoản bằng trình duyệt (gõ mã + Đồng ý); nhớ trên máy, dùng chung với `sb login`; `action:"logout"` để đăng xuất |
101
+ | `sb_site_use` | Đổi site mọi tool mặc định làm việc, trong các site của tài khoản |
82
102
  | `sb_api_find` | Tìm operation theo ý định — mỗi kết quả một dòng — rồi đọc call sheet của một operation theo id: schema tham số thật, credential cần dùng, và các trường body đọc thẳng từ handler decode chúng, mỗi trường mang theo cái bẫy doc comment của chính nó ghi lại |
83
103
  | `sb_api_call` | Chạy operation, hoặc bất kỳ route nào bằng method+path; mặc định chạy khô. Chọn field (đường dẫn có dấu chấm, trên danh sách lẫn câu trả lời ghi một object) và phân trang kết quả phía MCP; `merge` cho PUT thay cả bản ghi, `If-Match`, `file` multipart |
84
104
  | `sb_page_open` | Mở một trang để sửa và trả về outline — hoặc, với `form_id`, tài liệu trường của biểu mẫu (trường, giá trị mặc định, quy tắc trường phụ thuộc) |
package/dist/index.js CHANGED
@@ -1,14 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
3
  import { buildContext, createServer } from './server.js';
4
- import { runInstallCli } from './install/index.js';
4
+ import { runInstall } from './install/index.js';
5
+ import { pkgVersion } from './server.js';
5
6
  import { closeBrowser } from './vision/shoot.js';
6
7
  async function main() {
7
8
  // `sbuilder-mcp install` writes this server into the agent clients on this
8
9
  // machine and exits. Checked BEFORE the transport opens: an installer that
9
10
  // also spoke MCP on stdout would corrupt the protocol for whatever ran it.
10
11
  if (process.argv[2] === 'install') {
11
- process.exit(runInstallCli(process.argv.slice(3)));
12
+ process.exit(await runInstall(process.argv.slice(3), { version: pkgVersion() }));
12
13
  }
13
14
  const ctx = buildContext();
14
15
  const server = createServer(ctx);
@@ -1,5 +1,7 @@
1
1
  import { targets, detected } from './paths.js';
2
2
  import { mergeInto } from './write.js';
3
+ import { openBrowser, pollDevice, startDevice } from '../transport/device.js';
4
+ import { readPairSync, rotate, savePair } from '../transport/stored.js';
3
5
  /** The name the server appears under in every client. */
4
6
  export const SERVER_NAME = 'sbuilder';
5
7
  /**
@@ -27,8 +29,11 @@ const FLAGS = [
27
29
  '--email',
28
30
  '--password',
29
31
  '--client',
32
+ '--login',
30
33
  '--dry-run',
31
34
  ];
35
+ /** Flags that take no value. */
36
+ const SWITCHES = new Set(['--login', '--dry-run']);
32
37
  export function buildEntry(opts, pkg = 'sbuilder-mcp') {
33
38
  const env = {};
34
39
  if (opts.api)
@@ -49,9 +54,10 @@ export function buildEntry(opts, pkg = 'sbuilder-mcp') {
49
54
  // and writing an account password into six config files to buy the handful of
50
55
  // account-level calls it adds is a bad trade the installer should not make for
51
56
  // someone.
52
- if (!opts.token && opts.email)
57
+ // Nor with --login: the point of it is that no password is written anywhere.
58
+ if (!opts.token && !opts.login && opts.email)
53
59
  env.SB_EMAIL = opts.email;
54
- if (!opts.token && opts.password)
60
+ if (!opts.token && !opts.login && opts.password)
55
61
  env.SB_PASSWORD = opts.password;
56
62
  return { command: 'npx', args: ['-y', pkg], env };
57
63
  }
@@ -111,7 +117,7 @@ export function runInstallCli(argv) {
111
117
  const i = argv.indexOf(f);
112
118
  if (i >= 0) {
113
119
  taken.add(i);
114
- if (f !== '--dry-run')
120
+ if (!SWITCHES.has(f))
115
121
  taken.add(i + 1);
116
122
  }
117
123
  }
@@ -128,11 +134,14 @@ export function runInstallCli(argv) {
128
134
  email: get('--email') ?? process.env.SB_EMAIL,
129
135
  password: get('--password') ?? process.env.SB_PASSWORD,
130
136
  clients: get('--client')?.split(','),
137
+ login: argv.includes('--login'),
131
138
  dryRun: argv.includes('--dry-run'),
132
139
  };
133
- if (!opts.token && !(opts.email && opts.password)) {
140
+ if (!opts.token && !(opts.email && opts.password) && !opts.login) {
134
141
  console.error('sbuilder: nothing to install with.\n' +
135
- ' Get a key from your store: Apps → AI agent → Create key, then\n' +
142
+ ' Sign in through the browser (the whole account, no key to copy):\n' +
143
+ ' npx -y sbuilder-mcp install --login --api https://your-host --site site_…\n' +
144
+ ' or use a key from your store: Apps → AI agent → Create key, then\n' +
136
145
  ' npx -y sbuilder-mcp install --token wbk_… --api https://your-host\n');
137
146
  return 1;
138
147
  }
@@ -174,3 +183,87 @@ export function runInstallCli(argv) {
174
183
  return 0;
175
184
  return results.some((r) => r.status === 'installed' || r.status === 'unchanged') ? 0 : 1;
176
185
  }
186
+ /** The stored login's email when it still works (renewing it once if refused), else undefined. */
187
+ async function storedUser(api, f) {
188
+ let pair = readPairSync(api);
189
+ for (let attempt = 0; pair && attempt < 2; attempt++) {
190
+ const res = await f(`${api.replace(/\/+$/, '')}/api/auth/me`, {
191
+ headers: { Authorization: `Bearer ${pair.accessToken}` },
192
+ }).catch(() => null);
193
+ if (res?.ok) {
194
+ const me = (await res.json().catch(() => ({})));
195
+ return me.user?.email || 'this account';
196
+ }
197
+ if (res?.status !== 401)
198
+ return undefined;
199
+ pair = await rotate(api, pair.accessToken, f).catch(() => undefined);
200
+ }
201
+ return undefined;
202
+ }
203
+ /**
204
+ * `install --login`: the browser sign-in `sb login` does, in this terminal.
205
+ * Reuses a login the machine already holds. Returns false when it did not sign in.
206
+ */
207
+ export async function deviceLogin(api, deps = {}) {
208
+ const log = deps.log ?? ((l) => console.error(l));
209
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
210
+ const f = deps.fetchImpl ?? fetch;
211
+ const already = await storedUser(api, f);
212
+ if (already) {
213
+ log(`✔ Already signed in as ${already} on ${api}.`);
214
+ return true;
215
+ }
216
+ const s = await startDevice(api, deps.version ?? '0.0.0', f);
217
+ log('Sign in to Store Builder');
218
+ log(` 1. Open ${s.verificationUri}`);
219
+ log(` 2. Type ${s.userCode}`);
220
+ log(` 3. Check the page shows the same code, then Approve. It expires in ${Math.round(s.expiresIn / 60)} minutes.`);
221
+ if ((deps.open ?? openBrowser)(s.verificationUri))
222
+ log('Opened the page in your browser. Waiting for approval…');
223
+ let interval = s.interval * 1000;
224
+ const deadline = Date.now() + s.expiresIn * 1000;
225
+ while (Date.now() < deadline) {
226
+ await sleep(interval);
227
+ // A dropped connection is not a refusal; anything else the server says is.
228
+ const r = await pollDevice(api, s.deviceCode, f).catch((err) => {
229
+ if (err instanceof TypeError)
230
+ return { state: 'pending' };
231
+ throw err;
232
+ });
233
+ if (r.state === 'approved') {
234
+ await savePair(api, r.pair);
235
+ log('✔ Signed in. The login is kept on this machine (shared with the sb CLI).');
236
+ return true;
237
+ }
238
+ if (r.state === 'slow')
239
+ interval += 5000;
240
+ if (r.state === 'denied') {
241
+ log('✖ The sign-in was denied in the browser. Nothing was installed.');
242
+ return false;
243
+ }
244
+ if (r.state === 'expired')
245
+ break;
246
+ }
247
+ log('✖ The code expired before it was approved. Run the command again.');
248
+ return false;
249
+ }
250
+ /** The CLI entry: signs in first when --login is given, then writes the clients. */
251
+ export async function runInstall(argv, deps = {}) {
252
+ if (argv.includes('--login') && !argv.includes('--dry-run')) {
253
+ const i = argv.indexOf('--api');
254
+ const api = (i >= 0 ? argv[i + 1] : undefined) ?? process.env.SB_API;
255
+ if (!api) {
256
+ console.error('sbuilder: --login needs --api https://your-host (the platform to sign in to).');
257
+ return 1;
258
+ }
259
+ try {
260
+ if (!(await deviceLogin(api, deps)))
261
+ return 1;
262
+ }
263
+ catch (err) {
264
+ console.error(err.message);
265
+ return 1;
266
+ }
267
+ }
268
+ return runInstallCli(argv);
269
+ }
package/dist/server.js CHANGED
@@ -2,12 +2,14 @@ import { setAgentClient } from './transport/identity.js';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4
4
  import { Session } from './transport/auth.js';
5
+ import { readPairSync } from './transport/stored.js';
5
6
  import { Notices } from './mcp/notices.js';
6
7
  import { UndoLog } from './tools/undo.js';
7
8
  import { SWAGGER_SOURCE } from './catalog/api.generated.js';
8
9
  import { ELEMENT_SOURCE } from './catalog/elements.generated.js';
9
10
  import { registerApiTools } from './tools/api.js';
10
11
  import { registerSessionTools } from './tools/session.js';
12
+ import { registerLoginTools } from './tools/login.js';
11
13
  import { registerPageTools } from './tools/page.js';
12
14
  import { registerPageUpdateTools } from './tools/pageupdate.js';
13
15
  import { registerPageVersionTools } from './tools/pageversion.js';
@@ -29,7 +31,7 @@ import { refuseUnknownArgs } from './mcp/strict.js';
29
31
  * It used to claim a base style value "vanishes on publish" — the misreading
30
32
  * CLAUDE.md records as corrected — and every session read it first.
31
33
  */
32
- const INSTRUCTIONS = `Store Builder. Call sb_connect first.
34
+ const INSTRUCTIONS = `Store Builder. Call sb_connect first; sb_login = whole account, sb_site_use = switch.
33
35
 
34
36
  API: sb_api_find query → one line per operation (${SWAGGER_SOURCE.operations} reachable); sb_api_find id → its call sheet; sb_api_call runs it. /api/v1 paths take the API key only; every other path takes the key or the session. Undescribed body: send back a modified copy of the matching GET.
35
37
 
@@ -37,7 +39,7 @@ Design, native first: sb_page_open → sb_catalog_search (${ELEMENT_SOURCE.count
37
39
  - Writes and API calls default to dry_run:true; pass dry_run:false to act.
38
40
  - sb_set writes per breakpoint by default; base is the cascade's fallback layer, for values that should not vary.
39
41
  - Outline flags: global = shared master, an edit lands on every page; overlay = not this page; app = app block, not editable inside.
40
- - sb_live_join shows edits live in an open editor (needs SB_EMAIL/SB_PASSWORD).`;
42
+ - sb_live_join shows edits live in an open editor.`;
41
43
  /**
42
44
  * The published version, read from package.json at runtime so serverInfo never
43
45
  * drifts from what npm shipped. package.json sits one level above both dist/ and
@@ -59,6 +61,7 @@ export function pkgVersion() {
59
61
  */
60
62
  const SESSION_FREE = new Set([
61
63
  'sb_connect',
64
+ 'sb_login',
62
65
  'sb_site_list',
63
66
  'sb_api_find',
64
67
  'sb_api_call',
@@ -77,12 +80,23 @@ const SESSION_FREE = new Set([
77
80
  ]);
78
81
  export function buildContext() {
79
82
  const base = process.env.SB_API ?? 'http://localhost:8080';
83
+ const session = new Session(base);
84
+ // THE MACHINE'S ACCOUNT LOGIN, when there is one (`sbuilder-mcp install
85
+ // --login`, sb_login, or `sb login` — one shared file). A password in the
86
+ // environment still wins: it is the more explicit instruction.
87
+ if (!(process.env.SB_EMAIL && process.env.SB_PASSWORD)) {
88
+ const pair = readPairSync(base);
89
+ if (pair)
90
+ void session.adoptStored(pair);
91
+ }
80
92
  return {
81
93
  base,
82
- session: new Session(base),
94
+ session,
83
95
  apiKey: process.env.SB_TOKEN,
84
96
  siteId: process.env.SB_SITE,
85
97
  siteName: process.env.SB_SITE_NAME,
98
+ // '' = a key whose site the install did not name: unknown, so any switch is "elsewhere".
99
+ keySite: process.env.SB_TOKEN ? (process.env.SB_SITE ?? '') : undefined,
86
100
  notices: new Notices(), undo: new UndoLog(),
87
101
  };
88
102
  }
@@ -102,6 +116,7 @@ export function createServer(ctx = buildContext()) {
102
116
  serializeToolCalls(server, (name) => SESSION_FREE.has(name));
103
117
  refuseUnknownArgs(server);
104
118
  registerSessionTools(server, ctx);
119
+ registerLoginTools(server, ctx, pkgVersion());
105
120
  registerApiTools(server, ctx);
106
121
  const pageSession = registerPageTools(server, ctx);
107
122
  registerPageUpdateTools(server, ctx);
package/dist/tools/api.js CHANGED
@@ -323,7 +323,26 @@ export function shapeResponse(raw, opts) {
323
323
  * session carries the whole account. Preferring it is also what lets a merchant
324
324
  * connect an agent with one env var and no password.
325
325
  */
326
- export function tokenFor(ctx, credential) {
326
+ /**
327
+ * The session moved off the site the API key belongs to. `keySite` is '' when a
328
+ * key was given with no SB_SITE: its site is unknown, so ANY switch counts.
329
+ */
330
+ export function onOtherSite(ctx) {
331
+ return ctx.keySite !== undefined && !!ctx.siteId && ctx.siteId !== ctx.keySite;
332
+ }
333
+ /**
334
+ * May the API key act for `siteId` (default: the current site)? Never once the
335
+ * session moved elsewhere — a key refused there is retried through /api/v1,
336
+ * which acts on the KEY's store: a write on the wrong site, reported as success.
337
+ */
338
+ export function keyServes(ctx, siteId) {
339
+ if (!ctx.apiKey)
340
+ return false;
341
+ if (ctx.keySite && siteId !== undefined)
342
+ return siteId === ctx.keySite;
343
+ return !onOtherSite(ctx);
344
+ }
345
+ export function tokenFor(ctx, credential, siteId) {
327
346
  if (credential === 'apiKey') {
328
347
  // Naming the env var matters: the alternative is a 401 api_key_required
329
348
  // from the platform, which reads like a permissions problem rather than an
@@ -331,11 +350,24 @@ export function tokenFor(ctx, credential) {
331
350
  if (!ctx.apiKey) {
332
351
  throw new Error('sbuilder: SB_TOKEN is not set — /api/v1 operations need an API key');
333
352
  }
353
+ // /api/v1 names no site: the KEY decides which store it acts on. After a
354
+ // switch, a call meant for the current site would land on the key's.
355
+ if (onOtherSite(ctx)) {
356
+ throw new Error(`sbuilder: /api/v1 acts on the API key's own site (${ctx.keySite}), and this session ` +
357
+ `now works on ${ctx.siteId}. Use the /api/sites/{siteId}/… operation instead, or ` +
358
+ `sb_site_use ${ctx.keySite} to go back.`);
359
+ }
334
360
  return ctx.apiKey;
335
361
  }
336
362
  if (credential === 'siteScoped') {
337
- if (ctx.apiKey)
363
+ // The key on its own site; the account login anywhere else. Never the key
364
+ // off its site, even when the login is gone: that is a wrong-site write.
365
+ if (keyServes(ctx, siteId))
338
366
  return ctx.apiKey;
367
+ if (ctx.apiKey && !ctx.session.loggedIn()) {
368
+ throw new Error('sbuilder: this session works on another site than the API key\'s, and the account ' +
369
+ 'login is gone. Call sb_login again, or sb_site_use the key\'s own site.');
370
+ }
339
371
  if (ctx.session.loggedIn())
340
372
  return ctx.session.token();
341
373
  throw new Error('sbuilder: no credential for this site. Set SB_TOKEN to an API key from the site\'s ' +
@@ -6,6 +6,6 @@ import { tokenFor } from './api.js';
6
6
  * the rule and quietly grow a second copy of it. There is exactly one answer to
7
7
  * "which token opens /api/sites", and it lives in `tokenFor`.
8
8
  */
9
- export function siteToken(ctx) {
10
- return tokenFor(ctx, 'siteScoped');
9
+ export function siteToken(ctx, siteId) {
10
+ return tokenFor(ctx, 'siteScoped', siteId);
11
11
  }
@@ -34,6 +34,7 @@ import { offscreenNodes, offscreenRootOf } from '../domains/site/offscreen.js';
34
34
  import { searchStock, SearchUnavailable, NO_SEARCH_NEXT } from '../transport/stock.js';
35
35
  import { siteFor } from './context.js';
36
36
  import { siteToken } from './credentialpick.js';
37
+ import { keyServes } from './api.js';
37
38
  import { projectList, MEDIA_FIELDS } from './project.js';
38
39
  /**
39
40
  * The vocabulary a PURCHASE control's target speaks —
@@ -298,15 +299,15 @@ export function setEvent(doc, id, trigger, action, payload, guard) {
298
299
  * rotates, and a captured string replays an expired token forever on every
299
300
  * reconnect — silently, because a rejected socket auth still fires `onopen`.
300
301
  */
301
- export function liveTokenFor(ctx) {
302
+ export function liveTokenFor(ctx, siteId) {
302
303
  if (!ctx.session.loggedIn() && !ctx.apiKey) {
303
- throw new Error('sbuilder: the live-edit room needs a credential. Set SB_TOKEN, or SB_EMAIL and ' +
304
- 'SB_PASSWORD, and call sb_connect before sb_live_join.');
304
+ throw new Error('sbuilder: the live-edit room needs a credential. Call sb_login (or set SB_TOKEN) ' +
305
+ 'before sb_live_join.');
305
306
  }
306
- // Prefer the key, for the reason `tokenFor` prefers it everywhere: a key is
307
- // narrower — one site, its own scopes, revocable on its own — while a session
308
- // carries the whole account.
309
- return () => (ctx.apiKey ? ctx.apiKey : ctx.session.token());
307
+ // The same rule as every other call (tokenFor): the narrower key on ITS site,
308
+ // the account login on any other — a key is refused by another site's room,
309
+ // and a refused socket fails silently.
310
+ return () => siteToken(ctx, siteId);
310
311
  }
311
312
  /**
312
313
  * Open the room and hand it to the page session.
@@ -326,11 +327,11 @@ export function liveTokenFor(ctx) {
326
327
  * different site or re-join after a drop.
327
328
  */
328
329
  export function joinRoom(ctx, session, siteId) {
329
- const tokenFn = liveTokenFor(ctx);
330
+ const tokenFn = liveTokenFor(ctx, siteId);
330
331
  const wsBase = ctx.base.replace(/^http/, 'ws').replace(/\/$/, '');
331
332
  const socket = new RealtimeSocket(`${wsBase}/api/realtime/ws?site=${encodeURIComponent(siteId)}`, tokenFn, undefined,
332
333
  // A key never expires this way; a session renews near its end of life.
333
- ctx.apiKey ? undefined : () => ctx.session.ensureFresh());
334
+ keyServes(ctx, siteId) ? undefined : () => ctx.session.ensureFresh());
334
335
  const live = new LiveSession(socket, {
335
336
  onRemote: (patches) => session.applyRemote(patches),
336
337
  onDesync: (reason) => session.roomDesync(reason),
@@ -0,0 +1,174 @@
1
+ import { z } from 'zod';
2
+ import { request } from '../transport/http.js';
3
+ import { text } from '../mcp/response.js';
4
+ import { openBrowser, pollDevice, startDevice } from '../transport/device.js';
5
+ import { readPairSync, RELOGIN, savePair } from '../transport/stored.js';
6
+ /** One login in flight per process; a second sb_login keeps waiting on it. The
7
+ * PROMISE is kept, so two calls racing the first start share one code. */
8
+ const pending = new WeakMap();
9
+ /** How long one sb_login call waits for the approval before handing back. */
10
+ export const WAIT = { ms: 45_000 };
11
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
12
+ async function listSites(ctx) {
13
+ const out = (await request({
14
+ base: ctx.base,
15
+ method: 'GET',
16
+ path: '/api/sites',
17
+ token: ctx.session.token(),
18
+ fetchImpl: ctx.fetchImpl,
19
+ }));
20
+ return (out?.sites ?? []).map((s) => ({ id: s.id, name: s.name }));
21
+ }
22
+ /** Who the stored login is, and where the agent stands. */
23
+ export async function accountSummary(ctx) {
24
+ if (!ctx.session.userName) {
25
+ const me = (await request({
26
+ base: ctx.base,
27
+ method: 'GET',
28
+ path: '/api/auth/me',
29
+ token: ctx.session.token(),
30
+ fetchImpl: ctx.fetchImpl,
31
+ }).catch(() => null));
32
+ ctx.session.userName = me?.user?.email || me?.user?.name || '';
33
+ }
34
+ const sites = await listSites(ctx);
35
+ const here = ctx.siteId ? sites.find((s) => s.id === ctx.siteId) : undefined;
36
+ if (here)
37
+ ctx.siteName = here.name;
38
+ return {
39
+ status: 'signed_in',
40
+ user: ctx.session.userName,
41
+ sites,
42
+ ...(ctx.siteId ? { site: ctx.siteId } : {}),
43
+ ...(here ? { site_name: here.name } : {}),
44
+ note: ctx.siteId
45
+ ? here
46
+ ? `Working on ${JSON.stringify(here.name)} (${ctx.siteId}); every tool defaults to it. ` +
47
+ 'sb_site_use moves to another site in this list.'
48
+ : `SB_SITE is ${ctx.siteId}, which this account cannot operate — pick one with sb_site_use.`
49
+ : 'No site selected: pass site_id per call, or pick one with sb_site_use.',
50
+ };
51
+ }
52
+ export async function login(ctx, args, version) {
53
+ const f = ctx.fetchImpl ?? fetch;
54
+ if (args.action === 'logout') {
55
+ pending.delete(ctx);
56
+ await ctx.session.forgetStored();
57
+ return {
58
+ status: 'signed_out',
59
+ note: 'The account login is revoked and removed from this machine (the sb CLI shares it).',
60
+ };
61
+ }
62
+ // A login the machine already holds (sb login, another window) is adopted —
63
+ // a fresh browser flow would take another of the account's device slots.
64
+ if (!ctx.session.isStored()) {
65
+ const filed = readPairSync(ctx.base);
66
+ if (filed)
67
+ await ctx.session.adoptStored(filed);
68
+ }
69
+ if (ctx.session.isStored()) {
70
+ try {
71
+ return await accountSummary(ctx);
72
+ }
73
+ catch (err) {
74
+ // Only a dead login starts a new one; an outage is reported as such.
75
+ if (err.message !== RELOGIN && ctx.session.loggedIn())
76
+ throw err;
77
+ }
78
+ }
79
+ let started = pending.get(ctx);
80
+ let p = started ? await started.catch(() => undefined) : undefined;
81
+ if (!p || Date.now() > p.deadline) {
82
+ started = startDevice(ctx.base, version, f).then((start) => ({
83
+ start,
84
+ deadline: Date.now() + start.expiresIn * 1000,
85
+ interval: start.interval * 1000,
86
+ }));
87
+ pending.set(ctx, started);
88
+ started.catch(() => pending.delete(ctx));
89
+ p = await started;
90
+ const { start } = p;
91
+ const opened = openBrowser(start.verificationUri);
92
+ // RETURN THE CODE NOW. The person needs it to type into the page; waiting
93
+ // for the approval first would hide the one thing they must read.
94
+ return {
95
+ status: 'waiting',
96
+ url: start.verificationUri,
97
+ code: start.userCode,
98
+ browser_opened: opened,
99
+ expires_in_minutes: Math.round(start.expiresIn / 60),
100
+ note: `Tell the person: ${opened ? 'a browser page has opened' : `open ${start.verificationUri}`}, ` +
101
+ `type the code ${start.userCode}, check it matches, and press Approve. Then call sb_login ` +
102
+ 'again — it waits for the approval.',
103
+ };
104
+ }
105
+ const until = Date.now() + WAIT.ms;
106
+ while (Date.now() < until && Date.now() < p.deadline) {
107
+ await sleep(p.interval);
108
+ const r = await pollDevice(ctx.base, p.start.deviceCode, f);
109
+ if (r.state === 'approved') {
110
+ pending.delete(ctx);
111
+ await savePair(ctx.base, r.pair);
112
+ await ctx.session.adoptStored(r.pair);
113
+ ctx.session.userName = '';
114
+ return await accountSummary(ctx);
115
+ }
116
+ if (r.state === 'slow')
117
+ p.interval += 5000;
118
+ if (r.state === 'denied') {
119
+ pending.delete(ctx);
120
+ throw new Error('sbuilder: the login was denied in the browser. Nothing was stored.');
121
+ }
122
+ if (r.state === 'expired') {
123
+ pending.delete(ctx);
124
+ throw new Error('sbuilder: the code expired before it was approved. Call sb_login for a new one.');
125
+ }
126
+ }
127
+ return {
128
+ status: 'waiting',
129
+ url: p.start.verificationUri,
130
+ code: p.start.userCode,
131
+ note: `Not approved yet. The code is ${p.start.userCode}; call sb_login again once it is approved.`,
132
+ };
133
+ }
134
+ /** Move the agent to another site of the account. */
135
+ export async function useSite(ctx, siteId) {
136
+ if (!ctx.session.loggedIn()) {
137
+ if (ctx.apiKey && siteId === ctx.keySite) {
138
+ ctx.siteId = siteId;
139
+ return { site: siteId, note: 'Back on the API key\'s own site.' };
140
+ }
141
+ throw new Error('sbuilder: an API key opens one site only. Call sb_login (approve in the browser) to reach ' +
142
+ 'every site of the account, then sb_site_use again.');
143
+ }
144
+ const sites = await listSites(ctx);
145
+ const site = sites.find((s) => s.id === siteId);
146
+ if (!site) {
147
+ throw new Error(`sbuilder: this account cannot operate ${siteId}. Its sites: ` +
148
+ (sites.map((s) => `${s.id} (${s.name})`).join(', ') || 'none'));
149
+ }
150
+ ctx.siteId = site.id;
151
+ ctx.siteName = site.name;
152
+ return {
153
+ site: site.id,
154
+ site_name: site.name,
155
+ note: `Working on ${JSON.stringify(site.name)} now; every tool defaults to it. A page opened on ` +
156
+ 'the previous site stays open until sb_page_open opens one here.',
157
+ };
158
+ }
159
+ export function registerLoginTools(server, ctx, version) {
160
+ server.registerTool('sb_login', {
161
+ description: 'Sign in to the whole account in the browser, no password. The first call returns a code ' +
162
+ 'to type on the page it opens; call again to wait for the approval. Remembered on this ' +
163
+ 'machine. action:"logout" signs out.',
164
+ inputSchema: { action: z.enum(['start', 'logout']).optional() },
165
+ annotations: { openWorldHint: true },
166
+ }, async (args) => text(await login(ctx, args, version)));
167
+ server.registerTool('sb_site_use', {
168
+ description: 'Switch the site every tool defaults to (needs the sb_login account login).',
169
+ inputSchema: { site_id: z.string() },
170
+ // NOT read-only: it moves where every later write lands, so a client that
171
+ // auto-approves read-only tools must still ask before it.
172
+ annotations: { readOnlyHint: false, idempotentHint: true },
173
+ }, async ({ site_id }) => text(await useSite(ctx, site_id)));
174
+ }
@@ -2241,10 +2241,10 @@ export function registerPageTools(server, ctx) {
2241
2241
  if (!crossSite && to_page_id === from.pageId) {
2242
2242
  throw new Error('sbuilder: that is the open page — omit to_page_id to duplicate in place.');
2243
2243
  }
2244
- if (crossSite && ctx.apiKey) {
2244
+ if (crossSite && ctx.apiKey && !ctx.session.loggedIn()) {
2245
2245
  // A key belongs to exactly ONE site, and every /api/sites route prefers it.
2246
- throw new Error('sbuilder: a cross-site paste needs a session login — an API key (SB_TOKEN) opens one site only. ' +
2247
- 'Unset SB_TOKEN and connect with SB_EMAIL/SB_PASSWORD as a member of both sites.');
2246
+ throw new Error('sbuilder: a cross-site paste needs the account login — an API key (SB_TOKEN) opens one site only. ' +
2247
+ 'Call sb_login (as a member of both sites), then paste again.');
2248
2248
  }
2249
2249
  // A FROZEN copy of the source: opening the target replaces the session's document.
2250
2250
  let src = PageDoc.from(structuredClone(d.doc));
@@ -3,6 +3,7 @@ import { request } from '../transport/http.js';
3
3
  import { text } from '../mcp/response.js';
4
4
  import { API_OPERATIONS } from '../catalog/api.generated.js';
5
5
  import { PLATFORM_SOURCE } from '../catalog/source.generated.js';
6
+ import { accountSummary } from './login.js';
6
7
  /**
7
8
  * The provenance line, or '' when the generator had no git to ask.
8
9
  *
@@ -30,9 +31,29 @@ export function catalogAge(now = new Date()) {
30
31
  * failing the whole connect over it would hide that from a caller who does not
31
32
  * need /api/v1 at all.
32
33
  */
34
+ const LIVE_HINT = 'Nobody watching an open editor sees these edits until sb_live_join is called. Call it ' +
35
+ 'now if a person has the site open — it always yields to a human, and is safe to leave on ' +
36
+ 'for the whole session.';
33
37
  export async function connect(ctx, args) {
34
38
  const email = args.email ?? process.env.SB_EMAIL;
35
39
  const password = args.password ?? process.env.SB_PASSWORD;
40
+ // THE MACHINE'S ACCOUNT LOGIN (sb_login / install --login / sb login): the
41
+ // whole account, every site, no password anywhere.
42
+ if (ctx.session.isStored() && !(args.email && args.password)) {
43
+ const acct = await accountSummary(ctx);
44
+ return {
45
+ user: acct.user,
46
+ sites: acct.sites,
47
+ api_key: ctx.apiKey ? 'present' : 'missing',
48
+ ...(acct.site ? { site: acct.site } : {}),
49
+ ...(acct.site_name ? { site_name: acct.site_name } : {}),
50
+ operations: API_OPERATIONS.length,
51
+ ...(catalogAge() ? { catalog: catalogAge() } : {}),
52
+ note: 'Signed in to the whole account (browser login). ' + acct.note +
53
+ (ctx.apiKey ? '' : ' /api/v1 operations need an API key; use the /api/sites/{siteId}/… ones.'),
54
+ live: LIVE_HINT,
55
+ };
56
+ }
36
57
  // KEY-ONLY MODE. An API key from the site's Agent app opens both surfaces on
37
58
  // its own, which is the whole point of the connect button: one env var, no
38
59
  // password anywhere. There is no login to do and no site list to fetch — a key
@@ -49,12 +70,13 @@ export async function connect(ctx, args) {
49
70
  ...(catalogAge() ? { catalog: catalogAge() } : {}),
50
71
  note: ctx.siteId
51
72
  ? `Connected with an API key alone, on site ${ctx.siteId} (SB_SITE)${ctx.siteName ? `, the store called ${JSON.stringify(ctx.siteName)}` : ''}. Every tool ` +
52
- 'defaults to it, so site_id is optional. Set SB_EMAIL and SB_PASSWORD as well if ' +
53
- 'you want account-level calls (listing sites, members, roles), which a key cannot make.'
73
+ 'defaults to it, so site_id is optional. Call sb_login (approve in the browser) for ' +
74
+ 'account-level calls and other sites (listing sites, members, roles, sb_site_use), ' +
75
+ 'which a key cannot make.'
54
76
  : 'Connected with an API key alone. It is bound to one site, so there is no site list — ' +
55
- 'pass that site id to sb_page_open, or set SB_SITE once and leave site_id out. Set ' +
56
- 'SB_EMAIL and SB_PASSWORD as well if you want account-level calls (listing sites, ' +
57
- 'members, roles), which a key cannot make.',
77
+ 'pass that site id to sb_page_open, or set SB_SITE once and leave site_id out. Call ' +
78
+ 'sb_login (approve in the browser) for account-level calls and other sites, which a ' +
79
+ 'key cannot make.',
58
80
  // SAID HERE BECAUSE HERE IS WHERE IT IS STILL FREE.
59
81
  //
60
82
  // `sb_live_join` is opt-in and one call, and an agent that never makes it
@@ -68,14 +90,13 @@ export async function connect(ctx, args) {
68
90
  // an editor open beside it and never joined, because no surface an agent
69
91
  // reads on the way in mentions the room. The tool's own description says
70
92
  // what it does; nothing said WHEN. Connect is that when.
71
- live: 'Nobody watching an open editor sees these edits until sb_live_join is called. Call it ' +
72
- 'now if a person has the site open — it takes this key\'s own name, always yields to a ' +
73
- 'human, and is safe to leave on for the whole session.',
93
+ live: LIVE_HINT,
74
94
  };
75
95
  }
76
96
  if (!email || !password) {
77
- throw new Error('sbuilder: set SB_TOKEN to an API key from the site\'s Agent app, or set SB_EMAIL and ' +
78
- 'SB_PASSWORD for a full account session.');
97
+ throw new Error('sbuilder: not signed in. Call sb_login — it opens the browser, the person types a code and ' +
98
+ 'approves, and the whole account is reachable. (Or set SB_TOKEN to an API key from the ' +
99
+ 'site\'s Agent app.)');
79
100
  }
80
101
  await ctx.session.login(email, password);
81
102
  const listed = (await request({
@@ -103,8 +124,7 @@ export async function connect(ctx, args) {
103
124
  }
104
125
  export function registerSessionTools(server, ctx) {
105
126
  server.registerTool('sb_connect', {
106
- description: 'Log in and list the sites this account can operate. Call this first. Reads SB_EMAIL and ' +
107
- 'SB_PASSWORD from the environment unless you pass them.',
127
+ description: 'Call this first: what this install can reach, and the account\'s sites.',
108
128
  inputSchema: {
109
129
  email: z.string().optional(),
110
130
  password: z.string().optional(),
@@ -128,10 +148,10 @@ export function registerSessionTools(server, ctx) {
128
148
  (ctx.siteId
129
149
  ? `This install works on ${ctx.siteId} (SB_SITE).`
130
150
  : 'Set SB_SITE to the site you mean.') +
131
- ' Set SB_EMAIL and SB_PASSWORD if you genuinely need the account-level list.');
151
+ ' Call sb_login (approve in the browser) if you need the account-level list.');
132
152
  }
133
- throw new Error('sbuilder: no credential. Set SB_TOKEN to an API key, or SB_EMAIL and SB_PASSWORD ' +
134
- 'and call sb_connect.');
153
+ throw new Error('sbuilder: no credential. Call sb_login (approve in the browser), or set SB_TOKEN to an ' +
154
+ 'API key.');
135
155
  }
136
156
  return text(await request({
137
157
  base: ctx.base,
@@ -130,7 +130,7 @@ async function writeLocale(ctx, siteId, path, creds, current, locale, refused) {
130
130
  }
131
131
  function refusal(siteId, what, refused, ctx) {
132
132
  return new Error(`sbuilder: 403 — the platform refused to ${what} on ${siteId} with ${refused.join(' and ')}` +
133
- (ctx.apiKey && !ctx.session.loggedIn() ? ' (no session to try: set SB_EMAIL/SB_PASSWORD)' : '') +
133
+ (ctx.apiKey && !ctx.session.loggedIn() ? ' (no account login to try: call sb_login)' : '') +
134
134
  '. The whole-settings write needs settings permission; a locale-only write needs ' +
135
135
  'pages.write on a platform that has it. Nothing was changed.');
136
136
  }
@@ -1,4 +1,5 @@
1
1
  import { onUnauthorized, request } from './http.js';
2
+ import { RELOGIN, rotate, takePair } from './stored.js';
2
3
  /**
3
4
  * A user session against the platform's private API.
4
5
  *
@@ -19,6 +20,13 @@ export class Session {
19
20
  expiresAt = 0;
20
21
  refreshToken = null;
21
22
  name = '';
23
+ /**
24
+ * The pair came from the machine's shared login file (sb login / sb_login),
25
+ * not from a password sign-in of this process. Two consequences: a refresh
26
+ * goes through the file's lock (other processes hold the same pair), and
27
+ * exiting does NOT sign it out — the login belongs to the machine.
28
+ */
29
+ stored = false;
22
30
  constructor(base, fetchImpl) {
23
31
  this.base = base;
24
32
  this.fetchImpl = fetchImpl;
@@ -51,6 +59,54 @@ export class Session {
51
59
  get userName() {
52
60
  return this.name;
53
61
  }
62
+ set userName(v) {
63
+ this.name = v;
64
+ }
65
+ /** True when this session is the machine's shared account login. */
66
+ isStored() {
67
+ return this.stored && this.access !== null;
68
+ }
69
+ /**
70
+ * Take over the machine's stored login. A password session this process
71
+ * opened is signed out first, so it does not strand a device slot.
72
+ */
73
+ async adoptStored(pair) {
74
+ // No await when nothing is held, so a boot-time adoption is synchronous.
75
+ if (!this.stored && this.access)
76
+ await this.logout();
77
+ this.stored = true;
78
+ this.access = pair.accessToken;
79
+ this.refreshToken = pair.refreshToken;
80
+ // A stored pair carries no expiresIn; the token's own `exp` says when, so
81
+ // ensureFresh() can renew before a call that cannot retry (uploads, socket).
82
+ this.expiresAt = jwtExpiry(pair.accessToken);
83
+ this.listen();
84
+ }
85
+ /**
86
+ * Sign the MACHINE out: revoke the stored login on the server and remove it
87
+ * from the shared file. Every MCP window and the sb CLI lose it together.
88
+ */
89
+ async forgetStored() {
90
+ await this.renewing?.catch(() => undefined);
91
+ const mine = this.refreshToken;
92
+ this.stored = false;
93
+ this.access = null;
94
+ this.refreshToken = null;
95
+ this.unrenew?.();
96
+ this.unrenew = null;
97
+ // Revoke what the FILE holds — `sb login` may have replaced the pair this
98
+ // process adopted — and the one in memory if it differs.
99
+ const filed = await takePair(this.base);
100
+ for (const rt of new Set([filed?.refreshToken, mine].filter(Boolean))) {
101
+ await request({
102
+ base: this.base,
103
+ method: 'POST',
104
+ path: '/api/auth/logout',
105
+ body: { refreshToken: rt },
106
+ fetchImpl: this.fetchImpl,
107
+ }).catch((err) => console.error('[sbuilder-mcp] sign-out failed:', err.message));
108
+ }
109
+ }
54
110
  token() {
55
111
  if (!this.access)
56
112
  throw new Error('sbuilder: not logged in — call sb_connect first');
@@ -70,6 +126,7 @@ export class Session {
70
126
  // A second sb_connect in one process would otherwise strand the first
71
127
  // device session — see logout().
72
128
  await this.logout();
129
+ this.stored = false;
73
130
  const out = (await request({
74
131
  base: this.base,
75
132
  method: 'POST',
@@ -88,6 +145,31 @@ export class Session {
88
145
  const rt = this.refreshToken;
89
146
  if (!rt)
90
147
  throw new Error('sbuilder: no refresh token — log in first');
148
+ if (this.stored) {
149
+ const stale = this.access;
150
+ let next;
151
+ try {
152
+ next = await rotate(this.base, stale ?? '', this.fetchImpl ?? fetch);
153
+ }
154
+ catch (err) {
155
+ // The login is gone (or the file is): stop presenting a dead token.
156
+ if (err.message === RELOGIN) {
157
+ this.access = null;
158
+ this.refreshToken = null;
159
+ this.unrenew?.();
160
+ this.unrenew = null;
161
+ }
162
+ throw err;
163
+ }
164
+ if (this.refreshToken !== rt)
165
+ return;
166
+ if (this.access)
167
+ this.retired.add(this.access);
168
+ this.access = next.accessToken;
169
+ this.refreshToken = next.refreshToken;
170
+ this.expiresAt = jwtExpiry(next.accessToken);
171
+ return;
172
+ }
91
173
  const out = (await request({
92
174
  base: this.base,
93
175
  method: 'POST',
@@ -134,11 +216,14 @@ export class Session {
134
216
  // brings back, not the one it just spent (presenting a used one ends the session).
135
217
  await this.renewing?.catch(() => undefined);
136
218
  const refreshToken = this.refreshToken;
219
+ const shared = this.stored;
137
220
  this.access = null;
138
221
  this.refreshToken = null;
139
222
  this.unrenew?.();
140
223
  this.unrenew = null;
141
- if (!refreshToken)
224
+ // THE MACHINE'S login, shared with other windows and the sb CLI: a process
225
+ // exiting is not the person signing out. forgetStored() is that.
226
+ if (!refreshToken || shared)
142
227
  return;
143
228
  try {
144
229
  await request({
@@ -154,6 +239,19 @@ export class Session {
154
239
  }
155
240
  }
156
241
  }
242
+ /** A JWT's `exp` as an epoch-ms deadline; 0 when it is not a JWT or has none. */
243
+ export function jwtExpiry(token) {
244
+ try {
245
+ const part = token.split('.')[1];
246
+ if (!part)
247
+ return 0;
248
+ const exp = JSON.parse(Buffer.from(part, 'base64url').toString('utf8')).exp;
249
+ return typeof exp === 'number' && exp > 0 ? exp * 1000 : 0;
250
+ }
251
+ catch {
252
+ return 0;
253
+ }
254
+ }
157
255
  /** expiresIn seconds → an epoch deadline; 0 when the pair carried none. */
158
256
  function expiry(seconds) {
159
257
  return typeof seconds === 'number' && seconds > 0 ? Date.now() + seconds * 1000 : 0;
@@ -0,0 +1,85 @@
1
+ import { spawn } from 'node:child_process';
2
+ /**
3
+ * The platform's browser login (RFC 8628 shape) — the flow `sb login` uses.
4
+ *
5
+ * The person opens the editor's /device page, TYPES the code shown here, checks
6
+ * it matches, and approves. The code is never put in the URL on purpose: a link
7
+ * that pre-fills it is a link a phisher can send.
8
+ */
9
+ /** What the approval page shows as the asking app — on the server's allowlist
10
+ * (web_builder KnownDeviceClients) from v1.0.278; older servers say "unknown app". */
11
+ export const DEVICE_CLIENT = 'sbuilder-mcp';
12
+ const trim = (base) => base.replace(/\/+$/, '');
13
+ async function post(base, path, body, fetchImpl) {
14
+ const res = await fetchImpl(`${trim(base)}${path}`, {
15
+ method: 'POST',
16
+ headers: { 'Content-Type': 'application/json' },
17
+ body: JSON.stringify(body),
18
+ });
19
+ const data = (await res.json().catch(() => ({})));
20
+ return { status: res.status, data };
21
+ }
22
+ export async function startDevice(base, version, fetchImpl = fetch) {
23
+ const r = await post(base, '/api/auth/device/start', { client: DEVICE_CLIENT, clientVersion: version }, fetchImpl);
24
+ if (r.status !== 200) {
25
+ throw new Error(r.data.code === 'device_login_unavailable'
26
+ ? 'sbuilder: this platform has no browser login configured (device_login_unavailable). ' +
27
+ 'Use an API key (SB_TOKEN) instead.'
28
+ : `sbuilder: could not start the browser login: HTTP ${r.status} ${String(r.data.error ?? '')}`);
29
+ }
30
+ return r.data;
31
+ }
32
+ /** One poll. A 429 counts as slow_down, as the CLI treats it. */
33
+ export async function pollDevice(base, deviceCode, fetchImpl = fetch) {
34
+ const r = await post(base, '/api/auth/device/token', { deviceCode }, fetchImpl);
35
+ if (r.status === 200) {
36
+ const t = (r.data.tokens ?? {});
37
+ if (!t.accessToken || !t.refreshToken)
38
+ throw new Error('sbuilder: the login answered without tokens');
39
+ return { state: 'approved', pair: { accessToken: t.accessToken, refreshToken: t.refreshToken } };
40
+ }
41
+ const code = r.data.code;
42
+ if (code === 'authorization_pending')
43
+ return { state: 'pending' };
44
+ if (code === 'slow_down' || r.status === 429)
45
+ return { state: 'slow' };
46
+ if (code === 'access_denied')
47
+ return { state: 'denied' };
48
+ if (code === 'expired_token')
49
+ return { state: 'expired' };
50
+ throw new Error(`sbuilder: the browser login failed: HTTP ${r.status} ${String(r.data.error ?? '')}`);
51
+ }
52
+ /**
53
+ * Best effort: a machine with no browser (SSH, CI) still has the address,
54
+ * which every caller prints. SB_NO_BROWSER=1 turns it off.
55
+ */
56
+ export function openBrowser(url) {
57
+ if (process.env.SB_NO_BROWSER)
58
+ return false;
59
+ // The URL comes from the server: only a web page is opened, never another
60
+ // scheme, and never through a shell (cmd would read `&` in it as a command).
61
+ let href;
62
+ try {
63
+ const u = new URL(url);
64
+ if (u.protocol !== 'https:' && u.protocol !== 'http:')
65
+ return false;
66
+ href = u.href;
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ const [cmd, args] = process.platform === 'darwin'
72
+ ? ['open', [href]]
73
+ : process.platform === 'win32'
74
+ ? ['rundll32', ['url.dll,FileProtocolHandler', href]]
75
+ : ['xdg-open', [href]];
76
+ try {
77
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
78
+ child.on('error', () => { });
79
+ child.unref();
80
+ return true;
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ }
@@ -8,6 +8,7 @@ import { request as httpRequest } from 'node:http';
8
8
  import { request as httpsRequest } from 'node:https';
9
9
  import { ApiError } from './http.js';
10
10
  import { siteToken } from '../tools/credentialpick.js';
11
+ import { keyServes } from '../tools/api.js';
11
12
  /**
12
13
  * Both upload doors answer `{ url, key, size, asset }`, and the asset ROW carries
13
14
  * only its object key — the url is top-level. Reading `asset.url` alone reported
@@ -87,7 +88,7 @@ export function typeForName(name) {
87
88
  async function fromUrl(ctx, siteId, url, source) {
88
89
  const doFetch = ctx.fetchImpl ?? fetch;
89
90
  // Its own fetch, so the 401 renewal in http.ts never sees it — renew first.
90
- if (!ctx.apiKey && ctx.session.loggedIn())
91
+ if (ctx.session.loggedIn() && !keyServes(ctx, siteId))
91
92
  await ctx.session.ensureFresh().catch(() => undefined);
92
93
  const res = await doFetch(`${ctx.base.replace(/\/$/, '')}/api/media/${encodeURIComponent(siteId)}/from-url`, {
93
94
  method: 'POST',
@@ -314,7 +315,7 @@ export async function fetchPublic(ctx, doFetch, url) {
314
315
  }
315
316
  export async function uploadMedia(ctx, siteId, source) {
316
317
  const doFetch = ctx.fetchImpl ?? fetch;
317
- if (!ctx.apiKey && ctx.session.loggedIn())
318
+ if (ctx.session.loggedIn() && !keyServes(ctx, siteId))
318
319
  await ctx.session.ensureFresh().catch(() => undefined);
319
320
  // THE SERVER'S OWN DOOR FIRST, when the source is a URL.
320
321
  //
@@ -394,7 +395,7 @@ export async function uploadMedia(ctx, siteId, source) {
394
395
  // built — but the identity headers belong here as much as on any other call:
395
396
  // an install whose only traffic is image uploads is still an install.
396
397
  headers: {
397
- Authorization: `Bearer ${siteToken(ctx)}`,
398
+ Authorization: `Bearer ${siteToken(ctx, siteId)}`,
398
399
  Accept: 'application/json',
399
400
  ...identityHeaders(),
400
401
  },
@@ -414,7 +415,9 @@ export async function uploadMedia(ctx, siteId, source) {
414
415
  // So a refusal here is not the end of the road, and retrying costs one request
415
416
  // on a path that was failing anyway. Only when BOTH doors refuse is the key
416
417
  // itself the suspect.
417
- if ((res.status === 401 || res.status === 403) && ctx.apiKey) {
418
+ // Only for the KEY's own site: /api/v1 names no site, so off it this retry
419
+ // would upload into the key's store and report success.
420
+ if ((res.status === 401 || res.status === 403) && keyServes(ctx, siteId)) {
418
421
  const viaPartner = await post('/api/v1/media');
419
422
  if (viaPartner.ok)
420
423
  res = viaPartner;
@@ -450,7 +453,7 @@ export async function uploadMedia(ctx, siteId, source) {
450
453
  'site, since a key minted for another one is refused before the upload is read. Or the ' +
451
454
  'DEPLOYMENT: /api/media took keys only from "feat(media): a wbk_ API key may upload", ' +
452
455
  'so a server older than that refuses a perfectly good key — check the running build ' +
453
- "before changing the key. Failing both, set SB_EMAIL / SB_PASSWORD to upload as a person.");
456
+ "before changing the key. Failing both, call sb_login to upload as a person.");
454
457
  }
455
458
  const env = (parsed ?? {});
456
459
  const fieldText = env.fields
@@ -0,0 +1,143 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { mkdir, open, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join } from 'node:path';
5
+ import { randomBytes } from 'node:crypto';
6
+ /** ${XDG_CONFIG_HOME:-~/.config}/sb/credentials.json — the CLI's path, exactly. */
7
+ export function credentialsPath(env = process.env) {
8
+ const base = env.XDG_CONFIG_HOME || join(homedir(), '.config');
9
+ return join(base, 'sb', 'credentials.json');
10
+ }
11
+ /** The key a pair is stored under: one per API origin, so dev and prod coexist. */
12
+ export function originOf(api) {
13
+ return new URL(api).origin;
14
+ }
15
+ export const RELOGIN = 'sbuilder: the account login on this machine has expired or was signed out. Call sb_login ' +
16
+ '(or run `sb login`) and approve it in the browser again.';
17
+ async function readAll(path) {
18
+ try {
19
+ return JSON.parse(await readFile(path, 'utf8'));
20
+ }
21
+ catch (err) {
22
+ if (err.code === 'ENOENT')
23
+ return {};
24
+ throw new Error(`sbuilder: ${path} is not readable as JSON — delete it and sign in again.`);
25
+ }
26
+ }
27
+ /** Startup read, synchronous so a context can be built before the transport opens. */
28
+ export function readPairSync(api, path = credentialsPath()) {
29
+ try {
30
+ const pair = JSON.parse(readFileSync(path, 'utf8'))[originOf(api)];
31
+ return pair?.accessToken && pair?.refreshToken ? pair : undefined;
32
+ }
33
+ catch {
34
+ // Absent or unreadable: no stored login. An unreadable file is reported
35
+ // when something tries to WRITE it, not at boot.
36
+ return undefined;
37
+ }
38
+ }
39
+ /** Temp file + rename, owner-only: `mode` applies only to a file being created. */
40
+ async function writeAll(path, data) {
41
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
42
+ const tmp = `${path}.${randomBytes(6).toString('hex')}.tmp`;
43
+ await writeFile(tmp, JSON.stringify(data, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
44
+ await rename(tmp, path);
45
+ }
46
+ /** Lock timings; exported so a test can shorten them. Same values as the CLI. */
47
+ export const LOCK = { retryMs: 50, staleMs: 30_000, giveUpMs: 60_000 };
48
+ /** Runs `fn` holding `<path>.lock` (O_EXCL). A lock older than staleMs is a crashed holder. */
49
+ export async function withLock(path, fn) {
50
+ const lock = `${path}.lock`;
51
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
52
+ const started = Date.now();
53
+ for (;;) {
54
+ try {
55
+ const fh = await open(lock, 'wx', 0o600);
56
+ await fh.close();
57
+ break;
58
+ }
59
+ catch (err) {
60
+ if (err.code !== 'EEXIST')
61
+ throw err;
62
+ const age = await stat(lock).then((s) => Date.now() - s.mtimeMs, () => 0);
63
+ if (age > LOCK.staleMs) {
64
+ await unlink(lock).catch(() => { });
65
+ continue;
66
+ }
67
+ if (Date.now() - started > LOCK.giveUpMs) {
68
+ throw new Error(`sbuilder: another process is holding ${lock}. If none is running, delete it.`);
69
+ }
70
+ await new Promise((r) => setTimeout(r, LOCK.retryMs));
71
+ }
72
+ }
73
+ try {
74
+ return await fn();
75
+ }
76
+ finally {
77
+ await unlink(lock).catch(() => { });
78
+ }
79
+ }
80
+ /** Stores (or, with undefined, removes) the pair for an API, under the lock. */
81
+ export async function savePair(api, pair, path = credentialsPath()) {
82
+ await withLock(path, async () => {
83
+ const all = await readAll(path);
84
+ if (pair)
85
+ all[originOf(api)] = pair;
86
+ else
87
+ delete all[originOf(api)];
88
+ await writeAll(path, all);
89
+ });
90
+ }
91
+ /** Removes and returns the pair the FILE holds now (which may not be the one in memory). */
92
+ export async function takePair(api, path = credentialsPath()) {
93
+ return withLock(path, async () => {
94
+ const all = await readAll(path);
95
+ const pair = all[originOf(api)];
96
+ if (pair) {
97
+ delete all[originOf(api)];
98
+ await writeAll(path, all);
99
+ }
100
+ return pair;
101
+ });
102
+ }
103
+ /**
104
+ * The server refused `rejected`: return the pair to continue with.
105
+ *
106
+ * Adopts a pair another process already rotated to; otherwise rotates once and
107
+ * writes it back. A 400/401 from the refresh means the login is gone — the
108
+ * entry is removed and RELOGIN thrown. An outage keeps the pair.
109
+ */
110
+ export function rotate(api, rejected, fetchImpl = fetch, path = credentialsPath()) {
111
+ const origin = originOf(api);
112
+ return withLock(path, async () => {
113
+ const all = await readAll(path);
114
+ const pair = all[origin];
115
+ if (!pair)
116
+ throw new Error(RELOGIN);
117
+ if (pair.accessToken !== rejected)
118
+ return pair;
119
+ let res;
120
+ try {
121
+ res = await fetchImpl(`${api.replace(/\/+$/, '')}/api/auth/refresh`, {
122
+ method: 'POST',
123
+ headers: { 'Content-Type': 'application/json' },
124
+ body: JSON.stringify({ refreshToken: pair.refreshToken }),
125
+ });
126
+ }
127
+ catch {
128
+ throw new Error(`sbuilder: could not reach ${origin} to renew the login — try again.`);
129
+ }
130
+ if (res.status === 400 || res.status === 401) {
131
+ delete all[origin];
132
+ await writeAll(path, all);
133
+ throw new Error(RELOGIN);
134
+ }
135
+ if (!res.ok)
136
+ throw new Error(`sbuilder: could not renew the login: HTTP ${res.status}. Try again.`);
137
+ const { tokens } = (await res.json());
138
+ const next = { accessToken: tokens.accessToken, refreshToken: tokens.refreshToken };
139
+ all[origin] = next;
140
+ await writeAll(path, all);
141
+ return next;
142
+ });
143
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sbuilder-mcp",
3
- "version": "0.108.0",
3
+ "version": "0.109.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",