02f94ef631
* 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>
157 lines
4.5 KiB
TypeScript
157 lines
4.5 KiB
TypeScript
/**
|
|
* Minimal Google OAuth 2.0 client for the cloud-backup extension.
|
|
*
|
|
* Scope: `drive.file` — app-created files only, not the user's full Drive.
|
|
* Access type: `offline` — returns a refresh token on first consent.
|
|
* Prompt: `consent` — forces the consent screen so the refresh token is
|
|
* re-issued even if the user has previously authorised the app.
|
|
*/
|
|
|
|
import {
|
|
fetchWithTimeout,
|
|
OAUTH_TIMEOUT_MS,
|
|
OAUTH_REVOKE_TIMEOUT_MS,
|
|
} from '@/lib/http/fetch-with-timeout'
|
|
|
|
const DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive.file'
|
|
const AUTH_ENDPOINT = 'https://accounts.google.com/o/oauth2/v2/auth'
|
|
const TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token'
|
|
const USERINFO_ENDPOINT = 'https://openidconnect.googleapis.com/v1/userinfo'
|
|
|
|
export interface OAuthEnv {
|
|
clientId: string
|
|
clientSecret: string
|
|
redirectUri: string
|
|
}
|
|
|
|
export function getOAuthEnv(origin: string): OAuthEnv {
|
|
const clientId = process.env.GOOGLE_CLIENT_ID
|
|
const clientSecret = process.env.GOOGLE_CLIENT_SECRET
|
|
if (!clientId || !clientSecret) {
|
|
throw new Error(
|
|
'Google OAuth is not configured: set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET'
|
|
)
|
|
}
|
|
return {
|
|
clientId,
|
|
clientSecret,
|
|
redirectUri: `${origin}/api/extensions/ext/cloud-backup/oauth/callback`,
|
|
}
|
|
}
|
|
|
|
export function buildAuthorizationUrl(env: OAuthEnv, state: string): string {
|
|
const params = new URLSearchParams({
|
|
client_id: env.clientId,
|
|
redirect_uri: env.redirectUri,
|
|
response_type: 'code',
|
|
scope: `openid email ${DRIVE_SCOPE}`,
|
|
access_type: 'offline',
|
|
prompt: 'consent',
|
|
include_granted_scopes: 'true',
|
|
state,
|
|
})
|
|
return `${AUTH_ENDPOINT}?${params.toString()}`
|
|
}
|
|
|
|
export interface TokenExchangeResult {
|
|
access_token: string
|
|
refresh_token: string
|
|
expires_in: number
|
|
id_token?: string
|
|
}
|
|
|
|
export async function exchangeCodeForTokens(
|
|
env: OAuthEnv,
|
|
code: string
|
|
): Promise<TokenExchangeResult> {
|
|
const body = new URLSearchParams({
|
|
code,
|
|
client_id: env.clientId,
|
|
client_secret: env.clientSecret,
|
|
redirect_uri: env.redirectUri,
|
|
grant_type: 'authorization_code',
|
|
})
|
|
const res = await fetchWithTimeout(
|
|
TOKEN_ENDPOINT,
|
|
{
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
body: body.toString(),
|
|
},
|
|
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Google token exchange' },
|
|
)
|
|
if (!res.ok) {
|
|
const errText = await res.text()
|
|
throw new Error(`Google token exchange failed: ${res.status} ${errText}`)
|
|
}
|
|
const json = (await res.json()) as TokenExchangeResult
|
|
if (!json.refresh_token) {
|
|
throw new Error(
|
|
'No refresh token returned — Google only issues one on first consent. ' +
|
|
'Revoke the app at myaccount.google.com/permissions and try again.'
|
|
)
|
|
}
|
|
return json
|
|
}
|
|
|
|
export interface AccessTokenResult {
|
|
access_token: string
|
|
expires_in: number
|
|
}
|
|
|
|
export async function refreshAccessToken(
|
|
env: OAuthEnv,
|
|
refreshToken: string
|
|
): Promise<AccessTokenResult> {
|
|
const body = new URLSearchParams({
|
|
client_id: env.clientId,
|
|
client_secret: env.clientSecret,
|
|
refresh_token: refreshToken,
|
|
grant_type: 'refresh_token',
|
|
})
|
|
const res = await fetchWithTimeout(
|
|
TOKEN_ENDPOINT,
|
|
{
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
body: body.toString(),
|
|
},
|
|
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Google token refresh' },
|
|
)
|
|
if (!res.ok) {
|
|
const errText = await res.text()
|
|
throw new Error(`Google token refresh failed: ${res.status} ${errText}`)
|
|
}
|
|
return (await res.json()) as AccessTokenResult
|
|
}
|
|
|
|
export async function revokeToken(token: string): Promise<void> {
|
|
try {
|
|
await fetchWithTimeout(
|
|
`https://oauth2.googleapis.com/revoke?token=${encodeURIComponent(token)}`,
|
|
{
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
},
|
|
{ timeoutMs: OAUTH_REVOKE_TIMEOUT_MS, description: 'Google token revoke' },
|
|
)
|
|
} catch {
|
|
// Best-effort revoke: swallow timeouts and network errors so disconnect flows still complete locally.
|
|
}
|
|
}
|
|
|
|
export async function fetchUserEmail(accessToken: string): Promise<string> {
|
|
const res = await fetchWithTimeout(
|
|
USERINFO_ENDPOINT,
|
|
{
|
|
headers: { Authorization: `Bearer ${accessToken}` },
|
|
},
|
|
{ timeoutMs: OAUTH_TIMEOUT_MS, description: 'Google userinfo fetch' },
|
|
)
|
|
if (!res.ok) {
|
|
throw new Error(`Failed to fetch Google user info: ${res.status}`)
|
|
}
|
|
const json = (await res.json()) as { email?: string }
|
|
return json.email || 'unknown@google'
|
|
}
|