toolaby 1.6.1 → 1.6.2

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/README.md CHANGED
@@ -24,14 +24,14 @@ If the extension is built with WXT, CRXJS or Plasmo, the command puts the same f
24
24
 
25
25
  **`toolaby create <tool-id>`** makes a new, minimal extension in a folder named after the tool, ready for *Load unpacked*.
26
26
 
27
- **`toolaby pack [folder]`** makes the zip for the Chrome Web Store from your built extension: the manifest's `key` left out (the store refuses one it did not issue), and refused if the build carries a Test key or points at `localhost`. A store zip is public, so files that look private (`*.pem`, `*.key`, `*.p12` and other keys, `*.env`, `credentials.json`, source maps) are left out and named; `--allow-private` packs them. Dotfiles and links that lead out of the folder are never packed. Nothing is sent anywhere.
27
+ **`toolaby pack [folder]`** makes the zip for the Chrome Web Store from your built extension: the manifest's `key` left out (the store refuses one it did not issue), and refused if the build carries a Test key or points at `localhost`. A store zip is public, so files that look private (`*.pem`, `*.key`, `*.p12` and other keys, `id_rsa` and the other SSH keys, certificates, `*.env`, `credentials.json`, a service account's key such as `firebase-adminsdk-….json`, `_netrc`, source maps) are left out and named; `--allow-private` packs them. Dotfiles and links that lead out of the folder are never packed. Nothing is sent anywhere.
28
28
 
29
29
  **`toolaby tools`** lists your tools and their ids. **`toolaby whoami`** says who you are signed in as. **`toolaby logout`** signs the command out and revokes its session on the server.
30
30
 
31
31
  ## Where things live
32
32
 
33
33
  - Your session: `~/.config/toolaby/credentials.json`, readable by you alone (mode 600). `toolaby logout` deletes it after revoking it.
34
- - The session is per side. `TOOLABY_TOKEN` stands in for the file where there is no home directory (CI). `TOOLABY_WALL` or `--wall <url>` names any other Wall.
34
+ - The session is per side. `TOOLABY_TOKEN` stands in for the file where there is no home directory (CI), and is sent to one Wall only: Live (`toolaby.app`), or the one `TOOLABY_TOKEN_WALL` names — `TOOLABY_TOKEN_WALL=https://test.toolaby.app` for a Test session. If that Wall refuses it, the session `toolaby login` stored for that Wall is used instead. `TOOLABY_WALL` or `--wall <url>` names any other Wall.
35
35
 
36
36
  `wire` and `create` write only inside the folder they work on, and never through a symbolic link. A manifest, a framework's config or a Wall that names a place outside it (`../`, an absolute path, a link) is refused before anything is written. `create` writes only the files it knows a new extension has.
37
37
 
package/bin.mjs CHANGED
@@ -10,6 +10,7 @@
10
10
  // toolaby mcp the Wall for coding agents: an MCP server on stdio (lib/mcp.js)
11
11
  // toolaby webhooks events the six events, with an example of each
12
12
  // toolaby webhooks trigger <event> send an example delivery: to your registered endpoints, or with --to straight to a local server
13
+ // toolaby webhooks secret this machine's development secret, which --to signs with
13
14
  // toolaby webhooks endpoints the workspace's endpoints
14
15
  // toolaby webhooks add <url> register an endpoint; the secret is printed once
15
16
  // toolaby webhooks remove <id> remove one
@@ -23,13 +24,14 @@
23
24
  // session lives in ~/.config/toolaby/credentials.json (mode 600), one per
24
25
  // side; a command that needs one and has none signs you in on the spot.
25
26
  // `logout` revokes it on the server before forgetting it. TOOLABY_TOKEN
26
- // stands in for the file where there is no home (CI); TOOLABY_WALL or
27
- // `--wall <url>` names any other Wall (a laptop's, a self-hosted one).
27
+ // stands in for the file where there is no home (CI), for one Wall alone:
28
+ // Live, or the one TOOLABY_TOKEN_WALL names. TOOLABY_WALL or `--wall <url>`
29
+ // names any other Wall (a laptop's, a self-hosted one).
28
30
  //
29
31
  // The wiring rules — what a folder is and what its manifest needs — are the
30
32
  // platform's own (wall/src/packages/wiring), carried here transpiled in lib/,
31
33
  // so this and the dashboard's Wire button never disagree.
32
- import { mkdirSync, writeFileSync, existsSync, readFileSync, readdirSync, statSync, lstatSync, realpathSync, chmodSync, unlinkSync } from 'node:fs';
34
+ import { mkdirSync, writeFileSync, existsSync, readFileSync, readdirSync, statSync, lstatSync, realpathSync, chmodSync, unlinkSync, renameSync } from 'node:fs';
33
35
  import { join, resolve, dirname, relative, basename, sep } from 'node:path';
34
36
  import { deflateRawSync } from 'node:zlib';
35
37
  import { homedir } from 'node:os';
@@ -39,9 +41,9 @@ import { wireManifest, drawsItself, WORKER_LINES } from './lib/manifest.js';
39
41
  import { detectProject, CODE_FILES, POPUP_FILES, SIDE_PANEL_FILES, filesToWrite, fillPages, scaffoldManifest, scaffoldFilesFor, surfacesOf, hasPopup, hasSidePanel, SURFACES, STALE_FILES, BUILD_COPY_NOTE, AGENT_FILES, AGENT_ENTRY_FILES } from './lib/project.js';
40
42
  import { runMcp } from './lib/mcp.js';
41
43
  import { runCheck } from './lib/check.js';
42
- import { inside, signInPage, opener, privateKind, SCAFFOLD_FILES } from './lib/safe.js';
44
+ import { inside, signInPage, opener, privateKind, privateContent, oneLine, fetchBounded, fetchHere, readText, SCAFFOLD_FILES } from './lib/safe.js';
43
45
 
44
- const VERSION = '1.6.1';
46
+ const VERSION = '1.6.2';
45
47
  const CLIENT_ID = 'toolaby-cli';
46
48
  const argv = process.argv.slice(2);
47
49
  // `--version` and `--help` are commands of their own; every other command is the first bare word.
@@ -53,11 +55,18 @@ const opt = (k, d = null) => { const i = rest.indexOf(k); return i >= 0 && rest[
53
55
  const flag = (k) => rest.includes(k) || (k === '--force' && command === 'upgrade');
54
56
  const WALLS = { test: 'https://test.toolaby.app', live: 'https://toolaby.app' };
55
57
  const live = flag('--live');
56
- const wall = (opt('--wall') ?? process.env.TOOLABY_WALL ?? (live ? WALLS.live : WALLS.test)).replace(/\/$/, '');
58
+ // An address as fetch() reads it: a URL loses its tabs and line breaks when it is parsed, and kept in the name every
59
+ // message prints, a --wall or a TOOLABY_WALL with one in it drew lines of its own (25 Sep 2026).
60
+ const address = (s) => s.replace(/[\t\n\r]/g, '').replace(/\/$/, '');
61
+ const wall = address(opt('--wall') ?? process.env.TOOLABY_WALL ?? (live ? WALLS.live : WALLS.test));
57
62
  /** The side, for every message: what a developer must never be unsure of. */
58
63
  const side = wall === WALLS.live ? 'Live' : wall === WALLS.test ? 'Test' : wall;
59
- const out = (s = '') => console.log(s);
60
- const fail = (s) => { console.error(`\n ${s}\n`); process.exit(1); };
64
+ // Every line leaves without terminal controls: names, paths and answers come from folders and servers this command does
65
+ // not own, and one could clear the screen, draw a fake ✓ and hide what followed (25 Sep 2026). The command writes none,
66
+ // nor any character that shows nothing — a zero width, a mark of direction, a filler — which could hide a word.
67
+ const plain = (s) => String(s).replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u115f\u1160\u200b-\u200f\u2028-\u202e\u2060-\u2069\u2800\u3164\ufeff\uffa0]/g, '');
68
+ const out = (s = '') => console.log(plain(s));
69
+ const fail = (s) => { console.error(`\n ${plain(s)}\n`); process.exit(1); };
61
70
 
62
71
  // ── The session: one per Wall, in the user's config, readable by them alone ─────────────────────────────────────────
63
72
  const CONFIG_DIR = join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'toolaby');
@@ -68,14 +77,29 @@ function writeCredentials(all) {
68
77
  writeFileSync(CREDENTIALS, JSON.stringify(all, null, 2) + '\n', { mode: 0o600 });
69
78
  try { chmodSync(CREDENTIALS, 0o600); } catch { /* not every filesystem has modes */ }
70
79
  }
71
- const storedToken = () => process.env.TOOLABY_TOKEN || readCredentials()[wall]?.token || null;
80
+ // TOOLABY_TOKEN goes to one Wall, the one it was made for: the one TOOLABY_TOKEN_WALL names, or — with none named —
81
+ // Live. A --wall or a TOOLABY_WALL, which a cloned project's settings can set, once received it wherever it pointed,
82
+ // and with no Wall named it went to Test and Live alike, so a CI job's Live session reached Test too (25 Sep 2026).
83
+ // Refused there (401), it gives way to the session `toolaby login` stored for that Wall, and is not sent again.
84
+ const tokenWall = address(process.env.TOOLABY_TOKEN_WALL || WALLS.live);
85
+ let envRefused = false;
86
+ const envToken = () => (process.env.TOOLABY_TOKEN && !envRefused && tokenWall === wall ? process.env.TOOLABY_TOKEN : null);
87
+ const storedToken = () => envToken() || readCredentials()[wall]?.token || null;
88
+ /** Said where a session is missing and TOOLABY_TOKEN is set: it is kept for another Wall, and a CI job should know. */
89
+ const envElsewhere = () => (process.env.TOOLABY_TOKEN && !envRefused && !envToken() ? `\n TOOLABY_TOKEN is sent to ${tokenWall} alone; TOOLABY_TOKEN_WALL=${wall} sends it here instead.` : '');
72
90
 
