Files
accounted/extensions/general/skatteverket/lib/oauth.ts
T
MattssonandClaude Opus 4.7 02f94ef631 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>
2026-04-22 18:14:01 +02:00

154 lines
4.1 KiB
TypeScript

import type { SkatteverketTokens } from '../types'
import {
fetchWithTimeout,
OAUTH_TIMEOUT_MS,
SKATTEVERKET_EXCHANGE_TIMEOUT_MS,
} from '@/lib/http/fetch-with-timeout'
/**
* Skatteverket OAuth2 helpers for the `per` (BankID) flow.
*
* Endpoints:
* Authorize: GET {base}/authorize
* Token: POST {base}/token
*
* The `per` flow is user-facing BankID authentication.
* No mTLS required (unlike the `org` flow).
*/
const DEFAULT_OAUTH_BASE_URL = 'https://peroauth2.test.skatteverket.se/oauth2/v1/per'
const DEFAULT_SCOPES = 'momsdeklaration inkforetag ska skahmst'
function getOAuthBaseUrl(): string {
return process.env.SKATTEVERKET_OAUTH_BASE_URL || DEFAULT_OAUTH_BASE_URL
}
function getClientId(): string {
const id = process.env.SKATTEVERKET_OAUTH2_CLIENT_ID
if (!id) throw new Error('SKATTEVERKET_OAUTH2_CLIENT_ID is required')
return id
}
function getClientSecret(): string {
const secret = process.env.SKATTEVERKET_OAUTH2_CLIENT_SECRET
if (!secret) throw new Error('SKATTEVERKET_OAUTH2_CLIENT_SECRET is required')
return secret
}
/**
* Build the Skatteverket OAuth2 authorization URL.
* User is redirected here to authenticate with BankID.
*/
export function buildAuthorizeUrl(
redirectUri: string,
state: string,
scope?: string
): string {
const base = getOAuthBaseUrl()
const params = new URLSearchParams({
client_id: getClientId(),
response_type: 'code',
state,
redirect_uri: redirectUri,
scope: scope || DEFAULT_SCOPES,
})
return `${base}/authorize?${params.toString()}`
}
/**
* Exchange an authorization code for tokens.
* Must be called immediately upon receiving the callback — code expires in 5 minutes.
*/
export async function exchangeCodeForTokens(
code: string,
redirectUri: string
): Promise<SkatteverketTokens> {
const base = getOAuthBaseUrl()
const body = new URLSearchParams({
grant_type: 'authorization_code',
client_id: getClientId(),
client_secret: getClientSecret(),
redirect_uri: redirectUri,
code,
})
const response = await fetchWithTimeout(
`${base}/token`,
{
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
body: body.toString(),
},
{
timeoutMs: SKATTEVERKET_EXCHANGE_TIMEOUT_MS,
description: 'Skatteverket token exchange',
},
)
if (!response.ok) {
const text = await response.text()
throw new Error(`Skatteverket token exchange failed (${response.status}): ${text}`)
}
const data = await response.json()
return {
access_token: data.access_token,
refresh_token: data.refresh_token ?? null,
expires_at: Date.now() + (data.expires_in ?? 3600) * 1000,
refresh_count: 0,
scope: data.scope ?? DEFAULT_SCOPES,
}
}
/**
* Refresh an access token using a stored refresh token.
*
* The `per` flow supports up to 10 refreshes per session.
* Each refresh returns a NEW refresh_token that must be stored.
* Refresh tokens are valid for 65 minutes.
*/
export async function refreshAccessToken(
refreshToken: string,
previousRefreshCount: number
): Promise<SkatteverketTokens> {
const base = getOAuthBaseUrl()
const body = new URLSearchParams({
grant_type: 'refresh_token',
client_id: getClientId(),
client_secret: getClientSecret(),
refresh_token: refreshToken,
})
const response = await fetchWithTimeout(
`${base}/token`,
{
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
body: body.toString(),
},
{
timeoutMs: OAUTH_TIMEOUT_MS,
description: 'Skatteverket token refresh',
},
)
if (!response.ok) {
const text = await response.text()
throw new Error(`Skatteverket token refresh failed (${response.status}): ${text}`)
}
const data = await response.json()
return {
access_token: data.access_token,
// Each refresh returns a new refresh_token — must be stored
refresh_token: data.refresh_token ?? null,
expires_at: Date.now() + (data.expires_in ?? 3600) * 1000,
refresh_count: previousRefreshCount + 1,
scope: data.scope ?? '',
}
}