Files
accounted/lib/invoices/peppol-transport.ts
T
f31eeaa603 feat(connect): Peppol through the connector (hosted proxy, instance transport, ownership ledger) (#2177)
* feat(connect): peppol connector foundation: capability, ledger/budget service, quota

Adds the storage + package shape for brokering Peppol through the connector with
the same one-address + rate-budget model as bank/skatteverket: a peppol
capability (connector-gated, free on hosted), peppol as a ledger + upstream
service, a conservative rate budget, and a migration extending the ledger
service CHECK and the per-key limits (peppol_connections_per_company). Proxy
route + instance-side Qvalia reroute follow. Switch-on gated on the Qvalia
brokering-terms check.

(cherry picked from commit 3cc0da6a3, migration renumbered 20260902190000)

Signed-off-by: Jakob Wennberg <jakob.wennberg@arcim.io>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MMUUom4fUk6zi4xYZSSfat

* feat(connect): Peppol through the connector: hosted proxy, instance transport, ownership ledger

Completes the Peppol upstream for self-hosted instances on the connector
(WS3): an instance with a connector key carrying the peppol scope and no
Qvalia keys of its own sends and receives e-invoices through Arcim's
contracted access point, the same way bank and Skatteverket already route.

Hosted: app/api/connect/peppol/[...path] speaks the PeppolTransport
operations (lookup, submit, status, evidence, recipient PUT/DELETE, inbound
list/xml) rather than proxying Qvalia paths, because the Qvalia account is
shared by every hosted company and every instance: reads must be scoped to
what the caller owns, and the inbound read endpoint is destructive for the
whole account. Ownership: a receiving registration is a ledger row (service
peppol, participant id in account_uids, sha256 in handle_hash so one key
holds a participant at a time); outbound submissions land in the new
connector_peppol_submissions table and gate status/evidence; inbound
documents are served from the hosted archive filtered by the participants
the key holds. Per-company quota (peppol_connections_per_company), the
shared PEPPOL_RECEIVING_MAX_REGISTRATIONS cap, and the global peppol rate
budget apply. Provider failures cross as CONNECTOR_UPSTREAM_ERROR with the
adapter's retryable flag (422 or 502).

Instance: lib/invoices/transports/connector.ts implements PeppolTransport
over that API and registers itself in connector mode (key present, no
QVALIA_* keys); getPeppolTransportAvailability() defaults to it when no
provider is selected, so an instance needs no PEPPOL_TRANSPORT_PROVIDER.
Webhooks are not brokered; the existing outbound status poll covers it.
Hosted is byte-identical: it has its own keys, so connector mode is never on.

Docs: SELF-HOSTING.md, SOVEREIGN.md, .env.example. Switch-on for third-party
instances stays gated on the Qvalia brokering-terms check; without the scope
every operation answers 403.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MMUUom4fUk6zi4xYZSSfat
Signed-off-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>

* fix(connect): authorize Peppol participants per key, harden the proxy after review

Review follow-ups on #2177. Authorization: a key may only register (and send
as) participant identifiers Arcim recorded on the key at issuance
(connector_keys.peppol_participants, migration 20260902191000) or the
licensee's own org number, and a document may only be submitted as a sender
the key has registered; X-Connector-Company stays an opaque per-company ref.
Cap: the shared access-point cap now counts fresh pending reservations and is
re-checked after this request's own reservation, so concurrent registrations
cannot both pass. Inbound: both halves of the participant id are filtered in
the archive query (over-fetched, then exact-pair checked), so foreign rows
sharing an identifier cannot consume the limit. Delete: deregistration is a
required transport capability, checked before the ledger row is revoked, and
registration refuses an access point that cannot deregister. Instance
transport: the hosted URL must be https (loopback http only, same rule as
getConnectorConfig), and the response body is read inside the timeout window
with body-read failures mapped to retryable transport errors.
issue-connector-key.ts gains --peppol-participants and
--peppol-connections-per-company. Declined: NOT VALID on the ledger CHECK
(the table is empty until keys are issued; the validated scan is instant).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MMUUom4fUk6zi4xYZSSfat
Signed-off-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>

* fix(connect): bind Peppol ownership to the instance company, query exact participant pairs

