easybill-mcp 1.0.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +123 -15
  2. package/dist/constants.d.ts +2 -1
  3. package/dist/constants.js +18 -1
  4. package/dist/constants.js.map +1 -1
  5. package/dist/hosted/accounts.d.ts +13 -0
  6. package/dist/hosted/accounts.js +70 -0
  7. package/dist/hosted/accounts.js.map +1 -0
  8. package/dist/hosted/config.d.ts +73 -0
  9. package/dist/hosted/config.js +200 -0
  10. package/dist/hosted/config.js.map +1 -0
  11. package/dist/hosted/http.d.ts +23 -0
  12. package/dist/hosted/http.js +524 -0
  13. package/dist/hosted/http.js.map +1 -0
  14. package/dist/hosted/pages.d.ts +22 -0
  15. package/dist/hosted/pages.js +130 -0
  16. package/dist/hosted/pages.js.map +1 -0
  17. package/dist/hosted/provider.d.ts +54 -0
  18. package/dist/hosted/provider.js +190 -0
  19. package/dist/hosted/provider.js.map +1 -0
  20. package/dist/hosted/store.d.ts +119 -0
  21. package/dist/hosted/store.js +254 -0
  22. package/dist/hosted/store.js.map +1 -0
  23. package/dist/hosted/upstream.d.ts +68 -0
  24. package/dist/hosted/upstream.js +280 -0
  25. package/dist/hosted/upstream.js.map +1 -0
  26. package/dist/index.d.ts +5 -1
  27. package/dist/index.js +19 -24
  28. package/dist/index.js.map +1 -1
  29. package/dist/instructions.d.ts +1 -1
  30. package/dist/instructions.js +16 -1
  31. package/dist/instructions.js.map +1 -1
  32. package/dist/server.d.ts +26 -0
  33. package/dist/server.js +47 -0
  34. package/dist/server.js.map +1 -0
  35. package/dist/services/client.d.ts +43 -4
  36. package/dist/services/client.js +35 -9
  37. package/dist/services/client.js.map +1 -1
  38. package/dist/services/format.d.ts +17 -4
  39. package/dist/services/format.js.map +1 -1
  40. package/dist/tools/catalog.d.ts +2 -2
  41. package/dist/tools/catalog.js.map +1 -1
  42. package/dist/tools/crud.d.ts +2 -2
  43. package/dist/tools/crud.js.map +1 -1
  44. package/dist/tools/customers.d.ts +2 -2
  45. package/dist/tools/customers.js +12 -4
  46. package/dist/tools/customers.js.map +1 -1
  47. package/dist/tools/documents.d.ts +2 -2
  48. package/dist/tools/documents.js +73 -43
  49. package/dist/tools/documents.js.map +1 -1
  50. package/dist/tools/files-io.d.ts +44 -0
  51. package/dist/tools/files-io.js +173 -0
  52. package/dist/tools/files-io.js.map +1 -0
  53. package/dist/tools/files.d.ts +2 -2
  54. package/dist/tools/files.js +9 -27
  55. package/dist/tools/files.js.map +1 -1
  56. package/dist/tools/finance.d.ts +2 -2
  57. package/dist/tools/finance.js.map +1 -1
  58. package/dist/tools/incoming.d.ts +11 -0
  59. package/dist/tools/incoming.js +222 -0
  60. package/dist/tools/incoming.js.map +1 -0
  61. package/dist/tools/meta.d.ts +2 -2
  62. package/dist/tools/meta.js +14 -6
  63. package/dist/tools/meta.js.map +1 -1
  64. package/dist/tools/registry.d.ts +40 -9
  65. package/dist/tools/registry.js +75 -12
  66. package/dist/tools/registry.js.map +1 -1
  67. package/dist/tools/search.d.ts +9 -8
  68. package/dist/tools/search.js +49 -17
  69. package/dist/tools/search.js.map +1 -1
  70. package/dist/tools/work.d.ts +2 -2
  71. package/dist/tools/work.js.map +1 -1
  72. package/package.json +5 -2
