@mindstone/mcp-server-xero 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +7 -6
  2. package/dist/handlers/list-xero-accounts.handler.js +5 -5
  3. package/dist/handlers/list-xero-bank-transactions.handler.js +16 -9
  4. package/dist/handlers/list-xero-credit-notes.handler.js +14 -9
  5. package/dist/handlers/list-xero-invoices.handler.js +11 -18
  6. package/dist/handlers/list-xero-items.handler.js +6 -5
  7. package/dist/handlers/list-xero-manual-journals.handler.js +1 -1
  8. package/dist/handlers/list-xero-payments.handler.js +1 -1
  9. package/dist/handlers/list-xero-profit-and-loss.handler.js +8 -12
  10. package/dist/handlers/summarise-xero-totals.handler.js +195 -0
  11. package/dist/helpers/contact-totals-tool.js +107 -0
  12. package/dist/helpers/format-line-item.js +20 -13
  13. package/dist/helpers/format-report.js +28 -0
  14. package/dist/helpers/page-note.js +6 -0
  15. package/dist/helpers/xero-date-where.js +27 -0
  16. package/dist/tools/list/index.js +5 -1
  17. package/dist/tools/list/list-accounts.tool.js +9 -2
  18. package/dist/tools/list/list-aged-payables-by-contact.tool.js +5 -18
  19. package/dist/tools/list/list-aged-receivables-by-contact.tool.js +5 -18
  20. package/dist/tools/list/list-bank-summary.tool.js +2 -8
  21. package/dist/tools/list/list-bank-transactions.tool.js +60 -16
  22. package/dist/tools/list/list-budget-summary.tool.js +2 -8
  23. package/dist/tools/list/list-credit-notes.tool.js +47 -12
  24. package/dist/tools/list/list-executive-summary.tool.js +2 -8
  25. package/dist/tools/list/list-invoices.tool.js +20 -20
  26. package/dist/tools/list/list-items.tool.js +3 -6
  27. package/dist/tools/list/list-manual-journals.tool.js +1 -3
  28. package/dist/tools/list/list-organisation-details.tool.js +15 -15
  29. package/dist/tools/list/list-payments.tool.js +1 -2
  30. package/dist/tools/list/list-payroll-employees.tool.js +1 -1
  31. package/dist/tools/list/list-profit-and-loss.tool.js +23 -24
  32. package/dist/tools/list/list-quotes.tool.js +2 -3
  33. package/dist/tools/list/list-report-balance-sheet.tool.js +2 -8
  34. package/dist/tools/list/list-trial-balance.tool.js +2 -16
  35. package/dist/tools/list/summarise-sales-by-customer.tool.js +9 -0
  36. package/dist/tools/list/summarise-spend-by-supplier.tool.js +10 -0
  37. package/node_modules/cross-spawn/README.md +19 -3
  38. package/node_modules/cross-spawn/lib/parse.js +38 -10
  39. package/node_modules/cross-spawn/lib/util/escape.js +84 -25
  40. package/node_modules/cross-spawn/lib/util/readShebang.js +8 -2
  41. package/node_modules/cross-spawn/lib/util/resolveCommand.js +8 -1
  42. package/node_modules/cross-spawn/package.json +21 -24
  43. package/package.json +1 -1