73
91
  async function api(path, { method = 'GET', body, token = storedToken(), raw = false } = {}) {
74
- const res = await fetch(`${wall}${path}`, {
92
+ // Only the Wall answers for the Wall: a redirect elsewhere is refused (lib/safe.js).
93
+ const res = await fetchHere(`${wall}${path}`, {
75
94
  method,
76
95
  headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'User-Agent': `toolaby-cli/${VERSION}`, ...(token ? { Authorization: `Bearer ${token}` } : {}) },
77
96
  body: body ? JSON.stringify(body) : undefined,
78
97
  }).catch((e) => { throw new Error(`Could not reach ${wall}: ${e.message}`); });
98
+ if (res.status === 401 && token && token === envToken()) {
99
+ envRefused = true;
100
+ const stored = storedToken();
101
+ if (stored && stored !== token) return api(path, { method, body, token: stored, raw });
102
+ }
79
103
  if (raw) return res;
80
104
  const json = await res.json().catch(() => ({}));
81
105
  return { status: res.status, ok: res.ok, json };
@@ -98,7 +122,7 @@ async function login() {
98
122
  // Wall hands over is opened on this computer, and a file: or another site's page opens whatever it names.
99
123
  const page = signInPage(link, wall);
100
124
  if (!page) fail(`The Wall at ${wall} gave ${JSON.stringify(String(link).slice(0, 200))} as its sign-in page, which is not its own address over https.\n It was not opened, and nothing was signed in.`);
101
- out(`\n Sign in to the ${side} Wall to continue.\n\n Open ${page}\n Code ${user_code} (approve it there — it expires in ${Math.round(expires_in / 60)} minutes)\n`);
125
+ out(`\n Sign in to the ${side} Wall to continue.\n\n Open ${page}\n Code ${oneLine(user_code)} (approve it there — it expires in ${Math.round(expires_in / 60)} minutes)\n`);
102
126
  openBrowser(page);
103
127
  let every = Math.max(1, Number(interval) || 5) * 1000;
104
128
  const until = Date.now() + Number(expires_in) * 1000;
@@ -114,44 +138,46 @@ async function login() {
114
138
  const all = readCredentials();
115
139
  all[wall] = { token, email, at: new Date().toISOString() };
116
140
  writeCredentials(all);
117
- out(`\n\n Signed in${email ? ` as ${email}` : ''} · ${side}.\n`);
141
+ out(`\n\n Signed in${email ? ` as ${oneLine(email)}` : ''} · ${side}.\n`);
118
142
  return token;
119
143
  }
120
144
  const why = poll.json.error;
121
145
  if (why === 'slow_down') every += 5000;
122
146
  else if (why === 'expired_token') fail('The code expired before it was approved. Run `toolaby login` again.');
123
147
  else if (why === 'access_denied') fail('The sign-in was denied in the browser. Nothing was signed in.');
124
- else if (why && why !== 'authorization_pending') fail(`The Wall answered "${why}"${poll.json.error_description ? `: ${poll.json.error_description}` : ''}.`);
148
+ else if (why && why !== 'authorization_pending') fail(`The Wall answered "${oneLine(why)}"${poll.json.error_description ? `: ${oneLine(poll.json.error_description)}` : ''}.`);
125
149
  }
126
150
  fail('The code expired before it was approved. Run `toolaby login` again.');
127
151
  }
128
152
 
129
153
  /** A token to act with: the stored one, else a sign-in right here — `wire` in a fresh terminal is one command, not two. */
130
154
  async function tokenOrLogin() {
131
- return storedToken() ?? (await login());
155
+ const token = storedToken();
156
+ if (!token && envElsewhere()) out(envElsewhere());
157
+ return token ?? (await login());
132
158
  }
133
159
 
134
160
  async function whoami() {
135
161
  const token = storedToken();
136
- if (!token) fail(`Not signed in to ${side} (${wall}). Run \`toolaby login${live ? ' --live' : ''}\`.`);
162
+ if (!token) fail(`Not signed in to ${side} (${wall}). Run \`toolaby login${live ? ' --live' : ''}\`.${envElsewhere()}`);
137
163
  const me = await api('/api/cli/me', { token });
138
164
  if (me.status === 401) fail(`The session for ${wall} is no longer valid. Run \`toolaby login\`.`);
139
165
  if (!me.ok) fail(`The Wall answered HTTP ${me.status}.`);
140
- out(`\n ${me.json.email} · ${side} · ${wall}\n`);
141
- for (const w of me.json.workspaces) out(` ${w.name} (${w.slug}, ${w.role}) ${w.site}`);
166
+ out(`\n ${oneLine(me.json.email)} · ${side} · ${wall}\n`);
167
+ for (const w of me.json.workspaces) out(` ${oneLine(w.name)} (${oneLine(w.slug)}, ${oneLine(w.role)}) ${oneLine(w.site)}`);
142
168
  out();
143
169
  }
144
170
 
145
171
  async function logout() {
146
172
  const all = readCredentials();
147
173
  const entry = all[wall];
148
- if (!entry && !process.env.TOOLABY_TOKEN) { out(`\n Not signed in to ${side} (${wall}).\n`); return; }
174
+ if (!entry && !envToken()) { out(`\n Not signed in to ${side} (${wall}).\n`); return; }
149
175
  // Revoked on the server first; forgotten here whatever the server said — but the difference is reported.
150
- const res = await api('/api/dev-auth/sign-out', { method: 'POST', body: {}, token: entry?.token ?? process.env.TOOLABY_TOKEN }).catch(() => ({ ok: false, status: 0 }));
176
+ const res = await api('/api/dev-auth/sign-out', { method: 'POST', body: {}, token: entry?.token ?? envToken() }).catch(() => ({ ok: false, status: 0 }));
151
177
  delete all[wall];
152
178
  writeCredentials(all);
153
179
  out(res.ok ? `\n Signed out of ${side} (${wall}): the session was revoked and forgotten.\n` : `\n The session was forgotten here, but the Wall could not be reached to revoke it (HTTP ${res.status}); it expires on its own, or sign it out from the dashboard.\n`);
154
- if (process.env.TOOLABY_TOKEN) out(' TOOLABY_TOKEN is set in this shell and still authenticates.\n');
180
+ if (envToken()) out(' TOOLABY_TOKEN is set in this shell and still authenticates.\n');
155
181
  }
156
182
 
157
183
  async function tools() {
@@ -161,7 +187,7 @@ async function tools() {
161
187
  if (!res.ok) fail(`The Wall answered HTTP ${res.status}.`);
162
188
  if (!res.json.tools.length) { out(`\n No tools on ${side} yet. Make one in the dashboard, then \`toolaby wire <tool-id>${live ? ' --live' : ''}\` in your extension's folder.\n`); return; }
163
189
  out(`\n ${side}\n`);
164
- for (const t of res.json.tools) out(` ${t.slug.padEnd(40)} ${t.name}${t.bundle ? ' (bundle)' : ''} ${t.site}`);
190
+ for (const t of res.json.tools) out(` ${oneLine(t.slug).padEnd(40)} ${oneLine(t.name)}${t.bundle ? ' (bundle)' : ''} ${oneLine(t.site)}`);
165
191
  out();
166
192
  }
167
193
 
@@ -177,9 +203,11 @@ function listTree(dir, depth, prefix = '', acc = new Set()) {
177
203
  }
178
204
  return acc;
179
205
  }
180
- const readJson = (path) => { try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; } };
206
+ const readJson = (path) => { try { return JSON.parse(readText(path)); } catch { return null; } };
207
+ /** A project file's text, or `none` where it is no file to read (lib/safe.js readText): a link to a device reads as nothing. */
208
+ const readOr = (path, none = null) => { try { return readText(path); } catch { return none; } };
181
209
  /** Whether a background already starts the platform, outside its comments: then it needs no lines added. */
182
- const startsPlatform = (path) => { try { return /\bstartBackground\s*\(/.test(readFileSync(path, 'utf8').replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '')); } catch { return false; } };
210
+ const startsPlatform = (path) => { try { return /\bstartBackground\s*\(/.test(readText(path).replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '')); } catch { return false; } };
183
211
  const isId = (s) => typeof s === 'string' && /^[a-z0-9][a-z0-9-]{1,118}$/.test(s);
184
212
  /** Whether anything is at the path, a link to nowhere included (existsSync follows a link, and says no for a dangling one). */
185
213
  const there = (path) => { try { lstatSync(path); return true; } catch { return false; } };