@@ -0,0 +1,130 @@
1
+ /**
2
+ * HTML for the connect page — the page a person lands on when they connect the
3
+ * MCP server in claude.ai. Server-rendered, no JavaScript, German UI.
4
+ */
5
+ const escape = (value) => value.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
6
+ const STYLE = `
7
+ :root { --bg:#f6f7f9; --card:#fff; --text:#1d2330; --muted:#5f6b7a; --line:#e3e7ed; --accent:#1f6feb; --ok:#1a7f37; --warn:#b35900; --danger:#c62828; color-scheme: light; }
8
+ @media (prefers-color-scheme: dark) { :root { --bg:#111418; --card:#1a1f26; --text:#e6e9ee; --muted:#9aa5b4; --line:#2a313b; --accent:#4c8dff; --ok:#3fb950; --warn:#e3913a; --danger:#f0605d; color-scheme: dark; } }
9
+ * { box-sizing: border-box; }
10
+ body { margin:0; background:var(--bg); color:var(--text); font:15px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif; padding:32px 16px; }
11
+ main { max-width:640px; margin:0 auto; }
12
+ h1 { font-size:22px; margin:0 0 6px; }
13
+ p.lead { color:var(--muted); margin:0 0 24px; }
14
+ .card { background:var(--card); border:1px solid var(--line); border-radius:10px; }
15
+ .tenant { display:flex; gap:12px; align-items:center; justify-content:space-between; padding:14px 16px; flex-wrap:wrap; }
16
+ .tenant + .tenant { border-top:1px solid var(--line); }
17
+ .name { font-weight:600; }
18
+ .status { font-size:13px; color:var(--muted); }
19
+ .status.ok { color:var(--ok); } .status.warn { color:var(--warn); }
20
+ .badge { font-size:12px; border:1px solid var(--line); border-radius:99px; padding:1px 8px; margin-left:6px; color:var(--muted); font-weight:400; }
21
+ .actions { display:flex; gap:8px; }
22
+ form { margin:0; }
23
+ button { font:inherit; font-size:14px; border-radius:7px; padding:6px 14px; cursor:pointer; border:1px solid var(--line); background:var(--card); color:var(--text); }
24
+ button.primary { background:var(--accent); border-color:var(--accent); color:#fff; }
25
+ button.link { border:none; background:none; color:var(--danger); padding:6px 4px; }
26
+ button:disabled { opacity:.45; cursor:not-allowed; }
27
+ .footer { display:flex; gap:12px; justify-content:flex-end; align-items:center; margin-top:20px; flex-wrap:wrap; }
28
+ .footer .hint { margin-right:auto; color:var(--muted); font-size:13px; }
29
+ .banner { border-radius:8px; padding:10px 14px; margin-bottom:16px; font-size:14px; border:1px solid; }
30
+ .banner.error { border-color:var(--danger); color:var(--danger); }
31
+ .banner.notice { border-color:var(--ok); color:var(--ok); }
32
+ details { margin-top:24px; color:var(--muted); font-size:13px; }
33
+ `;
34
+ let iconLink = "";
35
+ /** Links the configured icon from every page (set once at startup). */
36
+ export function setPageIcon(href, mimeType) {
37
+ iconLink = `<link rel="icon" href="${escape(href)}" type="${escape(mimeType)}">`;
38
+ }
39
+ function layout(title, body) {
40
+ return `<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
41
+ <meta name="referrer" content="no-referrer"><title>${escape(title)}</title>${iconLink}<style>${STYLE}</style></head>
42
+ <body><main>${body}</main></body></html>`;
43
+ }
44
+ const formatDate = (seconds) => new Date(seconds * 1000).toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", year: "numeric", timeZone: "Europe/Berlin" });
45
+ function tenantRow(sessionId, tenant, connection, mode) {
46
+ const base = `/connect/${encodeURIComponent(sessionId)}/tenants/${encodeURIComponent(tenant.id)}`;
47
+ const badge = `<span class="badge">${tenant.writes ? "Lesen &amp; Schreiben" : "Nur lesen"}</span>`;
48
+ // API-key mode opens a form (GET); OAuth mode starts the easybill login (POST).
49
+ const connectButton = (label, primary) => mode === "apikey"
50
+ ? `<form method="get" action="${base}/key"><button${primary ? ' class="primary"' : ""}>${label}</button></form>`
51
+ : `<form method="post" action="${base}/connect"><button${primary ? ' class="primary"' : ""}>${label}</button></form>`;
52
+ const disconnect = `<form method="post" action="${base}/disconnect"><button class="link">Trennen</button></form>`;
53
+ let status;
54
+ let actions;
55
+ if (!connection) {
56
+ status = `<div class="status">Nicht verbunden</div>`;
57
+ actions = connectButton("Verbinden", true);
58
+ }
59
+ else if (connection.broken_reason) {
60
+ status = `<div class="status warn">${connection.auth_kind === "apikey" ? "API-Key ungültig – bitte neu hinterlegen" : "Verbindung abgelaufen – bitte neu verbinden"}</div>`;
61
+ actions = connectButton("Neu verbinden", true) + disconnect;
62
+ }
63
+ else {
64
+ const who = connection.login_label
65
+ ? connection.auth_kind === "apikey"
66
+ ? ` (${escape(connection.login_label)})`
67
+ : ` als ${escape(connection.login_label)}`
68
+ : "";
69
+ status = `<div class="status ok">✓ Verbunden${who} · seit ${formatDate(connection.connected_at)}</div>`;
70
+ actions = connectButton("Neu verbinden", false) + disconnect;
71
+ }
72
+ return `<div class="tenant"><div><div class="name">${escape(tenant.name)}${badge}</div>${status}</div><div class="actions">${actions}</div></div>`;
73
+ }
74
+ export function renderConnectPage({ mode, viewer, session, tenants, connections, error, notice }) {
75
+ const byTenant = new Map(connections.map((c) => [c.tenant_id, c]));
76
+ const usable = connections.filter((c) => !c.broken_reason && tenants.some((t) => t.id === c.tenant_id)).length;
77
+ const sid = encodeURIComponent(session.id);
78
+ const banners = (error ? `<div class="banner error">${escape(error)}</div>` : "") +
79
+ (notice ? `<div class="banner notice">${escape(notice)}</div>` : "");
80
+ const footer = session.kind === "authorize"
81
+ ? `<div class="footer">
82
+ <span class="hint">${usable === 0 ? "Verbinde mindestens einen Account." : `${usable} Account${usable === 1 ? "" : "s"} verbunden.`}</span>
83
+ <form method="post" action="/connect/${sid}/cancel"><button>Abbrechen</button></form>
84
+ <form method="post" action="/connect/${sid}/finish"><button class="primary"${usable === 0 ? " disabled" : ""}>Fertig – zurück zu Claude</button></form>
85
+ </div>`
86
+ : `<div class="footer"><form method="post" action="/connect/${sid}/finish"><button class="primary">Fertig</button></form></div>`;
87
+ return layout("easybill verbinden", `<h1>easybill-Accounts verbinden</h1>
88
+ <p class="lead">Verbinde jeden Account, auf den du Zugriff hast, ${mode === "apikey" ? "mit deinem persönlichen easybill-API-Key" : "mit deinem eigenen easybill-Login"}.
89
+ Accounts ohne Zugriff lässt du einfach aus – du kannst sie später ergänzen.</p>
90
+ ${viewer ? `<p class="status" style="margin:-16px 0 20px">Angemeldet als ${escape(viewer)}</p>` : ""}
91
+ ${banners}
92
+ <div class="card">${tenants.map((t) => tenantRow(session.id, t, byTenant.get(t.id), mode)).join("")}</div>
93
+ ${footer}
94
+ <details><summary>Hinweise</summary>${mode === "apikey"
95
+ ? `<p>Dein API-Key wird verschlüsselt gespeichert und nur für deine eigenen Anfragen über Claude verwendet.</p>
96
+ <p>Den Zugriff entziehst du hier über „Trennen“ – oder in easybill, indem du einen neuen API-Key generierst; der alte ist dann ungültig.</p>`
97
+ : `<p>„Verbinden“ öffnet die Anmeldung von easybill. Deine Zugangsdaten gibst du nur dort ein; dieser Server sieht sie nie und speichert nur das Zugriffstoken, das easybill ausstellt.</p>
98
+ <p>Meldet easybill dich automatisch mit dem falschen Account an, melde dich in easybill ab und verbinde erneut.</p>
99
+ <p>Den Zugriff kannst du jederzeit hier über „Trennen“ oder in easybill selbst entziehen.</p>`}
100
+ </details>`);
101
+ }
102
+ export function renderKeyForm(session, tenant, error) {
103
+ const sid = encodeURIComponent(session.id);
104
+ const action = `/connect/${sid}/tenants/${encodeURIComponent(tenant.id)}/key`;
105
+ return layout(`${tenant.name} verbinden`, `<h1>„${escape(tenant.name)}“ verbinden</h1>
106
+ <p class="lead">Füge deinen persönlichen API-Key aus diesem easybill-Account ein.</p>
107
+ ${error ? `<div class="banner error">${escape(error)}</div>` : ""}
108
+ <div class="card" style="padding:16px">
109
+ <ol style="margin:0 0 16px; padding-left:20px">
110
+ <li>In easybill bei „${escape(tenant.name)}“ einloggen.</li>
111
+ <li>Rechts oben aufs Benutzer-Icon → <b>Profil und Einstellungen</b>.</li>
112
+ <li>Im Abschnitt <b>API Key</b> den Schlüssel über das Augensymbol anzeigen und kopieren.
113
+ Gibt es noch keinen: <b>Neuen Schlüssel generieren</b> und rechts oben <b>Speichern</b>.</li>
114
+ </ol>
115
+ <form method="post" action="${action}">
116
+ <label for="api_key" style="display:block; font-weight:600; margin-bottom:6px">API-Key</label>
117
+ <input id="api_key" name="api_key" type="password" required autocomplete="off" spellcheck="false"
118
+ style="width:100%; font:inherit; padding:8px 10px; border:1px solid var(--line); border-radius:7px; background:var(--bg); color:var(--text)">
119
+ <div class="footer">
120
+ <span class="hint">Ein neu generierter Key ersetzt den alten – Integrationen, die den alten nutzen, hören dann auf zu funktionieren.</span>
121
+ <a href="/connect/${sid}" style="color:var(--muted)">Zurück</a>
122
+ <button class="primary">Prüfen und verbinden</button>
123
+ </div>
124
+ </form>
125
+ </div>`);
126
+ }
127
+ export function renderMessage(title, text) {
128
+ return layout(title, `<h1>${escape(title)}</h1><p class="lead">${escape(text)}</p>`);
129
+ }
130
+ //# sourceMappingURL=pages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pages.js","sourceRoot":"","sources":["../../src/hosted/pages.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,MAAM,MAAM,GAAG,CAAC,KAAa,EAAU,EAAE,CACvC,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC;AAElH,MAAM,KAAK,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2Bb,CAAC;AAEF,IAAI,QAAQ,GAAG,EAAE,CAAC;AAElB,uEAAuE;AACvE,MAAM,UAAU,WAAW,CAAC,IAAY,EAAE,QAAgB;IACxD,QAAQ,GAAG,0BAA0B,MAAM,CAAC,IAAI,CAAC,WAAW,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;AACnF,CAAC;AAED,SAAS,MAAM,CAAC,KAAa,EAAE,IAAY;IACzC,OAAO;qDAC4C,MAAM,CAAC,KAAK,CAAC,WAAW,QAAQ,UAAU,KAAK;cACtF,IAAI,uBAAuB,CAAC;AAC1C,CAAC;AAED,MAAM,UAAU,GAAG,CAAC,OAAe,EAAU,EAAE,CAC7C,IAAI,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC,kBAAkB,CAAC,OAAO,EAAE,EAAE,GAAG,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,eAAe,EAAE,CAAC,CAAC;AAIzI,SAAS,SAAS,CAChB,SAAiB,EACjB,MAAoB,EACpB,UAAqC,EACrC,IAAiB;IAE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AI,CAAC;;MAEzB,KAAK,CAAC,CAAC,CAAC,6BAA6B,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE;;;+BAGtC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC;;;;;oCAKd,MAAM;;;;;;8BAMZ,GAAG;;;;WAItB,CACR,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,KAAa,EAAE,IAAY;IACvD,OAAO,MAAM,CAAC,KAAK,EAAE,OAAO,MAAM,CAAC,KAAK,CAAC,wBAAwB,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACvF,CAAC"}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The OAuth authorization server MCP clients (claude.ai, Claude Code, …) talk to.
3
+ *
4
+ * The SDK's mcpAuthRouter handles the protocol (metadata, dynamic client
5
+ * registration, PKCE checks, token endpoint); this provider supplies the state.
6
+ *
7
+ * The interesting step is `authorize`: instead of a login form it sends the
8
+ * person to the connect page, where they link their easybill accounts via
9
+ * easybill's own OAuth. Only when they press "Fertig" does the MCP client get its
10
+ * authorization code (see `completeAuthorization`).
11
+ */
12
+ import type { Request, Response } from "express";
13
+ import type { OAuthRegisteredClientsStore } from "@modelcontextprotocol/sdk/server/auth/clients.js";
14
+ import type { AuthorizationParams, OAuthServerProvider } from "@modelcontextprotocol/sdk/server/auth/provider.js";
15
+ import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
16
+ import type { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
17
+ import type { HostedConfig } from "./config.js";
18
+ import type { SessionRow, Store } from "./store.js";
19
+ /** How long the connect page stays usable once opened. */
20
+ export declare const SESSION_TTL_SECONDS: number;
21
+ export declare const GRANT_COOKIE = "easybill_mcp_grant";
22
+ /**
23
+ * Remembers a person's grant in their browser, so reconnecting the MCP client
24
+ * (new token, same person) finds the easybill accounts already connected.
25
+ */
26
+ export declare class GrantCookie {
27
+ private readonly secret;
28
+ private readonly secure;
29
+ constructor(secret: string, secure: boolean);
30
+ private sign;
31
+ read(req: Request): string | undefined;
32
+ write(res: Response, grantId: string): void;
33
+ clear(res: Response): void;
34
+ }
35
+ export declare class HostedOAuthProvider implements OAuthServerProvider {
36
+ private readonly config;
37
+ private readonly store;
38
+ private readonly cookie;
39
+ readonly clientsStore: OAuthRegisteredClientsStore;
40
+ constructor(config: HostedConfig, store: Store, cookie: GrantCookie);
41
+ /** Accepts the MCP endpoint (and the bare origin, which some clients send) as RFC 8707 resource. */
42
+ private checkResource;
43
+ authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise<void>;
44
+ /** Called when the person presses "Fertig": returns the redirect back to the MCP client. */
45
+ completeAuthorization(session: SessionRow): string;
46
+ /** Called when the person cancels: tells the MCP client access was denied. */
47
+ denyAuthorization(session: SessionRow): string;
48
+ challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise<string>;
49
+ exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, _codeVerifier?: string, redirectUri?: string, resource?: URL): Promise<OAuthTokens>;
50
+ exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, _scopes?: string[], resource?: URL): Promise<OAuthTokens>;
51
+ private issueTokens;
52
+ verifyAccessToken(token: string): Promise<AuthInfo>;
53
+ revokeToken(_client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest): Promise<void>;
54
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * The OAuth authorization server MCP clients (claude.ai, Claude Code, …) talk to.
3
+ *
4
+ * The SDK's mcpAuthRouter handles the protocol (metadata, dynamic client
5
+ * registration, PKCE checks, token endpoint); this provider supplies the state.
6
+ *
7
+ * The interesting step is `authorize`: instead of a login form it sends the
8
+ * person to the connect page, where they link their easybill accounts via
9
+ * easybill's own OAuth. Only when they press "Fertig" does the MCP client get its
10
+ * authorization code (see `completeAuthorization`).
11
+ */
12
+ import { createHmac, timingSafeEqual } from "node:crypto";
13
+ import { InvalidGrantError, InvalidTargetError, InvalidTokenError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
14
+ /** How long the connect page stays usable once opened. */
15
+ export const SESSION_TTL_SECONDS = 30 * 60;
16
+ export const GRANT_COOKIE = "easybill_mcp_grant";
17
+ const GRANT_COOKIE_MAX_AGE = 180 * 24 * 3600;
18
+ /**
19
+ * Remembers a person's grant in their browser, so reconnecting the MCP client
20
+ * (new token, same person) finds the easybill accounts already connected.
21
+ */
22
+ export class GrantCookie {
23
+ secret;
24
+ secure;
25
+ constructor(secret, secure) {
26
+ this.secret = secret;
27
+ this.secure = secure;
28
+ }
29
+ sign(grantId) {
30
+ return createHmac("sha256", this.secret).update(`grant:${grantId}`).digest("base64url");
31
+ }
32
+ read(req) {
33
+ const header = req.headers.cookie;
34
+ if (!header)
35
+ return undefined;
36
+ for (const part of header.split(";")) {
37
+ const [name, ...rest] = part.trim().split("=");
38
+ if (name !== GRANT_COOKIE)
39
+ continue;
40
+ const [grantId, signature] = decodeURIComponent(rest.join("=")).split(".");
41
+ if (!grantId || !signature)
42
+ return undefined;
43
+ const expected = Buffer.from(this.sign(grantId));
44
+ const actual = Buffer.from(signature);
45
+ return expected.length === actual.length && timingSafeEqual(expected, actual) ? grantId : undefined;
46
+ }
47
+ return undefined;
48
+ }
49
+ write(res, grantId) {
50
+ res.cookie(GRANT_COOKIE, `${grantId}.${this.sign(grantId)}`, {
51
+ httpOnly: true,
52
+ secure: this.secure,
53
+ sameSite: "lax",
54
+ maxAge: GRANT_COOKIE_MAX_AGE * 1000,
55
+ path: "/",
56
+ });
57
+ }
58
+ clear(res) {
59
+ res.clearCookie(GRANT_COOKIE, { path: "/" });
60
+ }
61
+ }
62
+ export class HostedOAuthProvider {
63
+ config;
64
+ store;
65
+ cookie;
66
+ clientsStore;
67
+ constructor(config, store, cookie) {
68
+ this.config = config;
69
+ this.store = store;
70
+ this.cookie = cookie;
71
+ this.clientsStore = {
72
+ getClient: (clientId) => store.getClient(clientId),
73
+ registerClient: (client) => {
74
+ const full = client;
75
+ store.saveClient(full);
76
+ return full;
77
+ },
78
+ };
79
+ }
80
+ /** Accepts the MCP endpoint (and the bare origin, which some clients send) as RFC 8707 resource. */
81
+ checkResource(resource) {
82
+ if (!resource)
83
+ return;
84
+ const allowed = [this.config.mcpUrl.href, this.config.publicUrl.href, `${this.config.publicUrl.origin}/`];
85
+ if (!allowed.includes(resource.href)) {
86
+ throw new InvalidTargetError(`This server only issues tokens for ${this.config.mcpUrl.href}`);
87
+ }
88
+ }
89
+ async authorize(client, params, res) {
90
+ this.checkResource(params.resource);
91
+ const remembered = this.cookie.read(res.req);
92
+ const grantId = remembered && this.store.grantExists(remembered) ? remembered : this.store.createGrant();
93
+ const sessionId = this.store.createSession({
94
+ kind: "authorize",
95
+ grant_id: grantId,
96
+ client_id: client.client_id,
97
+ redirect_uri: params.redirectUri,
98
+ code_challenge: params.codeChallenge,
99
+ state: params.state ?? null,
100
+ resource: params.resource?.href ?? null,
101
+ }, SESSION_TTL_SECONDS);
102
+ res.redirect(302, `/connect/${sessionId}`);
103
+ }
104
+ /** Called when the person presses "Fertig": returns the redirect back to the MCP client. */
105
+ completeAuthorization(session) {
106
+ if (session.kind !== "authorize" || !session.client_id || !session.redirect_uri || !session.code_challenge) {
107
+ throw new Error("not an authorization session");
108
+ }
109
+ const code = this.store.createCode({
110
+ grant_id: session.grant_id,
111
+ client_id: session.client_id,
112
+ code_challenge: session.code_challenge,
113
+ redirect_uri: session.redirect_uri,
114
+ resource: session.resource,
115
+ });
116
+ this.store.deleteSession(session.id);
117
+ const target = new URL(session.redirect_uri);
118
+ target.searchParams.set("code", code);
119
+ if (session.state)
120
+ target.searchParams.set("state", session.state);
121
+ return target.href;
122
+ }
123
+ /** Called when the person cancels: tells the MCP client access was denied. */
124
+ denyAuthorization(session) {
125
+ this.store.deleteSession(session.id);
126
+ const target = new URL(session.redirect_uri);
127
+ target.searchParams.set("error", "access_denied");
128
+ target.searchParams.set("error_description", "The user cancelled connecting easybill.");
129
+ if (session.state)
130
+ target.searchParams.set("state", session.state);
131
+ return target.href;
132
+ }
133
+ async challengeForAuthorizationCode(client, authorizationCode) {
134
+ const row = this.store.getCode(authorizationCode);
135
+ if (!row || row.client_id !== client.client_id)
136
+ throw new InvalidGrantError("Invalid authorization code");
137
+ return row.code_challenge;
138
+ }
139
+ async exchangeAuthorizationCode(client, authorizationCode, _codeVerifier, redirectUri, resource) {
140
+ const row = this.store.getCode(authorizationCode);
141
+ if (!row || row.client_id !== client.client_id)
142
+ throw new InvalidGrantError("Invalid authorization code");
143
+ if (redirectUri !== undefined && redirectUri !== row.redirect_uri) {
144
+ throw new InvalidGrantError("redirect_uri does not match the authorization request");
145
+ }
146
+ this.checkResource(resource);
147
+ // Single use, also when the exchange fails further down.
148
+ this.store.deleteCode(authorizationCode);
149
+ return this.issueTokens(row.grant_id, client.client_id, resource?.href ?? row.resource);
150
+ }
151
+ async exchangeRefreshToken(client, refreshToken, _scopes, resource) {
152
+ const row = this.store.getToken(refreshToken);
153
+ if (!row || row.kind !== "refresh" || row.client_id !== client.client_id || !this.store.grantExists(row.grant_id)) {
154
+ throw new InvalidGrantError("Invalid refresh token");
155
+ }
156
+ this.checkResource(resource);
157
+ // Rotate: the old refresh token stops working.
158
+ this.store.deleteToken(refreshToken);
159
+ return this.issueTokens(row.grant_id, client.client_id, resource?.href ?? row.resource);
160
+ }
161
+ issueTokens(grantId, clientId, resource) {
162
+ const access = this.store.createToken({ kind: "access", grant_id: grantId, client_id: clientId, resource }, this.config.accessTokenTtlSeconds);
163
+ const refresh = this.store.createToken({ kind: "refresh", grant_id: grantId, client_id: clientId, resource }, this.config.refreshTokenTtlSeconds);
164
+ this.store.touchGrant(grantId);
165
+ return {
166
+ access_token: access.token,
167
+ token_type: "Bearer",
168
+ expires_in: this.config.accessTokenTtlSeconds,
169
+ refresh_token: refresh.token,
170
+ };
171
+ }
172
+ async verifyAccessToken(token) {
173
+ const row = this.store.getToken(token);
174
+ if (!row || row.kind !== "access" || !this.store.grantExists(row.grant_id)) {
175
+ throw new InvalidTokenError("Invalid or expired access token");
176
+ }
177
+ return {
178
+ token,
179
+ clientId: row.client_id,
180
+ scopes: [],
181
+ expiresAt: row.expires_at,
182
+ ...(row.resource ? { resource: new URL(row.resource) } : {}),
183
+ extra: { grantId: row.grant_id },
184
+ };
185
+ }
186
+ async revokeToken(_client, request) {
187
+ this.store.deleteToken(request.token);
188
+ }
189
+ }
190
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/hosted/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAG1D,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,iDAAiD,CAAC;AAW3H,0DAA0D;AAC1D,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,GAAG,EAAE,CAAC;AAE3C,MAAM,CAAC,MAAM,YAAY,GAAG,oBAAoB,CAAC;AACjD,MAAM,oBAAoB,GAAG,GAAG,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7C;;;GAGG;AACH,MAAM,OAAO,WAAW;IAEH;IACA;IAFnB,YACmB,MAAc,EACd,MAAe;QADf,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAS;IAC/B,CAAC;IAEI,IAAI,CAAC,OAAe;QAC1B,OAAO,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,SAAS,OAAO,EAAE,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAC1F,CAAC;IAED,IAAI,CAAC,GAAY;QACf,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC;QAClC,IAAI,CAAC,MAAM;YAAE,OAAO,SAAS,C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,CAAC,CAAC,EAAE,QAAQ,EAAE,IAAI,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC5D,KAAK,EAAE,EAAE,OAAO,EAAE,GAAG,CAAC,QAAQ,EAAE;SACjC,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,OAAmC,EAAE,OAAoC;QACzF,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACxC,CAAC;CACF"}
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Persistent state for hosted mode, in SQLite (node:sqlite, no extra dependency).
3
+ *
4
+ * Vocabulary:
5
+ * - grant: one person's bundle of easybill connections. Every token this
6
+ * server issues to an MCP client points at a grant.
7
+ * - connection: a grant's OAuth tokens for one tenant (easybill account).
8
+ * - session: a short-lived visit to the connect page, either during the MCP
9
+ * client's OAuth authorization ("authorize") or from a link the
10
+ * model handed out ("manage").
11
+ *
12
+ * Secrets at rest: easybill tokens are AES-256-GCM encrypted; tokens this server
13
+ * issues are stored only as SHA-256 hashes.
14
+ */
15
+ import type { OAuthClientInformationFull } from "@modelcontextprotocol/sdk/shared/auth.js";
16
+ export declare const randomToken: (bytes?: number) => string;
17
+ export declare const sha256: (value: string) => string;
18
+ export interface SessionRow {
19
+ id: string;
20
+ kind: "authorize" | "manage";
21
+ grant_id: string;
22
+ client_id: string | null;
23
+ redirect_uri: string | null;
24
+ code_challenge: string | null;
25
+ state: string | null;
26
+ resource: string | null;
27
+ expires_at: number;
28
+ }
29
+ export interface ConnectionRow {
30
+ grant_id: string;
31
+ tenant_id: string;
32
+ /** "apikey": a personal easybill API key in access_token. "oauth": easybill OAuth tokens. */
33
+ auth_kind: "apikey" | "oauth";
34
+ access_token: string;
35
+ refresh_token: string;
36
+ access_expires_at: number;
37
+ refresh_expires_at: number;
38
+ /** Who logged in, for display: name / email from easybill. */
39
+ login_label: string | null;
40
+ claims: Record<string, unknown>;
41
+ connected_at: number;
42
+ /** Set when a refresh failed for good; the person has to reconnect. */
43
+ broken_reason: string | null;
44
+ }
45
+ export interface TokenRow {
46
+ kind: "access" | "refresh";
47
+ grant_id: string;
48
+ client_id: string;
49
+ resource: string | null;
50
+ expires_at: number;
51
+ }
52
+ export interface CodeRow {
53
+ grant_id: string;
54
+ client_id: string;
55
+ code_challenge: string;
56
+ redirect_uri: string;
57
+ resource: string | null;
58
+ expires_at: number;
59
+ }
60
+ export declare class Store {
61
+ private readonly db;
62
+ private readonly key;
63
+ constructor(dbPath: string, secret: string);
64
+ close(): void;
65
+ private encrypt;
66
+ private decrypt;
67
+ getMeta(key: string): string | undefined;
68
+ setMeta(key: string, value: string): void;
69
+ /** Secret metadata (the upstream client secret) goes through here. */
70
+ getSecretMeta(key: string): string | undefined;
71
+ setSecretMeta(key: string, value: string): void;
72
+ getClient(clientId: string): OAuthClientInformationFull | undefined;
73
+ saveClient(client: OAuthClientInformationFull): void;
74
+ createGrant(): string;
75
+ grantExists(id: string): boolean;
76
+ touchGrant(id: string): void;
77
+ createSession(row: Omit<SessionRow, "id" | "expires_at">, ttlSeconds: number): string;
78
+ getSession(id: string): SessionRow | undefined;
79
+ deleteSession(id: string): void;
80
+ createUpstreamState(sessionId: string, tenantId: string, codeVerifier: string): string;
81
+ /** Single use: the row is deleted as it is read. */
82
+ takeUpstreamState(state: string): {
83
+ sessionId: string;
84
+ tenantId: string;
85
+ codeVerifier: string;
86
+ } | undefined;
87
+ saveConnection(row: Omit<ConnectionRow, "broken_reason">): void;
88
+ updateConnectionTokens(grantId: string, tenantId: string, tokens: {
89
+ access_token: string;
90
+ refresh_token: string;
91
+ access_expires_at: number;
92
+ refresh_expires_at: number;
93
+ }): void;
94
+ markConnectionBroken(grantId: string, tenantId: string, reason: string): void;
95
+ getConnection(grantId: string, tenantId: string): ConnectionRow | undefined;
96
+ listConnections(grantId: string): ConnectionRow[];
97
+ deleteConnection(grantId: string, tenantId: string): void;
98
+ private decodeConnection;
99
+ /**
100
+ * The easybill login IDs seen when a tenant was first connected. An API key
101
+ * carries no account identifier, so this is how we recognise "same company"
102
+ * later: login IDs are unique across easybill.
103
+ */
104
+ getTenantFingerprint(tenantId: string): string[] | undefined;
105
+ setTenantFingerprint(tenantId: string, loginIds: string[]): void;
106
+ /** All tenants' fingerprints, to refuse a key that belongs to a different tenant. */
107
+ listTenantFingerprints(): Map<string, string[]>;
108
+ createCode(row: Omit<CodeRow, "expires_at">): string;
109
+ getCode(code: string): CodeRow | undefined;
110
+ deleteCode(code: string): void;
111
+ createToken(row: Omit<TokenRow, "expires_at">, ttlSeconds: number): {
112
+ token: string;
113
+ expiresAt: number;
114
+ };
115
+ getToken(token: string): TokenRow | undefined;
116
+ deleteToken(token: string): void;
117
+ /** Drops expired rows. Cheap; run it periodically. */
118
+ purgeExpired(): void;
119
+ }