bilan-mcp 0.0.0-stage → 1.0.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 (77) hide show
  1. package/.env.example +22 -0
  2. package/BRAND.md +59 -0
  3. package/LICENSE +21 -0
  4. package/README.md +106 -2
  5. package/SECURITY.md +45 -0
  6. package/dist/src/cli/auth-callback.d.ts +61 -0
  7. package/dist/src/cli/auth-callback.js +290 -0
  8. package/dist/src/cli/connect.d.ts +8 -0
  9. package/dist/src/cli/connect.js +111 -0
  10. package/dist/src/cli/gateway.d.ts +1 -0
  11. package/dist/src/cli/gateway.js +136 -0
  12. package/dist/src/cli/install.d.ts +2 -0
  13. package/dist/src/cli/install.js +49 -0
  14. package/dist/src/cli/schedule.d.ts +2 -0
  15. package/dist/src/cli/schedule.js +43 -0
  16. package/dist/src/cli/setup.d.ts +2 -0
  17. package/dist/src/cli/setup.js +59 -0
  18. package/dist/src/cli/sync.d.ts +6 -0
  19. package/dist/src/cli/sync.js +47 -0
  20. package/dist/src/config.d.ts +31 -0
  21. package/dist/src/config.js +118 -0
  22. package/dist/src/db/database.d.ts +143 -0
  23. package/dist/src/db/database.js +231 -0
  24. package/dist/src/db/schema.d.ts +1 -0
  25. package/dist/src/db/schema.js +180 -0
  26. package/dist/src/engine/analytics.d.ts +207 -0
  27. package/dist/src/engine/analytics.js +631 -0
  28. package/dist/src/engine/budgets.d.ts +40 -0
  29. package/dist/src/engine/budgets.js +240 -0
  30. package/dist/src/engine/entities.d.ts +96 -0
  31. package/dist/src/engine/entities.js +473 -0
  32. package/dist/src/engine/export.d.ts +80 -0
  33. package/dist/src/engine/export.js +161 -0
  34. package/dist/src/engine/rules.d.ts +53 -0
  35. package/dist/src/engine/rules.js +349 -0
  36. package/dist/src/engine/sync.d.ts +120 -0
  37. package/dist/src/engine/sync.js +795 -0
  38. package/dist/src/engine/tokens.d.ts +57 -0
  39. package/dist/src/engine/tokens.js +154 -0
  40. package/dist/src/engine/transfers.d.ts +10 -0
  41. package/dist/src/engine/transfers.js +121 -0
  42. package/dist/src/fx/rates.d.ts +78 -0
  43. package/dist/src/fx/rates.js +407 -0
  44. package/dist/src/gateway/mcp-http.d.ts +46 -0
  45. package/dist/src/gateway/mcp-http.js +390 -0
  46. package/dist/src/gateway/tunnel.d.ts +38 -0
  47. package/dist/src/gateway/tunnel.js +240 -0
  48. package/dist/src/index.d.ts +2 -0
  49. package/dist/src/index.js +109 -0
  50. package/dist/src/providers/csv-import.d.ts +27 -0
  51. package/dist/src/providers/csv-import.js +596 -0
  52. package/dist/src/providers/enable-banking.d.ts +123 -0
  53. package/dist/src/providers/enable-banking.js +475 -0
  54. package/dist/src/providers/mock.d.ts +18 -0
  55. package/dist/src/providers/mock.js +379 -0
  56. package/dist/src/providers/types.d.ts +41 -0
  57. package/dist/src/providers/types.js +27 -0
  58. package/dist/src/security/sanitize.d.ts +22 -0
  59. package/dist/src/security/sanitize.js +90 -0
  60. package/dist/src/server.d.ts +29 -0
  61. package/dist/src/server.js +890 -0
  62. package/dist/src/setup/autosync.d.ts +64 -0
  63. package/dist/src/setup/autosync.js +382 -0
  64. package/dist/src/setup/clients.d.ts +41 -0
  65. package/dist/src/setup/clients.js +414 -0
  66. package/dist/src/setup/env-writer.d.ts +21 -0
  67. package/dist/src/setup/env-writer.js +150 -0
  68. package/dist/src/setup/local-tls.d.ts +12 -0
  69. package/dist/src/setup/local-tls.js +81 -0
  70. package/dist/src/utils/dates.d.ts +17 -0
  71. package/dist/src/utils/dates.js +53 -0
  72. package/dist/src/wizard/server.d.ts +88 -0
  73. package/dist/src/wizard/server.js +1736 -0
  74. package/dist/src/wizard/ui.d.ts +5 -0
  75. package/dist/src/wizard/ui.js +6627 -0
  76. package/docs/callback.html +162 -0
  77. package/package.json +71 -4
