@diy-accounting-uk/diya-submit 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -2
- package/bin/diya-submit-mcp.js +63 -0
- package/lib/accounts-tools.js +18 -0
- package/lib/auth.js +347 -0
- package/lib/batch-tools.js +61 -0
- package/lib/book-tools.js +312 -0
- package/lib/finance/bank-lines.js +195 -0
- package/lib/finance/book-from-workbook.js +331 -0
- package/lib/finance/labels.js +33 -0
- package/lib/finance/mail-invoices.js +356 -0
- package/lib/finance/package-writer.js +66 -0
- package/lib/finance/paypal-lines.js +207 -0
- package/lib/finance/paypal-statement-lines.js +784 -0
- package/lib/finance/stripe-lines.js +268 -0
- package/lib/hosted-tools.js +59 -0
- package/lib/http.js +24 -0
- package/lib/itsa-tools.js +95 -0
- package/lib/practice-tools.js +123 -0
- package/lib/server.js +492 -0
- package/lib/submit-tools.js +405 -0
- package/lib/vat-tools.js +21 -0
- package/lib/vendored/app/lib/xmlDom.js +73 -0
- package/lib/vendored/app/services/accountsIxbrlCommon.js +414 -0
- package/lib/vendored/app/services/microEntityAccounts.js +224 -0
- package/lib/vendored/app/services/paypalTransactions.js +256 -0
- package/lib/vendored/app/services/smallCompanyAccounts.js +261 -0
- package/lib/vendored/app/services/smallCompanyAccountsIxbrl.js +426 -0
- package/package.json +46 -4
package/README.md
CHANGED
|
@@ -1,3 +1,72 @@
|
|
|
1
|
-
|
|
1
|
+
<!-- SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0 -->
|
|
2
|
+
<!-- Copyright (C) 2006-2026 DIY Accounting Limited -->
|
|
2
3
|
|
|
3
|
-
|
|
4
|
+
# @diy-accounting-uk/diya-submit
|
|
5
|
+
|
|
6
|
+
The submission MCP for DIY Accounting Submit (`PLAN_SUBMISSION_MCP.md`). It opens a customer's
|
|
7
|
+
books with the published `@diy-accounting-uk/diya-gl` engine, derives the figures a filing
|
|
8
|
+
needs, and drives the VAT return and the micro-entity accounts through this service's
|
|
9
|
+
endpoints. This package is the skeleton: the server, the stdio transport and the two book
|
|
10
|
+
tools. The derivation and filing tools are the plan's later rows.
|
|
11
|
+
|
|
12
|
+
## Run
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
npm --prefix mcp install
|
|
16
|
+
node mcp/bin/diya-submit-mcp.js
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Point an MCP client at that command with no arguments. The server is `mcp/lib/server.js`; the
|
|
20
|
+
stdio entry point only connects it to stdin and stdout, so the hosted transport connects the
|
|
21
|
+
same server to a different one.
|
|
22
|
+
|
|
23
|
+
## Hosted
|
|
24
|
+
|
|
25
|
+
The same server runs behind the site at `/mcp`, for chat clients that connect by URL. Add
|
|
26
|
+
`https://submit.diyaccounting.co.uk/mcp` as a custom connector in Claude (web, Desktop, mobile or
|
|
27
|
+
Cowork), or in Claude Code:
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
claude mcp add --transport http diya-submit https://submit.diyaccounting.co.uk/mcp
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The client finds the sign-in through `/.well-known/oauth-protected-resource/mcp`, registers itself, and
|
|
34
|
+
the user signs in with their Submit account. The ci form of the URL is
|
|
35
|
+
`https://ci-submit.diyaccounting.co.uk/mcp`. The hosted tool set is `HOSTED_TOOL_NAMES` in
|
|
36
|
+
`lib/hosted-tools.js`: `open_book` reads the DIYA cloud only, and the sign-in, filesystem and HMRC
|
|
37
|
+
tools are not registered.
|
|
38
|
+
|
|
39
|
+
## Tools
|
|
40
|
+
|
|
41
|
+
| Tool | Does |
|
|
42
|
+
|---|---|
|
|
43
|
+
| `open_book` | Loads a book from a path: a directory of `book.toml` + `lines.jsonl`, or one file the engine reads (a workbook, a package zip, a diya-gl zip, a diya-gl JSON file). Answers the product, entity, period, line count and the book checks summary. |
|
|
44
|
+
| `save_book` | Writes the session's book to a path as `diya-gl-dir`, `diya-gl-zip`, `json`, `xlsx` or `zip`. The last two compose the product's workbook from the site's templates. |
|
|
45
|
+
| `derive_itsa_quarterly_update` | One period of HMRC's Self Employment Business API from a self-employed book: the period's own figures in a tax year filed as dated period summaries, the running total from 6 April in a year filed as cumulative period summaries (2025-26 on). `periodEndDate` picks the period; `quarterlyPeriodType` is `standard` or `calendar`. A field the book cannot source is omitted, never sent as zero. |
|
|
46
|
+
| `derive_itsa_annual_submission` | The year's allowances and adjustments for the annual submission, restricted to the fields HMRC accepts for that tax year (`sa103-mtd-mapping.json`'s `api.years`). With `path`, also written as the JSON file the site's annual submission page imports. |
|
|
47
|
+
| `list_vat_obligations` | VAT obligations for `vrn` (or `clientId`), filtered by `from`, `to`, `status`. Needs `hmrcAccessToken`; optional `hmrcAccount`, `govTestScenario`. |
|
|
48
|
+
| `submit_vat_return` | Files the seven confirmed boxes (`vatDueSales`, `vatDueAcquisitions`, `vatReclaimedCurrPeriod`, `totalValueSalesExVAT`, `totalValuePurchasesExVAT`, `totalValueGoodsSuppliedExVAT`, `totalAcquisitionsExVAT`) for `periodStart` to `periodEnd`, for `vatNumber` or `clientId`. Needs `hmrcAccessToken`. Answers `receipt`, `periodKey`, `receiptId`. |
|
|
49
|
+
| `get_vat_receipt` | A stored receipt by `name` (`<receiptId>.json`); optional `clientId`. |
|
|
50
|
+
| `preview_micro_entity_accounts` | The rendered micro-entity iXBRL for confirmed figures, without reaching the Companies House gateway. Inputs: `companyNumber`, `companyName`, `periodStart`, `periodEnd`, `balanceSheet`, `averageEmployees`, `director`, `statementsAccepted`. |
|
|
51
|
+
| `submit_micro_entity_accounts` | Files the same figures with `companyAuthCode`; answers `submissionNumber`. |
|
|
52
|
+
| `poll_accounts_submission` | The filing's outcome for a `submissionNumber`: `PENDING`, `ACCEPT` (with `receiptId`) or `REJECT` (with `rejections`). |
|
|
53
|
+
|
|
54
|
+
The filing tools call the deployed REST API at `DIYA_SUBMIT_BASE_URL` with the MCP's own sign-in bearer (`sign_in`), and poll a 202 answer to its terminal status. They validate required inputs before any request.
|
|
55
|
+
|
|
56
|
+
One book per session, in memory. `open_book` replaces it. The two ITSA tools live in `lib/itsa-tools.js`
|
|
57
|
+
and register through `registerItsaTools(server, session)`.
|
|
58
|
+
|
|
59
|
+
## Test
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
npm --prefix mcp test
|
|
63
|
+
npm --prefix mcp run test:system
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`test:system` starts `npm run start:simulator` from the repository root, grants a bundle, then runs `list_vat_obligations`, `submit_vat_return` and `get_vat_receipt` against it, using whichever open obligation the simulator answers.
|
|
67
|
+
|
|
68
|
+
The tests open the BrickWork Pro Ltd and Precision Code Ltd example books under `test/fixtures/`
|
|
69
|
+
(copies of the spreadsheets repository's `examples/`) and round-trip each through the three
|
|
70
|
+
formats that need no template; the ITSA tests open the BrickWork Pro self-employed VAT book
|
|
71
|
+
(`examples/brickwork-pro/se-vat`) and check the quarterly running totals and the annual field set
|
|
72
|
+
by tax year.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
|
|
3
|
+
// Copyright (C) 2006-2026 DIY Accounting Limited
|
|
4
|
+
|
|
5
|
+
// diya-submit-mcp.js -- the stdio surface of the submission MCP: the same
|
|
6
|
+
// server lib/server.js builds, connected to stdin and stdout. Point an MCP
|
|
7
|
+
// client at this command with no arguments.
|
|
8
|
+
//
|
|
9
|
+
// --all-clients <tool> [--arg key=value ...] is a one-shot mode instead: it runs run_for_clients
|
|
10
|
+
// (batch-tools.js) for the given tool across every one of the practice's clients, prints one line
|
|
11
|
+
// per client to stdout, and exits non-zero if any client's run was not ok. No stdio server starts
|
|
12
|
+
// in this mode.
|
|
13
|
+
|
|
14
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
15
|
+
|
|
16
|
+
import { runForClients } from "../lib/batch-tools.js";
|
|
17
|
+
import { createSession } from "../lib/book-tools.js";
|
|
18
|
+
import { createServer } from "../lib/server.js";
|
|
19
|
+
|
|
20
|
+
function parseAllClientsArgs(args) {
|
|
21
|
+
const toolIndex = args.indexOf("--all-clients");
|
|
22
|
+
const tool = args[toolIndex + 1];
|
|
23
|
+
if (!tool) {
|
|
24
|
+
throw new Error("--all-clients requires a tool name");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const toolArgs = {};
|
|
28
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
29
|
+
if (args[i] !== "--arg") continue;
|
|
30
|
+
const pair = args[i + 1];
|
|
31
|
+
const separatorIndex = pair ? pair.indexOf("=") : -1;
|
|
32
|
+
if (separatorIndex === -1) {
|
|
33
|
+
throw new Error(`--arg requires key=value, got "${pair ?? ""}"`);
|
|
34
|
+
}
|
|
35
|
+
toolArgs[pair.slice(0, separatorIndex)] = pair.slice(separatorIndex + 1);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return { tool, args: toolArgs };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function runAllClients(args) {
|
|
42
|
+
const { tool, args: toolArgs } = parseAllClientsArgs(args);
|
|
43
|
+
const { rows, summary } = await runForClients(createSession(), { tool, args: toolArgs });
|
|
44
|
+
|
|
45
|
+
for (const row of rows) {
|
|
46
|
+
const outcome = row.ok ? "ok" : `failed: ${row.error}`;
|
|
47
|
+
console.log(`${row.clientId}\t${row.displayName}\t${outcome}`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
process.exitCode = summary.failed > 0 ? 1 : 0;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const cliArgs = process.argv.slice(2);
|
|
54
|
+
if (cliArgs.includes("--all-clients")) {
|
|
55
|
+
try {
|
|
56
|
+
await runAllClients(cliArgs);
|
|
57
|
+
} catch (err) {
|
|
58
|
+
console.error(err?.message ?? String(err));
|
|
59
|
+
process.exitCode = 1;
|
|
60
|
+
}
|
|
61
|
+
} else {
|
|
62
|
+
await createServer().connect(new StdioServerTransport());
|
|
63
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
|
|
2
|
+
// Copyright (C) 2006-2026 DIY Accounting Limited
|
|
3
|
+
|
|
4
|
+
// accounts-tools.js -- derive_micro_entity_accounts: the seven FRS 105
|
|
5
|
+
// balance-sheet lines the accounts filing takes. The derivation lives in
|
|
6
|
+
// app/services/microEntityAccounts.js, shared with the nightly company
|
|
7
|
+
// book pull; this file re-exports it for the MCP tool registration.
|
|
8
|
+
|
|
9
|
+
export {
|
|
10
|
+
BALANCE_SHEET_LINES,
|
|
11
|
+
linesFromPublishedBalanceSheet,
|
|
12
|
+
linesFromOpeningBalance,
|
|
13
|
+
roundForFiling,
|
|
14
|
+
profitAndLossFromPublishedAccount,
|
|
15
|
+
deriveMicroEntityAccounts,
|
|
16
|
+
} from "./vendored/app/services/microEntityAccounts.js";
|
|
17
|
+
|
|
18
|
+
export { deriveSmallCompanyAccounts } from "./vendored/app/services/smallCompanyAccounts.js";
|
package/lib/auth.js
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
// SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
|
|
2
|
+
// Copyright (C) 2006-2026 DIY Accounting Limited
|
|
3
|
+
|
|
4
|
+
// auth.js -- the submission MCP's own stdio sign-in: authorization code with PKCE on a loopback
|
|
5
|
+
// redirect, the flow every CLI uses. signIn() opens the pool's hosted UI with a code challenge,
|
|
6
|
+
// catches the code on the first free port of the loopback listener's range (IdentityStack.java's
|
|
7
|
+
// mcpUserPoolClient, ports 49152 to 49159), exchanges it at the token endpoint, and keeps the
|
|
8
|
+
// refresh token under ~/.config/diya-submit/ mode 600. accessToken() hands out the cached id
|
|
9
|
+
// token, refreshing it silently (no browser) once it is close to expiry. Neither function stores
|
|
10
|
+
// an HMRC or Companies House credential; those are a
|
|
11
|
+
// different tool's own session state (submit-tools.js), never this one's.
|
|
12
|
+
//
|
|
13
|
+
// Configuration comes from the environment: DIYA_SUBMIT_AUTH_DOMAIN (the pool's hosted UI
|
|
14
|
+
// domain, e.g. https://ci-auth.diyaccounting.co.uk) and DIYA_SUBMIT_MCP_CLIENT_ID (the MCP's own
|
|
15
|
+
// app client, IdentityStack.java's mcpUserPoolClient).
|
|
16
|
+
|
|
17
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
18
|
+
import { spawn } from "node:child_process";
|
|
19
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
20
|
+
import { createServer } from "node:http";
|
|
21
|
+
import { homedir } from "node:os";
|
|
22
|
+
import { join } from "node:path";
|
|
23
|
+
|
|
24
|
+
const LOOPBACK_HOST = "127.0.0.1";
|
|
25
|
+
const LOOPBACK_PORT_FIRST = 49152;
|
|
26
|
+
const LOOPBACK_PORT_LAST = 49159;
|
|
27
|
+
const CALLBACK_PATH = "/callback";
|
|
28
|
+
const SCOPES = "email openid profile";
|
|
29
|
+
|
|
30
|
+
// Refresh this long before the cached id token's own expiry, so a call that starts just before
|
|
31
|
+
// it lapses does not race the clock.
|
|
32
|
+
const REFRESH_SKEW_MS = 60_000;
|
|
33
|
+
|
|
34
|
+
function authDomain() {
|
|
35
|
+
const value = process.env.DIYA_SUBMIT_AUTH_DOMAIN;
|
|
36
|
+
if (!value) throw new Error("DIYA_SUBMIT_AUTH_DOMAIN is not set");
|
|
37
|
+
return value.replace(/\/$/, "");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function clientId() {
|
|
41
|
+
const value = process.env.DIYA_SUBMIT_MCP_CLIENT_ID;
|
|
42
|
+
if (!value) throw new Error("DIYA_SUBMIT_MCP_CLIENT_ID is not set");
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function baseUrl() {
|
|
47
|
+
const value = process.env.DIYA_SUBMIT_BASE_URL;
|
|
48
|
+
if (!value) throw new Error("DIYA_SUBMIT_BASE_URL is not set");
|
|
49
|
+
return value.replace(/\/$/, "");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Overridable for tests only; production never sets DIYA_SUBMIT_CONFIG_DIR and always keeps the
|
|
53
|
+
// credentials under the user's own config directory.
|
|
54
|
+
function credentialsDir() {
|
|
55
|
+
return process.env.DIYA_SUBMIT_CONFIG_DIR || join(homedir(), ".config", "diya-submit");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function credentialsPath() {
|
|
59
|
+
return join(credentialsDir(), "credentials.json");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function readCredentials() {
|
|
63
|
+
const path = credentialsPath();
|
|
64
|
+
if (!existsSync(path)) return null;
|
|
65
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function writeCredentials(credentials) {
|
|
69
|
+
const dir = credentialsDir();
|
|
70
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
71
|
+
const path = credentialsPath();
|
|
72
|
+
writeFileSync(path, JSON.stringify(credentials, null, 2), { mode: 0o600 });
|
|
73
|
+
// writeFileSync's mode is still subject to the process umask, so set it again explicitly: the
|
|
74
|
+
// refresh token inside must never be group- or world-readable.
|
|
75
|
+
chmodSync(dir, 0o700);
|
|
76
|
+
chmodSync(path, 0o600);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function base64url(buffer) {
|
|
80
|
+
return buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function newCodeVerifier() {
|
|
84
|
+
return base64url(randomBytes(32));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function codeChallengeFor(verifier) {
|
|
88
|
+
return base64url(createHash("sha256").update(verifier).digest());
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// The command that opens a URL in the operator's default browser, one per platform: darwin's own
|
|
92
|
+
// opener, Windows' shell built-in (which needs an empty-title argument before the URL so `start`
|
|
93
|
+
// does not read the URL itself as a window title), and the freedesktop opener everywhere else.
|
|
94
|
+
const BROWSER_LAUNCH_COMMANDS = {
|
|
95
|
+
darwin: (url) => ({ command: "open", args: [url] }),
|
|
96
|
+
win32: (url) => ({ command: "cmd", args: ["/c", "start", '""', url] }),
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
function openInBrowser(url) {
|
|
100
|
+
const forPlatform = BROWSER_LAUNCH_COMMANDS[process.platform] || ((u) => ({ command: "xdg-open", args: [u] }));
|
|
101
|
+
const { command, args } = forPlatform(url);
|
|
102
|
+
try {
|
|
103
|
+
spawn(command, args, { stdio: "ignore", detached: true }).unref();
|
|
104
|
+
} catch {
|
|
105
|
+
// The caller always prints the URL too; a launch failure (e.g. a headless machine) is not
|
|
106
|
+
// fatal, the operator opens the printed link themselves.
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Binds the first free port in the loopback range, starting from LOOPBACK_PORT_FIRST (or the port
|
|
112
|
+
* passed in, for a retry). This listener answers exactly one request in its whole life, so
|
|
113
|
+
* keep-alive only risks a socket a later signIn() on the same port could inherit stale; disabled
|
|
114
|
+
* outright rather than reasoned about.
|
|
115
|
+
* @returns {Promise<{server: import("node:http").Server, port: number}>}
|
|
116
|
+
*/
|
|
117
|
+
function bindLoopbackServer(port = LOOPBACK_PORT_FIRST) {
|
|
118
|
+
return new Promise((resolve, reject) => {
|
|
119
|
+
const server = createServer();
|
|
120
|
+
server.keepAliveTimeout = 0;
|
|
121
|
+
server.once("error", (err) => {
|
|
122
|
+
if (err.code === "EADDRINUSE" && port < LOOPBACK_PORT_LAST) {
|
|
123
|
+
resolve(bindLoopbackServer(port + 1));
|
|
124
|
+
} else {
|
|
125
|
+
reject(err);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
server.once("listening", () => resolve({ server, port }));
|
|
129
|
+
server.listen(port, LOOPBACK_HOST);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The html response the loopback listener sends the browser once, whichever way the hosted UI's
|
|
135
|
+
* callback answered.
|
|
136
|
+
*/
|
|
137
|
+
function respondToCallback(res, error) {
|
|
138
|
+
res.writeHead(200, { "Content-Type": "text/html", "Connection": "close" });
|
|
139
|
+
const message = error ? `Sign-in failed: ${error}. You can close this window.` : "Signed in. You can close this window.";
|
|
140
|
+
res.end(`<p>${message}</p>`);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function settledCodeFrom({ error, code, state, expectedState }) {
|
|
144
|
+
if (error) throw new Error(`The hosted UI reported an error: ${error}`);
|
|
145
|
+
if (state !== expectedState) throw new Error("The hosted UI's callback state did not match; sign-in was refused");
|
|
146
|
+
if (!code) throw new Error("The hosted UI's callback carried no authorization code");
|
|
147
|
+
return code;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Resolves once the hosted UI's callback request arrives on this server (or rejects on a state
|
|
152
|
+
* mismatch or an error the hosted UI reports), then closes the server: it answers exactly one
|
|
153
|
+
* request.
|
|
154
|
+
* @param {import("node:http").Server} server
|
|
155
|
+
* @param {number} port
|
|
156
|
+
* @param {string} expectedState
|
|
157
|
+
* @returns {Promise<string>}
|
|
158
|
+
*/
|
|
159
|
+
function waitForCallback(server, port, expectedState) {
|
|
160
|
+
return new Promise((resolve, reject) => {
|
|
161
|
+
server.on("request", (req, res) => {
|
|
162
|
+
const url = new URL(req.url, `http://${LOOPBACK_HOST}:${port}`);
|
|
163
|
+
if (url.pathname !== CALLBACK_PATH) {
|
|
164
|
+
res.writeHead(404).end();
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const error = url.searchParams.get("error");
|
|
168
|
+
const code = url.searchParams.get("code");
|
|
169
|
+
const state = url.searchParams.get("state");
|
|
170
|
+
respondToCallback(res, error);
|
|
171
|
+
server.close();
|
|
172
|
+
try {
|
|
173
|
+
resolve(settledCodeFrom({ error, code, state, expectedState }));
|
|
174
|
+
} catch (settleError) {
|
|
175
|
+
reject(settleError);
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Binds the first free port in the loopback range and answers with the bound redirect URI plus a
|
|
183
|
+
* function that waits for the hosted UI's callback request on that same server.
|
|
184
|
+
* @returns {Promise<{redirectUri: string, waitForCode: (expectedState: string) => Promise<string>}>}
|
|
185
|
+
*/
|
|
186
|
+
async function startLoopbackServer() {
|
|
187
|
+
const { server, port } = await bindLoopbackServer();
|
|
188
|
+
const redirectUri = `http://${LOOPBACK_HOST}:${port}${CALLBACK_PATH}`;
|
|
189
|
+
return { redirectUri, waitForCode: (expectedState) => waitForCallback(server, port, expectedState) };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function requestToken(params) {
|
|
193
|
+
const response = await fetch(`${authDomain()}/oauth2/token`, {
|
|
194
|
+
method: "POST",
|
|
195
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
196
|
+
body: new URLSearchParams(params).toString(),
|
|
197
|
+
});
|
|
198
|
+
const body = await response.json().catch(() => ({}));
|
|
199
|
+
if (!response.ok) {
|
|
200
|
+
throw new Error(body?.error_description || body?.error || `The token endpoint answered HTTP ${response.status}`);
|
|
201
|
+
}
|
|
202
|
+
return body;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function storeTokens(tokens, previousRefreshToken) {
|
|
206
|
+
const refreshToken = tokens.refresh_token || previousRefreshToken;
|
|
207
|
+
// Cognito issues the id and access tokens together with the same lifetime, so one
|
|
208
|
+
// expires_in covers both.
|
|
209
|
+
const expiresAt = Date.now() + tokens.expires_in * 1000;
|
|
210
|
+
const credentials = {
|
|
211
|
+
refreshToken,
|
|
212
|
+
idToken: tokens.id_token,
|
|
213
|
+
idTokenExpiresAt: expiresAt,
|
|
214
|
+
accessToken: tokens.access_token,
|
|
215
|
+
accessTokenExpiresAt: expiresAt,
|
|
216
|
+
};
|
|
217
|
+
writeCredentials(credentials);
|
|
218
|
+
return credentials;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* signIn: opens the pool's hosted UI in the operator's browser with a PKCE code challenge, waits
|
|
223
|
+
* on the loopback listener for the authorization code, exchanges it, and stores the refresh token.
|
|
224
|
+
* A no-argument, interactive, one-time step; accessToken() is what every other tool call uses
|
|
225
|
+
* afterwards.
|
|
226
|
+
* @returns {Promise<{signedIn: true}>}
|
|
227
|
+
*/
|
|
228
|
+
export async function signIn() {
|
|
229
|
+
const verifier = newCodeVerifier();
|
|
230
|
+
const challenge = codeChallengeFor(verifier);
|
|
231
|
+
const state = base64url(randomBytes(16));
|
|
232
|
+
|
|
233
|
+
const { redirectUri, waitForCode } = await startLoopbackServer();
|
|
234
|
+
|
|
235
|
+
const authorizeUrl = new URL(`${authDomain()}/oauth2/authorize`);
|
|
236
|
+
authorizeUrl.searchParams.set("response_type", "code");
|
|
237
|
+
authorizeUrl.searchParams.set("client_id", clientId());
|
|
238
|
+
authorizeUrl.searchParams.set("redirect_uri", redirectUri);
|
|
239
|
+
authorizeUrl.searchParams.set("scope", SCOPES);
|
|
240
|
+
authorizeUrl.searchParams.set("code_challenge", challenge);
|
|
241
|
+
authorizeUrl.searchParams.set("code_challenge_method", "S256");
|
|
242
|
+
authorizeUrl.searchParams.set("state", state);
|
|
243
|
+
|
|
244
|
+
console.error(`Opening the hosted UI to sign in. If it does not open, visit:\n${authorizeUrl.toString()}`);
|
|
245
|
+
openInBrowser(authorizeUrl.toString());
|
|
246
|
+
|
|
247
|
+
const code = await waitForCode(state);
|
|
248
|
+
const tokens = await requestToken({
|
|
249
|
+
grant_type: "authorization_code",
|
|
250
|
+
client_id: clientId(),
|
|
251
|
+
code,
|
|
252
|
+
redirect_uri: redirectUri,
|
|
253
|
+
code_verifier: verifier,
|
|
254
|
+
});
|
|
255
|
+
storeTokens(tokens);
|
|
256
|
+
return { signedIn: true };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Reads the stored credentials, refreshing them (a silent, no-browser token-endpoint call)
|
|
261
|
+
* whenever the requested token has less than REFRESH_SKEW_MS left, or none is cached yet.
|
|
262
|
+
* @param {"idToken"|"accessToken"} tokenField
|
|
263
|
+
* @param {"idTokenExpiresAt"|"accessTokenExpiresAt"} expiresAtField
|
|
264
|
+
* @returns {Promise<string>}
|
|
265
|
+
*/
|
|
266
|
+
async function cachedOrRefreshed(tokenField, expiresAtField) {
|
|
267
|
+
const credentials = readCredentials();
|
|
268
|
+
if (!credentials?.refreshToken) {
|
|
269
|
+
throw new Error("Not signed in to DIY Accounting Submit. Run signIn() first.");
|
|
270
|
+
}
|
|
271
|
+
if (credentials[tokenField] && credentials[expiresAtField] > Date.now() + REFRESH_SKEW_MS) {
|
|
272
|
+
return credentials[tokenField];
|
|
273
|
+
}
|
|
274
|
+
const tokens = await requestToken({
|
|
275
|
+
grant_type: "refresh_token",
|
|
276
|
+
client_id: clientId(),
|
|
277
|
+
refresh_token: credentials.refreshToken,
|
|
278
|
+
});
|
|
279
|
+
const updated = storeTokens(tokens, credentials.refreshToken);
|
|
280
|
+
return updated[tokenField];
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* idToken: the id token book-tools.js sends on for the cloud book routes (their native JWT
|
|
285
|
+
* authoriser accepts either an access token's client_id or an id token's aud claim). Answers
|
|
286
|
+
* the cached one while it still has more than REFRESH_SKEW_MS left, otherwise refreshes first.
|
|
287
|
+
* @returns {Promise<string>}
|
|
288
|
+
*/
|
|
289
|
+
export async function idToken() {
|
|
290
|
+
return cachedOrRefreshed("idToken", "idTokenExpiresAt");
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* accessToken: the MCP's own Cognito access token, for the custom Lambda authoriser's
|
|
295
|
+
* X-Authorization header (submit-tools.js's HMRC and Companies House calls) and for the plain
|
|
296
|
+
* Authorization header the sign-out route's all-clients JWT authoriser reads. Answers the
|
|
297
|
+
* cached one while it still has more than REFRESH_SKEW_MS left, otherwise refreshes first.
|
|
298
|
+
* @returns {Promise<string>}
|
|
299
|
+
*/
|
|
300
|
+
export async function accessToken() {
|
|
301
|
+
return cachedOrRefreshed("accessToken", "accessTokenExpiresAt");
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* storedCredentials: the credentials a stdio session carries, the file-backed pair above.
|
|
306
|
+
*/
|
|
307
|
+
export const storedCredentials = { accessToken, idToken };
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* signOut: revokes the refresh token at Cognito, tells the authenticated sign-out route to
|
|
311
|
+
* publish "logout" and delete the session item, then deletes the local credentials file.
|
|
312
|
+
* Best-effort on the network calls -- a revoke or sign-out failure (offline, an already-expired
|
|
313
|
+
* token) still leaves the local credentials gone, since the whole point is that this machine no
|
|
314
|
+
* longer holds a usable session.
|
|
315
|
+
* @returns {Promise<{signedOut: true}>}
|
|
316
|
+
*/
|
|
317
|
+
export async function signOut() {
|
|
318
|
+
const credentials = readCredentials();
|
|
319
|
+
|
|
320
|
+
if (credentials?.refreshToken) {
|
|
321
|
+
try {
|
|
322
|
+
await fetch(`${authDomain()}/oauth2/revoke`, {
|
|
323
|
+
method: "POST",
|
|
324
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
325
|
+
body: new URLSearchParams({ token: credentials.refreshToken, client_id: clientId() }).toString(),
|
|
326
|
+
});
|
|
327
|
+
} catch (error) {
|
|
328
|
+
console.error(`Revoking the refresh token failed (continuing sign-out): ${error.message}`);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
if (credentials?.accessToken) {
|
|
333
|
+
try {
|
|
334
|
+
await fetch(`${baseUrl()}/api/v1/session/sign-out`, {
|
|
335
|
+
method: "POST",
|
|
336
|
+
headers: { Authorization: `Bearer ${credentials.accessToken}` },
|
|
337
|
+
});
|
|
338
|
+
} catch (error) {
|
|
339
|
+
console.error(`Calling the sign-out route failed (continuing sign-out): ${error.message}`);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const path = credentialsPath();
|
|
344
|
+
if (existsSync(path)) unlinkSync(path);
|
|
345
|
+
|
|
346
|
+
return { signedOut: true };
|
|
347
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
|
|
2
|
+
// Copyright (C) 2006-2026 DIY Accounting Limited
|
|
3
|
+
|
|
4
|
+
// batch-tools.js -- run_for_clients: one client-scoped tool, run once per client in the
|
|
5
|
+
// practice's own list (practice-tools.js's listClients), collecting one result row per client.
|
|
6
|
+
// The allow-list is exactly the tools that take a clientId to act on one client at a time --
|
|
7
|
+
// the four submission tools (submit-tools.js) and the two book tools (book-tools.js) -- not
|
|
8
|
+
// practice-tools.js's own client-management tools (list_clients has no clientId to loop over;
|
|
9
|
+
// add_client creates a client rather than acting on an existing one; invite_client and
|
|
10
|
+
// client_authorisation_status already take one clientId per call by design, so looping them
|
|
11
|
+
// over every client would invite an authorisation request or a status check nobody asked for).
|
|
12
|
+
//
|
|
13
|
+
// A failure for one client is carried in that client's row, never thrown; run_for_clients throws
|
|
14
|
+
// only when the client list itself cannot be read, since without it there is nothing to loop over.
|
|
15
|
+
|
|
16
|
+
import { openBook, saveBook } from "./book-tools.js";
|
|
17
|
+
import { listClients } from "./practice-tools.js";
|
|
18
|
+
import { listVatObligations, submitVatReturn, getVatReceipt, submitMicroEntityAccounts } from "./submit-tools.js";
|
|
19
|
+
|
|
20
|
+
const HANDLERS = {
|
|
21
|
+
list_vat_obligations: listVatObligations,
|
|
22
|
+
submit_vat_return: submitVatReturn,
|
|
23
|
+
get_vat_receipt: getVatReceipt,
|
|
24
|
+
submit_micro_entity_accounts: submitMicroEntityAccounts,
|
|
25
|
+
open_book: openBook,
|
|
26
|
+
save_book: saveBook,
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export const RUN_FOR_CLIENTS_TOOLS = Object.keys(HANDLERS);
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* run_for_clients: lists the practice's own clients, then calls the chosen tool once per client
|
|
33
|
+
* with that client's clientId merged into args (args' own clientId, if given, is overridden -- the
|
|
34
|
+
* point of this tool is to run for every client, not to repeat one). Each call's outcome becomes
|
|
35
|
+
* one row; a rejected call becomes {ok: false, error}, never a thrown error, so one client's
|
|
36
|
+
* failure never stops the rest.
|
|
37
|
+
* @param {Object} session - passed through to each per-client call unchanged
|
|
38
|
+
* @param {{tool: string, args?: Object}} params
|
|
39
|
+
* @returns {Promise<{tool: string, rows: Array<{clientId: string, displayName: string, ok: boolean, result?: *, error?: string}>, summary: {total: number, ok: number, failed: number}}>}
|
|
40
|
+
*/
|
|
41
|
+
export async function runForClients(session, { tool, args = {} } = {}) {
|
|
42
|
+
const handler = HANDLERS[tool];
|
|
43
|
+
if (!handler) {
|
|
44
|
+
throw new Error(`run_for_clients does not support tool "${tool}"; must be one of ${RUN_FOR_CLIENTS_TOOLS.join(", ")}`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const { clients } = await listClients(session, {});
|
|
48
|
+
|
|
49
|
+
const rows = [];
|
|
50
|
+
for (const client of clients) {
|
|
51
|
+
try {
|
|
52
|
+
const result = await handler(session, { ...args, clientId: client.clientId });
|
|
53
|
+
rows.push({ clientId: client.clientId, displayName: client.displayName, ok: true, result });
|
|
54
|
+
} catch (err) {
|
|
55
|
+
rows.push({ clientId: client.clientId, displayName: client.displayName, ok: false, error: err?.message ?? String(err) });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const okCount = rows.filter((row) => row.ok).length;
|
|
60
|
+
return { tool, rows, summary: { total: rows.length, ok: okCount, failed: rows.length - okCount } };
|
|
61
|
+
}
|