@sielay/freeagent-mcp 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/LICENSE +21 -0
- package/README.md +292 -2
- package/SECURITY.md +115 -0
- package/dist/bin/cli.d.ts +2 -0
- package/dist/bin/cli.js +186 -0
- package/dist/bin/cli.js.map +1 -0
- package/dist/bin/db.d.ts +12 -0
- package/dist/bin/db.js +34 -0
- package/dist/bin/db.js.map +1 -0
- package/dist/config/env.d.ts +42 -0
- package/dist/config/env.js +117 -0
- package/dist/config/env.js.map +1 -0
- package/dist/config/errors.d.ts +9 -0
- package/dist/config/errors.js +13 -0
- package/dist/config/errors.js.map +1 -0
- package/dist/config/http.d.ts +42 -0
- package/dist/config/http.js +140 -0
- package/dist/config/http.js.map +1 -0
- package/dist/core/format.d.ts +26 -0
- package/dist/core/format.js +121 -0
- package/dist/core/format.js.map +1 -0
- package/dist/core/pagination.d.ts +24 -0
- package/dist/core/pagination.js +80 -0
- package/dist/core/pagination.js.map +1 -0
- package/dist/core/schemas.d.ts +20 -0
- package/dist/core/schemas.js +41 -0
- package/dist/core/schemas.js.map +1 -0
- package/dist/core/server.d.ts +38 -0
- package/dist/core/server.js +102 -0
- package/dist/core/server.js.map +1 -0
- package/dist/core/tool.d.ts +26 -0
- package/dist/core/tool.js +11 -0
- package/dist/core/tool.js.map +1 -0
- package/dist/core/tools/accounting.d.ts +35 -0
- package/dist/core/tools/accounting.js +174 -0
- package/dist/core/tools/accounting.js.map +1 -0
- package/dist/core/tools/bank-accounts.d.ts +8 -0
- package/dist/core/tools/bank-accounts.js +35 -0
- package/dist/core/tools/bank-accounts.js.map +1 -0
- package/dist/core/tools/bank-transactions.d.ts +21 -0
- package/dist/core/tools/bank-transactions.js +135 -0
- package/dist/core/tools/bank-transactions.js.map +1 -0
- package/dist/core/tools/company.d.ts +2 -0
- package/dist/core/tools/company.js +31 -0
- package/dist/core/tools/company.js.map +1 -0
- package/dist/core/tools/contacts.d.ts +20 -0
- package/dist/core/tools/contacts.js +82 -0
- package/dist/core/tools/contacts.js.map +1 -0
- package/dist/core/tools/index.d.ts +3 -0
- package/dist/core/tools/index.js +28 -0
- package/dist/core/tools/index.js.map +1 -0
- package/dist/core/tools/invoices-bills.d.ts +51 -0
- package/dist/core/tools/invoices-bills.js +217 -0
- package/dist/core/tools/invoices-bills.js.map +1 -0
- package/dist/crypto/encoding.d.ts +10 -0
- package/dist/crypto/encoding.js +55 -0
- package/dist/crypto/encoding.js.map +1 -0
- package/dist/crypto/keyring.d.ts +31 -0
- package/dist/crypto/keyring.js +88 -0
- package/dist/crypto/keyring.js.map +1 -0
- package/dist/crypto/tokens.d.ts +19 -0
- package/dist/crypto/tokens.js +32 -0
- package/dist/crypto/tokens.js.map +1 -0
- package/dist/freeagent/client.d.ts +43 -0
- package/dist/freeagent/client.js +138 -0
- package/dist/freeagent/client.js.map +1 -0
- package/dist/freeagent/company.d.ts +16 -0
- package/dist/freeagent/company.js +34 -0
- package/dist/freeagent/company.js.map +1 -0
- package/dist/freeagent/endpoints.d.ts +8 -0
- package/dist/freeagent/endpoints.js +17 -0
- package/dist/freeagent/endpoints.js.map +1 -0
- package/dist/freeagent/http.d.ts +2 -0
- package/dist/freeagent/http.js +6 -0
- package/dist/freeagent/http.js.map +1 -0
- package/dist/freeagent/oauth.d.ts +27 -0
- package/dist/freeagent/oauth.js +84 -0
- package/dist/freeagent/oauth.js.map +1 -0
- package/dist/http/context.d.ts +26 -0
- package/dist/http/context.js +26 -0
- package/dist/http/context.js.map +1 -0
- package/dist/http/db-token-source.d.ts +25 -0
- package/dist/http/db-token-source.js +83 -0
- package/dist/http/db-token-source.js.map +1 -0
- package/dist/http/grants.d.ts +7 -0
- package/dist/http/grants.js +22 -0
- package/dist/http/grants.js.map +1 -0
- package/dist/http/handler.d.ts +21 -0
- package/dist/http/handler.js +100 -0
- package/dist/http/handler.js.map +1 -0
- package/dist/http/mcp.d.ts +3 -0
- package/dist/http/mcp.js +76 -0
- package/dist/http/mcp.js.map +1 -0
- package/dist/http/oauth.d.ts +15 -0
- package/dist/http/oauth.js +436 -0
- package/dist/http/oauth.js.map +1 -0
- package/dist/http/response.d.ts +40 -0
- package/dist/http/response.js +130 -0
- package/dist/http/response.js.map +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/local/login.d.ts +23 -0
- package/dist/local/login.js +41 -0
- package/dist/local/login.js.map +1 -0
- package/dist/local/loopback.d.ts +7 -0
- package/dist/local/loopback.js +66 -0
- package/dist/local/loopback.js.map +1 -0
- package/dist/local/stdio.d.ts +14 -0
- package/dist/local/stdio.js +72 -0
- package/dist/local/stdio.js.map +1 -0
- package/dist/local/token-source.d.ts +21 -0
- package/dist/local/token-source.js +44 -0
- package/dist/local/token-source.js.map +1 -0
- package/dist/logging/logger.d.ts +22 -0
- package/dist/logging/logger.js +73 -0
- package/dist/logging/logger.js.map +1 -0
- package/dist/ops.d.ts +14 -0
- package/dist/ops.js +30 -0
- package/dist/ops.js.map +1 -0
- package/dist/store/migrate.d.ts +7 -0
- package/dist/store/migrate.js +24 -0
- package/dist/store/migrate.js.map +1 -0
- package/dist/store/pg.d.ts +26 -0
- package/dist/store/pg.js +59 -0
- package/dist/store/pg.js.map +1 -0
- package/dist/store/postgres.d.ts +41 -0
- package/dist/store/postgres.js +288 -0
- package/dist/store/postgres.js.map +1 -0
- package/dist/store/sql.d.ts +29 -0
- package/dist/store/sql.js +46 -0
- package/dist/store/sql.js.map +1 -0
- package/dist/store/token-file.d.ts +16 -0
- package/dist/store/token-file.js +121 -0
- package/dist/store/token-file.js.map +1 -0
- package/dist/store/types.d.ts +137 -0
- package/dist/store/types.js +2 -0
- package/dist/store/types.js.map +1 -0
- package/migrations/001_init.sql +102 -0
- package/package.json +74 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lukasz Sielski
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,293 @@
|
|
|
1
|
-
#
|
|
1
|
+
# FreeAgent MCP server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@sielay/freeagent-mcp` lets Claude read one company's
|
|
4
|
+
[FreeAgent](https://www.freeagent.com) books through the
|
|
5
|
+
[Model Context Protocol](https://modelcontextprotocol.io) (MCP).
|
|
6
|
+
|
|
7
|
+
- **Read-only.** Version 0.1 has 18 tools and none of them can change
|
|
8
|
+
your books.
|
|
9
|
+
- **One company.** Each install is locked to one FreeAgent company ID.
|
|
10
|
+
The server refuses to sign in to any other company.
|
|
11
|
+
- **Two ways to run it:**
|
|
12
|
+
- On your own computer over stdio, for Claude Code and Claude Desktop.
|
|
13
|
+
- On Vercel as a remote connector for claude.ai, with its own OAuth 2.1
|
|
14
|
+
sign-in and a Postgres database.
|
|
15
|
+
- **Sandbox first.** The server uses the FreeAgent sandbox unless you set
|
|
16
|
+
`FREEAGENT_ENV=production`.
|
|
17
|
+
|
|
18
|
+
For the security design, see [SECURITY.md](SECURITY.md). For how this
|
|
19
|
+
package differs from
|
|
20
|
+
[WavingCatApps/freeagent-mcp-vercel](https://github.com/WavingCatApps/freeagent-mcp-vercel),
|
|
21
|
+
see [Why this package](docs/why-this-package.md).
|
|
22
|
+
|
|
23
|
+
## Contents
|
|
24
|
+
|
|
25
|
+
- [Before you start](#before-you-start)
|
|
26
|
+
- [Quick start: your own computer](#quick-start-your-own-computer)
|
|
27
|
+
- [Deploy to Vercel](#deploy-to-vercel)
|
|
28
|
+
- [Connect Claude](#connect-claude)
|
|
29
|
+
- [Tools](#tools)
|
|
30
|
+
- [Environment variables](#environment-variables)
|
|
31
|
+
- [Command line](#command-line)
|
|
32
|
+
- [Rotate the encryption key](#rotate-the-encryption-key)
|
|
33
|
+
- [Emergency revoke](#emergency-revoke)
|
|
34
|
+
- [Use it as a library](#use-it-as-a-library)
|
|
35
|
+
- [Develop](#develop)
|
|
36
|
+
|
|
37
|
+
## Before you start
|
|
38
|
+
|
|
39
|
+
You need:
|
|
40
|
+
|
|
41
|
+
- Node.js 22 or later.
|
|
42
|
+
- A FreeAgent developer app from [dev.freeagent.com](https://dev.freeagent.com).
|
|
43
|
+
Start with sandbox credentials.
|
|
44
|
+
- Your numeric FreeAgent company ID. The `login --discover` command
|
|
45
|
+
prints it.
|
|
46
|
+
|
|
47
|
+
Reports such as profit and loss need the FreeAgent user who signs in to
|
|
48
|
+
have the **Tax, Accounting and Users** access level.
|
|
49
|
+
|
|
50
|
+
## Quick start: your own computer
|
|
51
|
+
|
|
52
|
+
1. In your FreeAgent app, add this redirect URI:
|
|
53
|
+
|
|
54
|
+
```text
|
|
55
|
+
http://127.0.0.1:53682/callback
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
2. Find your company ID. This command signs in, prints the ID, and stores
|
|
59
|
+
nothing:
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
FREEAGENT_CLIENT_ID=… FREEAGENT_CLIENT_SECRET=… \
|
|
63
|
+
npx -y @sielay/freeagent-mcp login --discover
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
3. Generate an encryption key for the local token file:
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
echo "v1:$(openssl rand -base64 32)"
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Store the key in your password manager. Without it, the token file
|
|
73
|
+
cannot be read.
|
|
74
|
+
|
|
75
|
+
4. Sign in and save the tokens:
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
FREEAGENT_CLIENT_ID=… FREEAGENT_CLIENT_SECRET=… \
|
|
79
|
+
ALLOWED_FREEAGENT_COMPANY_ID=… TOKEN_ENCRYPTION_KEYS='v1:…' \
|
|
80
|
+
npx -y @sielay/freeagent-mcp login
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
The tokens go to `~/.config/freeagent-mcp/tokens.enc`, encrypted, with
|
|
84
|
+
file mode `600`.
|
|
85
|
+
|
|
86
|
+
5. Add the server to Claude Code:
|
|
87
|
+
|
|
88
|
+
```sh
|
|
89
|
+
claude mcp add freeagent \
|
|
90
|
+
-e FREEAGENT_CLIENT_ID=… \
|
|
91
|
+
-e FREEAGENT_CLIENT_SECRET=… \
|
|
92
|
+
-e ALLOWED_FREEAGENT_COMPANY_ID=… \
|
|
93
|
+
-e TOKEN_ENCRYPTION_KEYS='v1:…' \
|
|
94
|
+
-- npx -y @sielay/freeagent-mcp
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
For Claude Desktop, add the same command and variables to
|
|
98
|
+
`claude_desktop_config.json`.
|
|
99
|
+
|
|
100
|
+
## Deploy to Vercel
|
|
101
|
+
|
|
102
|
+
The [Vercel example](examples/vercel/) runs the server as one Vercel
|
|
103
|
+
Function in London (`lhr1`), backed by Neon Postgres. One deployment serves
|
|
104
|
+
one FreeAgent company.
|
|
105
|
+
|
|
106
|
+
[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsielay%2Ffreeagent-mcp%2Ftree%2Fmain%2Fexamples%2Fvercel&env=PUBLIC_BASE_URL,FREEAGENT_CLIENT_ID,FREEAGENT_CLIENT_SECRET,ALLOWED_FREEAGENT_COMPANY_ID,TOKEN_ENCRYPTION_KEYS,DATABASE_URL,CRON_SECRET&envDescription=See%20examples%2Fvercel%2F.env.example&project-name=freeagent-mcp)
|
|
107
|
+
|
|
108
|
+
The example's [README](examples/vercel/README.md) covers each step:
|
|
109
|
+
|
|
110
|
+
1. Create the FreeAgent app with `https://<your-domain>/oauth/callback`
|
|
111
|
+
as its redirect URI.
|
|
112
|
+
2. Create a Neon database in `aws-eu-west-2` and run `migrate`.
|
|
113
|
+
3. Add every variable as a **Sensitive** variable scoped to Production.
|
|
114
|
+
4. Turn on Deployment Protection for Preview deployments.
|
|
115
|
+
5. Add the Firewall rate-limit rules.
|
|
116
|
+
|
|
117
|
+
Use your own custom domain as `PUBLIC_BASE_URL`, never a `*.vercel.app`
|
|
118
|
+
deployment URL. The domain is part of every token's audience.
|
|
119
|
+
|
|
120
|
+
## Connect Claude
|
|
121
|
+
|
|
122
|
+
### claude.ai and Claude Desktop (remote)
|
|
123
|
+
|
|
124
|
+
1. Open **Settings → Connectors → Add custom connector**.
|
|
125
|
+
2. Enter `https://<your-domain>/mcp`.
|
|
126
|
+
3. Select **Connect**. Claude registers itself, then shows this server's
|
|
127
|
+
consent page.
|
|
128
|
+
4. Select **Allow**. You go to FreeAgent to sign in.
|
|
129
|
+
5. Sign in to the company that matches `ALLOWED_FREEAGENT_COMPANY_ID`.
|
|
130
|
+
Any other company is refused, and its tokens are discarded.
|
|
131
|
+
|
|
132
|
+
### Recommended tool permissions
|
|
133
|
+
|
|
134
|
+
All 18 tools are read-only, but some return personal data.
|
|
135
|
+
|
|
136
|
+
- Keep the report tools (`get_profit_and_loss`, `get_balance_sheet`,
|
|
137
|
+
`get_trial_balance`, `list_vat_returns`, `get_vat_return`) on **Always
|
|
138
|
+
allow**.
|
|
139
|
+
- Set `list_contacts`, `get_contact`, and the bank transaction tools to
|
|
140
|
+
**Needs approval** if the chat might be shared.
|
|
141
|
+
- Turn off any tool you do not use. Fewer tools also means a shorter
|
|
142
|
+
tool list for the model.
|
|
143
|
+
|
|
144
|
+
## Tools
|
|
145
|
+
|
|
146
|
+
Every tool returns a summary line first, then compact rows. Tools that
|
|
147
|
+
list records accept `limit` (1–200, default 50) and return a `next_cursor`
|
|
148
|
+
when more rows exist. Money totals are exact and kept per currency.
|
|
149
|
+
|
|
150
|
+
| Tool | Returns |
|
|
151
|
+
|---|---|
|
|
152
|
+
| `get_company` | Company name, ID, type, currency, registration, and VAT status |
|
|
153
|
+
| `list_bank_accounts` | Bank accounts and balances, by account type |
|
|
154
|
+
| `list_bank_transactions` | Transactions for one account, by date, optionally unexplained only |
|
|
155
|
+
| `get_bank_transaction` | One transaction with its explanations |
|
|
156
|
+
| `list_bank_transaction_explanations` | Explanations for one account, by date |
|
|
157
|
+
| `list_contacts` | Contacts by view, optionally changed since a time |
|
|
158
|
+
| `get_contact` | One contact |
|
|
159
|
+
| `list_invoices` | Invoices by view, contact, and date, with totals per currency |
|
|
160
|
+
| `get_invoice` | One invoice with line items |
|
|
161
|
+
| `list_bills` | Bills by view, supplier, and date |
|
|
162
|
+
| `get_bill` | One bill with line items |
|
|
163
|
+
| `list_expenses` | Expenses by date, with totals per currency |
|
|
164
|
+
| `list_categories` | Accounting categories by group, optionally with sub-accounts |
|
|
165
|
+
| `get_profit_and_loss` | Profit and loss for dates or an accounting year |
|
|
166
|
+
| `get_balance_sheet` | Balance sheet at a date |
|
|
167
|
+
| `get_trial_balance` | Trial balance for a period |
|
|
168
|
+
| `list_vat_returns` | VAT returns by status |
|
|
169
|
+
| `get_vat_return` | One VAT return with its nine boxes |
|
|
170
|
+
|
|
171
|
+
FreeAgent cannot filter invoices by date, so `list_invoices` filters
|
|
172
|
+
locally. It reads at most 10 pages per call and says so when it stops.
|
|
173
|
+
|
|
174
|
+
Write tools are not part of version 0.1. The `ENABLE_WRITE_TOOLS` and
|
|
175
|
+
`ENABLE_CLIENT_FACING_WRITES` flags exist so that later versions can add
|
|
176
|
+
them switched off by default.
|
|
177
|
+
|
|
178
|
+
## Environment variables
|
|
179
|
+
|
|
180
|
+
The server checks every variable at start-up. If any value is wrong, it
|
|
181
|
+
refuses to start and names the variable without printing its value.
|
|
182
|
+
|
|
183
|
+
| Variable | Used by | Default | Notes |
|
|
184
|
+
|---|---|---|---|
|
|
185
|
+
| `FREEAGENT_CLIENT_ID` | both | required | From your FreeAgent app. |
|
|
186
|
+
| `FREEAGENT_CLIENT_SECRET` | both | required | From your FreeAgent app. |
|
|
187
|
+
| `ALLOWED_FREEAGENT_COMPANY_ID` | both | required | Numeric. `login --discover` prints it. |
|
|
188
|
+
| `FREEAGENT_ENV` | both | `sandbox` | Set `production` to use real books. |
|
|
189
|
+
| `TOKEN_ENCRYPTION_KEYS` | both | required | Comma-separated `v<n>:<base64 32 bytes>`. The highest version encrypts. Local mode can skip it when it uses `FREEAGENT_REFRESH_TOKEN`. |
|
|
190
|
+
| `FREEAGENT_TIMEOUT_MS` | both | `15000` | Timeout for each FreeAgent call. |
|
|
191
|
+
| `LOG_LEVEL` | both | `info` | `debug`, `info`, `warn`, or `error`. Logs go to stderr. |
|
|
192
|
+
| `ENABLE_WRITE_TOOLS` | both | `false` | No write tools exist yet. |
|
|
193
|
+
| `ENABLE_CLIENT_FACING_WRITES` | both | `false` | Ignored unless write tools are on. |
|
|
194
|
+
| `FREEAGENT_TOKEN_FILE` | local | `~/.config/freeagent-mcp/tokens.enc` | Encrypted token file. |
|
|
195
|
+
| `FREEAGENT_LOCAL_PORT` | local | `53682` | Loopback port for `login`. |
|
|
196
|
+
| `FREEAGENT_REFRESH_TOKEN` | local | none | Use this token instead of the token file. |
|
|
197
|
+
| `FREEAGENT_ACCESS_TOKEN` | local | none | Optional, with `FREEAGENT_REFRESH_TOKEN`. |
|
|
198
|
+
| `PUBLIC_BASE_URL` | remote | required | `https://` custom domain, no trailing slash. |
|
|
199
|
+
| `DATABASE_URL` | remote | required | Postgres. Neon hosts use Neon's HTTP driver; any other host needs the `pg` package. A remote host needs `sslmode=require` or `verify-full`. |
|
|
200
|
+
| `DATABASE_CA_CERT` | remote | none | PEM of the database's root CA, for `sslmode=verify-full` when Node does not trust it (Supabase). |
|
|
201
|
+
| `CRON_SECRET` | remote | required on Vercel | At least 32 characters. |
|
|
202
|
+
| `ALLOWED_REDIRECT_URIS` | remote | `https://claude.ai/api/mcp/auth_callback` | Comma-separated. Clients may register only these. |
|
|
203
|
+
| `ALLOWED_ORIGINS` | remote | `https://claude.ai,https://claude.com` | Browser origins allowed to call `/mcp`. |
|
|
204
|
+
| `RATE_LIMIT_PER_MINUTE` | remote | `60` | Tool calls per connection per minute, 1–120. |
|
|
205
|
+
| `MAX_CLIENTS` | remote | `50` | Cap on registered clients. |
|
|
206
|
+
| `AUDIT_RETENTION_DAYS` | remote | `90` | Days to keep audit rows, 1–3650. |
|
|
207
|
+
|
|
208
|
+
## Command line
|
|
209
|
+
|
|
210
|
+
```sh
|
|
211
|
+
npx @sielay/freeagent-mcp # run over stdio (default)
|
|
212
|
+
npx @sielay/freeagent-mcp login # sign in and save encrypted tokens
|
|
213
|
+
npx @sielay/freeagent-mcp login --discover # print your company ID, store nothing
|
|
214
|
+
npx @sielay/freeagent-mcp migrate # create or update the database tables
|
|
215
|
+
npx @sielay/freeagent-mcp rotate-keys # re-encrypt stored tokens with the newest key
|
|
216
|
+
npx @sielay/freeagent-mcp revoke-all --yes # end every session, delete every token
|
|
217
|
+
npx @sielay/freeagent-mcp cleanup # delete expired rows and old audit rows
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
`rotate-keys`, `revoke-all`, and `cleanup` act on the database when
|
|
221
|
+
`DATABASE_URL` is set, and on the local token file otherwise.
|
|
222
|
+
|
|
223
|
+
## Rotate the encryption key
|
|
224
|
+
|
|
225
|
+
1. Generate a new key and add it with a higher version, keeping the old
|
|
226
|
+
one:
|
|
227
|
+
|
|
228
|
+
```text
|
|
229
|
+
TOKEN_ENCRYPTION_KEYS=v2:<new key>,v1:<old key>
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
2. Deploy. New tokens now use `v2`.
|
|
233
|
+
3. Re-encrypt every stored token:
|
|
234
|
+
|
|
235
|
+
```sh
|
|
236
|
+
DATABASE_URL=… TOKEN_ENCRYPTION_KEYS='v2:…,v1:…' npx @sielay/freeagent-mcp rotate-keys
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
If the command reports changed grants, run it again. It skips a grant
|
|
240
|
+
that refreshed during the run rather than overwrite it.
|
|
241
|
+
4. Remove `v1` from `TOKEN_ENCRYPTION_KEYS` and deploy again.
|
|
242
|
+
|
|
243
|
+
## Emergency revoke
|
|
244
|
+
|
|
245
|
+
If you suspect a leak:
|
|
246
|
+
|
|
247
|
+
1. End every session and delete every stored FreeAgent token:
|
|
248
|
+
|
|
249
|
+
```sh
|
|
250
|
+
DATABASE_URL=… npx @sielay/freeagent-mcp revoke-all --yes
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
2. In FreeAgent's settings, remove the app's access. FreeAgent has no
|
|
254
|
+
documented API to revoke it.
|
|
255
|
+
3. Rotate the FreeAgent client secret at
|
|
256
|
+
[dev.freeagent.com](https://dev.freeagent.com).
|
|
257
|
+
4. Rotate `TOKEN_ENCRYPTION_KEYS` and `CRON_SECRET`.
|
|
258
|
+
5. Reconnect Claude.
|
|
259
|
+
|
|
260
|
+
To end one connection only, send its refresh token to `POST /revoke`
|
|
261
|
+
([RFC 7009](https://www.rfc-editor.org/rfc/rfc7009)). The server deletes
|
|
262
|
+
that connection's tokens and its stored FreeAgent tokens.
|
|
263
|
+
|
|
264
|
+
## Use it as a library
|
|
265
|
+
|
|
266
|
+
```ts
|
|
267
|
+
import { createHttpHandler } from "@sielay/freeagent-mcp";
|
|
268
|
+
|
|
269
|
+
const handler = createHttpHandler(); // reads process.env, fails closed
|
|
270
|
+
export const GET = handler;
|
|
271
|
+
export const POST = handler;
|
|
272
|
+
export const DELETE = handler;
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
The handler takes a Web `Request` and returns a `Response`, so it runs on
|
|
276
|
+
any platform that supports Web-standard handlers. `createFreeAgentServer`
|
|
277
|
+
builds the MCP server alone, for your own transport. A `TokenStore`
|
|
278
|
+
interface lets you replace the Postgres store.
|
|
279
|
+
|
|
280
|
+
## Develop
|
|
281
|
+
|
|
282
|
+
```sh
|
|
283
|
+
npm ci
|
|
284
|
+
TEST_DATABASE_URL=postgres://… npm run check # types, lint, tests, build
|
|
285
|
+
npm run smoke # pack, install into the Vercel example, call it
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Tests that need Postgres are skipped when `TEST_DATABASE_URL` is unset.
|
|
289
|
+
CI always sets it.
|
|
290
|
+
|
|
291
|
+
## Licence
|
|
292
|
+
|
|
293
|
+
[MIT](LICENSE)
|
package/SECURITY.md
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# Security
|
|
2
|
+
|
|
3
|
+
This server gives an AI model read access to a company's accounts. This
|
|
4
|
+
page describes what it protects, how, and what it does not cover.
|
|
5
|
+
|
|
6
|
+
## Report a vulnerability
|
|
7
|
+
|
|
8
|
+
Report vulnerabilities privately through
|
|
9
|
+
[GitHub security advisories](https://github.com/sielay/freeagent-mcp/security/advisories/new).
|
|
10
|
+
Do not open a public issue.
|
|
11
|
+
|
|
12
|
+
Include the version, the steps to reproduce, and the impact you expect.
|
|
13
|
+
You get a reply within 7 days. Fixes go to the latest minor version only.
|
|
14
|
+
|
|
15
|
+
## What the server protects
|
|
16
|
+
|
|
17
|
+
- The company's FreeAgent access and refresh tokens.
|
|
18
|
+
- The MCP tokens that Claude holds.
|
|
19
|
+
- The financial and personal data that the tools return.
|
|
20
|
+
|
|
21
|
+
## Controls
|
|
22
|
+
|
|
23
|
+
Each control links to the code that implements it and the test that
|
|
24
|
+
proves it. Paths are relative to the repository root.
|
|
25
|
+
|
|
26
|
+
### Tokens the server issues
|
|
27
|
+
|
|
28
|
+
| Control | Code | Test |
|
|
29
|
+
|---|---|---|
|
|
30
|
+
| Tokens are 32 random bytes, base64url, with a type prefix (`fam_at_`, `fam_rt_`, `fam_ac_`). | [src/crypto/tokens.ts:16-17](src/crypto/tokens.ts#L16-L17) | [token type confusion](test/http.security.test.ts#L154) |
|
|
31
|
+
| The database stores only the SHA-256 hash of each token. | [src/crypto/tokens.ts:33](src/crypto/tokens.ts#L33) | [stores FreeAgent tokens encrypted](test/http.flow.test.ts#L62) |
|
|
32
|
+
| Access tokens last 1 hour. | [src/http/context.ts:17](src/http/context.ts#L17) | [access token TTL](test/http.security.test.ts#L220) |
|
|
33
|
+
| Refresh tokens rotate on every use, expire after 30 idle days, and a connection ends after 90 days. | [src/http/context.ts:18-19](src/http/context.ts#L18-L19), [src/store/postgres.ts:224-243](src/store/postgres.ts#L224-L243) | [rotation](test/http.security.test.ts#L182), [expiry](test/http.security.test.ts#L208) |
|
|
34
|
+
| Reusing a refresh token, or presenting it from another client, ends the whole connection and deletes its FreeAgent tokens. | [src/store/postgres.ts:254-262](src/store/postgres.ts#L254-L262) | [reuse](test/http.security.test.ts#L190), [another client](test/http.security.test.ts#L201) |
|
|
35
|
+
| `/mcp` accepts only access tokens issued for this server's own resource URL. | [src/http/mcp.ts:31-35](src/http/mcp.ts#L31-L35) | [audience](test/http.security.test.ts#L168) |
|
|
36
|
+
| Revocation ([RFC 7009](https://www.rfc-editor.org/rfc/rfc7009)) deletes the connection and its FreeAgent tokens. | [src/http/oauth.ts:456](src/http/oauth.ts#L456) | [revocation](test/http.security.test.ts#L228), [another client cannot revoke](test/http.security.test.ts#L245) |
|
|
37
|
+
|
|
38
|
+
### Sign-in flow
|
|
39
|
+
|
|
40
|
+
| Control | Code | Test |
|
|
41
|
+
|---|---|---|
|
|
42
|
+
| PKCE with `S256` only. `plain` and missing challenges are refused. | [src/http/oauth.ts:185-186](src/http/oauth.ts#L185-L186) | [plain](test/http.security.test.ts#L85), [missing](test/http.security.test.ts#L94), [mismatch](test/http.security.test.ts#L101) |
|
|
43
|
+
| Authorisation codes last 60 seconds, live in the database, and work once. A second use revokes the tokens from the first. | [src/http/context.ts:20](src/http/context.ts#L20), [src/store/postgres.ts:88-111](src/store/postgres.ts#L88-L111) | [TTL](test/http.security.test.ts#L134), [used code](test/http.security.test.ts#L123), [expired code](test/http.security.test.ts#L114) |
|
|
44
|
+
| Clients may register only allowlisted redirect URIs. The default list holds Claude's callback alone. | [src/config/http.ts:127](src/config/http.ts#L127), [src/http/oauth.ts:103](src/http/oauth.ts#L103) | [registration refused](test/http.security.test.ts#L50) |
|
|
45
|
+
| Redirect URIs must match exactly. | [src/http/oauth.ts:176](src/http/oauth.ts#L176) | [authorize never redirects](test/http.security.test.ts#L56), [code bound to redirect](test/http.security.test.ts#L142) |
|
|
46
|
+
| A consent page with a CSRF token, `__Host-` cookies, and a strict content security policy. | [src/http/response.ts:89-118](src/http/response.ts#L89-L118) | [CSRF](test/http.security.test.ts#L267), [deny](test/http.security.test.ts#L309), [headers](test/http.security.test.ts#L357) |
|
|
47
|
+
| Consent accepts form posts only from its own page. It ends with a page that moves on by itself, so `form-action` stays `'self'` through FreeAgent's own redirects. | [src/http/oauth.ts:231](src/http/oauth.ts#L231), [src/http/response.ts:46](src/http/response.ts#L46) | [Origin: null](test/http.security.test.ts#L277), [continue page](test/http.security.test.ts#L292) |
|
|
48
|
+
| The FreeAgent callback must reach the same browser that started the sign-in. | [src/http/oauth.ts:276](src/http/oauth.ts#L276) | [callback binding](test/http.security.test.ts#L319) |
|
|
49
|
+
| After sign-in, the server checks the FreeAgent company ID and discards tokens for any other company. | [src/http/oauth.ts:307](src/http/oauth.ts#L307) | [wrong company](test/http.security.test.ts#L254) |
|
|
50
|
+
|
|
51
|
+
### FreeAgent tokens at rest
|
|
52
|
+
|
|
53
|
+
| Control | Code | Test |
|
|
54
|
+
|---|---|---|
|
|
55
|
+
| AES-256-GCM with a random 96-bit IV for each value. | [src/crypto/keyring.ts:73-76](src/crypto/keyring.ts#L73-L76) | [round-trip](test/crypto.keyring.test.ts#L8), [tampering](test/crypto.keyring.test.ts#L38) |
|
|
56
|
+
| The associated data binds each value to its record, company, and field, so ciphertext cannot be moved. | [src/http/grants.ts:6-7](src/http/grants.ts#L6-L7) | [AAD mismatch](test/crypto.keyring.test.ts#L30) |
|
|
57
|
+
| Versioned keys and a `rotate-keys` command that never overwrites a newer token. | [src/ops.ts:17-36](src/ops.ts#L17-L36) | [rotation](test/ops.test.ts#L22), [refreshed during the run](test/ops.test.ts#L42) |
|
|
58
|
+
| Concurrent instances refresh FreeAgent tokens once, under a database lease. | [src/http/db-token-source.ts:56-59](src/http/db-token-source.ts#L56-L59) | [20 parallel instances](test/http.refresh.test.ts#L24) |
|
|
59
|
+
| The local token file is encrypted, written with mode `600`, and refused if other users can read it. | [src/store/token-file.ts:69-89](src/store/token-file.ts#L69-L89) | [mode 0600](test/local.test.ts#L47), [readable file refused](test/local.test.ts#L55) |
|
|
60
|
+
|
|
61
|
+
### HTTP surface
|
|
62
|
+
|
|
63
|
+
| Control | Code | Test |
|
|
64
|
+
|---|---|---|
|
|
65
|
+
| `GET` and `DELETE` on `/mcp` return `405`. | [src/http/handler.ts:83](src/http/handler.ts#L83) | [405](test/http.security.test.ts#L326) |
|
|
66
|
+
| Browser origins outside `ALLOWED_ORIGINS` get `403`. | [src/http/mcp.ts:24](src/http/mcp.ts#L24) | [Origin](test/http.security.test.ts#L331) |
|
|
67
|
+
| Body limits: 256 KB on `/mcp`, 16 KB on OAuth routes. | [src/http/context.ts:22-23](src/http/context.ts#L22-L23) | [413](test/http.security.test.ts#L337) |
|
|
68
|
+
| Rate limits per connection on `/mcp` and per address on registration. | [src/http/mcp.ts:37](src/http/mcp.ts#L37), [src/http/oauth.ts:89](src/http/oauth.ts#L89) | [per connection](test/http.security.test.ts#L347), [registration](test/http.security.test.ts#L65) |
|
|
69
|
+
| HSTS, `nosniff`, `no-referrer`, and `no-store` on token responses. | [src/http/response.ts:6-29](src/http/response.ts#L6-L29) | [headers](test/http.security.test.ts#L357) |
|
|
70
|
+
|
|
71
|
+
### Configuration and operations
|
|
72
|
+
|
|
73
|
+
| Control | Code | Test |
|
|
74
|
+
|---|---|---|
|
|
75
|
+
| Sandbox unless `FREEAGENT_ENV=production`. | [src/config/http.ts:61](src/config/http.ts#L61) | [sandbox default](test/config.test.ts#L24) |
|
|
76
|
+
| Bad configuration stops the server. Errors name the variable, never its value. A remote database must use TLS. | [src/config/http.ts:115-124](src/config/http.ts#L115-L124) | [fail closed](test/http.security.test.ts#L376), [no echo](test/config.test.ts#L57) |
|
|
77
|
+
| A Postgres host other than Neon is reached over TLS. `sslmode=verify-full` verifies the certificate, with `DATABASE_CA_CERT` for roots Node does not trust. | [src/store/pg.ts:45](src/store/pg.ts#L45) | [TLS settings](test/store.pg.test.ts#L10), [bad certificate](test/store.pg.test.ts#L29) |
|
|
78
|
+
| Logs drop tokens, secrets, and authorisation headers. Tool calls log the tool name and outcome only. | [src/logging/logger.ts:21-40](src/logging/logger.ts#L21-L40) | [logs](test/logs.no-secrets.test.ts#L7), [full connection](test/http.refresh.test.ts#L74) |
|
|
79
|
+
| Every tool is read-only. Write tools would need `ENABLE_WRITE_TOOLS`, and tools that reach clients a second flag. | [src/core/server.ts:34-43](src/core/server.ts#L34-L43) | [read-only](test/server.write-tools.test.ts#L21), [flags](test/server.write-tools.test.ts#L39) |
|
|
80
|
+
| `revoke-all` ends every session and deletes every stored FreeAgent token. | [src/bin/cli.ts:127](src/bin/cli.ts#L127) | [revoke-all](test/ops.test.ts#L56) |
|
|
81
|
+
| The cleanup job needs `CRON_SECRET`. | [src/http/handler.ts:111](src/http/handler.ts#L111) | [cleanup](test/http.security.test.ts#L390) |
|
|
82
|
+
|
|
83
|
+
## Threat model
|
|
84
|
+
|
|
85
|
+
| Threat | Controls | What remains |
|
|
86
|
+
|---|---|---|
|
|
87
|
+
| Leaked MCP access token | 1-hour lifetime, audience check, rate limit, read-only tools, revocation | Read access for up to 1 hour or until revoked. |
|
|
88
|
+
| Leaked MCP refresh token | Rotation, reuse detection, 30-day idle and 90-day absolute limits | If the attacker refreshes first, the real client's next refresh ends the connection for both. |
|
|
89
|
+
| Database read | Token hashes only. FreeAgent tokens encrypted with a key held outside the database. | None without the key. |
|
|
90
|
+
| Database write | Associated data binds each ciphertext to its record. | The attacker can delete rows, which denies service. |
|
|
91
|
+
| Key and database together | None. | Full FreeAgent access as the user who signed in. Run the [emergency revoke](README.md#emergency-revoke). |
|
|
92
|
+
| Malicious MCP client | Redirect allowlist, exact match, PKCE, consent page, client cap | A client can only receive codes at an allowlisted URI. |
|
|
93
|
+
| Wrong FreeAgent company | Company ID check after sign-in | None. |
|
|
94
|
+
| Compromised dependency | Three runtime dependencies at exact versions, lockfile, `npm audit` in CI, Dependabot, actions pinned by commit, npm provenance | A compromised dependency runs with the server's full rights. |
|
|
95
|
+
|
|
96
|
+
## Out of scope
|
|
97
|
+
|
|
98
|
+
- A compromised Vercel, Neon, GitHub, or FreeAgent account.
|
|
99
|
+
- A malicious user who signs in with valid FreeAgent access.
|
|
100
|
+
- Prompt injection through text stored in FreeAgent, such as a contact
|
|
101
|
+
name or an invoice comment. The tools are read-only, so injected text
|
|
102
|
+
cannot change the books through this server, but it can mislead the
|
|
103
|
+
model.
|
|
104
|
+
- Data that Claude keeps in its own conversation history.
|
|
105
|
+
|
|
106
|
+
## Known limits
|
|
107
|
+
|
|
108
|
+
- FreeAgent has no documented endpoint to revoke an app's tokens. After
|
|
109
|
+
`revoke-all`, also remove the app's access in FreeAgent's settings.
|
|
110
|
+
- Refresh token reuse has no grace period. A client that retries a
|
|
111
|
+
refresh after a network failure must reconnect.
|
|
112
|
+
- Automated tests use a simulated FreeAgent API. Version 0.1 has also run
|
|
113
|
+
against FreeAgent production for one UK limited company, over stdio and
|
|
114
|
+
as a claude.ai connector. Test it in the FreeAgent sandbox before you
|
|
115
|
+
use production with your own books.
|
package/dist/bin/cli.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { rm } from "node:fs/promises";
|
|
3
|
+
import { ConfigError, defaultTokenFilePath, loadDiscoveryConfig, loadLocalConfig } from "../config/env.js";
|
|
4
|
+
import { DecryptionError, KeyRing, KeyRingError } from "../crypto/keyring.js";
|
|
5
|
+
import { CompanyNotAllowedError } from "../freeagent/company.js";
|
|
6
|
+
import { runLogin } from "../local/login.js";
|
|
7
|
+
import { openInBrowser, waitForLoopbackCode } from "../local/loopback.js";
|
|
8
|
+
import { runStdio } from "../local/stdio.js";
|
|
9
|
+
import { createLogger } from "../logging/logger.js";
|
|
10
|
+
import { rotateGrantKeys } from "../ops.js";
|
|
11
|
+
import { runMigrations } from "../store/migrate.js";
|
|
12
|
+
import { PostgresTokenStore } from "../store/postgres.js";
|
|
13
|
+
import { TokenFile, TokenFileError } from "../store/token-file.js";
|
|
14
|
+
import { loadMigrations, openSql } from "./db.js";
|
|
15
|
+
const HELP = `Usage: freeagent-mcp [command]
|
|
16
|
+
|
|
17
|
+
Commands:
|
|
18
|
+
stdio Run the MCP server over stdio (default)
|
|
19
|
+
login Approve access in FreeAgent and save encrypted tokens
|
|
20
|
+
login --discover Print your FreeAgent company ID, store nothing
|
|
21
|
+
migrate Apply database migrations to DATABASE_URL
|
|
22
|
+
rotate-keys Re-encrypt stored FreeAgent tokens with the newest key
|
|
23
|
+
revoke-all --yes Emergency: revoke every session and delete every stored token
|
|
24
|
+
cleanup Delete expired tokens and old audit rows
|
|
25
|
+
|
|
26
|
+
rotate-keys, revoke-all, and cleanup use DATABASE_URL when it is set,
|
|
27
|
+
otherwise the local encrypted token file.
|
|
28
|
+
help Show this help
|
|
29
|
+
|
|
30
|
+
Configuration comes from environment variables. See the README.`;
|
|
31
|
+
function print(line) {
|
|
32
|
+
// stderr: stdout is reserved for the MCP protocol.
|
|
33
|
+
process.stderr.write(`${line}\n`);
|
|
34
|
+
}
|
|
35
|
+
async function main(argv) {
|
|
36
|
+
const [command = "stdio", ...rest] = argv;
|
|
37
|
+
switch (command) {
|
|
38
|
+
case "stdio": {
|
|
39
|
+
const config = loadLocalConfig();
|
|
40
|
+
await runStdio(config, createLogger({ level: config.logLevel }));
|
|
41
|
+
return -1; // keep running
|
|
42
|
+
}
|
|
43
|
+
case "login": {
|
|
44
|
+
const discover = rest.includes("--discover");
|
|
45
|
+
const unknown = rest.filter((a) => a !== "--discover");
|
|
46
|
+
if (unknown.length > 0) {
|
|
47
|
+
print(`Unknown option: ${unknown.join(" ")}\n\n${HELP}`);
|
|
48
|
+
return 2;
|
|
49
|
+
}
|
|
50
|
+
if (discover) {
|
|
51
|
+
const config = loadDiscoveryConfig();
|
|
52
|
+
await runLogin({
|
|
53
|
+
oauth: { ...config.freeagent },
|
|
54
|
+
environment: config.freeagent.environment,
|
|
55
|
+
port: config.localPort,
|
|
56
|
+
discover: true,
|
|
57
|
+
waitForCode: (uri, state) => waitForLoopbackCode(uri, state),
|
|
58
|
+
openUrl: openInBrowser,
|
|
59
|
+
print,
|
|
60
|
+
});
|
|
61
|
+
return 0;
|
|
62
|
+
}
|
|
63
|
+
const config = loadLocalConfig();
|
|
64
|
+
if (config.tokens.mode === "env") {
|
|
65
|
+
print("FREEAGENT_REFRESH_TOKEN is set, so the token file is not used. Unset it to log in.");
|
|
66
|
+
return 2;
|
|
67
|
+
}
|
|
68
|
+
const tokenFile = new TokenFile(config.tokens.path, await KeyRing.parse(config.encryptionKeys));
|
|
69
|
+
await runLogin({
|
|
70
|
+
oauth: { ...config.freeagent },
|
|
71
|
+
environment: config.freeagent.environment,
|
|
72
|
+
port: config.localPort,
|
|
73
|
+
allowedCompanyId: config.freeagent.allowedCompanyId,
|
|
74
|
+
discover: false,
|
|
75
|
+
tokenFile,
|
|
76
|
+
waitForCode: (uri, state) => waitForLoopbackCode(uri, state),
|
|
77
|
+
openUrl: openInBrowser,
|
|
78
|
+
print,
|
|
79
|
+
});
|
|
80
|
+
return 0;
|
|
81
|
+
}
|
|
82
|
+
case "migrate": {
|
|
83
|
+
const { sql, close } = await openSql(process.env["DATABASE_URL"]);
|
|
84
|
+
try {
|
|
85
|
+
const applied = await runMigrations(sql, await loadMigrations());
|
|
86
|
+
print(applied.length > 0 ? `Applied: ${applied.join(", ")}` : "Database is up to date.");
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
await close();
|
|
90
|
+
}
|
|
91
|
+
return 0;
|
|
92
|
+
}
|
|
93
|
+
case "rotate-keys": {
|
|
94
|
+
const keys = await KeyRing.parse(process.env["TOKEN_ENCRYPTION_KEYS"]);
|
|
95
|
+
if (process.env["DATABASE_URL"]) {
|
|
96
|
+
const { sql, close } = await openSql(process.env["DATABASE_URL"]);
|
|
97
|
+
try {
|
|
98
|
+
const report = await rotateGrantKeys(new PostgresTokenStore(sql), keys);
|
|
99
|
+
print(`Re-encrypted ${report.rotated} grants with ${keys.currentVersion}; ${report.alreadyCurrent} already current; ${report.conflicts} changed during the run.`);
|
|
100
|
+
if (report.conflicts > 0) {
|
|
101
|
+
print("Run rotate-keys again to finish the changed grants.");
|
|
102
|
+
return 1;
|
|
103
|
+
}
|
|
104
|
+
print(`When every grant is current, remove the old keys from TOKEN_ENCRYPTION_KEYS.`);
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
await close();
|
|
108
|
+
}
|
|
109
|
+
return 0;
|
|
110
|
+
}
|
|
111
|
+
const config = loadLocalConfig();
|
|
112
|
+
if (config.tokens.mode !== "file") {
|
|
113
|
+
print("Nothing to rotate: tokens come from environment variables.");
|
|
114
|
+
return 0;
|
|
115
|
+
}
|
|
116
|
+
const file = new TokenFile(config.tokens.path, keys);
|
|
117
|
+
const tokens = await file.read(config.freeagent.environment, config.freeagent.allowedCompanyId);
|
|
118
|
+
if (!tokens) {
|
|
119
|
+
print(`No token file at ${config.tokens.path}.`);
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
|
122
|
+
await file.write(config.freeagent.environment, config.freeagent.allowedCompanyId, tokens);
|
|
123
|
+
print(`Re-encrypted ${config.tokens.path} with ${keys.currentVersion}.`);
|
|
124
|
+
return 0;
|
|
125
|
+
}
|
|
126
|
+
case "revoke-all": {
|
|
127
|
+
if (!rest.includes("--yes")) {
|
|
128
|
+
print("revoke-all deletes every session and every stored FreeAgent token. Every user must reconnect.\nRun again with --yes to confirm.");
|
|
129
|
+
return 2;
|
|
130
|
+
}
|
|
131
|
+
if (process.env["DATABASE_URL"]) {
|
|
132
|
+
const { sql, close } = await openSql(process.env["DATABASE_URL"]);
|
|
133
|
+
try {
|
|
134
|
+
const count = await new PostgresTokenStore(sql).revokeAll();
|
|
135
|
+
await new PostgresTokenStore(sql).audit({ event: "revoke_all", ok: true });
|
|
136
|
+
print(`Revoked ${count} sessions and deleted their FreeAgent tokens.`);
|
|
137
|
+
}
|
|
138
|
+
finally {
|
|
139
|
+
await close();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
const path = process.env["FREEAGENT_TOKEN_FILE"] ?? defaultTokenFilePath(process.env);
|
|
144
|
+
await rm(path, { force: true });
|
|
145
|
+
print(`Deleted ${path}.`);
|
|
146
|
+
}
|
|
147
|
+
print("Next: remove the app's access in FreeAgent settings (FreeAgent has no revoke API), then rotate TOKEN_ENCRYPTION_KEYS and, if leaked, the FreeAgent client secret.");
|
|
148
|
+
return 0;
|
|
149
|
+
}
|
|
150
|
+
case "cleanup": {
|
|
151
|
+
const { sql, close } = await openSql(process.env["DATABASE_URL"]);
|
|
152
|
+
try {
|
|
153
|
+
const days = Number(process.env["AUDIT_RETENTION_DAYS"] ?? "90");
|
|
154
|
+
if (!Number.isInteger(days) || days < 1 || days > 3650)
|
|
155
|
+
throw new ConfigError(["AUDIT_RETENTION_DAYS must be a whole number from 1 to 3650"]);
|
|
156
|
+
const counts = await new PostgresTokenStore(sql).cleanup(days);
|
|
157
|
+
print(Object.entries(counts).map(([table, n]) => `${table}: ${n}`).join("\n"));
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
await close();
|
|
161
|
+
}
|
|
162
|
+
return 0;
|
|
163
|
+
}
|
|
164
|
+
case "help":
|
|
165
|
+
case "--help":
|
|
166
|
+
case "-h":
|
|
167
|
+
print(HELP);
|
|
168
|
+
return 0;
|
|
169
|
+
default:
|
|
170
|
+
print(`Unknown command: ${command}\n\n${HELP}`);
|
|
171
|
+
return 2;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
main(process.argv.slice(2)).then((code) => {
|
|
175
|
+
if (code >= 0)
|
|
176
|
+
process.exitCode = code;
|
|
177
|
+
}, (error) => {
|
|
178
|
+
const known = error instanceof ConfigError ||
|
|
179
|
+
error instanceof KeyRingError ||
|
|
180
|
+
error instanceof DecryptionError ||
|
|
181
|
+
error instanceof TokenFileError ||
|
|
182
|
+
error instanceof CompanyNotAllowedError;
|
|
183
|
+
print(known ? error.message : `Failed: ${error instanceof Error ? error.name : "unknown error"}${error instanceof Error ? `: ${error.message}` : ""}`);
|
|
184
|
+
process.exitCode = 1;
|
|
185
|
+
});
|
|
186
|
+
//# sourceMappingURL=cli.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/bin/cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAC3G,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,s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AC7B,KAAK,YAAY,eAAe;QAChC,KAAK,YAAY,cAAc;QAC/B,KAAK,YAAY,sBAAsB,CAAC;IAC1C,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IACvJ,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CACF,CAAC"}
|
package/dist/bin/db.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Migration } from "../store/migrate.js";
|
|
2
|
+
import { type Sql } from "../store/sql.js";
|
|
3
|
+
/**
|
|
4
|
+
* Opens DATABASE_URL for CLI commands. Neon hosts use the HTTP driver; any
|
|
5
|
+
* other Postgres needs the optional `pg` package.
|
|
6
|
+
*/
|
|
7
|
+
export declare function openSql(databaseUrl: string | undefined): Promise<{
|
|
8
|
+
sql: Sql;
|
|
9
|
+
close: () => Promise<void>;
|
|
10
|
+
}>;
|
|
11
|
+
/** Reads the package's SQL migrations, shipped beside `dist/`. */
|
|
12
|
+
export declare function loadMigrations(): Promise<Migration[]>;
|