fix(inbox): never extract the receiving company as its own supplier (#2080)

* fix(inbox): never extract the receiving company as its own supplier

The model sometimes reads the Kund/Kunduppgifter block of bank agreements
and similar documents as the issuer, so the inbox offered to create the
user's own company as a leverantor. Two layers: a supplier-direction rule
in the extraction prompt (issuer, never the customer/recipient block), and
a deterministic post-extraction guard that nulls the supplier block when
its org number, derived VAT number, or exact name equals the receiving
company's own. All AI extraction paths (upload, deferred, retry,
attach-document, document-extraction, MCP) pass the company identity.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hqm9QgdyNAFaWiz6Ww7pgb

* fix(inbox): keep the own-company guard alive for photographed documents

Skeptic findings on PR #2080: normalizeImageForExtraction rebuilt the input
without ownCompany, so the guard never fired for HEIC/oversized phone photos
(the motivating case). Spread the original input instead. Also let a
provably different extracted org number outvote a name coincidence, and
accept 12-digit personnummer-form own org numbers (19/20 century prefix,
enskild firma) alongside the 16-prefixed organisation form.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hqm9QgdyNAFaWiz6Ww7pgb

* docs(compliance): add RoPA entry for the own-company-identity lookup

Compliance swarm (GDPR Art. 30): fetchOwnCompanyIdentity reads
companies.name and org_number on every extraction; record the processing
activity (transient in-memory comparison, never sent to the model).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hqm9QgdyNAFaWiz6Ww7pgb

* fix(inbox): log own-company identity lookup failures instead of failing silent

Compliance swarm (SOC 2 CC7.2): the bare catch in fetchOwnCompanyIdentity
made a persistently broken lookup (RLS misconfig, DB outage) disable the
guard invisibly. Also pin the VAT-number match across prefixed and bare
digit forms in the test matrix.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hqm9QgdyNAFaWiz6Ww7pgb

* fix(inbox): surface maybeSingle query errors in the own-company lookup

CodeRabbit: maybeSingle() reports RLS/query failures in error without
throwing, so the failure log added for SOC 2 CC7.2 never fired for exactly
those cases. Throw the reported error into the existing catch (still fail
open to nulls).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hqm9QgdyNAFaWiz6Ww7pgb

