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:
co-authored by
Claude Fable 5
Jakob Wennberg
parent
9ef7de861f
commit
3ac80edc96
@@ -0,0 +1,123 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, createMockRouteParams, createQueuedMockSupabase } from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
const service = createQueuedMockSupabase()
|
||||
const requireAuthMock = vi.fn()
|
||||
const sendEmailMock = vi.fn()
|
||||
const isConfiguredMock = vi.fn()
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: () => service.supabase,
|
||||
}))
|
||||
vi.mock('@/lib/email/service', () => ({
|
||||
getEmailService: () => ({
|
||||
sendEmail: (...args: unknown[]) => sendEmailMock(...args),
|
||||
isConfigured: () => isConfiguredMock(),
|
||||
}),
|
||||
}))
|
||||
vi.mock('@/lib/support', () => ({
|
||||
getSupportRecipientEmail: () => 'support@example.test',
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const user = { id: 'user-1', email: 'owner@example.test' }
|
||||
const requestedRow = {
|
||||
company_id: 'company-1',
|
||||
status: 'requested',
|
||||
max_sends: null,
|
||||
receive_enabled: false,
|
||||
requested_at: '2026-08-21T15:00:00.000Z',
|
||||
requested_by: 'user-1',
|
||||
request_note: null,
|
||||
enabled_at: null,
|
||||
enabled_by: null,
|
||||
disabled_at: null,
|
||||
note: null,
|
||||
created_at: '2026-08-21T15:00:00.000Z',
|
||||
updated_at: '2026-08-21T15:00:00.000Z',
|
||||
}
|
||||
|
||||
describe('POST /api/settings/peppol/access', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
service.reset()
|
||||
isConfiguredMock.mockReturnValue(true)
|
||||
sendEmailMock.mockResolvedValue({ success: true })
|
||||
requireAuthMock.mockResolvedValue({ user, supabase: mockSupabase, error: null })
|
||||
})
|
||||
|
||||
function post(body: unknown = {}) {
|
||||
return POST(createMockRequest('/api/settings/peppol/access', { method: 'POST', body }), createMockRouteParams({}))
|
||||
}
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: mockSupabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
expect((await post()).status).toBe(401)
|
||||
})
|
||||
|
||||
it('rejects an oversized note', async () => {
|
||||
const response = await post({ note: 'x'.repeat(2001) })
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('refuses the sandbox', async () => {
|
||||
enqueue({ data: { is_sandbox: true }, error: null })
|
||||
const response = await post()
|
||||
expect(response.status).toBe(403)
|
||||
expect((await response.json()).error.code).toBe('PEPPOL_SANDBOX_NOT_ALLOWED')
|
||||
})
|
||||
|
||||
it('records the request, mails the operators and returns the locked summary', async () => {
|
||||
enqueue({ data: { is_sandbox: false }, error: null }) // sandbox check
|
||||
service.enqueue({ data: null, error: null }) // no access row
|
||||
service.enqueue({ data: requestedRow, error: null }) // upsert
|
||||
enqueue({ data: { company_name: 'Kund AB', org_number: '556677-8899' }, error: null }) // company settings
|
||||
service.enqueue({ data: requestedRow, error: null }) // summary read
|
||||
|
||||
const response = await post({ note: 'Vi fakturerar Region Skåne' })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(201)
|
||||
expect(body.data.access).toMatchObject({ status: 'requested', send_enabled: false })
|
||||
expect(sendEmailMock).toHaveBeenCalledTimes(1)
|
||||
const mail = sendEmailMock.mock.calls[0][0] as { to: string; subject: string; text: string }
|
||||
expect(mail.to).toBe('support@example.test')
|
||||
expect(mail.subject).toContain('Kund AB')
|
||||
expect(mail.text).toContain('company-1')
|
||||
expect(mail.text).toContain('Region Skåne')
|
||||
})
|
||||
|
||||
it('is idempotent for a repeated request (no second e-mail) and 409 when already enabled', async () => {
|
||||
enqueue({ data: { is_sandbox: false }, error: null })
|
||||
service.enqueue({ data: requestedRow, error: null })
|
||||
service.enqueue({ data: requestedRow, error: null })
|
||||
const again = await post()
|
||||
expect(again.status).toBe(200)
|
||||
expect(sendEmailMock).not.toHaveBeenCalled()
|
||||
|
||||
reset(); service.reset()
|
||||
enqueue({ data: { is_sandbox: false }, error: null })
|
||||
service.enqueue({ data: { ...requestedRow, status: 'enabled', enabled_at: '2026-08-21T16:00:00.000Z' }, error: null })
|
||||
const enabled = await post()
|
||||
expect(enabled.status).toBe(409)
|
||||
expect((await enabled.json()).error.code).toBe('PEPPOL_ACCESS_ALREADY_ENABLED')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { privateNoStore } from '@/lib/api/private-no-store'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import {
|
||||
getPeppolAccessSummary,
|
||||
requestPeppolAccess,
|
||||
} from '@/lib/invoices/peppol-access'
|
||||
import { isSandboxCompany } from '@/lib/sandbox/guard'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { getSupportRecipientEmail } from '@/lib/support'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
const RequestAccessSchema = z.object({
|
||||
note: z.string().trim().max(2000).optional(),
|
||||
})
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/settings/peppol/access: the company asks for Peppol access.
|
||||
*
|
||||
* Writes the request row (service role; the browser cannot grant itself
|
||||
* anything) and tells the operators by e-mail. The e-mail is best-effort: the
|
||||
* row is the source of truth and the operators' script lists open requests.
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'settings.peppol.access.request',
|
||||
async (request, { supabase, companyId, user, log, requestId }) => {
|
||||
const validation = await validateBody(request, RequestAccessSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const note = validation.data.note?.trim() || null
|
||||
|
||||
if (await isSandboxCompany(supabase, companyId)) {
|
||||
return privateNoStore(errorResponseFromCode('PEPPOL_SANDBOX_NOT_ALLOWED', log, { requestId }))
|
||||
}
|
||||
|
||||
const service = createServiceClient()
|
||||
try {
|
||||
const result = await requestPeppolAccess({ service, companyId, userId: user.id, note })
|
||||
if (!result.ok) {
|
||||
return privateNoStore(errorResponseFromCode(result.code, log, { requestId }))
|
||||
}
|
||||
|
||||
if (result.created) {
|
||||
const { data: company } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name, org_number')
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
const emailService = getEmailService()
|
||||
if (emailService.isConfigured()) {
|
||||
const companyName = (company as { company_name?: string | null } | null)?.company_name ?? 'okänt bolag'
|
||||
const orgNumber = (company as { org_number?: string | null } | null)?.org_number ?? 'saknas'
|
||||
const sent = await emailService.sendEmail({
|
||||
to: getSupportRecipientEmail(),
|
||||
subject: `[${getBranding().appName.toLowerCase()} peppol] Åtkomstbegäran: ${companyName}`,
|
||||
replyTo: user.email,
|
||||
html: [
|
||||
`<p><strong>Bolag:</strong> ${escapeHtml(companyName)} (${escapeHtml(orgNumber)})</p>`,
|
||||
`<p><strong>Company ID:</strong> ${companyId}</p>`,
|
||||
`<p><strong>Begärd av:</strong> ${escapeHtml(user.email ?? '')} (${user.id})</p>`,
|
||||
note ? `<hr /><p>${escapeHtml(note).replace(/\n/g, '<br />')}</p>` : '',
|
||||
`<hr /><p>Aktivera: <code>npx tsx --env-file=.env.local scripts/peppol/access.ts enable ${companyId} --max-sends 50</code></p>`,
|
||||
].join('\n'),
|
||||
text: `Bolag: ${companyName} (${orgNumber})\nCompany ID: ${companyId}\nBegärd av: ${user.email ?? ''} (${user.id})\n\n${note ?? ''}\n\nAktivera: npx tsx --env-file=.env.local scripts/peppol/access.ts enable ${companyId} --max-sends 50`,
|
||||
})
|
||||
if (!sent.success) {
|
||||
log.warn('peppol access request e-mail failed', { companyId, reason: sent.error })
|
||||
}
|
||||
} else {
|
||||
log.warn('peppol access request: e-mail service not configured, request recorded only', { companyId })
|
||||
}
|
||||
}
|
||||
|
||||
const summary = await getPeppolAccessSummary({ supabase: service, service, companyId })
|
||||
return privateNoStore(NextResponse.json({ data: { access: summary } }, { status: result.created ? 201 : 200 }))
|
||||
} catch (err) {
|
||||
return privateNoStore(errorResponse(err, log, { requestId }))
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
Reference in New Issue
Block a user