* fix(providers): name the real Björn Lundén connect failure: integration not activated, not bad credentials Every Björn Lundén connect in prod has failed with "Leverantören avvisade autentiseringen" (10 consents since June; only BL's own sandbox company ever received tokens). Live-verified against a real customer User-Key today: BL answers 403 "<service>:READ is out of allowed scope for service provider Arcim" on every read endpoint. The key is right and binds the company; the company has simply never activated our integration, and it cannot until BL moves the listing out of sandbox. The generic 403 mapping told the user to re-check what they pasted, which can never help. - BjornLundenClient: isBjornLundenScopeError / isBjornLundenUnknownKeyError, matching the verbatim live 403 and 500 bodies. - submitProviderToken: 403-with-scope-body -> ProviderTokenInvalidError kind 'integration-not-activated'; 500/404 -> 'company-key-not-found'; 401 (our own client_credentials token refused) rethrows as a generic submit failure instead of blaming the pasted key. - New 422 structured errors BL_INTEGRATION_NOT_ACTIVATED and BL_COMPANY_KEY_NOT_FOUND with Swedish/English copy that names the fix (activate under Integrationer in Lundify, else SIE) and where the GUID is. - Wizard copy for BL moved to i18n keys and reordered: activate first, then paste the key; the key only works once the integration is activated. - Tests: route mapping for both kinds, probe classification incl. the captured live bodies, registry entries pinned to 422. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CQG9jNyxM7mwMUHWBrFUxY * fix(providers): drop the unknown-key body matcher, the live BL 500 body is not stable Verifying through BjornLundenClient against apigateway.blinfo.se, a made-up User-Key answered 500 with a Spring BeanCreationException for databaseConnector, not the null getCurrentUser() message captured earlier. The unknown-key verdict already keys on the status alone in submitProviderToken; keep only the 403 scope matcher, whose body IS stable. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CQG9jNyxM7mwMUHWBrFUxY --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
208 lines
6.9 KiB
TypeScript
208 lines
6.9 KiB
TypeScript
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;
|
|
// The SIE export renders a whole fiscal year server-side (megabytes for an
|
|
// active company): give it more room than ordinary CRUD reads.
|
|
const SIE_FETCH_TIMEOUT_MS = 60_000;
|
|
|
|
export class BjornLundenApiError extends Error {
|
|
constructor(
|
|
message: string,
|
|
public readonly statusCode: number,
|
|
public readonly body?: string,
|
|
) {
|
|
super(message);
|
|
this.name = 'BjornLundenApiError';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* True when BL answered 403 because the company behind the User-Key has not
|
|
* activated our integration: the service provider holds no scopes for that
|
|
* company. Live-verified 2026-09-05 against a real customer key:
|
|
*
|
|
* {"body":{"status":"FORBIDDEN","message":"Calls to details:READ is out of
|
|
* allowed scope for service provider Arcim "}, "statusCodeValue":403}
|
|
*
|
|
* The key itself is right, so this must never be reported as "check what
|
|
* you pasted": the fix is on the BL side (activate the integration).
|
|
*
|
|
* An UNKNOWN key is a different signal: BL fails to bind the company database
|
|
* and answers 500. That body is not stable (observed both a null
|
|
* ServiceInfo.getCurrentUser() message and a Spring BeanCreationException for
|
|
* databaseConnector), so callers key the unknown-key verdict on the status
|
|
* alone; only the 403 case has a body worth matching.
|
|
*/
|
|
export function isBjornLundenScopeError(error: unknown): boolean {
|
|
return (
|
|
error instanceof BjornLundenApiError &&
|
|
error.statusCode === 403 &&
|
|
/out of allowed scope/i.test(error.body ?? '')
|
|
)
|
|
}
|
|
|
|
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;
|
|
}
|
|
return error.statusCode === 429 || error.statusCode >= 500;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
interface BLPaginatedResponse<T> {
|
|
pageRequested: number;
|
|
totalPages: number;
|
|
totalRows: number;
|
|
data: T[];
|
|
}
|
|
|
|
export interface BLFinancialYear {
|
|
entityId: number;
|
|
/** BL's period key, e.g. "202501" */
|
|
id?: string;
|
|
fromDate: string;
|
|
toDate: string;
|
|
open?: boolean;
|
|
}
|
|
|
|
export class BjornLundenClient {
|
|
private readonly rateLimiter: TokenBucketRateLimiter;
|
|
private readonly baseUrl: string;
|
|
|
|
constructor(baseUrl?: string) {
|
|
this.baseUrl = baseUrl ?? BL_BASE_URL;
|
|
this.rateLimiter = new TokenBucketRateLimiter(BL_RATE_LIMIT, 'ratelimit:bjornlunden');
|
|
}
|
|
|
|
/**
|
|
* @param options.retry Set to false to fail fast on the first error instead
|
|
* of retrying. Used by credential probes, where a bad User-Key answers
|
|
* HTTP 500 (a "retryable" status) and would otherwise burn the full retry
|
|
* budget with backoff before reporting the bad key.
|
|
*/
|
|
async get<T>(
|
|
accessToken: string,
|
|
userKey: string,
|
|
path: string,
|
|
options?: { retry?: boolean },
|
|
): Promise<T> {
|
|
return withRetry(
|
|
async () => {
|
|
await this.rateLimiter.acquire();
|
|
const url = `${this.baseUrl}${path}`;
|
|
const response = await fetch(url, {
|
|
headers: {
|
|
Authorization: `Bearer ${accessToken}`,
|
|
'User-Key': userKey,
|
|
Accept: 'application/json',
|
|
},
|
|
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const body = await response.text().catch(() => '');
|
|
throw new BjornLundenApiError(
|
|
`Björn Lunden API error: ${response.status} ${response.statusText}`,
|
|
response.status,
|
|
body,
|
|
);
|
|
}
|
|
|
|
return response.json() as Promise<T>;
|
|
},
|
|
{
|
|
maxAttempts: options?.retry === false ? 1 : 3,
|
|
initialDelayMs: 1000,
|
|
shouldRetry: isRetryableError,
|
|
},
|
|
);
|
|
}
|
|
|
|
async getPage<T>(
|
|
accessToken: string,
|
|
userKey: string,
|
|
relativePath: string,
|
|
options?: { page?: number; pageSize?: number },
|
|
): Promise<{ items: T[]; page: number; totalPages: number; totalCount: number }> {
|
|
// Sandbox-verified: the batch endpoints honor `page` and `rows`. The
|
|
// response envelope echoes `pageRequested`, but a `pageRequested` REQUEST
|
|
// param is silently ignored (as is `rowsRequested`): sending those would
|
|
// re-fetch page 1 forever.
|
|
const params = new URLSearchParams();
|
|
params.set('page', String(options?.page ?? 1));
|
|
params.set('rows', String(options?.pageSize ?? 50));
|
|
|
|
const path = `${relativePath}?${params.toString()}`;
|
|
const response = await this.get<BLPaginatedResponse<T>>(accessToken, userKey, path);
|
|
|
|
return {
|
|
items: Array.isArray(response.data) ? response.data : [],
|
|
page: response.pageRequested ?? (options?.page ?? 1),
|
|
totalPages: response.totalPages ?? 1,
|
|
totalCount: response.totalRows ?? 0,
|
|
};
|
|
}
|
|
|
|
async getAll<T>(accessToken: string, userKey: string, path: string): Promise<T[]> {
|
|
const response = await this.get<T[] | BLPaginatedResponse<T>>(accessToken, userKey, path);
|
|
if (Array.isArray(response)) {
|
|
return response;
|
|
}
|
|
return Array.isArray(response.data) ? response.data : [];
|
|
}
|
|
|
|
/**
|
|
* Fetch a binary resource with the same rate-limit/retry behavior as get().
|
|
* Used for the SIE export, which BL serves as raw bytes
|
|
* (Content-Type: text/vnd.sie-gruppen.si, typically CP437-encoded) despite
|
|
* the swagger declaring a base64 string: callers must run the bytes
|
|
* through detectEncoding()/decodeBuffer().
|
|
*/
|
|
async getBytes(accessToken: string, userKey: string, path: string): Promise<ArrayBuffer> {
|
|
return withRetry(
|
|
async () => {
|
|
await this.rateLimiter.acquire();
|
|
const url = `${this.baseUrl}${path}`;
|
|
const response = await fetch(url, {
|
|
headers: {
|
|
Authorization: `Bearer ${accessToken}`,
|
|
'User-Key': userKey,
|
|
},
|
|
signal: AbortSignal.timeout(SIE_FETCH_TIMEOUT_MS),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const body = await response.text().catch(() => '');
|
|
throw new BjornLundenApiError(
|
|
`Björn Lunden API error: ${response.status} ${response.statusText}`,
|
|
response.status,
|
|
body,
|
|
);
|
|
}
|
|
|
|
return response.arrayBuffer();
|
|
},
|
|
{
|
|
maxAttempts: 3,
|
|
initialDelayMs: 1000,
|
|
shouldRetry: isRetryableError,
|
|
},
|
|
);
|
|
}
|
|
|
|
/** All financial years registered in BL for the company behind the User-Key. */
|
|
async listFinancialYears(accessToken: string, userKey: string): Promise<BLFinancialYear[]> {
|
|
return this.getAll<BLFinancialYear>(accessToken, userKey, '/financialyear');
|
|
}
|
|
|
|
async getDetail<T>(accessToken: string, userKey: string, path: string): Promise<T> {
|
|
return this.get<T>(accessToken, userKey, path);
|
|
}
|
|
}
|