---------

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Mattsson
2026-08-31 15:13:14 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent fc54e79e08
commit 84c8e1ce59
10 changed files with 369 additions and 7 deletions
@@ -10,6 +10,7 @@ vi.mock('@/lib/supabase/server', () => ({
const extractMock = vi.fn()
vi.mock('@/extensions/general/invoice-inbox/lib/extract-invoice-fields', () => ({
extractInvoiceFields: (...args: unknown[]) => extractMock(...args),
fetchOwnCompanyIdentity: vi.fn().mockResolvedValue({ orgNumber: null, name: null }),
}))
const hasCapabilityMock = vi.fn()
@@ -1,6 +1,6 @@
import type { Extension } from '@/lib/extensions/types'
import type { SupabaseClient } from '@supabase/supabase-js'
import { extractInvoiceFields } from '@/extensions/general/invoice-inbox/lib/extract-invoice-fields'
import { extractInvoiceFields, fetchOwnCompanyIdentity } from '@/extensions/general/invoice-inbox/lib/extract-invoice-fields'
import { getAiStatus } from '@/lib/ai'
import { hasCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
@@ -176,6 +176,7 @@ async function extractAndPersist(
buffer,
mimeType,
fileName: (document.file_name as string) || 'document',
ownCompany: await fetchOwnCompanyIdentity(supabase, companyId),
})
// extractInvoiceFields returns an "empty" result on failure rather than
// throwing. `skipped` means no model call was made (and why); a null
@@ -2,6 +2,8 @@ import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest'
import {
extractInvoiceFields,
extractJsonObject,
stripOwnCompanyAsSupplier,
emptyResult,
} from '@/extensions/general/invoice-inbox/lib/extract-invoice-fields'
// Mock the Bedrock SDK so tests drive the JSON parser without
@@ -610,6 +612,75 @@ describe('extractInvoiceFields', () => {
expect(content[0].source.media_type).toBe('image/jpeg')
})
// ── Own-company-as-supplier guard (2026-08) ──────────
it('strips the supplier when the model extracted the receiving company itself', async () => {
// A bank agreement's Kunduppgifter block: the model read the customer
// (the user's own company) as the issuer.
mockCreate.mockReturnValueOnce(
aiResponse({
...VALID_RESULT,
documentKind: 'other',
supplier: {
name: 'Testbrand AB',
orgNumber: '5566778899',
vatNumber: null,
address: 'Provgatan 1, 111 11 Teststad',
bankgiro: null,
plusgiro: null,
},
})
)
const { data } = await extractInvoiceFields({
buffer: Buffer.from('%PDF'),
mimeType: 'application/pdf',
fileName: 'affarsavtal.pdf',
ownCompany: { orgNumber: '556677-8899', name: 'Testbrand AB' },
})
expect(data.supplier).toEqual({
name: null,
orgNumber: null,
vatNumber: null,
address: null,
bankgiro: null,
plusgiro: null,
})
// Only the supplier block is affected.
expect(data.totals.total).toBe(6.25)
})
it('still strips the own company on the image-normalization path (photographed documents)', async () => {
// normalizeImageForExtraction rebuilds the input for HEIC/oversized
// photos; ownCompany must survive that rebuild or the guard is dead for
// exactly the phone-photo documents the fix targets.
sharpMock.mockImplementationOnce(() => workingSharpChain(Buffer.from('converted-jpeg')))
mockCreate.mockReturnValueOnce(
aiResponse({
...VALID_RESULT,
supplier: { ...VALID_RESULT.supplier, name: 'Testbrand AB', orgNumber: '5566778899' },
})
)
const { data } = await extractInvoiceFields({
buffer: Buffer.alloc(5 * 1024 * 1024, 1),
mimeType: 'image/jpeg',
fileName: 'photo-of-avtal.jpg',
ownCompany: { orgNumber: '556677-8899', name: 'Testbrand AB' },
})
expect(data.supplier.name).toBeNull()
expect(data.supplier.orgNumber).toBeNull()
})
it('leaves a genuine supplier untouched when ownCompany is passed', async () => {
mockCreate.mockReturnValueOnce(aiResponse(VALID_RESULT))
const { data } = await extractInvoiceFields({
buffer: Buffer.from('%PDF'),
mimeType: 'application/pdf',
fileName: 'invoice.pdf',
ownCompany: { orgNumber: '556677-8899', name: 'Testbrand AB' },
})
expect(data.supplier.name).toBe('Anthropic, PBC')
})
it('does not invoke sharp for normal-sized supported images', async () => {
mockCreate.mockReturnValueOnce(aiResponse(VALID_RESULT))
await extractInvoiceFields({
@@ -628,3 +699,128 @@ describe('extractInvoiceFields', () => {
else delete process.env.AWS_SECRET_ACCESS_KEY
})
})
describe('stripOwnCompanyAsSupplier', () => {
function withSupplier(supplier: Partial<ReturnType<typeof emptyResult>['supplier']>) {
const base = emptyResult()
return { ...base, supplier: { ...base.supplier, ...supplier } }
}
const strippedSupplier = {
name: null,
orgNumber: null,
vatNumber: null,
address: null,
bankgiro: null,
plusgiro: null,
}
const own = { orgNumber: '556677-8899', name: 'Testbrand AB' }
it('matches the org number across hyphen and 12-digit variants', () => {
for (const extracted of ['5566778899', '556677-8899', '165566778899', '16556677-8899']) {
const result = stripOwnCompanyAsSupplier(
withSupplier({ name: 'Något AB', orgNumber: extracted }),
own
)
expect(result.supplier, `orgNumber ${extracted}`).toEqual(strippedSupplier)
}
})
it('matches the derived Swedish VAT number (SE<orgnr>01)', () => {
// Both the full prefixed form and a bare digits form denote the same
// registration: digitsOf strips the SE prefix before comparing.
for (const vat of ['SE556677889901', '556677889901', 'SE 556677-8899 01']) {
const result = stripOwnCompanyAsSupplier(
withSupplier({ name: 'Något AB', vatNumber: vat }),
own
)
expect(result.supplier, `vatNumber ${vat}`).toEqual(strippedSupplier)
}
})
it('matches the exact company name case-insensitively', () => {
const result = stripOwnCompanyAsSupplier(withSupplier({ name: ' testbrand ab ' }), own)
expect(result.supplier).toEqual(strippedSupplier)
})
it('matches a personnummer-form own org number (enskild firma)', () => {
// companies.org_number for enskild firma is the owner's personnummer,
// often stored in 12-digit century form.
const result = stripOwnCompanyAsSupplier(
withSupplier({ name: 'Firma X', orgNumber: '550505-5566' }),
{ orgNumber: '195505055566', name: 'Firma X Enskild' }
)
expect(result.supplier).toEqual(strippedSupplier)
})
it('lets a provably different org number outvote a name coincidence', () => {
// A same-named but distinct entity (foreign registry, generic name) with
// its own org number on the document stays a valid supplier.
const supplier = {
name: 'Testbrand AB',
orgNumber: '5029032081',
vatNumber: null,
address: null,
bankgiro: null,
plusgiro: null,
}
expect(stripOwnCompanyAsSupplier(withSupplier(supplier), own).supplier).toEqual(supplier)
})
it('leaves a different supplier alone', () => {
const supplier = {
name: 'SEB',
orgNumber: '5029032081',
vatNumber: null,
address: null,
bankgiro: null,
plusgiro: null,
}
expect(stripOwnCompanyAsSupplier(withSupplier(supplier), own).supplier).toEqual(supplier)
})
it('never matches on an empty own identity (junk cannot match junk)', () => {
const result = stripOwnCompanyAsSupplier(
withSupplier({ name: 'Något AB', orgNumber: null }),
{ orgNumber: null, name: null }
)
expect(result.supplier.name).toBe('Något AB')
})
it('fetchOwnCompanyIdentity degrades to nulls on a reported query error (fail open, logged)', async () => {
const { fetchOwnCompanyIdentity } = await import(
'@/extensions/general/invoice-inbox/lib/extract-invoice-fields'
)
const supabase = {
from: () => ({
select: () => ({
eq: () => ({
maybeSingle: () =>
Promise.resolve({ data: null, error: new Error('permission denied') }),
}),
}),
}),
}
await expect(
fetchOwnCompanyIdentity(supabase as never, 'company-1')
).resolves.toEqual({ orgNumber: null, name: null })
})
it('is a no-op without ownCompany', () => {
const data = withSupplier({ name: 'Testbrand AB', orgNumber: '5566778899' })
expect(stripOwnCompanyAsSupplier(data, undefined)).toBe(data)
})
it('preserves every non-supplier field when stripping', () => {
const base = withSupplier({ name: 'Testbrand AB' })
const data = {
...base,
documentKind: 'other' as const,
totals: { ...base.totals, total: 2500 },
prominentAmounts: [{ amount: 2500, label: 'Engångspris' }],
}
const result = stripOwnCompanyAsSupplier(data, own)
expect(result.documentKind).toBe('other')
expect(result.totals.total).toBe(2500)
expect(result.prominentAmounts).toEqual([{ amount: 2500, label: 'Engångspris' }])
})
})
@@ -9,6 +9,7 @@ import type { ExtensionContext } from '@/lib/extensions/types'
vi.mock('@/extensions/general/invoice-inbox/lib/extract-invoice-fields', () => ({
extractInvoiceFields: vi.fn(),
fetchOwnCompanyIdentity: vi.fn().mockResolvedValue({ orgNumber: null, name: null }),
}))
vi.mock('@/lib/rate-limits/inbox', () => ({
+3 -1
View File
@@ -12,7 +12,7 @@ import { validateBody } from '@/lib/api/validate'
import { hasErrorEntry } from '@/lib/errors/structured-errors'
import { dbError } from '@/lib/errors/db-error'
import { matchSupplierId } from '@/lib/suppliers/match-supplier'
import { extractInvoiceFields, ExtractionSchema, emptyResult } from './lib/extract-invoice-fields'
import { extractInvoiceFields, ExtractionSchema, emptyResult, fetchOwnCompanyIdentity } from './lib/extract-invoice-fields'
import { mirrorExtractionToDocument } from './lib/mirror-extraction'
import {
uploadAndExtract,
@@ -1081,6 +1081,7 @@ export const invoiceInboxExtension: Extension = {
buffer: Buffer.from(slicedBuffer ?? buffer),
mimeType: file.type,
fileName: file.name,
ownCompany: await fetchOwnCompanyIdentity(ctx.supabase, ctx.companyId),
})
const { data: extracted } = extraction
if (!skipExtraction && slicedBuffer != null && pageCount != null) {
@@ -1448,6 +1449,7 @@ export const invoiceInboxExtension: Extension = {
buffer,
mimeType: doc.mime_type,
fileName: doc.file_name,
ownCompany: await fetchOwnCompanyIdentity(ctx.supabase, ctx.companyId),
})
const { data: extracted } = extraction
await mirrorExtractionToDocument(item.document_id, {
File diff suppressed because one or more lines are too long
@@ -1,6 +1,6 @@
import { after } from 'next/server'
import { uploadDocument } from '@/lib/core/documents/document-service'
import { extractInvoiceFields, emptyResult } from './extract-invoice-fields'
import { extractInvoiceFields, emptyResult, fetchOwnCompanyIdentity } from './extract-invoice-fields'
import { mirrorExtractionToDocument } from './mirror-extraction'
import { getAiStatus } from '@/lib/ai'
import { hasCapability } from '@/lib/entitlements/has-capability'
@@ -520,6 +520,7 @@ export async function processArchivedDocument(
buffer: Buffer.from(slicedBuffer ?? file.buffer),
mimeType: file.type,
fileName: file.name,
ownCompany: await fetchOwnCompanyIdentity(supabase, companyId),
})
const { data: extracted, rawText } = extraction
if (!skipExtraction && slicedBuffer != null && pageCount != null) {
@@ -660,6 +661,7 @@ function scheduleDeferredExtraction(job: DeferredExtractionJob): void {
buffer: Buffer.from(slicedBuffer ?? job.file.buffer),
mimeType: job.file.type,
fileName: job.file.name,
ownCompany: await fetchOwnCompanyIdentity(supabase, job.companyId),
})
extracted = result.data
rawText = result.rawText
+7 -2
View File
@@ -266,7 +266,7 @@ import {
} from '@/lib/core/documents/document-service'
import { toSameOriginStorageUrl } from '@/lib/core/documents/storage-proxy'
import { createHash } from 'node:crypto'
import { extractInvoiceFields, ExtractionSchema as InvoiceExtractionSchema, AgentExtractionSchema } from '@/extensions/general/invoice-inbox/lib/extract-invoice-fields'
import { extractInvoiceFields, ExtractionSchema as InvoiceExtractionSchema, AgentExtractionSchema, fetchOwnCompanyIdentity } from '@/extensions/general/invoice-inbox/lib/extract-invoice-fields'
import { mirrorExtractionToDocument } from '@/extensions/general/invoice-inbox/lib/mirror-extraction'
// Skatteverket filing tools (PR5). Cross-extension lib import, same sanctioned
// pattern as invoice-inbox above: the CI guard only checks lib/, app/api/,
@@ -602,7 +602,12 @@ async function createDocumentInboxItem(
if (existing) return existing
}
const extraction = await extractInvoiceFields({ buffer, mimeType, fileName })
const extraction = await extractInvoiceFields({
buffer,
mimeType,
fileName,
ownCompany: await fetchOwnCompanyIdentity(supabase, companyId),
})
const { data: extracted } = extraction
// uploadDocument()/completePendingDocumentUpload() were told this inbox
// item owns extraction, so the document-extraction extension yielded;