honeybook-mcp 1.1.3 → 1.1.4

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.
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "metadata": {
9
9
  "description": "HoneyBook client-portal tools for Claude Code",
10
- "version": "1.1.3"
10
+ "version": "1.1.4"
11
11
  },
12
12
  "plugins": [
13
13
  {
@@ -15,7 +15,7 @@
15
15
  "displayName": "HoneyBook",
16
16
  "source": "./",
17
17
  "description": "HoneyBook client-portal MCP for Claude — view wedding-vendor contracts and invoices via MCP",
18
- "version": "1.1.3",
18
+ "version": "1.1.4",
19
19
  "author": {
20
20
  "name": "Chris Chall"
21
21
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "honeybook",
3
3
  "displayName": "HoneyBook",
4
- "version": "1.1.3",
4
+ "version": "1.1.4",
5
5
  "description": "HoneyBook client-portal MCP for Claude — view wedding-vendor contracts and invoices via MCP",
6
6
  "author": {
7
7
  "name": "Chris Chall",
package/dist/auth.js CHANGED
@@ -67,7 +67,7 @@ import { bootstrap } from '@fetchproxy/bootstrap';
67
67
  import { bridgeErrorInfo } from '@chrischall/mcp-utils/fetchproxy';
68
68
  import { parseBoolEnv } from '@chrischall/mcp-utils';
69
69
  import pkg from '../package.json' with { type: 'json' };
70
- import { sessionStore, normalizeOrigin } from './sessions.js';
70
+ import { sessionStore, normalizeOrigin, vendorPortalSubdomain } from './sessions.js';
71
71
  /** True if the user has explicitly disabled the fetchproxy capture path. */
72
72
  function fetchproxyDisabled() {
73
73
  return parseBoolEnv('HONEYBOOK_DISABLE_FETCHPROXY');
@@ -87,6 +87,8 @@ function fetchproxyDisabled() {
87
87
  * subsequent tool call without an explicit `origin` will use it.
88
88
  */
89
89
  export async function captureSessionViaFetchproxy(opts) {
90
+ // Refuse a foreign host before the bridge opens (fleet-audit#139).
91
+ const vendorSubdomain = vendorPortalSubdomain(opts.portalOrigin);
90
92
  if (fetchproxyDisabled()) {
91
93
  throw new Error('HoneyBook auth: fetchproxy capture is disabled by HONEYBOOK_DISABLE_FETCHPROXY. ' +
92
94
  'Unset that env var to enable session capture via the browser extension.');
@@ -111,6 +113,10 @@ export async function captureSessionViaFetchproxy(opts) {
111
113
  // know which tab to target.
112
114
  domains: ['honeybook.com', 'hbportal.co'],
113
115
  storageDomain: 'hbportal.co',
116
+ // Pin the read to the vendor's own tab. Without it the extension reads
117
+ // whichever hbportal.co tab is open, so vendor A's token could be
118
+ // stored under vendor B's origin (fleet-audit#139).
119
+ storageSubdomain: vendorSubdomain,
114
120
  declare: {
115
121
  cookies: [],
116
122
  // `HONEYBOOK_REACT_CURR_USER` is ~6.5KB of mostly unused user
package/dist/bundle.js CHANGED
@@ -26988,6 +26988,22 @@ var storage = new AsyncLocalStorage();
26988
26988
  function withCallSignal(signal, fn, request) {
26989
26989
  return signal ? storage.run({ signal, ...request ? { request } : {} }, fn) : fn();
26990
26990
  }
26991
+ function currentCallSignal() {
26992
+ return storage.getStore()?.signal;
26993
+ }
26994
+ function withAmbientCancellation(own2) {
26995
+ const ambient = currentCallSignal();
26996
+ if (!ambient)
26997
+ return own2;
26998
+ if (!own2)
26999
+ return ambient;
27000
+ return AbortSignal.any([own2, ambient]);
27001
+ }
27002
+ function throwIfCancelled() {
27003
+ const signal = currentCallSignal();
27004
+ if (signal?.aborted)
27005
+ throw signal.reason instanceof Error ? signal.reason : new Error(String(signal.reason));
27006
+ }
26991
27007
 
26992
27008
  // node_modules/@chrischall/mcp-utils/dist/caller/index.js
26993
27009
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
@@ -61817,6 +61833,21 @@ var sessionStore = new SessionStore({
61817
61833
  keyOf: (session) => session.portalOrigin,
61818
61834
  normalizeKey: normalizeOrigin
61819
61835
  });
61836
+ function vendorPortalSubdomain(input2) {
61837
+ let url4 = null;
61838
+ try {
61839
+ url4 = new URL(input2);
61840
+ } catch {
61841
+ url4 = null;
61842
+ }
61843
+ const match = url4 && url4.protocol === "https:" && url4.port === "" ? /^([a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\.hbportal\.co$/.exec(url4.hostname) : null;
61844
+ if (!match) {
61845
+ throw new Error(
61846
+ `"${input2}" is not a HoneyBook vendor portal link. Expected https://<vendor>.hbportal.co/\u2026 (the link in the vendor's HoneyBook email).`
61847
+ );
61848
+ }
61849
+ return match[1];
61850
+ }
61820
61851
 
61821
61852
  // src/flows.ts
61822
61853
  import { join as join3 } from "node:path";
@@ -61865,15 +61896,65 @@ var flowStore = new SessionStore({
61865
61896
  var API_BASE = "https://api.honeybook.com";
61866
61897
  var clientCache = /* @__PURE__ */ new Map();
61867
61898
  var moduleState = { apiVersionPromise: null };
61899
+ var httpTimeouts = { requestMs: 3e4 };
61900
+ function hbRequestSignal() {
61901
+ return withAmbientCancellation(AbortSignal.timeout(httpTimeouts.requestMs));
61902
+ }
61903
+ async function withHbTimeout(what, fn) {
61904
+ const signal = hbRequestSignal();
61905
+ try {
61906
+ return await fn(signal);
61907
+ } catch (err) {
61908
+ if (err?.name === "TimeoutError" && !currentCallSignal()?.aborted) {
61909
+ throw new Error(`HoneyBook did not respond within ${httpTimeouts.requestMs / 1e3}s (${what}).`);
61910
+ }
61911
+ throw err;
61912
+ }
61913
+ }
61914
+ function cancellableDelay(ms) {
61915
+ const signal = currentCallSignal();
61916
+ return new Promise((resolve2, reject) => {
61917
+ if (signal?.aborted) return reject(signal.reason);
61918
+ const onAbort = () => {
61919
+ clearTimeout(timer);
61920
+ reject(signal.reason);
61921
+ };
61922
+ const timer = setTimeout(() => {
61923
+ signal?.removeEventListener("abort", onAbort);
61924
+ resolve2();
61925
+ }, ms);
61926
+ signal?.addEventListener("abort", onAbort, { once: true });
61927
+ });
61928
+ }
61868
61929
  async function fetchApiVersion() {
61869
61930
  const override = readEnvVar("HONEYBOOK_API_VERSION");
61870
61931
  if (override) return Number(override);
61871
- const res = await fetch(`${API_BASE}/api/gon?callback=parseGon`);
61872
- const text = await res.text();
61932
+ const text = await withHbTimeout("GET /api/gon", async (signal) => {
61933
+ const res = await fetch(`${API_BASE}/api/gon?callback=parseGon`, { signal });
61934
+ return res.text();
61935
+ });
61873
61936
  const m = /"api_version":\s*(\d+)/.exec(text);
61874
61937
  if (!m) throw new Error(`Could not parse api_version from /api/gon response: ${text.slice(0, 200)}`);
61875
61938
  return Number(m[1]);
61876
61939
  }
61940
+ function apiPath(strings, ...values) {
61941
+ let out = strings[0] ?? "";
61942
+ values.forEach((value, i) => {
61943
+ const raw = String(value);
61944
+ if (raw === "" || raw === "." || raw === "..") {
61945
+ throw new Error(`${JSON.stringify(raw)} is not a valid HoneyBook id.`);
61946
+ }
61947
+ out += encodeURIComponent(raw) + (strings[i + 1] ?? "");
61948
+ });
61949
+ return out;
61950
+ }
61951
+ function assertNoPathTraversal(path) {
61952
+ const pathname = path.split(/[?#]/, 1)[0] ?? "";
61953
+ const dotSegment = /^(?:\.|%2e){1,2}$/i;
61954
+ if (pathname.includes("\\") || pathname.split("/").some((seg) => dotSegment.test(seg))) {
61955
+ throw new Error(`Refusing HoneyBook API path with a path traversal segment: ${path}`);
61956
+ }
61957
+ }
61877
61958
  var HoneyBookApiError = class extends Error {
61878
61959
  /** Structural marker, so the predicate survives a duplicated module copy. */
61879
61960
  honeyBookApiError = true;
@@ -61894,49 +61975,55 @@ var HoneyBookApiError = class extends Error {
61894
61975
  function isHoneyBookApiError(err) {
61895
61976
  return err instanceof HoneyBookApiError || typeof err === "object" && err !== null && err.honeyBookApiError === true;
61896
61977
  }
61897
- async function hbApiRequest(caller, method, path, body, isVersionRetry = false, isRateRetry = false) {
61978
+ async function hbApiRequest(caller, method, path, body, isVersionRetry = false, isRateRetry = false, dedupeId = crypto.randomUUID()) {
61979
+ assertNoPathTraversal(path);
61898
61980
  const headers = {
61899
61981
  accept: "application/json, text/plain, */*",
61900
61982
  "hb-api-client-version": String(caller.getApiVersion()),
61901
- "hb-api-duplicate-calls-prevention-uuid": crypto.randomUUID(),
61983
+ "hb-api-duplicate-calls-prevention-uuid": dedupeId,
61902
61984
  ...caller.authHeaders()
61903
61985
  };
61904
61986
  if (body !== void 0) headers["content-type"] = "application/json";
61905
- const response = await fetch(`${API_BASE}${path}`, {
61906
- method,
61907
- headers,
61908
- ...body !== void 0 ? { body: JSON.stringify(body) } : {}
61987
+ const { status, ok, text } = await withHbTimeout(`${method} ${path}`, async (signal) => {
61988
+ const response = await fetch(`${API_BASE}${path}`, {
61989
+ method,
61990
+ headers,
61991
+ signal,
61992
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
61993
+ });
61994
+ if (response.status === 401 || response.status === 429) {
61995
+ return { status: response.status, ok: false, text: "" };
61996
+ }
61997
+ return { status: response.status, ok: response.ok, text: await response.text() };
61909
61998
  });
61910
- if (response.status === 401) throw caller.authExpiredError();
61911
- if (response.status === 429) {
61999
+ if (status === 401) throw caller.authExpiredError();
62000
+ if (status === 429) {
61912
62001
  if (!isRateRetry) {
61913
- await new Promise((r) => setTimeout(r, 2e3));
61914
- return hbApiRequest(caller, method, path, body, isVersionRetry, true);
62002
+ await cancellableDelay(2e3);
62003
+ return hbApiRequest(caller, method, path, body, isVersionRetry, true, dedupeId);
61915
62004
  }
61916
62005
  throw new Error("Rate limited by HoneyBook API");
61917
62006
  }
61918
- if (!response.ok) {
61919
- const text2 = await response.text();
61920
- if (response.status === 404 && text2.includes("HBUnauthorizedError")) {
62007
+ if (!ok) {
62008
+ if (status === 404 && text.includes("HBUnauthorizedError")) {
61921
62009
  throw caller.authExpiredError();
61922
62010
  }
61923
- if (text2.includes("HBWrongAPIVersionError") && !isVersionRetry) {
62011
+ if (text.includes("HBWrongAPIVersionError") && !isVersionRetry) {
61924
62012
  try {
61925
- const parsed = JSON.parse(text2);
62013
+ const parsed = JSON.parse(text);
61926
62014
  const fresh = parsed.error_data?.server_api_version ?? await fetchApiVersion();
61927
62015
  caller.setApiVersion(fresh);
61928
62016
  moduleState.apiVersionPromise = Promise.resolve(fresh);
61929
62017
  } catch {
61930
62018
  caller.setApiVersion(await fetchApiVersion());
61931
62019
  }
61932
- return hbApiRequest(caller, method, path, body, true, isRateRetry);
62020
+ return hbApiRequest(caller, method, path, body, true, isRateRetry, dedupeId);
61933
62021
  }
61934
62022
  throw new HoneyBookApiError(
61935
- formatApiError(response.status, method, path, text2, { service: "HoneyBook" }),
61936
- { status: response.status, method, path, body: text2 }
62023
+ formatApiError(status, method, path, text, { service: "HoneyBook" }),
62024
+ { status, method, path, body: text }
61937
62025
  );
61938
62026
  }
61939
- const text = await response.text();
61940
62027
  return text ? JSON.parse(text) : null;
61941
62028
  }
61942
62029
  var HoneyBookClient = class {
@@ -67725,7 +67812,7 @@ function bridgeErrorInfo(err) {
67725
67812
  // package.json
67726
67813
  var package_default = {
67727
67814
  name: "honeybook-mcp",
67728
- version: "1.1.3",
67815
+ version: "1.1.4",
67729
67816
  mcpName: "io.github.chrischall/honeybook-mcp",
67730
67817
  description: "HoneyBook client-portal MCP server for Claude",
67731
67818
  author: "Claude Code (AI) <https://www.anthropic.com/claude>",
@@ -67791,6 +67878,7 @@ function fetchproxyDisabled() {
67791
67878
  return parseBoolEnv("HONEYBOOK_DISABLE_FETCHPROXY");
67792
67879
  }
67793
67880
  async function captureSessionViaFetchproxy(opts) {
67881
+ const vendorSubdomain = vendorPortalSubdomain(opts.portalOrigin);
67794
67882
  if (fetchproxyDisabled()) {
67795
67883
  throw new Error(
67796
67884
  "HoneyBook auth: fetchproxy capture is disabled by HONEYBOOK_DISABLE_FETCHPROXY. Unset that env var to enable session capture via the browser extension."
@@ -67816,6 +67904,10 @@ async function captureSessionViaFetchproxy(opts) {
67816
67904
  // know which tab to target.
67817
67905
  domains: ["honeybook.com", "hbportal.co"],
67818
67906
  storageDomain: "hbportal.co",
67907
+ // Pin the read to the vendor's own tab. Without it the extension reads
67908
+ // whichever hbportal.co tab is open, so vendor A's token could be
67909
+ // stored under vendor B's origin (fleet-audit#139).
67910
+ storageSubdomain: vendorSubdomain,
67819
67911
  declare: {
67820
67912
  cookies: [],
67821
67913
  // `HONEYBOOK_REACT_CURR_USER` is ~6.5KB of mostly unused user
@@ -67990,6 +68082,7 @@ function fetchproxyDisabled2() {
67990
68082
  }
67991
68083
  async function captureFlowCredentialViaFetchproxy(opts) {
67992
68084
  const link2 = parseFlowLink(opts.flowLinkUrl);
68085
+ const vendorSubdomain = vendorPortalSubdomain(link2.portalOrigin);
67993
68086
  if (fetchproxyDisabled2()) {
67994
68087
  throw new Error(
67995
68088
  "HoneyBook flow auth: fetchproxy capture is disabled by HONEYBOOK_DISABLE_FETCHPROXY. Unset that env var to enable credential capture via the browser extension."
@@ -68003,6 +68096,7 @@ async function captureFlowCredentialViaFetchproxy(opts) {
68003
68096
  version: package_default.version,
68004
68097
  domains: ["honeybook.com", "hbportal.co"],
68005
68098
  storageDomain: "hbportal.co",
68099
+ storageSubdomain: vendorSubdomain,
68006
68100
  declare: {
68007
68101
  cookies: [],
68008
68102
  localStorage: [],
@@ -68179,21 +68273,24 @@ async function fetchFlowMinimal(flowId, opts) {
68179
68273
  if (opts.userId) query.set("user_id", opts.userId);
68180
68274
  const suffix = query.size > 0 ? `?${query}` : "";
68181
68275
  const url4 = `${API_BASE}/api/v2/flow/${encodeURIComponent(flowId)}/minimal${suffix}`;
68182
- const response = await fetch(url4, {
68183
- headers: {
68184
- accept: "application/json, text/plain, */*",
68185
- "hb-api-client-version": String(opts.apiVersion)
68186
- }
68276
+ const { response, body } = await withHbTimeout(`GET /api/v2/flow/${flowId}/minimal`, async (signal) => {
68277
+ const response2 = await fetch(url4, {
68278
+ signal,
68279
+ headers: {
68280
+ accept: "application/json, text/plain, */*",
68281
+ "hb-api-client-version": String(opts.apiVersion)
68282
+ }
68283
+ });
68284
+ return { response: response2, body: await response2.text().catch(() => "") };
68187
68285
  });
68188
68286
  if (!response.ok) {
68189
- const body = await response.text().catch(() => "");
68190
68287
  const detail = body.slice(0, 300);
68191
68288
  const cause = response.status === 404 ? `no flow ${flowId} \u2014 it may have been deleted, or the id is wrong` : /WrongAPIVersion/i.test(body) ? `HoneyBook rejected hb-api-client-version ${opts.apiVersion}; this package's pinned value needs updating` : "that route is public, so this is a HoneyBook-side problem rather than a credential one";
68192
68289
  throw new Error(
68193
68290
  `HoneyBook flow: GET /api/v2/flow/${flowId}/minimal answered ${response.status} \u2014 ${cause}. It is where the context id (ctxc) the questionnaire read sends comes from.` + (detail ? ` Response: ${detail}` : "")
68194
68291
  );
68195
68292
  }
68196
- return await response.json();
68293
+ return JSON.parse(body);
68197
68294
  }
68198
68295
  function flowContextId(minimal) {
68199
68296
  return minimal.branding_data?.company_id ?? null;
@@ -68320,7 +68417,7 @@ function registerHealthcheckTools(server) {
68320
68417
  },
68321
68418
  probeFn: async () => {
68322
68419
  const client = await getActiveClient();
68323
- return client.request("GET", `/api/v2/users/${client.scope.userId}/payment_methods`);
68420
+ return client.request("GET", apiPath`/api/v2/users/${client.scope.userId}/payment_methods`);
68324
68421
  },
68325
68422
  classifyThrown: (err) => {
68326
68423
  const msg = err instanceof Error ? err.message : String(err);
@@ -68520,7 +68617,7 @@ async function listWorkspaceFiles(args) {
68520
68617
  const client = await getActiveClient(args.origin);
68521
68618
  const res = await client.request(
68522
68619
  "GET",
68523
- `/api/v2/users/${client.scope.userId}/workspace_files`
68620
+ apiPath`/api/v2/users/${client.scope.userId}/workspace_files`
68524
68621
  );
68525
68622
  const filtered = args.file_type ? res.data.filter((f) => f.file_type === args.file_type) : res.data;
68526
68623
  const prefix = res.last_page === false ? "// NOTE: more results exist on later pages; pagination is not yet wired up.\n" : "";
@@ -68529,7 +68626,7 @@ async function listWorkspaceFiles(args) {
68529
68626
  async function getWorkspaceFile(args) {
68530
68627
  const section = args.section ?? "summary";
68531
68628
  const client = await getActiveClient(args.origin);
68532
- const raw = await client.request("GET", `/api/v2/workspace_files/${args.file_id}`);
68629
+ const raw = await client.request("GET", apiPath`/api/v2/workspace_files/${args.file_id}`);
68533
68630
  let body;
68534
68631
  switch (section) {
68535
68632
  case "raw":
@@ -68593,7 +68690,7 @@ async function getWorkspace(args) {
68593
68690
  const client = await getActiveClient(args.origin);
68594
68691
  const res = await client.request(
68595
68692
  "GET",
68596
- `/api/v2/workspaces/${args.workspace_id}`
68693
+ apiPath`/api/v2/workspaces/${args.workspace_id}`
68597
68694
  );
68598
68695
  return minifiedResult(res);
68599
68696
  }
@@ -68619,7 +68716,7 @@ async function listPaymentMethods(args) {
68619
68716
  const client = await getActiveClient(args.origin);
68620
68717
  const res = await client.request(
68621
68718
  "GET",
68622
- `/api/v2/users/${client.scope.userId}/payment_methods`
68719
+ apiPath`/api/v2/users/${client.scope.userId}/payment_methods`
68623
68720
  );
68624
68721
  return minifiedResult(res);
68625
68722
  }
@@ -68644,7 +68741,7 @@ async function signContract(args) {
68644
68741
  const client = await getActiveClient(args.origin);
68645
68742
  const file2 = await client.request(
68646
68743
  "GET",
68647
- `/api/v2/workspace_files/${args.file_id}`
68744
+ apiPath`/api/v2/workspace_files/${args.file_id}`
68648
68745
  );
68649
68746
  if (file2.file_type !== "agreement") {
68650
68747
  throw new Error(
@@ -68660,7 +68757,8 @@ async function signContract(args) {
68660
68757
  Re-run sign_contract with { confirm: true } to proceed.`
68661
68758
  );
68662
68759
  }
68663
- const url4 = `${client.scope.portalOrigin}/app/workspace_file/${file2._id}/agreement`;
68760
+ vendorPortalSubdomain(client.scope.portalOrigin);
68761
+ const url4 = `${client.scope.portalOrigin}/app/workspace_file/${encodeURIComponent(String(file2._id))}/agreement`;
68664
68762
  return rawTextResult(
68665
68763
  `HoneyBook's signing flow requires a browser signature that this MCP cannot replay headlessly yet.
68666
68764
 
@@ -68694,7 +68792,7 @@ function registerContractTools(server) {
68694
68792
  // src/tools/invoices.ts
68695
68793
  async function payInvoice(args) {
68696
68794
  const client = await getActiveClient(args.origin);
68697
- const file2 = await client.request("GET", `/api/v2/workspace_files/${args.file_id}`);
68795
+ const file2 = await client.request("GET", apiPath`/api/v2/workspace_files/${args.file_id}`);
68698
68796
  if (file2.file_type !== "invoice") {
68699
68797
  throw new Error(
68700
68798
  `File ${args.file_id} is not an invoice (file_type=${file2.file_type}). Only invoices can be paid.`
@@ -68706,7 +68804,8 @@ async function payInvoice(args) {
68706
68804
  Re-run pay_invoice with { confirm: true } to proceed.`
68707
68805
  );
68708
68806
  }
68709
- const url4 = `${client.scope.portalOrigin}/app/workspace_file/${file2._id}/invoice`;
68807
+ vendorPortalSubdomain(client.scope.portalOrigin);
68808
+ const url4 = `${client.scope.portalOrigin}/app/workspace_file/${encodeURIComponent(String(file2._id))}/invoice`;
68710
68809
  const pendingNote = file2.has_pending_payment ? "\n\nNote: this invoice already has a pending payment \u2014 check the status before re-paying." : "";
68711
68810
  return rawTextResult(
68712
68811
  `HoneyBook's payment flow requires browser-side card/SCA handling that this MCP cannot replay headlessly yet.
@@ -68804,7 +68903,7 @@ var PROJECT_VIEWS = ["compact", "raw"];
68804
68903
  async function getProject(args) {
68805
68904
  const view = resolveView(args.view, PROJECT_VIEWS);
68806
68905
  const client = await getActiveClient(args.origin);
68807
- const res = await client.request("GET", `/api/v2/events/${args.project_id}/details`);
68906
+ const res = await client.request("GET", apiPath`/api/v2/events/${args.project_id}/details`);
68808
68907
  return viewResult(view, view === "raw" ? res : summarizeProject(res));
68809
68908
  }
68810
68909
  function registerProjectTools(server) {
@@ -68856,7 +68955,7 @@ function arr(o, k) {
68856
68955
  return Array.isArray(v) ? v : [];
68857
68956
  }
68858
68957
  async function fetchWorkspaceFeed(client, workspaceId) {
68859
- const res = await client.request("GET", `/api/v2/workspaces/${workspaceId}/feed`);
68958
+ const res = await client.request("GET", apiPath`/api/v2/workspaces/${workspaceId}/feed`);
68860
68959
  const feed = obj(res, "feed");
68861
68960
  const users = {};
68862
68961
  const feedUsers = obj(feed, "feed_users") ?? {};
@@ -69068,6 +69167,26 @@ var PENDING_TASK_STATE = {
69068
69167
  Aborted: 3
69069
69168
  };
69070
69169
  var pendingTaskPolling = { intervalMs: 1e3, maxPolls: 60 };
69170
+ var PendingTaskTimeoutError = class extends Error {
69171
+ /** Structural marker, so the predicate survives a duplicated module copy. */
69172
+ pendingTaskTimeout = true;
69173
+ taskId;
69174
+ taskType;
69175
+ /** The last `pending_task_state_cd` seen (Pending or Started). */
69176
+ lastState;
69177
+ constructor(taskId, taskType, lastState, polls) {
69178
+ super(
69179
+ `HoneyBook task ${taskId} ("${taskType}") timed out after ${polls} polls without finishing. It was not cancelled and may still complete.`
69180
+ );
69181
+ this.name = "PendingTaskTimeoutError";
69182
+ this.taskId = taskId;
69183
+ this.taskType = taskType;
69184
+ this.lastState = lastState;
69185
+ }
69186
+ };
69187
+ function isPendingTaskTimeoutError(err) {
69188
+ return err instanceof PendingTaskTimeoutError || typeof err === "object" && err !== null && err.pendingTaskTimeout === true;
69189
+ }
69071
69190
  async function runClientPendingTask(client, taskType, taskData) {
69072
69191
  const created = await client.request(
69073
69192
  "POST",
@@ -69080,9 +69199,11 @@ async function runClientPendingTask(client, taskType, taskData) {
69080
69199
  `HoneyBook accepted the "${taskType}" task but returned no task_id: ${JSON.stringify(created)}`
69081
69200
  );
69082
69201
  }
69202
+ let lastState = PENDING_TASK_STATE.Pending;
69083
69203
  for (let poll = 0; poll < pendingTaskPolling.maxPolls; poll++) {
69204
+ throwIfCancelled();
69084
69205
  if (poll > 0 && pendingTaskPolling.intervalMs > 0) {
69085
- await new Promise((r) => setTimeout(r, pendingTaskPolling.intervalMs));
69206
+ await cancellableDelay(pendingTaskPolling.intervalMs);
69086
69207
  }
69087
69208
  const raw = await client.request(
69088
69209
  "GET",
@@ -69099,14 +69220,15 @@ async function runClientPendingTask(client, taskType, taskData) {
69099
69220
  if (state === PENDING_TASK_STATE.Finished) {
69100
69221
  return { task_id: taskId, result: task.pending_task_result };
69101
69222
  }
69102
- if (state === PENDING_TASK_STATE.Pending || state === PENDING_TASK_STATE.Started) continue;
69223
+ if (state === PENDING_TASK_STATE.Pending || state === PENDING_TASK_STATE.Started) {
69224
+ lastState = state;
69225
+ continue;
69226
+ }
69103
69227
  throw new Error(
69104
69228
  `HoneyBook task ${taskId} ("${taskType}") failed: ${task.pending_task_error_message || `state ${state}`}`
69105
69229
  );
69106
69230
  }
69107
- throw new Error(
69108
- `HoneyBook task ${taskId} ("${taskType}") timed out after ${pendingTaskPolling.maxPolls} polls without finishing.`
69109
- );
69231
+ throw new PendingTaskTimeoutError(taskId, taskType, lastState, pendingTaskPolling.maxPolls);
69110
69232
  }
69111
69233
 
69112
69234
  // src/tools/messages.ts
@@ -69221,11 +69343,22 @@ Re-run send_message with { confirm: true } to send it.`
69221
69343
  flow_attachments: []
69222
69344
  };
69223
69345
  if (replyTo) taskData.feed_to_reply_id = replyTo._id;
69224
- const { task_id, result } = await runClientPendingTask(
69225
- client,
69226
- "send_workspace_message",
69227
- taskData
69228
- );
69346
+ let outcome;
69347
+ try {
69348
+ outcome = await runClientPendingTask(client, "send_workspace_message", taskData);
69349
+ } catch (err) {
69350
+ if (!isPendingTaskTimeoutError(err)) throw err;
69351
+ return minifiedResult({
69352
+ status: "pending",
69353
+ task_id: err.taskId,
69354
+ workspace_id: args.workspace_id,
69355
+ subject,
69356
+ to: recipients.map((u) => u.name),
69357
+ reply_to: replyTo ? replyTo._id : null,
69358
+ warning: "HoneyBook had not finished sending when polling stopped. The task was not cancelled and the message may still be delivered. Check list_messages for this workspace before resending \u2014 do NOT re-run send_message until you have confirmed it did not go out."
69359
+ });
69360
+ }
69361
+ const { task_id, result } = outcome;
69229
69362
  const sendResults = result?.workspaces?.result?.send_results;
69230
69363
  if (result?.workspaces?.result?.failed) {
69231
69364
  const failed = (sendResults ?? []).filter((r) => r.success === false);
@@ -69245,7 +69378,7 @@ Re-run send_message with { confirm: true } to send it.`
69245
69378
  }
69246
69379
  async function markMessagesSeen(args) {
69247
69380
  const client = await getActiveClient(args.origin);
69248
- await client.request("PUT", `/api/v2/workspaces/${args.workspace_id}/feed_items/seen`, {
69381
+ await client.request("PUT", apiPath`/api/v2/workspaces/${args.workspace_id}/feed_items/seen`, {
69249
69382
  item_ids: args.message_ids
69250
69383
  });
69251
69384
  return minifiedResult({ workspace_id: args.workspace_id, marked: args.message_ids });
@@ -69284,7 +69417,7 @@ function registerMessageTools(server) {
69284
69417
  server.registerTool(
69285
69418
  "send_message",
69286
69419
  {
69287
- description: "Send a message to the vendor (and the other members of the workspace) through the HoneyBook portal, exactly as the Activity tab composer does. HoneyBook emails it to every recipient. Pass reply_to_message_id to reply in-thread (the subject is inherited). Requires confirm:true.",
69420
+ description: 'Send a message to the vendor (and the other members of the workspace) through the HoneyBook portal, exactly as the Activity tab composer does. HoneyBook emails it to every recipient. Pass reply_to_message_id to reply in-thread (the subject is inherited). Requires confirm:true. If HoneyBook has not finished sending within about a minute the result has status "pending" and a task_id: the message may still be delivered, so check list_messages before resending.',
69288
69421
  inputSchema: external_exports.object({
69289
69422
  workspace_id: external_exports.string().describe(WORKSPACE_DESC),
69290
69423
  body: external_exports.string().describe("Message text. Plain text is sent as-is (line breaks preserved); HTML is passed through."),
@@ -69376,7 +69509,7 @@ async function listTasks(args) {
69376
69509
  const perPage = args.per_page ?? 50;
69377
69510
  const currDate = args.curr_date ?? today();
69378
69511
  const apiDate = encodeURIComponent(toApiDate(currDate));
69379
- const base = `/api/v2/tasks/workspaces/${args.workspace_id}`;
69512
+ const base = apiPath`/api/v2/tasks/workspaces/${args.workspace_id}`;
69380
69513
  const tasks = await client.request(
69381
69514
  "GET",
69382
69515
  `${base}?page=${page}&perPage=${perPage}&sort_by=due_date&sort_desc=false&curr_date=${apiDate}`
@@ -69384,7 +69517,7 @@ async function listTasks(args) {
69384
69517
  const counts = await client.request("GET", `${base}/counts?curr_date=${apiDate}`);
69385
69518
  const groups = await client.request(
69386
69519
  "GET",
69387
- `/api/v2/workspaces/${args.workspace_id}/taskgroup`
69520
+ apiPath`/api/v2/workspaces/${args.workspace_id}/taskgroup`
69388
69521
  );
69389
69522
  return minifiedResult({
69390
69523
  workspace_id: args.workspace_id,
@@ -69421,7 +69554,7 @@ async function listNotes(args) {
69421
69554
  const client = await getActiveClient(args.origin);
69422
69555
  const notes = await client.request(
69423
69556
  "GET",
69424
- `/api/v2/notes/workspace/${args.workspace_id}`
69557
+ apiPath`/api/v2/notes/workspace/${args.workspace_id}`
69425
69558
  );
69426
69559
  return minifiedResult({ workspace_id: args.workspace_id, notes: notes ?? [] });
69427
69560
  }
@@ -69447,7 +69580,7 @@ async function listAttachments(args) {
69447
69580
  const client = await getActiveClient(args.origin);
69448
69581
  const res = await client.request(
69449
69582
  "GET",
69450
- `/api/v2/workspaces/${args.workspace_id}/attachments`
69583
+ apiPath`/api/v2/workspaces/${args.workspace_id}/attachments`
69451
69584
  );
69452
69585
  const a = res?.attachments ?? {};
69453
69586
  return minifiedResult({
@@ -69482,7 +69615,7 @@ async function listPayments(args) {
69482
69615
  const client = await getActiveClient(args.origin);
69483
69616
  const res = await client.request(
69484
69617
  "GET",
69485
- `/api/v2/workspaces/${args.workspace_id}/payments`
69618
+ apiPath`/api/v2/workspaces/${args.workspace_id}/payments`
69486
69619
  );
69487
69620
  const totals = {};
69488
69621
  const files = (res?.workspace_files ?? []).map((f) => {
@@ -69542,7 +69675,7 @@ var __dirname = dirname2(fileURLToPath(import.meta.url));
69542
69675
  await loadDotenvSafely({ path: join6(__dirname, "..", ".env"), override: false });
69543
69676
  await runMcp({
69544
69677
  name: "honeybook-mcp",
69545
- version: "1.1.3",
69678
+ version: "1.1.4",
69546
69679
  // x-release-please-version
69547
69680
  tools: [
69548
69681
  registerSessionTools,
package/dist/client.js CHANGED
@@ -1,21 +1,107 @@
1
1
  import { sessionStore } from './sessions.js';
2
2
  import { flowStore } from './flows.js';
3
- import { readEnvVar, formatApiError } from '@chrischall/mcp-utils';
3
+ import { readEnvVar, formatApiError, withAmbientCancellation, currentCallSignal } from '@chrischall/mcp-utils';
4
4
  export const API_BASE = 'https://api.honeybook.com';
5
5
  // Cache keyed by portalOrigin
6
6
  const clientCache = new Map();
7
7
  export const moduleState = { apiVersionPromise: null };
8
+ /**
9
+ * Per-request bound on every HoneyBook fetch. Mutable so tests can shrink it.
10
+ *
11
+ * Without one a stalled api.honeybook.com connection hung the tool call until
12
+ * the client gave up — and because `getActiveClient` memoizes the `/api/gon`
13
+ * promise, a hung version fetch hung every later call in the process
14
+ * (fleet-audit#137).
15
+ */
16
+ export const httpTimeouts = { requestMs: 30_000 };
17
+ /**
18
+ * The signal for one HoneyBook fetch: the per-request timeout, combined with
19
+ * the running tool call's cancellation (made ambient by mcp-utils' tool
20
+ * wrapper) so a caller that goes away stops the request too.
21
+ */
22
+ export function hbRequestSignal() {
23
+ return withAmbientCancellation(AbortSignal.timeout(httpTimeouts.requestMs));
24
+ }
25
+ /**
26
+ * Run one fetch (and its body read) under {@link hbRequestSignal}, turning the
27
+ * timeout's bare `TimeoutError` into a message that says what happened. A
28
+ * caller's own cancellation propagates with its own reason.
29
+ */
30
+ export async function withHbTimeout(what, fn) {
31
+ const signal = hbRequestSignal();
32
+ try {
33
+ return await fn(signal);
34
+ }
35
+ catch (err) {
36
+ if (err?.name === 'TimeoutError' && !currentCallSignal()?.aborted) {
37
+ throw new Error(`HoneyBook did not respond within ${httpTimeouts.requestMs / 1000}s (${what}).`);
38
+ }
39
+ throw err;
40
+ }
41
+ }
42
+ /** A delay that ends early, rejecting, when the tool call is cancelled. */
43
+ export function cancellableDelay(ms) {
44
+ const signal = currentCallSignal();
45
+ return new Promise((resolve, reject) => {
46
+ if (signal?.aborted)
47
+ return reject(signal.reason);
48
+ const onAbort = () => {
49
+ clearTimeout(timer);
50
+ reject(signal.reason);
51
+ };
52
+ const timer = setTimeout(() => {
53
+ signal?.removeEventListener('abort', onAbort);
54
+ resolve();
55
+ }, ms);
56
+ signal?.addEventListener('abort', onAbort, { once: true });
57
+ });
58
+ }
8
59
  export async function fetchApiVersion() {
9
60
  const override = readEnvVar('HONEYBOOK_API_VERSION');
10
61
  if (override)
11
62
  return Number(override);
12
- const res = await fetch(`${API_BASE}/api/gon?callback=parseGon`);
13
- const text = await res.text();
63
+ const text = await withHbTimeout('GET /api/gon', async (signal) => {
64
+ const res = await fetch(`${API_BASE}/api/gon?callback=parseGon`, { signal });
65
+ return res.text();
66
+ });
14
67
  const m = /"api_version":\s*(\d+)/.exec(text);
15
68
  if (!m)
16
69
  throw new Error(`Could not parse api_version from /api/gon response: ${text.slice(0, 200)}`);
17
70
  return Number(m[1]);
18
71
  }
72
+ /**
73
+ * Build an API path from a template, encoding every interpolated value as ONE
74
+ * path segment.
75
+ *
76
+ * Tool ids come from the model, and the model reads vendor-written text. A raw
77
+ * `workspaces/${id}/feed_items/seen` with `id = "x/../../users/me/foo?"` is
78
+ * normalized by the URL parser into a request to a different endpoint under the
79
+ * user's token (fleet-audit#138). `encodeURIComponent` neutralizes `/`, `?` and
80
+ * `#`, but not a bare `.` or `..`, so those — and the empty id — are refused.
81
+ */
82
+ export function apiPath(strings, ...values) {
83
+ let out = strings[0] ?? '';
84
+ values.forEach((value, i) => {
85
+ const raw = String(value);
86
+ if (raw === '' || raw === '.' || raw === '..') {
87
+ throw new Error(`${JSON.stringify(raw)} is not a valid HoneyBook id.`);
88
+ }
89
+ out += encodeURIComponent(raw) + (strings[i + 1] ?? '');
90
+ });
91
+ return out;
92
+ }
93
+ /**
94
+ * Last line of defence behind {@link apiPath}: refuse any path the URL parser
95
+ * would rewrite — a `.`/`..` segment (percent-encoded or not) or a backslash,
96
+ * which WHATWG treats as `/` for https URLs.
97
+ */
98
+ function assertNoPathTraversal(path) {
99
+ const pathname = path.split(/[?#]/, 1)[0] ?? '';
100
+ const dotSegment = /^(?:\.|%2e){1,2}$/i;
101
+ if (pathname.includes('\\') || pathname.split('/').some((seg) => dotSegment.test(seg))) {
102
+ throw new Error(`Refusing HoneyBook API path with a path traversal segment: ${path}`);
103
+ }
104
+ }
19
105
  /**
20
106
  * An unsuccessful HoneyBook response, carrying the STATUS a caller has to
21
107
  * branch on.
@@ -55,38 +141,53 @@ export function isHoneyBookApiError(err) {
55
141
  * One authenticated request to api.honeybook.com, shared by every credential
56
142
  * kind. See {@link HbApiCaller} for why the identity is a parameter.
57
143
  */
58
- export async function hbApiRequest(caller, method, path, body, isVersionRetry = false, isRateRetry = false) {
144
+ export async function hbApiRequest(caller, method, path, body, isVersionRetry = false, isRateRetry = false,
145
+ /**
146
+ * One id per LOGICAL request, reused by the 429 and version retries below so
147
+ * HoneyBook's own duplicate-call prevention can recognise a replay. A fresh
148
+ * id per attempt would let a retried POST create a second pending task.
149
+ */
150
+ dedupeId = crypto.randomUUID()) {
151
+ assertNoPathTraversal(path);
59
152
  const headers = {
60
153
  accept: 'application/json, text/plain, */*',
61
154
  'hb-api-client-version': String(caller.getApiVersion()),
62
- 'hb-api-duplicate-calls-prevention-uuid': crypto.randomUUID(),
155
+ 'hb-api-duplicate-calls-prevention-uuid': dedupeId,
63
156
  ...caller.authHeaders(),
64
157
  };
65
158
  if (body !== undefined)
66
159
  headers['content-type'] = 'application/json';
67
- const response = await fetch(`${API_BASE}${path}`, {
68
- method,
69
- headers,
70
- ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
160
+ // The status and the body are read under one timeout, so a server that sends
161
+ // headers and then stalls mid-body cannot hang the call either.
162
+ const { status, ok, text } = await withHbTimeout(`${method} ${path}`, async (signal) => {
163
+ const response = await fetch(`${API_BASE}${path}`, {
164
+ method,
165
+ headers,
166
+ signal,
167
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
168
+ });
169
+ if (response.status === 401 || response.status === 429) {
170
+ return { status: response.status, ok: false, text: '' };
171
+ }
172
+ return { status: response.status, ok: response.ok, text: await response.text() };
71
173
  });
72
- if (response.status === 401)
174
+ if (status === 401)
73
175
  throw caller.authExpiredError();
74
- if (response.status === 429) {
176
+ if (status === 429) {
75
177
  if (!isRateRetry) {
76
- await new Promise((r) => setTimeout(r, 2000));
77
- return hbApiRequest(caller, method, path, body, isVersionRetry, true);
178
+ await cancellableDelay(2000);
179
+ return hbApiRequest(caller, method, path, body, isVersionRetry, true, dedupeId);
78
180
  }
79
181
  throw new Error('Rate limited by HoneyBook API');
80
182
  }
81
- if (!response.ok) {
82
- const text = await response.text();
183
+ if (!ok) {
83
184
  // A revoked or stale credential does NOT come back as 401 — the API answers
84
185
  // 404 with an HBUnauthorizedError body. Without this, an expired session
85
186
  // surfaced as an opaque "HoneyBook error 404" instead of the re-capture
86
187
  // instruction. Gate on the body so a genuinely missing resource stays a
87
188
  // plain 404. Verified live for the flow path too: an unauthenticated GET of
88
189
  // /api/v2/flow/<id>/active answers exactly this shape.
89
- if (response.status === 404 && text.includes('HBUnauthorizedError')) {
190
+ if (status === 404 && text.includes('HBUnauthorizedError')) {
90
191
  throw caller.authExpiredError();
91
192
  }
92
193
  if (text.includes('HBWrongAPIVersionError') && !isVersionRetry) {
@@ -99,11 +200,10 @@ export async function hbApiRequest(caller, method, path, body, isVersionRetry =
99
200
  catch {
100
201
  caller.setApiVersion(await fetchApiVersion());
101
202
  }
102
- return hbApiRequest(caller, method, path, body, true, isRateRetry);
203
+ return hbApiRequest(caller, method, path, body, true, isRateRetry, dedupeId);
103
204
  }
104
- throw new HoneyBookApiError(formatApiError(response.status, method, path, text, { service: 'HoneyBook' }), { status: response.status, method, path, body: text });
205
+ throw new HoneyBookApiError(formatApiError(status, method, path, text, { service: 'HoneyBook' }), { status, method, path, body: text });
105
206
  }
106
- const text = await response.text();
107
207
  return (text ? JSON.parse(text) : null);
108
208
  }
109
209
  export class HoneyBookClient {
package/dist/feed.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { apiPath } from './client.js';
1
2
  /**
2
3
  * The feed item types that are messages a person reads, as opposed to
3
4
  * activity. `workspace_file_email` is the email that delivers a file
@@ -19,7 +20,7 @@ function arr(o, k) {
19
20
  return Array.isArray(v) ? v : [];
20
21
  }
21
22
  export async function fetchWorkspaceFeed(client, workspaceId) {
22
- const res = await client.request('GET', `/api/v2/workspaces/${workspaceId}/feed`);
23
+ const res = await client.request('GET', apiPath `/api/v2/workspaces/${workspaceId}/feed`);
23
24
  const feed = obj(res, 'feed');
24
25
  const users = {};
25
26
  const feedUsers = obj(feed, 'feed_users') ?? {};
package/dist/flow-auth.js CHANGED
@@ -20,6 +20,7 @@ import { bridgeErrorInfo } from '@chrischall/mcp-utils/fetchproxy';
20
20
  import { parseBoolEnv } from '@chrischall/mcp-utils';
21
21
  import pkg from '../package.json' with { type: 'json' };
22
22
  import { flowStorageKey, flowStore, parseFlowLink } from './flows.js';
23
+ import { vendorPortalSubdomain } from './sessions.js';
23
24
  /** True if the user has explicitly disabled the fetchproxy capture path. */
24
25
  function fetchproxyDisabled() {
25
26
  return parseBoolEnv('HONEYBOOK_DISABLE_FETCHPROXY');
@@ -36,6 +37,8 @@ export async function captureFlowCredentialViaFetchproxy(opts) {
36
37
  // Parse BEFORE the disabled check and before the bridge opens: a portal link
37
38
  // handed to this tool is a mistake we can name without touching the browser.
38
39
  const link = parseFlowLink(opts.flowLinkUrl);
40
+ // Same host rule, and the same tab pinning, as a portal capture (fleet-audit#139).
41
+ const vendorSubdomain = vendorPortalSubdomain(link.portalOrigin);
39
42
  if (fetchproxyDisabled()) {
40
43
  throw new Error('HoneyBook flow auth: fetchproxy capture is disabled by HONEYBOOK_DISABLE_FETCHPROXY. ' +
41
44
  'Unset that env var to enable credential capture via the browser extension.');
@@ -48,6 +51,7 @@ export async function captureFlowCredentialViaFetchproxy(opts) {
48
51
  version: pkg.version,
49
52
  domains: ['honeybook.com', 'hbportal.co'],
50
53
  storageDomain: 'hbportal.co',
54
+ storageSubdomain: vendorSubdomain,
51
55
  declare: {
52
56
  cookies: [],
53
57
  localStorage: [],
@@ -24,7 +24,7 @@
24
24
  // email header did not appear because the measured blob had no `email` in it at
25
25
  // all (only `_id` and `hash`); `getHeaders()` does send it when there is one, so
26
26
  // it stays conditional here rather than being deleted on one observation.
27
- import { API_BASE, fetchApiVersion, hbApiRequest, isHoneyBookApiError, moduleState, } from './client.js';
27
+ import { API_BASE, fetchApiVersion, hbApiRequest, isHoneyBookApiError, moduleState, withHbTimeout, } from './client.js';
28
28
  import { flowStore } from './flows.js';
29
29
  /**
30
30
  * The one "no flow credential yet" message. Shared the way
@@ -155,11 +155,15 @@ export async function fetchFlowMinimal(flowId, opts) {
155
155
  query.set('user_id', opts.userId);
156
156
  const suffix = query.size > 0 ? `?${query}` : '';
157
157
  const url = `${API_BASE}/api/v2/flow/${encodeURIComponent(flowId)}/minimal${suffix}`;
158
- const response = await fetch(url, {
159
- headers: {
160
- accept: 'application/json, text/plain, */*',
161
- 'hb-api-client-version': String(opts.apiVersion),
162
- },
158
+ const { response, body } = await withHbTimeout(`GET /api/v2/flow/${flowId}/minimal`, async (signal) => {
159
+ const response = await fetch(url, {
160
+ signal,
161
+ headers: {
162
+ accept: 'application/json, text/plain, */*',
163
+ 'hb-api-client-version': String(opts.apiVersion),
164
+ },
165
+ });
166
+ return { response, body: await response.text().catch(() => '') };
163
167
  });
164
168
  if (!response.ok) {
165
169
  // The body, and a cause keyed on the STATUS — not one blanket "HoneyBook is
@@ -168,7 +172,6 @@ export async function fetchFlowMinimal(flowId, opts) {
168
172
  // or was never there, and an HBWrongAPIVersionError is this package's
169
173
  // pinned `hb-api-client-version` having rotted, which is ours to fix and
170
174
  // nothing to do with HoneyBook being down.
171
- const body = await response.text().catch(() => '');
172
175
  const detail = body.slice(0, 300);
173
176
  const cause = response.status === 404
174
177
  ? `no flow ${flowId} — it may have been deleted, or the id is wrong`
@@ -179,7 +182,7 @@ export async function fetchFlowMinimal(flowId, opts) {
179
182
  `It is where the context id (ctxc) the questionnaire read sends comes from.` +
180
183
  (detail ? ` Response: ${detail}` : ''));
181
184
  }
182
- return (await response.json());
185
+ return JSON.parse(body);
183
186
  }
184
187
  /**
185
188
  * The `ctxc` value: the vendor's company id.
package/dist/index.js CHANGED
@@ -20,7 +20,7 @@ import { registerAttachmentTools } from './tools/attachments.js';
20
20
  import { registerPaymentTools } from './tools/payments.js';
21
21
  await runMcp({
22
22
  name: 'honeybook-mcp',
23
- version: '1.1.3', // x-release-please-version
23
+ version: '1.1.4', // x-release-please-version
24
24
  tools: [
25
25
  registerSessionTools,
26
26
  registerFlowTools,
@@ -1,3 +1,5 @@
1
+ import { throwIfCancelled } from '@chrischall/mcp-utils';
2
+ import { cancellableDelay } from './client.js';
1
3
  /**
2
4
  * HoneyBook's "client pending task" protocol.
3
5
  *
@@ -27,15 +29,47 @@ export const PENDING_TASK_STATE = {
27
29
  * composer's spinner.
28
30
  */
29
31
  export const pendingTaskPolling = { intervalMs: 1000, maxPolls: 60 };
32
+ /**
33
+ * The task was still Pending/Started when polling gave up. It was NOT
34
+ * cancelled server-side and may still complete — for `send_workspace_message`
35
+ * that means the email may still go out, so a caller must not present this as
36
+ * a plain failure that invites a resend.
37
+ */
38
+ export class PendingTaskTimeoutError extends Error {
39
+ /** Structural marker, so the predicate survives a duplicated module copy. */
40
+ pendingTaskTimeout = true;
41
+ taskId;
42
+ taskType;
43
+ /** The last `pending_task_state_cd` seen (Pending or Started). */
44
+ lastState;
45
+ constructor(taskId, taskType, lastState, polls) {
46
+ super(`HoneyBook task ${taskId} ("${taskType}") timed out after ${polls} polls without finishing. ` +
47
+ 'It was not cancelled and may still complete.');
48
+ this.name = 'PendingTaskTimeoutError';
49
+ this.taskId = taskId;
50
+ this.taskType = taskType;
51
+ this.lastState = lastState;
52
+ }
53
+ }
54
+ export function isPendingTaskTimeoutError(err) {
55
+ return (err instanceof PendingTaskTimeoutError ||
56
+ (typeof err === 'object' &&
57
+ err !== null &&
58
+ err.pendingTaskTimeout === true));
59
+ }
30
60
  export async function runClientPendingTask(client, taskType, taskData) {
31
61
  const created = await client.request('POST', '/api/v2/client_pending_task', { task_type: taskType, task_data: taskData });
32
62
  const taskId = created?.task_id;
33
63
  if (!taskId) {
34
64
  throw new Error(`HoneyBook accepted the "${taskType}" task but returned no task_id: ${JSON.stringify(created)}`);
35
65
  }
66
+ let lastState = PENDING_TASK_STATE.Pending;
36
67
  for (let poll = 0; poll < pendingTaskPolling.maxPolls; poll++) {
68
+ // A caller that has gone stops the polling (fleet-audit#137). The task
69
+ // itself is not cancelled — HoneyBook offers no cancel — only our wait.
70
+ throwIfCancelled();
37
71
  if (poll > 0 && pendingTaskPolling.intervalMs > 0) {
38
- await new Promise((r) => setTimeout(r, pendingTaskPolling.intervalMs));
72
+ await cancellableDelay(pendingTaskPolling.intervalMs);
39
73
  }
40
74
  const raw = await client.request('GET', `/api/v2/client_pending_tasks?task_ids[]=${encodeURIComponent(taskId)}`);
41
75
  const tasks = Array.isArray(raw) ? raw : raw ? [raw] : [];
@@ -49,9 +83,11 @@ export async function runClientPendingTask(client, taskType, taskData) {
49
83
  if (state === PENDING_TASK_STATE.Finished) {
50
84
  return { task_id: taskId, result: task.pending_task_result };
51
85
  }
52
- if (state === PENDING_TASK_STATE.Pending || state === PENDING_TASK_STATE.Started)
86
+ if (state === PENDING_TASK_STATE.Pending || state === PENDING_TASK_STATE.Started) {
87
+ lastState = state;
53
88
  continue;
89
+ }
54
90
  throw new Error(`HoneyBook task ${taskId} ("${taskType}") failed: ${task.pending_task_error_message || `state ${state}`}`);
55
91
  }
56
- throw new Error(`HoneyBook task ${taskId} ("${taskType}") timed out after ${pendingTaskPolling.maxPolls} polls without finishing.`);
92
+ throw new PendingTaskTimeoutError(taskId, taskType, lastState, pendingTaskPolling.maxPolls);
57
93
  }
package/dist/sessions.js CHANGED
@@ -26,3 +26,32 @@ export const sessionStore = new SessionStore({
26
26
  keyOf: (session) => session.portalOrigin,
27
27
  normalizeKey: normalizeOrigin,
28
28
  });
29
+ /**
30
+ * The vendor label of a HoneyBook client-portal origin — `acme` for
31
+ * `https://acme.hbportal.co` — or a refusal for anything else.
32
+ *
33
+ * Captures read the signed-in tab's storage, so the origin a session is
34
+ * labelled with must be the tab it was read from. Only a single-label
35
+ * `https://<vendor>.hbportal.co` (default port) qualifies: that is the one
36
+ * shape the fetchproxy read can be pinned to (`storageSubdomain`), and the one
37
+ * whose deep links (`pay_invoice`, `sign_contract`) are safe to hand the user.
38
+ * Any other host would store a real token under a name that is not where it
39
+ * came from, and turn those links into a phishing primitive (fleet-audit#139).
40
+ */
41
+ export function vendorPortalSubdomain(input) {
42
+ let url = null;
43
+ try {
44
+ url = new URL(input);
45
+ }
46
+ catch {
47
+ url = null;
48
+ }
49
+ const match = url && url.protocol === 'https:' && url.port === ''
50
+ ? /^([a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\.hbportal\.co$/.exec(url.hostname)
51
+ : null;
52
+ if (!match) {
53
+ throw new Error(`"${input}" is not a HoneyBook vendor portal link. Expected https://<vendor>.hbportal.co/… ` +
54
+ '(the link in the vendor\'s HoneyBook email).');
55
+ }
56
+ return match[1];
57
+ }
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { minifiedResult, schemaOrigin } from '@chrischall/mcp-utils';
3
- import { getActiveClient } from '../client.js';
3
+ import { apiPath, getActiveClient } from '../client.js';
4
4
  /**
5
5
  * The Files tab's "attachments" bucket: loose images, files and bookmarks
6
6
  * shared in the workspace. Contracts, invoices and proposals are NOT here —
@@ -8,7 +8,7 @@ import { getActiveClient } from '../client.js';
8
8
  */
9
9
  export async function listAttachments(args) {
10
10
  const client = await getActiveClient(args.origin);
11
- const res = await client.request('GET', `/api/v2/workspaces/${args.workspace_id}/attachments`);
11
+ const res = await client.request('GET', apiPath `/api/v2/workspaces/${args.workspace_id}/attachments`);
12
12
  const a = res?.attachments ?? {};
13
13
  return minifiedResult({
14
14
  workspace_id: args.workspace_id,
@@ -1,9 +1,10 @@
1
1
  import { z } from 'zod';
2
2
  import { rawTextResult, schemaOrigin, schemaConfirm } from '@chrischall/mcp-utils';
3
- import { getActiveClient } from '../client.js';
3
+ import { apiPath, getActiveClient } from '../client.js';
4
+ import { vendorPortalSubdomain } from '../sessions.js';
4
5
  export async function signContract(args) {
5
6
  const client = await getActiveClient(args.origin);
6
- const file = await client.request('GET', `/api/v2/workspace_files/${args.file_id}`);
7
+ const file = await client.request('GET', apiPath `/api/v2/workspace_files/${args.file_id}`);
7
8
  if (file.file_type !== 'agreement') {
8
9
  throw new Error(`File ${args.file_id} is not an agreement (file_type=${file.file_type}). Only contracts can be signed.`);
9
10
  }
@@ -14,7 +15,10 @@ export async function signContract(args) {
14
15
  return rawTextResult(`About to sign "${file.file_title}" (${file.status_name || 'not signed'}).\n` +
15
16
  `Re-run sign_contract with { confirm: true } to proceed.`);
16
17
  }
17
- const url = `${client.scope.portalOrigin}/app/workspace_file/${file._id}/agreement`;
18
+ // Re-checked here, not only at capture: a sessions.json written before the
19
+ // host rule existed can still hold a foreign origin (fleet-audit#139).
20
+ vendorPortalSubdomain(client.scope.portalOrigin);
21
+ const url = `${client.scope.portalOrigin}/app/workspace_file/${encodeURIComponent(String(file._id))}/agreement`;
18
22
  return rawTextResult(`HoneyBook's signing flow requires a browser signature that this MCP cannot replay headlessly yet.\n\n` +
19
23
  `Open this link to sign the contract in your HoneyBook portal:\n\n${url}\n\n` +
20
24
  `(If you'd like the MCP to sign directly in a future version, sign one contract while running a network capture — see docs/risks.md.)`);
@@ -1,5 +1,5 @@
1
1
  import { registerCredentialHealthcheckTool } from '@chrischall/mcp-utils/healthcheck';
2
- import { getActiveClient, isNoPortalSessionError, noPortalSessionError } from '../client.js';
2
+ import { apiPath, getActiveClient, isNoPortalSessionError, noPortalSessionError } from '../client.js';
3
3
  import { sessionStore } from '../sessions.js';
4
4
  import { flowStore } from '../flows.js';
5
5
  /**
@@ -45,7 +45,7 @@ export function registerHealthcheckTools(server) {
45
45
  },
46
46
  probeFn: async () => {
47
47
  const client = await getActiveClient();
48
- return client.request('GET', `/api/v2/users/${client.scope.userId}/payment_methods`);
48
+ return client.request('GET', apiPath `/api/v2/users/${client.scope.userId}/payment_methods`);
49
49
  },
50
50
  classifyThrown: (err) => {
51
51
  const msg = err instanceof Error ? err.message : String(err);
@@ -1,9 +1,10 @@
1
1
  import { z } from 'zod';
2
2
  import { rawTextResult, schemaOrigin, schemaConfirm } from '@chrischall/mcp-utils';
3
- import { getActiveClient } from '../client.js';
3
+ import { apiPath, getActiveClient } from '../client.js';
4
+ import { vendorPortalSubdomain } from '../sessions.js';
4
5
  export async function payInvoice(args) {
5
6
  const client = await getActiveClient(args.origin);
6
- const file = await client.request('GET', `/api/v2/workspace_files/${args.file_id}`);
7
+ const file = await client.request('GET', apiPath `/api/v2/workspace_files/${args.file_id}`);
7
8
  if (file.file_type !== 'invoice') {
8
9
  throw new Error(`File ${args.file_id} is not an invoice (file_type=${file.file_type}). Only invoices can be paid.`);
9
10
  }
@@ -11,7 +12,10 @@ export async function payInvoice(args) {
11
12
  return rawTextResult(`About to pay "${file.file_title}" (${file.status_name || 'open'}).\n` +
12
13
  `Re-run pay_invoice with { confirm: true } to proceed.`);
13
14
  }
14
- const url = `${client.scope.portalOrigin}/app/workspace_file/${file._id}/invoice`;
15
+ // Re-checked here, not only at capture: a sessions.json written before the
16
+ // host rule existed can still hold a foreign origin (fleet-audit#139).
17
+ vendorPortalSubdomain(client.scope.portalOrigin);
18
+ const url = `${client.scope.portalOrigin}/app/workspace_file/${encodeURIComponent(String(file._id))}/invoice`;
15
19
  const pendingNote = file.has_pending_payment
16
20
  ? '\n\nNote: this invoice already has a pending payment — check the status before re-paying.'
17
21
  : '';
@@ -1,8 +1,8 @@
1
1
  import { z } from 'zod';
2
2
  import { minifiedResult, rawTextResult, schemaConfirm, schemaOrigin } from '@chrischall/mcp-utils';
3
- import { getActiveClient } from '../client.js';
3
+ import { apiPath, getActiveClient } from '../client.js';
4
4
  import { fetchWorkspaceFeed, isMessageItem, itemDate, summarizeMessage, summarizeActivity, expandMessage, } from '../feed.js';
5
- import { runClientPendingTask } from '../pending-tasks.js';
5
+ import { runClientPendingTask, isPendingTaskTimeoutError } from '../pending-tasks.js';
6
6
  export const FEED_KINDS = ['messages', 'activity', 'all'];
7
7
  const ORIGIN_DESC = 'Portal origin (e.g. https://<vendor>.hbportal.co). Optional when only one session is active.';
8
8
  const WORKSPACE_DESC = 'The workspace _id (from list_projects, or .workspace._id on any workspace_file).';
@@ -120,7 +120,29 @@ export async function sendMessage(args) {
120
120
  };
121
121
  if (replyTo)
122
122
  taskData.feed_to_reply_id = replyTo._id;
123
- const { task_id, result } = await runClientPendingTask(client, 'send_workspace_message', taskData);
123
+ let outcome;
124
+ try {
125
+ outcome = await runClientPendingTask(client, 'send_workspace_message', taskData);
126
+ }
127
+ catch (err) {
128
+ // The task is still running server-side and may yet email every recipient.
129
+ // Reporting that as an error invites a resend, which creates a SECOND task
130
+ // (fleet-audit#136) — so it comes back as a non-error "pending" result.
131
+ if (!isPendingTaskTimeoutError(err))
132
+ throw err;
133
+ return minifiedResult({
134
+ status: 'pending',
135
+ task_id: err.taskId,
136
+ workspace_id: args.workspace_id,
137
+ subject,
138
+ to: recipients.map((u) => u.name),
139
+ reply_to: replyTo ? replyTo._id : null,
140
+ warning: 'HoneyBook had not finished sending when polling stopped. The task was not cancelled and the ' +
141
+ 'message may still be delivered. Check list_messages for this workspace before resending — ' +
142
+ 'do NOT re-run send_message until you have confirmed it did not go out.',
143
+ });
144
+ }
145
+ const { task_id, result } = outcome;
124
146
  const sendResults = result?.workspaces?.result?.send_results;
125
147
  if (result?.workspaces?.result?.failed) {
126
148
  const failed = (sendResults ?? []).filter((r) => r.success === false);
@@ -138,7 +160,7 @@ export async function sendMessage(args) {
138
160
  }
139
161
  export async function markMessagesSeen(args) {
140
162
  const client = await getActiveClient(args.origin);
141
- await client.request('PUT', `/api/v2/workspaces/${args.workspace_id}/feed_items/seen`, {
163
+ await client.request('PUT', apiPath `/api/v2/workspaces/${args.workspace_id}/feed_items/seen`, {
142
164
  item_ids: args.message_ids,
143
165
  });
144
166
  return minifiedResult({ workspace_id: args.workspace_id, marked: args.message_ids });
@@ -174,7 +196,9 @@ export function registerMessageTools(server) {
174
196
  server.registerTool('send_message', {
175
197
  description: 'Send a message to the vendor (and the other members of the workspace) through the HoneyBook portal, ' +
176
198
  'exactly as the Activity tab composer does. HoneyBook emails it to every recipient. ' +
177
- 'Pass reply_to_message_id to reply in-thread (the subject is inherited). Requires confirm:true.',
199
+ 'Pass reply_to_message_id to reply in-thread (the subject is inherited). Requires confirm:true. ' +
200
+ 'If HoneyBook has not finished sending within about a minute the result has status "pending" and a ' +
201
+ 'task_id: the message may still be delivered, so check list_messages before resending.',
178
202
  inputSchema: z.object({
179
203
  workspace_id: z.string().describe(WORKSPACE_DESC),
180
204
  body: z
@@ -1,9 +1,9 @@
1
1
  import { z } from 'zod';
2
2
  import { minifiedResult, schemaOrigin } from '@chrischall/mcp-utils';
3
- import { getActiveClient } from '../client.js';
3
+ import { apiPath, getActiveClient } from '../client.js';
4
4
  export async function listNotes(args) {
5
5
  const client = await getActiveClient(args.origin);
6
- const notes = await client.request('GET', `/api/v2/notes/workspace/${args.workspace_id}`);
6
+ const notes = await client.request('GET', apiPath `/api/v2/notes/workspace/${args.workspace_id}`);
7
7
  return minifiedResult({ workspace_id: args.workspace_id, notes: notes ?? [] });
8
8
  }
9
9
  export function registerNoteTools(server) {
@@ -1,9 +1,9 @@
1
1
  import { z } from 'zod';
2
2
  import { minifiedResult, schemaOrigin } from '@chrischall/mcp-utils';
3
- import { getActiveClient } from '../client.js';
3
+ import { apiPath, getActiveClient } from '../client.js';
4
4
  export async function listPaymentMethods(args) {
5
5
  const client = await getActiveClient(args.origin);
6
- const res = await client.request('GET', `/api/v2/users/${client.scope.userId}/payment_methods`);
6
+ const res = await client.request('GET', apiPath `/api/v2/users/${client.scope.userId}/payment_methods`);
7
7
  return minifiedResult(res);
8
8
  }
9
9
  export function registerPaymentMethodTools(server) {
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { minifiedResult, schemaOrigin } from '@chrischall/mcp-utils';
3
- import { getActiveClient } from '../client.js';
3
+ import { apiPath, getActiveClient } from '../client.js';
4
4
  function num(v) {
5
5
  return typeof v === 'number' ? v : undefined;
6
6
  }
@@ -12,7 +12,7 @@ function num(v) {
12
12
  */
13
13
  export async function listPayments(args) {
14
14
  const client = await getActiveClient(args.origin);
15
- const res = await client.request('GET', `/api/v2/workspaces/${args.workspace_id}/payments`);
15
+ const res = await client.request('GET', apiPath `/api/v2/workspaces/${args.workspace_id}/payments`);
16
16
  // Totals are kept PER CURRENCY: each file names its own, and a workspace
17
17
  // can mix them, so one bare number would be in no currency at all.
18
18
  const totals = {};
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { minifiedResult, resolveView, schemaOrigin, viewParam, viewResult } from '@chrischall/mcp-utils';
3
- import { getActiveClient } from '../client.js';
3
+ import { apiPath, getActiveClient } from '../client.js';
4
4
  /**
5
5
  * HoneyBook calls a client's project an **event** (`/api/v2/client/events`);
6
6
  * each has exactly one client-portal workspace, whose id is what every other
@@ -86,7 +86,7 @@ export const PROJECT_VIEWS = ['compact', 'raw'];
86
86
  export async function getProject(args) {
87
87
  const view = resolveView(args.view, PROJECT_VIEWS);
88
88
  const client = await getActiveClient(args.origin);
89
- const res = await client.request('GET', `/api/v2/events/${args.project_id}/details`);
89
+ const res = await client.request('GET', apiPath `/api/v2/events/${args.project_id}/details`);
90
90
  return viewResult(view, view === 'raw' ? res : summarizeProject(res));
91
91
  }
92
92
  export function registerProjectTools(server) {
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { minifiedResult, schemaOrigin } from '@chrischall/mcp-utils';
3
- import { getActiveClient } from '../client.js';
3
+ import { apiPath, getActiveClient } from '../client.js';
4
4
  /** Today in the caller's LOCAL timezone — the UTC date is a day off for an evening west of Greenwich. */
5
5
  export function today(now = new Date()) {
6
6
  const y = now.getFullYear();
@@ -31,10 +31,10 @@ export async function listTasks(args) {
31
31
  const perPage = args.per_page ?? 50;
32
32
  const currDate = args.curr_date ?? today();
33
33
  const apiDate = encodeURIComponent(toApiDate(currDate));
34
- const base = `/api/v2/tasks/workspaces/${args.workspace_id}`;
34
+ const base = apiPath `/api/v2/tasks/workspaces/${args.workspace_id}`;
35
35
  const tasks = await client.request('GET', `${base}?page=${page}&perPage=${perPage}&sort_by=due_date&sort_desc=false&curr_date=${apiDate}`);
36
36
  const counts = await client.request('GET', `${base}/counts?curr_date=${apiDate}`);
37
- const groups = await client.request('GET', `/api/v2/workspaces/${args.workspace_id}/taskgroup`);
37
+ const groups = await client.request('GET', apiPath `/api/v2/workspaces/${args.workspace_id}/taskgroup`);
38
38
  return minifiedResult({
39
39
  workspace_id: args.workspace_id,
40
40
  page,
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { minifiedResult, rawTextResult, schemaOrigin } from '@chrischall/mcp-utils';
3
- import { getActiveClient } from '../client.js';
3
+ import { apiPath, getActiveClient } from '../client.js';
4
4
  import { FILE_TYPES } from '../types.js';
5
5
  /**
6
6
  * Vendor-side sub-fields on `company` that a CLIENT never needs but that
@@ -200,7 +200,7 @@ function extractPayments(file) {
200
200
  }
201
201
  export async function listWorkspaceFiles(args) {
202
202
  const client = await getActiveClient(args.origin);
203
- const res = await client.request('GET', `/api/v2/users/${client.scope.userId}/workspace_files`);
203
+ const res = await client.request('GET', apiPath `/api/v2/users/${client.scope.userId}/workspace_files`);
204
204
  const filtered = args.file_type
205
205
  ? res.data.filter((f) => f.file_type === args.file_type)
206
206
  : res.data;
@@ -212,7 +212,7 @@ export async function listWorkspaceFiles(args) {
212
212
  export async function getWorkspaceFile(args) {
213
213
  const section = args.section ?? 'summary';
214
214
  const client = await getActiveClient(args.origin);
215
- const raw = await client.request('GET', `/api/v2/workspace_files/${args.file_id}`);
215
+ const raw = await client.request('GET', apiPath `/api/v2/workspace_files/${args.file_id}`);
216
216
  let body;
217
217
  switch (section) {
218
218
  case 'raw':
@@ -1,9 +1,9 @@
1
1
  import { z } from 'zod';
2
2
  import { minifiedResult, schemaOrigin } from '@chrischall/mcp-utils';
3
- import { getActiveClient } from '../client.js';
3
+ import { apiPath, getActiveClient } from '../client.js';
4
4
  export async function getWorkspace(args) {
5
5
  const client = await getActiveClient(args.origin);
6
- const res = await client.request('GET', `/api/v2/workspaces/${args.workspace_id}`);
6
+ const res = await client.request('GET', apiPath `/api/v2/workspaces/${args.workspace_id}`);
7
7
  return minifiedResult(res);
8
8
  }
9
9
  export function registerWorkspaceTools(server) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "honeybook-mcp",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "mcpName": "io.github.chrischall/honeybook-mcp",
5
5
  "description": "HoneyBook client-portal MCP server for Claude",
6
6
  "author": "Claude Code (AI) <https://www.anthropic.com/claude>",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/chrischall/honeybook-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "1.1.3",
9
+ "version": "1.1.4",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "honeybook-mcp",
14
- "version": "1.1.3",
14
+ "version": "1.1.4",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },