* feat: add option to exclude year-end closing entries in SIE export and related reports * delete docs * fix: allow Chrome's PDF viewer in verifikat document preview The /api/documents/:id/inline route shipped with `object-src 'none'` in its CSP, which blocked Chrome's built-in PDF viewer (it renders inline PDFs via an internal <embed>). Users on Chrome saw "Det här innehållet har blockerats" when expanding a PDF attachment in the bookkeeping view; Firefox (PDF.js) and Edge (own viewer) were unaffected, and JPGs worked because <img> isn't subject to object-src. Drops the CSP for this route to the minimum needed for embeddability: `frame-ancestors 'self'`. X-Content-Type-Options: nosniff plus the fixed Content-Type from the handler already block MIME confusion; X-Frame-Options: SAMEORIGIN + frame-ancestors still block clickjacking. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(auth): add webmail deep link to email confirmation screens Mirrors Stripe's signup UX: after asking the user to verify their email, detect their webmail provider from the domain and show a button that opens the inbox in a new tab. Gmail gets a from:<sender> search pre-populated; Outlook/Yahoo/iCloud/Proton open the inbox directly. Unknown / custom domains fall back to the existing copy. Sender address is configurable via NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM (default noreply@gnubok.se) so white-label installs can match their Supabase Auth SMTP config. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(auth): unblock first-time password set for BankID users with MFA Supabase rejects updateUser({password}) and mfa.unenroll with "AAL2 session is required" whenever a TOTP factor is enrolled. BankID magic-link logins produce AAL1, and middleware skips MFA enforcement for bankid_linked users, so they had no path to AAL2 — leaving them unable to set a backup password or disable MFA without going through the email-recovery escape hatch. - /api/account/password: branch on app_metadata.has_password. First-time set writes via service.auth.admin.updateUserById (no existing credential to protect, AAL2 guard does not apply). Change-password keeps the user-session updateUser so AAL2 still fires for credential rotation. - /mfa/verify: accept a safeReturnTo query param and route there after successful verify, so step-up flows can land back where they came from. - SecuritySettings: detect the AAL2 error from both change-password and mfa.unenroll and redirect through /mfa/verify?returnTo=/settings/account instead of toasting a dead-end error. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Add tests and rounding utility for öre precision in bokslut calculations - Implemented `roundOre` function for rounding SEK amounts to two decimal places, ensuring consistent monetary calculations. - Introduced `ORE_TOLERANCE` constant for comparing rounded amounts, facilitating invariant checks in financial entries. - Created comprehensive tests for `roundOre`, covering typical cases, edge cases, and idempotency. - Added year-end invariants tests to verify database-level guarantees for closing entries, ensuring they balance to the öre and reject discrepancies. - Developed end-to-end tests for the dispositions chain, validating the correctness of calculations across various scenarios. * fix: update PDF rendering to remove Swish QR code generation and set default to disable Swish visibility * fix: enhance security by rejecting data URIs in safeReturnTo function tests * fix: improve rounding logic in roundOre function and add customer_type migration * fix: add customer_type column to customers and enforce CHECK constraint --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
190 lines
6.3 KiB
TypeScript
190 lines
6.3 KiB
TypeScript
import { eventBus } from '@/lib/events/bus'
|
|
import type { CoreEventType } from '@/lib/events/types'
|
|
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
|
import { createLogger } from '@/lib/logger'
|
|
|
|
const log = createLogger('event-log')
|
|
|
|
/**
|
|
* Event types persisted to the event_log table for external automation platforms.
|
|
* Excludes noise events that are always followed by an actionable event.
|
|
*/
|
|
const PERSISTED_EVENT_TYPES: CoreEventType[] = [
|
|
'journal_entry.committed',
|
|
'journal_entry.reversed',
|
|
'journal_entry.corrected',
|
|
'document.uploaded',
|
|
'document.accessed',
|
|
'document.deleted',
|
|
'invoice.created',
|
|
'invoice.sent',
|
|
'credit_note.created',
|
|
'transaction.synced',
|
|
'transaction.categorized',
|
|
'transaction.reconciled',
|
|
'period.locked',
|
|
'period.year_closed',
|
|
'customer.created',
|
|
'supplier.created',
|
|
'receipt.matched',
|
|
'receipt.confirmed',
|
|
'supplier_invoice.registered',
|
|
'supplier_invoice.approved',
|
|
'supplier_invoice.paid',
|
|
'supplier_invoice.credited',
|
|
'invoice.match_confirmed',
|
|
'supplier_invoice.match_confirmed',
|
|
'supplier_invoice.confirmed',
|
|
// MCP telemetry — every tool invocation, tools/list call, and resources/read.
|
|
// Lightweight metadata only; 30-day TTL on event_log bounds the volume.
|
|
'mcp.tool_called',
|
|
'mcp.tools_list_called',
|
|
'mcp.resource_read',
|
|
// Bank connection consent lifecycle — required audit trail per ASVS V16
|
|
// and GDPR Art.30 (records of processing) for PSD2 consent decisions.
|
|
'bank_connection.consent_granted',
|
|
'bank_connection.account_selection_changed',
|
|
'bank_connection.revoked',
|
|
'bank_connection.cash_account_mirror_failed',
|
|
]
|
|
|
|
// Excluded (with reasoning):
|
|
// - journal_entry.drafted: always followed by .committed
|
|
// - receipt.extracted: intermediate AI step; .matched/.confirmed are actionable
|
|
// - supplier_invoice.received: inbox receipt; .confirmed is actionable
|
|
// - supplier_invoice.extracted: intermediate AI step
|
|
|
|
/**
|
|
* Extract the primary entity ID from an event payload.
|
|
*/
|
|
function extractEntityId(payload: Record<string, unknown>): string | null {
|
|
// Try common entity shapes in priority order
|
|
const entityKeys = [
|
|
'entry', 'invoice', 'transaction', 'customer', 'supplier', 'receipt',
|
|
'supplierInvoice', 'creditNote', 'period', 'document', 'inboxItem',
|
|
] as const
|
|
|
|
for (const key of entityKeys) {
|
|
const entity = payload[key]
|
|
if (entity && typeof entity === 'object' && 'id' in entity) {
|
|
const id = (entity as Record<string, unknown>).id
|
|
if (typeof id === 'string') return id
|
|
}
|
|
}
|
|
|
|
// Flat-string ID fields on events that don't carry a full entity object.
|
|
// Bank connection events fall into this category — the connection lives in
|
|
// an extension table, so we record its id directly.
|
|
if (typeof payload.connectionId === 'string') {
|
|
return payload.connectionId
|
|
}
|
|
|
|
// For journal_entry.corrected: use the corrected entry's ID
|
|
if ('corrected' in payload) {
|
|
const corrected = payload.corrected
|
|
if (corrected && typeof corrected === 'object' && 'id' in corrected) {
|
|
const id = (corrected as Record<string, unknown>).id
|
|
if (typeof id === 'string') return id
|
|
}
|
|
}
|
|
|
|
// For journal_entry.reversed: use the reversal entry's ID
|
|
if ('reversalEntry' in payload) {
|
|
const reversalEntry = payload.reversalEntry
|
|
if (reversalEntry && typeof reversalEntry === 'object' && 'id' in reversalEntry) {
|
|
const id = (reversalEntry as Record<string, unknown>).id
|
|
if (typeof id === 'string') return id
|
|
}
|
|
}
|
|
|
|
return null
|
|
}
|
|
|
|
/**
|
|
* Strip userId and companyId from payload (each stored in its own column) and
|
|
* return clean data for the JSONB blob.
|
|
*/
|
|
function stripMetaFields(payload: Record<string, unknown>): Record<string, unknown> {
|
|
const { userId: _userId, companyId: _companyId, ...data } = payload
|
|
return data
|
|
}
|
|
|
|
/**
|
|
* Persist a single event to the event_log table.
|
|
*/
|
|
async function persistEvent(
|
|
eventType: string,
|
|
userId: string,
|
|
companyId: string,
|
|
entityId: string | null,
|
|
data: Record<string, unknown>
|
|
): Promise<void> {
|
|
const supabase = createServiceClientNoCookies()
|
|
|
|
const { error } = await supabase
|
|
.from('event_log')
|
|
.insert({
|
|
user_id: userId,
|
|
company_id: companyId,
|
|
event_type: eventType,
|
|
entity_id: entityId,
|
|
data,
|
|
})
|
|
|
|
if (error) {
|
|
log.error(`Failed to persist event ${eventType}:`, error.message)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Register event log handlers on the event bus.
|
|
* Persists events to the event_log table for external automation platforms.
|
|
* Returns an array of unsubscribe functions.
|
|
*/
|
|
export function registerEventLogHandler(): (() => void)[] {
|
|
return PERSISTED_EVENT_TYPES.map((eventType) =>
|
|
eventBus.on(eventType, async (payload) => {
|
|
try {
|
|
const rawPayload = payload as Record<string, unknown>
|
|
const userId = rawPayload.userId as string
|
|
const companyId = rawPayload.companyId
|
|
|
|
// All persisted event payloads mandate companyId in TypeScript; this guard
|
|
// protects against any caller that bypasses the type system. Writing NULL
|
|
// would make the row invisible to the company_id-scoped SELECT RLS policy.
|
|
if (typeof companyId !== 'string' || companyId.length === 0) {
|
|
log.error(`Event ${eventType} missing companyId; skipping persistence`)
|
|
return
|
|
}
|
|
|
|
// transaction.synced carries an array — batch insert
|
|
if (eventType === 'transaction.synced' && Array.isArray(rawPayload.transactions)) {
|
|
const transactions = rawPayload.transactions as Array<Record<string, unknown>>
|
|
if (transactions.length === 0) return
|
|
|
|
const rows = transactions.map(tx => ({
|
|
user_id: userId,
|
|
company_id: companyId,
|
|
event_type: eventType,
|
|
entity_id: typeof tx.id === 'string' ? tx.id : null,
|
|
data: { transaction: tx },
|
|
}))
|
|
|
|
const supabase = createServiceClientNoCookies()
|
|
const { error } = await supabase.from('event_log').insert(rows)
|
|
if (error) {
|
|
log.error(`Failed to persist batch transaction.synced:`, error.message)
|
|
}
|
|
return
|
|
}
|
|
|
|
const entityId = extractEntityId(rawPayload)
|
|
const data = stripMetaFields(rawPayload)
|
|
await persistEvent(eventType, userId, companyId, entityId, data)
|
|
} catch (err) {
|
|
log.error(`Event log handler error for ${eventType}:`, err)
|
|
}
|
|
})
|
|
)
|
|
}
|