Files
accounted/lib/invoices/__tests__/peppol-registration.test.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

202 lines
8.9 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { createQueuedMockSupabase } from '@/tests/helpers'
import {
PEPPOL_BIS_BILLING_CREDIT_NOTE_DOCUMENT_TYPE_ID,
PEPPOL_RECEIVING_DOCUMENT_TYPES,
deregisterCompanyFromPeppolReceiving,
preparePeppolParticipant,
registerCompanyForPeppolReceiving,
} from '@/lib/invoices/peppol-registration'
import { PEPPOL_BIS_BILLING_INVOICE_DOCUMENT_TYPE_ID } from '@/lib/invoices/peppol-bis-billing'
import { PeppolTransportError, type PeppolTransport } from '@/lib/invoices/peppol-transport'
const { supabase: mockService, enqueue, reset, calls } = createQueuedMockSupabase()
const service = mockService as unknown as SupabaseClient
const settings = {
org_number: '559538-6219',
company_name: 'Arcim Technology AB',
vat_number: 'SE559538621901',
city: 'Stockholm',
country: 'SE',
}
function makeTransport(overrides: Partial<PeppolTransport> = {}): PeppolTransport {
return {
provider: 'qvalia',
lookupRecipient: vi.fn(),
submit: vi.fn(),
verifyWebhook: vi.fn(),
retrieveEvidence: vi.fn(),
registerRecipient: vi.fn().mockResolvedValue({
status: 'registered',
participant: { scheme: '0007', identifier: '5595386219' },
providerAccountReference: 'SE5595386219',
raw: {},
}),
unregisterRecipient: vi.fn().mockResolvedValue(undefined),
...overrides,
}
}
const registeredRow = {
id: 'reg-1',
company_id: 'company-1',
user_id: 'user-1',
provider: 'qvalia',
provider_account_reference: 'SE5595386219',
participant_scheme: '0007',
participant_identifier: '5595386219',
status: 'registered',
business_card: {},
document_types: PEPPOL_RECEIVING_DOCUMENT_TYPES,
registered_at: '2026-08-21T16:00:00.000Z',
deregistered_at: null,
last_error: null,
created_at: '2026-08-21T15:59:00.000Z',
updated_at: '2026-08-21T16:00:00.000Z',
}
describe('preparePeppolParticipant', () => {
it('derives 0007 + organisation number and the business card', () => {
expect(preparePeppolParticipant(settings)).toEqual({
ok: true,
participant: { scheme: '0007', identifier: '5595386219' },
businessCard: {
companyName: 'Arcim Technology AB',
countryCode: 'SE',
geographicalInformation: 'Stockholm',
vatNumber: 'SE559538621901',
orgNumber: '5595386219',
},
})
expect(preparePeppolParticipant({ ...settings, org_number: '16559538-6219' })).toMatchObject({
ok: true,
participant: { identifier: '5595386219' },
})
})
it('refuses missing numbers, personnummer and missing names', () => {
expect(preparePeppolParticipant({ ...settings, org_number: null })).toEqual({ ok: false, code: 'PEPPOL_REGISTRATION_ORG_NUMBER_REQUIRED' })
expect(preparePeppolParticipant({ ...settings, org_number: '198001011234' })).toEqual({ ok: false, code: 'PEPPOL_REGISTRATION_ORG_NUMBER_REQUIRED' })
expect(preparePeppolParticipant({ ...settings, org_number: '8001011234' })).toEqual({ ok: false, code: 'PEPPOL_REGISTRATION_PERSONAL_NUMBER' })
expect(preparePeppolParticipant({ ...settings, company_name: ' ' })).toEqual({ ok: false, code: 'PEPPOL_REGISTRATION_COMPANY_NAME_REQUIRED' })
})
})
describe('registerCompanyForPeppolReceiving', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
})
it('advertises Invoice and CreditNote for BIS Billing 3', () => {
expect(PEPPOL_RECEIVING_DOCUMENT_TYPES.map((t) => t.documentTypeId)).toEqual([
PEPPOL_BIS_BILLING_INVOICE_DOCUMENT_TYPE_ID,
PEPPOL_BIS_BILLING_CREDIT_NOTE_DOCUMENT_TYPE_ID,
])
})
it('writes pending, publishes through the transport, then finalizes as registered', async () => {
const transport = makeTransport()
enqueue({ data: [], error: null }) // existing registrations
enqueue({ data: { id: 'reg-1' }, error: null }) // insert pending
enqueue({ data: registeredRow, error: null }) // finalize update
const result = await registerCompanyForPeppolReceiving({
service, companyId: 'company-1', userId: 'user-1', transport, settings,
})
expect(result).toEqual({ ok: true, registration: registeredRow })
expect(transport.registerRecipient).toHaveBeenCalledWith({
participant: { scheme: '0007', identifier: '5595386219' },
businessCard: expect.objectContaining({ companyName: 'Arcim Technology AB', orgNumber: '5595386219' }),
documentTypes: PEPPOL_RECEIVING_DOCUMENT_TYPES,
tenantReference: 'company-1',
})
const inserted = calls.find((c) => c.method === 'insert')
expect(inserted?.args[0]).toMatchObject({ status: 'pending', participant_identifier: '5595386219', company_id: 'company-1' })
const finalized = calls.filter((c) => c.method === 'update').at(-1)
expect(finalized?.args[0]).toMatchObject({ status: 'registered', provider_account_reference: 'SE5595386219', last_error: null })
})
it('records a failed registration with the provider reason and reports it', async () => {
const transport = makeTransport({
registerRecipient: vi.fn().mockRejectedValue(new PeppolTransportError('Qvalia answered 500', { retryable: true, detail: 'smp down' })),
})
enqueue({ data: [], error: null })
enqueue({ data: { id: 'reg-1' }, error: null })
enqueue({ data: null, error: null }) // failure update
const result = await registerCompanyForPeppolReceiving({
service, companyId: 'company-1', userId: 'user-1', transport, settings,
})
expect(result).toEqual({ ok: false, code: 'PEPPOL_REGISTRATION_FAILED', detail: 'smp down' })
const failed = calls.filter((c) => c.method === 'update').at(-1)
expect(failed?.args[0]).toMatchObject({ status: 'failed', last_error: 'Qvalia answered 500: smp down' })
})
it('refuses the registration past the contracted cap, and lets an already-registered company through', async () => {
process.env.PEPPOL_RECEIVING_MAX_REGISTRATIONS = '10'
try {
const transport = makeTransport()
enqueue({ data: [], error: null }) // no registration for this company
enqueue({ data: null, error: null, count: 10 }) // live count at the cap
expect(await registerCompanyForPeppolReceiving({
service, companyId: 'company-1', userId: 'user-1', transport, settings,
})).toEqual({ ok: false, code: 'PEPPOL_REGISTRATION_CAP_REACHED' })
expect(transport.registerRecipient).not.toHaveBeenCalled()
// A company that already holds a live row re-registers without consuming a slot.
reset()
enqueue({ data: [{ ...registeredRow, status: 'failed', registered_at: null }], error: null })
enqueue({ data: registeredRow, error: null })
// failed is not live, so the cap applies: count below cap lets it in
reset()
enqueue({ data: [registeredRow], error: null }) // live row exists
enqueue({ data: registeredRow, error: null }) // finalize update
expect((await registerCompanyForPeppolReceiving({
service, companyId: 'company-1', userId: 'user-1', transport, settings,
})).ok).toBe(true)
} finally {
delete process.env.PEPPOL_RECEIVING_MAX_REGISTRATIONS
}
})
it('stops before the network on a personnummer and on a send-only transport', async () => {
const transport = makeTransport()
expect(await registerCompanyForPeppolReceiving({
service, companyId: 'company-1', userId: 'user-1', transport, settings: { ...settings, org_number: '8001011234' },
})).toEqual({ ok: false, code: 'PEPPOL_REGISTRATION_PERSONAL_NUMBER' })
expect(transport.registerRecipient).not.toHaveBeenCalled()
const sendOnly = makeTransport({ registerRecipient: undefined })
expect(await registerCompanyForPeppolReceiving({
service, companyId: 'company-1', userId: 'user-1', transport: sendOnly, settings,
})).toEqual({ ok: false, code: 'PEPPOL_RECEIVING_UNSUPPORTED' })
})
})
describe('deregisterCompanyFromPeppolReceiving', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
})
it('withdraws the live identifier and marks the row deregistered', async () => {
const transport = makeTransport()
enqueue({ data: [registeredRow], error: null })
enqueue({ data: { ...registeredRow, status: 'deregistered', deregistered_at: '2026-08-21T17:00:00.000Z' }, error: null })
const result = await deregisterCompanyFromPeppolReceiving({ service, companyId: 'company-1', transport })
expect(result.ok).toBe(true)
expect(transport.unregisterRecipient).toHaveBeenCalledWith({ scheme: '0007', identifier: '5595386219' })
})
it('reports not found when nothing is live', async () => {
enqueue({ data: [{ ...registeredRow, status: 'deregistered' }], error: null })
expect(await deregisterCompanyFromPeppolReceiving({ service, companyId: 'company-1', transport: makeTransport() }))
.toEqual({ ok: false, code: 'PEPPOL_REGISTRATION_NOT_FOUND' })
})
})