@@ -193,7 +221,7 @@ function placesIn(root, paths, named = {}) {
193
221
  const at = {}; const refused = [];
194
222
  for (const rel of new Set(paths)) {
195
223
  const r = inside(root, rel);
196
- if (r.why) refused.push(`${JSON.stringify(rel)}${named[rel] ? ` (${named[rel]})` : ''}: ${r.why}`);
224
+ if (r.why) refused.push(`${JSON.stringify(rel)}${named[rel] ? ` (${named[rel]})` : ''}: ${oneLine(r.why)}`);
197
225
  else at[rel] = r.path;
198
226
  }
199
227
  if (refused.length) fail(`Refused:\n\n${refused.map((r) => ` ${r}`).join('\n')}\n\n This command writes only inside ${root}, and never through a symbolic link. Nothing was written.`);
@@ -204,21 +232,27 @@ function placesIn(root, paths, named = {}) {
204
232
  async function filesFor(slug, scaffold, manifestKey = null, surfaces = null) {
205
233
  const token = await tokenOrLogin();
206
234
  const q = new URLSearchParams(); if (scaffold) q.set('scaffold', '1'); if (manifestKey) q.set('manifestKey', manifestKey); if (surfaces) q.set('surfaces', surfaces);
235
+ // The folder's manifest names another extension than the tool's: switched only when asked (--adopt-key).
236
+ if (manifestKey && flag('--adopt-key')) q.set('adoptKey', '1');
207
237
  const res = await api(`/api/cli/wiring/${slug}${q.size ? `?${q}` : ''}`, { token });
208
238
  if (res.status === 401) { out(' The stored session is no longer valid; signing in again.'); await login(); return filesFor(slug, scaffold, manifestKey, surfaces); }
239
+ if (res.status === 409 && res.json?.error === 'identity_conflict') {
240
+ const offered = oneLine(res.json.offered); const current = oneLine(res.json.current);
241
+ fail(`This folder's manifest names the extension ${offered}; ${slug} is bound to ${current}. Nothing was written.\n\n Run it again with --adopt-key to make ${offered} the tool's extension: its key then works from that one, and ${current}'s copies are named no more.\n Or take the key out of this folder's manifest, and the tool's own goes in.`);
242
+ }
209
243
  if (res.status === 404) {
210
244
  // Say who the command is: the tool may well exist — in a workspace of another account of theirs.
211
245
  const me = await api('/api/cli/me', { token }).catch(() => null);
212
- const who = me?.ok ? `\n\n You are signed in as ${me.json.email}${me.json.workspaces.length ? ` (workspaces: ${me.json.workspaces.map((w) => w.slug).join(', ')})` : ' (no workspace yet)'}.\n Another account owns it? \`toolaby logout\`, sign in to the dashboard as that account, then run this again.` : '';
213
- fail(`${res.json.message ?? `No tool "${slug}" in your workspaces.`}${who}`);
246
+ const who = me?.ok ? `\n\n You are signed in as ${oneLine(me.json.email)}${me.json.workspaces.length ? ` (workspaces: ${me.json.workspaces.map((w) => oneLine(w.slug)).join(', ')})` : ' (no workspace yet)'}.\n Another account owns it? \`toolaby logout\`, sign in to the dashboard as that account, then run this again.` : '';
247
+ fail(`${oneLine(res.json.message ?? `No tool "${slug}" in your workspaces.`)}${who}`);
214
248
  }
215
- if (!res.ok) fail(res.json.message ?? `The Wall answered HTTP ${res.status}.`);
249
+ if (!res.ok) fail(oneLine(res.json.message ?? `The Wall answered HTTP ${res.status}.`));
216
250
  return res.json;
217
251
  }
218
252
 
219
253
  async function wire() {
220
254
  const slug = positional[0];
221
- if (!isId(slug)) fail(command === 'upgrade' ? 'usage: toolaby upgrade <tool-id> [--into <folder>] — `toolaby tools` lists your ids' : 'usage: toolaby wire <tool-id> [--into <folder>] [--force] — `toolaby tools` lists your ids');
255
+ if (!isId(slug)) fail(command === 'upgrade' ? 'usage: toolaby upgrade <tool-id> [--into <folder>] — `toolaby tools` lists your ids' : 'usage: toolaby wire <tool-id> [--into <folder>] [--force] [--adopt-key] — `toolaby tools` lists your ids');
222
256
  const dir = resolve(opt('--into') ?? '.');
223
257
  if (!existsSync(dir)) fail(`${dir} does not exist`);
224
258
  const tree = listTree(dir, 3);
@@ -230,13 +264,13 @@ async function wire() {
230
264
  const site = plan.site;
231
265
  const manifestKey = plan.identity?.manifestKey ?? null;
232
266
  const configSource = ['manifest.config.ts', 'manifest.config.js', 'manifest.ts', 'src/manifest.ts'].find(has);
233
- const project = detectProject({ has, packageJson: has('package.json') ? readJson(join(dir, 'package.json')) : null, manifest, manifestSource: configSource ? readFileSync(join(dir, configSource), 'utf8') : null, site, tree, manifestKey });
267
+ const project = detectProject({ has, packageJson: has('package.json') ? readJson(join(dir, 'package.json')) : null, manifest, manifestSource: configSource ? readOr(join(dir, configSource)) : null, site, tree, manifestKey });
234
268
  // Nothing recognised: nothing is written and nothing guessed. A manifest below the top is where to point --into; otherwise the Set up page's Do it myself has the files and the three things to paste.
235
- if (project.kind === 'unknown') fail(`${dir} has no manifest.json at the top and is not a WXT, CRXJS or Plasmo project${project.foundManifest ? ` — there is one at ${project.foundManifest}: run this with --into ${dirname(project.foundManifest) || '.'}` : ''}.\n Nothing was written. For a layout of your own, the tool's Set up page → Do it myself has the files and the three things to paste.`);
269
+ if (project.kind === 'unknown') fail(`${dir} has no manifest.json at the top and is not a WXT, CRXJS or Plasmo project${project.foundManifest ? ` — there is one at ${oneLine(project.foundManifest)}: run this with --into ${oneLine(dirname(project.foundManifest)) || '.'}` : ''}.\n Nothing was written. For a layout of your own, the tool's Set up page → Do it myself has the files and the three things to paste.`);
236
270
 
237
271
  // The extension's own popup and side panel: the manifest's, or — wired before — what the existing configuration remembers.
238
272
  const configPath = join(dir, `${project.codeDir}toolaby.config.js`);
239
- const oldConfig = existsSync(configPath) ? readFileSync(configPath, 'utf8') : '';
273
+ const oldConfig = existsSync(configPath) ? readOr(configPath, '') : '';
240
274
  const remembered = oldConfig.match(/appPopup:\s*'([^']*)'/)?.[1] || null;
241
275
  const rememberedSidePanel = oldConfig.match(/appSidePanel:\s*'([^']*)'/)?.[1] || null;
242
276
  // An extension whose own pages draw the panel — what `create` makes, or "your popup first" — keeps them in front.
@@ -266,7 +300,7 @@ async function wire() {
266
300
  const wrote = targets.filter((path) => typeof plan.files[path.split('/').pop()] === 'string');
267
301
  for (const path of wrote) write(path, fillPages(plan.files[path.split('/').pop()], { appPopup, appSidePanel }));
268
302
  for (const f of entries) { write(f, plan.files[f]); wrote.push(f); }
269
- const ownAgents = has('AGENTS.md') && !readFileSync(join(dir, 'AGENTS.md'), 'utf8').includes('TOOLABY.md');
303
+ const ownAgents = has('AGENTS.md') && !readOr(join(dir, 'AGENTS.md'), '').includes('TOOLABY.md');
270
304
  for (const p of stale) unlinkSync(at[p]);
271
305
  const did = [];
272
306
  let ownWorker = null;
@@ -283,12 +317,13 @@ async function wire() {
283
317
  ownWorker = { file: project.worker, classic: false };
284
318
  }
285
319
 
286
- out(`\n ${plan.name} → ${dir}${project.kind === 'plain' ? '' : ` (${project.label})`} · ${side}${side === 'Test' ? ' (the tk_test_ key; `--live` for the store build)' : ''}\n`);
287
- out(` Written: ${wrote.join(', ')}${did.length ? `,\n ${did.join(',\n ')}` : ''}.\n`);
320
+ out(`\n ${oneLine(plan.name)} → ${dir}${project.kind === 'plain' ? '' : ` (${project.label})`} · ${side}${side === 'Test' ? ' (the tk_test_ key; `--live` for the store build)' : ''}\n`);
321
+ // Each thing done is a line, and names what the manifest and the Wall named: the popup, the background, the address.
322
+ out(` Written: ${wrote.join(', ')}${did.length ? `,\n ${did.map(oneLine).join(',\n ')}` : ''}.\n`);
288
323
  if (ownAgents) out(' Your AGENTS.md is your own: add a line so coding agents find the Wall\'s guide — "Before changing anything paid, read TOOLABY.md."\n');
289
324
  if (stale.length) out(` Removed: ${stale.join(', ')} — earlier files, now inside toolaby.js.\n`);
290
325
  for (const sn of project.snippets) out(` Add to ${sn.file} — yours to paste, the manifest being generated:\n\n${sn.code.split('\n').map((l) => ` ${l}`).join('\n')}\n`);
291
- if (ownWorker) out(` Your background, ${ownWorker.file}: add${ownWorker.classic ? ' — after giving "background" a "type": "module" in manifest.json (importScripts() is not available in a module worker)' : ''}:\n\n${project.workerLines.trimEnd().split('\n').map((l) => ` ${l}`).join('\n')}\n`);
326
+ if (ownWorker) out(` Your background, ${oneLine(ownWorker.file)}: add${ownWorker.classic ? ' — after giving "background" a "type": "module" in manifest.json (importScripts() is not available in a module worker)' : ''}:\n\n${project.workerLines.trimEnd().split('\n').map((l) => ` ${l}`).join('\n')}\n`);
292
327
  if (project.built) out(` ${BUILD_COPY_NOTE}\n`);
293
328
  out(` Next: ${project.kind === 'plain' && !project.built ? '' : 'build or start the dev server, then '}chrome://extensions → reload it. The tool's Set up page says "checked in" the moment it starts.`);
294
329
  if (project.note) out(` ${project.note}\n`);
@@ -323,21 +358,27 @@ async function create() {
323
358
  const entries = AGENT_ENTRY_FILES.filter((f) => typeof plan.files[f] === 'string');
324
359
  const icons = [16, 48, 128].map((s) => `icons/icon${s}.png`);
325
360
  const at = placesIn(dir, [...wanted, 'manifest.json', ...icons, ...agentFiles.map((f) => f.path), ...entries]);
361
+ // The icons first, each within a megabyte and half a minute, and nothing written until they are in: a Wall at another
362
+ // address (--wall, TOOLABY_WALL) could send one without end, and the new folder took it until the disk was full
363
+ // (25 Sep 2026).
364
+ const iconBytes = {};
365
+ for (const icon of icons) {
366
+ const got = await fetchBounded(`${wall}/boilerplate/${icon}`).catch((e) => ({ why: e.name === 'TimeoutError' ? 'it took longer than 30 seconds' : oneLine(e.message) }));
367
+ if (got.why || !got.body) fail(`The Wall at ${wall} did not send ${icon}: ${got.why ?? 'it sent more than a megabyte, which no icon is'}. Nothing was written.`);
368
+ iconBytes[icon] = got.body;
369
+ }
326
370
  const write = (rel, content) => { mkdirSync(dirname(at[rel]), { recursive: true }); writeFileSync(at[rel], content); };
327
371
  // Both surfaces, and the panel drawn inside them: no page of the Wall's stands in front, so both names stay empty.
328
372
  for (const f of wanted) write(f, fillPages(plan.files[f]));
329
373
  // The manifest names the side panel only now that the page is beside it — an extension whose side_panel points at a
330
374
  // missing file does not load at all, so a Wall that stops serving the page must not leave the key behind either.
331
375
  // The extension's identity too: every copy gets the id the tool key is bound to, wherever its folder is.
332
- write('manifest.json', JSON.stringify(scaffoldManifest(JSON.parse(readFileSync(at['manifest.json'], 'utf8')), { sidePanel: hasSidePanel(surfaces), popup: hasPopup(surfaces), key: plan.identity?.manifestKey ?? null }), null, 2) + '\n');
333
- for (const icon of icons) {
334
- const res = await fetch(`${wall}/boilerplate/${icon}`);
335
- write(icon, Buffer.from(await res.arrayBuffer()));
336
- }
376
+ write('manifest.json', JSON.stringify(scaffoldManifest(JSON.parse(readText(at['manifest.json'])), { sidePanel: hasSidePanel(surfaces), popup: hasPopup(surfaces), key: plan.identity?.manifestKey ?? null }), null, 2) + '\n');
377
+ for (const icon of icons) write(icon, iconBytes[icon]);
337
378
  for (const f of agentFiles) write(f.path, plan.files[f.name]);
338
379
  for (const f of entries) write(f, plan.files[f]);
339
380
  const clicking = { both: 'Click the icon: the popup shows what the Free plan holds. Open side panel, in it, is the same page at the panel\'s width', popup: 'Click the icon: the popup shows what the Free plan holds', 'side-panel': 'Click the icon: the side panel opens — it has no popup, so the click is the panel\'s', none: 'No popup and no side panel: nothing opens on a click. Your code says when to sell — toolaby.openPaymentPage()' }[surfaces];
340
- out(`\n ${plan.name} → ${dir}${surfaces === 'both' ? '' : ` (--surfaces ${surfaces})`}\n\n 1. chrome://extensions → Developer mode → Load unpacked → ${dir}\n 2. ${clicking}; Buy opens ${plan.buyer ?? `${plan.site}/tools/${slug}`}\n\n Edit background.js: your work goes behind toolaby.gate().\n Surfaces, and how to add or drop one later: ${wall}/docs/surfaces\n`);
381
+ out(`\n ${oneLine(plan.name)} → ${dir}${surfaces === 'both' ? '' : ` (--surfaces ${surfaces})`}\n\n 1. chrome://extensions → Developer mode → Load unpacked → ${dir}\n 2. ${clicking}; Buy opens ${oneLine(plan.buyer ?? `${plan.site}/tools/${slug}`)}\n\n Edit background.js: your work goes behind toolaby.gate().\n Surfaces, and how to add or drop one later: ${wall}/docs/surfaces\n`);
341
382
  if (typeof plan.files['TOOLABY.md'] === 'string') out(` With a coding agent: AGENTS.md and TOOLABY.md tell it how this extension sells. For Claude Code, the Wall itself:\n claude mcp add toolaby -- npx -y toolaby@latest mcp${live ? ' --live' : ''}\n`);
342
383
  }
343
384
 
@@ -350,7 +391,18 @@ async function create() {
350
391
  // (or one it prints) and POSTs it to the URL — a server on localhost, no
351
392
  // tunnel, no deploy — so a handler can be written and run before anything
352
393
  // is registered.
353
- const DEV_SECRET = 'whsec_dG9vbGFieS1kZXYtd2ViaG9vay1zZWNyZXQtMDAwMQ==';
394
+ // This machine's development secret: made once, kept beside the credentials (mode 600), never the same as anyone
395
+ // else's. It was one constant, shipped in the package and printed in the docs, and a server deployed with it took
396
+ // forged events from anyone (25 Sep 2026).
397
+ const DEV_SECRET_FILE = join(CONFIG_DIR, 'dev-webhook-secret');
398
+ function devSecret() {
399
+ try { const kept = readFileSync(DEV_SECRET_FILE, 'utf8').trim(); if (/^whsec_[A-Za-z0-9+/=]{20,}$/.test(kept)) return kept; } catch { /* made below */ }
400
+ const made = `whsec_${randomBytes(24).toString('base64')}`;
401
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
402
+ writeFileSync(DEV_SECRET_FILE, made + '\n', { mode: 0o600 });
403
+ try { chmodSync(DEV_SECRET_FILE, 0o600); } catch { /* not every filesystem has modes */ }
404
+ return made;
405
+ }
354
406
  async function catalogue() {
355
407
  const res = await api('/api/cli/webhooks/events', { token: await tokenOrLogin() });
356
408
  if (res.status === 401) fail(`The session for ${side} is no longer valid. Run \`toolaby login${live ? ' --live' : ''}\`.`);
@@ -362,8 +414,13 @@ async function webhooks() {
362
414
  if (sub === 'events') {
363
415
  const events = await catalogue();
364
416
  out(`\n ${side}\n`);
365
- for (const e of events) out(` ${e.type.padEnd(26)} ${e.description}`);
366
- out(`\n toolaby webhooks trigger <event> → your registered endpoints\n toolaby webhooks trigger <event> --to <url> → a local server, signed with a secret you name\n`);
417
+ for (const e of events) out(` ${oneLine(e.type).padEnd(26)} ${oneLine(e.description)}`);
418
+ out(`\n toolaby webhooks trigger <event> → your registered endpoints\n toolaby webhooks trigger <event> --to <url> → a local server, signed with this machine's development secret\n toolaby webhooks secret → that secret, for the local server's WALL_WEBHOOK_SECRET\n`);
419
+ return;
420
+ }
421
+ if (sub === 'secret') {
422
+ // For the server on this machine: `WALL_WEBHOOK_SECRET=$(npx toolaby webhooks secret) node server.mjs`.
423
+ process.stdout.write(devSecret() + '\n');
367
424
  return;
368
425
  }
369
426
  if (sub === 'trigger') {
@@ -372,14 +429,14 @@ async function webhooks() {
372
429
  const to = opt('--to');
373
430
  if (!to) {
374
431
  const res = await api('/api/cli/webhooks/trigger', { method: 'POST', body: { type, workspace: opt('--workspace') ?? undefined }, token: await tokenOrLogin() });
375
- if (!res.ok) fail(res.json.message ?? `The Wall answered HTTP ${res.status}.`);
376
- out(`\n Sent ${res.json.sent} to every endpoint of ${res.json.workspace} · ${side}. Its id is ${res.json.id}; the delivery log is under Configure → Webhooks.\n`);
432
+ if (!res.ok) fail(oneLine(res.json.message ?? `The Wall answered HTTP ${res.status}.`));
433
+ out(`\n Sent ${oneLine(res.json.sent)} to every endpoint of ${oneLine(res.json.workspace)} · ${side}. Its id is ${oneLine(res.json.id)}; the delivery log is under Configure → Webhooks.\n`);
377
434
  return;
378
435
  }
379
436
  const events = await catalogue();
380
437
  const event = events.find((e) => e.type === type);
381
438
  if (!event) fail(`No event "${type}". \`toolaby webhooks events\` lists them.`);
382
- const secret = opt('--secret') ?? DEV_SECRET;
439
+ const secret = opt('--secret') ?? devSecret();
383
440
  if (!/^whsec_[A-Za-z0-9+/=]+$/.test(secret)) fail('--secret must be a Standard Webhooks secret: whsec_ followed by base64.');
384
441
  const id = `msg_${randomBytes(12).toString('base64url')}`;
385
442
  const timestamp = Math.floor(Date.now() / 1000);
@@ -390,18 +447,18 @@ async function webhooks() {
390
447
  res = await fetch(to, { method: 'POST', headers: { 'Content-Type': 'application/json', 'webhook-id': id, 'webhook-timestamp': String(timestamp), 'webhook-signature': signature, 'User-Agent': `toolaby-cli/${VERSION}` }, body });
391
448
  } catch (e) { fail(`Could not reach ${to}: ${e.message}`); }
392
449
  const text = (await res.text()).slice(0, 200);
393
- out(`\n POST ${to} → ${res.status}${text ? ` ${text.replace(/\s+/g, ' ')}` : ''}`);
394
- out(` ${type}, signed with ${opt('--secret') ? 'your secret' : `${DEV_SECRET} — set WALL_WEBHOOK_SECRET to it to verify`}.\n`);
450
+ out(`\n POST ${to} → ${res.status}${text ? ` ${oneLine(text)}` : ''}`);
451
+ out(` ${type}, signed with ${opt('--secret') ? 'your secret' : "this machine's development secret — `npx toolaby webhooks secret` prints it for WALL_WEBHOOK_SECRET"}.\n`);
395
452
  if (res.status >= 300) out(' A real delivery would be retried until your server answers 2xx.\n');
396
453
  return;
397
454
  }
398
455
  if (sub === 'endpoints') {
399
456
  const ws = opt('--workspace');
400
457
  const res = await api(`/api/cli/webhooks/endpoints${ws ? `?workspace=${encodeURIComponent(ws)}` : ''}`, { token: await tokenOrLogin() });
401
- if (!res.ok) fail(res.json.message ?? `The Wall answered HTTP ${res.status}.`);
402
- out(`\n ${res.json.workspace} · ${side}\n`);
458
+ if (!res.ok) fail(oneLine(res.json.message ?? `The Wall answered HTTP ${res.status}.`));
459
+ out(`\n ${oneLine(res.json.workspace)} · ${side}\n`);
403
460
  if (res.json.endpoints.length === 0) out(' None yet. `toolaby webhooks add <url>` registers one.');
404
- for (const e of res.json.endpoints) out(` ${e.id} ${e.disabled ? 'paused ' : 'on '} ${e.url}${e.description ? ` — ${e.description}` : ''}${e.events.length ? ` (${e.events.join(', ')})` : ''}`);
461
+ for (const e of res.json.endpoints) out(` ${oneLine(e.id)} ${e.disabled ? 'paused ' : 'on '} ${oneLine(e.url)}${e.description ? ` — ${oneLine(e.description)}` : ''}${e.events.length ? ` (${oneLine(e.events.join(', '))})` : ''}`);
405
462
  out();
406
463
  return;
407
464
  }
@@ -410,16 +467,16 @@ async function webhooks() {
410
467
  if (!url) fail('usage: toolaby webhooks add <url> [--description <text>] [--events a.b,c.d] [--workspace <slug>]');
411
468
  const events = (opt('--events') ?? '').split(',').map((e) => e.trim()).filter(Boolean);
412
469
  const res = await api('/api/cli/webhooks/endpoints', { method: 'POST', body: { url, description: opt('--description') ?? '', events, workspace: opt('--workspace') ?? undefined }, token: await tokenOrLogin() });
413
- if (!res.ok) fail(res.json.message ?? `The Wall answered HTTP ${res.status}.`);
414
- out(`\n Added ${res.json.id} → ${res.json.url} · ${res.json.workspace} · ${side}\n\n Signing secret, shown once — keep it where your server keeps secrets:\n\n ${res.json.secret}\n`);
470
+ if (!res.ok) fail(oneLine(res.json.message ?? `The Wall answered HTTP ${res.status}.`));
471
+ out(`\n Added ${oneLine(res.json.id)} → ${oneLine(res.json.url)} · ${oneLine(res.json.workspace)} · ${side}\n\n Signing secret, shown once — keep it where your server keeps secrets:\n\n ${oneLine(res.json.secret)}\n`);
415
472
  return;
416
473
  }
417
474
  if (sub === 'remove') {
418
475
  const id = positional[1];
419
476
  if (!id) fail('usage: toolaby webhooks remove <ep_…> [--workspace <slug>] — `toolaby webhooks endpoints` lists them');
420
477
  const res = await api('/api/cli/webhooks/endpoints', { method: 'DELETE', body: { id, workspace: opt('--workspace') ?? undefined }, token: await tokenOrLogin() });
421
- if (!res.ok) fail(res.json.message ?? `The Wall answered HTTP ${res.status}.`);
422
- out(`\n Removed ${res.json.removed} · ${res.json.workspace} · ${side}. Deliveries to it stop at once.\n`);
478
+ if (!res.ok) fail(oneLine(res.json.message ?? `The Wall answered HTTP ${res.status}.`));
479
+ out(`\n Removed ${oneLine(res.json.removed)} · ${oneLine(res.json.workspace)} · ${side}. Deliveries to it stop at once.\n`);
423
480
  return;
424
481
  }
425
482
  fail('usage: toolaby webhooks events | trigger <event> [--to <url>] | endpoints | add <url> | remove <id>');
@@ -469,28 +526,30 @@ function zipOf(entries) {
469
526
 
470
527
  /**
471
528
  * What goes in the zip: every file in the folder but dotfiles, node_modules and zips — and, left out with the reason,
472
- * a file that looks private (lib/safe.js), which --allow-private packs anyway, and a link that leads out of the folder
473
- * or to nothing, which is never packed: a link in a cloned repository can put ~/.ssh/id_rsa in a store zip as logo.png.
474
- * A zip is public once the store serves it. A folder reached twice through links is walked once.
529
+ * a file that looks private by its name or its contents (lib/safe.js), which --allow-private packs anyway, and never a
530
+ * link: one out of the folder can put ~/.ssh/id_rsa in a store zip as logo.png, and one inside it the folder's own
531
+ * .env or .git, under an innocent name (25 Sep 2026). Nor a name no zip should hold — a backslash, which unzips as a
532
+ * folder, or a control character — nor anything but a file. A zip is public once the store serves it.
475
533
  */
476
534
  function filesIn(root) {
477
- const top = realpathSync(root);
478
- const found = []; const left = []; const walked = new Set([top]);
535
+ const found = []; const left = []; const privately = [];
479
536
  const walk = (dir) => {
480
537
  for (const name of readdirSync(dir).sort()) {
481
538
  if (name.startsWith('.') || name === 'node_modules' || name.endsWith('.zip')) continue;
482
539
  const p = join(dir, name);
483
- const rel = relative(root, p).split('\\').join('/');
484
- let real = null; try { real = realpathSync(p); } catch { /* a link to nothing */ }
485
- if (!real || (real !== top && !real.startsWith(top + sep))) { left.push([rel, real ? 'a link out of the folder' : 'a link to nothing']); continue; }
486
- if (statSync(p).isDirectory()) { if (!walked.has(real)) { walked.add(real); walk(p); } continue; }
487
- const why = privateKind(name);
540
+ const rel = relative(root, p).split(sep).join('/');
541
+ const st = lstatSync(p);
542
+ if (st.isSymbolicLink()) { left.push([rel, 'a link']); continue; }
543
+ if (/[\\\u0000-\u001f\u007f]/.test(name)) { left.push([rel, 'a name no zip should hold']); continue; }
544
+ if (st.isDirectory()) { walk(p); continue; }
545
+ if (!st.isFile()) { left.push([rel, 'not a file']); continue; }
546
+ const why = privateKind(name) ?? privateContent(readFileSync(p));
488
547
  if (why && !flag('--allow-private')) left.push([rel, why]);
489
- else found.push(p);
548
+ else { found.push(p); if (why) privately.push([rel, why]); }
490
549
  }
491
550
  };
492
551
  walk(root);
493
- return { found, left };
552
+ return { found, left, privately };
494
553
  }
495
554
 
496
555
  function pack() {
@@ -498,12 +557,13 @@ function pack() {
498
557
  const folder = given ? resolve(given) : BUILD_DIRS.map((d) => resolve(d)).find((d) => existsSync(join(d, 'manifest.json')));
499
558
  if (!folder || !existsSync(join(folder, 'manifest.json'))) fail(given ? `No manifest.json in ${given}.` : `No manifest.json here or in ${BUILD_DIRS.slice(1).join(', ')}. Build first, or name the folder: toolaby pack <folder>.`);
500
559
  let manifest;
501
- try { manifest = JSON.parse(readFileSync(join(folder, 'manifest.json'), 'utf8')); } catch (e) { fail(`manifest.json does not parse: ${e.message}`); }
560
+ // The parser's message quotes the file it could not read, line breaks and all.
561
+ try { manifest = JSON.parse(readText(join(folder, 'manifest.json'))); } catch (e) { fail(`manifest.json does not parse: ${oneLine(e.message)}`); }
502
562
  if (!manifest.version) fail('manifest.json has no "version".');
503
563
  // One to four numbers, as Chrome and the store take it — and a file name here: the zip is named with it, and a
504
564
  // version with "../" in it put the zip outside the folder.
505
565
  if (typeof manifest.version !== 'string' || !/^\d{1,5}(\.\d{1,5}){0,3}$/.test(manifest.version)) fail(`manifest.json's "version" is ${JSON.stringify(manifest.version)}: Chrome takes one to four numbers separated by dots, like 1.2.0.`);
506
- const { found: files, left } = filesIn(folder);
566
+ const { found: files, left, privately } = filesIn(folder);
507
567
  const problems = [];
508
568
 
509
569
  // Which side the build sells on: the tool keys inside it, wherever the bundler put them.
@@ -520,35 +580,38 @@ function pack() {
520
580
 
521
581
  // Addresses of this machine have no place in a store build.
522
582
  const local = [...(manifest.host_permissions ?? []), ...(manifest.externally_connectable?.matches ?? [])].filter((m) => typeof m === 'string' && LOCAL.test(m));
523
- if (local.length && !flag('--allow-local')) problems.push(`The manifest points at this machine: ${local.join(', ')}. A store build has no localhost in host_permissions or externally_connectable. (--allow-local packs it anyway.)`);
583
+ if (local.length && !flag('--allow-local')) problems.push(`The manifest points at this machine: ${local.map(oneLine).join(', ')}. A store build has no localhost in host_permissions or externally_connectable. (--allow-local packs it anyway.)`);
524
584
 
525
585
  // The Wall the key names must be reachable from the extension, or sign-in and the purchase handoff fail.
526
586
  for (const site of sites) {
527
587
  const hosts = manifest.host_permissions ?? []; const ec = manifest.externally_connectable?.matches ?? [];
528
- if (!hosts.includes(`${site}/*`) || !ec.includes(`${site}/*`)) problems.push(`The manifest does not name ${site}/* in both host_permissions and externally_connectable: sign-in and the purchase would not reach the extension. \`npx toolaby wire <tool-id> --live --force\` adds them.`);
588
+ if (!hosts.includes(`${site}/*`) || !ec.includes(`${site}/*`)) problems.push(`The manifest does not name ${oneLine(site)}/* in both host_permissions and externally_connectable: sign-in and the purchase would not reach the extension. \`npx toolaby wire <tool-id> --live --force\` adds them.`);
529
589
  }
530
590
  if (problems.length) fail(`Not packed:\n\n${problems.map((p) => ` · ${p}`).join('\n\n')}`);
531
591
 
532
592
  const hadKey = typeof manifest.key === 'string';
533
593
  const { key: _key, ...forStore } = manifest;
534
594
  const entries = files.map((f) => {
535
- const name = relative(folder, f).split('\\').join('/');
595
+ const name = relative(folder, f).split(sep).join('/');
536
596
  return [name, name === 'manifest.json' ? Buffer.from(JSON.stringify(forStore, null, 2) + '\n') : readFileSync(f)];
537
597
  });
538
598
  // Named after the extension, or after its folder when the name is a __MSG_…__ placeholder.
539
599
  const named = typeof manifest.name === 'string' && !manifest.name.startsWith('__MSG_') ? manifest.name : basename(folder);
540
600
  const safe = named.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'extension';
541
601
  const target = resolve(opt('--out') ?? `${safe}-${manifest.version}.zip`);
542
- writeFileSync(target, zipOf(entries));
602
+ // Written beside it under a name nobody could have made, then moved over it: a link a cloned project left under the
603
+ // zip's own name took the write wherever it pointed (25 Sep 2026). A move replaces the link itself.
604
+ const fresh = `${target}.${process.pid}.${randomBytes(6).toString('hex')}.part`;
605
+ writeFileSync(fresh, zipOf(entries), { flag: 'wx' });
606
+ renameSync(fresh, target);
543
607
  const kb = (statSync(target).size / 1024).toFixed(0);
544
608
  out(`\n ${relative(process.cwd(), target) || target} · ${entries.length} files, ${kb} KB · version ${manifest.version}${modes.has('live') ? ' · Live key' : ''}`);
545
609
  // What was left out, and why — or, asked for, what private file went in: a store zip is public.
546
- const links = left.filter(([, why]) => why.startsWith('a link'));
547
- const kept = left.filter(([, why]) => !why.startsWith('a link'));
548
- if (kept.length) out(` Left out, as private: ${kept.map(([f, why]) => `${f} (${why})`).join(', ')}. Anyone can download a store item and unzip it; --allow-private packs ${kept.length > 1 ? 'them' : 'it'} anyway.`);
549
- if (links.length) out(` Left out: ${links.map(([f, why]) => `${f} (${why})`).join(', ')}. The zip holds the folder's own files: copy in what belongs in it.`);
550
- const privately = flag('--allow-private') ? files.map((f) => [relative(folder, f).split('\\').join('/'), privateKind(basename(f))]).filter(([, why]) => why) : [];
551
- if (privately.length) out(` Packed as asked (--allow-private): ${privately.map(([f, why]) => `${f} (${why})`).join(', ')}. Anyone who downloads the item can read ${privately.length > 1 ? 'them' : 'it'}.`);
610
+ const links = left.filter(([, why]) => why === 'a link' || why === 'not a file' || why === 'a name no zip should hold');
611
+ const kept = left.filter((entry) => !links.includes(entry));
612
+ if (kept.length) out(` Left out, as private: ${kept.map(([f, why]) => `${oneLine(f)} (${why})`).join(', ')}. Anyone can download a store item and unzip it; --allow-private packs ${kept.length > 1 ? 'them' : 'it'} anyway.`);
613
+ if (links.length) out(` Left out: ${links.map(([f, why]) => `${oneLine(f)} (${why})`).join(', ')}. The zip holds the folder's own files: copy in what belongs in it.`);
614
+ if (privately.length) out(` Packed as asked (--allow-private): ${privately.map(([f, why]) => `${oneLine(f)} (${why})`).join(', ')}. Anyone who downloads the item can read ${privately.length > 1 ? 'them' : 'it'}.`);
552
615
  if (hadKey) out(' The manifest\'s "key" is left out: the store keeps the id it gives the item. Your unpacked copy keeps the key and its own id; the Wall admits both once the listing\'s address is on the tool.');
553
616
  out(' Upload it at https://chrome.google.com/webstore/devconsole — a new item, or Package → Upload new package.\n');
554
617
  }
@@ -578,7 +641,7 @@ function help() {
578
641
  toolaby tools your tools, with their ids
579
642
  toolaby pack [folder] the zip for the Chrome Web Store: the built extension, its manifest's "key" left out;
580
643
  refuses a Test key or localhost inside --out <file.zip>
581
- leaves out keys, .env files and source maps --allow-private packs them
644
+ leaves out keys, certificates, .env and credential files, source maps --allow-private packs them
582
645
  toolaby check [folder] whether the extension here is wired right: files, key, manifest, client, features;
583
646
  --browser loads it in Chromium (needs Playwright in the project)
584
647
  toolaby mcp the Wall for coding agents, an MCP server on stdio:
@@ -589,11 +652,12 @@ function help() {
589
652
  toolaby login · whoami · logout the session, per side; a command that needs one signs you in itself
590
653
 
591
654
  Every command acts on Test (test.toolaby.app) unless told --live (toolaby.app).
592
- --wall <url> or TOOLABY_WALL names any other Wall; TOOLABY_TOKEN a session, for CI.
655
+ --wall <url> or TOOLABY_WALL names any other Wall; TOOLABY_TOKEN a session, for CI —
656
+ sent to Live alone, or to the one Wall TOOLABY_TOKEN_WALL names (https://test.toolaby.app for Test).
593
657
  `);
594
658
  }
595
659
 
596
660
  const commands = { login: async () => { await login(); }, logout, whoami, tools, wire, upgrade: wire, create, webhooks, pack, check, mcp, help, '--help': help, '-h': help, '--version': () => out(VERSION), '-v': () => out(VERSION) };
597
661
  const run = commands[command];
598
662
  if (!run) { console.error(`\n Unknown command "${command}".`); help(); process.exit(1); }
599
- Promise.resolve().then(run).catch((e) => fail(e.message));
663
+ Promise.resolve().then(run).catch((e) => fail(oneLine(e.message)));
package/lib/check.js CHANGED
@@ -3,12 +3,15 @@
3
3
  // client's freshness, the feature keys the code gates on against the tool's, the paywall's page, whether a copy has
4
4
  // checked in and whether the key is current, and — with --browser, where Playwright is installed — the extension
5
5
  // loaded in Chromium, its background answering and its own pages opening without an error.
6
- import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
6
+ import { existsSync, readdirSync, statSync } from 'node:fs';
7
7
  import { join, relative, resolve } from 'node:path';
8
8
  import { createHash } from 'node:crypto';
9
9
  import { createRequire } from 'node:module';
10
+ import { oneLine, keySite, fetchBounded, readText } from './safe.js';
10
11
 
11
12
  const KEY = /tk_(test|live|dev)_[A-Za-z0-9_-]{20,}/;
13
+ /** A tool id as the Wall makes them (lib/mcp.js has the same): the only thing the check puts after a Wall's address. */
14
+ const TOOL_ID = /^[a-z0-9][a-z0-9-]{1,118}$/;
12
15
  const CODE = /\.(m?js|jsx|ts|tsx|html|vue|svelte)$/;
13
16
  const SKIP = new Set(['node_modules', '.git', 'dist', 'build', '.output', '.wxt', '.plasmo', '.next', 'coverage']);
14
17
  const sha = (s) => createHash('sha256').update(s).digest('hex');
@@ -65,8 +68,9 @@ export async function runCheck({ dir: given, out, api, token, detectProject, wir
65
68
  const manifest = has('manifest.json') ? readJson(join(dir, 'manifest.json')) : null;
66
69
  if (has('manifest.json') && !manifest) { bad('manifest.json is not valid JSON.'); return false; }
67
70
  const configSource = ['manifest.config.ts', 'manifest.config.js', 'manifest.ts', 'src/manifest.ts'].find(has);
68
- const project = detectProject({ has, packageJson: has('package.json') ? readJson(join(dir, 'package.json')) : null, manifest, manifestSource: configSource ? readFileSync(join(dir, configSource), 'utf8') : null, site: 'https://example.invalid', tree });
69
- if (project.kind === 'unknown') { bad(`Not an extension project: no manifest.json at the top, and not WXT, CRXJS or Plasmo${project.foundManifest ? ` (there is a manifest at ${project.foundManifest}: run this with --into ${project.foundManifest.replace(/\/?manifest\.json$/, '') || '.'})` : ''}.`); return false; }
71
+ const readOr = (p, none = null) => { try { return readText(p); } catch { return none; } };
72
+ const project = detectProject({ has, packageJson: has('package.json') ? readJson(join(dir, 'package.json')) : null, manifest, manifestSource: configSource ? readOr(join(dir, configSource)) : null, site: 'https://example.invalid', tree });
73
+ if (project.kind === 'unknown') { bad(`Not an extension project: no manifest.json at the top, and not WXT, CRXJS or Plasmo${project.foundManifest ? ` (there is a manifest at ${oneLine(project.foundManifest)}: run this with --into ${oneLine(project.foundManifest.replace(/\/?manifest\.json$/, '')) || '.'})` : ''}.`); return false; }
70
74
  ok(project.kind === 'plain' ? 'A plain extension: manifest.json at the top.' : `A ${project.label} project.`);
71
75
 
72
76
  // 2. The Wall's files.
@@ -75,40 +79,48 @@ export async function runCheck({ dir: given, out, api, token, detectProject, wir
75
79
  if (missing.length) { bad(`${missing.map((f) => `${project.codeDir}${f}`).join(' and ')} missing. Run \`npx toolaby wire <tool-id>\` here.`); return false; }
76
80
  ok(`The Wall's files are in ${project.codeDir || 'the top folder'}.`);
77
81
 
78
- // 3. The tool key, and the tool it names.
79
- const keyText = readFileSync(at('toolaby.config.js'), 'utf8').match(KEY)?.[0];
82
+ // 3. The tool key, and the tool it names — from a file: a link to a device or a pipe is read as nothing.
83
+ const configText = readOr(at('toolaby.config.js'), '');
84
+ const keyText = configText.match(KEY)?.[0];
80
85
  const key = keyText ? decodeKey(keyText) : null;
81
86
  if (!key) { bad('toolaby.config.js holds no tool key. Run `npx toolaby upgrade <tool-id>` here.'); return false; }
82
87
  const mode = keyText.split('_')[1];
88
+ // The key is the project's: the Wall it names is asked twice below, with no session, and its tool id goes into a path
89
+ // the developer's session asks of their own Wall. So only a Wall's address (lib/safe.js), and only a tool id. A cloned
90
+ // project's key sent the two requests wherever it named, and a tool id of ".." made the signed-in one a request for
91
+ // another route (25 Sep 2026).
92
+ if (!keySite(key.site) || !TOOL_ID.test(key.slug)) {
93
+ bad(`The tool key names ${JSON.stringify(key.slug)} at ${JSON.stringify(key.site)}, which is not a tool on a Wall: its address is https (http only on this machine) with nothing after the host, and its id lowercase letters, digits and dashes. Nothing was asked of it. \`npx toolaby upgrade <tool-id>\` writes the tool's own key.`);
94
+ return false;
95
+ }
83
96
  ok(`The tool key names ${key.slug}, on ${mode === 'live' ? 'Live' : mode === 'test' ? 'Test' : 'a development Wall'} (${key.site}).`);
84
- const pub = await fetch(`${key.site}/api/tools/${encodeURIComponent(key.slug)}`).then(async (r) => ({ status: r.status, json: await r.json().catch(() => null) })).catch((e) => ({ status: 0, json: null, error: e.message }));
97
+ const pub = await fetchBounded(`${key.site}/api/tools/${encodeURIComponent(key.slug)}`).then((r) => ({ status: r.status, json: jsonOf(r.body) })).catch(() => ({ status: 0, json: null }));
85
98
  const tool = pub.status === 200 ? pub.json : null;
86
99
  if (!tool) bad(pub.status === 0 ? `The Wall at ${key.site} could not be reached.` : pub.status === 404 ? `The Wall does not sell ${key.slug}: deleted, switched off, or on the other side. \`npx toolaby tools${mode === 'live' ? ' --live' : ''}\` lists yours.` : `The Wall answered HTTP ${pub.status} for the tool.`);
87
100
  else {
88
- ok(`The Wall knows it: ${tool.name}.`);
101
+ ok(`The Wall knows it: ${oneLine(tool.name)}.`);
89
102
  const jwk = tool.publicKeyJwk ?? {};
90
103
  if (key.x && jwk.x && (key.x !== jwk.x || key.y !== jwk.y)) warn('The workspace\'s signing key was rotated after this key was written. Installed copies fetch the new one; `npx toolaby upgrade <tool-id>` writes it in.');
91
104
  }
92
105
 
93
106
  // 4. The manifest, against the platform's own wiring rules: what wiring it again would add.
94
- const configText = readFileSync(at('toolaby.config.js'), 'utf8');
95
107
  if (project.manifestFile && manifest) {
96
108
  const again = wireManifest(manifest, { site: key.site, has, remembered: null, rememberedSidePanel: null, manifestKey: typeof manifest.key === 'string' ? manifest.key : null });
97
109
  const needed = (again.did ?? []).filter((d) => !/popup|side panel/i.test(d));
98
- if (needed.length) bad(`The manifest lacks what the Wall needs: ${needed.join('; ')}. \`npx toolaby upgrade ${key.slug}\` adds it.`);
110
+ if (needed.length) bad(`The manifest lacks what the Wall needs: ${needed.map(oneLine).join('; ')}. \`npx toolaby upgrade ${key.slug}\` adds it.`);
99
111
  else ok('The manifest has the permissions and host permissions the Wall needs.');
100
112
  // The identity: without the `key`, each copy's id follows its folder, and once the extension is named the tool key refuses every copy not chosen.
101
113
  if (typeof manifest.key !== 'string' && /manifestKey:\s*'[A-Za-z0-9+/]{100,}={0,2}'/.test(configText)) warn(`manifest.json has no "key": each copy's id then depends on its folder, and once your extension is named the tool key refuses any copy you did not choose on the Keys page. \`npx toolaby upgrade ${key.slug}\` adds it.`);
102
114
  } else warn(`The manifest is generated by ${project.label}: build, then check the built manifest has ${key.site}/* in host_permissions and externally_connectable.`);
103
115
 
104
116
  // 5. The client, as fresh as the Wall's.
105
- const client = await fetch(`${key.site}/client/toolaby.js`).then((r) => (r.ok ? r.text() : null)).catch(() => null);
117
+ const client = await fetchBounded(`${key.site}/client/toolaby.js`).then((r) => (r.ok && r.body ? r.body.toString('utf8') : null)).catch(() => null);
106
118
  if (client === null) warn('The Wall\'s current client could not be read to compare.');
107
- else if (sha(client) !== sha(readFileSync(at('toolaby.js'), 'utf8'))) warn(`toolaby.js is not the Wall's current client. \`npx toolaby upgrade ${key.slug}\` replaces it (your own files stay).`);
119
+ else if (sha(client) !== sha(readOr(at('toolaby.js'), ''))) warn(`toolaby.js is not the Wall's current client. \`npx toolaby upgrade ${key.slug}\` replaces it (your own files stay).`);
108
120
  else ok('toolaby.js is the Wall\'s current client.');
109
121
 
110
122
  // 6. The features the code gates on, against the tool's; and the page showPaywall() opens.
111
- const sources = sourceFiles(dir).map((f) => readFileSync(f, 'utf8'));
123
+ const sources = sourceFiles(dir).map((f) => { try { return readText(f); } catch { return ''; } });
112
124
  if (project.manifestFile && manifest && sources.some((s) => /\bshowPaywall\s*\(/.test(withoutComments(s)))) {
113
125
  const pages = [manifest.action?.default_popup ? 'toolaby-popup.html' : null, (manifest.side_panel?.default_path || manifest.sidebar_action?.default_panel) ? 'toolaby-sidepanel.html' : null].filter(Boolean);
114
126
  const absent = pages.filter((p) => !existsSync(join(dir, `${project.popupDir}${p}`)));
@@ -168,7 +180,7 @@ async function browserCheck({ dir, project, manifest, ok, warn, bad }) {
168
180
  new Promise((r) => setTimeout(() => r('timeout'), 8000)),
169
181
  ])).catch((e) => `error: ${e.message}`);
170
182
  if (answer && answer !== 'timeout' && !String(answer).startsWith('error')) ok('The background answers the Wall\'s client: its listeners registered.');
171
- else bad(`The background did not answer (${answer ?? 'nothing'}): its module threw while loading, so none of its listeners registered.`);
183
+ else bad(`The background did not answer (${oneLine(answer ?? 'nothing')}): its module threw while loading, so none of its listeners registered.`);
172
184
  await page.close().catch(() => {});
173
185
  // The extension's own pages, each opened in a tab: one whose script throws is a popup that opens blank.
174
186
  const own = [shipped?.action?.default_popup, shipped?.side_panel?.default_path].filter((p, i, all) => typeof p === 'string' && p && all.indexOf(p) === i);
@@ -179,12 +191,13 @@ async function browserCheck({ dir, project, manifest, ok, warn, bad }) {
179
191
  await tab.goto(`chrome-extension://${id}/${p}`).catch((e) => errors.push(e.message));
180
192
  await tab.waitForTimeout(1500);
181
193
  await tab.close().catch(() => {});
182
- if (errors.length) bad(`${p} threw when it opened: ${errors[0]}`);
183
- else ok(`${p} opens without an error.`);
194
+ if (errors.length) bad(`${oneLine(p)} threw when it opened: ${oneLine(errors[0])}`);
195
+ else ok(`${oneLine(p)} opens without an error.`);
184
196
  }
185
197
  } finally {
186
198
  await ctx.close().catch(() => {});
187
199
  }
188
200
  }
189
201
 
190
- function readJsonSafe(p) { try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; } }
202
+ function readJsonSafe(p) { try { return JSON.parse(readText(p)); } catch { return null; } }
203
+ function jsonOf(body) { try { return body ? JSON.parse(body.toString('utf8')) : null; } catch { return null; } }
package/lib/mcp.js CHANGED
@@ -10,17 +10,34 @@
10
10
  // them) to a command line that has none and that the Wall also serves as one tarball; this is the stdio transport and
11
11
  // the tools capability exactly as the specification words them. Nothing but protocol messages goes to stdout.
12
12
 
13
+ import { fetchBounded } from './safe.js';
14
+
13
15
  const PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
16
+ /**
17
+ * A tool id as the Wall makes them. Checked before it goes into a path: `..`, encoded or not, is a path the address
18
+ * resolves away, and `/api/cli/tools/../x` asked for `/api/cli/x` (25 Sep 2026).
19
+ */
20
+ const TOOL_ID = /^[a-z0-9][a-z0-9-]{1,118}$/;
21
+
22
+ /**
23
+ * What a tool does, as the specification's annotations say it (2025-03-26 on), for a client deciding what it may run
24
+ * without asking: a read changes nothing, a write changes the developer's own workspace — destructive where it takes
25
+ * away or gives away (what the Free plan holds, the feature list, access to someone), idempotent where a second call
26
+ * changes nothing more. Every tool acts on that workspace on the Wall and nothing beyond it. The writes carried no
27
+ * annotations, and a client took them for whatever its defaults were (25 Sep 2026).
28
+ */
29
+ const READS = { readOnlyHint: true, openWorldHint: false };
14
30
 
15
31
  /** The tools, with JSON Schema for their arguments, and what each calls on the Wall. */
16
32
  function toolsFor(side) {
17
- const tool = { type: 'string', description: 'The tool id, as `toolaby_list_tools` gives it (like "acme--word-counter").' };
33
+ const tool = { type: 'string', pattern: TOOL_ID.source, description: 'The tool id, as `toolaby_list_tools` gives it (like "acme--word-counter").' };
18
34
  return [
19
35
  {
20
36
  name: 'toolaby_whoami',
21
37
  title: 'Who is signed in',
22
38
  description: `The developer signed in to the ${side} Wall, and their workspaces.`,
23
39
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
40
+ annotations: READS,
24
41
  run: (_a, api) => api('/api/cli/me'),
25
42
  },
26
43
  {
@@ -28,6 +45,7 @@ function toolsFor(side) {
28
45
  title: 'List tools',
29
46
  description: `Every tool in the developer's workspaces on the ${side} Wall, with the id the other tools take.`,
30
47
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
48
+ annotations: READS,
31
49
  run: (_a, api) => api('/api/cli/tools'),
32
50
  },
33
51
  {
@@ -35,12 +53,13 @@ function toolsFor(side) {
35
53
  title: 'Read a tool',
36
54
  description: `One tool on the ${side} Wall: what the Free plan holds (freePlan.holds, in a sentence), its features, its plans with what each unlocks, its tool key, and its extension: identityId is the id of every copy whose manifest has the tool's key (such a copy needs no binding, so boundId stays null), checkedInAt says whether one has checked in, inUse which builds. Then the addresses of its pages.`,
37
55
  inputSchema: { type: 'object', properties: { tool }, required: ['tool'], additionalProperties: false },
56
+ annotations: READS,
38
57
  run: (a, api) => api(`/api/cli/tools/${encodeURIComponent(a.tool)}`),
39
58
  },
40
59
  {
41
60
  name: 'toolaby_create_tool',
42
61
  title: 'Create a tool',
43
- description: `A new tool on the ${side} Wall. Its Free plan holds everything until access is set. Then wire an extension to it: \`npx toolaby create <id>\` for a new one, \`npx toolaby wire <id>\` for an existing one.`,
62
+ description: `A new tool on the ${side} Wall. This changes what the developer's own workspace sells: one more tool. Its Free plan holds everything until access is set. Then wire an extension to it: \`npx toolaby create <id>\` for a new one, \`npx toolaby wire <id>\` for an existing one.`,
44
63
  inputSchema: {
45
64
  type: 'object',
46
65
  properties: {
@@ -52,12 +71,13 @@ function toolsFor(side) {
52
71
  required: ['name'],
53
72
  additionalProperties: false,
54
73
  },
74
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
55
75
  run: (a, api) => api('/api/cli/tools', { method: 'POST', body: a }),
56
76
  },
57
77
  {
58
78
  name: 'toolaby_set_access',
59
79
  title: 'Set what the Free plan holds',
60
- description: 'What a buyer gets before paying: "open" (the tool\'s use, unlimited), "free_uses" (a number of uses per device, counted by gate() without a feature), or "paid" (nothing before a plan). Whichever it is, a feature a plan sells (not marked free) is refused until bought. signInRequired asks for an account first. Takes effect on every device at its next check. The answer says when the tool key changed: `npx toolaby upgrade <id>` then writes the new one.',
80
+ description: 'What a buyer gets before paying: "open" (the tool\'s use, unlimited), "free_uses" (a number of uses per device, counted by gate() without a feature), or "paid" (nothing before a plan). This changes access in the developer\'s own workspace, for every buyer of the tool. Whichever it is, a feature a plan sells (not marked free) is refused until bought. signInRequired asks for an account first. Takes effect on every device at its next check. The answer says when the tool key changed: `npx toolaby upgrade <id>` then writes the new one.',
61
81
  inputSchema: {
62
82
  type: 'object',
63
83
  properties: {
@@ -69,12 +89,13 @@ function toolsFor(side) {
69
89
  required: ['tool', 'access'],
70
90
  additionalProperties: false,
71
91
  },
92
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
72
93
  run: ({ tool: t, ...rest }, api) => api(`/api/cli/tools/${encodeURIComponent(t)}/access`, { method: 'POST', body: rest }),
73
94
  },
74
95
  {
75
96
  name: 'toolaby_set_features',
76
97
  title: 'Set features, and the plans that unlock them',
77
- description: 'The tool\'s whole feature list (it replaces the current one: send the features it has too), and which plans unlock which. A feature\'s key is what the extension passes to gate({ feature }) and has(). A feature marked free is on the Free plan too; one that is not free and that no plan unlocks is refused to everyone. The plans must exist first (toolaby_add_plan); a plan not named in `plans` keeps what it unlocks.',
98
+ description: 'The tool\'s whole feature list (it replaces the current one: send the features it has too), and which plans unlock which. This changes billing in the developer\'s own workspace: what every plan of the tool sells. A feature\'s key is what the extension passes to gate({ feature }) and has(). A feature marked free is on the Free plan too; one that is not free and that no plan unlocks is refused to everyone. The plans must exist first (toolaby_add_plan); a plan not named in `plans` keeps what it unlocks.',
78
99
  inputSchema: {
79
100
  type: 'object',
80
101
  properties: {
@@ -102,12 +123,13 @@ function toolsFor(side) {
102
123
  required: ['tool', 'features'],
103
124
  additionalProperties: false,
104
125
  },
126
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
105
127
  run: ({ tool: t, ...rest }, api) => api(`/api/cli/tools/${encodeURIComponent(t)}/features`, { method: 'POST', body: rest }),
106
128
  },
107
129
  {
108
130
  name: 'toolaby_add_plan',
109
131
  title: 'Add a plan',
110
- description: `A plan buyers can buy: a Price on the workspace's Stripe account (${side === 'Test' ? 'on Test, its test account' : 'on Live, the connected account'}). "one_time" makes a lifetime licence; "subscription" bills monthly or yearly. Answers with the plan: its id (the tool's first plan is "default"), which openPaymentPage(id) takes, and its name as buyers see it, the name given and the kind ("Pro · Lifetime"). Then say what it unlocks with toolaby_set_features. The answer says when the tool key changed (the first subscription plan changes it): \`npx toolaby upgrade <id>\` then writes the new one.`,
132
+ description: `A plan buyers can buy: a Price on the workspace's Stripe account (${side === 'Test' ? 'on Test, its test account' : 'on Live, the connected account'}). This changes billing in the developer's own workspace. "one_time" makes a lifetime licence; "subscription" bills monthly or yearly. Answers with the plan: its id (the tool's first plan is "default"), which openPaymentPage(id) takes, and its name as buyers see it, the name given and the kind ("Pro · Lifetime"). Then say what it unlocks with toolaby_set_features. The answer says when the tool key changed (the first subscription plan changes it): \`npx toolaby upgrade <id>\` then writes the new one.`,
111
133
  inputSchema: {
112
134
  type: 'object',
113
135
  properties: {
@@ -124,18 +146,20 @@ function toolsFor(side) {
124
146
  required: ['tool', 'billing', 'amount', 'currency'],
125
147
  additionalProperties: false,
126
148
  },
149
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
127
150
  run: ({ tool: t, ...rest }, api) => api(`/api/cli/tools/${encodeURIComponent(t)}/plans`, { method: 'POST', body: rest }),
128
151
  },
129
152
  {
130
153
  name: 'toolaby_grant',
131
154
  title: 'Grant access',
132
- description: 'Access to the tool without paying: to test a paid feature on Test, or for a reviewer. An address with no account gets one; the grant applies once that person signs in to the extension with it (the link arrives by email), so testing a paid feature this way needs a person for a moment. For a number of days, or until revoked. On the Free plan a workspace holds 100 grants and other passes at once.',
155
+ description: 'Access to the tool without paying: to test a paid feature on Test, or for a reviewer. This changes access in the developer\'s own workspace: the person gets the paid features, and each call is another grant. An address with no account gets one; the grant applies once that person signs in to the extension with it (the link arrives by email), so testing a paid feature this way needs a person for a moment. For a number of days, or until revoked. On the Free plan a workspace holds 100 grants and other passes at once.',
133
156
  inputSchema: {
134
157
  type: 'object',
135
158
  properties: { tool, email: { type: 'string' }, days: { type: 'integer', minimum: 1, maximum: 3650, description: 'Optional: how long. Default: until revoked.' } },
136
159
  required: ['tool', 'email'],
137
160
  additionalProperties: false,
138
161
  },
162
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
139
163
  run: ({ tool: t, ...rest }, api) => api(`/api/cli/tools/${encodeURIComponent(t)}/grants`, { method: 'POST', body: rest }),
140
164
  },
141
165
  {
@@ -143,6 +167,7 @@ function toolsFor(side) {
143
167
  title: 'Read the docs',
144
168
  description: 'The Wall\'s docs as Markdown. Without a page: the index, every page with what it covers. With a page (like "gating", "pricing", "reference/client"): that page.',
145
169
  inputSchema: { type: 'object', properties: { page: { type: 'string' } }, additionalProperties: false },
170
+ annotations: READS,
146
171
  run: (a, _api, docs) => docs(a.page),
147
172
  },
148
173
  ];
@@ -168,13 +193,20 @@ export function runMcp({ version, side, wall, api, token }) {
168
193
  const clean = typeof page === 'string' ? page.replace(/^\/+|\.md$|\/+$/g, '').replace(/^docs\//, '') : '';
169
194
  if (clean && !/^[a-z0-9-]+(\/[a-z0-9-]+)*$/.test(clean)) return { ok: false, status: 400, json: { message: 'A page is a path like "gating" or "reference/client".' } };
170
195
  const url = clean ? `${wall}/docs/${clean}.md` : `${wall}/llms.txt`;
171
- const res = await fetch(url).catch((e) => ({ ok: false, status: 0, text: async () => e.message }));
172
- const text = await res.text();
196
+ // The Wall's own pages, a few megabytes at most: a redirect elsewhere handed an agent any host's page as the docs (25 Sep 2026).
197
+ const res = await fetchBounded(url, { limit: 4 * 1024 * 1024 }).catch(() => ({ ok: false, status: 0, body: null }));
198
+ if (res.ok && !res.body) return { ok: false, status: 413, json: { message: 'The docs page is larger than any the Wall serves.' } };
199
+ const text = res.body ? res.body.toString('utf8') : '';
173
200
  return res.ok ? { ok: true, status: res.status, text } : { ok: false, status: res.status, json: { message: res.status === 404 ? `No docs page "${clean}". Call toolaby_docs without a page for the index.` : `The docs answered HTTP ${res.status}.` } };
174
201
  };
175
202
  const call = async (name, args) => {
176
203
  const t = tools.find((x) => x.name === name);
177
204
  if (!t) return { error: { code: -32602, message: `Unknown tool: ${name}` } };
205
+ // Arguments are an object, or none: anything else threw before the answer, and the request went unanswered.
206
+ if (args !== undefined && (args === null || typeof args !== 'object' || Array.isArray(args))) return { error: { code: -32602, message: 'Arguments are an object.' } };
207
+ if (args && 'tool' in args && (typeof args.tool !== 'string' || !TOOL_ID.test(args.tool))) {
208
+ return { result: { content: [{ type: 'text', text: 'A tool id is lowercase letters, digits and dashes, as toolaby_list_tools gives it.' }], isError: true } };
209
+ }
178
210
  if (name !== 'toolaby_docs' && !token()) {
179
211
  return { result: { content: [{ type: 'text', text: `Not signed in to the ${side} Wall (${wall}). Run \`npx toolaby login${side === 'Live' ? ' --live' : ''}\` in a terminal, then call this again.` }], isError: true } };
180
212
  }
package/lib/project.js CHANGED
@@ -120,11 +120,13 @@ export function detectProject(o) {
120
120
  if (crxjs && !has('manifest.json')) {
121
121
  const configFile = first(has, ['manifest.config.ts', 'manifest.config.js', 'manifest.ts', 'manifest.js', 'src/manifest.ts', 'src/manifest.js']);
122
122
  const source = o.manifestSource ?? '';
123
- const declared = source.match(/default_popup:\s*['"]([^'"]+)['"]/)?.[1] ?? null;
123
+ // A name as one line of a path: read across a line break or a backslash, a project's config drew lines of its own
124
+ // into the snippets the command prints and the dashboard shows (25 Sep 2026).
125
+ const declared = source.match(/default_popup:\s*['"]([^'"\\\r\n]+)['"]/)?.[1] ?? null;
124
126
  const appPopup = declared && declared !== 'toolaby-popup.html' ? declared : null;
125
- const declaredPanel = source.match(/default_path:\s*['"]([^'"]+)['"]/)?.[1] ?? null;
127
+ const declaredPanel = source.match(/default_path:\s*['"]([^'"\\\r\n]+)['"]/)?.[1] ?? null;
126
128
  const appSidePanel = declaredPanel && declaredPanel !== 'toolaby-sidepanel.html' ? declaredPanel : null;
127
- const worker = source.match(/service_worker:\s*['"]([^'"]+)['"]/)?.[1] ?? first(has, ['src/background.ts', 'src/background.js', 'background.ts', 'background.js']);
129
+ const worker = source.match(/service_worker:\s*['"]([^'"\\\r\n]+)['"]/)?.[1] ?? first(has, ['src/background.ts', 'src/background.js', 'background.ts', 'background.js']);
128
130
  const workerFile = worker ?? 'src/background.ts';
129
131
  const workerLines = `import { toolaby } from '${importPath(workerFile)}';\n\ntoolaby.startBackground();\n`;
130
132
  const code = [
package/lib/safe.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // What this command will not do, whoever asks: write outside the project it was pointed at, write a file of a new
2
- // extension it does not know, open a sign-in page that is not the Wall's, or put a private file in a store zip.
2
+ // extension it does not know, open a sign-in page that is not the Wall's, put a private file in a store zip, print a
3
+ // line it did not write, ask whatever address a project names, or take a download without end.
3
4
  //
4
5
  // Each of these took someone else's word. A cloned repository's manifest named the file `wire` wrote — a service
5
6
  // worker at "../../.zshrc" overwrote the shell's startup file — and a link in the folder took a write wherever it
@@ -7,7 +8,7 @@
7
8
  // address (--wall, TOOLABY_WALL) could write any file with any content. And on Windows the sign-in address went
8
9
  // through cmd.exe, where an `&` in it ran a command. Hand-written, unlike manifest.js and project.js: this is the
9
10
  // command's own boundary, not a wiring rule the browser shares.
10
- import { lstatSync } from 'node:fs';
11
+ import { lstatSync, readFileSync, statSync } from 'node:fs';
11
12
  import { isAbsolute, join, posix, relative, resolve, sep, win32 } from 'node:path';
12
13
 
13
14
  /**
@@ -44,6 +45,110 @@ export function inside(root, rel) {
44
45
 
45
46
  const LOOPBACK = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$|\.localhost$/i;
46
47
 
48
+ /**
49
+ * A value from a Wall's answer or a project's file, as one line. Every line leaves without terminal controls (bin.mjs),
50
+ * but keeps its line breaks, which the command's own messages need — so a tool name with "\n✓ Ready to publish" in it
51
+ * printed a whole line of its own, under the command's real ones (25 Sep 2026). Each such value goes through this
52
+ * where it is put into a line: line breaks and tabs, and any run of space, are one space.
53
+ */
54
+ export const oneLine = (value) => String(value).replace(/\s+/g, ' ').slice(0, 500);
55
+
56
+ /** An address a Wall answers on: https, or http on this machine, for a Wall on the developer's laptop. */
57
+ const wallScheme = (url) => url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK.test(url.hostname));
58
+
59
+ /**
60
+ * The Wall a tool key names, when `check` may ask it anything: an origin, https or on this machine, and nothing else —
61
+ * no path, no credentials, no other scheme — or null. The key is read from the project's own toolaby.config.js, and a
62
+ * cloned project's key sent `check`'s requests wherever it named: a server inside the developer's network, any path on
63
+ * any host (25 Sep 2026).
64
+ */
65
+ export function keySite(site) {
66
+ let url;
67
+ try { url = new URL(site); } catch { return null; }
68
+ return url.origin === site && wallScheme(url) ? site : null;
69
+ }
70
+
71
+ /**
72
+ * A GET that cannot run away with the command: the body read up to `limit` bytes and no further, the whole within `ms`,
73
+ * and a redirect followed — five at most — only to an address a Wall answers on. Answers `{ status, ok, body }`, the
74
+ * body null when it passed the limit; throws as fetch does, and with a TimeoutError when the time runs out. A Wall at
75
+ * another address (--wall, TOOLABY_WALL) could send `create` an icon without end, which the new folder took until the
76
+ * disk was full; and an https address that redirected took `check` anywhere (25 Sep 2026).
77
+ */
78
+ export async function fetchBounded(url, { limit = 1024 * 1024, ms = 30_000 } = {}) {
79
+ const signal = AbortSignal.timeout(ms);
80
+ const origin = new URL(url).origin;
81
+ let res = await fetch(url, { redirect: 'manual', signal });
82
+ for (let hops = 0; hops < 5 && res.status >= 300 && res.status < 400 && res.headers.get('location'); hops++) {
83
+ const next = new URL(res.headers.get('location'), url);
84
+ // Within the address asked, and no further: an https Wall that redirected sent `check` to a service on this
85
+ // machine, whose answer it printed as the tool's (25 Sep 2026).
86
+ if (next.origin !== origin || !wallScheme(next)) break;
87
+ await res.body?.cancel().catch(() => {});
88
+ url = next.href;
89
+ res = await fetch(url, { redirect: 'manual', signal });
90
+ }
91
+ const answered = { status: res.status, ok: res.ok };
92
+ if (Number(res.headers.get('content-length')) > limit) { await res.body?.cancel().catch(() => {}); return { ...answered, body: null }; }
93
+ const chunks = [];
94
+ let size = 0;
95
+ const reader = res.body?.getReader();
96
+ for (;;) {
97
+ const { done, value } = reader ? await reader.read() : { done: true };
98
+ if (done) break;
99
+ size += value.byteLength;
100
+ if (size > limit) { await reader.cancel().catch(() => {}); return { ...answered, body: null }; }
101
+ chunks.push(value);
102
+ }
103
+ return { ...answered, body: Buffer.concat(chunks) };
104
+ }
105
+
106
+ /**
107
+ * A request that follows a redirect only within the address it asked — a Wall moving a page on its own host — and
108
+ * refuses one elsewhere: fetch drops the session on the way, but the command took whatever the other address answered
109
+ * for the Wall's word, and the MCP server handed an agent a page from any host (25 Sep 2026).
110
+ */
111
+ export async function fetchHere(url, init = {}) {
112
+ const origin = new URL(url).origin;
113
+ let res = await fetch(url, { ...init, redirect: 'manual' });
114
+ for (let hops = 0; hops < 5 && res.status >= 300 && res.status < 400 && res.headers.get('location'); hops++) {
115
+ const next = new URL(res.headers.get('location'), url);
116
+ await res.body?.cancel().catch(() => {});
117
+ if (next.origin !== origin) throw new Error(`it answered with a redirect to ${next.origin}, which is not followed`);
118
+ url = next.href;
119
+ res = await fetch(url, { ...init, redirect: 'manual' });
120
+ }
121
+ return res;
122
+ }
123
+
124
+ /** The most of one project file the command reads as text: a manifest, a config, a source file — none comes near it. */
125
+ export const READ_LIMIT = 5 * 1024 * 1024;
126
+
127
+ /**
128
+ * A project file's text, where it is a file and no larger than READ_LIMIT; otherwise it throws, as a missing one does.
129
+ * A cloned repository can hold a link to /dev/zero, or a pipe, under any name the command reads: it waited, or filled
130
+ * its memory, for ever (25 Sep 2026).
131
+ */
132
+ export function readText(path, limit = READ_LIMIT) {
133
+ const st = statSync(path);
134
+ if (!st.isFile()) throw new Error(`${path} is not a file`);
135
+ if (st.size > limit) throw new Error(`${path} is larger than any file this reads`);
136
+ return readFileSync(path, 'utf8');
137
+ }
138
+
139
+ /**
140
+ * Why a file's contents have no place in a store zip, whatever it is called, or null: a private key, a cloud service
141
+ * account's key, a source map written into the code. Names alone let `key.txt`, a Google Cloud key under the name
142
+ * its console gives it, and a bundle's inline map through (25 Sep 2026).
143
+ */
144
+ export function privateContent(bytes) {
145
+ const text = bytes.subarray(0, 4 * 1024 * 1024).toString('latin1');
146
+ if (/"type"\s*:\s*"service_account"/.test(text) && /"private_key"\s*:/.test(text)) return "a service account's key inside";
147
+ if (/-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----/.test(text)) return 'a private key inside';
148
+ if (/[#@]\s*sourceMappingURL\s*=\s*data:/.test(text)) return 'a source map inside';
149
+ return null;
150
+ }
151
+
47
152
  /**
48
153
  * The page `login` opens: the one the Wall gave, when it is the Wall's own over https — or, for a Wall on this
49
154
  * machine, a page on this machine. Anything else is null, and is not opened: an address elsewhere, a downgrade to
@@ -72,15 +177,22 @@ export function opener(platform, url) {
72
177
 
73
178
  /**
74
179
  * Why a file has no place in a store zip, or null: a private key or a keystore (Chrome's own "Pack extension" leaves
75
- * the extension's .pem beside the folder, and it ends up inside), an environment file, a file of credentials by its
76
- * name, or a source map, which carries the source. A store zip is public: anyone can download an item and unzip it.
77
- * `pack` leaves these out and names them; --allow-private packs them. Dotfiles, .env among them, are never packed.
180
+ * the extension's .pem beside the folder, and it ends up inside), a certificate, an environment file, a file of
181
+ * credentials by its name — a cloud service account's key, a package registry's or a machine's login — or a source
182
+ * map, which carries the source. A store zip is public: anyone can download an item and unzip it. `pack` leaves these
183
+ * out and names them; --allow-private packs them. Dotfiles, .env and .npmrc among them, are never packed, and are
184
+ * named here all the same. A certificate, a service account's key under the name its console downloads it with
185
+ * (firebase-adminsdk-…json, …-service-account-…json), an SSH key with a suffix and Windows' _netrc were packed until
186
+ * 25 Sep 2026.
78
187
  */
79
188
  export function privateKind(name) {
80
189
  const n = name.toLowerCase();
81
- if (/\.(pem|key|p12|pfx|p8|jks|keystore|ppk)$/.test(n) || /^id_(rsa|dsa|ecdsa|ed25519)$/.test(n)) return 'a private key';
190
+ if (/\.(pem|key|p12|pfx|p8|jks|keystore|bks|ppk)$/.test(n) || /^id_(rsa|dsa|ecdsa|ed25519)(?!.*\.pub$)/.test(n)) return 'a private key';
191
+ if (/\.(crt|cer|der)$/.test(n)) return 'a certificate';
82
192
  if (/\.env(\.[^.]+)*$/.test(n)) return 'an environment file';
83
- if (/^(credentials|secrets?|service[-_]?account[^/]*)\.json$/.test(n)) return 'credentials';
193
+ if (/^(credentials|secrets?)(\.(json|ya?ml|toml))?$/.test(n) || /(service[-_]?account|firebase-adminsdk|^client_secret)[^/]*\.json$/.test(n)) return 'credentials';
194
+ if (/\.tfstate(\.backup)?$/.test(n)) return "a deployment's state";
195
+ if (/^[._]?(npmrc|yarnrc\.yml|netrc|pypirc|git-credentials|htpasswd|pgpass)$/.test(n)) return 'credentials';
84
196
  if (n.endsWith('.map')) return 'a source map';
85
197
  return null;
86
198
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toolaby",
3
- "version": "1.6.1",
3
+ "version": "1.6.2",
4
4
  "description": "The Toolaby command line: sign in once, then wire any Chrome extension to your tool on the Wall — sign-in, the Free plan, licences and subscriptions — or start a new one; check it, and give coding agents the Wall as an MCP server.",
5
5
  "type": "module",
6
6
  "bin": {