Fix/critical issues (#351)

* fix: add 15s timeout to accounting provider HTTP clients

Node's built-in fetch has no default timeout, so a stalled provider
could hold a serverless worker open for many minutes — worse with
withRetry (6x on Fortnox, 3x on others) and getPaginated stacking
across pages.

Wrap each fetch() in the Fortnox, Visma, Bokio, Briox, and Björn
Lundén clients with signal: AbortSignal.timeout(15_000), and treat
TimeoutError/AbortError as retryable so a single stalled attempt
retries cleanly instead of hanging the request.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: add timeouts to OAuth token endpoints

Wrap every OAuth2 token exchange, refresh, and revoke POST in an
AbortController via a new fetchWithTimeout helper. Without this, a
hung provider endpoint holds the request thread indefinitely — worst
case being Skatteverket, where refreshAccessToken sits on the hot
path of every bookkeeping action and exchangeCodeForTokens races the
5-minute BankID auth-code TTL.

On timeout, the Skatteverket OAuth callback now redirects to
/reports?tab=vat-declaration with a Swedish retry message instead
of leaving the user stranded on the callback URL.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: close RLS escalation on membership and settings tables

Any authenticated user who was a member (including viewer) could issue a
direct PostgREST PATCH against company_members and promote themselves to
owner, bypassing the app-layer requireWritePermission guard entirely.
Reproduced on prod, then verified the fix on staging.

Tighten INSERT/UPDATE/DELETE policies on company_members, team_members,
api_keys, company_invitations, team_invitations, companies, teams, and
company_settings to require the caller to hold role IN ('owner','admin')
in the target company/team. Role check is wrapped in SECURITY DEFINER
helpers (user_is_company_admin, user_is_team_admin, user_role_in_company)
to avoid RLS recursion when a policy on company_members references
company_members in its subquery.

Add a BEFORE UPDATE trigger on company_members that rejects any role
change unless the caller already holds role='owner', so admins cannot
mint further owners even though they can otherwise write.

Legitimate write paths are unaffected: company creation goes through the
create_company_with_owner SECURITY DEFINER RPC, invite acceptance uses
the service role, and team->company membership syncs via SECURITY
DEFINER triggers. All bypass RLS.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(migrations): resolve duplicate schema_migrations version 20260421160000

Two migration files shared timestamp 20260421160000 on main
(booking_template_usage.sql and opening_balances_rpc.sql), causing
supabase_migrations.schema_migrations PK collisions on any fresh CI run:

  duplicate key value violates unique constraint "schema_migrations_pkey"
  Key (version)=(20260421160000) already exists.

Bump opening_balances_rpc.sql to 20260421160500. booking_template_usage
keeps 20260421160000 because its table already exists on prod; the
renamed file has an idempotent CREATE OR REPLACE FUNCTION body and has
not yet been deployed to prod, so moving its version is free.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(migrations): make booking_template_usage migration idempotent

The table already exists on prod (applied out-of-band) but prod's
schema_migrations does not track version 20260421160000, so the next
PR-driven deploy would re-run this migration and fail on
`CREATE TABLE public.booking_template_usage` with a duplicate-relation
error.

Add IF NOT EXISTS to CREATE TABLE and CREATE INDEX, and DROP POLICY
IF EXISTS before each CREATE POLICY. No functional change on fresh
databases; prod just silently no-ops the table/index creates and
re-declares policies without dropping-then-missing them.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: implement isTimeoutError utility and enforce role restrictions on company_members insert

* fix: implement fallback for user_id in commit_journal_entry function when auth.uid() is NULL

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-04-22 18:14:01 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent e13a450e21
commit 02f94ef631
20 changed files with 776 additions and 114 deletions
+4
View File
@@ -86,6 +86,10 @@ const ERROR_PATTERN_MAP: [RegExp, string | null][] = [
/Entry date .+ is outside fiscal period/i,
'Datumet ligger utanför det valda räkenskapsåret.',
],
[
/timed out after \d+m?s/i,
'Anslutningen mot tjänsten tog för lång tid. Försök igen.',
],
]
/**
@@ -0,0 +1,124 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { fetchWithTimeout, TimeoutError } from '../fetch-with-timeout'
describe('fetchWithTimeout', () => {
const originalFetch = globalThis.fetch
beforeEach(() => {
vi.resetAllMocks()
})
afterEach(() => {
globalThis.fetch = originalFetch
})
it('returns the response when fetch resolves before the deadline', async () => {
const mockResponse = new Response('ok', { status: 200 })
globalThis.fetch = vi.fn().mockResolvedValue(mockResponse)
const result = await fetchWithTimeout(
'https://example.test/',
{ method: 'POST' },
{ timeoutMs: 1000, description: 'test fetch' },
)
expect(result).toBe(mockResponse)
expect(globalThis.fetch).toHaveBeenCalledOnce()
})
it('throws TimeoutError when fetch hangs past the timeout', async () => {
globalThis.fetch = vi.fn().mockImplementation((_url, init?: RequestInit) => {
return new Promise((_resolve, reject) => {
const signal = init?.signal
if (!signal) return
signal.addEventListener('abort', () => {
const reason = (signal as AbortSignal & { reason?: unknown }).reason
const err = new Error('aborted')
err.name =
reason instanceof DOMException ? reason.name : 'AbortError'
reject(err)
})
})
})
const start = Date.now()
await expect(
fetchWithTimeout(
'https://example.test/',
{ method: 'POST' },
{ timeoutMs: 50, description: 'slow fetch' },
),
).rejects.toBeInstanceOf(TimeoutError)
const elapsed = Date.now() - start
expect(elapsed).toBeGreaterThanOrEqual(40)
expect(elapsed).toBeLessThan(1000)
})
it('includes the description and timeout ms in the error message', async () => {
globalThis.fetch = vi.fn().mockImplementation((_url, init?: RequestInit) => {
return new Promise((_resolve, reject) => {
const signal = init?.signal
signal?.addEventListener('abort', () => {
const err = new Error('aborted')
err.name = 'TimeoutError'
reject(err)
})
})
})
try {
await fetchWithTimeout(
'https://example.test/',
{ method: 'POST' },
{ timeoutMs: 50, description: 'Fortnox token exchange' },
)
expect.fail('expected TimeoutError to be thrown')
} catch (err) {
expect(err).toBeInstanceOf(TimeoutError)
expect((err as Error).name).toBe('TimeoutError')
expect((err as Error).message).toContain('Fortnox token exchange')
expect((err as Error).message).toContain('50')
}
})
it('propagates non-timeout errors unchanged', async () => {
const networkError = new TypeError('fetch failed')
globalThis.fetch = vi.fn().mockRejectedValue(networkError)
await expect(
fetchWithTimeout(
'https://example.test/',
{ method: 'POST' },
{ timeoutMs: 1000, description: 'test fetch' },
),
).rejects.toBe(networkError)
})
it('honours an external AbortSignal without labelling it a timeout', async () => {
const externalController = new AbortController()
globalThis.fetch = vi.fn().mockImplementation((_url, init?: RequestInit) => {
return new Promise((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
const err = new Error('aborted by caller')
err.name = 'AbortError'
reject(err)
})
})
})
const promise = fetchWithTimeout(
'https://example.test/',
{ method: 'POST', signal: externalController.signal },
{ timeoutMs: 10_000, description: 'caller-cancelable fetch' },
)
externalController.abort()
await expect(promise).rejects.toSatisfy(
(err: unknown) =>
err instanceof Error &&
!(err instanceof TimeoutError) &&
err.name === 'AbortError',
)
})
})
+54
View File
@@ -0,0 +1,54 @@
/**
* Thin `fetch` wrapper that aborts after a deadline.
*
* Used by OAuth token endpoints where a hung provider would otherwise hold
* the request thread indefinitely. The Skatteverket callback handler also
* relies on `TimeoutError` to distinguish a hung token exchange (where the
* 5-minute BankID auth code may expire mid-call) from other failures.
*/
export class TimeoutError extends Error {
readonly name = 'TimeoutError'
}
export function isTimeoutError(error: unknown): boolean {
return (
error instanceof Error &&
(error.name === 'TimeoutError' || error.name === 'AbortError')
)
}
export const OAUTH_TIMEOUT_MS = 10_000
export const OAUTH_REVOKE_TIMEOUT_MS = 5_000
export const SKATTEVERKET_EXCHANGE_TIMEOUT_MS = 8_000
interface FetchWithTimeoutOptions {
timeoutMs: number
description: string
}
export async function fetchWithTimeout(
input: RequestInfo | URL,
init: RequestInit,
options: FetchWithTimeoutOptions,
): Promise<Response> {
const { timeoutMs, description } = options
const timeoutSignal = AbortSignal.timeout(timeoutMs)
const signal = init.signal
? AbortSignal.any([init.signal, timeoutSignal])
: timeoutSignal
try {
return await fetch(input, { ...init, signal })
} catch (err) {
if (
timeoutSignal.aborted &&
err instanceof Error &&
(err.name === 'TimeoutError' || err.name === 'AbortError')
) {
throw new TimeoutError(`${description} timed out after ${timeoutMs}ms`)
}
throw err
}
}
+5
View File
@@ -1,6 +1,9 @@
import { TokenBucketRateLimiter } from '../rate-limiter';
import { withRetry } from '../retry';
import { BL_BASE_URL, BL_RATE_LIMIT } from './config';
import { isTimeoutError } from '@/lib/http/fetch-with-timeout';
const FETCH_TIMEOUT_MS = 15_000;
export class BjornLundenApiError extends Error {
constructor(
@@ -14,6 +17,7 @@ export class BjornLundenApiError extends Error {
}
function isRetryableError(error: unknown): boolean {
if (isTimeoutError(error)) return true;
if (error instanceof BjornLundenApiError) {
if (error.statusCode === 401 || error.statusCode === 403 || error.statusCode === 404) {
return false;
@@ -50,6 +54,7 @@ export class BjornLundenClient {
'User-Key': userKey,
Accept: 'application/json',
},
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!response.ok) {
+18 -10
View File
@@ -1,4 +1,8 @@
import type { TokenResponse } from '../types';
import {
fetchWithTimeout,
OAUTH_TIMEOUT_MS,
} from '@/lib/http/fetch-with-timeout';
const BL_AUTH_URL = 'https://apigateway.blinfo.se/auth/oauth/v2/token';
@@ -6,17 +10,21 @@ export async function fetchBjornLundenToken(
clientId: string,
clientSecret: string,
): Promise<TokenResponse> {
const response = await fetch(BL_AUTH_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
const response = await fetchWithTimeout(
BL_AUTH_URL,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret,
}).toString(),
},
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret,
}).toString(),
});
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Björn Lundén token request' },
);
if (!response.ok) {
const body = await response.text().catch(() => '');
+5
View File
@@ -2,9 +2,12 @@ import { TokenBucketRateLimiter } from '../rate-limiter';
import { withRetry } from '../retry';
import { BOKIO_BASE_URL, BOKIO_RATE_LIMIT } from './config';
import { createLogger } from '@/lib/logger';
import { isTimeoutError } from '@/lib/http/fetch-with-timeout';
const log = createLogger('bokio-client');
const FETCH_TIMEOUT_MS = 15_000;
export class BokioApiError extends Error {
constructor(
message: string,
@@ -17,6 +20,7 @@ export class BokioApiError extends Error {
}
function isRetryableError(error: unknown): boolean {
if (isTimeoutError(error)) return true;
if (error instanceof BokioApiError) {
if (error.statusCode === 401 || error.statusCode === 403 || error.statusCode === 404) {
return false;
@@ -53,6 +57,7 @@ export class BokioClient {
Authorization: `Bearer ${accessToken}`,
Accept: 'application/json',
},
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!response.ok) {
+5
View File
@@ -1,6 +1,9 @@
import { TokenBucketRateLimiter } from '../rate-limiter';
import { withRetry } from '../retry';
import { BRIOX_BASE_URL, BRIOX_RATE_LIMIT } from './config';
import { isTimeoutError } from '@/lib/http/fetch-with-timeout';
const FETCH_TIMEOUT_MS = 15_000;
export class BrioxApiError extends Error {
constructor(
@@ -14,6 +17,7 @@ export class BrioxApiError extends Error {
}
function isRetryableError(error: unknown): boolean {
if (isTimeoutError(error)) return true;
if (error instanceof BrioxApiError) {
if (error.statusCode === 401 || error.statusCode === 403 || error.statusCode === 404) {
return false;
@@ -53,6 +57,7 @@ export class BrioxClient {
Accept: 'application/json',
'Content-Type': 'application/json',
},
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!response.ok) {
+22 -10
View File
@@ -1,5 +1,9 @@
import { BRIOX_TOKEN_URL, BRIOX_REFRESH_URL } from './config';
import type { TokenResponse } from '../types';
import {
fetchWithTimeout,
OAUTH_TIMEOUT_MS,
} from '@/lib/http/fetch-with-timeout';
interface BrioxTokenData {
access_token: string;
@@ -29,12 +33,16 @@ export async function exchangeBrioxCode(
): Promise<TokenResponse> {
const url = `${BRIOX_TOKEN_URL}?clientid=${encodeURIComponent(clientId)}&token=${encodeURIComponent(applicationToken)}`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
const response = await fetchWithTimeout(
url,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
},
});
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Briox token exchange' },
);
if (!response.ok) {
const body = await response.text().catch(() => '');
@@ -51,12 +59,16 @@ export async function refreshBrioxToken(
): Promise<TokenResponse> {
const url = `${BRIOX_REFRESH_URL}?refreshtoken=${encodeURIComponent(refreshToken)}&token=${encodeURIComponent(refreshToken)}`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
const response = await fetchWithTimeout(
url,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
},
});
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Briox token refresh' },
);
if (!response.ok) {
const body = await response.text().catch(() => '');
+6
View File
@@ -1,6 +1,9 @@
import { TokenBucketRateLimiter } from '../rate-limiter';
import { withRetry } from '../retry';
import { FORTNOX_BASE_URL, FORTNOX_RATE_LIMIT } from './config';
import { isTimeoutError } from '@/lib/http/fetch-with-timeout';
const FETCH_TIMEOUT_MS = 15_000;
export class FortnoxApiError extends Error {
constructor(
@@ -15,6 +18,7 @@ export class FortnoxApiError extends Error {
}
function isRetryableError(error: unknown): boolean {
if (isTimeoutError(error)) return true;
if (error instanceof FortnoxApiError) {
if (error.statusCode === 401 || error.statusCode === 403 || error.statusCode === 404) {
return false;
@@ -44,6 +48,7 @@ export class FortnoxClient {
Accept: 'application/json',
'Content-Type': 'application/json',
},
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!response.ok) {
@@ -87,6 +92,7 @@ export class FortnoxClient {
headers: {
Authorization: `Bearer ${accessToken}`,
},
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!response.ok) {
+48 -31
View File
@@ -1,5 +1,10 @@
import { FORTNOX_AUTH_URL, FORTNOX_TOKEN_URL } from './config';
import type { OAuthConfig, TokenResponse } from '../types';
import {
fetchWithTimeout,
OAUTH_TIMEOUT_MS,
OAUTH_REVOKE_TIMEOUT_MS,
} from '@/lib/http/fetch-with-timeout';
const DEFAULT_SCOPES = [
'companyinformation',
@@ -40,18 +45,22 @@ export async function exchangeFortnoxCode(
config: OAuthConfig,
code: string,
): Promise<TokenResponse> {
const response = await fetch(FORTNOX_TOKEN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: basicAuthHeader(config),
const response = await fetchWithTimeout(
FORTNOX_TOKEN_URL,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: basicAuthHeader(config),
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: config.redirectUri,
}).toString(),
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: config.redirectUri,
}).toString(),
});
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Fortnox token exchange' },
);
if (!response.ok) {
const body = await response.text().catch(() => '');
@@ -65,17 +74,21 @@ export async function refreshFortnoxToken(
config: OAuthConfig,
refreshToken: string,
): Promise<TokenResponse> {
const response = await fetch(FORTNOX_TOKEN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: basicAuthHeader(config),
const response = await fetchWithTimeout(
FORTNOX_TOKEN_URL,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: basicAuthHeader(config),
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
}).toString(),
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
}).toString(),
});
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Fortnox token refresh' },
);
if (!response.ok) {
const body = await response.text().catch(() => '');
@@ -89,17 +102,21 @@ export async function revokeFortnoxToken(
config: OAuthConfig,
refreshToken: string,
): Promise<boolean> {
const response = await fetch(FORTNOX_TOKEN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: basicAuthHeader(config),
const response = await fetchWithTimeout(
FORTNOX_TOKEN_URL,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: basicAuthHeader(config),
},
body: new URLSearchParams({
token: refreshToken,
token_type_hint: 'refresh_token',
}).toString(),
},
body: new URLSearchParams({
token: refreshToken,
token_type_hint: 'refresh_token',
}).toString(),
});
{ timeoutMs: OAUTH_REVOKE_TIMEOUT_MS, description: 'Fortnox token revoke' },
);
return response.ok;
}
+5
View File
@@ -1,6 +1,9 @@
import { TokenBucketRateLimiter } from '../rate-limiter';
import { withRetry } from '../retry';
import { VISMA_BASE_URL, VISMA_RATE_LIMIT } from './config';
import { isTimeoutError } from '@/lib/http/fetch-with-timeout';
const FETCH_TIMEOUT_MS = 15_000;
export class VismaApiError extends Error {
constructor(
@@ -14,6 +17,7 @@ export class VismaApiError extends Error {
}
function isRetryableError(error: unknown): boolean {
if (isTimeoutError(error)) return true;
if (error instanceof VismaApiError) {
if (error.statusCode === 401 || error.statusCode === 403 || error.statusCode === 404) {
return false;
@@ -48,6 +52,7 @@ export class VismaClient {
Accept: 'application/json',
'Content-Type': 'application/json',
},
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!response.ok) {
+48 -31
View File
@@ -1,5 +1,10 @@
import { VISMA_AUTH_URL, VISMA_TOKEN_URL, VISMA_REVOKE_URL } from './config';
import type { OAuthConfig, TokenResponse } from '../types';
import {
fetchWithTimeout,
OAUTH_TIMEOUT_MS,
OAUTH_REVOKE_TIMEOUT_MS,
} from '@/lib/http/fetch-with-timeout';
const DEFAULT_SCOPES = [
'ea:api',
@@ -41,18 +46,22 @@ export async function exchangeVismaCode(
config: OAuthConfig,
code: string,
): Promise<TokenResponse> {
const response = await fetch(VISMA_TOKEN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: basicAuthHeader(config),
const response = await fetchWithTimeout(
VISMA_TOKEN_URL,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: basicAuthHeader(config),
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: config.redirectUri,
}).toString(),
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: config.redirectUri,
}).toString(),
});
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Visma token exchange' },
);
if (!response.ok) {
const body = await response.text().catch(() => '');
@@ -66,17 +75,21 @@ export async function refreshVismaToken(
config: OAuthConfig,
refreshToken: string,
): Promise<TokenResponse> {
const response = await fetch(VISMA_TOKEN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: basicAuthHeader(config),
const response = await fetchWithTimeout(
VISMA_TOKEN_URL,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: basicAuthHeader(config),
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
}).toString(),
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
}).toString(),
});
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Visma token refresh' },
);
if (!response.ok) {
const body = await response.text().catch(() => '');
@@ -90,17 +103,21 @@ export async function revokeVismaToken(
config: OAuthConfig,
refreshToken: string,
): Promise<boolean> {
const response = await fetch(VISMA_REVOKE_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: basicAuthHeader(config),
const response = await fetchWithTimeout(
VISMA_REVOKE_URL,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: basicAuthHeader(config),
},
body: new URLSearchParams({
token: refreshToken,
token_type_hint: 'refresh_token',
}).toString(),
},
body: new URLSearchParams({
token: refreshToken,
token_type_hint: 'refresh_token',
}).toString(),
});
{ timeoutMs: OAUTH_REVOKE_TIMEOUT_MS, description: 'Visma token revoke' },
);
return response.ok;
}