feat(peppol): gate Peppol per company: request access, operator enables with a sending cap (#1794)

* feat(peppol): gate Peppol per company: request access, operator enables with a sending cap

Peppol is no longer available to every company by default. Each transmission
is billed per document by the access point and each receiving identifier
consumes a contracted tenant slot, so the product now works like this:

- peppol_access (new table, RLS read-only for members, service-role writes):
  status requested | enabled | disabled, max_sends (null = no cap),
  receive_enabled as a separate grant, who asked and who enabled.
- POST /api/settings/peppol/access: the company asks from Settings >
  Fakturering; the row is written and the operators are e-mailed (best effort,
  the row is the source of truth).
- scripts/peppol/access.ts list | enable <company|orgnr> [--max-sends N]
  [--receive] | disable | show: the operator side.
- POST /api/invoices/[id]/peppol/send refuses PEPPOL_ACCESS_REQUIRED /
  PEPPOL_SEND_LIMIT_REACHED before touching the invoice; the invoice page's
  send item says so instead of pretending. Registration for receiving refuses
  PEPPOL_ACCESS_REQUIRED / PEPPOL_RECEIVING_NOT_ENABLED.
- Settings UI: access status row with "Begär åtkomst", sends used of cap,
  receiving switch only once receiving is granted.

Refs #546

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TqFpxeWqbpR7bcwUJLRERQ

* test(peppol): pass route params to the settings handlers; baseline-align the access row

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TqFpxeWqbpR7bcwUJLRERQ

* fix(peppol): revoke default table privileges from authenticated on the access and receiving tables

Supabase grants ALL on new tables to authenticated by default; the earlier
REVOKE covered PUBLIC and anon only, so a member's UPDATE on peppol_access was
an RLS-filtered no-op instead of a permission error (pg-real caught it).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TqFpxeWqbpR7bcwUJLRERQ

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-08-21 17:27:45 +02:00
committed by GitHub
co-authored by Claude Fable 5 Jakob Wennberg
parent 9ef7de861f
commit 3ac80edc96
20 changed files with 1075 additions and 34 deletions
@@ -13,6 +13,11 @@ vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
const serviceTables = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => serviceTables.supabase,
}))
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
@@ -4,8 +4,10 @@ import { privateNoStore } from '@/lib/api/private-no-store'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { ensureInitialized } from '@/lib/init'
import { getPeppolAccessSummary } from '@/lib/invoices/peppol-access'
import { listPeppolDeliverySummaries } from '@/lib/invoices/peppol-delivery'
import { getPeppolTransportAvailability } from '@/lib/invoices/peppol-transport'
import { createServiceClient } from '@/lib/supabase/server'
ensureInitialized()
@@ -39,9 +41,11 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
companyId,
invoiceId,
})
const access = await getPeppolAccessSummary({ supabase, service: createServiceClient(), companyId })
return privateNoStore(NextResponse.json({
data: deliveries,
transport: getPeppolTransportAvailability(),
access,
}))
} catch (err) {
return privateNoStore(errorResponse(err, log, { requestId }))
@@ -16,6 +16,7 @@ import {
} from '@/lib/invoices/peppol-transport'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
const serviceTables = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
const serviceRpcMock = vi.fn()
const issueAndBookMock = vi.fn()
@@ -37,7 +38,10 @@ vi.mock('@/lib/auth/require-write', () => ({
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => ({ rpc: (...args: unknown[]) => serviceRpcMock(...args) }),
createServiceClient: () => ({
from: (...args: unknown[]) => serviceTables.supabase.from(...(args as [string])),
rpc: (...args: unknown[]) => serviceRpcMock(...args),
}),
}))
vi.mock('@/lib/invoices/issue-and-book-invoice', () => ({
@@ -135,6 +139,21 @@ function makeTransport(overrides: Partial<PeppolTransport> = {}): PeppolTranspor
}
}
const accessRow = {
company_id: 'company-1',
status: 'enabled',
max_sends: 50,
receive_enabled: false,
requested_at: null, requested_by: null, request_note: null,
enabled_at: '2026-08-21T16:00:00.000Z', enabled_by: 'jakob', disabled_at: null, note: null,
created_at: '2026-08-21T16:00:00.000Z', updated_at: '2026-08-21T16:00:00.000Z',
}
/** Peppol access is per company: grant it (service reads access row, then the send count). */
function grantAccess(maxSends: number | null = 50, sent = 0) {
serviceTables.enqueue({ data: { ...accessRow, max_sends: maxSends }, error: null })
serviceTables.enqueue({ data: null, error: null, count: sent })
}
/** The service-role RPC echoes the event's status back as the projection. */
function serviceRpcEcho() {
serviceRpcMock.mockImplementation(async (_fn: string, args: Record<string, unknown>) => ({
@@ -157,6 +176,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
serviceTables.reset()
serviceRpcEcho()
process.env.PEPPOL_TRANSPORT_PROVIDER = 'qvalia'
process.env.QVALIA_PARTNER_REG_NO = 'SE5560000000'
@@ -208,8 +228,31 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
expect(body.error.details.reason).toBe('provider_selection_required')
})
it('refuses a company without a Peppol grant before touching the invoice', async () => {
const transport = makeTransport()
unregister = registerPeppolTransport(transport)
serviceTables.enqueue({ data: null, error: null }) // no access row
const response = await send()
expect(response.status).toBe(403)
expect((await response.json()).error.code).toBe('PEPPOL_ACCESS_REQUIRED')
expect(transport.submit).not.toHaveBeenCalled()
})
it('refuses once the company has used its sending cap', async () => {
const transport = makeTransport()
unregister = registerPeppolTransport(transport)
grantAccess(5, 5)
const response = await send()
expect(response.status).toBe(409)
const body = await response.json()
expect(body.error.code).toBe('PEPPOL_SEND_LIMIT_REACHED')
expect(body.error.details).toMatchObject({ max_sends: 5, sent_count: 5 })
expect(transport.submit).not.toHaveBeenCalled()
})
it('returns 404 when the invoice is not in the active company', async () => {
unregister = registerPeppolTransport(makeTransport())
grantAccess()
enqueue({ data: null, error: { message: 'not found' } })
const response = await send()
expect(response.status).toBe(404)
@@ -218,6 +261,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
it('rejects cancelled and proforma invoices with a state conflict', async () => {
unregister = registerPeppolTransport(makeTransport())
grantAccess()
enqueue({ data: invoiceRow({ status: 'cancelled' }), error: null })
enqueue({ data: company, error: null })
const response = await send()
@@ -235,6 +279,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
}),
})
unregister = registerPeppolTransport(transport)
grantAccess()
enqueue({ data: invoiceRow(), error: null })
enqueue({ data: company, error: null })
enqueue({ data: stagedDelivery, error: null })
@@ -252,6 +297,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
it('looks up, submits the staged XML and records the lifecycle for an already issued invoice', async () => {
const transport = makeTransport()
unregister = registerPeppolTransport(transport)
grantAccess()
enqueue({ data: invoiceRow(), error: null })
enqueue({ data: company, error: null })
enqueue({ data: stagedDelivery, error: null })
@@ -294,6 +340,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
it('issues and books a draft only after the network accepted it', async () => {
const transport = makeTransport()
unregister = registerPeppolTransport(transport)
grantAccess()
enqueue({ data: invoiceRow({ status: 'draft' }), error: null })
enqueue({ data: company, error: null })
enqueue({ data: stagedDelivery, error: null })
@@ -315,6 +362,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
it('reports a failed issuance without pretending the network send did not happen', async () => {
unregister = registerPeppolTransport(makeTransport())
grantAccess()
issueAndBookMock.mockResolvedValue({ ok: false, errorCode: 'INVOICE_MARK_SENT_RACE' })
enqueue({ data: invoiceRow({ status: 'draft' }), error: null })
enqueue({ data: company, error: null })
@@ -334,6 +382,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
it('replays idempotently when the exact XML was already handed to the network', async () => {
const transport = makeTransport()
unregister = registerPeppolTransport(transport)
grantAccess()
enqueue({ data: invoiceRow(), error: null })
enqueue({ data: company, error: null })
enqueue({
@@ -360,6 +409,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
),
})
unregister = registerPeppolTransport(transport)
grantAccess()
enqueue({ data: invoiceRow({ status: 'draft' }), error: null })
enqueue({ data: company, error: null })
enqueue({ data: stagedDelivery, error: null })
@@ -386,6 +436,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
),
})
unregister = registerPeppolTransport(transport)
grantAccess()
enqueue({ data: invoiceRow(), error: null })
enqueue({ data: company, error: null })
enqueue({ data: stagedDelivery, error: null })
@@ -405,6 +456,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
it('refuses to resend an exact document the access point already rejected', async () => {
const transport = makeTransport()
unregister = registerPeppolTransport(transport)
grantAccess()
enqueue({ data: invoiceRow(), error: null })
enqueue({ data: company, error: null })
enqueue({
+16 -1
View File
@@ -17,6 +17,7 @@ import {
stagePeppolDelivery,
type PeppolDeliverySummary,
} from '@/lib/invoices/peppol-delivery'
import { checkPeppolSendPermission } from '@/lib/invoices/peppol-access'
import { generatePeppolDocumentOrResponse, loadPeppolRecords } from '@/lib/invoices/peppol-document'
import {
getPeppolTransport,
@@ -112,6 +113,21 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
}))
}
// Access is granted per company by the operators and capped in sends:
// refuse before any invoice data is touched.
const service = createServiceClient()
const permission = await checkPeppolSendPermission({ service, companyId })
if (!permission.ok) {
return privateNoStore(errorResponseFromCode(permission.code, log, {
requestId,
details: {
access_status: permission.summary.status,
max_sends: permission.summary.max_sends,
sent_count: permission.summary.sent_count,
},
}))
}
const records = await loadPeppolRecords({ supabase, companyId, invoiceId, log, requestId })
if (!records.ok) return records.response
const { invoice, company } = records
@@ -153,7 +169,6 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
if (!generated.ok) return generated.response
const document = generated.document
const service = createServiceClient()
const provider = transport.provider
// Consolidated Qvalia setup: one provider account for every company. The
// adapter resolves the account; the lifecycle only needs a stable label.