@@ -2,7 +2,7 @@ import { listXeroPayrollEmployees } from "../../handlers/list-xero-payroll-emplo
2
2
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
3
3
  const ListPayrollEmployeesTool = CreateXeroTool("list-payroll-employees", `List all payroll employees in Xero.
4
4
  This retrieves comprehensive employee details including names, User IDs, dates of birth, email addresses, gender, phone numbers, start dates, engagement types (Permanent, FixedTerm, or Casual), titles, and when records were last updated.
5
- The response presents a complete overview of all staff currently registered in your Xero payroll, with their personal and employment information. If there are many employees, ask the user if they would like to see more detailed information about specific employees before proceeding.`, {}, async () => {
5
+ The response presents a complete overview of all staff currently registered in your Xero payroll, with their personal and employment information.`, {}, async () => {
6
6
  const response = await listXeroPayrollEmployees();
7
7
  if (response.isError) {
8
8
  return {
@@ -1,15 +1,29 @@
1
1
  import { z } from "zod";
2
2
  import { listXeroProfitAndLoss } from "../../handlers/list-xero-profit-and-loss.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
- const ListProfitAndLossTool = CreateXeroTool("list-profit-and-loss", "Lists profit and loss report in Xero. This provides a summary of revenue, expenses, and profit or loss over a specified period of time.", {
5
- fromDate: z.string().optional().describe("Optional start date in YYYY-MM-DD format"),
6
- toDate: z.string().optional().describe("Optional end date in YYYY-MM-DD format"),
7
- periods: z.number().optional().describe("Optional number of periods to compare"),
8
- timeframe: z.enum(["MONTH", "QUARTER", "YEAR"]).optional().describe("Optional timeframe for the report (MONTH, QUARTER, YEAR)"),
9
- standardLayout: z.boolean().optional().describe("Optional flag to use standard layout"),
10
- paymentsOnly: z.boolean().optional().describe("Optional flag to include only accounts with payments"),
4
+ import { formatReport } from "../../helpers/format-report.js";
5
+ const ListProfitAndLossTool = CreateXeroTool("list-profit-and-loss", `Profit and loss (income statement) from Xero: income, costs and profit by account, for one period or several side by side.
6
+ This is the quickest way to answer "how much did we spend on X", "what did we earn", or a month-by-month trend: one call covers up to 12 periods.
7
+ Month by month: fromDate and toDate are one whole month, periods the number of earlier months, timeframe MONTH; Xero adds the earlier months as extra columns, newest first.
8
+ Xero cuts each earlier month to the length of that first month, so a 30-day November drops 31 October. Base the call on the latest month with 31 days (e.g. 2026-10-01 to 2026-10-31, periods 11), then ask for any later month in its own call.
9
+ The report's first lines name the period it covers. Amounts exclude tax.`, {
10
+ fromDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Must be YYYY-MM-DD format").optional()
11
+ .describe("Start of the (latest) period, YYYY-MM-DD. Defaults to the start of the current month."),
12
+ toDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Must be YYYY-MM-DD format").optional()
13
+ .describe("End of the (latest) period, YYYY-MM-DD. Defaults to the end of the current month."),
14
+ periods: z.number().int().min(1).max(11).optional()
15
+ .describe("How many earlier periods to add as columns for comparison (1-11). Leave out for the one period only."),
16
+ timeframe: z.enum(["MONTH", "QUARTER", "YEAR"]).optional()
17
+ .describe("Length of each earlier period when periods is set. Defaults to MONTH."),
18
+ trackingCategoryID: z.string().optional()
19
+ .describe("Split the columns by this tracking category (e.g. department or project); from list-tracking-categories."),
20
+ trackingOptionID: z.string().optional()
21
+ .describe("Show only this option of the tracking category (needs trackingCategoryID)."),
22
+ standardLayout: z.boolean().optional().describe("Use Xero's standard layout rather than the organisation's custom one."),
23
+ paymentsOnly: z.boolean().optional()
24
+ .describe("Cash basis: count only what has been paid or received, rather than invoices and bills when issued."),
11
25
  }, async (args) => {
12
- const response = await listXeroProfitAndLoss(args?.fromDate, args?.toDate, args?.periods, args?.timeframe, args?.standardLayout, args?.paymentsOnly);
26
+ const response = await listXeroProfitAndLoss(args?.fromDate, args?.toDate, args?.periods, args?.timeframe, args?.trackingCategoryID, args?.trackingOptionID, args?.standardLayout, args?.paymentsOnly);
13
27
  if (response.error !== null) {
14
28
  return {
15
29
  content: [
@@ -24,22 +38,7 @@ const ListProfitAndLossTool = CreateXeroTool("list-profit-and-loss", "Lists prof
24
38
  const profitAndLossReport = response.result;
25
39
  return {
26
40
  content: [
27
- {
28
- type: "text",
29
- text: `Profit and Loss Report: ${profitAndLossReport?.reportName ?? "Unnamed"}`,
30
- },
31
- {
32
- type: "text",
33
- text: `Date Range: ${profitAndLossReport?.reportDate ?? "Not specified"}`,
34
- },
35
- {
36
- type: "text",
37
- text: `Updated At: ${profitAndLossReport?.updatedDateUTC ? profitAndLossReport.updatedDateUTC.toISOString() : "Unknown"}`,
38
- },
39
- {
40
- type: "text",
41
- text: JSON.stringify(profitAndLossReport.rows, null, 2),
42
- },
41
+ { type: "text", text: formatReport(profitAndLossReport) },
43
42
  ],
44
43
  };
45
44
  });
@@ -2,9 +2,8 @@ import { z } from "zod";
2
2
  import { listXeroQuotes } from "../../handlers/list-xero-quotes.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
4
  const ListQuotesTool = CreateXeroTool("list-quotes", `List all quotes in Xero.
5
- Ask the user if they want to see quotes for a specific contact before running.
6
- Ask the user if they want the next page of quotes after running this tool if 10 quotes are returned.
7
- If they do, call this tool again with the page number and the contact provided in the previous call.
5
+ Can filter by contact or quote number.
6
+ Returns up to 100 quotes a page. If 100 come back there may be more: call this tool again with the next page number and the same filters.
8
7
 
9
8
  COMMON MISTAKES:
10
9
  - Only use the params listed above. Do not invent additional filter or sort params.
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { listXeroReportBalanceSheet } from "../../handlers/list-xero-report-balance-sheet.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ import { formatReport } from "../../helpers/format-report.js";
4
5
  const ListReportBalanceSheetTool = CreateXeroTool("list-report-balance-sheet", "List the Balance Sheet report from Xero.", {
5
6
  date: z.string().optional().describe("Optional date in YYYY-MM-DD format"),
6
7
  periods: z.number().optional().describe("Optional number of periods to compare"),
@@ -26,14 +27,7 @@ const ListReportBalanceSheetTool = CreateXeroTool("list-report-balance-sheet", "
26
27
  const balanceSheetReport = response.result;
27
28
  return {
28
29
  content: [
29
- {
30
- type: "text",
31
- text: `Balance sheet Report: ${balanceSheetReport?.reportName ?? "Unnamed"}`,
32
- },
33
- {
34
- type: "text",
35
- text: JSON.stringify(balanceSheetReport.rows, null, 2),
36
- },
30
+ { type: "text", text: formatReport(balanceSheetReport) },
37
31
  ],
38
32
  };
39
33
  });
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { listXeroTrialBalance } from "../../handlers/list-xero-trial-balance.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ import { formatReport } from "../../helpers/format-report.js";
4
5
  const ListTrialBalanceTool = CreateXeroTool("list-trial-balance", "Lists trial balance in Xero. This provides a snapshot of the general ledger, showing debit and credit balances for each account.", {
5
6
  date: z.string().optional().describe("Optional date in YYYY-MM-DD format"),
6
7
  paymentsOnly: z.boolean().optional().describe("Optional flag to include only accounts with payments"),
@@ -20,22 +21,7 @@ const ListTrialBalanceTool = CreateXeroTool("list-trial-balance", "Lists trial b
20
21
  const trialBalanceReport = response.result;
21
22
  return {
22
23
  content: [
23
- {
24
- type: "text",
25
- text: `Trial Balance Report: ${trialBalanceReport?.reportName || "Unnamed"}`,
26
- },
27
- {
28
- type: "text",
29
- text: `Date: ${trialBalanceReport?.reportDate || "Not specified"}`,
30
- },
31
- {
32
- type: "text",
33
- text: `Updated At: ${trialBalanceReport?.updatedDateUTC ? trialBalanceReport.updatedDateUTC.toISOString() : "Unknown"}`,
34
- },
35
- {
36
- type: "text",
37
- text: JSON.stringify(trialBalanceReport.rows, null, 2),
38
- },
24
+ { type: "text", text: formatReport(trialBalanceReport) },
39
25
  ],
40
26
  };
41
27
  });
@@ -0,0 +1,9 @@
1
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
2
+ import { contactTotalsParams, runContactTotals } from "../../helpers/contact-totals-tool.js";
3
+ const SummariseSalesByCustomerTool = CreateXeroTool("summarise-sales-by-customer", `Total what each customer was invoiced or paid over a date range, ranked by amount, in one call.
4
+ Use it for questions like "top customers by revenue", "how much did X buy this year", "who are our biggest clients".
5
+ It reads every approved or paid sales invoice, every receive-money bank transaction (money in not entered as an invoice) and every customer credit note in the range, and totals their line amounts without tax, in the base currency, by customer and by account. Payments against invoices are not counted again.
6
+
7
+ To narrow to a kind of income, first call list-accounts and pass the matching revenue account codes as accountCodes.
8
+ Prefer this over paging list-invoices by hand for any total or ranking. For what customers still owe, use list-invoices with type ACCREC and status AUTHORISED.`, contactTotalsParams("sales"), async (args) => runContactTotals("sales", args));
9
+ export default SummariseSalesByCustomerTool;
@@ -0,0 +1,10 @@
1
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
2
+ import { contactTotalsParams, runContactTotals } from "../../helpers/contact-totals-tool.js";
3
+ const SummariseSpendBySupplierTool = CreateXeroTool("summarise-spend-by-supplier", `Total what the organisation spent with each supplier over a date range, ranked by amount, in one call.
4
+ Use it for questions like "biggest suppliers", "what do we spend on software subscriptions", "top costs this year", "how much did we pay X".
5
+ It reads every approved or paid bill, every spend-money bank transaction (card and bank payments not entered as bills) and every supplier credit note in the range, and totals their line amounts without tax, in the base currency, by supplier and by account. Bill payments are not counted again.
6
+
7
+ To narrow to a kind of cost (software, subscriptions, travel), first call list-accounts and pass the matching expense account codes as accountCodes.
8
+ Prefer this over paging list-invoices or list-bank-transactions by hand for any total or ranking.
9
+ For totals per account month by month (e.g. travel each month this year), one list-profit-and-loss call with periods is quicker than calling this once per month.`, contactTotalsParams("spend"), async (args) => runContactTotals("spend", args));
10
+ export default SummariseSpendBySupplierTool;
@@ -1,14 +1,12 @@
1
1
  # cross-spawn
2
2
 
3
- [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Build status][appveyor-image]][appveyor-url]
3
+ [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url]
4
4
 
5
5
  [npm-url]:https://npmjs.org/package/cross-spawn
6
6
  [downloads-image]:https://img.shields.io/npm/dm/cross-spawn.svg
7
7
  [npm-image]:https://img.shields.io/npm/v/cross-spawn.svg
8
8
  [ci-url]:https://github.com/moxystudio/node-cross-spawn/actions/workflows/ci.yaml
9
9
  [ci-image]:https://github.com/moxystudio/node-cross-spawn/actions/workflows/ci.yaml/badge.svg
10
- [appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn
11
- [appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg
12
10
 
13
11
  A cross platform solution to node's spawn and spawnSync.
14
12
 
@@ -70,6 +68,24 @@ While `cross-spawn` adds support for `options.shell` in node `<v4.8`, all of its
70
68
 
71
69
  This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using `options.shell` you are probably targeting a specific platform anyway and you don't want things to get into your way.
72
70
 
71
+ ### Windows argument escaping
72
+
73
+ On Unix systems arguments are passed to a new process as an array of strings, but on Windows they are passed as a single command line string and it is up to the child process to parse it back into an array. Therefore `cross-spawn` and the child process must agree on how the command line is encoded.
74
+
75
+ `cross-spawn` escapes arguments according to the conventions of the Microsoft C runtime, which most programs use, including Node.js, Python, Java and .NET. However, some programs have their own way of parsing the command line, in which case they may see a different array of arguments than the one you passed.
76
+
77
+ Commands that are not executables, such as batch files (`.bat` and `.cmd`), are run through `cmd.exe`, which uses non-standard parsing and is especially vulnerable to malicious input, as it may be used to run arbitrary commands. `cross-spawn` escapes the command and its arguments according to `cmd.exe` rules, similarly to other runtimes such as [Rust](https://doc.rust-lang.org/std/process/index.html#windows-argument-splitting). Still, due to the complexity of `cmd.exe`, there are limitations that no escaping can overcome:
78
+
79
+ - Some characters can't be escaped at all. Line breaks (`\r` and `\n`) can't be escaped and passing them results in an error being thrown.
80
+ - The command must be the name or path of a single program, with its arguments passed in `args`. The command is quoted, so `spawn('npm install')` fails with `ENOENT`, like it does on other platforms, and double quotes in it are ignored, since Windows file names can't contain them.
81
+ - Shell built-ins that run other commands, such as `call` and `start`, pass their arguments to those commands unescaped. Call the program directly instead, e.g. `spawn('tool.bat', args)` instead of `spawn('call', ['tool.bat', ...args])`.
82
+ - Batch files are assumed to forward arguments as received, e.g. with `%*`, `%1` or `"%~1"`. Batch files that use `%~1` unquoted, `call` or enable delayed expansion re-parse their arguments and may be vulnerable to malicious input.
83
+ - Programs called by batch files must follow the Microsoft C runtime conventions. Programs that don't, such as those written in Go or that use `CommandLineToArgvW`, may split arguments containing double quotes differently.
84
+
85
+ Additionally, programs that read their arguments with the legacy ANSI code page instead of Unicode may convert certain Unicode characters into others, such as `"` (U+FF02) into `"`, which changes how arguments are split. This is known as [WorstFit](https://worst.fit) and can't be mitigated by `cross-spawn`.
86
+
87
+ When passing untrusted input on Windows, validate it so that only a safe subset is allowed, and prefer calling executables directly rather than through batch files.
88
+
73
89
  ### Shebangs support
74
90
 
75
91
  While `cross-spawn` handles shebangs on Windows, its support is limited. More specifically, it just supports `#!/usr/bin/env <program>` where `<program>` must not contain any arguments.
@@ -7,7 +7,11 @@ const readShebang = require('./util/readShebang');
7
7
 
8
8
  const isWin = process.platform === 'win32';
9
9
  const isExecutableRegExp = /\.(?:com|exe)$/i;
10
- const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
10
+ const isBatchFileRegExp = /\.(?:bat|cmd)$/i;
11
+ // Windows strips trailing dots and spaces from file names, so `cmd.exe` runs `foo.bat ` as `foo.bat`
12
+ // Other trailing whitespace, such as tabs, is treated the same way to be safe
13
+ // See CVE-2024-36138 for the equivalent Node.js vulnerability
14
+ const trailingDotsAndSpacesRegExp = /[.\s]+$/;
11
15
 
12
16
  function detectShebang(parsed) {
13
17
  parsed.file = resolveCommand(parsed);
@@ -24,11 +28,29 @@ function detectShebang(parsed) {
24
28
  return parsed.file;
25
29
  }
26
30
 
31
+ function isBatchFile(parsed, commandFile) {
32
+ if (commandFile) {
33
+ return isBatchFileRegExp.test(commandFile.replace(trailingDotsAndSpacesRegExp, ''));
34
+ }
35
+
36
+ // The command couldn't be resolved, but cmd.exe might still find a batch file after stripping
37
+ // trailing dots and spaces, e.g.: `foo ` might run `foo.bat`
38
+ const command = parsed.command.replace(trailingDotsAndSpacesRegExp, '');
39
+ const file = command !== parsed.command ? resolveCommand(Object.assign({}, parsed, { command })) : null;
40
+
41
+ return isBatchFileRegExp.test(file || command);
42
+ }
43
+
27
44
  function parseNonShell(parsed) {
28
45
  if (!isWin) {
29
46
  return parsed;
30
47
  }
31
48
 
49
+ // Windows file names can't contain double quotes, and cmd.exe ignores them in command names, so remove them
50
+ // Otherwise a quoted command, e.g. `"foo.bat"`, wouldn't be found and could be run as a batch file without
51
+ // being detected as one
52
+ parsed.command = parsed.command.replace(/"/g, '');
53
+
32
54
  // Detect & add support for shebangs
33
55
  const commandFile = detectShebang(parsed);
34
56
 
@@ -38,23 +60,29 @@ function parseNonShell(parsed) {
38
60
  // If a shell is required, use cmd.exe and take care of escaping everything correctly
39
61
  // Note that `forceShell` is an hidden option used only in tests
40
62
  if (parsed.options.forceShell || needsShell) {
41
- // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
42
- // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
43
- // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
44
- // we need to double escape them
45
- const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
46
-
47
63
  // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
48
64
  // This is necessary otherwise it will always fail with ENOENT in those cases
49
65
  parsed.command = path.normalize(parsed.command);
50
66
 
51
67
  // Escape command & arguments
52
- parsed.command = escape.command(parsed.command);
53
- parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
68
+ // Batch files need a different escaping strategy, see `lib/util/escape.js` for more information
69
+ if (isBatchFile(parsed, commandFile)) {
70
+ // Run the batch file by its resolved path, if it was found, otherwise as written
71
+ // When a batch file is run through a quoted name found in PATH, e.g. `"gradle"`, cmd.exe sets `%~dp0` to
72
+ // the current directory instead of the batch file's directory, which breaks batch files that use it to
73
+ // find their own files, such as Gradle's
74
+ parsed.command = escape.batchCommand(commandFile ? path.normalize(commandFile) : parsed.command);
75
+ parsed.args = parsed.args.map((arg) => escape.batchArgument(arg));
76
+ } else {
77
+ parsed.command = escape.command(parsed.command);
78
+ parsed.args = parsed.args.map((arg) => escape.argument(arg));
79
+ }
54
80
 
55
81
  const shellCommand = [parsed.command].concat(parsed.args).join(' ');
56
82
 
57
- parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
83
+ // Enable command extensions with /e:on, needed by the %cd:~,% trick, as they might be disabled in the registry
84
+ // Disable delayed expansion with /v:off, otherwise !VAR! would be expanded if enabled in the registry
85
+ parsed.args = ['/d', '/e:on', '/v:off', '/s', '/c', `"${shellCommand}"`];
58
86
  parsed.command = process.env.comspec || 'cmd.exe';
59
87
  parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
60
88
  }
@@ -1,47 +1,106 @@
1
1
  'use strict';
2
2
 
3
3
  // See http://www.robvanderwoude.com/escapechars.php
4
- const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
4
+ // Note that % is not included because escaping it with ^ doesn't prevent %VAR% expansion if
5
+ // a variable named `VAR^` exists, see `escapePercent()` below
6
+ const metaCharsRegExp = /([()\][!^"`<>&|;, *?])/g;
7
+
8
+ // cmd.exe treats CR and LF as command separators and there's no way to escape them
9
+ // Allowing them would enable command injection, so we reject them instead
10
+ const lineBreakRegExp = /[\r\n]/;
11
+
12
+ function assertNoLineBreaks(arg) {
13
+ if (lineBreakRegExp.test(arg)) {
14
+ throw new TypeError('The command and its arguments cannot contain line breaks when executed through cmd.exe');
15
+ }
16
+ }
17
+
18
+ // %VAR% is expanded even inside double quotes or when escaped with ^, so we replace % with %%cd:~,%
19
+ // The latter is an empty substring of the %cd% dynamic variable, which interrupts the expansion
20
+ // This must be done after escaping meta chars, as the replacement must not be escaped itself
21
+ function escapePercent(arg) {
22
+ return arg.replace(/%/g, '%%cd:~,%');
23
+ }
24
+
25
+ // Quotes an argument so that it's parsed back verbatim by programs following the Microsoft C runtime rules,
26
+ // where backslashes are only special when they precede a double quote
27
+ // Algorithm below is based on https://qntm.org/cmd, but implemented with a loop instead of regular expressions,
28
+ // which runs in linear time and correctly handles any number of backslashes
29
+ function quoteArgument(arg, escapedQuote) {
30
+ let quoted = '"';
31
+ let backslashes = 0;
32
+
33
+ for (const char of arg) {
34
+ if (char === '\\') {
35
+ backslashes += 1;
36
+ continue;
37
+ }
38
+
39
+ if (char === '"') {
40
+ // Sequence of backslashes followed by a double quote:
41
+ // double up all the backslashes and escape the double quote
42
+ quoted += '\\'.repeat(backslashes * 2) + escapedQuote;
43
+ } else {
44
+ // All other backslashes occur literally
45
+ quoted += '\\'.repeat(backslashes) + char;
46
+ }
47
+
48
+ backslashes = 0;
49
+ }
50
+
51
+ // Sequence of backslashes followed by the end of the string (which will become a double quote):
52
+ // double up all the backslashes
53
+ return `${quoted}${'\\'.repeat(backslashes * 2)}"`;
54
+ }
5
55
 
6
56
  function escapeCommand(arg) {
7
- // Escape meta chars
8
- arg = arg.replace(metaCharsRegExp, '^$1');
57
+ assertNoLineBreaks(arg);
9
58
 
10
- return arg;
59
+ // Quote the command, so that cmd.exe treats it as a single name
60
+ // Otherwise cmd.exe would end the name at the first space, tab, `,`, `;` or `=`, even if escaped with ^,
61
+ // and run whatever it finds with that name, e.g. a batch file, with the rest as extra arguments
62
+ // Command names can't contain double quotes, see `parse.js`, and meta chars are literal inside quotes
63
+ return `"${escapePercent(arg)}"`;
11
64
  }
12
65
 
13
- function escapeArgument(arg, doubleEscapeMetaChars) {
66
+ function escapeArgument(arg) {
14
67
  // Convert to string
15
68
  arg = `${arg}`;
16
69
 
17
- // Algorithm below is based on https://qntm.org/cmd
18
- // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input
19
- // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information
70
+ assertNoLineBreaks(arg);
20
71
 
21
- // Sequence of backslashes followed by a double quote:
22
- // double up all the backslashes and escape the double quote
23
- arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
72
+ // Quote the whole thing, escaping double quotes with a backslash
73
+ arg = quoteArgument(arg, '\\"');
24
74
 
25
- // Sequence of backslashes followed by the end of the string
26
- // (which will become a double quote later):
27
- // double up all the backslashes
28
- arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1');
75
+ // Escape meta chars and neutralize %VAR% expansion
76
+ arg = escapePercent(arg.replace(metaCharsRegExp, '^$1'));
29
77
 
30
- // All other backslashes occur literally
78
+ return arg;
79
+ }
31
80
 
32
- // Quote the whole thing:
33
- arg = `"${arg}"`;
81
+ // Batch files (.bat and .cmd) usually proxy their arguments with %* or read them with "%~1",
82
+ // which makes cmd.exe parse them a second time, after ^ escapes have already been consumed
83
+ // Instead of escaping meta chars with ^, we rely on double quotes, which keep meta chars literal in both parses
84
+ // This is the same approach taken by Rust after BatBadBut (CVE-2024-24576)
34
85
 
35
- // Escape meta chars
36
- arg = arg.replace(metaCharsRegExp, '^$1');
86
+ function escapeBatchCommand(arg) {
87
+ assertNoLineBreaks(arg);
37
88
 
38
- // Double escape meta chars if necessary
39
- if (doubleEscapeMetaChars) {
40
- arg = arg.replace(metaCharsRegExp, '^$1');
41
- }
89
+ // Command names can't contain double quotes, so we just need to quote it
90
+ return `"${escapePercent(arg)}"`;
91
+ }
42
92
 
43
- return arg;
93
+ function escapeBatchArgument(arg) {
94
+ // Convert to string
95
+ arg = `${arg}`;
96
+
97
+ assertNoLineBreaks(arg);
98
+
99
+ // Quote the whole thing, escaping double quotes by doubling them, which keeps cmd.exe's quoting balanced
100
+ return escapePercent(quoteArgument(arg, '""'));
44
101
  }
45
102
 
46
103
  module.exports.command = escapeCommand;
47
104
  module.exports.argument = escapeArgument;
105
+ module.exports.batchCommand = escapeBatchCommand;
106
+ module.exports.batchArgument = escapeBatchArgument;
@@ -13,8 +13,14 @@ function readShebang(command) {
13
13
  try {
14
14
  fd = fs.openSync(command, 'r');
15
15
  fs.readSync(fd, buffer, 0, size, 0);
16
- fs.closeSync(fd);
17
- } catch (e) { /* Empty */ }
16
+ } catch (e) { /* Empty */ } finally {
17
+ // Always close the file descriptor, even if reading failed
18
+ if (fd !== undefined) {
19
+ try {
20
+ fs.closeSync(fd);
21
+ } catch (e) { /* Empty */ }
22
+ }
23
+ }
18
24
 
19
25
  // Attempt to extract shebang (null is returned if not a shebang)
20
26
  return shebangCommand(buffer.toString());
@@ -4,6 +4,13 @@ const path = require('path');
4
4
  const which = require('which');
5
5
  const getPathKey = require('path-key');
6
6
 
7
+ // Returns the child's PATHEXT, which cmd.exe will use to find the command
8
+ function getPathExt(env) {
9
+ const key = Object.keys(env).find((name) => name.toUpperCase() === 'PATHEXT');
10
+
11
+ return key ? env[key] : undefined;
12
+ }
13
+
7
14
  function resolveCommandAttempt(parsed, withoutPathExt) {
8
15
  const env = parsed.options.env || process.env;
9
16
  const cwd = process.cwd();
@@ -26,7 +33,7 @@ function resolveCommandAttempt(parsed, withoutPathExt) {
26
33
  try {
27
34
  resolved = which.sync(parsed.command, {
28
35
  path: env[getPathKey({ env })],
29
- pathExt: withoutPathExt ? path.delimiter : undefined,
36
+ pathExt: withoutPathExt ? path.delimiter : getPathExt(env),
30
37
  });
31
38
  } catch (e) {
32
39
  /* Empty */
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cross-spawn",
3
- "version": "7.0.6",
3
+ "version": "7.1.2",
4
4
  "description": "Cross platform child_process#spawn and child_process#spawnSync",
5
5
  "keywords": [
6
6
  "spawn",
@@ -21,26 +21,26 @@
21
21
  "license": "MIT",
22
22
  "main": "index.js",
23
23
  "files": [
24
- "lib"
24
+ "lib",
25
+ "!lib/**/*.test.js"
25
26
  ],
26
27
  "scripts": {
27
28
  "lint": "eslint .",
28
29
  "test": "jest --env node --coverage",
29
30
  "prerelease": "npm t && npm run lint",
30
31
  "release": "standard-version",
31
- "postrelease": "git push --follow-tags origin HEAD && npm publish"
32
+ "postrelease": "git push --follow-tags origin HEAD && npm publish",
33
+ "prepare": "husky"
32
34
  },
33
- "husky": {
34
- "hooks": {
35
- "commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
36
- "pre-commit": "lint-staged"
37
- }
35
+ "jest": {
36
+ "collectCoverageFrom": [
37
+ "index.js",
38
+ "lib/**/*.js",
39
+ "!lib/**/*.test.js"
40
+ ]
38
41
  },
39
42
  "lint-staged": {
40
- "*.js": [
41
- "eslint --fix",
42
- "git add"
43
- ]
43
+ "*.js": "eslint --fix"
44
44
  },
45
45
  "commitlint": {
46
46
  "extends": [
@@ -53,18 +53,15 @@
53
53
  "which": "^2.0.1"
54
54
  },
55
55
  "devDependencies": {
56
- "@commitlint/cli": "^8.1.0",
57
- "@commitlint/config-conventional": "^8.1.0",
58
- "babel-core": "^6.26.3",
59
- "babel-jest": "^24.9.0",
60
- "babel-preset-moxy": "^3.1.0",
61
- "eslint": "^5.16.0",
62
- "eslint-config-moxy": "^7.1.0",
63
- "husky": "^3.0.5",
64
- "jest": "^24.9.0",
65
- "lint-staged": "^9.2.5",
66
- "mkdirp": "^0.5.1",
67
- "rimraf": "^3.0.0",
56
+ "@commitlint/cli": "^20.5.3",
57
+ "@commitlint/config-conventional": "^20.5.3",
58
+ "@eslint/js": "^9.39.5",
59
+ "eslint": "^9.39.5",
60
+ "eslint-plugin-jest": "^28.14.0",
61
+ "globals": "^16.5.0",
62
+ "husky": "^9.1.7",
63
+ "jest": "^30.5.2",
64
+ "lint-staged": "^15.5.2",
68
65
  "standard-version": "^9.5.0"
69
66
  },
70
67
  "engines": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mindstone/mcp-server-xero",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "mcpName": "io.github.mindstone/mcp-server-xero",
5
5
  "description": "Xero MCP server for invoices, contacts, payments, quotes, and financial reports",
6
6
  "license": "MIT",