Second review round on #2177. Ownership is now (key, company_ref), not key
alone: a sender must be registered under the same company header, status and
evidence reads look the submission up under the header company, DELETE and
re-registration refuse a participant the key holds for another company, so
one company on a multi-company instance cannot act on another company's
registration through the shared key. The instance transport resolves the
owning company from its own peppol_deliveries / peppol_registrations rows
before status, evidence and deregistration calls (deps.companyFor,
deps.companyForParticipant, wired in transports/index.ts). Inbound listing
stays key-wide (the instance routes documents to its own companies by its
own registrations). The archive query now runs one exact-pair query per
scheme (scheme fixed, that scheme's identifiers), so neither foreign nor
cross-pair rows can consume the limit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MMUUom4fUk6zi4xYZSSfat
Signed-off-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>

---------

Signed-off-by: Jakob Wennberg <jakob.wennberg@arcim.io>
Signed-off-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-02 20:57:57 +02:00

257 lines
8.4 KiB
TypeScript

/**
* Provider-neutral boundary between Accounted's Peppol lifecycle and a
* contracted Access Point. Core code must not infer network delivery from an
* HTTP response: submissions, asynchronous events, and evidence are distinct.
*/
export type PeppolDeliveryStatus =
| 'staged'
| 'recipient_verified'
| 'submitting'
| 'retryable_failure'
| 'submission_accepted'
| 'transport_succeeded'
| 'recipient_acknowledged'
| 'business_accepted'
| 'business_rejected'
| 'no_route'
| 'failed'
export interface PeppolParticipant {
scheme: string
identifier: string
}
export interface PeppolRecipientCapability {
documentTypeId: string
processId: string
}
export type PeppolRecipientLookup =
| {
reachable: true
participant: PeppolParticipant
capabilities: PeppolRecipientCapability[]
checkedAt: string
}
| {
reachable: false
participant: PeppolParticipant
reasonCode: string
checkedAt: string
}
export interface PeppolSubmission {
idempotencyKey: string
tenantReference: string
sender: PeppolParticipant
recipient: PeppolParticipant
documentTypeId: string
processId: string
filename: string
contentType: 'application/xml'
document: string
documentSha256: string
}
export interface PeppolSubmissionReceipt {
provider: string
providerSubmissionId: string
idempotencyKey: string
tenantReference: string
acceptedAt: string
}
export interface PeppolVerifiedEvent {
provider: string
providerTenantId: string | null
providerSubmissionId: string | null
providerEventId: string | null
/**
* Accounted's delivery idempotency key. A provider webhook only knows its
* own submission id, so an adapter returns `null` here and the webhook route
* resolves the key from `providerSubmissionId` before persisting.
*/
idempotencyKey: string | null
eventCode: string
normalizedStatus: PeppolDeliveryStatus
isTerminal: boolean
detail: string | null
occurredAt: string
rawPayload: Record<string, unknown>
eventSha256: string
verificationMethod: string
}
export interface PeppolDeliveryEvidence {
provider: string
evidenceType: string
payload: Record<string, unknown>
exactDocument: string | null
exactDocumentSha256: string | null
evidenceSha256: string
retrievedAt: string
}
export interface PeppolWebhookRequest {
headers: Headers
rawBody: Uint8Array
}
/** What the SMP publishes about a receiving participant (Peppol Directory business card). */
export interface PeppolBusinessCard {
companyName: string
countryCode: string
geographicalInformation?: string | null
vatNumber?: string | null
orgNumber?: string | null
}
export interface PeppolDocumentTypeRegistration {
/** Process identifier, e.g. urn:fdc:peppol.eu:2017:poacc:billing:01:1.0 */
processId: string
/** Document type identifier, e.g. the BIS Billing 3 Invoice id. */
documentTypeId: string
}
export interface PeppolRecipientRegistrationInput {
participant: PeppolParticipant
businessCard: PeppolBusinessCard
documentTypes: PeppolDocumentTypeRegistration[]
description?: string | null
/**
* The registering tenant (company id). Providers that hold one account per
* installation ignore it; the connector transport needs it because the
* hosted access point enforces a per-company registration quota.
*/
tenantReference?: string | null
}
export interface PeppolRecipientRegistration {
status: 'registered' | 'updated'
participant: PeppolParticipant
/** Provider account the identifier is attached to (Qvalia accountRegNo). */
providerAccountReference: string | null
raw: Record<string, unknown>
}
export type PeppolInboundDocumentType = 'Invoice' | 'CreditNote'
/** One inbound document as the provider hands it over, before Accounted reads it. */
export interface PeppolInboundMessage {
provider: string
providerDocumentId: string
documentType: PeppolInboundDocumentType
/** UBL-JSON payload (the provider's rendering of the received XML). */
payload: Record<string, unknown>
receivedAt: string | null
}
export interface PeppolInboundListOptions {
documentType: PeppolInboundDocumentType
limit?: number
/** Include documents already handed over once (re-sync); default only unread. */
includeRead?: boolean
}
/**
* Provider-neutral failure raised by an adapter. `retryable` separates an
* operational problem (network, rate limit, credentials) from a verdict on the
* document itself (rejected, duplicate); the send route records them as
* different lifecycle events.
*/
export class PeppolTransportError extends Error {
readonly retryable: boolean
readonly detail: string | null
constructor(message: string, options: { retryable: boolean; detail?: string | null; cause?: unknown }) {
super(message, options.cause !== undefined ? { cause: options.cause } : undefined)
this.name = 'PeppolTransportError'
this.retryable = options.retryable
this.detail = options.detail ?? null
}
}
export function isPeppolTransportError(error: unknown): error is PeppolTransportError {
return error instanceof PeppolTransportError
}
export interface PeppolTransport {
readonly provider: string
lookupRecipient(participant: PeppolParticipant): Promise<PeppolRecipientLookup>
submit(submission: PeppolSubmission): Promise<PeppolSubmissionReceipt>
verifyWebhook(request: PeppolWebhookRequest): Promise<PeppolVerifiedEvent[]>
retrieveEvidence(providerSubmissionId: string): Promise<PeppolDeliveryEvidence[]>
/**
* Receiving side. Optional: a send-only provider leaves these undefined and
* the product keeps receiving switched off for it.
*/
registerRecipient?(input: PeppolRecipientRegistrationInput): Promise<PeppolRecipientRegistration>
unregisterRecipient?(participant: PeppolParticipant): Promise<void>
listInboundDocuments?(options: PeppolInboundListOptions): Promise<PeppolInboundMessage[]>
/** The exact received document, for the archive (räkenskapsinformation). */
fetchInboundDocumentXml?(
providerDocumentId: string,
documentType: PeppolInboundDocumentType,
): Promise<string | null>
/**
* Pull the provider's current delivery status for an outbound submission
* and return it as verified events (same shape as a webhook, `idempotencyKey`
* unresolved). For providers without webhooks, or as a safety net when a
* webhook was missed. Returns [] when the provider has nothing new to say.
*/
pollDeliveryStatus?(providerSubmissionId: string): Promise<PeppolVerifiedEvent[]>
}
/**
* Provider id of the instance-side transport that reaches Arcim's access
* point through the hosted connector (lib/invoices/transports/connector.ts).
* Declared here so availability resolution needs no import of that module.
*/
export const CONNECTOR_PEPPOL_PROVIDER = 'connector'
const transports = new Map<string, PeppolTransport>()
export function registerPeppolTransport(transport: PeppolTransport): () => void {
const provider = transport.provider.trim().toLowerCase()
if (!provider) throw new Error('Peppol transport provider is required')
if (transports.has(provider)) {
throw new Error(`Peppol transport already registered: ${provider}`)
}
transports.set(provider, transport)
return () => {
if (transports.get(provider) === transport) transports.delete(provider)
}
}
export function getPeppolTransport(provider: string): PeppolTransport | null {
return transports.get(provider.trim().toLowerCase()) ?? null
}
export type PeppolTransportAvailability =
| { available: true; provider: string }
| {
available: false
provider: null
reason: 'provider_selection_required' | 'provider_adapter_unavailable'
}
export function getPeppolTransportAvailability(): PeppolTransportAvailability {
const configuredProvider = process.env.PEPPOL_TRANSPORT_PROVIDER?.trim().toLowerCase()
if (!configuredProvider) {
// A self-hosted instance in connector mode has exactly one possible
// provider, so it needs no PEPPOL_TRANSPORT_PROVIDER. Hosted never
// registers the connector transport, so this branch is inert there.
if (transports.has(CONNECTOR_PEPPOL_PROVIDER)) {
return { available: true, provider: CONNECTOR_PEPPOL_PROVIDER }
}
return { available: false, provider: null, reason: 'provider_selection_required' }
}
if (!transports.has(configuredProvider)) {
return { available: false, provider: null, reason: 'provider_adapter_unavailable' }
}
return { available: true, provider: configuredProvider }
}