docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,102 +0,0 @@
|
||||
# accounted-mcp
|
||||
|
||||
Connect Claude Desktop, Claude Code, or another stdio MCP client to your
|
||||
[Accounted](https://app.accounted.se) bookkeeping account.
|
||||
|
||||
This zero-dependency bridge forwards JSON-RPC over stdio to the hosted Accounted
|
||||
MCP server. New connections receive the `accounted_*` tool namespace. Existing
|
||||
`gnubok-mcp` configurations remain supported separately.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Create an API key in Accounted under **Settings > API**.
|
||||
2. Add the bridge to your MCP client:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"accounted": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "accounted-mcp"],
|
||||
"env": {
|
||||
"ACCOUNTED_API_KEY": "gnubok_sk_test_...",
|
||||
"ACCOUNTED_CLIENT": "claude-desktop"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The credential value retains the legacy `gnubok_sk_*` wire prefix for backward
|
||||
compatibility. Only the MCP integration is being renamed in this release.
|
||||
|
||||
## Environment variables
|
||||
|
||||
| Variable | Required | Default | Description |
|
||||
|---|---:|---|---|
|
||||
| `ACCOUNTED_API_KEY` | yes | none | Your existing Accounted API key. |
|
||||
| `ACCOUNTED_URL` | no | Accounted hosted MCP endpoint | Override for self-hosted Accounted. The bridge adds `tool_namespace=accounted` when omitted. |
|
||||
| `ACCOUNTED_CLIENT` | no | none | Telemetry-only distribution marker such as `claude-desktop`. |
|
||||
|
||||
The API key scopes determine which tools are visible and callable. Write tools
|
||||
stage pending operations for explicit approval before anything is booked.
|
||||
|
||||
## OAuth connector (no API key, no account needed up front)
|
||||
|
||||
Clients with OAuth support connect directly without this bridge and without an
|
||||
existing API key. The sign-in screen lets a new user create the Accounted
|
||||
account (BankID or e-mail), and company setup then continues in the
|
||||
conversation through the `onboarding` skill and `accounted_create_company`:
|
||||
|
||||
```text
|
||||
https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted
|
||||
```
|
||||
|
||||
```bash
|
||||
# Claude Code
|
||||
claude mcp add --transport http accounted \
|
||||
"https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted"
|
||||
|
||||
# OpenAI Codex
|
||||
codex mcp add accounted --url \
|
||||
"https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted"
|
||||
```
|
||||
|
||||
Claude.ai and Claude Desktop: Settings > Connectors > Add custom connector,
|
||||
paste the URL, then in step 2 choose:
|
||||
|
||||
- **Authentication: "Required when the server asks."** Claude auto-detects
|
||||
"None" because the server answers the handshake without credentials; with
|
||||
"None" the first company-scoped call shows an error instead of the sign-in.
|
||||
- **OAuth client: "No client ID, register one automatically" (DCR).** The
|
||||
server does not advertise Anthropic's hosted client metadata (CIMD) yet.
|
||||
- No additional headers; transport stays Streamable HTTP.
|
||||
|
||||
The connector works before you connect (documentation tools); the first
|
||||
company-scoped call opens the sign-in prompt, where a new user creates the
|
||||
account.
|
||||
|
||||
## Compatibility
|
||||
|
||||
The legacy `gnubok-mcp` package, environment variables, endpoint behavior, and
|
||||
`gnubok_*` tool aliases remain supported. Existing installations do not need to
|
||||
change.
|
||||
|
||||
## Releasing
|
||||
|
||||
The package is published to npm by the `Publish MCP bridges to npm` workflow
|
||||
(`.github/workflows/npm-publish.yml`), never by hand:
|
||||
|
||||
1. Bump `version` in `packages/accounted-mcp/package.json`.
|
||||
2. Merge the change to `main`.
|
||||
3. The workflow compares the new version with the registry and, if it is not
|
||||
there yet, runs `npm publish --provenance --access public`. A version that
|
||||
already exists on npm is skipped, so other `package.json` edits are harmless.
|
||||
|
||||
The workflow needs the repository secret `NPM_TOKEN`: an npm granular access
|
||||
token with read and write access to `accounted-mcp` and `gnubok-mcp`, with
|
||||
two-factor bypass enabled so CI can publish. npm caps the lifetime of such
|
||||
tokens (90 days at the time of writing), so rotate the secret before it lapses.
|
||||
Without the secret the run fails at its first step. The workflow can also be
|
||||
started from the Actions tab, for one package or both, with a dry-run option
|
||||
that packs and validates without publishing.
|
||||
@@ -1,35 +0,0 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
const packageDir = path.resolve(__dirname, '..')
|
||||
const packageJson = JSON.parse(
|
||||
readFileSync(path.join(packageDir, 'package.json'), 'utf8')
|
||||
) as {
|
||||
name: string
|
||||
bin: Record<string, string>
|
||||
dependencies?: Record<string, string>
|
||||
}
|
||||
const source = readFileSync(path.join(packageDir, 'index.mjs'), 'utf8')
|
||||
|
||||
describe('accounted-mcp package', () => {
|
||||
it('publishes the Accounted command without runtime dependencies', () => {
|
||||
expect(packageJson.name).toBe('accounted-mcp')
|
||||
expect(packageJson.bin).toEqual({ 'accounted-mcp': './index.mjs' })
|
||||
expect(packageJson.dependencies).toBeUndefined()
|
||||
})
|
||||
|
||||
it('uses Accounted configuration names and preserves the API-key wire prefix', () => {
|
||||
expect(source).toContain('ACCOUNTED_API_KEY')
|
||||
expect(source).toContain('ACCOUNTED_URL')
|
||||
expect(source).toContain('ACCOUNTED_CLIENT')
|
||||
expect(source).toContain('X-Accounted-Client')
|
||||
expect(source).toContain('tool_namespace')
|
||||
expect(source).toContain('gnubok_sk_')
|
||||
|
||||
expect(source).not.toContain('GNUBOK_API_KEY')
|
||||
expect(source).not.toContain('GNUBOK_URL')
|
||||
expect(source).not.toContain('X-Gnubok-Client')
|
||||
expect(source).not.toContain('app.gnubok.se')
|
||||
})
|
||||
})
|
||||
@@ -1,168 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* accounted-mcp: Connect an MCP client to your Accounted bookkeeping account.
|
||||
*
|
||||
* Usage in claude_desktop_config.json:
|
||||
* {
|
||||
* "mcpServers": {
|
||||
* "accounted": {
|
||||
* "command": "npx",
|
||||
* "args": ["-y", "accounted-mcp"],
|
||||
* "env": {
|
||||
* "ACCOUNTED_API_KEY": "gnubok_sk_..."
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
|
||||
const API_KEY = process.env.ACCOUNTED_API_KEY
|
||||
const DEFAULT_MCP_URL =
|
||||
'https://app.accounted.se/api/extensions/ext/mcp-server/mcp'
|
||||
|
||||
function resolveMcpUrl(rawUrl) {
|
||||
try {
|
||||
const url = new URL(rawUrl)
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
||||
throw new Error('unsupported protocol')
|
||||
}
|
||||
if (!url.searchParams.has('tool_namespace')) {
|
||||
url.searchParams.set('tool_namespace', 'accounted')
|
||||
}
|
||||
return url.toString()
|
||||
} catch {
|
||||
process.stderr.write('accounted-mcp: ACCOUNTED_URL must be a valid HTTP(S) URL\n')
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
const MCP_URL = resolveMcpUrl(process.env.ACCOUNTED_URL || DEFAULT_MCP_URL)
|
||||
|
||||
// Optional distribution-channel marker (for example, "claude-desktop").
|
||||
// Forwarded for telemetry only and never used for authentication or behavior.
|
||||
const rawClient = process.env.ACCOUNTED_CLIENT
|
||||
const CLIENT =
|
||||
rawClient && /^[A-Za-z0-9._-]{1,64}$/.test(rawClient) ? rawClient : undefined
|
||||
if (rawClient && !CLIENT) {
|
||||
process.stderr.write(
|
||||
'accounted-mcp: ignoring ACCOUNTED_CLIENT: must match [A-Za-z0-9._-]{1,64}\n'
|
||||
)
|
||||
}
|
||||
|
||||
if (!API_KEY) {
|
||||
process.stderr.write(
|
||||
'Error: ACCOUNTED_API_KEY is required.\n' +
|
||||
'Get your API key at: https://app.accounted.se/settings/api\n' +
|
||||
'\n' +
|
||||
'No API key (or no account yet)? Connect over OAuth instead; the sign-in\n' +
|
||||
'screen lets you create the account, and setup continues in the chat:\n' +
|
||||
' claude mcp add --transport http accounted \\\n' +
|
||||
' "https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted"\n' +
|
||||
' codex mcp add accounted --url \\\n' +
|
||||
' "https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted"\n' +
|
||||
' Claude.ai / Desktop: Settings > Connectors > Add custom connector with that URL.\n' +
|
||||
'\n' +
|
||||
'Add it to your Claude Desktop config:\n' +
|
||||
'{\n' +
|
||||
' "mcpServers": {\n' +
|
||||
' "accounted": {\n' +
|
||||
' "command": "npx",\n' +
|
||||
' "args": ["-y", "accounted-mcp"],\n' +
|
||||
' "env": {\n' +
|
||||
' "ACCOUNTED_API_KEY": "gnubok_sk_..."\n' +
|
||||
' }\n' +
|
||||
' }\n' +
|
||||
' }\n' +
|
||||
'}\n'
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
let buffer = ''
|
||||
|
||||
process.stdin.setEncoding('utf8')
|
||||
process.stdin.on('data', (chunk) => {
|
||||
buffer += chunk
|
||||
|
||||
let newlineIdx
|
||||
while ((newlineIdx = buffer.indexOf('\n')) !== -1) {
|
||||
const line = buffer.slice(0, newlineIdx).trim()
|
||||
buffer = buffer.slice(newlineIdx + 1)
|
||||
|
||||
if (!line) continue
|
||||
|
||||
handleMessage(line).catch((err) => {
|
||||
process.stderr.write(`accounted-mcp error: ${err.message}\n`)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
process.stdin.on('end', () => {
|
||||
process.exit(0)
|
||||
})
|
||||
|
||||
async function handleMessage(line) {
|
||||
let parsed
|
||||
try {
|
||||
parsed = JSON.parse(line)
|
||||
} catch {
|
||||
process.stderr.write('accounted-mcp: invalid JSON\n')
|
||||
return
|
||||
}
|
||||
|
||||
const isNotification = parsed.id === undefined || parsed.id === null
|
||||
|
||||
try {
|
||||
const res = await fetch(MCP_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${API_KEY}`,
|
||||
...(CLIENT ? { 'X-Accounted-Client': CLIENT } : {}),
|
||||
},
|
||||
body: line,
|
||||
})
|
||||
|
||||
if (res.status === 202 || res.status === 204) {
|
||||
return
|
||||
}
|
||||
|
||||
const responseText = await res.text()
|
||||
|
||||
// Guard against non-JSON error responses such as CDN or proxy pages.
|
||||
if (!res.ok && !isNotification) {
|
||||
let message = `HTTP ${res.status}`
|
||||
try {
|
||||
const json = JSON.parse(responseText)
|
||||
if (json.error) {
|
||||
message =
|
||||
typeof json.error === 'string'
|
||||
? json.error
|
||||
: JSON.stringify(json.error)
|
||||
}
|
||||
} catch {
|
||||
// The body was not JSON: use the generic HTTP status message.
|
||||
}
|
||||
const errorResponse = JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: parsed.id,
|
||||
error: { code: -32000, message },
|
||||
})
|
||||
process.stdout.write(`${errorResponse}\n`)
|
||||
return
|
||||
}
|
||||
|
||||
if (responseText) {
|
||||
process.stdout.write(`${responseText}\n`)
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isNotification) {
|
||||
const errorResponse = JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: parsed.id,
|
||||
error: { code: -32000, message: `Connection error: ${err.message}` },
|
||||
})
|
||||
process.stdout.write(`${errorResponse}\n`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "accounted-mcp",
|
||||
"version": "1.0.0",
|
||||
"description": "Connect MCP clients to your Accounted bookkeeping account",
|
||||
"bin": {
|
||||
"accounted-mcp": "./index.mjs"
|
||||
},
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"mcp",
|
||||
"accounted",
|
||||
"bookkeeping",
|
||||
"claude",
|
||||
"accounting"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/erp-mafia/accounted.git",
|
||||
"directory": "packages/accounted-mcp"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"files": [
|
||||
"index.mjs",
|
||||
"README.md"
|
||||
]
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Arcim
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,41 +0,0 @@
|
||||
# @accounted/connect-contract
|
||||
|
||||
The wire contract between an Accounted ledger installation (the hosted service
|
||||
or a self-hosted instance) and Accounted Connect, the service that operates
|
||||
the provider integrations only Accounted can run: bank feeds through its PSD2
|
||||
credentials, the Skatteverket API client, the Peppol access point, company
|
||||
lookup, the migration sources.
|
||||
|
||||
This package is shape only: constants, Zod schemas and the TypeScript types
|
||||
inferred from them. There is no behaviour and no provider code in it. Both
|
||||
sides of the connection validate with the same schemas so they cannot drift
|
||||
apart, and the package is MIT so that anyone may implement either side.
|
||||
|
||||
What is in it:
|
||||
|
||||
- key prefix, header names and the entitlements path an installation uses;
|
||||
- the entitlements and sync-report payloads of the hourly key sync;
|
||||
- the error envelope and the stable error codes the service answers with;
|
||||
- the Peppol operations (`/api/connect/peppol/*`): request and response
|
||||
schemas plus the operation table (method, path, company header required).
|
||||
|
||||
Versioning: `CONTRACT_VERSION` is a date. Fields are only ever added; a
|
||||
breaking change is a new operation or family, never a changed one.
|
||||
|
||||
## Use
|
||||
|
||||
```ts
|
||||
import { peppolSubmissionSchema, PEPPOL_OPERATIONS, CONTRACT_VERSION } from '@accounted/connect-contract'
|
||||
|
||||
const parsed = peppolSubmissionSchema.safeParse(body)
|
||||
if (!parsed.success) return badRequest(parsed.error)
|
||||
```
|
||||
|
||||
Inside the Accounted repository the package is consumed from source through a
|
||||
path alias. To publish, build from the repository root with the root
|
||||
dependencies installed:
|
||||
|
||||
```bash
|
||||
npx tsc -p packages/connect-contract/tsconfig.json
|
||||
cd packages/connect-contract && npm publish --access public
|
||||
```
|
||||
@@ -1,41 +0,0 @@
|
||||
{
|
||||
"name": "@accounted/connect-contract",
|
||||
"version": "0.1.0",
|
||||
"description": "Wire contract between an Accounted ledger installation and the Accounted Connect service: constants, Zod schemas and types. Shape only, no behaviour.",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"zod": "^4.0.0"
|
||||
},
|
||||
"keywords": [
|
||||
"accounted",
|
||||
"gnubok",
|
||||
"connector",
|
||||
"peppol",
|
||||
"bookkeeping"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/erp-mafia/accounted.git",
|
||||
"directory": "packages/connect-contract"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
CONNECTOR_ERROR_CODES,
|
||||
CONNECTOR_KEY_PREFIX,
|
||||
CONTRACT_VERSION,
|
||||
PEPPOL_OPERATIONS,
|
||||
bankSyncRequestSchema,
|
||||
bankSyncResponseSchema,
|
||||
connectorEntitlementsSchema,
|
||||
connectorErrorSchema,
|
||||
connectorSyncReportSchema,
|
||||
peppolInboundMessageSchema,
|
||||
peppolLookupResultSchema,
|
||||
peppolParticipantSchema,
|
||||
peppolRecipientRegistrationRequestSchema,
|
||||
peppolSubmissionSchema,
|
||||
} from '../index'
|
||||
|
||||
const participant = { scheme: '0007', identifier: '5561234567' }
|
||||
|
||||
describe('contract constants', () => {
|
||||
it('pins the version as a date and the key prefix as the frozen wire format', () => {
|
||||
expect(CONTRACT_VERSION).toMatch(/^\d{4}-\d{2}-\d{2}$/)
|
||||
expect(CONNECTOR_KEY_PREFIX).toBe('gnubok_ck_')
|
||||
})
|
||||
|
||||
it('lists every operation with a method, path and schemas', () => {
|
||||
for (const [name, op] of Object.entries(PEPPOL_OPERATIONS)) {
|
||||
expect(op.path.startsWith('/'), name).toBe(true)
|
||||
expect(['POST', 'PUT', 'DELETE']).toContain(op.method)
|
||||
expect(typeof op.request.safeParse).toBe('function')
|
||||
expect(typeof op.response.safeParse).toBe('function')
|
||||
}
|
||||
expect(new Set(CONNECTOR_ERROR_CODES).size).toBe(CONNECTOR_ERROR_CODES.length)
|
||||
})
|
||||
})
|
||||
|
||||
describe('entitlements and errors', () => {
|
||||
it('round-trips the entitlements and sync payloads', () => {
|
||||
expect(
|
||||
connectorEntitlementsSchema.safeParse({
|
||||
status: 'active',
|
||||
scopes: ['bank_sync', 'peppol'],
|
||||
current_period_end: null,
|
||||
org_number: '5561234567',
|
||||
instance_url: null,
|
||||
server_time: '2026-09-02T12:00:00Z',
|
||||
}).success,
|
||||
).toBe(true)
|
||||
expect(connectorEntitlementsSchema.safeParse({ status: 'gone', scopes: [] }).success).toBe(false)
|
||||
expect(connectorSyncReportSchema.safeParse({ active_company_count: 3 }).success).toBe(true)
|
||||
expect(connectorSyncReportSchema.safeParse({ active_company_count: -1 }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('accepts the error envelope with or without the retry hint', () => {
|
||||
expect(connectorErrorSchema.safeParse({ error: 'x', code: 'CONNECTOR_NOT_OWNED' }).success).toBe(true)
|
||||
expect(connectorErrorSchema.safeParse({ error: 'x', code: 'CONNECTOR_UPSTREAM_ERROR', retryable: true, detail: null }).success).toBe(true)
|
||||
expect(connectorErrorSchema.safeParse({ code: 'x' }).success).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('peppol schemas', () => {
|
||||
it('validates participants as four-digit ICD scheme plus identifier', () => {
|
||||
expect(peppolParticipantSchema.safeParse(participant).success).toBe(true)
|
||||
expect(peppolParticipantSchema.safeParse({ scheme: '007', identifier: 'x' }).success).toBe(false)
|
||||
expect(peppolParticipantSchema.safeParse({ scheme: 'abcd', identifier: 'x' }).success).toBe(false)
|
||||
expect(peppolParticipantSchema.safeParse({ scheme: '0007', identifier: '' }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('discriminates lookup results on reachable', () => {
|
||||
expect(peppolLookupResultSchema.safeParse({ reachable: true, participant, capabilities: [], checkedAt: 't' }).success).toBe(true)
|
||||
expect(peppolLookupResultSchema.safeParse({ reachable: false, participant, reasonCode: 'participant_not_found', checkedAt: 't' }).success).toBe(true)
|
||||
expect(peppolLookupResultSchema.safeParse({ reachable: false, participant, checkedAt: 't' }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('requires an XML submission with a hex sha256 and rejects non-xml content types', () => {
|
||||
const base = {
|
||||
idempotencyKey: 'k',
|
||||
tenantReference: 'c',
|
||||
sender: participant,
|
||||
recipient: participant,
|
||||
documentTypeId: 'd',
|
||||
processId: 'p',
|
||||
filename: 'f.xml',
|
||||
contentType: 'application/xml',
|
||||
document: '<Invoice/>',
|
||||
documentSha256: 'a'.repeat(64),
|
||||
}
|
||||
expect(peppolSubmissionSchema.safeParse(base).success).toBe(true)
|
||||
expect(peppolSubmissionSchema.safeParse({ ...base, contentType: 'application/json' }).success).toBe(false)
|
||||
expect(peppolSubmissionSchema.safeParse({ ...base, documentSha256: 'zz' }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('validates registrations and inbound messages', () => {
|
||||
expect(
|
||||
peppolRecipientRegistrationRequestSchema.safeParse({
|
||||
participant,
|
||||
businessCard: { companyName: 'AB', countryCode: 'SE' },
|
||||
documentTypes: [{ processId: 'p', documentTypeId: 'd' }],
|
||||
}).success,
|
||||
).toBe(true)
|
||||
expect(
|
||||
peppolRecipientRegistrationRequestSchema.safeParse({ participant, businessCard: { companyName: 'AB', countryCode: 'SWE' }, documentTypes: [] }).success,
|
||||
).toBe(false)
|
||||
expect(
|
||||
peppolInboundMessageSchema.safeParse({ provider: 'qvalia', providerDocumentId: 'doc-1', documentType: 'Invoice', payload: {}, receivedAt: null }).success,
|
||||
).toBe(true)
|
||||
expect(peppolInboundMessageSchema.safeParse({ provider: 'qvalia', providerDocumentId: 'doc-1', documentType: 'Order', payload: {} }).success).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('bank sync operation', () => {
|
||||
it('validates the request and response shapes', () => {
|
||||
expect(bankSyncRequestSchema.safeParse({ session_id: 's', account_uid: 'a', account_currency: 'SEK', date_from: '2026-08-01', date_to: '2026-09-03', strategy: 'longest' }).success).toBe(true)
|
||||
expect(bankSyncRequestSchema.safeParse({ session_id: 's', account_uid: 'a', account_currency: 'SEKK' }).success).toBe(false)
|
||||
expect(bankSyncRequestSchema.safeParse({ session_id: 's', account_uid: 'a', account_currency: 'SEK', date_from: '2026/08/01' }).success).toBe(false)
|
||||
expect(bankSyncRequestSchema.safeParse({ session_id: 's', account_uid: 'a', account_currency: 'SEK', date_from: '2026-02-30' }).success).toBe(false)
|
||||
expect(bankSyncResponseSchema.safeParse({ transactions: [{ booking_date: '', amount: 1, currency: 'SEK', description: 'x', counterparty_name: null, counterparty_account: null, reference: null, merchant_category_code: null, bank_transaction_code: null, proprietary_bank_transaction_code: null }], raw_pages: [], skipped_pending: 0, returned_min_booking_date: null, returned_max_booking_date: null, effective_date_from: null, pages: 0 }).success).toBe(false)
|
||||
expect(
|
||||
bankSyncResponseSchema.safeParse({
|
||||
transactions: [{ booking_date: '2026-09-01', amount: -12.5, currency: 'SEK', description: 'x', counterparty_name: null, counterparty_account: null, reference: null, merchant_category_code: null, bank_transaction_code: null, proprietary_bank_transaction_code: null }],
|
||||
raw_pages: ['{}'], skipped_pending: 0, returned_min_booking_date: '2026-09-01', returned_max_booking_date: '2026-09-01', effective_date_from: null, pages: 1,
|
||||
}).success,
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,57 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { normalizeBankTransactionCode, normalizedBankTransactionSchema } from '../index'
|
||||
|
||||
describe('normalizeBankTransactionCode', () => {
|
||||
it('flattens an Enable Banking object to code/sub_code when the ISO code is present', () => {
|
||||
expect(
|
||||
normalizeBankTransactionCode({ description: 'Card purchase', code: 'PMNT', sub_code: 'CCRD' }),
|
||||
).toBe('PMNT/CCRD')
|
||||
expect(normalizeBankTransactionCode({ description: null, code: 'PMNT', sub_code: null })).toBe('PMNT')
|
||||
expect(normalizeBankTransactionCode({ code: ' PMNT ', sub_code: ' ' })).toBe('PMNT')
|
||||
})
|
||||
|
||||
it('falls back to the description when the ASPSP left code null (the Swedish norm)', () => {
|
||||
expect(
|
||||
normalizeBankTransactionCode({ description: 'Kortköp/uttag', code: null, sub_code: null }),
|
||||
).toBe('Kortköp/uttag')
|
||||
expect(normalizeBankTransactionCode({ description: 'Swish' })).toBe('Swish')
|
||||
})
|
||||
|
||||
it('passes strings through trimmed and blanks as null', () => {
|
||||
expect(normalizeBankTransactionCode('PMNT-CCRD-POSD')).toBe('PMNT-CCRD-POSD')
|
||||
expect(normalizeBankTransactionCode(' XB ')).toBe('XB')
|
||||
expect(normalizeBankTransactionCode(' ')).toBeNull()
|
||||
expect(normalizeBankTransactionCode('')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for empty objects, arrays, numbers and nullish input', () => {
|
||||
expect(normalizeBankTransactionCode({ description: '', code: null, sub_code: null })).toBeNull()
|
||||
expect(normalizeBankTransactionCode({})).toBeNull()
|
||||
expect(normalizeBankTransactionCode(['PMNT'])).toBeNull()
|
||||
expect(normalizeBankTransactionCode(42)).toBeNull()
|
||||
expect(normalizeBankTransactionCode(null)).toBeNull()
|
||||
expect(normalizeBankTransactionCode(undefined)).toBeNull()
|
||||
})
|
||||
|
||||
it('produces a value the wire schema accepts, which the raw object is not', () => {
|
||||
const raw = { description: 'Card purchase', code: null, sub_code: null }
|
||||
const base = {
|
||||
booking_date: '2026-09-03',
|
||||
amount: -250,
|
||||
currency: 'SEK',
|
||||
description: 'Card purchase',
|
||||
counterparty_name: null,
|
||||
counterparty_account: null,
|
||||
reference: null,
|
||||
merchant_category_code: null,
|
||||
proprietary_bank_transaction_code: null,
|
||||
}
|
||||
expect(normalizedBankTransactionSchema.safeParse({ ...base, bank_transaction_code: raw }).success).toBe(false)
|
||||
expect(
|
||||
normalizedBankTransactionSchema.safeParse({
|
||||
...base,
|
||||
bank_transaction_code: normalizeBankTransactionCode(raw),
|
||||
}).success,
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,407 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* @accounted/connect-contract
|
||||
*
|
||||
* The wire contract between an Accounted ledger installation (hosted, or a
|
||||
* self-hosted instance) and the Accounted Connect service that operates the
|
||||
* provider integrations only Accounted can run: bank feeds through its PSD2
|
||||
* credentials, the Skatteverket API client, the Peppol access point, company
|
||||
* lookup, the migration sources.
|
||||
*
|
||||
* Everything here is shape, never behaviour: constants, Zod schemas and the
|
||||
* TypeScript types inferred from them, plus the one normalizer that keeps a
|
||||
* provider field on that shape (normalizeBankTransactionCode). Both sides
|
||||
* validate with the same schemas so they cannot drift apart. The package is MIT so that anyone may
|
||||
* implement either side of it: a self-hosted ledger talking to Accounted
|
||||
* Connect, or an alternative connector service talking to the open ledger.
|
||||
*
|
||||
* Versioning: `CONTRACT_VERSION` is a date. Fields are only ever added; a
|
||||
* breaking change is a new operation or family name, never a changed one.
|
||||
*/
|
||||
|
||||
export const CONTRACT_VERSION = '2026-09-08'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Keys, headers and paths
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Connector keys start with this prefix; the rest is 32 random bytes, base64url. */
|
||||
export const CONNECTOR_KEY_PREFIX = 'gnubok_ck_'
|
||||
|
||||
/** Header alternative to `Authorization: Bearer`, for proxied calls where Authorization carries an upstream token. */
|
||||
export const CONNECTOR_KEY_HEADER = 'x-connector-key'
|
||||
|
||||
export const CONNECTOR_ENTITLEMENTS_PATH = '/api/connect/entitlements'
|
||||
|
||||
/** Default origin of the connector service. Installations that pointed at the hosted app's copy of the routes set GNUBOK_CONNECT_URL explicitly. */
|
||||
export const DEFAULT_CONNECT_BASE_URL = 'https://connect.accounted.se'
|
||||
|
||||
/**
|
||||
* Request headers an installation sends alongside its key. The company header
|
||||
* is the installation's own opaque company reference: the service never
|
||||
* resolves it to anything and only uses it to scope quotas and ownership.
|
||||
*/
|
||||
export const CONNECTOR_HEADERS = {
|
||||
company: 'X-Connector-Company',
|
||||
upstreamAuthorization: 'X-Connector-Upstream-Authorization',
|
||||
upstreamContentType: 'X-Connector-Upstream-Content-Type',
|
||||
} as const
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Entitlements (installation <-> service)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const connectorKeyStatusSchema = z.enum(['active', 'suspended', 'revoked'])
|
||||
export type ConnectorKeyStatus = z.infer<typeof connectorKeyStatusSchema>
|
||||
|
||||
/** What the service tells an installation about its key. */
|
||||
export const connectorEntitlementsSchema = z.object({
|
||||
status: connectorKeyStatusSchema,
|
||||
/** Capability keys the subscription covers. */
|
||||
scopes: z.array(z.string()),
|
||||
/** End of the paid period, ISO; null for an open-ended (manually issued) key. */
|
||||
current_period_end: z.string().nullable(),
|
||||
org_number: z.string(),
|
||||
/** The installation origin this key is pinned to; null until the first sync claims it. */
|
||||
instance_url: z.string().nullable(),
|
||||
server_time: z.string(),
|
||||
})
|
||||
export type ConnectorEntitlements = z.infer<typeof connectorEntitlementsSchema>
|
||||
|
||||
/** What an installation reports on every sync (quantity billing input). */
|
||||
export const connectorSyncReportSchema = z.object({
|
||||
active_company_count: z.number().int().min(0),
|
||||
instance_url: z.string().optional(),
|
||||
app_version: z.string().optional(),
|
||||
})
|
||||
export type ConnectorSyncReport = z.infer<typeof connectorSyncReportSchema>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Errors
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Every refusal from the service is this shape. `code` is stable and machine
|
||||
* readable; `retryable` tells the installation whether backing off helps.
|
||||
*/
|
||||
export const connectorErrorSchema = z.object({
|
||||
error: z.string(),
|
||||
code: z.string(),
|
||||
retryable: z.boolean().optional(),
|
||||
detail: z.string().nullable().optional(),
|
||||
})
|
||||
export type ConnectorError = z.infer<typeof connectorErrorSchema>
|
||||
|
||||
/** Codes the service may answer with, in addition to upstream-specific ones. */
|
||||
export const CONNECTOR_ERROR_CODES = [
|
||||
'BAD_REQUEST',
|
||||
'CONNECTOR_SCOPE_MISSING',
|
||||
'CONNECTOR_COMPANY_MISSING',
|
||||
'CONNECTOR_PATH_NOT_ALLOWED',
|
||||
'CONNECTOR_NOT_OWNED',
|
||||
'CONNECTOR_QUOTA_EXCEEDED',
|
||||
'CONNECTOR_RATE_LIMITED',
|
||||
'CONNECTOR_STATE_INVALID',
|
||||
'CONNECTOR_STATE_CONSUMED',
|
||||
'CONNECTOR_REDIRECT_INVALID',
|
||||
'CONNECTOR_LEDGER_FAILED',
|
||||
'CONNECTOR_UPSTREAM_ERROR',
|
||||
'CONNECTOR_UPSTREAM_UNCONFIGURED',
|
||||
'CONNECTOR_PEPPOL_PARTICIPANT_TAKEN',
|
||||
'CONNECTOR_PEPPOL_PARTICIPANT_NOT_ALLOWED',
|
||||
'CONNECTOR_PEPPOL_SENDER_NOT_REGISTERED',
|
||||
'PEPPOL_RECEIVING_UNSUPPORTED',
|
||||
'PEPPOL_REGISTRATION_CAP_REACHED',
|
||||
] as const
|
||||
export type ConnectorErrorCode = (typeof CONNECTOR_ERROR_CODES)[number]
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bank sync operation (installation -> service, POST /api/connect/bank/sync)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The installation holds the PSD2 session and the account; the service does
|
||||
* the provider paging, the booked-only filter and the normalization, and
|
||||
* returns what the installation ingests plus the raw provider pages it
|
||||
* archives. Stored keys (external ids) stay computed on the installation from
|
||||
* booking_date, amount and its own account scope, exactly as before.
|
||||
*/
|
||||
export const bankSyncRequestSchema = z.object({
|
||||
/** The Enable Banking session id the installation obtained (ownership is checked). */
|
||||
session_id: z.string().trim().min(1).max(200),
|
||||
account_uid: z.string().trim().min(1).max(200),
|
||||
account_currency: z.string().trim().length(3),
|
||||
date_from: z.iso.date().optional(),
|
||||
date_to: z.iso.date().optional(),
|
||||
strategy: z.enum(['default', 'longest']).optional(),
|
||||
})
|
||||
export type BankSyncRequest = z.infer<typeof bankSyncRequestSchema>
|
||||
|
||||
export const normalizedBankTransactionSchema = z.object({
|
||||
/** A real calendar date: the installation's stored keys and ledger date derive from it. */
|
||||
booking_date: z.iso.date(),
|
||||
amount: z.number(),
|
||||
currency: z.string(),
|
||||
description: z.string(),
|
||||
counterparty_name: z.string().nullable(),
|
||||
counterparty_account: z.string().nullable(),
|
||||
reference: z.string().nullable(),
|
||||
merchant_category_code: z.string().nullable(),
|
||||
bank_transaction_code: z.string().nullable(),
|
||||
proprietary_bank_transaction_code: z.string().nullable(),
|
||||
})
|
||||
export type NormalizedBankTransaction = z.infer<typeof normalizedBankTransactionSchema>
|
||||
|
||||
/**
|
||||
* Enable Banking sends `bank_transaction_code` (and, in principle,
|
||||
* `proprietary_bank_transaction_code`) as an object
|
||||
* `{ description, code, sub_code }`, not as the string both sides declared.
|
||||
* Swedish ASPSPs leave `code` null and put the only signal in `description`
|
||||
* ("Card purchase", "Swish", "Kortköp/uttag"). The wire field is a string, so
|
||||
* every producer (the Connect service and a ledger's direct Enable Banking
|
||||
* path) flattens with this one rule before the value reaches
|
||||
* `normalizedBankTransactionSchema` or a ledger column:
|
||||
*
|
||||
* object with `code` -> `code`, or `code/sub_code` when a sub-code exists
|
||||
* object without code -> `description`
|
||||
* string -> trimmed as is
|
||||
* anything else -> null
|
||||
*
|
||||
* Shared here rather than copied per producer so the two sides cannot drift:
|
||||
* the 2026-09-03 outage was exactly that drift (Connect forwarded the object,
|
||||
* the ledger rejected it, and the direct path had been storing the object's
|
||||
* JSON text since 2026-08-09).
|
||||
*/
|
||||
export function normalizeBankTransactionCode(input: unknown): string | null {
|
||||
if (typeof input === 'string') {
|
||||
const trimmed = input.trim()
|
||||
return trimmed.length > 0 ? trimmed : null
|
||||
}
|
||||
if (input && typeof input === 'object' && !Array.isArray(input)) {
|
||||
const record = input as Record<string, unknown>
|
||||
const text = (key: string): string | null => {
|
||||
const value = record[key]
|
||||
if (typeof value !== 'string') return null
|
||||
const trimmed = value.trim()
|
||||
return trimmed.length > 0 ? trimmed : null
|
||||
}
|
||||
const code = text('code')
|
||||
if (code) {
|
||||
const subCode = text('sub_code')
|
||||
return subCode ? `${code}/${subCode}` : code
|
||||
}
|
||||
return text('description')
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export const bankSyncResponseSchema = z.object({
|
||||
transactions: z.array(normalizedBankTransactionSchema),
|
||||
/** Raw provider pages, verbatim, for the installation's archive. */
|
||||
raw_pages: z.array(z.string()),
|
||||
skipped_pending: z.number().int().min(0),
|
||||
returned_min_booking_date: z.string().nullable(),
|
||||
returned_max_booking_date: z.string().nullable(),
|
||||
/** Set when the provider rejected the window and a narrower date_from was used. */
|
||||
effective_date_from: z.string().nullable(),
|
||||
pages: z.number().int().min(0),
|
||||
})
|
||||
export type BankSyncResponse = z.infer<typeof bankSyncResponseSchema>
|
||||
|
||||
/** Error codes specific to the bank sync operation. */
|
||||
export const BANK_SYNC_ERROR_CODES = ['CONNECTOR_BANK_SESSION_EXPIRED', 'CONNECTOR_BANK_UPSTREAM_ERROR'] as const
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Peppol operations (installation -> service, /api/connect/peppol/*)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The Peppol upstream speaks transport operations, not provider paths: the
|
||||
* access-point account is shared, so the service scopes every read to what
|
||||
* the calling key and company own. These schemas mirror the ledger's
|
||||
* PeppolTransport interface one to one.
|
||||
*/
|
||||
|
||||
export const PEPPOL_MAX_DOCUMENT_CHARS = 5_000_000
|
||||
|
||||
const peppolFourDigitScheme = z
|
||||
.string()
|
||||
.length(4)
|
||||
.regex(/^\d+$/, 'ISO 6523 ICD scheme: four digits')
|
||||
|
||||
export const peppolParticipantSchema = z.object({
|
||||
scheme: peppolFourDigitScheme,
|
||||
identifier: z.string().trim().min(1).max(64),
|
||||
})
|
||||
export type PeppolParticipant = z.infer<typeof peppolParticipantSchema>
|
||||
|
||||
export const peppolDocumentTypeSchema = z.enum(['Invoice', 'CreditNote'])
|
||||
export type PeppolInboundDocumentType = z.infer<typeof peppolDocumentTypeSchema>
|
||||
|
||||
export const peppolDeliveryStatusSchema = z.enum([
|
||||
'staged',
|
||||
'recipient_verified',
|
||||
'submitting',
|
||||
'retryable_failure',
|
||||
'submission_accepted',
|
||||
'transport_succeeded',
|
||||
'recipient_acknowledged',
|
||||
'business_accepted',
|
||||
'business_rejected',
|
||||
'no_route',
|
||||
'failed',
|
||||
])
|
||||
export type PeppolDeliveryStatus = z.infer<typeof peppolDeliveryStatusSchema>
|
||||
|
||||
export const peppolRecipientCapabilitySchema = z.object({
|
||||
documentTypeId: z.string(),
|
||||
processId: z.string(),
|
||||
})
|
||||
|
||||
export const peppolLookupRequestSchema = z.object({ participant: peppolParticipantSchema })
|
||||
export type PeppolLookupRequest = z.infer<typeof peppolLookupRequestSchema>
|
||||
|
||||
export const peppolLookupResultSchema = z.discriminatedUnion('reachable', [
|
||||
z.object({
|
||||
reachable: z.literal(true),
|
||||
participant: peppolParticipantSchema,
|
||||
capabilities: z.array(peppolRecipientCapabilitySchema),
|
||||
checkedAt: z.string(),
|
||||
}),
|
||||
z.object({
|
||||
reachable: z.literal(false),
|
||||
participant: peppolParticipantSchema,
|
||||
reasonCode: z.string(),
|
||||
checkedAt: z.string(),
|
||||
}),
|
||||
])
|
||||
export type PeppolLookupResult = z.infer<typeof peppolLookupResultSchema>
|
||||
|
||||
export const peppolSubmissionSchema = z.object({
|
||||
idempotencyKey: z.string().trim().min(1).max(128),
|
||||
/** The installation's own company reference; the service overrides it with the company header. */
|
||||
tenantReference: z.string().trim().min(1).max(128),
|
||||
sender: peppolParticipantSchema,
|
||||
recipient: peppolParticipantSchema,
|
||||
documentTypeId: z.string().trim().min(1).max(512),
|
||||
processId: z.string().trim().min(1).max(512),
|
||||
filename: z.string().trim().min(1).max(255),
|
||||
contentType: z.literal('application/xml'),
|
||||
document: z.string().min(1).max(PEPPOL_MAX_DOCUMENT_CHARS),
|
||||
documentSha256: z.string().regex(/^[0-9a-f]{64}$/),
|
||||
})
|
||||
export type PeppolSubmission = z.infer<typeof peppolSubmissionSchema>
|
||||
|
||||
export const peppolSubmissionReceiptSchema = z.object({
|
||||
provider: z.string(),
|
||||
providerSubmissionId: z.string(),
|
||||
idempotencyKey: z.string(),
|
||||
tenantReference: z.string(),
|
||||
acceptedAt: z.string(),
|
||||
})
|
||||
export type PeppolSubmissionReceipt = z.infer<typeof peppolSubmissionReceiptSchema>
|
||||
|
||||
export const peppolSubmissionRefSchema = z.object({
|
||||
providerSubmissionId: z.string().trim().min(1).max(128),
|
||||
})
|
||||
export type PeppolSubmissionRef = z.infer<typeof peppolSubmissionRefSchema>
|
||||
|
||||
export const peppolVerifiedEventSchema = z.object({
|
||||
provider: z.string(),
|
||||
providerTenantId: z.string().nullable(),
|
||||
providerSubmissionId: z.string().nullable(),
|
||||
providerEventId: z.string().nullable(),
|
||||
idempotencyKey: z.string().nullable(),
|
||||
eventCode: z.string(),
|
||||
normalizedStatus: peppolDeliveryStatusSchema,
|
||||
isTerminal: z.boolean(),
|
||||
detail: z.string().nullable(),
|
||||
occurredAt: z.string(),
|
||||
rawPayload: z.record(z.string(), z.unknown()),
|
||||
eventSha256: z.string(),
|
||||
verificationMethod: z.string(),
|
||||
})
|
||||
export type PeppolVerifiedEvent = z.infer<typeof peppolVerifiedEventSchema>
|
||||
|
||||
export const peppolDeliveryEvidenceSchema = z.object({
|
||||
provider: z.string(),
|
||||
evidenceType: z.string(),
|
||||
payload: z.record(z.string(), z.unknown()),
|
||||
exactDocument: z.string().nullable(),
|
||||
exactDocumentSha256: z.string().nullable(),
|
||||
evidenceSha256: z.string(),
|
||||
retrievedAt: z.string(),
|
||||
})
|
||||
export type PeppolDeliveryEvidence = z.infer<typeof peppolDeliveryEvidenceSchema>
|
||||
|
||||
export const peppolBusinessCardSchema = z.object({
|
||||
companyName: z.string().trim().min(1).max(200),
|
||||
countryCode: z.string().trim().length(2),
|
||||
geographicalInformation: z.string().max(500).nullish(),
|
||||
vatNumber: z.string().max(64).nullish(),
|
||||
orgNumber: z.string().max(64).nullish(),
|
||||
})
|
||||
|
||||
export const peppolRecipientRegistrationRequestSchema = z.object({
|
||||
participant: peppolParticipantSchema,
|
||||
businessCard: peppolBusinessCardSchema,
|
||||
documentTypes: z
|
||||
.array(z.object({ processId: z.string().min(1).max(512), documentTypeId: z.string().min(1).max(512) }))
|
||||
.min(1)
|
||||
.max(20),
|
||||
description: z.string().max(200).nullish(),
|
||||
/** The installation's own company reference; the service uses the company header. */
|
||||
tenantReference: z.string().max(128).nullish(),
|
||||
})
|
||||
export type PeppolRecipientRegistrationRequest = z.infer<typeof peppolRecipientRegistrationRequestSchema>
|
||||
|
||||
export const peppolRecipientRegistrationResultSchema = z.object({
|
||||
status: z.enum(['registered', 'updated']),
|
||||
participant: peppolParticipantSchema,
|
||||
/** Opaque on the connector: the service never reveals its provider account reference. */
|
||||
providerAccountReference: z.string().nullable(),
|
||||
raw: z.record(z.string(), z.unknown()),
|
||||
})
|
||||
export type PeppolRecipientRegistrationResult = z.infer<typeof peppolRecipientRegistrationResultSchema>
|
||||
|
||||
export const peppolInboundListRequestSchema = z.object({
|
||||
documentType: peppolDocumentTypeSchema,
|
||||
limit: z.number().int().min(1).max(100).optional(),
|
||||
includeRead: z.boolean().optional(),
|
||||
})
|
||||
export type PeppolInboundListRequest = z.infer<typeof peppolInboundListRequestSchema>
|
||||
|
||||
export const peppolInboundMessageSchema = z.object({
|
||||
provider: z.string(),
|
||||
providerDocumentId: z.string(),
|
||||
documentType: peppolDocumentTypeSchema,
|
||||
payload: z.record(z.string(), z.unknown()),
|
||||
receivedAt: z.string().nullable(),
|
||||
})
|
||||
export type PeppolInboundMessage = z.infer<typeof peppolInboundMessageSchema>
|
||||
|
||||
export const peppolInboundXmlRequestSchema = z.object({
|
||||
providerDocumentId: z.string().trim().min(1).max(128),
|
||||
documentType: peppolDocumentTypeSchema,
|
||||
})
|
||||
export type PeppolInboundXmlRequest = z.infer<typeof peppolInboundXmlRequestSchema>
|
||||
|
||||
export const peppolInboundXmlResultSchema = z.object({ xml: z.string().nullable() })
|
||||
export type PeppolInboundXmlResult = z.infer<typeof peppolInboundXmlResultSchema>
|
||||
|
||||
/**
|
||||
* The operation table: method, path under `/api/connect/peppol`, whether the
|
||||
* company header is required, and the request and response schemas.
|
||||
*/
|
||||
export const PEPPOL_OPERATIONS = {
|
||||
lookup: { method: 'POST', path: '/lookup', company: false, request: peppolLookupRequestSchema, response: peppolLookupResultSchema },
|
||||
submit: { method: 'POST', path: '/submit', company: true, request: peppolSubmissionSchema, response: peppolSubmissionReceiptSchema },
|
||||
status: { method: 'POST', path: '/status', company: true, request: peppolSubmissionRefSchema, response: z.array(peppolVerifiedEventSchema) },
|
||||
evidence: { method: 'POST', path: '/evidence', company: true, request: peppolSubmissionRefSchema, response: z.array(peppolDeliveryEvidenceSchema) },
|
||||
register: { method: 'PUT', path: '/recipient', company: true, request: peppolRecipientRegistrationRequestSchema, response: peppolRecipientRegistrationResultSchema },
|
||||
unregister: { method: 'DELETE', path: '/recipient', company: true, request: peppolParticipantSchema, response: z.null() },
|
||||
inboundList: { method: 'POST', path: '/inbound/list', company: false, request: peppolInboundListRequestSchema, response: z.array(peppolInboundMessageSchema) },
|
||||
inboundXml: { method: 'POST', path: '/inbound/xml', company: false, request: peppolInboundXmlRequestSchema, response: peppolInboundXmlResultSchema },
|
||||
} as const
|
||||
export type PeppolOperation = keyof typeof PEPPOL_OPERATIONS
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"declaration": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src"
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["src/__tests__"]
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
# gnubok-mcp
|
||||
|
||||
Legacy compatibility package for existing MCP configurations. New installations
|
||||
should use [`accounted-mcp`](https://www.npmjs.com/package/accounted-mcp).
|
||||
This package, its environment variables, and all existing API keys remain
|
||||
supported.
|
||||
|
||||
Connect [Claude Desktop](https://claude.ai/download) (or any stdio MCP client) to your [Accounted](https://app.gnubok.se) bookkeeping account. This is a thin stdio → HTTPS bridge: it forwards JSON-RPC over stdio to the hosted Accounted MCP server, which exposes 150+ bookkeeping tools (invoices, transactions, VAT/momsdeklaration, payroll, reports, year-end).
|
||||
|
||||
Write tools stage a pending operation that you confirm before anything is booked: the bridge never books on its own.
|
||||
|
||||
## Quickstart
|
||||
|
||||
1. Mint an API key in the Accounted dashboard at **[/settings/api](https://app.gnubok.se/settings/api)**. Use a `gnubok_sk_test_*` key against the sandbox while you evaluate; switch to `gnubok_sk_live_*` for real data. The key's scopes gate which tools are callable.
|
||||
|
||||
2. Run the bridge with the key in the environment:
|
||||
|
||||
```bash
|
||||
GNUBOK_API_KEY=gnubok_sk_test_... npx gnubok-mcp
|
||||
```
|
||||
|
||||
It reads JSON-RPC from stdin and writes responses to stdout, so you normally point an MCP client at it rather than running it by hand.
|
||||
|
||||
## Claude Desktop config
|
||||
|
||||
Add the bridge to your `claude_desktop_config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"gnubok": {
|
||||
"command": "npx",
|
||||
"args": ["gnubok-mcp"],
|
||||
"env": {
|
||||
"GNUBOK_API_KEY": "gnubok_sk_test_..."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Restart Claude Desktop. The Accounted tools appear in the client and you can start asking questions like *"Show my uncategorized bank transactions and suggest categories."*
|
||||
|
||||
### Environment variables
|
||||
|
||||
| Variable | Required | Default | Purpose |
|
||||
|---|---|---|---|
|
||||
| `GNUBOK_API_KEY` | yes | - | Your `gnubok_sk_*` API key. |
|
||||
| `GNUBOK_URL` | no | `https://app.gnubok.se/api/extensions/ext/mcp-server/mcp` | Override the MCP endpoint (e.g. for self-hosted Accounted). |
|
||||
| `GNUBOK_CLIENT` | no | - | Distribution-channel marker (e.g. `openclaw`), sent as `X-Gnubok-Client`. Telemetry only: never affects auth or behavior. |
|
||||
|
||||
## Alternative: claude.ai connector (no API key)
|
||||
|
||||
If you use **claude.ai** or Claude Desktop's custom-connector flow, you can skip this bridge entirely and add Accounted as an OAuth 2.1 custom connector instead: paste the connector URL `https://app.gnubok.se/api/extensions/ext/mcp-server/mcp?client=claude-connector` and authorise on the Accounted consent screen (read-only scopes by default; write scopes are ticked explicitly).
|
||||
|
||||
## Docs
|
||||
|
||||
Full setup, sample prompts, and a 10-minute reviewer test: **[Connect with Claude](https://app.gnubok.se/docs/api/connect-claude)**.
|
||||
|
||||
## Releasing
|
||||
|
||||
The package is published to npm by the `Publish MCP bridges to npm` workflow
|
||||
(`.github/workflows/npm-publish.yml`), never by hand:
|
||||
|
||||
1. Bump `version` in `packages/gnubok-mcp/package.json`.
|
||||
This is the legacy package: bump it only for compatibility fixes; new
|
||||
functionality goes to `accounted-mcp`.
|
||||
2. Merge the change to `main`.
|
||||
3. The workflow compares the new version with the registry and, if it is not
|
||||
there yet, runs `npm publish --provenance --access public`. A version that
|
||||
already exists on npm is skipped, so other `package.json` edits are harmless.
|
||||
|
||||
The workflow needs the repository secret `NPM_TOKEN`: an npm granular access
|
||||
token with read and write access to `accounted-mcp` and `gnubok-mcp`, with
|
||||
two-factor bypass enabled so CI can publish. npm caps the lifetime of such
|
||||
tokens (90 days at the time of writing), so rotate the secret before it lapses.
|
||||
Without the secret the run fails at its first step. The workflow can also be
|
||||
started from the Actions tab, for one package or both, with a dry-run option
|
||||
that packs and validates without publishing.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -1,134 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* gnubok-mcp: Connect Claude Desktop to your Accounted bookkeeping account.
|
||||
*
|
||||
* Usage in claude_desktop_config.json:
|
||||
* {
|
||||
* "mcpServers": {
|
||||
* "gnubok": {
|
||||
* "command": "npx",
|
||||
* "args": ["gnubok-mcp"],
|
||||
* "env": {
|
||||
* "GNUBOK_API_KEY": "gnubok_sk_..."
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* Get your API key at: https://app.gnubok.se/settings/api
|
||||
*/
|
||||
|
||||
const API_KEY = process.env.GNUBOK_API_KEY
|
||||
const MCP_URL = process.env.GNUBOK_URL || 'https://app.gnubok.se/api/extensions/ext/mcp-server/mcp'
|
||||
// Optional distribution-channel marker (e.g. 'openclaw'). Forwarded as
|
||||
// X-Gnubok-Client and recorded in server telemetry only, never affects auth.
|
||||
// Mirrors the server's allow-list so an invalid value degrades to "no header"
|
||||
// instead of fetch() rejecting every request with an invalid-header error.
|
||||
const rawClient = process.env.GNUBOK_CLIENT
|
||||
const CLIENT = rawClient && /^[A-Za-z0-9._-]{1,64}$/.test(rawClient) ? rawClient : undefined
|
||||
if (rawClient && !CLIENT) {
|
||||
process.stderr.write('gnubok-mcp: ignoring GNUBOK_CLIENT: must match [A-Za-z0-9._-]{1,64}\n')
|
||||
}
|
||||
|
||||
if (!API_KEY) {
|
||||
process.stderr.write(
|
||||
'Error: GNUBOK_API_KEY is required.\n' +
|
||||
'Get your API key at: https://app.gnubok.se/settings/api\n' +
|
||||
'\n' +
|
||||
'Add it to your Claude Desktop config:\n' +
|
||||
'{\n' +
|
||||
' "mcpServers": {\n' +
|
||||
' "gnubok": {\n' +
|
||||
' "command": "npx",\n' +
|
||||
' "args": ["gnubok-mcp"],\n' +
|
||||
' "env": {\n' +
|
||||
' "GNUBOK_API_KEY": "gnubok_sk_..."\n' +
|
||||
' }\n' +
|
||||
' }\n' +
|
||||
' }\n' +
|
||||
'}\n'
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
let buffer = ''
|
||||
|
||||
process.stdin.setEncoding('utf8')
|
||||
process.stdin.on('data', (chunk) => {
|
||||
buffer += chunk
|
||||
|
||||
let newlineIdx
|
||||
while ((newlineIdx = buffer.indexOf('\n')) !== -1) {
|
||||
const line = buffer.slice(0, newlineIdx).trim()
|
||||
buffer = buffer.slice(newlineIdx + 1)
|
||||
|
||||
if (!line) continue
|
||||
|
||||
handleMessage(line).catch((err) => {
|
||||
process.stderr.write(`gnubok-mcp error: ${err.message}\n`)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
process.stdin.on('end', () => {
|
||||
process.exit(0)
|
||||
})
|
||||
|
||||
async function handleMessage(line) {
|
||||
let parsed
|
||||
try {
|
||||
parsed = JSON.parse(line)
|
||||
} catch {
|
||||
process.stderr.write(`gnubok-mcp: invalid JSON\n`)
|
||||
return
|
||||
}
|
||||
|
||||
const isNotification = parsed.id === undefined || parsed.id === null
|
||||
|
||||
try {
|
||||
const res = await fetch(MCP_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${API_KEY}`,
|
||||
...(CLIENT ? { 'X-Gnubok-Client': CLIENT } : {}),
|
||||
},
|
||||
body: line,
|
||||
})
|
||||
|
||||
if (res.status === 202 || res.status === 204) {
|
||||
return
|
||||
}
|
||||
|
||||
const text = await res.text()
|
||||
|
||||
// Guard against non-JSON error responses (CDN HTML pages, proxy errors)
|
||||
if (!res.ok && !isNotification) {
|
||||
let message = `HTTP ${res.status}`
|
||||
try {
|
||||
const json = JSON.parse(text)
|
||||
if (json.error) message = typeof json.error === 'string' ? json.error : JSON.stringify(json.error)
|
||||
} catch { /* body wasn't JSON: use generic message */ }
|
||||
const errorResponse = JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: parsed.id,
|
||||
error: { code: -32000, message },
|
||||
})
|
||||
process.stdout.write(errorResponse + '\n')
|
||||
return
|
||||
}
|
||||
|
||||
if (text) {
|
||||
process.stdout.write(text + '\n')
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isNotification) {
|
||||
const errorResponse = JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: parsed.id,
|
||||
error: { code: -32000, message: `Connection error: ${err.message}` },
|
||||
})
|
||||
process.stdout.write(errorResponse + '\n')
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "gnubok-mcp",
|
||||
"version": "1.1.0",
|
||||
"description": "Connect Claude Desktop to your Accounted bookkeeping account",
|
||||
"bin": {
|
||||
"gnubok-mcp": "./index.mjs"
|
||||
},
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"mcp",
|
||||
"gnubok",
|
||||
"bookkeeping",
|
||||
"claude",
|
||||
"accounting"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/erp-mafia/accounted.git",
|
||||
"directory": "packages/gnubok-mcp"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"files": [
|
||||
"index.mjs",
|
||||
"README.md"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user