Add/mcp and visma (#547)
* fix: simplify COMING_SOON_PROVIDERS to include only bjornlunden and briox * feat: add supplier creation functionality and related operations * feat: reorder and enhance OAuth scopes in Visma integration * feat: implement create supplier functionality with validation and risk tier management
This commit is contained in:
@@ -201,6 +201,8 @@ export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
|
||||
gnubok_export_sie: 'reports:read',
|
||||
gnubok_audit_package: 'reports:read',
|
||||
gnubok_import_sie: 'bookkeeping:write',
|
||||
// Supplier CRUD
|
||||
gnubok_create_supplier: 'suppliers:write',
|
||||
// Supplier invoice lifecycle
|
||||
gnubok_approve_supplier_invoice: 'suppliers:write',
|
||||
gnubok_credit_supplier_invoice: 'suppliers:write',
|
||||
|
||||
@@ -52,6 +52,8 @@ import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { appendProcessingHistory } from '@/lib/processing-history/append'
|
||||
import { CreateSupplierParamsSchema } from '@/lib/pending-operations/schemas/create-supplier'
|
||||
import { z } from 'zod'
|
||||
import type {
|
||||
Transaction,
|
||||
TransactionCategory,
|
||||
@@ -60,6 +62,7 @@ import type {
|
||||
Currency,
|
||||
Invoice,
|
||||
Customer,
|
||||
Supplier,
|
||||
PendingOperation,
|
||||
CompanySettings,
|
||||
InvoiceItem,
|
||||
@@ -319,6 +322,63 @@ async function commitCreateCustomer(
|
||||
return { data: { customer_id: data.id } }
|
||||
}
|
||||
|
||||
async function commitCreateSupplier(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
// Defense in depth: re-validate the staged params at the commit boundary so a
|
||||
// tampered pending_operations row cannot inject unexpected fields or
|
||||
// malformed payment-routing data into the suppliers table (ASVS V4.5).
|
||||
let validated
|
||||
try {
|
||||
validated = CreateSupplierParamsSchema.parse(params)
|
||||
} catch (err) {
|
||||
if (err instanceof z.ZodError) {
|
||||
const issue = err.issues[0]
|
||||
const path = issue?.path?.join('.') ?? 'params'
|
||||
return { error: `Invalid ${path}: ${issue?.message ?? 'validation failed'}`, status: 400 }
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('suppliers')
|
||||
.insert({
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
name: validated.name,
|
||||
supplier_type: validated.supplier_type,
|
||||
email: validated.email ?? null,
|
||||
phone: validated.phone ?? null,
|
||||
org_number: validated.org_number ?? null,
|
||||
vat_number: validated.vat_number ?? null,
|
||||
address_line1: validated.address_line1 ?? null,
|
||||
address_line2: validated.address_line2 ?? null,
|
||||
postal_code: validated.postal_code ?? null,
|
||||
city: validated.city ?? null,
|
||||
country: validated.country ?? 'SE',
|
||||
bankgiro: validated.bankgiro ?? null,
|
||||
plusgiro: validated.plusgiro ?? null,
|
||||
bank_account: validated.bank_account ?? null,
|
||||
iban: validated.iban ?? null,
|
||||
bic: validated.bic ?? null,
|
||||
default_expense_account: validated.default_expense_account ?? null,
|
||||
default_payment_terms: validated.default_payment_terms,
|
||||
default_currency: validated.default_currency ?? 'SEK',
|
||||
notes: validated.notes ?? null,
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) return { error: error.message, status: 500 }
|
||||
|
||||
await eventBus.emit({ type: 'supplier.created', payload: { supplier: data as Supplier, userId, companyId } })
|
||||
|
||||
return { data: { supplier_id: data.id } }
|
||||
}
|
||||
|
||||
async function commitCreateTransaction(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
@@ -1935,6 +1995,9 @@ export async function commitPendingOperation(
|
||||
case 'create_customer':
|
||||
result = await commitCreateCustomer(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'create_supplier':
|
||||
result = await commitCreateSupplier(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'create_invoice':
|
||||
result = await commitCreateInvoice(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
|
||||
@@ -27,6 +27,12 @@ export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
|
||||
match_transaction_invoice: 'medium',
|
||||
create_invoice: 'medium', // creates as draft; sending is a separate op
|
||||
create_transaction: 'medium', // ingests an uncategorized row; reversible by delete
|
||||
// Supplier master data carries payment-routing fields (IBAN, BIC, bankgiro,
|
||||
// bank_account) that drive outgoing payment files and supplier invoice
|
||||
// postings. A wrong account or org_number can enable supplier-fraud / BEC
|
||||
// (silently rerouting payment), so always require explicit human approval
|
||||
// rather than auto-commit.
|
||||
create_supplier: 'medium',
|
||||
// Pinning a doc to a tx is reversible while pre-categorization, but the link
|
||||
// becomes part of the verifikation underlag (BFL 5 kap 6 §) once categorize
|
||||
// propagates it. A wrong attachment requires a rättelse, so require human
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* Authoritative server-side validation for the create_supplier staged
|
||||
* operation. Used by:
|
||||
* - The MCP tool execute() before staging (extensions/general/mcp-server/server.ts)
|
||||
* - commitCreateSupplier() before the suppliers INSERT (lib/pending-operations/commit.ts)
|
||||
*
|
||||
* Defense in depth: validating at the commit boundary protects the DB even
|
||||
* if a caller writes directly to pending_operations.params bypassing the
|
||||
* MCP tool, satisfying ASVS V4.5 / ISO A.8.28 input-validation guidance.
|
||||
*
|
||||
* Financial identifiers (IBAN, BIC, bankgiro, plusgiro, org_number,
|
||||
* vat_number, default_expense_account) are format-validated so adversarial
|
||||
* or malformed payment-routing data cannot be persisted. Bankgiro additionally
|
||||
* passes the Luhn check (SE-R-008/009). VAT number format is checked against
|
||||
* the VIES per-country pattern (SE-R-001, ML 17 kap 24§ p.4).
|
||||
*/
|
||||
import { z } from 'zod'
|
||||
import { validateBankgiroNumber } from '@/lib/bankgiro/luhn'
|
||||
import { parseVatNumber } from '@/lib/vat/vies-client'
|
||||
|
||||
const IBAN_RE = /^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/
|
||||
const BIC_RE = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/
|
||||
const SE_ORG_NUMBER_RE = /^\d{6}-?\d{4}$|^\d{12}$/
|
||||
const COUNTRY_RE = /^[A-Z]{2}$/
|
||||
const PLUSGIRO_RE = /^\d{1,7}-?\d{1}$/
|
||||
const BAS_EXPENSE_RE = /^[4567]\d{3}$/
|
||||
const SUPPLIER_TYPES = ['swedish_business', 'eu_business', 'non_eu_business'] as const
|
||||
|
||||
/**
|
||||
* Accept string | null | undefined, trim, and normalise empty to undefined.
|
||||
* Then run the inner zod string validators on the survivor.
|
||||
*/
|
||||
function optString(inner: z.ZodTypeAny) {
|
||||
return z.preprocess(
|
||||
(v) => {
|
||||
if (v == null) return undefined
|
||||
if (typeof v !== 'string') return v
|
||||
const t = v.trim()
|
||||
return t === '' ? undefined : t
|
||||
},
|
||||
inner.optional(),
|
||||
)
|
||||
}
|
||||
|
||||
const emailField = optString(z.string().email('Invalid email format').max(255))
|
||||
const phoneField = optString(z.string().max(50))
|
||||
const orgNumberField = optString(
|
||||
z
|
||||
.string()
|
||||
.max(20)
|
||||
.refine(
|
||||
(v) => SE_ORG_NUMBER_RE.test(v.replace(/\s/g, '')),
|
||||
'Invalid Swedish org number format (expected XXXXXX-XXXX or 12 digits)',
|
||||
),
|
||||
)
|
||||
const vatNumberField = optString(
|
||||
z
|
||||
.string()
|
||||
.max(20)
|
||||
.refine(
|
||||
(v) => parseVatNumber(v) !== null,
|
||||
'Invalid EU VAT number format (must include valid country prefix)',
|
||||
),
|
||||
)
|
||||
const countryField = optString(
|
||||
z.string().refine((v) => COUNTRY_RE.test(v.toUpperCase()), 'country must be a 2-letter ISO 3166-1 alpha-2 code'),
|
||||
)
|
||||
const bankgiroField = optString(
|
||||
z.string().max(20).refine(
|
||||
(v) => validateBankgiroNumber(v),
|
||||
'Invalid Bankgiro (must be 7-8 digits with valid Luhn check digit)',
|
||||
),
|
||||
)
|
||||
const plusgiroField = optString(
|
||||
z.string().max(20).refine(
|
||||
(v) => PLUSGIRO_RE.test(v.replace(/\s/g, '')),
|
||||
'Invalid Plusgiro (expected 2-8 digits)',
|
||||
),
|
||||
)
|
||||
const ibanField = optString(
|
||||
z.string().max(34).refine(
|
||||
(v) => IBAN_RE.test(v.replace(/\s/g, '').toUpperCase()),
|
||||
'Invalid IBAN format',
|
||||
),
|
||||
)
|
||||
const bicField = optString(
|
||||
z.string().max(11).refine(
|
||||
(v) => BIC_RE.test(v.replace(/\s/g, '').toUpperCase()),
|
||||
'Invalid BIC/SWIFT format',
|
||||
),
|
||||
)
|
||||
const expenseAccountField = optString(
|
||||
z.string().refine(
|
||||
(v) => BAS_EXPENSE_RE.test(v),
|
||||
'default_expense_account must be a 4-digit BAS expense account (class 4, 5, 6, or 7)',
|
||||
),
|
||||
)
|
||||
// Accept either a number or a numeric string. Critically, an explicit 0 is
|
||||
// preserved (some suppliers are due-on-receipt). null/undefined falls through
|
||||
// to the 30-day default via .default().
|
||||
const paymentTermsField = z
|
||||
.preprocess(
|
||||
(v) => {
|
||||
if (v == null || v === '') return undefined
|
||||
if (typeof v === 'number') return v
|
||||
if (typeof v === 'string') {
|
||||
const n = Number(v)
|
||||
return Number.isNaN(n) ? v : n
|
||||
}
|
||||
return v
|
||||
},
|
||||
z.number().int('default_payment_terms must be an integer').min(0).max(365).optional(),
|
||||
)
|
||||
.default(30)
|
||||
|
||||
export const CreateSupplierParamsSchema = z
|
||||
.object({
|
||||
name: z
|
||||
.preprocess(
|
||||
(v) => (typeof v === 'string' ? v.trim() : v),
|
||||
z.string().min(1, 'Supplier name is required').max(255),
|
||||
),
|
||||
supplier_type: z.enum(SUPPLIER_TYPES).default('swedish_business'),
|
||||
email: emailField,
|
||||
phone: phoneField,
|
||||
org_number: orgNumberField,
|
||||
vat_number: vatNumberField,
|
||||
address_line1: optString(z.string().max(255)),
|
||||
address_line2: optString(z.string().max(255)),
|
||||
postal_code: optString(z.string().max(20)),
|
||||
city: optString(z.string().max(100)),
|
||||
country: countryField,
|
||||
bankgiro: bankgiroField,
|
||||
plusgiro: plusgiroField,
|
||||
bank_account: optString(z.string().max(50)),
|
||||
iban: ibanField,
|
||||
bic: bicField,
|
||||
default_expense_account: expenseAccountField,
|
||||
default_payment_terms: paymentTermsField,
|
||||
default_currency: optString(z.string().length(3, 'currency must be a 3-letter ISO code')),
|
||||
notes: optString(z.string().max(2000)),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((val, ctx) => {
|
||||
if (val.supplier_type === 'eu_business' && !val.vat_number) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['vat_number'],
|
||||
message: 'EU business suppliers must have an EU VAT number (ML 17 kap 24§)',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export type CreateSupplierParams = z.infer<typeof CreateSupplierParamsSchema>
|
||||
@@ -7,24 +7,29 @@ import {
|
||||
} from '@/lib/http/fetch-with-timeout';
|
||||
|
||||
const DEFAULT_SCOPES = [
|
||||
'offline_access',
|
||||
'ea:api',
|
||||
'offline_access',
|
||||
'ea:sales',
|
||||
'ea:accounting',
|
||||
'ea:purchase',
|
||||
'vls:api',
|
||||
];
|
||||
|
||||
const EACCOUNTING_ACR_VALUE = 'service:44643EB1-3F76-4C1C-A672-402AE8085934';
|
||||
|
||||
const ALLOWED_PROMPT_VALUES = new Set(['none', 'login', 'consent', 'select_account']);
|
||||
|
||||
export function buildVismaAuthUrl(
|
||||
config: OAuthConfig,
|
||||
options?: { scopes?: string[]; state?: string; acrValues?: string },
|
||||
options?: { scopes?: string[]; state?: string; acrValues?: string; prompt?: string },
|
||||
): string {
|
||||
const promptCandidate = options?.prompt ?? 'select_account';
|
||||
const prompt = ALLOWED_PROMPT_VALUES.has(promptCandidate) ? promptCandidate : 'select_account';
|
||||
|
||||
const params = new URLSearchParams({
|
||||
client_id: config.clientId,
|
||||
redirect_uri: config.redirectUri,
|
||||
response_type: 'code',
|
||||
prompt,
|
||||
acr_values: options?.acrValues ?? EACCOUNTING_ACR_VALUE,
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user