fix: OAuth callback redirect and timeout resilience (#43)
* fix: include reversed entries in all reports (general ledger, trial balance, VAT, SIE, NE, INK2) Reversed entries (storno) must appear alongside their original posted entries in reports for a complete audit trail. Previously, filtering by status='posted' excluded them, causing discrepancies when corrections had been made. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: semi-manual invoice payment booking with editable journal lines When marking an invoice as paid, users now see a dialog where they can: - Choose which bank/cash account the payment goes to (1910, 1920, 1930, etc.) - Review and edit the proposed journal entry lines before committing - The happy path remains fast — lines are pre-filled correctly Implementation: - Pure proposePaymentLines() function for line computation (accrual + cash) - PaymentBookingDialog with AccountCombobox, balance validation, date picker - API accepts optional custom lines, falls back to auto-generation without them - 18 tests (8 unit + 10 API) all passing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address Greptile review — validation fallback, balance check, error handling - P1: Return 400 on invalid body instead of silently falling back to auto-generated lines (split JSON parse from schema validation) - P1: Add server-side balance check for custom lines before committing (debit must equal credit, totalDebit > 0) - P2: Wrap PaymentBookingDialog init() in try/catch with toast on failure and auto-close instead of silent empty state - Add 2 new tests: unbalanced lines → 400, invalid schema → 400 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: OAuth callback redirect for local dev and timeout resilience - Pass redirectUri dynamically from NEXT_PUBLIC_APP_URL so OAuth callbacks work on localhost (not just production) - Encode consentId/provider in OAuth state (base64url JSON) so the callback doesn't depend on session storage - Add skipAuth flag to extension API routes for OAuth callbacks (external provider redirects have no user session cookie) - Wrap AbortError in descriptive timeout messages in arcim-client - Make preview endpoint resilient to partial failures (company info and SIE fetch are individually non-blocking) - Simplify login page (remove unused magic link auth mode) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: create journal entry before marking invoice as paid Move journal entry creation before the invoice status update so that if accounting fails, the invoice is not permanently marked paid without a corresponding entry. Previously the error was silently swallowed. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: update mark-paid tests for journal-first ordering Reorder mock queue to match new flow (settings before update), update failure test to expect 500 instead of silent success, add try-catch with proper error response in route handler. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
8976cd812d
commit
bac49b6ee6
@@ -97,8 +97,16 @@ export const arcimMigrationExtension: Extension = {
|
||||
// Generate OTC for OAuth flow
|
||||
const otc = await generateOtc(consent.id)
|
||||
|
||||
// Get OAuth URL from Arcim (redirect URI is configured server-side in the gateway)
|
||||
const { url } = await getAuthUrl(provider, otc.code)
|
||||
// Build the OAuth callback URL using the current app URL (localhost in dev, production in prod)
|
||||
const appUrl = process.env.NEXT_PUBLIC_APP_URL || ''
|
||||
const callbackUrl = `${appUrl}/api/extensions/ext/arcim-migration/callback`
|
||||
|
||||
// Encode consentId + provider in state so the callback doesn't depend on session storage
|
||||
const statePayload = JSON.stringify({ otc: otc.code, consentId: consent.id, provider })
|
||||
const stateEncoded = Buffer.from(statePayload).toString('base64url')
|
||||
|
||||
// Pass callbackUrl as redirectUri so Fortnox redirects here (works for localhost and production)
|
||||
const { url } = await getAuthUrl(provider, stateEncoded, callbackUrl)
|
||||
|
||||
return NextResponse.json({
|
||||
consentId: consent.id,
|
||||
@@ -181,37 +189,63 @@ export const arcimMigrationExtension: Extension = {
|
||||
},
|
||||
|
||||
// ── OAuth callback ────────────────────────────────────────────
|
||||
// This handler is called by the OAuth provider redirect. It does NOT
|
||||
// require user auth — the request comes from the provider, not the user's
|
||||
// browser session. Authentication is validated via the OTC code + consent.
|
||||
// The 'skipAuth' flag is checked by the extension dispatch route.
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/callback',
|
||||
skipAuth: true,
|
||||
handler: async (request: Request, ctx?: ExtensionContext) => {
|
||||
const log = ctx?.log ?? console
|
||||
const url = new URL(request.url)
|
||||
const code = url.searchParams.get('code')
|
||||
const state = url.searchParams.get('state') // OTC code
|
||||
const stateRaw = url.searchParams.get('state')
|
||||
|
||||
if (!code || !state) {
|
||||
if (!code || !stateRaw) {
|
||||
return NextResponse.json({ error: 'Missing code or state' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
// The state is the OTC code, and the code is the OAuth auth code
|
||||
// Exchange with the Arcim gateway
|
||||
const consentId = ctx?.settings
|
||||
? await ctx.settings.get<string>('consent_id')
|
||||
: null
|
||||
const provider = ctx?.settings
|
||||
? await ctx.settings.get<ArcimProvider>('provider')
|
||||
: null
|
||||
// Decode state — supports both new format (base64url JSON with consentId/provider)
|
||||
// and legacy format (plain OTC code string)
|
||||
let consentId: string | null = null
|
||||
let provider: ArcimProvider | null = null
|
||||
let otcCode: string = stateRaw
|
||||
|
||||
try {
|
||||
const decoded = JSON.parse(Buffer.from(stateRaw, 'base64url').toString())
|
||||
if (decoded.consentId && decoded.provider && decoded.otc) {
|
||||
consentId = decoded.consentId
|
||||
provider = decoded.provider as ArcimProvider
|
||||
otcCode = decoded.otc
|
||||
}
|
||||
} catch {
|
||||
// Legacy: state is just the OTC code — fall back to ctx.settings
|
||||
}
|
||||
|
||||
// Fall back to session-based settings if state didn't contain the data
|
||||
if (!consentId || !provider) {
|
||||
consentId = ctx?.settings
|
||||
? await ctx.settings.get<string>('consent_id')
|
||||
: null
|
||||
provider = ctx?.settings
|
||||
? await ctx.settings.get<ArcimProvider>('provider')
|
||||
: null
|
||||
}
|
||||
|
||||
if (!consentId || !provider) {
|
||||
return NextResponse.json({ error: 'No active migration session' }, { status: 400 })
|
||||
}
|
||||
|
||||
await exchangeAuthToken(consentId, provider, state, code)
|
||||
// The redirectUri used for the token exchange must match the one used in the auth URL
|
||||
const appUrl = process.env.NEXT_PUBLIC_APP_URL || ''
|
||||
const redirectUri = `${appUrl}/api/extensions/ext/arcim-migration/callback`
|
||||
|
||||
await exchangeAuthToken(consentId, provider, otcCode, code, redirectUri)
|
||||
|
||||
// Redirect to import page with success
|
||||
const appUrl = process.env.NEXT_PUBLIC_APP_URL || ''
|
||||
return NextResponse.redirect(`${appUrl}/import?migration=connected&consentId=${consentId}`)
|
||||
} catch (error) {
|
||||
log.error('OAuth callback error:', error)
|
||||
@@ -251,11 +285,16 @@ export const arcimMigrationExtension: Extension = {
|
||||
)
|
||||
}
|
||||
|
||||
// Fetch company info for preview
|
||||
const companyInfo = await fetchCompanyInfo(consentId)
|
||||
const mapped = companyInfo ? mapCompanyInfo(companyInfo) : null
|
||||
// Fetch company info for preview (non-blocking — continue if it fails)
|
||||
let mapped = null
|
||||
try {
|
||||
const companyInfo = await fetchCompanyInfo(consentId)
|
||||
mapped = companyInfo ? mapCompanyInfo(companyInfo) : null
|
||||
} catch (err) {
|
||||
log.info('Company info fetch failed:', err instanceof Error ? err.message : String(err))
|
||||
}
|
||||
|
||||
// Try to fetch SIE stats
|
||||
// Try to fetch SIE stats (non-blocking — continue if it fails)
|
||||
let sieAvailable = false
|
||||
let sieStats: { accountCount: number; transactionCount: number; fiscalYears: number[] } | null = null
|
||||
|
||||
|
||||
@@ -38,15 +38,26 @@ async function request<T>(
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
'Authorization': `Bearer ${getApiKey()}`,
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers,
|
||||
},
|
||||
}).finally(() => clearTimeout(timer))
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
...options,
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
'Authorization': `Bearer ${getApiKey()}`,
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
clearTimeout(timer)
|
||||
if (err instanceof DOMException || (err instanceof Error && err.name === 'AbortError')) {
|
||||
throw new Error(`Arcim API timeout after ${Math.round(timeoutMs / 1000)}s: ${path}`)
|
||||
}
|
||||
throw err
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const body = await response.text().catch(() => '')
|
||||
@@ -92,10 +103,12 @@ export async function deleteConsent(consentId: string): Promise<void> {
|
||||
|
||||
export async function getAuthUrl(
|
||||
provider: ArcimProvider,
|
||||
state?: string
|
||||
state?: string,
|
||||
redirectUri?: string
|
||||
): Promise<{ url: string }> {
|
||||
const params = new URLSearchParams()
|
||||
if (state) params.set('state', state)
|
||||
if (redirectUri) params.set('redirectUri', redirectUri)
|
||||
const qs = params.toString()
|
||||
return request<{ url: string }>(`/api/v1/auth/${provider}/url${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
@@ -104,7 +117,8 @@ export async function exchangeAuthToken(
|
||||
consentId: string,
|
||||
provider: ArcimProvider,
|
||||
otcCode: string,
|
||||
oauthCode: string
|
||||
oauthCode: string,
|
||||
redirectUri?: string
|
||||
): Promise<{ success: boolean; consentId: string }> {
|
||||
return request(`/api/v1/auth/${provider}/callback`, {
|
||||
method: 'POST',
|
||||
@@ -112,6 +126,7 @@ export async function exchangeAuthToken(
|
||||
code: oauthCode,
|
||||
consentId,
|
||||
otcCode,
|
||||
...(redirectUri ? { redirectUri } : {}),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user