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
+22
View File
@@ -1330,6 +1330,28 @@ const INVOICE: Record<string, StructuredErrorEntry> = {
message_sv: 'Bolaget är inte registrerat för Peppol-mottagning.',
message_en: 'The company is not registered for Peppol receiving.',
},
// Peppol access is granted per company by the operators (#546): locked by
// default, requested from settings, enabled with a sending cap.
PEPPOL_ACCESS_REQUIRED: {
httpStatus: 403,
message_sv: 'Peppol är inte aktiverat för det här bolaget. Begär åtkomst under Inställningar > Fakturering > E-faktura via Peppol, så aktiverar vi det.',
message_en: 'Peppol is not enabled for this company. Request access under Settings > Invoicing > E-invoicing via Peppol and we will enable it.',
},
PEPPOL_SEND_LIMIT_REACHED: {
httpStatus: 409,
message_sv: 'Bolaget har använt sina Peppol-sändningar. Hör av dig till support för fler.',
message_en: 'The company has used its Peppol sends. Contact support for more.',
},
PEPPOL_RECEIVING_NOT_ENABLED: {
httpStatus: 403,
message_sv: 'Mottagning via Peppol är inte aktiverad för det här bolaget. Hör av dig till support så öppnar vi en plats.',
message_en: 'Receiving via Peppol is not enabled for this company. Contact support and we will open a slot.',
},
PEPPOL_ACCESS_ALREADY_ENABLED: {
httpStatus: 409,
message_sv: 'Peppol är redan aktiverat för bolaget.',
message_en: 'Peppol is already enabled for the company.',
},
PEPPOL_REGISTRATION_CAP_REACHED: {
httpStatus: 409,
message_sv: 'Alla platser för Peppol-mottagning är upptagna just nu. Hör av dig till support så öppnar vi fler. Att skicka e-fakturor fungerar ändå.',
@@ -0,0 +1,118 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { createQueuedMockSupabase } from '@/tests/helpers'
import {
checkPeppolSendPermission,
requestPeppolAccess,
setPeppolAccess,
summarizePeppolAccess,
type PeppolAccessRow,
} from '@/lib/invoices/peppol-access'
const { supabase: mockService, enqueue, reset, calls } = createQueuedMockSupabase()
const service = mockService as unknown as SupabaseClient
function row(overrides: Partial<PeppolAccessRow> = {}): PeppolAccessRow {
return {
company_id: 'company-1',
status: 'enabled',
max_sends: 50,
receive_enabled: false,
requested_at: '2026-08-21T15:00:00.000Z',
requested_by: 'user-1',
request_note: null,
enabled_at: '2026-08-21T16:00:00.000Z',
enabled_by: 'jakob',
disabled_at: null,
note: null,
created_at: '2026-08-21T15:00:00.000Z',
updated_at: '2026-08-21T16:00:00.000Z',
...overrides,
}
}
describe('summarizePeppolAccess', () => {
it('is locked without a row and reports sends only when enabled', () => {
expect(summarizePeppolAccess(null, 0)).toMatchObject({ status: 'none', send_enabled: false, receive_enabled: false, remaining_sends: null })
expect(summarizePeppolAccess(row({ status: 'requested' }), 0)).toMatchObject({ status: 'requested', send_enabled: false })
expect(summarizePeppolAccess(row(), 12)).toMatchObject({ send_enabled: true, max_sends: 50, sent_count: 12, remaining_sends: 38 })
expect(summarizePeppolAccess(row({ max_sends: null }), 12)).toMatchObject({ max_sends: null, remaining_sends: null })
expect(summarizePeppolAccess(row({ receive_enabled: true }), 0).receive_enabled).toBe(true)
expect(summarizePeppolAccess(row({ status: 'disabled', receive_enabled: true, disabled_at: 'x' }), 0).receive_enabled).toBe(false)
})
})
describe('checkPeppolSendPermission', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
})
it('refuses a company without a grant before counting anything', async () => {
enqueue({ data: null, error: null })
const result = await checkPeppolSendPermission({ service, companyId: 'company-1' })
expect(result).toMatchObject({ ok: false, code: 'PEPPOL_ACCESS_REQUIRED' })
expect(calls.filter((c) => c.table === 'peppol_deliveries')).toHaveLength(0)
})
it('refuses a requested or disabled company', async () => {
enqueue({ data: row({ status: 'requested', enabled_at: null }), error: null })
expect(await checkPeppolSendPermission({ service, companyId: 'company-1' })).toMatchObject({ ok: false, code: 'PEPPOL_ACCESS_REQUIRED' })
enqueue({ data: row({ status: 'disabled', disabled_at: 'x' }), error: null })
expect(await checkPeppolSendPermission({ service, companyId: 'company-1' })).toMatchObject({ ok: false, code: 'PEPPOL_ACCESS_REQUIRED' })
})
it('allows an enabled company under its cap and refuses at the cap', async () => {
enqueue({ data: row({ max_sends: 3 }), error: null })
enqueue({ data: null, error: null, count: 2 })
expect(await checkPeppolSendPermission({ service, companyId: 'company-1' })).toEqual({ ok: true, remaining: 1 })
enqueue({ data: row({ max_sends: 3 }), error: null })
enqueue({ data: null, error: null, count: 3 })
expect(await checkPeppolSendPermission({ service, companyId: 'company-1' })).toMatchObject({ ok: false, code: 'PEPPOL_SEND_LIMIT_REACHED' })
})
it('treats a null cap as unlimited', async () => {
enqueue({ data: row({ max_sends: null }), error: null })
enqueue({ data: null, error: null, count: 999 })
expect(await checkPeppolSendPermission({ service, companyId: 'company-1' })).toEqual({ ok: true, remaining: null })
})
})
describe('requestPeppolAccess / setPeppolAccess', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
})
it('creates a request, is idempotent on a second ask, and refuses when already enabled', async () => {
enqueue({ data: null, error: null })
enqueue({ data: row({ status: 'requested', enabled_at: null }), error: null })
const first = await requestPeppolAccess({ service, companyId: 'company-1', userId: 'user-1', note: 'offentlig sektor' })
expect(first).toMatchObject({ ok: true, created: true })
const upsert = calls.find((c) => c.method === 'upsert')?.args[0] as Record<string, unknown>
expect(upsert).toMatchObject({ company_id: 'company-1', status: 'requested', requested_by: 'user-1', request_note: 'offentlig sektor' })
enqueue({ data: row({ status: 'requested', enabled_at: null }), error: null })
expect(await requestPeppolAccess({ service, companyId: 'company-1', userId: 'user-1', note: null })).toMatchObject({ ok: true, created: false })
enqueue({ data: row(), error: null })
expect(await requestPeppolAccess({ service, companyId: 'company-1', userId: 'user-1', note: null })).toEqual({ ok: false, code: 'PEPPOL_ACCESS_ALREADY_ENABLED' })
})
it('grants with a cap and receiving flag, and disables without touching the cap', async () => {
enqueue({ data: row({ max_sends: 25, receive_enabled: true }), error: null })
await setPeppolAccess({ service, companyId: 'company-1', status: 'enabled', maxSends: 25, receiveEnabled: true, by: 'jakob' })
const granted = calls.find((c) => c.method === 'upsert')?.args[0] as Record<string, unknown>
expect(granted).toMatchObject({ status: 'enabled', max_sends: 25, receive_enabled: true, enabled_by: 'jakob', disabled_at: null })
expect(typeof granted.enabled_at).toBe('string')
reset()
enqueue({ data: row({ status: 'disabled', disabled_at: 'x' }), error: null })
await setPeppolAccess({ service, companyId: 'company-1', status: 'disabled', by: 'jakob' })
const disabled = calls.find((c) => c.method === 'upsert')?.args[0] as Record<string, unknown>
expect(disabled.status).toBe('disabled')
expect(disabled.max_sends).toBeUndefined()
expect(typeof disabled.disabled_at).toBe('string')
})
})
+183
View File
@@ -0,0 +1,183 @@
/**
* Peppol access per company: locked by default, requested by the company,
* granted (with a sending cap, and separately receiving) by the operators.
*
* Why a gate at all: every transmission through the Access Point is billed
* per document and every receiving identifier consumes a contracted tenant
* slot, so "anyone can toggle it on" is a cost and a contract exposure, not a
* feature. The gate is also the product truth on the invoice page: the send
* action says "ask for access" instead of pretending.
*/
import type { SupabaseClient } from '@supabase/supabase-js'
export type PeppolAccessStatus = 'requested' | 'enabled' | 'disabled'
export interface PeppolAccessRow {
company_id: string
status: PeppolAccessStatus
max_sends: number | null
receive_enabled: boolean
requested_at: string | null
requested_by: string | null
request_note: string | null
enabled_at: string | null
enabled_by: string | null
disabled_at: string | null
note: string | null
created_at: string
updated_at: string
}
/** What the product shows and gates on. `sent_count` counts real transmissions. */
export interface PeppolAccessSummary {
status: PeppolAccessStatus | 'none'
send_enabled: boolean
receive_enabled: boolean
max_sends: number | null
sent_count: number
remaining_sends: number | null
requested_at: string | null
enabled_at: string | null
}
export async function getPeppolAccess(
supabase: SupabaseClient,
companyId: string,
): Promise<PeppolAccessRow | null> {
const { data, error } = await supabase
.from('peppol_access')
.select('*')
.eq('company_id', companyId)
.maybeSingle()
if (error) throw new Error(`Failed to read Peppol access: ${error.message}`)
return (data as PeppolAccessRow | null) ?? null
}
/** Transmissions actually handed to the access point (a provider submission id exists). */
export async function countPeppolSends(
service: SupabaseClient,
companyId: string,
): Promise<number> {
const { count, error } = await service
.from('peppol_deliveries')
.select('id', { count: 'exact', head: true })
.eq('company_id', companyId)
.not('provider_submission_id', 'is', null)
if (error) throw new Error(`Failed to count Peppol sends: ${error.message}`)
return count ?? 0
}
export function summarizePeppolAccess(row: PeppolAccessRow | null, sentCount: number): PeppolAccessSummary {
const enabled = row?.status === 'enabled'
const maxSends = enabled ? row?.max_sends ?? null : null
return {
status: row?.status ?? 'none',
send_enabled: enabled,
receive_enabled: enabled && !!row?.receive_enabled,
max_sends: maxSends,
sent_count: sentCount,
remaining_sends: maxSends === null ? null : Math.max(0, maxSends - sentCount),
requested_at: row?.requested_at ?? null,
enabled_at: row?.enabled_at ?? null,
}
}
export async function getPeppolAccessSummary(args: {
supabase: SupabaseClient
service: SupabaseClient
companyId: string
}): Promise<PeppolAccessSummary> {
const row = await getPeppolAccess(args.supabase, args.companyId)
const sent = row?.status === 'enabled' ? await countPeppolSends(args.service, args.companyId) : 0
return summarizePeppolAccess(row, sent)
}
export type PeppolSendPermission =
| { ok: true; remaining: number | null }
| { ok: false; code: 'PEPPOL_ACCESS_REQUIRED' | 'PEPPOL_SEND_LIMIT_REACHED'; summary: PeppolAccessSummary }
/** The gate the send route asks before it touches the network. */
export async function checkPeppolSendPermission(args: {
service: SupabaseClient
companyId: string
}): Promise<PeppolSendPermission> {
const row = await getPeppolAccess(args.service, args.companyId)
if (!row || row.status !== 'enabled') {
return { ok: false, code: 'PEPPOL_ACCESS_REQUIRED', summary: summarizePeppolAccess(row, 0) }
}
const sent = await countPeppolSends(args.service, args.companyId)
const summary = summarizePeppolAccess(row, sent)
if (summary.max_sends !== null && sent >= summary.max_sends) {
return { ok: false, code: 'PEPPOL_SEND_LIMIT_REACHED', summary }
}
return { ok: true, remaining: summary.remaining_sends }
}
export type RequestPeppolAccessResult =
| { ok: true; row: PeppolAccessRow; created: boolean }
| { ok: false; code: 'PEPPOL_ACCESS_ALREADY_ENABLED' }
/**
* A company asks for access. Idempotent: a second request keeps the first
* timestamp; a company that already has access is told so. A disabled
* company may ask again (the row goes back to `requested`).
*/
export async function requestPeppolAccess(args: {
service: SupabaseClient
companyId: string
userId: string
note: string | null
}): Promise<RequestPeppolAccessResult> {
const existing = await getPeppolAccess(args.service, args.companyId)
if (existing?.status === 'enabled') return { ok: false, code: 'PEPPOL_ACCESS_ALREADY_ENABLED' }
if (existing?.status === 'requested') return { ok: true, row: existing, created: false }
const now = new Date().toISOString()
const { data, error } = await args.service
.from('peppol_access')
.upsert({
company_id: args.companyId,
status: 'requested',
requested_at: now,
requested_by: args.userId,
request_note: args.note,
disabled_at: null,
}, { onConflict: 'company_id' })
.select('*')
.single()
if (error || !data) throw new Error(`Failed to request Peppol access: ${error?.message ?? 'no row'}`)
return { ok: true, row: data as PeppolAccessRow, created: !existing }
}
/** Operator action (service role): grant, adjust or withdraw access. */
export async function setPeppolAccess(args: {
service: SupabaseClient
companyId: string
status: 'enabled' | 'disabled'
maxSends?: number | null
receiveEnabled?: boolean
by: string
note?: string | null
}): Promise<PeppolAccessRow> {
const now = new Date().toISOString()
const enabling = args.status === 'enabled'
// Undefined values are dropped by JSON serialization, so an omitted option
// leaves the stored column untouched on re-runs.
const { data, error } = await args.service
.from('peppol_access')
.upsert({
company_id: args.companyId,
status: args.status,
max_sends: args.maxSends,
receive_enabled: args.receiveEnabled,
note: args.note,
enabled_at: enabling ? now : undefined,
enabled_by: enabling ? args.by : undefined,
disabled_at: enabling ? null : now,
}, { onConflict: 'company_id' })
.select('*')
.single()
if (error || !data) throw new Error(`Failed to set Peppol access: ${error?.message ?? 'no row'}`)
return data as PeppolAccessRow
}
+2
View File
@@ -1023,6 +1023,8 @@ export const ARCHIVE_COVERED_ELSEWHERE_TABLES: Record<string, string> = {
* a portable räkenskapsinformation backup.
*/
export const ARCHIVE_EXCLUDED_TABLES: Record<string, string> = {
// Operator-side Peppol access grant and sending cap: platform configuration, not the company's räkenskapsinformation.
peppol_access: 'platform access grant (status, sending cap); no bookkeeping content',
agent_conversations: 'AI assistant state, not räkenskapsinformation',
agent_memory: 'AI assistant state, not räkenskapsinformation',
agent_profiles: 'AI assistant state, not räkenskapsinformation',