package/.env.example ADDED
@@ -0,0 +1,22 @@
1
+ # Base currency for aggregated net worth, reports, and budgets
2
+ BASE_CURRENCY=RON
3
+
4
+ # Local SQLite database path (relative to BILAN_HOME / project root or absolute)
5
+ DB_PATH=./data/bilan.db
6
+
7
+ # Enable Banking API (Free Restricted Mode for personal EU/UK accounts)
8
+ # Register at https://enablebanking.com -> Control Panel -> Applications (Production)
9
+ # Enable Banking Production requires https://
10
+ # Default uses the zero-warning static GitHub Pages relay back to local 127.0.0.1:8788
11
+ # Offline alternative (self-signed local TLS): https://localhost:8787/callback
12
+ ENABLE_BANKING_APP_ID=
13
+ ENABLE_BANKING_PRIVATE_KEY_PATH=./secrets/enable-banking.pem
14
+ ENABLE_BANKING_REDIRECT_URI=https://razvangirgiz.github.io/bilan/callback.html
15
+
16
+ # Sync protection: minimum minutes between live PSD2 syncs per connection
17
+ # (PSD2 unattended access typically allows max 4 calls/day; 0 disables the guard)
18
+ MIN_SYNC_INTERVAL_MINUTES=60
19
+
20
+ # Optional: set to "true" to auto-seed realistic demo data (BT, ING, Revolut, Wise, Monzo)
21
+ # when the database is completely empty
22
+ AUTO_SEED_DEMO=false
package/BRAND.md ADDED
@@ -0,0 +1,59 @@
1
+ # bilan Brand Kit
2
+
3
+ A monochrome, Vercel-inspired private-ledger identity built for a **100% local, strictly read-only** multi-currency finance instrument. *bilan* (Romanian *bilanț*, French/international *bilan* = balance sheet) works naturally in both Romanian and English.
4
+
5
+ ## 1. Brand Personality
6
+
7
+ - **Genuine, not flashy:** High-contrast black, pure white, and brushed silver inspired by precision engineering instruments (Vercel, Braun, Linear).
8
+ - **Zero blue in product chrome:** All navigation, primary CTAs, focus rings, charts, and surfaces stay strictly monochrome. Authentic third-party brand colors are reserved exclusively for real bank logos and AI app logos.
9
+ - **Razor-short copy:** Clear 1 to 3 word labels, zero filler paragraphs, tabular numeric alignment everywhere.
10
+
11
+ ## 2. Logo Mark (Double-Entry Ledger Monogram)
12
+
13
+ A geometric **ledger fold** monogram forming an abstract lowercase `b`: precision interlocking white bars inside an Obsidian (`#0A0A0A`) rounded square with a brushed silver (`#A1A1AA`) corner proof.
14
+
15
+ ```svg
16
+ <svg width="28" height="28" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">
17
+ <rect width="28" height="28" rx="6" fill="#0A0A0A"/>
18
+ <rect x="7" y="6" width="3.5" height="16" rx="1" fill="#FFFFFF"/>
19
+ <rect x="10.5" y="13" width="8.5" height="3" rx="1" fill="#FFFFFF"/>
20
+ <rect x="10.5" y="19" width="8.5" height="3" rx="1" fill="#FFFFFF"/>
21
+ <rect x="17.5" y="13" width="3.5" height="9" rx="1" fill="#FFFFFF"/>
22
+ <rect x="19" y="5" width="4" height="4" rx="1" fill="#A1A1AA"/>
23
+ </svg>
24
+ ```
25
+
26
+ - **Wordmark:** `bilan` set in `Bricolage Grotesque`, weight `700`, tracking `-0.03em`, lowercase.
27
+ - **Clear space:** Minimum 8px around the 28px mark.
28
+
29
+ ## 3. Color System (Monochrome Obsidian & Silver)
30
+
31
+ | Token | Hex | Role |
32
+ |---|---|---|
33
+ | `--canvas` | `#FAFAFA` | Subtle dot-matrix studio canvas |
34
+ | `--surface` | `#FFFFFF` | Primary cards and tables |
35
+ | `--surface-subtle` | `#F4F4F5` | Recessed inputs, pills, dropzones |
36
+ | `--obsidian` | `#0A0A0A` | Primary ink, primary CTAs, executive KPI bands |
37
+ | `--obsidian-surface` | `#18181B` | Elevated dark card surfaces |
38
+ | `--muted-ink` | `#71717A` | Secondary labels and metadata |
39
+ | `--obsidian-muted` | `#A1A1AA` | Silver accent and secondary copy on dark cards |
40
+ | `--hairline` | `#E4E4E7` | 1px structural borders |
41
+ | `--hairline-strong` | `#D4D4D8` | Hover borders and outflow chart bars |
42
+ | `--live-dot` | `#16A34A` | Live active dot indicator only |
43
+ | `--warning` | `#A16207` | Expiring consent / uncategorized warning |
44
+ | `--error` | `#DC2626` | Sync failure / exceeded budget alert |
45
+
46
+ ## 4. Typography
47
+
48
+ - **Display, Headings & Hero Figures:** `Bricolage Grotesque` (`600`, `700`), tracking `-0.025em` to `-0.035em`.
49
+ - **Body, Controls & Tables:** `Plus Jakarta Sans` (`400`, `500`, `600`) with native system sans fallbacks.
50
+ - **Monospace:** `JetBrains Mono` (`400`, `500`) for dates, codes, redirect URLs, and JSON snippets.
51
+ - **Numeric Precision:** `font-variant-numeric: tabular-nums` on every balance, currency amount, rate, date, and counter.
52
+ - **Icons:** Inline monochrome 24x24 stroke SVGs (zero external icon font dependency; renders identically offline).
53
+
54
+ ## 5. Motion & Feedback
55
+
56
+ - **Curve:** `cubic-bezier(0.2, 0, 0, 1)` (`140ms-240ms`), honoring `prefers-reduced-motion: reduce`.
57
+ - **Dot Field:** Subtle magnetic silver-obsidian dot matrix that pauses its animation loop automatically when idle.
58
+ - **Notifications:** Dark Obsidian Sonner-style stacked toasts bottom-right (top on mobile), auto-dismissing with hover pause and `aria-live="polite"`.
59
+ - **Focus:** High-contrast `:focus-visible` Obsidian outline (`2px solid #0A0A0A`, `offset: 2px`).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bilan contributors
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,107 @@
1
- # Temporary Holding Version
1
+ # bilan
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Local-first, multi-currency Open Banking ledger & universal MCP server** for any AI agent: local coding harnesses (Antigravity, Claude Desktop, Claude Code, Codex, Cursor, Windsurf, OpenCode, Gemini CLI, VS Code, Zed, LM Studio) and remote/cloud agents or apps (Hark, Grokbot, ChatGPT, Claude web, OpenClaw, n8n, LangChain, custom apps).
4
+
5
+ Connect EU/EEA bank accounts for free via **Enable Banking (PSD2, Restricted Mode)** or import CSV statements for UK/US banks and brokers, organize accounts into **Personal** and **Business** workspaces (for example, a Romania SRL and a UK Ltd), and let your AI assistant analyze cashflow, track budgets, detect recurring subscriptions, and categorize transactions. Everything stays **strictly read-only and 100% local**.
6
+
7
+ ## Highlights
8
+
9
+ - **Local Web UI & Setup Wizard (`bilan setup`):** Runs on `http://127.0.0.1:8788` with automatic local HTTPS OAuth callback handling on `https://localhost:8787/callback` or zero-warning GitHub Pages redirect (`https://razvangirgiz.github.io/bilan/callback.html`).
10
+ - **Universal Remote MCP Gateway (`bilan gateway`):** Isolated HTTP/SSE MCP server on `127.0.0.1:8789` (`/mcp` Streamable HTTP + `/sse` legacy SSE) with per-agent scoped Bearer API keys (`read_only` or `read_write`), optional entity lock (e.g., UK Ltd only), rate limiting, audit log, and 1-click Cloudflare HTTPS Tunnel for cloud agents (Hark, Grokbot, ChatGPT, Claude web, OpenClaw, n8n).
11
+ - **Personal & Business Entities:** Create separate workspaces with country, currency, tax ID, linked accounts, and agent context notes so your AI knows which accounts belong to Personal vs. each company.
12
+ - **Transactions Explorer & Rules Manager:** Filter by entity, account, category, direction, date range, and search query; triage uncategorized transactions inline; create literal auto-categorization rules and manage or delete rules in place.
13
+ - **Reports, Budgets & Exports:** Inspect monthly cashflow charts, entity comparisons, category/merchant rankings, recurring bills, and multi-currency budgets; export filtered CSV (with UTF-8 BOM and formula-injection neutralization) or Markdown reports.
14
+ - **Background Auto-Sync (`bilan schedule`):** Native macOS `launchd` LaunchAgent presets (`1x`, `2x`, `3x`, `4x` daily) that stay within PSD2 bank rate limits, plus cross-process SQLite sync locking.
15
+ - **True Multi-Currency FX:** Tracks accounts in `RON`, `EUR`, `GBP`, `USD`, `CHF`, `PLN`, and more, converting via **BNR XML** and **ECB Frankfurter** (including historical backfill on sync).
16
+ - **Strictly Read-Only & Local:** Zero payment scopes, `0700`/`0600` local file permissions, masked IBANs (`****1234`), DNS rebinding and CSRF protection, and prompt-injection hygiene. See [SECURITY.md](./SECURITY.md) and [BRAND.md](./BRAND.md).
17
+
18
+ ---
19
+
20
+ ## Quick Start
21
+
22
+ Requires **Node.js 22.13+** (uses built-in `node:sqlite`, zero native builds).
23
+
24
+ ```bash
25
+ npm install
26
+ npm run build
27
+ npm run setup
28
+ ```
29
+
30
+ *(Once published to npm: `npx bilan setup`. Config, secrets, logs, and SQLite default to `~/.bilan` or `BILAN_HOME`.)*
31
+
32
+ The browser opens **bilan** at `http://127.0.0.1:8788`:
33
+
34
+ 1. **Key:** Drop your free Enable Banking `.pem` key (Application ID is extracted from the filename automatically).
35
+ 2. **Banks:** Link EU/EEA banks (Revolut, ING, Banca Transilvania, Wise, BCR, Raiffeisen, N26, Bunq, etc.), import CSV statements, and optionally enable background auto-sync.
36
+ 3. **AI apps:** Click **Install** next to any detected local MCP client, or use **Remote & cloud agents** to mint a scoped Bearer API key and start a 1-click Cloudflare HTTPS tunnel for cloud agents (Hark, Grokbot, ChatGPT, Claude web, OpenClaw, n8n, custom apps).
37
+ 4. **Accounts, Transactions & Reports:** Review balances by entity, triage transactions, track budgets, and query your ledger directly from your AI assistant.
38
+
39
+ > Want to explore first without connecting a real bank? Click **Load demo** in **Accounts** (or run `bilan sync --demo`). Clear demo data anytime with **Clear demo** without touching real banks.
40
+
41
+ ---
42
+
43
+ ## CLI Commands
44
+
45
+ ```bash
46
+ bilan setup # Open visual Web UI & Setup Wizard on http://127.0.0.1:8788
47
+ bilan gateway # Start isolated HTTP/SSE MCP Gateway on 127.0.0.1:8789
48
+ bilan gateway --tunnel # Expose MCP Gateway via Cloudflare HTTPS Tunnel
49
+ bilan gateway --create-key "Hark" --scope read_only --entity personal
50
+ bilan connect # Connect a bank interactively via Enable Banking PSD2 OAuth
51
+ bilan install # Auto-install MCP config into detected AI apps
52
+ bilan install claude-desktop # Install into a specific AI client
53
+ bilan sync # Sync all active banks (respects PSD2 rate limits & lock)
54
+ bilan sync --force # Force immediate sync
55
+ bilan sync --demo # Seed realistic multi-currency demo accounts
56
+ bilan sync --clear-demo # Remove only demo accounts, demo sync logs, and demo budgets
57
+ bilan schedule status # Inspect macOS LaunchAgent auto-sync status
58
+ bilan schedule enable 2x # Enable background auto-sync (1x | 2x | 3x | 4x daily)
59
+ bilan schedule disable # Disable background auto-sync
60
+ bilan # Start MCP stdio server
61
+ ```
62
+
63
+ ## MCP Tools
64
+
65
+ | Category | Tools |
66
+ |---|---|
67
+ | **Read & Analytics (Read-Only)** | `overview`, `list_accounts`, `transactions`, `cashflow`, `recurring`, `list_uncategorized`, `budget_status`, `sync_status` |
68
+ | **Entities, Budgets & Tagging (Local SQLite)** | `manage_entities`, `tag_transactions`, `manage_rules`, `manage_budgets`, `update_account` |
69
+ | **Sync, Onboarding & Import** | `list_supported_banks`, `start_bank_connect`, `complete_bank_connect`, `sync_now`, `import_csv`, `seed_demo_data`, `clear_demo_data` |
70
+
71
+ > For security, the MCP `import_csv` tool only reads `.csv`/`.tsv` files placed inside `<BILAN_HOME>/imports` (up to 5 MB). Web UI CSV imports are parsed strictly in memory.
72
+
73
+ ## Remote & Cloud Agents (Streamable HTTP + SSE)
74
+
75
+ To connect cloud or external agents (Hark, Grokbot, ChatGPT, Claude web, OpenClaw, n8n, LangChain, custom apps):
76
+
77
+ 1. Open **3. AI apps -> Remote & cloud agents** in `bilan setup` (or run `bilan gateway --tunnel`).
78
+ 2. Click **New API key**, choose **Read-only** (recommended) and optionally lock the key to a single entity (e.g. `Personal` or `UK Ltd`).
79
+ 3. Click **Start HTTPS tunnel** (uses `cloudflared` on isolated port `8789`, never exposing the Setup UI on `8788` or `.pem` keys).
80
+ 4. Paste the `/mcp` URL (or `/sse` for legacy SSE clients) and `Authorization: Bearer bilan_sk_...` header into your agent:
81
+
82
+ ```json
83
+ {
84
+ "mcpServers": {
85
+ "bilan": {
86
+ "url": "https://<your-tunnel>.trycloudflare.com/mcp",
87
+ "headers": {
88
+ "Authorization": "Bearer bilan_sk_..."
89
+ }
90
+ }
91
+ }
92
+ }
93
+ ```
94
+
95
+ For a permanent custom domain instead of a quick tunnel URL, set `CLOUDFLARE_TUNNEL_TOKEN` (and optionally `CLOUDFLARE_TUNNEL_PUBLIC_URL`) in `.env`.
96
+
97
+ ## Background Sync (Linux / Cron Alternative)
98
+
99
+ On macOS, use **Banks -> Background auto-sync** or `bilan schedule enable 2x`. On Linux or custom setups:
100
+
101
+ ```bash
102
+ 0 8,14,20 * * * /path/to/node /path/to/bilan/dist/src/index.js sync >> ~/.bilan/logs/autosync.log 2>&1
103
+ ```
104
+
105
+ ## License
106
+
107
+ MIT. See [LICENSE](./LICENSE).
package/SECURITY.md ADDED
@@ -0,0 +1,45 @@
1
+ # Security Model & Policy
2
+
3
+ `bilan` handles personal and business financial data and is built with defense-in-depth from day one.
4
+
5
+ ## Core Security Guarantees
6
+
7
+ 1. **Strictly Read-Only Bank Access (AISP Only):**
8
+ - `bilan` never requests Payment Initiation (PISP) scopes and exposes zero payment or transfer tools. Even if an AI agent is compromised, it cannot initiate payments or move money.
9
+ 2. **100% Local-First Storage & Strict Permissions:**
10
+ - All local state lives inside your configured home directory (`~/.bilan` or `BILAN_HOME`) with `0700` directory permissions (`data/`, `secrets/`, `logs/`, `imports/`, `cache/`) and `0600` file permissions (`data/bilan.db`, `-wal`, `-shm`, `.env`, `secrets/enable-banking.pem`, `secrets/localhost-key.pem`, `logs/autosync.log`, LaunchAgent plist, and MCP config backups).
11
+ - No telemetry, no cloud sync, no third-party analytics.
12
+ 3. **Minimal Data Stored & Exposed to LLMs:**
13
+ - Full IBANs are stripped before saving Enable Banking session metadata (`connections.metadata_json`) and are never sent to AI models; only the last 4 characters (`****1234`), `identification_hash`, and friendly account aliases are retained.
14
+ - Local `connections.id` values use opaque UUIDs so live Enable Banking `session_id` tokens are not exposed in APIs or logs.
15
+ - Compact, spaced, and hyphenated IBANs plus Luhn-validated payment card numbers inside merchant names, descriptions, and notes are redacted automatically.
16
+ 4. **Prompt Injection Hygiene:**
17
+ - Bank payment descriptions (`remittance_information`), merchant names, and metadata can be controlled by third parties.
18
+ - `McpServer.instructions` stays strictly static (never interpolates database or bank strings).
19
+ - Text sanitization strips ASCII controls, Unicode BiDi overrides/isolates, zero-width characters, and Unicode Tags (`U+E0000-E007F`).
20
+ - All financial MCP tool responses and context resources attach an explicit `UNTRUSTED_BANK_DATA_WARNING` reminding agents never to follow instructions found inside bank data.
21
+ 5. **Local Web UI & API Hardening (`http://127.0.0.1:8788`):**
22
+ - Binds strictly to `127.0.0.1` (never `0.0.0.0`).
23
+ - Blocks DNS rebinding by enforcing an exact `Host` header match (`127.0.0.1:<port>` or `localhost:<port>`) on every route.
24
+ - Enforces `Origin`, `Sec-Fetch-Site`, and a per-session random `X-Bilan-Token` header verified via `crypto.timingSafeEqual` on all data and mutation `/api/*` endpoints (including `GET /api/status`, `GET /api/transactions`, `GET /api/reports`, and `GET /api/export`).
25
+ - Serves `/` with a per-request `Content-Security-Policy` script nonce, `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, `Cross-Origin-Opener-Policy: same-origin`, and `Cross-Origin-Resource-Policy: same-origin`.
26
+ - `/api/bank-logo` only fetches `https://enablebanking.com/brands/...` with `redirect: "error"`, verifies PNG/JPEG/WebP magic bytes (rejecting upstream SVGs), caps size at 2 MB, enforces a 200-file cache quota, and responds with `Content-Security-Policy: default-src 'none'; sandbox`.
27
+ 6. **Sandboxed CSV Import & Safe Exports:**
28
+ - The MCP `import_csv` tool only reads regular `.csv`/`.tsv` files resolved via `fs.realpathSync()` strictly inside `<homeDir>/imports` (5 MB limit).
29
+ - Web UI CSV uploads are parsed in memory without writing bank statements to `/tmp`.
30
+ - Exported CSV cells neutralize spreadsheet formula injection (`=`, `+`, `-`, `@`, `|`, even after leading whitespace/newlines) and Markdown exports escape pipe and newline characters.
31
+ - `.env` updates reject invalid keys and newline/null-byte injection.
32
+ 7. **OAuth Callback Handling (`https://localhost:8787/callback` & `docs/callback.html`):**
33
+ - By default, `bilan setup` starts a local HTTPS callback listener on `https://localhost:8787/callback` using a locally generated self-signed certificate (`0600`).
34
+ - If you use the hosted `docs/callback.html` on GitHub Pages (`https://razvangirgiz.github.io/bilan/callback.html`), it restricts local redirect ports strictly to `8787`/`8788`, sets a strict CSP meta policy, and preserves both `code` and `state`. Without your local RSA `.pem` private key, an authorization `code` cannot be exchanged for a bank session.
35
+ 8. **Isolated Universal Remote MCP Gateway (`127.0.0.1:8789`):**
36
+ - Runs on a separate loopback port from the Setup Wizard (`8788`), so tunneling with Cloudflare Tunnel (`cloudflared`) never exposes Setup UI, `.env`, `.pem` keys, or bank OAuth configuration.
37
+ - Every `/mcp`, `/sse`, and `/messages` call requires an explicit `Authorization: Bearer bilan_sk_...` or `X-API-Key` header (query-string tokens are rejected so secrets never enter access logs).
38
+ - API keys are stored strictly as SHA-256 hashes and verified with `crypto.timingSafeEqual`.
39
+ - Remote keys support least-privilege `read_only` (8 read-only tools) or `read_write` (adds tagging, rules, budgets, sync) scopes plus optional `entity_scope` isolation so a remote agent can be locked to a single business or personal workspace.
40
+ - Admin tools (`import_csv`, `start_bank_connect`, `complete_bank_connect`, `seed_demo_data`, `clear_demo_data`) are strictly unavailable over remote HTTP/SSE transports.
41
+ - Enforces per-token rate limiting (60 req/min), SSE session ownership binding, max 512 KB HTTP body size, and writes every remote tool call and denied attempt to `agent_audit_log`.
42
+
43
+ ## Reporting a Vulnerability
44
+
45
+ Please do not open public issues for security vulnerabilities. Report them privately to the repository maintainers with steps to reproduce.
@@ -0,0 +1,61 @@
1
+ import type { SyncService } from "../engine/sync.js";
2
+ import type { EnableBankingProvider } from "../providers/enable-banking.js";
3
+ export interface AuthCompletionResult {
4
+ connectionId: string;
5
+ bankName: string;
6
+ accountsSynced: number;
7
+ transactionsAdded: number;
8
+ }
9
+ /**
10
+ * Extracts `code` and optional `state` from either a full redirect callback URL
11
+ * (e.g. `https://localhost:8787/callback?code=abc&state=xyz`) or a raw code string.
12
+ */
13
+ export declare function parseCallbackInput(rawInput: string): {
14
+ code: string;
15
+ state: string | null;
16
+ };
17
+ /**
18
+ * Handles Enable Banking PSD2 OAuth callbacks automatically on `127.0.0.1`:
19
+ * - `https://localhost:<port>/callback`: spins up a local HTTPS listener using a
20
+ * generated self-signed localhost TLS cert (zero copy-paste required!).
21
+ * - `http://localhost:<port>/callback`: spins up a local HTTP listener.
22
+ * - Remote `https://...` (or if TLS/port setup fails): falls back gracefully to manual paste.
23
+ */
24
+ export declare class LocalAuthCallbackServer {
25
+ private readonly redirectUri;
26
+ private readonly enableBanking;
27
+ private readonly syncService;
28
+ private readonly homeDir?;
29
+ private server;
30
+ private pending;
31
+ private idleTimer;
32
+ constructor(redirectUri: string, enableBanking: EnableBankingProvider, syncService: SyncService, homeDir?: string | undefined);
33
+ private isLocalhostRedirect;
34
+ startBankAuth(params: {
35
+ bankName: string;
36
+ country: string;
37
+ psuType?: "personal" | "business";
38
+ consentDays?: number;
39
+ defaultEntityId?: string;
40
+ timeoutMs?: number;
41
+ }): Promise<{
42
+ authUrl: string;
43
+ state: string;
44
+ validUntil: string;
45
+ callbackUrl: string;
46
+ mode: "local_http" | "local_https" | "manual_paste";
47
+ completion: Promise<AuthCompletionResult>;
48
+ }>;
49
+ /**
50
+ * Completes an authorization using either the full redirected URL from the browser
51
+ * address bar or just the `code` query parameter.
52
+ */
53
+ completeWithCallback(callbackUrlOrCode: string, fallbackBank?: {
54
+ bankName?: string;
55
+ country?: string;
56
+ }): Promise<AuthCompletionResult>;
57
+ private ensureListening;
58
+ private resetIdleTimer;
59
+ private scheduleCloseIfIdle;
60
+ close(): void;
61
+ }
@@ -0,0 +1,290 @@
1
+ import crypto from "node:crypto";
2
+ import http from "node:http";
3
+ import https from "node:https";
4
+ import { ensureLocalhostTlsCert } from "../setup/local-tls.js";
5
+ const CALLBACK_SECURITY_HEADERS = {
6
+ "Content-Type": "text/html; charset=utf-8",
7
+ "Cache-Control": "no-store",
8
+ "X-Frame-Options": "DENY",
9
+ "X-Content-Type-Options": "nosniff",
10
+ "Referrer-Policy": "no-referrer",
11
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
12
+ };
13
+ /**
14
+ * Extracts `code` and optional `state` from either a full redirect callback URL
15
+ * (e.g. `https://localhost:8787/callback?code=abc&state=xyz`) or a raw code string.
16
+ */
17
+ export function parseCallbackInput(rawInput) {
18
+ const trimmed = rawInput.trim();
19
+ if (/^https?:\/\//i.test(trimmed)) {
20
+ const url = new URL(trimmed);
21
+ const err = url.searchParams.get("error");
22
+ if (err) {
23
+ throw new Error(`Bank returned error: ${url.searchParams.get("error_description") || err}`);
24
+ }
25
+ const code = url.searchParams.get("code")?.trim();
26
+ if (!code) {
27
+ throw new Error("No 'code' query parameter found in the pasted callback URL.");
28
+ }
29
+ return {
30
+ code,
31
+ state: url.searchParams.get("state")?.trim() || null,
32
+ };
33
+ }
34
+ if (!trimmed) {
35
+ throw new Error("Empty callback URL / authorization code.");
36
+ }
37
+ return { code: trimmed, state: null };
38
+ }
39
+ /**
40
+ * Handles Enable Banking PSD2 OAuth callbacks automatically on `127.0.0.1`:
41
+ * - `https://localhost:<port>/callback`: spins up a local HTTPS listener using a
42
+ * generated self-signed localhost TLS cert (zero copy-paste required!).
43
+ * - `http://localhost:<port>/callback`: spins up a local HTTP listener.
44
+ * - Remote `https://...` (or if TLS/port setup fails): falls back gracefully to manual paste.
45
+ */
46
+ export class LocalAuthCallbackServer {
47
+ redirectUri;
48
+ enableBanking;
49
+ syncService;
50
+ homeDir;
51
+ server = null;
52
+ pending = new Map();
53
+ idleTimer = null;
54
+ constructor(redirectUri, enableBanking, syncService, homeDir) {
55
+ this.redirectUri = redirectUri;
56
+ this.enableBanking = enableBanking;
57
+ this.syncService = syncService;
58
+ this.homeDir = homeDir;
59
+ }
60
+ isLocalhostRedirect() {
61
+ const parsed = new URL(this.redirectUri);
62
+ const isLocal = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
63
+ return { isLocal, isHttps: parsed.protocol === "https:" };
64
+ }
65
+ async startBankAuth(params) {
66
+ if (!this.enableBanking.isConfigured()) {
67
+ throw new Error("Enable Banking is not configured yet. Set ENABLE_BANKING_APP_ID and place your .pem key at ENABLE_BANKING_PRIVATE_KEY_PATH in .env.");
68
+ }
69
+ const { isLocal, isHttps } = this.isLocalhostRedirect();
70
+ let mode = "manual_paste";
71
+ if (isLocal) {
72
+ try {
73
+ await this.ensureListening(isHttps);
74
+ mode = isHttps ? "local_https" : "local_http";
75
+ }
76
+ catch {
77
+ // Port busy (e.g. Setup Wizard already listening) or openssl unavailable -> manual paste still works
78
+ mode = "manual_paste";
79
+ }
80
+ }
81
+ const state = crypto.randomBytes(18).toString("hex");
82
+ const { url, validUntil } = await this.enableBanking.startAuth({
83
+ bankName: params.bankName,
84
+ country: params.country,
85
+ psuType: params.psuType ?? "personal",
86
+ state,
87
+ consentDays: params.consentDays,
88
+ });
89
+ const timeoutMs = params.timeoutMs ?? 10 * 60 * 1000;
90
+ const completion = new Promise((resolve, reject) => {
91
+ const entry = {
92
+ state,
93
+ bankName: params.bankName,
94
+ country: params.country.toUpperCase(),
95
+ validUntil,
96
+ defaultEntityId: params.defaultEntityId,
97
+ createdAt: Date.now(),
98
+ onComplete: resolve,
99
+ onError: reject,
100
+ };
101
+ this.pending.set(state, entry);
102
+ const timer = setTimeout(() => {
103
+ if (this.pending.has(state)) {
104
+ this.pending.delete(state);
105
+ reject(new Error(`Bank authorization timed out after ${Math.round(timeoutMs / 1000)}s.`));
106
+ this.scheduleCloseIfIdle();
107
+ }
108
+ }, timeoutMs);
109
+ timer.unref();
110
+ });
111
+ if (mode !== "manual_paste") {
112
+ this.resetIdleTimer(timeoutMs + 10_000);
113
+ }
114
+ return {
115
+ authUrl: url,
116
+ state,
117
+ validUntil,
118
+ callbackUrl: this.redirectUri,
119
+ mode,
120
+ completion,
121
+ };
122
+ }
123
+ /**
124
+ * Completes an authorization using either the full redirected URL from the browser
125
+ * address bar or just the `code` query parameter.
126
+ */
127
+ async completeWithCallback(callbackUrlOrCode, fallbackBank) {
128
+ const { code, state } = parseCallbackInput(callbackUrlOrCode);
129
+ const pending = state ? this.pending.get(state) : undefined;
130
+ if (state && pending) {
131
+ this.pending.delete(state);
132
+ }
133
+ try {
134
+ const session = await this.enableBanking.exchangeCode(code);
135
+ const conn = this.syncService.saveEnableBankingConnection({
136
+ sessionId: session.sessionId,
137
+ bankName: session.bankName ||
138
+ pending?.bankName ||
139
+ fallbackBank?.bankName ||
140
+ "Connected Bank",
141
+ country: session.country || pending?.country || fallbackBank?.country || "EU",
142
+ validUntil: session.validUntil ?? pending?.validUntil ?? null,
143
+ rawAccounts: session.accounts,
144
+ defaultEntityId: pending?.defaultEntityId,
145
+ });
146
+ const syncRes = await this.syncService.syncConnection(conn.id, {
147
+ force: true,
148
+ daysBack: 90,
149
+ });
150
+ const result = {
151
+ connectionId: conn.id,
152
+ bankName: conn.bank_name,
153
+ accountsSynced: syncRes.accountsSynced,
154
+ transactionsAdded: syncRes.transactionsAdded,
155
+ };
156
+ pending?.onComplete?.(result);
157
+ this.scheduleCloseIfIdle();
158
+ return result;
159
+ }
160
+ catch (error) {
161
+ const err = error instanceof Error ? error : new Error(String(error));
162
+ pending?.onError?.(err);
163
+ this.scheduleCloseIfIdle();
164
+ throw err;
165
+ }
166
+ }
167
+ async ensureListening(useHttps) {
168
+ if (this.server)
169
+ return;
170
+ const parsed = new URL(this.redirectUri);
171
+ const port = parsed.port
172
+ ? Number.parseInt(parsed.port, 10)
173
+ : useHttps
174
+ ? 443
175
+ : 80;
176
+ const expectedPath = parsed.pathname || "/callback";
177
+ const scheme = useHttps ? "https" : "http";
178
+ const handler = async (req, res) => {
179
+ try {
180
+ const reqUrl = new URL(req.url ?? "/", `${scheme}://localhost:${port}`);
181
+ if (reqUrl.pathname !== expectedPath) {
182
+ res.writeHead(404, {
183
+ "Content-Type": "text/plain; charset=utf-8",
184
+ "X-Content-Type-Options": "nosniff",
185
+ });
186
+ res.end("Not found");
187
+ return;
188
+ }
189
+ const errorParam = reqUrl.searchParams.get("error");
190
+ const errorDesc = reqUrl.searchParams.get("error_description");
191
+ const state = reqUrl.searchParams.get("state") ?? "";
192
+ const code = reqUrl.searchParams.get("code") ?? "";
193
+ const pending = this.pending.get(state);
194
+ if (!pending) {
195
+ res.writeHead(400, CALLBACK_SECURITY_HEADERS);
196
+ res.end(`<h2>Invalid or expired authorization state</h2><p>Please restart bank connection from bilan.</p>`);
197
+ return;
198
+ }
199
+ if (errorParam || !code) {
200
+ this.pending.delete(state);
201
+ const errMsg = errorDesc || errorParam || "Missing authorization code";
202
+ pending.onError?.(new Error(`Bank rejected authorization: ${errMsg}`));
203
+ res.writeHead(400, CALLBACK_SECURITY_HEADERS);
204
+ res.end(`<h2>Authorization failed</h2><p>${escapeHtml(errMsg)}</p>`);
205
+ this.scheduleCloseIfIdle();
206
+ return;
207
+ }
208
+ const result = await this.completeWithCallback(reqUrl.toString());
209
+ res.writeHead(200, CALLBACK_SECURITY_HEADERS);
210
+ res.end(`<!doctype html><html><body style="font-family:-apple-system,system-ui,sans-serif;background:#F4F4F5;color:#0A0A0A;display:grid;place-items:center;min-height:100vh;margin:0;padding:24px">
211
+ <div style="background:#FFFFFF;border:1px solid #E4E4E7;border-radius:14px;padding:28px;max-width:440px;width:100%;box-shadow:0 8px 24px -12px rgba(10,10,10,.08)">
212
+ <h2 style="margin:0 0 8px;font-size:18px;letter-spacing:-0.02em">${escapeHtml(result.bankName)} connected</h2>
213
+ <p style="margin:0;color:#52525B;font-size:14px">${result.accountsSynced} account(s) synced · ${result.transactionsAdded} transactions imported. You can close this tab.</p>
214
+ </div>
215
+ </body></html>`);
216
+ }
217
+ catch (error) {
218
+ const msg = error instanceof Error ? error.message : String(error);
219
+ res.writeHead(500, CALLBACK_SECURITY_HEADERS);
220
+ res.end(`<h2>Error completing bank connection</h2><pre>${escapeHtml(msg)}</pre>`);
221
+ }
222
+ };
223
+ let candidate;
224
+ if (useHttps) {
225
+ if (!this.homeDir) {
226
+ throw new Error("homeDir is required to generate localhost TLS cert.");
227
+ }
228
+ const tls = ensureLocalhostTlsCert(this.homeDir);
229
+ candidate = https.createServer({ key: tls.key, cert: tls.cert }, handler);
230
+ }
231
+ else {
232
+ candidate = http.createServer(handler);
233
+ }
234
+ // Assign `this.server` ONLY after listen succeeds so EADDRINUSE never leaves a dead handle
235
+ await new Promise((resolve, reject) => {
236
+ candidate.once("error", (err) => {
237
+ try {
238
+ candidate.close();
239
+ }
240
+ catch {
241
+ // ignore
242
+ }
243
+ reject(err);
244
+ });
245
+ candidate.listen(port, "127.0.0.1", () => {
246
+ this.server = candidate;
247
+ resolve();
248
+ });
249
+ });
250
+ }
251
+ resetIdleTimer(ms) {
252
+ if (this.idleTimer)
253
+ clearTimeout(this.idleTimer);
254
+ this.idleTimer = setTimeout(() => {
255
+ this.close();
256
+ }, ms);
257
+ this.idleTimer.unref();
258
+ }
259
+ scheduleCloseIfIdle() {
260
+ if (this.pending.size === 0) {
261
+ setTimeout(() => {
262
+ if (this.pending.size === 0)
263
+ this.close();
264
+ }, 1500).unref();
265
+ }
266
+ }
267
+ close() {
268
+ if (this.idleTimer) {
269
+ clearTimeout(this.idleTimer);
270
+ this.idleTimer = null;
271
+ }
272
+ if (this.server) {
273
+ const srv = this.server;
274
+ this.server = null;
275
+ if (typeof srv.closeAllConnections === "function") {
276
+ srv.closeAllConnections();
277
+ }
278
+ srv.close();
279
+ }
280
+ }
281
+ }
282
+ function escapeHtml(s) {
283
+ return s
284
+ .replace(/&/g, "&amp;")
285
+ .replace(/</g, "&lt;")
286
+ .replace(/>/g, "&gt;")
287
+ .replace(/"/g, "&quot;")
288
+ .replace(/'/g, "&#39;");
289
+ }
290
+ //# sourceMappingURL=auth-callback.js.map
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Interactive CLI to connect real banks via Enable Banking PSD2 OAuth:
4
+ * bilan connect
5
+ * bilan connect --country RO --search Transilvania
6
+ * bilan connect --country GB --search Monzo --entity "Acme UK Ltd" --psu-type business
7
+ */
8
+ export declare function runConnectCli(argv?: string[]): Promise<void>;