@open-banking-io/client 1.3.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +5 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/dist/index.cjs
CHANGED
|
@@ -55,7 +55,7 @@ var import_node_crypto = require("crypto");
|
|
|
55
55
|
// package.json
|
|
56
56
|
var package_default = {
|
|
57
57
|
name: "@open-banking-io/client",
|
|
58
|
-
version: "
|
|
58
|
+
version: "2.0.0",
|
|
59
59
|
description: "Server-to-server client for open-banking.io: API-key auth + client-side decryption of the zero-knowledge data envelopes with your exported private key.",
|
|
60
60
|
type: "module",
|
|
61
61
|
license: "MIT",
|
|
@@ -101,14 +101,14 @@ var package_default = {
|
|
|
101
101
|
},
|
|
102
102
|
devDependencies: {
|
|
103
103
|
"@eslint/js": "^10.0.1",
|
|
104
|
-
"@types/node": "^
|
|
105
|
-
"@vitest/coverage-v8": "^
|
|
104
|
+
"@types/node": "^26.6.6",
|
|
105
|
+
"@vitest/coverage-v8": "^5.1.1",
|
|
106
106
|
eslint: "^10.5.0",
|
|
107
107
|
prettier: "^3.8.4",
|
|
108
|
-
tsup: "^
|
|
108
|
+
tsup: "^9.0.0",
|
|
109
109
|
typescript: "^6.0.3",
|
|
110
110
|
"typescript-eslint": "^8.61.1",
|
|
111
|
-
vitest: "^
|
|
111
|
+
vitest: "^5.1.1"
|
|
112
112
|
},
|
|
113
113
|
homepage: "https://open-banking.io"
|
|
114
114
|
};
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/connect.ts","../package.json","../src/version.ts","../src/client.ts","../src/envelope.ts","../src/errors.ts","../src/consents.ts","../src/recipientKey.ts"],"sourcesContent":["export { OpenBankingClient, psuHeaders } from \"./client.js\";\nexport { SyncError } from \"./errors.js\";\nexport { closeReplacedConsents } from \"./consents.js\";\nexport type { CloseReplacedConsentsOptions, CloseReplacedConsentsResult } from \"./consents.js\";\nexport { decryptEnvelope, decryptTo, importPrivateKey } from \"./envelope.js\";\nexport {\n answerRecipientKeyChallenge,\n generateRecipientKeyPair,\n recipientKeyFingerprint,\n recipientPublicKey,\n} from \"./recipientKey.js\";\nexport type { RecipientKeyPair } from \"./recipientKey.js\";\nexport {\n buildAuthorizeUrl,\n bundleFromToken,\n CONNECT_RELAY_FIELDS,\n createPkce,\n createState,\n discover,\n exchangeCode,\n OAuthError,\n parseRelay,\n PARTNER_KEY_MISSING_DESCRIPTION,\n PARTNER_SUSPENDED_DESCRIPTION,\n pkceChallenge,\n RelayError,\n revokeToken,\n userinfo,\n} from \"./connect.js\";\nexport type {\n AuthorizeUrlOptions,\n ConnectRelay,\n ExchangeCodeOptions,\n HttpOptions,\n ParseRelayOptions,\n Pkce,\n RelayErrorCode,\n RelayInput,\n RelayRefusalReason,\n RevokeTokenOptions,\n ServerMetadata,\n TokenResponse,\n Userinfo,\n UserinfoOptions,\n} from \"./connect.js\";\nexport type {\n Account,\n Balance,\n Transaction,\n TransactionPage,\n TransactionQuery,\n Connection,\n SyncResult,\n SyncAllResult,\n SyncFailure,\n SyncFailureReason,\n SyncOptions,\n PsuHeaders,\n CredentialsBundle,\n EncryptionKey,\n OpenBankingClientOptions,\n} from \"./models.js\";\n","// Partner Connect: the OAuth 2.0 authorization-code flow (PKCE, form_post) that hands a partner an\n// API key and the user's private key. Documented at https://open-banking.io/en/docs/partners.\nimport { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport type { CredentialsBundle } from \"./models.js\";\nimport { USER_AGENT } from \"./version.js\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/** The relay fields the consent page form-posts to a redirect URI, in wire order. */\nexport const CONNECT_RELAY_FIELDS = [\"code\", \"state\", \"iss\", \"privateKey\", \"publicKey\"] as const;\n\nexport interface Pkce {\n /** The `code_verifier` to keep server-side and send on the token request. */\n verifier: string;\n /** The `code_challenge` to send on the authorize request. */\n challenge: string;\n method: \"S256\";\n}\n\n/** A fresh PKCE pair (RFC 7636): 32 random bytes, base64url, S256 challenge. */\nexport function createPkce(): Pkce {\n const verifier = randomBytes(32).toString(\"base64url\");\n return { verifier, challenge: pkceChallenge(verifier), method: \"S256\" };\n}\n\n/** The S256 challenge for a verifier — exposed so a stored verifier can be re-checked. */\nexport function pkceChallenge(verifier: string): string {\n return createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\n/** A fresh opaque `state` (16 random bytes, base64url). */\nexport function createState(): string {\n return randomBytes(16).toString(\"base64url\");\n}\n\nexport interface AuthorizeUrlOptions {\n /** The issuer, e.g. `https://open-banking.io`. */\n issuer: string;\n clientId: string;\n /** One of the client's registered redirect URIs, character for character. */\n redirectUri: string;\n state: string;\n /** From {@link createPkce}. */\n codeChallenge: string;\n /** Defaults to `accounts.read`, the only scope. */\n scope?: string;\n /** Prefills the email on the login page; never authenticates. */\n loginHint?: string;\n /** `pin_code` keeps a popup journey inside the popup (typed emailed code instead of a magic link). */\n challenge?: \"pin_code\";\n /** Space-separated locales; the first one the server publishes forces the language of every screen. */\n uiLocales?: string;\n /**\n * A connection's `sessionId` to renew: the user goes straight to that bank, whether its consent\n * is still live or has lapsed.\n */\n renewConnection?: string;\n}\n\n/** The `/oauth/authorize` URL for a top-level browser navigation. */\nexport function buildAuthorizeUrl(options: AuthorizeUrlOptions): string {\n const params = new URLSearchParams({\n response_type: \"code\",\n client_id: options.clientId,\n redirect_uri: options.redirectUri,\n scope: options.scope ?? \"accounts.read\",\n state: options.state,\n code_challenge: options.codeChallenge,\n code_challenge_method: \"S256\",\n response_mode: \"form_post\",\n });\n if (options.loginHint) params.set(\"login_hint\", options.loginHint);\n if (options.challenge) params.set(\"challenge\", options.challenge);\n if (options.uiLocales) params.set(\"ui_locales\", options.uiLocales);\n if (options.renewConnection) params.set(\"renew_connection\", options.renewConnection);\n return `${endpoint(options.issuer, \"/oauth/authorize\")}?${params.toString()}`;\n}\n\n/** What the consent page relayed to the redirect URI. */\nexport interface ConnectRelay {\n code: string;\n state: string;\n /** Present on current servers (RFC 9207); empty string from older ones. */\n iss: string;\n /** The user's base64 PKCS#8 private key. A credential: never log it. */\n privateKey: string;\n publicKey: string;\n}\n\nexport type RelayErrorCode =\n | \"access_denied\"\n | \"oauth_error\"\n | \"state_mismatch\"\n | \"issuer_mismatch\"\n | \"missing_code\"\n | \"missing_private_key\";\n\n/** The `error_description` the server relays when the partner has not installed its decryption key. */\nexport const PARTNER_KEY_MISSING_DESCRIPTION =\n \"this partner has not installed its decryption key; no authorizations can be started until it does\";\n/** The `error_description` the server relays while the partner is suspended. */\nexport const PARTNER_SUSPENDED_DESCRIPTION =\n \"this partner is suspended; no authorizations can be started\";\n\n/**\n * Why a `temporarily_unavailable` was relayed, when the server said so in the pinned words. Both\n * are on your side, not the bank's: install the key on your partner page, or write to us.\n */\nexport type RelayRefusalReason = \"partner_key_missing\" | \"partner_suspended\";\n\nfunction refusalReason(error: string, description: string): RelayRefusalReason | undefined {\n if (error !== \"temporarily_unavailable\") return undefined;\n if (description === PARTNER_KEY_MISSING_DESCRIPTION) return \"partner_key_missing\";\n if (description === PARTNER_SUSPENDED_DESCRIPTION) return \"partner_suspended\";\n return undefined;\n}\n\n/**\n * Thrown by {@link parseRelay}. `code` says why: `access_denied` is the user pressing \"Back to the\n * partner\" or declining (a normal outcome), `oauth_error` any other error the server relayed (the\n * fields are attached), the rest are validation failures on your side.\n */\nexport class RelayError extends Error {\n readonly code: RelayErrorCode;\n readonly error?: string;\n readonly errorDescription?: string;\n /** Set on an `oauth_error` whose description names a partner-side refusal. */\n readonly reason?: RelayRefusalReason;\n\n constructor(\n code: RelayErrorCode,\n message: string,\n oauth?: { error: string; errorDescription?: string },\n ) {\n super(message);\n this.name = \"RelayError\";\n this.code = code;\n this.error = oauth?.error;\n this.errorDescription = oauth?.errorDescription;\n this.reason = oauth ? refusalReason(oauth.error, oauth.errorDescription ?? \"\") : undefined;\n }\n}\n\nexport interface ParseRelayOptions {\n /** The `state` this flow was started with. Compared in constant time. */\n expectedState: string;\n /** When set, `iss` must equal it (trailing slashes ignored). */\n issuer?: string;\n /** Require `iss` to be present even when `issuer` is not checked. Default: only when `issuer` is set. */\n requireIss?: boolean;\n /**\n * Whether the relay must carry the user's private key. A partner that installed its own\n * decryption key receives `privateKey=\"\"` for every user who connected under it and decrypts\n * with that key instead — pass `\"optional\"`. Default `\"required\"`, the 1.1.0 behaviour.\n */\n expectPrivateKey?: \"required\" | \"optional\";\n}\n\n/** A form body, `URLSearchParams`, parsed body object, or JSON string. */\nexport type RelayInput = string | URLSearchParams | FormData | Record<string, unknown>;\n\n/**\n * Validates the form_post relay: `state` (constant time) and `iss` first, so a relayed error is only\n * honoured for this flow from this issuer; then an OAuth error becomes a {@link RelayError}, and\n * `code` and `privateKey` are checked.\n */\nexport function parseRelay(input: RelayInput, options: ParseRelayOptions): ConnectRelay {\n const fields = toRecord(input);\n const read = (name: string): string => {\n const value = fields[name];\n return typeof value === \"string\" ? value : \"\";\n };\n\n if (!options.expectedState || !constantTimeEqual(read(\"state\"), options.expectedState)) {\n throw new RelayError(\"state_mismatch\", \"The relayed state does not match this flow\");\n }\n\n const iss = read(\"iss\");\n const wantIss = options.issuer !== undefined || options.requireIss === true;\n if (wantIss && !iss) throw new RelayError(\"issuer_mismatch\", \"The relay carries no iss\");\n if (\n options.issuer !== undefined &&\n !constantTimeEqual(trimSlash(iss), trimSlash(options.issuer))\n ) {\n throw new RelayError(\"issuer_mismatch\", \"The relayed iss is not the expected issuer\");\n }\n\n const error = read(\"error\");\n if (error) {\n const description = read(\"error_description\");\n throw new RelayError(\n error === \"access_denied\" ? \"access_denied\" : \"oauth_error\",\n description ? `${error}: ${description}` : error,\n {\n error,\n errorDescription: description || undefined,\n },\n );\n }\n\n const code = read(\"code\");\n if (!code) throw new RelayError(\"missing_code\", \"The relay carries no authorization code\");\n const privateKey = read(\"privateKey\");\n if (!privateKey && (options.expectPrivateKey ?? \"required\") === \"required\") {\n throw new RelayError(\"missing_private_key\", \"The relay carries no private key\");\n }\n\n return { code, state: read(\"state\"), iss, privateKey, publicKey: read(\"publicKey\") };\n}\n\n/** An RFC 6749 §5.2 error body from the token or revocation endpoint. */\nexport class OAuthError extends Error {\n readonly status: number;\n readonly error: string;\n readonly errorDescription?: string;\n\n constructor(status: number, error: string, errorDescription?: string) {\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = \"OAuthError\";\n this.status = status;\n this.error = error;\n this.errorDescription = errorDescription;\n }\n}\n\nexport interface HttpOptions {\n /** Custom `fetch`, e.g. for tests. Defaults to the global. */\n fetch?: typeof globalThis.fetch;\n /** Per-request timeout; defaults to 30s. */\n timeoutMs?: number;\n}\n\nexport interface ExchangeCodeOptions extends HttpOptions {\n issuer: string;\n clientId: string;\n clientSecret: string;\n /** From the relay. */\n code: string;\n /** From {@link createPkce}, kept server-side. */\n codeVerifier: string;\n /** The redirect URI used on the authorize request; sent when given and must match. */\n redirectUri?: string;\n}\n\n/** The token endpoint's response. `accessToken` and `apiKey` are the same key. */\nexport interface TokenResponse {\n accessToken: string;\n tokenType: string;\n expiresIn: number;\n scope: string;\n apiKey: string;\n apiBaseUrl: string;\n /** The tenant subject the key reads for. */\n user: string;\n}\n\ninterface TokenResponseWire {\n access_token?: string;\n token_type?: string;\n expires_in?: number;\n scope?: string;\n apiKey?: string;\n apiBaseUrl?: string;\n user?: string;\n}\n\n/** Exchanges the relayed code for the key, server to server, with HTTP Basic client authentication. */\nexport async function exchangeCode(options: ExchangeCodeOptions): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: \"authorization_code\",\n code: options.code,\n code_verifier: options.codeVerifier,\n });\n if (options.redirectUri) body.set(\"redirect_uri\", options.redirectUri);\n\n const response = await post(\n endpoint(options.issuer, \"/oauth/token\"),\n body,\n {\n Authorization: basicAuth(options.clientId, options.clientSecret),\n Accept: \"application/json\",\n },\n options,\n );\n await throwIfOAuthError(response);\n\n const wire = (await response.json()) as TokenResponseWire;\n const accessToken = wire.access_token ?? wire.apiKey;\n if (!accessToken)\n throw new OAuthError(\n response.status,\n \"invalid_response\",\n \"The token response carries no access token\",\n );\n return {\n accessToken,\n tokenType: wire.token_type ?? \"Bearer\",\n expiresIn: wire.expires_in ?? 0,\n scope: wire.scope ?? \"\",\n apiKey: wire.apiKey ?? accessToken,\n apiBaseUrl: wire.apiBaseUrl ?? trimSlash(options.issuer),\n user: wire.user ?? \"\",\n };\n}\n\nexport interface RevokeTokenOptions extends HttpOptions {\n issuer: string;\n clientId: string;\n clientSecret: string;\n /** The key to revoke. Only keys issued to this client are touched; an unknown key still succeeds. */\n token: string;\n /**\n * Bank consents to close in the same call, with the decrypted Enable Banking session id of each.\n * Validated before the key is revoked: a refusal leaves the key alive.\n */\n closeConsents?: { connectionId: string; ebSessionId: string }[];\n}\n\n/** RFC 7009 revocation. Resolves on 200; throws {@link OAuthError} on a client-authentication failure. */\nexport async function revokeToken(options: RevokeTokenOptions): Promise<void> {\n const body = new URLSearchParams({ token: options.token, token_type_hint: \"access_token\" });\n for (const c of options.closeConsents ?? []) {\n body.append(\"connection_id\", c.connectionId);\n body.append(\"eb_session_id\", c.ebSessionId);\n }\n const response = await post(\n endpoint(options.issuer, \"/oauth/revoke\"),\n body,\n {\n Authorization: basicAuth(options.clientId, options.clientSecret),\n },\n options,\n );\n await throwIfOAuthError(response);\n}\n\nexport interface UserinfoOptions extends HttpOptions {\n issuer: string;\n accessToken: string;\n}\n\nexport interface Userinfo {\n sub: string;\n email: string;\n partnerId: string | null;\n clientId: string | null;\n scope: string;\n expiresAt: string | null;\n}\n\ninterface UserinfoWire {\n sub: string;\n email: string;\n partner_id: string | null;\n client_id: string | null;\n scope: string;\n expires_at: string | null;\n}\n\n/** What a key reads for. Throws {@link OAuthError} with status 401 when the key is revoked or expired. */\nexport async function userinfo(options: UserinfoOptions): Promise<Userinfo> {\n const response = await request(\n endpoint(options.issuer, \"/oauth/userinfo\"),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${options.accessToken}`,\n Accept: \"application/json\",\n \"User-Agent\": USER_AGENT,\n },\n },\n options,\n );\n await throwIfOAuthError(response);\n const wire = (await response.json()) as UserinfoWire;\n return {\n sub: wire.sub,\n email: wire.email,\n partnerId: wire.partner_id ?? null,\n clientId: wire.client_id ?? null,\n scope: wire.scope,\n expiresAt: wire.expires_at ?? null,\n };\n}\n\n/** RFC 8414 metadata with the `open_banking_io` extension. */\nexport interface ServerMetadata {\n issuer: string;\n authorization_endpoint: string;\n token_endpoint: string;\n revocation_endpoint: string;\n scopes_supported: string[];\n response_types_supported: string[];\n response_modes_supported: string[];\n grant_types_supported: string[];\n token_endpoint_auth_methods_supported: string[];\n revocation_endpoint_auth_methods_supported?: string[];\n code_challenge_methods_supported: string[];\n authorization_response_iss_parameter_supported?: boolean;\n service_documentation?: string;\n open_banking_io: {\n userinfo_endpoint: string;\n api_base_url: string;\n api_key_header: string;\n bearer_supported: boolean;\n login_challenges_supported?: string[];\n key_relay: { response_mode: string; fields: string[] };\n /** The server accepts a partner-held decryption key (always true on current servers). */\n recipient_key_supported?: boolean;\n /** Every partner must hold one before it can register a client or start an authorization. */\n recipient_key_required?: boolean;\n documentation: string;\n };\n}\n\nconst discoveryCache = new Map<string, { metadata: ServerMetadata; expiresAt: number }>();\nconst DISCOVERY_TTL_MS = 60 * 60 * 1000;\n\n/** Fetches `/.well-known/oauth-authorization-server`, cached per issuer for an hour. */\nexport async function discover(issuer: string, options: HttpOptions = {}): Promise<ServerMetadata> {\n const key = trimSlash(issuer);\n const cached = discoveryCache.get(key);\n if (cached && cached.expiresAt > Date.now()) return cached.metadata;\n\n const response = await request(\n `${key}/.well-known/oauth-authorization-server`,\n {\n method: \"GET\",\n headers: { Accept: \"application/json\", \"User-Agent\": USER_AGENT },\n },\n options,\n );\n if (!response.ok)\n throw new OAuthError(response.status, \"discovery_failed\", `HTTP ${response.status}`);\n const metadata = (await response.json()) as ServerMetadata;\n if (typeof metadata.issuer !== \"string\" || trimSlash(metadata.issuer) !== key) {\n throw new OAuthError(\n response.status,\n \"discovery_failed\",\n `Issuer mismatch: ${String(metadata.issuer)}`,\n );\n }\n discoveryCache.set(key, { metadata, expiresAt: Date.now() + DISCOVERY_TTL_MS });\n return metadata;\n}\n\n/** The credentials bundle the data client reads with: the key plus the relayed private key. */\nexport function bundleFromToken(token: TokenResponse, privateKey: string): CredentialsBundle {\n return {\n service: \"open-banking.io\",\n apiBaseUrl: token.apiBaseUrl,\n user: token.user,\n apiKey: token.accessToken,\n encryptionKey: { scheme: \"ecdh-p256-hkdf-aes-256-gcm\", curve: \"P-256\", privateKey },\n };\n}\n\nfunction endpoint(issuer: string, path: string): string {\n return trimSlash(issuer) + path;\n}\n\nfunction trimSlash(value: string): string {\n let end = value.length;\n while (end > 0 && value[end - 1] === \"/\") end--;\n return value.slice(0, end);\n}\n\nfunction basicAuth(clientId: string, clientSecret: string): string {\n const pair = `${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`;\n return `Basic ${Buffer.from(pair, \"utf8\").toString(\"base64\")}`;\n}\n\nfunction constantTimeEqual(a: string, b: string): boolean {\n const x = createHash(\"sha256\").update(a, \"utf8\").digest();\n const y = createHash(\"sha256\").update(b, \"utf8\").digest();\n return timingSafeEqual(x, y) && a.length === b.length;\n}\n\nfunction toRecord(input: RelayInput): Record<string, unknown> {\n if (typeof input === \"string\") {\n const trimmed = input.trim();\n if (trimmed.startsWith(\"{\")) return JSON.parse(trimmed) as Record<string, unknown>;\n return Object.fromEntries(new URLSearchParams(trimmed));\n }\n if (input instanceof URLSearchParams) return Object.fromEntries(input);\n if (input instanceof FormData) {\n const record: Record<string, unknown> = {};\n input.forEach((value, name) => {\n if (typeof value === \"string\") record[name] = value;\n });\n return record;\n }\n return input;\n}\n\nasync function post(\n url: string,\n body: URLSearchParams,\n headers: Record<string, string>,\n options: HttpOptions,\n): Promise<Response> {\n return request(\n url,\n {\n method: \"POST\",\n headers: {\n ...headers,\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": USER_AGENT,\n },\n body: body.toString(),\n },\n options,\n );\n}\n\nasync function request(url: string, init: RequestInit, options: HttpOptions): Promise<Response> {\n const fetchImpl = options.fetch ?? fetch;\n return fetchImpl(url, {\n ...init,\n signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n });\n}\n\nasync function throwIfOAuthError(response: Response): Promise<void> {\n if (response.ok) return;\n let error = \"http_error\";\n let description: string | undefined = `HTTP ${response.status}`;\n try {\n const body = (await response.json()) as { error?: string; error_description?: string };\n if (body.error) {\n error = body.error;\n description = body.error_description;\n }\n } catch {\n // A non-JSON error body keeps the HTTP status as the description.\n }\n throw new OAuthError(response.status, error, description);\n}\n","{\n \"name\": \"@open-banking-io/client\",\n \"version\": \"1.3.0\",\n \"description\": \"Server-to-server client for open-banking.io: API-key auth + client-side decryption of the zero-knowledge data envelopes with your exported private key.\",\n \"type\": \"module\",\n \"license\": \"MIT\",\n \"author\": \"open-banking.io\",\n \"keywords\": [\n \"open-banking\",\n \"psd2\",\n \"zero-knowledge\",\n \"encryption\",\n \"fintech\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/open-banking-io/clients\"\n },\n \"engines\": {\n \"node\": \">=20\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n }\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"test\": \"vitest run\",\n \"coverage\": \"vitest run --coverage\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format:check\": \"prettier --check .\"\n },\n \"overrides\": {\n \"esbuild\": \"^0.28.1\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^10.0.1\",\n \"@types/node\": \"^25.9.3\",\n \"@vitest/coverage-v8\": \"^4.1.9\",\n \"eslint\": \"^10.5.0\",\n \"prettier\": \"^3.8.4\",\n \"tsup\": \"^8.5.1\",\n \"typescript\": \"^6.0.3\",\n \"typescript-eslint\": \"^8.61.1\",\n \"vitest\": \"^4.1.9\"\n },\n \"homepage\": \"https://open-banking.io\"\n}\n","// The package version, sourced from package.json so it can never drift. tsup inlines the JSON at\n// build time (tree-shaken to the single string), and vitest/tsx resolve the import directly — so\n// this stays ESM/CJS-safe without a runtime file read.\nimport pkg from \"../package.json\" with { type: \"json\" };\n\nexport const VERSION: string = pkg.version;\n\n/** The `User-Agent` sent on every request: `open-banking-io/node/<version>`. */\nexport const USER_AGENT = `open-banking-io/node/${VERSION}`;\n","import { bundleFromToken, type TokenResponse } from \"./connect.js\";\nimport { readFileSync } from \"node:fs\";\nimport { decryptTo, importPrivateKey, type CryptoKey } from \"./envelope.js\";\nimport { SyncError } from \"./errors.js\";\nimport { USER_AGENT } from \"./version.js\";\nimport type {\n Account,\n AccountEnc,\n AccountWire,\n BalanceEnc,\n Connection,\n ConnectionWire,\n CredentialsBundle,\n DisplayNameEnc,\n OpenBankingClientOptions,\n PsuHeaders,\n SyncAllResult,\n SyncAllResultWire,\n SyncFailure,\n SyncOptions,\n SyncResult,\n SyncResultWire,\n Transaction,\n TransactionEnc,\n TransactionPage,\n TransactionPageWire,\n TransactionQuery,\n TransactionWire,\n UidEnc,\n} from \"./models.js\";\n\n/**\n * Server-to-server client for open-banking.io. Authenticates with an API key (`X-Api-Key`) and\n * decrypts the zero-knowledge data envelopes locally with the exported private key — the service\n * only ever returns ciphertext it cannot read.\n */\nexport class OpenBankingClient {\n /** Default per-request timeout (30s) when {@link OpenBankingClientOptions.timeoutMs} is unset. */\n static readonly DEFAULT_TIMEOUT_MS = 30_000;\n\n private readonly baseUrl: string;\n private readonly apiKey: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly privateKey: Promise<CryptoKey>;\n\n constructor(options: OpenBankingClientOptions) {\n const { apiBaseUrl, apiKey, privateKeyPkcs8, timeoutMs } = options;\n if (!apiBaseUrl?.trim()) throw new Error(\"apiBaseUrl is required\");\n if (!apiKey?.trim()) throw new Error(\"apiKey is required\");\n if (!privateKeyPkcs8?.trim()) throw new Error(\"privateKeyPkcs8 is required\");\n\n // Strip all trailing \"/\" without a backtracking regex (avoids ReDoS on long inputs).\n let end = apiBaseUrl.length;\n while (end > 0 && apiBaseUrl.charCodeAt(end - 1) === 47 /* \"/\" */) end--;\n this.baseUrl = apiBaseUrl.slice(0, end);\n this.apiKey = apiKey;\n this.timeoutMs = timeoutMs ?? OpenBankingClient.DEFAULT_TIMEOUT_MS;\n this.fetchImpl = options.fetch ?? fetch;\n this.privateKey = importPrivateKey(privateKeyPkcs8);\n }\n\n /**\n * Builds a client from a credentials-bundle JSON string or a path to a bundle file.\n *\n * `overrides` (optional) lets the bundle path set the same transport knobs as the\n * constructor — e.g. a custom {@link OpenBankingClientOptions.fetch} or\n * {@link OpenBankingClientOptions.timeoutMs}.\n */\n static fromCredentials(\n jsonOrPath: string,\n overrides: Partial<Pick<OpenBankingClientOptions, \"fetch\" | \"timeoutMs\">> = {},\n ): OpenBankingClient {\n let json = jsonOrPath;\n if (!jsonOrPath.trimStart().startsWith(\"{\")) {\n json = readFileSync(jsonOrPath, \"utf8\");\n }\n const bundle = JSON.parse(json) as CredentialsBundle;\n return OpenBankingClient.fromBundle(bundle, overrides);\n }\n\n static fromBundle(\n bundle: CredentialsBundle,\n overrides: Partial<Pick<OpenBankingClientOptions, \"fetch\" | \"timeoutMs\">> = {},\n ): OpenBankingClient {\n if (!bundle.apiKey?.trim()) throw new Error(\"The credentials bundle has no apiKey\");\n return new OpenBankingClient({\n apiBaseUrl: bundle.apiBaseUrl,\n apiKey: bundle.apiKey,\n privateKeyPkcs8: bundle.encryptionKey.privateKey,\n timeoutMs: overrides.timeoutMs,\n fetch: overrides.fetch,\n });\n }\n\n /**\n * Builds a client from a Partner Connect token response and the private key the consent page\n * relayed — see {@link exchangeCode} and {@link parseRelay}.\n */\n static fromTokenResponse(\n token: TokenResponse,\n privateKey: string,\n overrides: Partial<Pick<OpenBankingClientOptions, \"fetch\" | \"timeoutMs\">> = {},\n ): OpenBankingClient {\n return OpenBankingClient.fromBundle(bundleFromToken(token, privateKey), overrides);\n }\n\n /** Lists the user's accounts with all sensitive fields decrypted. */\n async getAccounts(): Promise<Account[]> {\n const wires = await this.getAccountWires();\n return Promise.all(wires.map((w) => this.mapAccount(w)));\n }\n\n /** Returns a page of an account's statement, newest first, with decrypted fields. */\n async getTransactions(accountId: string, query: TransactionQuery = {}): Promise<TransactionPage> {\n const qs = new URLSearchParams();\n if (query.from != null) qs.set(\"from\", query.from);\n if (query.to != null) qs.set(\"to\", query.to);\n if (query.limit != null) qs.set(\"limit\", String(query.limit));\n if (query.offset != null) qs.set(\"offset\", String(query.offset));\n const suffix = qs.toString() ? `?${qs.toString()}` : \"\";\n\n const page = await this.getJson<TransactionPageWire>(\n `/api/accounts/${encodeURIComponent(accountId)}/transactions${suffix}`,\n );\n\n const items = await Promise.all((page.items ?? []).map((t) => this.mapTransaction(t)));\n return { items, total: page.total };\n }\n\n /** Lists the user's bank connections. */\n async getConnections(): Promise<Connection[]> {\n const wires = await this.getJson<ConnectionWire[]>(\"/api/connections\");\n return wires.map((c) => ({\n sessionId: c.sessionId,\n aspspName: c.aspspName,\n aspspCountry: c.aspspCountry,\n validUntil: c.validUntil,\n status: c.status,\n accountCount: c.accountCount,\n lastSyncedAt: c.lastSyncedAt ?? null,\n psuType: c.psuType ?? null,\n isLive: c.isLive ?? (c.status === \"Active\" && Date.parse(c.validUntil) > Date.now()),\n accountIds: c.accountIds ?? [],\n }));\n }\n\n /**\n * Triggers an online sync of one account: decrypts that account's Enable Banking uid and posts\n * it, so the service can fetch fresh data without ever holding the uid in plaintext.\n *\n * A refusal throws {@link SyncError}. A uid a renewal replaced (`uid_outdated`) is re-read and\n * retried once.\n */\n async sync(accountId: string, options: SyncOptions = {}): Promise<SyncResult> {\n for (let attempt = 0; ; attempt++) {\n const wires = await this.getAccountWires();\n const account = wires.find((a) => a.id === accountId);\n if (!account) throw new Error(`Account ${accountId} not found`);\n\n const uid = account.needsReconnect ? null : await this.decryptUid(account);\n if (uid == null) {\n throw new SyncError(\n \"Account has no active session (reconnect required) — cannot sync\",\n 409,\n \"reconnect_needed\",\n );\n }\n\n try {\n const result = await this.postJson<SyncResultWire>(\n `/api/accounts/${encodeURIComponent(accountId)}/sync`,\n { uid },\n psuHeaders(options.psu),\n );\n return { newTransactions: result.newTransactions, totalFetched: result.totalFetched };\n } catch (e) {\n if (attempt === 0 && e instanceof SyncError && e.reason === \"uid_outdated\") continue;\n throw e;\n }\n }\n }\n\n /**\n * Triggers an online sync of every account that has an active session. Per-account refusals are\n * in `failures`, and so is every account whose consent needs renewing (`reconnect_needed`, never\n * sent); accounts answering `uid_outdated` are re-read and retried once.\n */\n async syncAll(options: SyncOptions = {}): Promise<SyncAllResult> {\n const read = await this.syncItems();\n const first = await this.postSyncAll(read.items, options);\n first.failures.push(...read.lapsed);\n const outdated = new Set(\n first.failures.filter((f) => f.reason === \"uid_outdated\").map((f) => f.accountId),\n );\n if (outdated.size === 0) return first;\n\n const reread = await this.syncItems();\n const retryItems = reread.items.filter((i) => outdated.has(i.accountId));\n const lapsedNow = reread.lapsed.filter((f) => outdated.has(f.accountId));\n const settled = new Set([...retryItems, ...lapsedNow].map((i) => i.accountId));\n const kept = first.failures.filter((f) => !settled.has(f.accountId));\n if (retryItems.length === 0) return { ...first, failures: [...kept, ...lapsedNow] };\n\n const second = await this.postSyncAll(retryItems, options);\n return {\n accounts: first.accounts + second.accounts,\n newTransactions: first.newTransactions + second.newTransactions,\n failures: [...kept, ...lapsedNow, ...second.failures],\n };\n }\n\n // ---- internals ---------------------------------------------------------------------------------\n\n private getAccountWires(): Promise<AccountWire[]> {\n return this.getJson<AccountWire[]>(\"/api/accounts\");\n }\n\n private async syncItems(): Promise<{\n items: { accountId: string; uid: string }[];\n lapsed: SyncFailure[];\n }> {\n const wires = await this.getAccountWires();\n const decrypted = await Promise.all(\n wires.map(async (a) => ({\n accountId: a.id,\n needsReconnect: a.needsReconnect,\n uid: a.needsReconnect ? null : await this.decryptUid(a),\n })),\n );\n return {\n items: decrypted\n .filter((x): x is typeof x & { uid: string } => x.uid != null)\n .map((x) => ({ accountId: x.accountId, uid: x.uid })),\n lapsed: decrypted\n .filter((x) => x.uid == null && x.needsReconnect)\n .map((x) => ({ accountId: x.accountId, reason: \"reconnect_needed\", bankErrorCode: null })),\n };\n }\n\n private async postSyncAll(\n items: { accountId: string; uid: string }[],\n options: SyncOptions,\n ): Promise<SyncAllResult> {\n if (items.length === 0) return { accounts: 0, newTransactions: 0, failures: [] };\n const result = await this.postJson<SyncAllResultWire>(\n \"/api/sync\",\n { items },\n psuHeaders(options.psu),\n );\n const failures: SyncFailure[] = (result.failures ?? []).map((f) => ({\n accountId: f.accountId,\n reason: f.reason,\n bankErrorCode: f.bankErrorCode ?? null,\n }));\n return { accounts: result.accounts, newTransactions: result.newTransactions, failures };\n }\n\n private async decryptUid(a: AccountWire): Promise<string | null> {\n const dec = await decryptTo<UidEnc>(await this.privateKey, a.uidEnc);\n return dec?.uid ?? null;\n }\n\n private async mapAccount(a: AccountWire): Promise<Account> {\n const priv = await this.privateKey;\n const acc = await decryptTo<AccountEnc>(priv, a.enc);\n const name = await decryptTo<DisplayNameEnc>(priv, a.displayNameEnc);\n const balances = await Promise.all(\n (a.balances ?? []).map(async (b) => {\n const dec = await decryptTo<BalanceEnc>(priv, b.enc);\n return {\n type: b.type,\n name: dec?.name ?? null,\n amount: dec?.amount ?? \"0\",\n currency: b.currency,\n referenceDate: b.referenceDate ?? null,\n };\n }),\n );\n\n return {\n id: a.id,\n aspspName: a.aspspName,\n aspspCountry: a.aspspCountry,\n currency: a.currency,\n accountType: a.accountType ?? null,\n bic: a.bic ?? null,\n needsReconnect: a.needsReconnect,\n iban: acc?.iban ?? null,\n bban: acc?.bban ?? null,\n ownerName: acc?.ownerName ?? null,\n accountName: acc?.accountName ?? null,\n product: acc?.product ?? null,\n displayName: name?.displayName ?? null,\n balances,\n };\n }\n\n private async mapTransaction(t: TransactionWire): Promise<Transaction> {\n const d = await decryptTo<TransactionEnc>(await this.privateKey, t.enc);\n return {\n id: t.id,\n currency: t.currency,\n creditDebitIndicator: t.creditDebitIndicator,\n status: t.status ?? null,\n bookingDate: t.bookingDate ?? null,\n valueDate: t.valueDate ?? null,\n transactionDate: t.transactionDate ?? null,\n bankTransactionCode: t.bankTransactionCode ?? null,\n amount: d?.amount ?? \"0\",\n creditorName: d?.creditorName ?? null,\n creditorIban: d?.creditorIban ?? null,\n creditorBban: d?.creditorBban ?? null,\n creditorAgentBic: d?.creditorAgentBic ?? null,\n debtorName: d?.debtorName ?? null,\n debtorIban: d?.debtorIban ?? null,\n debtorBban: d?.debtorBban ?? null,\n debtorAgentBic: d?.debtorAgentBic ?? null,\n remittanceInformation: d?.remittanceInformation ?? null,\n note: d?.note ?? null,\n referenceNumber: d?.referenceNumber ?? null,\n exchangeRate: d?.exchangeRate ?? null,\n merchantCategoryCode: d?.merchantCategoryCode ?? null,\n balanceAfterTransaction: d?.balanceAfter ?? null,\n balanceAfterCurrency: d?.balanceAfterCurrency ?? null,\n };\n }\n\n private async getJson<T>(path: string): Promise<T> {\n const res = await this.fetchImpl(this.baseUrl + path, {\n headers: { \"X-Api-Key\": this.apiKey, \"User-Agent\": USER_AGENT },\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n if (!res.ok) {\n throw new Error(`GET ${path} failed: ${res.status} ${res.statusText}`);\n }\n return (await res.json()) as T;\n }\n\n private async postJson<T>(\n path: string,\n body: unknown,\n extraHeaders: Record<string, string> = {},\n ): Promise<T> {\n const res = await this.fetchImpl(this.baseUrl + path, {\n method: \"POST\",\n headers: {\n ...extraHeaders,\n \"X-Api-Key\": this.apiKey,\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n if (!res.ok) {\n const problem = await readProblem(res);\n const retryAfter = Number.parseInt(res.headers.get(\"Retry-After\") ?? \"\", 10);\n throw new SyncError(\n `POST ${path} failed: ${res.status} ${problem.reason ?? res.statusText}`,\n res.status,\n problem.reason,\n problem.bankErrorCode,\n Number.isFinite(retryAfter) ? retryAfter : null,\n );\n }\n return (await res.json()) as T;\n }\n}\n\nasync function readProblem(\n res: Response,\n): Promise<{ reason: string | null; bankErrorCode: string | null }> {\n try {\n const body = (await res.json()) as { reason?: unknown; bankErrorCode?: unknown };\n return {\n reason: typeof body.reason === \"string\" ? body.reason : null,\n bankErrorCode: typeof body.bankErrorCode === \"string\" ? body.bankErrorCode : null,\n };\n } catch {\n return { reason: null, bankErrorCode: null };\n }\n}\n\n/** The `X-Psu-*` request headers for a forwarded {@link PsuHeaders}; empty when none is given. */\nexport function psuHeaders(psu: PsuHeaders | undefined): Record<string, string> {\n if (!psu?.ipAddress || !psu.userAgent) return {};\n const headers: Record<string, string> = {\n \"X-Psu-Ip-Address\": psu.ipAddress,\n \"X-Psu-User-Agent\": psu.userAgent,\n };\n const optional: [string, string | undefined][] = [\n [\"X-Psu-Referer\", psu.referer],\n [\"X-Psu-Accept\", psu.accept],\n [\"X-Psu-Accept-Language\", psu.acceptLanguage],\n [\"X-Psu-Accept-Charset\", psu.acceptCharset],\n [\"X-Psu-Accept-Encoding\", psu.acceptEncoding],\n ];\n for (const [name, value] of optional) if (value) headers[name] = value;\n return headers;\n}\n","import { webcrypto } from \"node:crypto\";\n\nconst { subtle } = webcrypto;\n\n/** Re-export the WebCrypto key type so callers don't depend on the DOM lib. */\nexport type CryptoKey = webcrypto.CryptoKey;\n\nconst VERSION = 0x01;\nconst POINT_LEN = 65;\nconst NONCE_LEN = 12;\nconst TAG_LEN = 16;\n\nconst HKDF_INFO = new TextEncoder().encode(\"bank.core.ci/zk/v1\");\nconst HKDF_SALT = new Uint8Array(32); // 32 zero bytes (must be exactly this).\n\n/**\n * Decrypts open-banking.io's zero-knowledge data envelopes.\n * Scheme: ephemeral ECDH on NIST P-256 -> HKDF-SHA256 -> AES-256-GCM.\n * Wire: `version(1)=0x01 | ephemeralPublicKeyRaw(65) | nonce(12) | tag(16) | ciphertext`.\n * Only the user's private key can decrypt — the service stores ciphertext it cannot read.\n */\nexport async function decryptEnvelope(\n privateKey: CryptoKey,\n envelopeBase64: string,\n): Promise<Uint8Array> {\n const bytes = base64ToBytes(envelopeBase64);\n if (bytes.length < 1 + POINT_LEN + NONCE_LEN + TAG_LEN || bytes[0] !== VERSION) {\n throw new Error(\"Invalid or unsupported envelope\");\n }\n\n const ephPub = bytes.subarray(1, 1 + POINT_LEN);\n const nonce = bytes.subarray(1 + POINT_LEN, 1 + POINT_LEN + NONCE_LEN);\n const tag = bytes.subarray(1 + POINT_LEN + NONCE_LEN, 1 + POINT_LEN + NONCE_LEN + TAG_LEN);\n const ciphertext = bytes.subarray(1 + POINT_LEN + NONCE_LEN + TAG_LEN);\n\n // Guard against invalid-curve attacks: WebCrypto's P-256 `importKey` validates that the raw point\n // lies on the curve and is not the point at infinity, so a forged/off-curve ephemeral public key\n // throws here rather than yielding a derivable (and exploitable) shared secret below.\n const ephKey = await subtle.importKey(\n \"raw\",\n ephPub,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false,\n [],\n );\n\n const shared = new Uint8Array(\n await subtle.deriveBits({ name: \"ECDH\", public: ephKey }, privateKey, 256),\n );\n\n const hkdf = await subtle.importKey(\"raw\", shared, \"HKDF\", false, [\"deriveKey\"]);\n\n const aesKey = await subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: HKDF_SALT, info: HKDF_INFO },\n hkdf,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"decrypt\"],\n );\n\n // Web Crypto AES-GCM expects ciphertext||tag.\n const ctWithTag = new Uint8Array(ciphertext.length + tag.length);\n ctWithTag.set(ciphertext, 0);\n ctWithTag.set(tag, ciphertext.length);\n\n const plaintext = await subtle.decrypt(\n { name: \"AES-GCM\", iv: nonce, tagLength: 128 },\n aesKey,\n ctWithTag,\n );\n\n return new Uint8Array(plaintext);\n}\n\n/** Decrypts a base64 envelope and JSON-parses its payload. `null`/`undefined` in -> `null`. */\nexport async function decryptTo<T>(\n privateKey: CryptoKey,\n envelopeBase64: string | null | undefined,\n): Promise<T | null> {\n if (envelopeBase64 == null) return null;\n const plaintext = await decryptEnvelope(privateKey, envelopeBase64);\n return JSON.parse(new TextDecoder().decode(plaintext)) as T;\n}\n\n/** Imports a base64 PKCS#8 P-256 ECDH private key for use with {@link decryptEnvelope}. */\nexport async function importPrivateKey(pkcs8Base64: string): Promise<CryptoKey> {\n return subtle.importKey(\n \"pkcs8\",\n base64ToBytes(pkcs8Base64),\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false,\n [\"deriveBits\"],\n );\n}\n\nfunction base64ToBytes(b64: string): Uint8Array<ArrayBuffer> {\n return new Uint8Array(Buffer.from(b64, \"base64\"));\n}\n","import type { SyncFailureReason } from \"./models.js\";\n\n/** A sync the service refused. `reason` is the stable code to branch on. */\nexport class SyncError extends Error {\n readonly status: number;\n readonly reason: SyncFailureReason | null;\n readonly bankErrorCode: string | null;\n readonly retryAfterSeconds: number | null;\n\n constructor(\n message: string,\n status: number,\n reason: SyncFailureReason | null,\n bankErrorCode: string | null = null,\n retryAfterSeconds: number | null = null,\n ) {\n super(message);\n this.name = \"SyncError\";\n this.status = status;\n this.reason = reason;\n this.bankErrorCode = bankErrorCode;\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n","import { OAuthError, revokeToken, userinfo, type HttpOptions } from \"./connect.js\";\nimport { decryptTo, importPrivateKey } from \"./envelope.js\";\nimport type { OpenConsentWire, SessionIdEnc } from \"./models.js\";\nimport { USER_AGENT } from \"./version.js\";\n\nexport interface CloseReplacedConsentsOptions extends HttpOptions {\n issuer: string;\n clientId: string;\n clientSecret: string;\n /** The PREVIOUS key — the one issued before the renewal. It is revoked by this call. */\n token: string;\n /** The base64 PKCS#8 private key the consents are sealed to. */\n privateKey: string;\n /** Defaults to the issuer. */\n apiBaseUrl?: string;\n}\n\nexport interface CloseReplacedConsentsResult {\n /** Consents sent to be closed at the bank. */\n closed: number;\n /** Consents listed but not closable (no envelope, or it would not decrypt). */\n failed: number;\n /** Whether the previous key is gone. When false, revoke it yourself. */\n revoked: boolean;\n}\n\n/**\n * After a renewal: closes, at the bank, the consents the previous key still has open, and revokes\n * that key in the same call. Reads `GET /api/connections/open-consents` only — never the live\n * connections, which by now hold the renewal. A key that is already gone, or was issued to another\n * client, closes nothing: the service answers such a revoke with 200 without closing anything. A\n * failure that retrying may clear (5xx, 429) throws, so the key survives for a retry: revoking it\n * without the close would leave the consents open with nothing left that can list them.\n */\nexport async function closeReplacedConsents(\n options: CloseReplacedConsentsOptions,\n): Promise<CloseReplacedConsentsResult> {\n const fetchImpl = options.fetch ?? fetch;\n const base = trimSlash(options.apiBaseUrl ?? options.issuer);\n const nothing = { closed: 0, failed: 0, revoked: false };\n\n let owner: string | null;\n try {\n owner = (await userinfo({ ...options, accessToken: options.token })).clientId;\n } catch (e) {\n if (e instanceof OAuthError && keyRefused(e.status)) return nothing;\n throw e;\n }\n if (owner !== options.clientId) return nothing;\n\n const res = await fetchImpl(`${base}/api/connections/open-consents`, {\n headers: { \"X-Api-Key\": options.token, \"User-Agent\": USER_AGENT },\n signal: AbortSignal.timeout(options.timeoutMs ?? 30_000),\n });\n if (keyRefused(res.status)) return nothing;\n if (!res.ok) throw new Error(`GET /api/connections/open-consents failed: ${res.status}`);\n const open = (await res.json()) as OpenConsentWire[];\n\n const key = await importPrivateKey(options.privateKey);\n const closeConsents: { connectionId: string; ebSessionId: string }[] = [];\n const seen = new Set<string>();\n let failed = 0;\n for (const c of open) {\n if (!c.connectionId || seen.has(c.connectionId)) continue;\n seen.add(c.connectionId);\n if (!c.sessionIdEnc) {\n failed += 1;\n continue;\n }\n let sessionId: string | null | undefined;\n try {\n sessionId = (await decryptTo<SessionIdEnc>(key, c.sessionIdEnc))?.sessionId;\n } catch {\n sessionId = null;\n }\n if (!sessionId) {\n failed += 1;\n continue;\n }\n closeConsents.push({ connectionId: c.connectionId, ebSessionId: sessionId });\n }\n\n try {\n await revokeToken({ ...options, closeConsents });\n } catch (e) {\n if (e instanceof OAuthError && e.status < 500 && e.status !== 429)\n return { closed: 0, failed: failed + closeConsents.length, revoked: false };\n throw e;\n }\n return { closed: closeConsents.length, failed, revoked: true };\n}\n\nconst keyRefused = (status: number) => status === 401 || status === 403;\n\nfunction trimSlash(url: string): string {\n let end = url.length;\n while (end > 0 && url.charCodeAt(end - 1) === 47) end--;\n return url.slice(0, end);\n}\n","import { createHash, webcrypto } from \"node:crypto\";\nimport { decryptTo, importPrivateKey } from \"./envelope.js\";\n\nconst subtle = webcrypto.subtle;\n\n/** A partner's recipient (decryption) key pair. The private half is a credential: never log it. */\nexport interface RecipientKeyPair {\n /** Base64 PKCS#8 — what your deployment loads. */\n privateKeyPkcs8Base64: string;\n /** Base64 raw 65-byte uncompressed P-256 point — what you install on your partner page. */\n publicKeyRawBase64: string;\n}\n\n/**\n * Generates the P-256 pair a partner installs on open-banking.io. The public half goes into\n * `PUT /api/partner/recipient-key` (or the partner page's paste box); keep the private half\n * where your deployment can read it — the service never sees it and cannot recover it.\n */\nexport async function generateRecipientKeyPair(): Promise<RecipientKeyPair> {\n const pair = await subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-256\" }, true, [\n \"deriveBits\",\n ]);\n return {\n privateKeyPkcs8Base64: Buffer.from(await subtle.exportKey(\"pkcs8\", pair.privateKey)).toString(\n \"base64\",\n ),\n publicKeyRawBase64: Buffer.from(await subtle.exportKey(\"raw\", pair.publicKey)).toString(\n \"base64\",\n ),\n };\n}\n\n/**\n * The fingerprint the partner page and the admin show for a key: SHA-256 of the raw 65-byte\n * point, lowercase hex, first 16 characters. Print it at boot and compare after every deploy.\n */\nexport function recipientKeyFingerprint(publicKeyRawBase64: string): string {\n return createHash(\"sha256\")\n .update(Buffer.from(publicKeyRawBase64, \"base64\"))\n .digest(\"hex\")\n .slice(0, 16);\n}\n\n/** The raw public point of a PKCS#8 private key — to fingerprint or re-install the key you hold. */\nexport async function recipientPublicKey(privateKeyPkcs8Base64: string): Promise<string> {\n const key = await subtle.importKey(\n \"pkcs8\",\n Buffer.from(privateKeyPkcs8Base64, \"base64\"),\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"],\n );\n const jwk = await subtle.exportKey(\"jwk\", key);\n if (!jwk.x || !jwk.y) throw new Error(\"The private key carries no public point\");\n return Buffer.concat([\n Buffer.from([0x04]),\n Buffer.from(jwk.x, \"base64url\"),\n Buffer.from(jwk.y, \"base64url\"),\n ]).toString(\"base64\");\n}\n\n/**\n * Answers the possession challenge from `POST /api/partner/recipient-key/challenge`: opens\n * the envelope with the private half and returns the nonce — the `challengeAnswer` for the install.\n */\nexport async function answerRecipientKeyChallenge(\n privateKeyPkcs8Base64: string,\n envelopeBase64: string,\n): Promise<string> {\n const payload = await decryptTo<{ nonce?: unknown }>(\n await importPrivateKey(privateKeyPkcs8Base64),\n envelopeBase64,\n );\n const nonce = payload?.nonce;\n if (typeof nonce !== \"string\" || nonce.length === 0)\n throw new Error(\"The challenge envelope carries no nonce\");\n return nonce;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,yBAAyD;;;ACFzD;AAAA,EACE,MAAQ;AAAA,EACR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ACL,uBAAuB,OAAO,KAAK,MAAMA,QAAO,UAAU,SAAS,KAAK,UAAU,CAAC,EAAE;AAAA,MACnF;AAAA,IACF;AAAA,IACA,oBAAoB,OAAO,KAAK,MAAMA,QAAO,UAAU,OAAO,KAAK,SAAS,CAAC,EAAE;AAAA,MAC7E;AAAA,IACF;AAAA,EACF;AACF;AAMO,SAAS,wBAAwB,oBAAoC;AAC1E,aAAO,gCAAW,QAAQ,EACvB,OAAO,OAAO,KAAK,oBAAoB,QAAQ,CAAC,EAChD,OAAO,KAAK,EACZ,MAAM,GAAG,EAAE;AAChB;AAGA,eAAsB,mBAAmB,uBAAgD;AACvF,QAAM,MAAM,MAAMA,QAAO;AAAA,IACvB;AAAA,IACA,OAAO,KAAK,uBAAuB,QAAQ;AAAA,IAC3C,EAAE,MAAM,QAAQ,YAAY,QAAQ;AAAA,IACpC;AAAA,IACA,CAAC,YAAY;AAAA,EACf;AACA,QAAM,MAAM,MAAMA,QAAO,UAAU,OAAO,GAAG;AAC7C,MAAI,CAAC,IAAI,KAAK,CAAC,IAAI,EAAG,OAAM,IAAI,MAAM,yCAAyC;AAC/E,SAAO,OAAO,OAAO;AAAA,IACnB,OAAO,KAAK,CAAC,CAAI,CAAC;AAAA,IAClB,OAAO,KAAK,IAAI,GAAG,WAAW;AAAA,IAC9B,OAAO,KAAK,IAAI,GAAG,WAAW;AAAA,EAChC,CAAC,EAAE,SAAS,QAAQ;AACtB;AAMA,eAAsB,4BACpB,uBACA,gBACiB;AACjB,QAAM,UAAU,MAAM;AAAA,IACpB,MAAM,iBAAiB,qBAAqB;AAAA,IAC5C;AAAA,EACF;AACA,QAAM,QAAQ,SAAS;AACvB,MAAI,OAAO,UAAU,YAAY,MAAM,WAAW;AAChD,UAAM,IAAI,MAAM,yCAAyC;AAC3D,SAAO;AACT;","names":["import_node_crypto","VERSION","trimSlash","import_node_crypto","subtle"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/connect.ts","../package.json","../src/version.ts","../src/client.ts","../src/envelope.ts","../src/errors.ts","../src/consents.ts","../src/recipientKey.ts"],"sourcesContent":["export { OpenBankingClient, psuHeaders } from \"./client.js\";\nexport { SyncError } from \"./errors.js\";\nexport { closeReplacedConsents } from \"./consents.js\";\nexport type { CloseReplacedConsentsOptions, CloseReplacedConsentsResult } from \"./consents.js\";\nexport { decryptEnvelope, decryptTo, importPrivateKey } from \"./envelope.js\";\nexport {\n answerRecipientKeyChallenge,\n generateRecipientKeyPair,\n recipientKeyFingerprint,\n recipientPublicKey,\n} from \"./recipientKey.js\";\nexport type { RecipientKeyPair } from \"./recipientKey.js\";\nexport {\n buildAuthorizeUrl,\n bundleFromToken,\n CONNECT_RELAY_FIELDS,\n createPkce,\n createState,\n discover,\n exchangeCode,\n OAuthError,\n parseRelay,\n PARTNER_KEY_MISSING_DESCRIPTION,\n PARTNER_SUSPENDED_DESCRIPTION,\n pkceChallenge,\n RelayError,\n revokeToken,\n userinfo,\n} from \"./connect.js\";\nexport type {\n AuthorizeUrlOptions,\n ConnectRelay,\n ExchangeCodeOptions,\n HttpOptions,\n ParseRelayOptions,\n Pkce,\n RelayErrorCode,\n RelayInput,\n RelayRefusalReason,\n RevokeTokenOptions,\n ServerMetadata,\n TokenResponse,\n Userinfo,\n UserinfoOptions,\n} from \"./connect.js\";\nexport type {\n Account,\n Balance,\n Transaction,\n TransactionPage,\n TransactionQuery,\n Connection,\n SyncResult,\n SyncAllResult,\n SyncFailure,\n SyncFailureReason,\n SyncOptions,\n PsuHeaders,\n CredentialsBundle,\n EncryptionKey,\n OpenBankingClientOptions,\n} from \"./models.js\";\n","// Partner Connect: the OAuth 2.0 authorization-code flow (PKCE, form_post) that hands a partner an\n// API key and the user's private key. Documented at https://open-banking.io/en/docs/partners.\nimport { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport type { CredentialsBundle } from \"./models.js\";\nimport { USER_AGENT } from \"./version.js\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/** The relay fields the consent page form-posts to a redirect URI, in wire order. */\nexport const CONNECT_RELAY_FIELDS = [\"code\", \"state\", \"iss\", \"privateKey\", \"publicKey\"] as const;\n\nexport interface Pkce {\n /** The `code_verifier` to keep server-side and send on the token request. */\n verifier: string;\n /** The `code_challenge` to send on the authorize request. */\n challenge: string;\n method: \"S256\";\n}\n\n/** A fresh PKCE pair (RFC 7636): 32 random bytes, base64url, S256 challenge. */\nexport function createPkce(): Pkce {\n const verifier = randomBytes(32).toString(\"base64url\");\n return { verifier, challenge: pkceChallenge(verifier), method: \"S256\" };\n}\n\n/** The S256 challenge for a verifier — exposed so a stored verifier can be re-checked. */\nexport function pkceChallenge(verifier: string): string {\n return createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\n/** A fresh opaque `state` (16 random bytes, base64url). */\nexport function createState(): string {\n return randomBytes(16).toString(\"base64url\");\n}\n\nexport interface AuthorizeUrlOptions {\n /** The issuer, e.g. `https://open-banking.io`. */\n issuer: string;\n clientId: string;\n /** One of the client's registered redirect URIs, character for character. */\n redirectUri: string;\n state: string;\n /** From {@link createPkce}. */\n codeChallenge: string;\n /** Defaults to `accounts.read`, the only scope. */\n scope?: string;\n /** Prefills the email on the login page; never authenticates. */\n loginHint?: string;\n /** `pin_code` keeps a popup journey inside the popup (typed emailed code instead of a magic link). */\n challenge?: \"pin_code\";\n /** Space-separated locales; the first one the server publishes forces the language of every screen. */\n uiLocales?: string;\n /**\n * A connection's `sessionId` to renew: the user goes straight to that bank, whether its consent\n * is still live or has lapsed.\n */\n renewConnection?: string;\n}\n\n/** The `/oauth/authorize` URL for a top-level browser navigation. */\nexport function buildAuthorizeUrl(options: AuthorizeUrlOptions): string {\n const params = new URLSearchParams({\n response_type: \"code\",\n client_id: options.clientId,\n redirect_uri: options.redirectUri,\n scope: options.scope ?? \"accounts.read\",\n state: options.state,\n code_challenge: options.codeChallenge,\n code_challenge_method: \"S256\",\n response_mode: \"form_post\",\n });\n if (options.loginHint) params.set(\"login_hint\", options.loginHint);\n if (options.challenge) params.set(\"challenge\", options.challenge);\n if (options.uiLocales) params.set(\"ui_locales\", options.uiLocales);\n if (options.renewConnection) params.set(\"renew_connection\", options.renewConnection);\n return `${endpoint(options.issuer, \"/oauth/authorize\")}?${params.toString()}`;\n}\n\n/** What the consent page relayed to the redirect URI. */\nexport interface ConnectRelay {\n code: string;\n state: string;\n /** Present on current servers (RFC 9207); empty string from older ones. */\n iss: string;\n /** The user's base64 PKCS#8 private key. A credential: never log it. */\n privateKey: string;\n publicKey: string;\n}\n\nexport type RelayErrorCode =\n | \"access_denied\"\n | \"oauth_error\"\n | \"state_mismatch\"\n | \"issuer_mismatch\"\n | \"missing_code\"\n | \"missing_private_key\";\n\n/** The `error_description` the server relays when the partner has not installed its decryption key. */\nexport const PARTNER_KEY_MISSING_DESCRIPTION =\n \"this partner has not installed its decryption key; no authorizations can be started until it does\";\n/** The `error_description` the server relays while the partner is suspended. */\nexport const PARTNER_SUSPENDED_DESCRIPTION =\n \"this partner is suspended; no authorizations can be started\";\n\n/**\n * Why a `temporarily_unavailable` was relayed, when the server said so in the pinned words. Both\n * are on your side, not the bank's: install the key on your partner page, or write to us.\n */\nexport type RelayRefusalReason = \"partner_key_missing\" | \"partner_suspended\";\n\nfunction refusalReason(error: string, description: string): RelayRefusalReason | undefined {\n if (error !== \"temporarily_unavailable\") return undefined;\n if (description === PARTNER_KEY_MISSING_DESCRIPTION) return \"partner_key_missing\";\n if (description === PARTNER_SUSPENDED_DESCRIPTION) return \"partner_suspended\";\n return undefined;\n}\n\n/**\n * Thrown by {@link parseRelay}. `code` says why: `access_denied` is the user pressing \"Back to the\n * partner\" or declining (a normal outcome), `oauth_error` any other error the server relayed (the\n * fields are attached), the rest are validation failures on your side.\n */\nexport class RelayError extends Error {\n readonly code: RelayErrorCode;\n readonly error?: string;\n readonly errorDescription?: string;\n /** Set on an `oauth_error` whose description names a partner-side refusal. */\n readonly reason?: RelayRefusalReason;\n\n constructor(\n code: RelayErrorCode,\n message: string,\n oauth?: { error: string; errorDescription?: string },\n ) {\n super(message);\n this.name = \"RelayError\";\n this.code = code;\n this.error = oauth?.error;\n this.errorDescription = oauth?.errorDescription;\n this.reason = oauth ? refusalReason(oauth.error, oauth.errorDescription ?? \"\") : undefined;\n }\n}\n\nexport interface ParseRelayOptions {\n /** The `state` this flow was started with. Compared in constant time. */\n expectedState: string;\n /** When set, `iss` must equal it (trailing slashes ignored). */\n issuer?: string;\n /** Require `iss` to be present even when `issuer` is not checked. Default: only when `issuer` is set. */\n requireIss?: boolean;\n /**\n * Whether the relay must carry the user's private key. A partner that installed its own\n * decryption key receives `privateKey=\"\"` for every user who connected under it and decrypts\n * with that key instead — pass `\"optional\"`. Default `\"required\"`, the 1.1.0 behaviour.\n */\n expectPrivateKey?: \"required\" | \"optional\";\n}\n\n/** A form body, `URLSearchParams`, parsed body object, or JSON string. */\nexport type RelayInput = string | URLSearchParams | FormData | Record<string, unknown>;\n\n/**\n * Validates the form_post relay: `state` (constant time) and `iss` first, so a relayed error is only\n * honoured for this flow from this issuer; then an OAuth error becomes a {@link RelayError}, and\n * `code` and `privateKey` are checked.\n */\nexport function parseRelay(input: RelayInput, options: ParseRelayOptions): ConnectRelay {\n const fields = toRecord(input);\n const read = (name: string): string => {\n const value = fields[name];\n return typeof value === \"string\" ? value : \"\";\n };\n\n if (!options.expectedState || !constantTimeEqual(read(\"state\"), options.expectedState)) {\n throw new RelayError(\"state_mismatch\", \"The relayed state does not match this flow\");\n }\n\n const iss = read(\"iss\");\n const wantIss = options.issuer !== undefined || options.requireIss === true;\n if (wantIss && !iss) throw new RelayError(\"issuer_mismatch\", \"The relay carries no iss\");\n if (\n options.issuer !== undefined &&\n !constantTimeEqual(trimSlash(iss), trimSlash(options.issuer))\n ) {\n throw new RelayError(\"issuer_mismatch\", \"The relayed iss is not the expected issuer\");\n }\n\n const error = read(\"error\");\n if (error) {\n const description = read(\"error_description\");\n throw new RelayError(\n error === \"access_denied\" ? \"access_denied\" : \"oauth_error\",\n description ? `${error}: ${description}` : error,\n {\n error,\n errorDescription: description || undefined,\n },\n );\n }\n\n const code = read(\"code\");\n if (!code) throw new RelayError(\"missing_code\", \"The relay carries no authorization code\");\n const privateKey = read(\"privateKey\");\n if (!privateKey && (options.expectPrivateKey ?? \"required\") === \"required\") {\n throw new RelayError(\"missing_private_key\", \"The relay carries no private key\");\n }\n\n return { code, state: read(\"state\"), iss, privateKey, publicKey: read(\"publicKey\") };\n}\n\n/** An RFC 6749 §5.2 error body from the token or revocation endpoint. */\nexport class OAuthError extends Error {\n readonly status: number;\n readonly error: string;\n readonly errorDescription?: string;\n\n constructor(status: number, error: string, errorDescription?: string) {\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = \"OAuthError\";\n this.status = status;\n this.error = error;\n this.errorDescription = errorDescription;\n }\n}\n\nexport interface HttpOptions {\n /** Custom `fetch`, e.g. for tests. Defaults to the global. */\n fetch?: typeof globalThis.fetch;\n /** Per-request timeout; defaults to 30s. */\n timeoutMs?: number;\n}\n\nexport interface ExchangeCodeOptions extends HttpOptions {\n issuer: string;\n clientId: string;\n clientSecret: string;\n /** From the relay. */\n code: string;\n /** From {@link createPkce}, kept server-side. */\n codeVerifier: string;\n /** The redirect URI used on the authorize request; sent when given and must match. */\n redirectUri?: string;\n}\n\n/** The token endpoint's response. `accessToken` and `apiKey` are the same key. */\nexport interface TokenResponse {\n accessToken: string;\n tokenType: string;\n expiresIn: number;\n scope: string;\n apiKey: string;\n apiBaseUrl: string;\n /** The tenant subject the key reads for. */\n user: string;\n}\n\ninterface TokenResponseWire {\n access_token?: string;\n token_type?: string;\n expires_in?: number;\n scope?: string;\n apiKey?: string;\n apiBaseUrl?: string;\n user?: string;\n}\n\n/** Exchanges the relayed code for the key, server to server, with HTTP Basic client authentication. */\nexport async function exchangeCode(options: ExchangeCodeOptions): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: \"authorization_code\",\n code: options.code,\n code_verifier: options.codeVerifier,\n });\n if (options.redirectUri) body.set(\"redirect_uri\", options.redirectUri);\n\n const response = await post(\n endpoint(options.issuer, \"/oauth/token\"),\n body,\n {\n Authorization: basicAuth(options.clientId, options.clientSecret),\n Accept: \"application/json\",\n },\n options,\n );\n await throwIfOAuthError(response);\n\n const wire = (await response.json()) as TokenResponseWire;\n const accessToken = wire.access_token ?? wire.apiKey;\n if (!accessToken)\n throw new OAuthError(\n response.status,\n \"invalid_response\",\n \"The token response carries no access token\",\n );\n return {\n accessToken,\n tokenType: wire.token_type ?? \"Bearer\",\n expiresIn: wire.expires_in ?? 0,\n scope: wire.scope ?? \"\",\n apiKey: wire.apiKey ?? accessToken,\n apiBaseUrl: wire.apiBaseUrl ?? trimSlash(options.issuer),\n user: wire.user ?? \"\",\n };\n}\n\nexport interface RevokeTokenOptions extends HttpOptions {\n issuer: string;\n clientId: string;\n clientSecret: string;\n /** The key to revoke. Only keys issued to this client are touched; an unknown key still succeeds. */\n token: string;\n /**\n * Bank consents to close in the same call, with the decrypted Enable Banking session id of each.\n * Validated before the key is revoked: a refusal leaves the key alive.\n */\n closeConsents?: { connectionId: string; ebSessionId: string }[];\n}\n\n/** RFC 7009 revocation. Resolves on 200; throws {@link OAuthError} on a client-authentication failure. */\nexport async function revokeToken(options: RevokeTokenOptions): Promise<void> {\n const body = new URLSearchParams({ token: options.token, token_type_hint: \"access_token\" });\n for (const c of options.closeConsents ?? []) {\n body.append(\"connection_id\", c.connectionId);\n body.append(\"eb_session_id\", c.ebSessionId);\n }\n const response = await post(\n endpoint(options.issuer, \"/oauth/revoke\"),\n body,\n {\n Authorization: basicAuth(options.clientId, options.clientSecret),\n },\n options,\n );\n await throwIfOAuthError(response);\n}\n\nexport interface UserinfoOptions extends HttpOptions {\n issuer: string;\n accessToken: string;\n}\n\nexport interface Userinfo {\n sub: string;\n email: string;\n partnerId: string | null;\n clientId: string | null;\n scope: string;\n expiresAt: string | null;\n}\n\ninterface UserinfoWire {\n sub: string;\n email: string;\n partner_id: string | null;\n client_id: string | null;\n scope: string;\n expires_at: string | null;\n}\n\n/** What a key reads for. Throws {@link OAuthError} with status 401 when the key is revoked or expired. */\nexport async function userinfo(options: UserinfoOptions): Promise<Userinfo> {\n const response = await request(\n endpoint(options.issuer, \"/oauth/userinfo\"),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${options.accessToken}`,\n Accept: \"application/json\",\n \"User-Agent\": USER_AGENT,\n },\n },\n options,\n );\n await throwIfOAuthError(response);\n const wire = (await response.json()) as UserinfoWire;\n return {\n sub: wire.sub,\n email: wire.email,\n partnerId: wire.partner_id ?? null,\n clientId: wire.client_id ?? null,\n scope: wire.scope,\n expiresAt: wire.expires_at ?? null,\n };\n}\n\n/** RFC 8414 metadata with the `open_banking_io` extension. */\nexport interface ServerMetadata {\n issuer: string;\n authorization_endpoint: string;\n token_endpoint: string;\n revocation_endpoint: string;\n scopes_supported: string[];\n response_types_supported: string[];\n response_modes_supported: string[];\n grant_types_supported: string[];\n token_endpoint_auth_methods_supported: string[];\n revocation_endpoint_auth_methods_supported?: string[];\n code_challenge_methods_supported: string[];\n authorization_response_iss_parameter_supported?: boolean;\n service_documentation?: string;\n open_banking_io: {\n userinfo_endpoint: string;\n api_base_url: string;\n api_key_header: string;\n bearer_supported: boolean;\n login_challenges_supported?: string[];\n key_relay: { response_mode: string; fields: string[] };\n /** The server accepts a partner-held decryption key (always true on current servers). */\n recipient_key_supported?: boolean;\n /** Every partner must hold one before it can register a client or start an authorization. */\n recipient_key_required?: boolean;\n documentation: string;\n };\n}\n\nconst discoveryCache = new Map<string, { metadata: ServerMetadata; expiresAt: number }>();\nconst DISCOVERY_TTL_MS = 60 * 60 * 1000;\n\n/** Fetches `/.well-known/oauth-authorization-server`, cached per issuer for an hour. */\nexport async function discover(issuer: string, options: HttpOptions = {}): Promise<ServerMetadata> {\n const key = trimSlash(issuer);\n const cached = discoveryCache.get(key);\n if (cached && cached.expiresAt > Date.now()) return cached.metadata;\n\n const response = await request(\n `${key}/.well-known/oauth-authorization-server`,\n {\n method: \"GET\",\n headers: { Accept: \"application/json\", \"User-Agent\": USER_AGENT },\n },\n options,\n );\n if (!response.ok)\n throw new OAuthError(response.status, \"discovery_failed\", `HTTP ${response.status}`);\n const metadata = (await response.json()) as ServerMetadata;\n if (typeof metadata.issuer !== \"string\" || trimSlash(metadata.issuer) !== key) {\n throw new OAuthError(\n response.status,\n \"discovery_failed\",\n `Issuer mismatch: ${String(metadata.issuer)}`,\n );\n }\n discoveryCache.set(key, { metadata, expiresAt: Date.now() + DISCOVERY_TTL_MS });\n return metadata;\n}\n\n/** The credentials bundle the data client reads with: the key plus the relayed private key. */\nexport function bundleFromToken(token: TokenResponse, privateKey: string): CredentialsBundle {\n return {\n service: \"open-banking.io\",\n apiBaseUrl: token.apiBaseUrl,\n user: token.user,\n apiKey: token.accessToken,\n encryptionKey: { scheme: \"ecdh-p256-hkdf-aes-256-gcm\", curve: \"P-256\", privateKey },\n };\n}\n\nfunction endpoint(issuer: string, path: string): string {\n return trimSlash(issuer) + path;\n}\n\nfunction trimSlash(value: string): string {\n let end = value.length;\n while (end > 0 && value[end - 1] === \"/\") end--;\n return value.slice(0, end);\n}\n\nfunction basicAuth(clientId: string, clientSecret: string): string {\n const pair = `${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`;\n return `Basic ${Buffer.from(pair, \"utf8\").toString(\"base64\")}`;\n}\n\nfunction constantTimeEqual(a: string, b: string): boolean {\n const x = createHash(\"sha256\").update(a, \"utf8\").digest();\n const y = createHash(\"sha256\").update(b, \"utf8\").digest();\n return timingSafeEqual(x, y) && a.length === b.length;\n}\n\nfunction toRecord(input: RelayInput): Record<string, unknown> {\n if (typeof input === \"string\") {\n const trimmed = input.trim();\n if (trimmed.startsWith(\"{\")) return JSON.parse(trimmed) as Record<string, unknown>;\n return Object.fromEntries(new URLSearchParams(trimmed));\n }\n if (input instanceof URLSearchParams) return Object.fromEntries(input);\n if (input instanceof FormData) {\n const record: Record<string, unknown> = {};\n input.forEach((value, name) => {\n if (typeof value === \"string\") record[name] = value;\n });\n return record;\n }\n return input;\n}\n\nasync function post(\n url: string,\n body: URLSearchParams,\n headers: Record<string, string>,\n options: HttpOptions,\n): Promise<Response> {\n return request(\n url,\n {\n method: \"POST\",\n headers: {\n ...headers,\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": USER_AGENT,\n },\n body: body.toString(),\n },\n options,\n );\n}\n\nasync function request(url: string, init: RequestInit, options: HttpOptions): Promise<Response> {\n const fetchImpl = options.fetch ?? fetch;\n return fetchImpl(url, {\n ...init,\n signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n });\n}\n\nasync function throwIfOAuthError(response: Response): Promise<void> {\n if (response.ok) return;\n let error = \"http_error\";\n let description: string | undefined = `HTTP ${response.status}`;\n try {\n const body = (await response.json()) as { error?: string; error_description?: string };\n if (body.error) {\n error = body.error;\n description = body.error_description;\n }\n } catch {\n // A non-JSON error body keeps the HTTP status as the description.\n }\n throw new OAuthError(response.status, error, description);\n}\n","{\n \"name\": \"@open-banking-io/client\",\n \"version\": \"2.0.0\",\n \"description\": \"Server-to-server client for open-banking.io: API-key auth + client-side decryption of the zero-knowledge data envelopes with your exported private key.\",\n \"type\": \"module\",\n \"license\": \"MIT\",\n \"author\": \"open-banking.io\",\n \"keywords\": [\n \"open-banking\",\n \"psd2\",\n \"zero-knowledge\",\n \"encryption\",\n \"fintech\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/open-banking-io/clients\"\n },\n \"engines\": {\n \"node\": \">=20\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n }\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"test\": \"vitest run\",\n \"coverage\": \"vitest run --coverage\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format:check\": \"prettier --check .\"\n },\n \"overrides\": {\n \"esbuild\": \"^0.28.1\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^10.0.1\",\n \"@types/node\": \"^26.6.6\",\n \"@vitest/coverage-v8\": \"^5.1.1\",\n \"eslint\": \"^10.5.0\",\n \"prettier\": \"^3.8.4\",\n \"tsup\": \"^9.0.0\",\n \"typescript\": \"^6.0.3\",\n \"typescript-eslint\": \"^8.61.1\",\n \"vitest\": \"^5.1.1\"\n },\n \"homepage\": \"https://open-banking.io\"\n}\n","// The package version, sourced from package.json so it can never drift. tsup inlines the JSON at\n// build time (tree-shaken to the single string), and vitest/tsx resolve the import directly — so\n// this stays ESM/CJS-safe without a runtime file read.\nimport pkg from \"../package.json\" with { type: \"json\" };\n\nexport const VERSION: string = pkg.version;\n\n/** The `User-Agent` sent on every request: `open-banking-io/node/<version>`. */\nexport const USER_AGENT = `open-banking-io/node/${VERSION}`;\n","import { bundleFromToken, type TokenResponse } from \"./connect.js\";\nimport { readFileSync } from \"node:fs\";\nimport { decryptTo, importPrivateKey, type CryptoKey } from \"./envelope.js\";\nimport { SyncError } from \"./errors.js\";\nimport { USER_AGENT } from \"./version.js\";\nimport type {\n Account,\n AccountEnc,\n AccountWire,\n BalanceEnc,\n Connection,\n ConnectionWire,\n CredentialsBundle,\n DisplayNameEnc,\n OpenBankingClientOptions,\n PsuHeaders,\n SyncAllResult,\n SyncAllResultWire,\n SyncFailure,\n SyncOptions,\n SyncResult,\n SyncResultWire,\n Transaction,\n TransactionEnc,\n TransactionPage,\n TransactionPageWire,\n TransactionQuery,\n TransactionWire,\n UidEnc,\n} from \"./models.js\";\n\n/**\n * Server-to-server client for open-banking.io. Authenticates with an API key (`X-Api-Key`) and\n * decrypts the zero-knowledge data envelopes locally with the exported private key — the service\n * only ever returns ciphertext it cannot read.\n */\nexport class OpenBankingClient {\n /** Default per-request timeout (30s) when {@link OpenBankingClientOptions.timeoutMs} is unset. */\n static readonly DEFAULT_TIMEOUT_MS = 30_000;\n\n private readonly baseUrl: string;\n private readonly apiKey: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly privateKey: Promise<CryptoKey>;\n\n constructor(options: OpenBankingClientOptions) {\n const { apiBaseUrl, apiKey, privateKeyPkcs8, timeoutMs } = options;\n if (!apiBaseUrl?.trim()) throw new Error(\"apiBaseUrl is required\");\n if (!apiKey?.trim()) throw new Error(\"apiKey is required\");\n if (!privateKeyPkcs8?.trim()) throw new Error(\"privateKeyPkcs8 is required\");\n\n // Strip all trailing \"/\" without a backtracking regex (avoids ReDoS on long inputs).\n let end = apiBaseUrl.length;\n while (end > 0 && apiBaseUrl.charCodeAt(end - 1) === 47 /* \"/\" */) end--;\n this.baseUrl = apiBaseUrl.slice(0, end);\n this.apiKey = apiKey;\n this.timeoutMs = timeoutMs ?? OpenBankingClient.DEFAULT_TIMEOUT_MS;\n this.fetchImpl = options.fetch ?? fetch;\n this.privateKey = importPrivateKey(privateKeyPkcs8);\n }\n\n /**\n * Builds a client from a credentials-bundle JSON string or a path to a bundle file.\n *\n * `overrides` (optional) lets the bundle path set the same transport knobs as the\n * constructor — e.g. a custom {@link OpenBankingClientOptions.fetch} or\n * {@link OpenBankingClientOptions.timeoutMs}.\n */\n static fromCredentials(\n jsonOrPath: string,\n overrides: Partial<Pick<OpenBankingClientOptions, \"fetch\" | \"timeoutMs\">> = {},\n ): OpenBankingClient {\n let json = jsonOrPath;\n if (!jsonOrPath.trimStart().startsWith(\"{\")) {\n json = readFileSync(jsonOrPath, \"utf8\");\n }\n const bundle = JSON.parse(json) as CredentialsBundle;\n return OpenBankingClient.fromBundle(bundle, overrides);\n }\n\n static fromBundle(\n bundle: CredentialsBundle,\n overrides: Partial<Pick<OpenBankingClientOptions, \"fetch\" | \"timeoutMs\">> = {},\n ): OpenBankingClient {\n if (!bundle.apiKey?.trim()) throw new Error(\"The credentials bundle has no apiKey\");\n return new OpenBankingClient({\n apiBaseUrl: bundle.apiBaseUrl,\n apiKey: bundle.apiKey,\n privateKeyPkcs8: bundle.encryptionKey.privateKey,\n timeoutMs: overrides.timeoutMs,\n fetch: overrides.fetch,\n });\n }\n\n /**\n * Builds a client from a Partner Connect token response and the private key the consent page\n * relayed — see {@link exchangeCode} and {@link parseRelay}.\n */\n static fromTokenResponse(\n token: TokenResponse,\n privateKey: string,\n overrides: Partial<Pick<OpenBankingClientOptions, \"fetch\" | \"timeoutMs\">> = {},\n ): OpenBankingClient {\n return OpenBankingClient.fromBundle(bundleFromToken(token, privateKey), overrides);\n }\n\n /** Lists the user's accounts with all sensitive fields decrypted. */\n async getAccounts(): Promise<Account[]> {\n const wires = await this.getAccountWires();\n return Promise.all(wires.map((w) => this.mapAccount(w)));\n }\n\n /** Returns a page of an account's statement, newest first, with decrypted fields. */\n async getTransactions(accountId: string, query: TransactionQuery = {}): Promise<TransactionPage> {\n const qs = new URLSearchParams();\n if (query.from != null) qs.set(\"from\", query.from);\n if (query.to != null) qs.set(\"to\", query.to);\n if (query.limit != null) qs.set(\"limit\", String(query.limit));\n if (query.offset != null) qs.set(\"offset\", String(query.offset));\n const suffix = qs.toString() ? `?${qs.toString()}` : \"\";\n\n const page = await this.getJson<TransactionPageWire>(\n `/api/accounts/${encodeURIComponent(accountId)}/transactions${suffix}`,\n );\n\n const items = await Promise.all((page.items ?? []).map((t) => this.mapTransaction(t)));\n return { items, total: page.total };\n }\n\n /** Lists the user's bank connections. */\n async getConnections(): Promise<Connection[]> {\n const wires = await this.getJson<ConnectionWire[]>(\"/api/connections\");\n return wires.map((c) => ({\n sessionId: c.sessionId,\n aspspName: c.aspspName,\n aspspCountry: c.aspspCountry,\n validUntil: c.validUntil,\n status: c.status,\n accountCount: c.accountCount,\n lastSyncedAt: c.lastSyncedAt ?? null,\n psuType: c.psuType ?? null,\n isLive: c.isLive ?? (c.status === \"Active\" && Date.parse(c.validUntil) > Date.now()),\n accountIds: c.accountIds ?? [],\n }));\n }\n\n /**\n * Triggers an online sync of one account: decrypts that account's Enable Banking uid and posts\n * it, so the service can fetch fresh data without ever holding the uid in plaintext.\n *\n * A refusal throws {@link SyncError}. A uid a renewal replaced (`uid_outdated`) is re-read and\n * retried once.\n */\n async sync(accountId: string, options: SyncOptions = {}): Promise<SyncResult> {\n for (let attempt = 0; ; attempt++) {\n const wires = await this.getAccountWires();\n const account = wires.find((a) => a.id === accountId);\n if (!account) throw new Error(`Account ${accountId} not found`);\n\n const uid = account.needsReconnect ? null : await this.decryptUid(account);\n if (uid == null) {\n throw new SyncError(\n \"Account has no active session (reconnect required) — cannot sync\",\n 409,\n \"reconnect_needed\",\n );\n }\n\n try {\n const result = await this.postJson<SyncResultWire>(\n `/api/accounts/${encodeURIComponent(accountId)}/sync`,\n { uid },\n psuHeaders(options.psu),\n );\n return { newTransactions: result.newTransactions, totalFetched: result.totalFetched };\n } catch (e) {\n if (attempt === 0 && e instanceof SyncError && e.reason === \"uid_outdated\") continue;\n throw e;\n }\n }\n }\n\n /**\n * Triggers an online sync of every account that has an active session. Per-account refusals are\n * in `failures`, and so is every account whose consent needs renewing (`reconnect_needed`, never\n * sent); accounts answering `uid_outdated` are re-read and retried once.\n */\n async syncAll(options: SyncOptions = {}): Promise<SyncAllResult> {\n const read = await this.syncItems();\n const first = await this.postSyncAll(read.items, options);\n first.failures.push(...read.lapsed);\n const outdated = new Set(\n first.failures.filter((f) => f.reason === \"uid_outdated\").map((f) => f.accountId),\n );\n if (outdated.size === 0) return first;\n\n const reread = await this.syncItems();\n const retryItems = reread.items.filter((i) => outdated.has(i.accountId));\n const lapsedNow = reread.lapsed.filter((f) => outdated.has(f.accountId));\n const settled = new Set([...retryItems, ...lapsedNow].map((i) => i.accountId));\n const kept = first.failures.filter((f) => !settled.has(f.accountId));\n if (retryItems.length === 0) return { ...first, failures: [...kept, ...lapsedNow] };\n\n const second = await this.postSyncAll(retryItems, options);\n return {\n accounts: first.accounts + second.accounts,\n newTransactions: first.newTransactions + second.newTransactions,\n failures: [...kept, ...lapsedNow, ...second.failures],\n };\n }\n\n // ---- internals ---------------------------------------------------------------------------------\n\n private getAccountWires(): Promise<AccountWire[]> {\n return this.getJson<AccountWire[]>(\"/api/accounts\");\n }\n\n private async syncItems(): Promise<{\n items: { accountId: string; uid: string }[];\n lapsed: SyncFailure[];\n }> {\n const wires = await this.getAccountWires();\n const decrypted = await Promise.all(\n wires.map(async (a) => ({\n accountId: a.id,\n needsReconnect: a.needsReconnect,\n uid: a.needsReconnect ? null : await this.decryptUid(a),\n })),\n );\n return {\n items: decrypted\n .filter((x): x is typeof x & { uid: string } => x.uid != null)\n .map((x) => ({ accountId: x.accountId, uid: x.uid })),\n lapsed: decrypted\n .filter((x) => x.uid == null && x.needsReconnect)\n .map((x) => ({ accountId: x.accountId, reason: \"reconnect_needed\", bankErrorCode: null })),\n };\n }\n\n private async postSyncAll(\n items: { accountId: string; uid: string }[],\n options: SyncOptions,\n ): Promise<SyncAllResult> {\n if (items.length === 0) return { accounts: 0, newTransactions: 0, failures: [] };\n const result = await this.postJson<SyncAllResultWire>(\n \"/api/sync\",\n { items },\n psuHeaders(options.psu),\n );\n const failures: SyncFailure[] = (result.failures ?? []).map((f) => ({\n accountId: f.accountId,\n reason: f.reason,\n bankErrorCode: f.bankErrorCode ?? null,\n }));\n return { accounts: result.accounts, newTransactions: result.newTransactions, failures };\n }\n\n private async decryptUid(a: AccountWire): Promise<string | null> {\n const dec = await decryptTo<UidEnc>(await this.privateKey, a.uidEnc);\n return dec?.uid ?? null;\n }\n\n private async mapAccount(a: AccountWire): Promise<Account> {\n const priv = await this.privateKey;\n const acc = await decryptTo<AccountEnc>(priv, a.enc);\n const name = await decryptTo<DisplayNameEnc>(priv, a.displayNameEnc);\n const balances = await Promise.all(\n (a.balances ?? []).map(async (b) => {\n const dec = await decryptTo<BalanceEnc>(priv, b.enc);\n return {\n type: b.type,\n name: dec?.name ?? null,\n amount: dec?.amount ?? \"0\",\n currency: b.currency,\n referenceDate: b.referenceDate ?? null,\n };\n }),\n );\n\n return {\n id: a.id,\n aspspName: a.aspspName,\n aspspCountry: a.aspspCountry,\n currency: a.currency,\n accountType: a.accountType ?? null,\n bic: a.bic ?? null,\n needsReconnect: a.needsReconnect,\n iban: acc?.iban ?? null,\n bban: acc?.bban ?? null,\n ownerName: acc?.ownerName ?? null,\n accountName: acc?.accountName ?? null,\n product: acc?.product ?? null,\n displayName: name?.displayName ?? null,\n balances,\n };\n }\n\n private async mapTransaction(t: TransactionWire): Promise<Transaction> {\n const d = await decryptTo<TransactionEnc>(await this.privateKey, t.enc);\n return {\n id: t.id,\n currency: t.currency,\n creditDebitIndicator: t.creditDebitIndicator,\n status: t.status ?? null,\n bookingDate: t.bookingDate ?? null,\n valueDate: t.valueDate ?? null,\n transactionDate: t.transactionDate ?? null,\n bankTransactionCode: t.bankTransactionCode ?? null,\n amount: d?.amount ?? \"0\",\n creditorName: d?.creditorName ?? null,\n creditorIban: d?.creditorIban ?? null,\n creditorBban: d?.creditorBban ?? null,\n creditorAgentBic: d?.creditorAgentBic ?? null,\n debtorName: d?.debtorName ?? null,\n debtorIban: d?.debtorIban ?? null,\n debtorBban: d?.debtorBban ?? null,\n debtorAgentBic: d?.debtorAgentBic ?? null,\n remittanceInformation: d?.remittanceInformation ?? null,\n note: d?.note ?? null,\n referenceNumber: d?.referenceNumber ?? null,\n exchangeRate: d?.exchangeRate ?? null,\n merchantCategoryCode: d?.merchantCategoryCode ?? null,\n balanceAfterTransaction: d?.balanceAfter ?? null,\n balanceAfterCurrency: d?.balanceAfterCurrency ?? null,\n };\n }\n\n private async getJson<T>(path: string): Promise<T> {\n const res = await this.fetchImpl(this.baseUrl + path, {\n headers: { \"X-Api-Key\": this.apiKey, \"User-Agent\": USER_AGENT },\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n if (!res.ok) {\n throw new Error(`GET ${path} failed: ${res.status} ${res.statusText}`);\n }\n return (await res.json()) as T;\n }\n\n private async postJson<T>(\n path: string,\n body: unknown,\n extraHeaders: Record<string, string> = {},\n ): Promise<T> {\n const res = await this.fetchImpl(this.baseUrl + path, {\n method: \"POST\",\n headers: {\n ...extraHeaders,\n \"X-Api-Key\": this.apiKey,\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n if (!res.ok) {\n const problem = await readProblem(res);\n const retryAfter = Number.parseInt(res.headers.get(\"Retry-After\") ?? \"\", 10);\n throw new SyncError(\n `POST ${path} failed: ${res.status} ${problem.reason ?? res.statusText}`,\n res.status,\n problem.reason,\n problem.bankErrorCode,\n Number.isFinite(retryAfter) ? retryAfter : null,\n );\n }\n return (await res.json()) as T;\n }\n}\n\nasync function readProblem(\n res: Response,\n): Promise<{ reason: string | null; bankErrorCode: string | null }> {\n try {\n const body = (await res.json()) as { reason?: unknown; bankErrorCode?: unknown };\n return {\n reason: typeof body.reason === \"string\" ? body.reason : null,\n bankErrorCode: typeof body.bankErrorCode === \"string\" ? body.bankErrorCode : null,\n };\n } catch {\n return { reason: null, bankErrorCode: null };\n }\n}\n\n/** The `X-Psu-*` request headers for a forwarded {@link PsuHeaders}; empty when none is given. */\nexport function psuHeaders(psu: PsuHeaders | undefined): Record<string, string> {\n if (!psu?.ipAddress || !psu.userAgent) return {};\n const headers: Record<string, string> = {\n \"X-Psu-Ip-Address\": psu.ipAddress,\n \"X-Psu-User-Agent\": psu.userAgent,\n };\n const optional: [string, string | undefined][] = [\n [\"X-Psu-Referer\", psu.referer],\n [\"X-Psu-Accept\", psu.accept],\n [\"X-Psu-Accept-Language\", psu.acceptLanguage],\n [\"X-Psu-Accept-Charset\", psu.acceptCharset],\n [\"X-Psu-Accept-Encoding\", psu.acceptEncoding],\n ];\n for (const [name, value] of optional) if (value) headers[name] = value;\n return headers;\n}\n","import { webcrypto } from \"node:crypto\";\n\nconst { subtle } = webcrypto;\n\n/** Re-export the WebCrypto key type so callers don't depend on the DOM lib. */\nexport type CryptoKey = webcrypto.CryptoKey;\n\nconst VERSION = 0x01;\nconst POINT_LEN = 65;\nconst NONCE_LEN = 12;\nconst TAG_LEN = 16;\n\nconst HKDF_INFO = new TextEncoder().encode(\"bank.core.ci/zk/v1\");\nconst HKDF_SALT = new Uint8Array(32); // 32 zero bytes (must be exactly this).\n\n/**\n * Decrypts open-banking.io's zero-knowledge data envelopes.\n * Scheme: ephemeral ECDH on NIST P-256 -> HKDF-SHA256 -> AES-256-GCM.\n * Wire: `version(1)=0x01 | ephemeralPublicKeyRaw(65) | nonce(12) | tag(16) | ciphertext`.\n * Only the user's private key can decrypt — the service stores ciphertext it cannot read.\n */\nexport async function decryptEnvelope(\n privateKey: CryptoKey,\n envelopeBase64: string,\n): Promise<Uint8Array> {\n const bytes = base64ToBytes(envelopeBase64);\n if (bytes.length < 1 + POINT_LEN + NONCE_LEN + TAG_LEN || bytes[0] !== VERSION) {\n throw new Error(\"Invalid or unsupported envelope\");\n }\n\n const ephPub = bytes.subarray(1, 1 + POINT_LEN);\n const nonce = bytes.subarray(1 + POINT_LEN, 1 + POINT_LEN + NONCE_LEN);\n const tag = bytes.subarray(1 + POINT_LEN + NONCE_LEN, 1 + POINT_LEN + NONCE_LEN + TAG_LEN);\n const ciphertext = bytes.subarray(1 + POINT_LEN + NONCE_LEN + TAG_LEN);\n\n // Guard against invalid-curve attacks: WebCrypto's P-256 `importKey` validates that the raw point\n // lies on the curve and is not the point at infinity, so a forged/off-curve ephemeral public key\n // throws here rather than yielding a derivable (and exploitable) shared secret below.\n const ephKey = await subtle.importKey(\n \"raw\",\n ephPub,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false,\n [],\n );\n\n const shared = new Uint8Array(\n await subtle.deriveBits({ name: \"ECDH\", public: ephKey }, privateKey, 256),\n );\n\n const hkdf = await subtle.importKey(\"raw\", shared, \"HKDF\", false, [\"deriveKey\"]);\n\n const aesKey = await subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: HKDF_SALT, info: HKDF_INFO },\n hkdf,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"decrypt\"],\n );\n\n // Web Crypto AES-GCM expects ciphertext||tag.\n const ctWithTag = new Uint8Array(ciphertext.length + tag.length);\n ctWithTag.set(ciphertext, 0);\n ctWithTag.set(tag, ciphertext.length);\n\n const plaintext = await subtle.decrypt(\n { name: \"AES-GCM\", iv: nonce, tagLength: 128 },\n aesKey,\n ctWithTag,\n );\n\n return new Uint8Array(plaintext);\n}\n\n/** Decrypts a base64 envelope and JSON-parses its payload. `null`/`undefined` in -> `null`. */\nexport async function decryptTo<T>(\n privateKey: CryptoKey,\n envelopeBase64: string | null | undefined,\n): Promise<T | null> {\n if (envelopeBase64 == null) return null;\n const plaintext = await decryptEnvelope(privateKey, envelopeBase64);\n return JSON.parse(new TextDecoder().decode(plaintext)) as T;\n}\n\n/** Imports a base64 PKCS#8 P-256 ECDH private key for use with {@link decryptEnvelope}. */\nexport async function importPrivateKey(pkcs8Base64: string): Promise<CryptoKey> {\n return subtle.importKey(\n \"pkcs8\",\n base64ToBytes(pkcs8Base64),\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false,\n [\"deriveBits\"],\n );\n}\n\nfunction base64ToBytes(b64: string): Uint8Array<ArrayBuffer> {\n return new Uint8Array(Buffer.from(b64, \"base64\"));\n}\n","import type { SyncFailureReason } from \"./models.js\";\n\n/** A sync the service refused. `reason` is the stable code to branch on. */\nexport class SyncError extends Error {\n readonly status: number;\n readonly reason: SyncFailureReason | null;\n readonly bankErrorCode: string | null;\n readonly retryAfterSeconds: number | null;\n\n constructor(\n message: string,\n status: number,\n reason: SyncFailureReason | null,\n bankErrorCode: string | null = null,\n retryAfterSeconds: number | null = null,\n ) {\n super(message);\n this.name = \"SyncError\";\n this.status = status;\n this.reason = reason;\n this.bankErrorCode = bankErrorCode;\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n","import { OAuthError, revokeToken, userinfo, type HttpOptions } from \"./connect.js\";\nimport { decryptTo, importPrivateKey } from \"./envelope.js\";\nimport type { OpenConsentWire, SessionIdEnc } from \"./models.js\";\nimport { USER_AGENT } from \"./version.js\";\n\nexport interface CloseReplacedConsentsOptions extends HttpOptions {\n issuer: string;\n clientId: string;\n clientSecret: string;\n /** The PREVIOUS key — the one issued before the renewal. It is revoked by this call. */\n token: string;\n /** The base64 PKCS#8 private key the consents are sealed to. */\n privateKey: string;\n /** Defaults to the issuer. */\n apiBaseUrl?: string;\n}\n\nexport interface CloseReplacedConsentsResult {\n /** Consents sent to be closed at the bank. */\n closed: number;\n /** Consents listed but not closable (no envelope, or it would not decrypt). */\n failed: number;\n /** Whether the previous key is gone. When false, revoke it yourself. */\n revoked: boolean;\n}\n\n/**\n * After a renewal: closes, at the bank, the consents the previous key still has open, and revokes\n * that key in the same call. Reads `GET /api/connections/open-consents` only — never the live\n * connections, which by now hold the renewal. A key that is already gone, or was issued to another\n * client, closes nothing: the service answers such a revoke with 200 without closing anything. A\n * failure that retrying may clear (5xx, 429) throws, so the key survives for a retry: revoking it\n * without the close would leave the consents open with nothing left that can list them.\n */\nexport async function closeReplacedConsents(\n options: CloseReplacedConsentsOptions,\n): Promise<CloseReplacedConsentsResult> {\n const fetchImpl = options.fetch ?? fetch;\n const base = trimSlash(options.apiBaseUrl ?? options.issuer);\n const nothing = { closed: 0, failed: 0, revoked: false };\n\n let owner: string | null;\n try {\n owner = (await userinfo({ ...options, accessToken: options.token })).clientId;\n } catch (e) {\n if (e instanceof OAuthError && keyRefused(e.status)) return nothing;\n throw e;\n }\n if (owner !== options.clientId) return nothing;\n\n const res = await fetchImpl(`${base}/api/connections/open-consents`, {\n headers: { \"X-Api-Key\": options.token, \"User-Agent\": USER_AGENT },\n signal: AbortSignal.timeout(options.timeoutMs ?? 30_000),\n });\n if (keyRefused(res.status)) return nothing;\n if (!res.ok) throw new Error(`GET /api/connections/open-consents failed: ${res.status}`);\n const open = (await res.json()) as OpenConsentWire[];\n\n const key = await importPrivateKey(options.privateKey);\n const closeConsents: { connectionId: string; ebSessionId: string }[] = [];\n const seen = new Set<string>();\n let failed = 0;\n for (const c of open) {\n if (!c.connectionId || seen.has(c.connectionId)) continue;\n seen.add(c.connectionId);\n if (!c.sessionIdEnc) {\n failed += 1;\n continue;\n }\n let sessionId: string | null | undefined;\n try {\n sessionId = (await decryptTo<SessionIdEnc>(key, c.sessionIdEnc))?.sessionId;\n } catch {\n sessionId = null;\n }\n if (!sessionId) {\n failed += 1;\n continue;\n }\n closeConsents.push({ connectionId: c.connectionId, ebSessionId: sessionId });\n }\n\n try {\n await revokeToken({ ...options, closeConsents });\n } catch (e) {\n if (e instanceof OAuthError && e.status < 500 && e.status !== 429)\n return { closed: 0, failed: failed + closeConsents.length, revoked: false };\n throw e;\n }\n return { closed: closeConsents.length, failed, revoked: true };\n}\n\nconst keyRefused = (status: number) => status === 401 || status === 403;\n\nfunction trimSlash(url: string): string {\n let end = url.length;\n while (end > 0 && url.charCodeAt(end - 1) === 47) end--;\n return url.slice(0, end);\n}\n","import { createHash, webcrypto } from \"node:crypto\";\nimport { decryptTo, importPrivateKey } from \"./envelope.js\";\n\nconst subtle = webcrypto.subtle;\n\n/** A partner's recipient (decryption) key pair. The private half is a credential: never log it. */\nexport interface RecipientKeyPair {\n /** Base64 PKCS#8 — what your deployment loads. */\n privateKeyPkcs8Base64: string;\n /** Base64 raw 65-byte uncompressed P-256 point — what you install on your partner page. */\n publicKeyRawBase64: string;\n}\n\n/**\n * Generates the P-256 pair a partner installs on open-banking.io. The public half goes into\n * `PUT /api/partner/recipient-key` (or the partner page's paste box); keep the private half\n * where your deployment can read it — the service never sees it and cannot recover it.\n */\nexport async function generateRecipientKeyPair(): Promise<RecipientKeyPair> {\n const pair = await subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-256\" }, true, [\n \"deriveBits\",\n ]);\n return {\n privateKeyPkcs8Base64: Buffer.from(await subtle.exportKey(\"pkcs8\", pair.privateKey)).toString(\n \"base64\",\n ),\n publicKeyRawBase64: Buffer.from(await subtle.exportKey(\"raw\", pair.publicKey)).toString(\n \"base64\",\n ),\n };\n}\n\n/**\n * The fingerprint the partner page and the admin show for a key: SHA-256 of the raw 65-byte\n * point, lowercase hex, first 16 characters. Print it at boot and compare after every deploy.\n */\nexport function recipientKeyFingerprint(publicKeyRawBase64: string): string {\n return createHash(\"sha256\")\n .update(Buffer.from(publicKeyRawBase64, \"base64\"))\n .digest(\"hex\")\n .slice(0, 16);\n}\n\n/** The raw public point of a PKCS#8 private key — to fingerprint or re-install the key you hold. */\nexport async function recipientPublicKey(privateKeyPkcs8Base64: string): Promise<string> {\n const key = await subtle.importKey(\n \"pkcs8\",\n Buffer.from(privateKeyPkcs8Base64, \"base64\"),\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"],\n );\n const jwk = await subtle.exportKey(\"jwk\", key);\n if (!jwk.x || !jwk.y) throw new Error(\"The private key carries no public point\");\n return Buffer.concat([\n Buffer.from([0x04]),\n Buffer.from(jwk.x, \"base64url\"),\n Buffer.from(jwk.y, \"base64url\"),\n ]).toString(\"base64\");\n}\n\n/**\n * Answers the possession challenge from `POST /api/partner/recipient-key/challenge`: opens\n * the envelope with the private half and returns the nonce — the `challengeAnswer` for the install.\n */\nexport async function answerRecipientKeyChallenge(\n privateKeyPkcs8Base64: string,\n envelopeBase64: string,\n): Promise<string> {\n const payload = await decryptTo<{ nonce?: unknown }>(\n await importPrivateKey(privateKeyPkcs8Base64),\n envelopeBase64,\n );\n const nonce = payload?.nonce;\n if (typeof nonce !== \"string\" || nonce.length === 0)\n throw new Error(\"The challenge envelope carries no nonce\");\n return nonce;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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imSlash","import_node_crypto","subtle"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -509,4 +509,5 @@ declare function recipientPublicKey(privateKeyPkcs8Base64: string): Promise<stri
|
|
|
509
509
|
*/
|
|
510
510
|
declare function answerRecipientKeyChallenge(privateKeyPkcs8Base64: string, envelopeBase64: string): Promise<string>;
|
|
511
511
|
|
|
512
|
-
export {
|
|
512
|
+
export { CONNECT_RELAY_FIELDS, OAuthError, OpenBankingClient, PARTNER_KEY_MISSING_DESCRIPTION, PARTNER_SUSPENDED_DESCRIPTION, RelayError, SyncError, answerRecipientKeyChallenge, buildAuthorizeUrl, bundleFromToken, closeReplacedConsents, createPkce, createState, decryptEnvelope, decryptTo, discover, exchangeCode, generateRecipientKeyPair, importPrivateKey, parseRelay, pkceChallenge, psuHeaders, recipientKeyFingerprint, recipientPublicKey, revokeToken, userinfo };
|
|
513
|
+
export type { Account, AuthorizeUrlOptions, Balance, CloseReplacedConsentsOptions, CloseReplacedConsentsResult, ConnectRelay, Connection, CredentialsBundle, EncryptionKey, ExchangeCodeOptions, HttpOptions, OpenBankingClientOptions, ParseRelayOptions, Pkce, PsuHeaders, RecipientKeyPair, RelayErrorCode, RelayInput, RelayRefusalReason, RevokeTokenOptions, ServerMetadata, SyncAllResult, SyncFailure, SyncFailureReason, SyncOptions, SyncResult, TokenResponse, Transaction, TransactionPage, TransactionQuery, Userinfo, UserinfoOptions };
|
package/dist/index.d.ts
CHANGED
|
@@ -509,4 +509,5 @@ declare function recipientPublicKey(privateKeyPkcs8Base64: string): Promise<stri
|
|
|
509
509
|
*/
|
|
510
510
|
declare function answerRecipientKeyChallenge(privateKeyPkcs8Base64: string, envelopeBase64: string): Promise<string>;
|
|
511
511
|
|
|
512
|
-
export {
|
|
512
|
+
export { CONNECT_RELAY_FIELDS, OAuthError, OpenBankingClient, PARTNER_KEY_MISSING_DESCRIPTION, PARTNER_SUSPENDED_DESCRIPTION, RelayError, SyncError, answerRecipientKeyChallenge, buildAuthorizeUrl, bundleFromToken, closeReplacedConsents, createPkce, createState, decryptEnvelope, decryptTo, discover, exchangeCode, generateRecipientKeyPair, importPrivateKey, parseRelay, pkceChallenge, psuHeaders, recipientKeyFingerprint, recipientPublicKey, revokeToken, userinfo };
|
|
513
|
+
export type { Account, AuthorizeUrlOptions, Balance, CloseReplacedConsentsOptions, CloseReplacedConsentsResult, ConnectRelay, Connection, CredentialsBundle, EncryptionKey, ExchangeCodeOptions, HttpOptions, OpenBankingClientOptions, ParseRelayOptions, Pkce, PsuHeaders, RecipientKeyPair, RelayErrorCode, RelayInput, RelayRefusalReason, RevokeTokenOptions, ServerMetadata, SyncAllResult, SyncFailure, SyncFailureReason, SyncOptions, SyncResult, TokenResponse, Transaction, TransactionPage, TransactionQuery, Userinfo, UserinfoOptions };
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import { createHash, randomBytes, timingSafeEqual } from "crypto";
|
|
|
4
4
|
// package.json
|
|
5
5
|
var package_default = {
|
|
6
6
|
name: "@open-banking-io/client",
|
|
7
|
-
version: "
|
|
7
|
+
version: "2.0.0",
|
|
8
8
|
description: "Server-to-server client for open-banking.io: API-key auth + client-side decryption of the zero-knowledge data envelopes with your exported private key.",
|
|
9
9
|
type: "module",
|
|
10
10
|
license: "MIT",
|
|
@@ -50,14 +50,14 @@ var package_default = {
|
|
|
50
50
|
},
|
|
51
51
|
devDependencies: {
|
|
52
52
|
"@eslint/js": "^10.0.1",
|
|
53
|
-
"@types/node": "^
|
|
54
|
-
"@vitest/coverage-v8": "^
|
|
53
|
+
"@types/node": "^26.6.6",
|
|
54
|
+
"@vitest/coverage-v8": "^5.1.1",
|
|
55
55
|
eslint: "^10.5.0",
|
|
56
56
|
prettier: "^3.8.4",
|
|
57
|
-
tsup: "^
|
|
57
|
+
tsup: "^9.0.0",
|
|
58
58
|
typescript: "^6.0.3",
|
|
59
59
|
"typescript-eslint": "^8.61.1",
|
|
60
|
-
vitest: "^
|
|
60
|
+
vitest: "^5.1.1"
|
|
61
61
|
},
|
|
62
62
|
homepage: "https://open-banking.io"
|
|
63
63
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/connect.ts","../package.json","../src/version.ts","../src/client.ts","../src/envelope.ts","../src/errors.ts","../src/consents.ts","../src/recipientKey.ts"],"sourcesContent":["// Partner Connect: the OAuth 2.0 authorization-code flow (PKCE, form_post) that hands a partner an\n// API key and the user's private key. Documented at https://open-banking.io/en/docs/partners.\nimport { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport type { CredentialsBundle } from \"./models.js\";\nimport { USER_AGENT } from \"./version.js\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/** The relay fields the consent page form-posts to a redirect URI, in wire order. */\nexport const CONNECT_RELAY_FIELDS = [\"code\", \"state\", \"iss\", \"privateKey\", \"publicKey\"] as const;\n\nexport interface Pkce {\n /** The `code_verifier` to keep server-side and send on the token request. */\n verifier: string;\n /** The `code_challenge` to send on the authorize request. */\n challenge: string;\n method: \"S256\";\n}\n\n/** A fresh PKCE pair (RFC 7636): 32 random bytes, base64url, S256 challenge. */\nexport function createPkce(): Pkce {\n const verifier = randomBytes(32).toString(\"base64url\");\n return { verifier, challenge: pkceChallenge(verifier), method: \"S256\" };\n}\n\n/** The S256 challenge for a verifier — exposed so a stored verifier can be re-checked. */\nexport function pkceChallenge(verifier: string): string {\n return createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\n/** A fresh opaque `state` (16 random bytes, base64url). */\nexport function createState(): string {\n return randomBytes(16).toString(\"base64url\");\n}\n\nexport interface AuthorizeUrlOptions {\n /** The issuer, e.g. `https://open-banking.io`. */\n issuer: string;\n clientId: string;\n /** One of the client's registered redirect URIs, character for character. */\n redirectUri: string;\n state: string;\n /** From {@link createPkce}. */\n codeChallenge: string;\n /** Defaults to `accounts.read`, the only scope. */\n scope?: string;\n /** Prefills the email on the login page; never authenticates. */\n loginHint?: string;\n /** `pin_code` keeps a popup journey inside the popup (typed emailed code instead of a magic link). */\n challenge?: \"pin_code\";\n /** Space-separated locales; the first one the server publishes forces the language of every screen. */\n uiLocales?: string;\n /**\n * A connection's `sessionId` to renew: the user goes straight to that bank, whether its consent\n * is still live or has lapsed.\n */\n renewConnection?: string;\n}\n\n/** The `/oauth/authorize` URL for a top-level browser navigation. */\nexport function buildAuthorizeUrl(options: AuthorizeUrlOptions): string {\n const params = new URLSearchParams({\n response_type: \"code\",\n client_id: options.clientId,\n redirect_uri: options.redirectUri,\n scope: options.scope ?? \"accounts.read\",\n state: options.state,\n code_challenge: options.codeChallenge,\n code_challenge_method: \"S256\",\n response_mode: \"form_post\",\n });\n if (options.loginHint) params.set(\"login_hint\", options.loginHint);\n if (options.challenge) params.set(\"challenge\", options.challenge);\n if (options.uiLocales) params.set(\"ui_locales\", options.uiLocales);\n if (options.renewConnection) params.set(\"renew_connection\", options.renewConnection);\n return `${endpoint(options.issuer, \"/oauth/authorize\")}?${params.toString()}`;\n}\n\n/** What the consent page relayed to the redirect URI. */\nexport interface ConnectRelay {\n code: string;\n state: string;\n /** Present on current servers (RFC 9207); empty string from older ones. */\n iss: string;\n /** The user's base64 PKCS#8 private key. A credential: never log it. */\n privateKey: string;\n publicKey: string;\n}\n\nexport type RelayErrorCode =\n | \"access_denied\"\n | \"oauth_error\"\n | \"state_mismatch\"\n | \"issuer_mismatch\"\n | \"missing_code\"\n | \"missing_private_key\";\n\n/** The `error_description` the server relays when the partner has not installed its decryption key. */\nexport const PARTNER_KEY_MISSING_DESCRIPTION =\n \"this partner has not installed its decryption key; no authorizations can be started until it does\";\n/** The `error_description` the server relays while the partner is suspended. */\nexport const PARTNER_SUSPENDED_DESCRIPTION =\n \"this partner is suspended; no authorizations can be started\";\n\n/**\n * Why a `temporarily_unavailable` was relayed, when the server said so in the pinned words. Both\n * are on your side, not the bank's: install the key on your partner page, or write to us.\n */\nexport type RelayRefusalReason = \"partner_key_missing\" | \"partner_suspended\";\n\nfunction refusalReason(error: string, description: string): RelayRefusalReason | undefined {\n if (error !== \"temporarily_unavailable\") return undefined;\n if (description === PARTNER_KEY_MISSING_DESCRIPTION) return \"partner_key_missing\";\n if (description === PARTNER_SUSPENDED_DESCRIPTION) return \"partner_suspended\";\n return undefined;\n}\n\n/**\n * Thrown by {@link parseRelay}. `code` says why: `access_denied` is the user pressing \"Back to the\n * partner\" or declining (a normal outcome), `oauth_error` any other error the server relayed (the\n * fields are attached), the rest are validation failures on your side.\n */\nexport class RelayError extends Error {\n readonly code: RelayErrorCode;\n readonly error?: string;\n readonly errorDescription?: string;\n /** Set on an `oauth_error` whose description names a partner-side refusal. */\n readonly reason?: RelayRefusalReason;\n\n constructor(\n code: RelayErrorCode,\n message: string,\n oauth?: { error: string; errorDescription?: string },\n ) {\n super(message);\n this.name = \"RelayError\";\n this.code = code;\n this.error = oauth?.error;\n this.errorDescription = oauth?.errorDescription;\n this.reason = oauth ? refusalReason(oauth.error, oauth.errorDescription ?? \"\") : undefined;\n }\n}\n\nexport interface ParseRelayOptions {\n /** The `state` this flow was started with. Compared in constant time. */\n expectedState: string;\n /** When set, `iss` must equal it (trailing slashes ignored). */\n issuer?: string;\n /** Require `iss` to be present even when `issuer` is not checked. Default: only when `issuer` is set. */\n requireIss?: boolean;\n /**\n * Whether the relay must carry the user's private key. A partner that installed its own\n * decryption key receives `privateKey=\"\"` for every user who connected under it and decrypts\n * with that key instead — pass `\"optional\"`. Default `\"required\"`, the 1.1.0 behaviour.\n */\n expectPrivateKey?: \"required\" | \"optional\";\n}\n\n/** A form body, `URLSearchParams`, parsed body object, or JSON string. */\nexport type RelayInput = string | URLSearchParams | FormData | Record<string, unknown>;\n\n/**\n * Validates the form_post relay: `state` (constant time) and `iss` first, so a relayed error is only\n * honoured for this flow from this issuer; then an OAuth error becomes a {@link RelayError}, and\n * `code` and `privateKey` are checked.\n */\nexport function parseRelay(input: RelayInput, options: ParseRelayOptions): ConnectRelay {\n const fields = toRecord(input);\n const read = (name: string): string => {\n const value = fields[name];\n return typeof value === \"string\" ? value : \"\";\n };\n\n if (!options.expectedState || !constantTimeEqual(read(\"state\"), options.expectedState)) {\n throw new RelayError(\"state_mismatch\", \"The relayed state does not match this flow\");\n }\n\n const iss = read(\"iss\");\n const wantIss = options.issuer !== undefined || options.requireIss === true;\n if (wantIss && !iss) throw new RelayError(\"issuer_mismatch\", \"The relay carries no iss\");\n if (\n options.issuer !== undefined &&\n !constantTimeEqual(trimSlash(iss), trimSlash(options.issuer))\n ) {\n throw new RelayError(\"issuer_mismatch\", \"The relayed iss is not the expected issuer\");\n }\n\n const error = read(\"error\");\n if (error) {\n const description = read(\"error_description\");\n throw new RelayError(\n error === \"access_denied\" ? \"access_denied\" : \"oauth_error\",\n description ? `${error}: ${description}` : error,\n {\n error,\n errorDescription: description || undefined,\n },\n );\n }\n\n const code = read(\"code\");\n if (!code) throw new RelayError(\"missing_code\", \"The relay carries no authorization code\");\n const privateKey = read(\"privateKey\");\n if (!privateKey && (options.expectPrivateKey ?? \"required\") === \"required\") {\n throw new RelayError(\"missing_private_key\", \"The relay carries no private key\");\n }\n\n return { code, state: read(\"state\"), iss, privateKey, publicKey: read(\"publicKey\") };\n}\n\n/** An RFC 6749 §5.2 error body from the token or revocation endpoint. */\nexport class OAuthError extends Error {\n readonly status: number;\n readonly error: string;\n readonly errorDescription?: string;\n\n constructor(status: number, error: string, errorDescription?: string) {\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = \"OAuthError\";\n this.status = status;\n this.error = error;\n this.errorDescription = errorDescription;\n }\n}\n\nexport interface HttpOptions {\n /** Custom `fetch`, e.g. for tests. Defaults to the global. */\n fetch?: typeof globalThis.fetch;\n /** Per-request timeout; defaults to 30s. */\n timeoutMs?: number;\n}\n\nexport interface ExchangeCodeOptions extends HttpOptions {\n issuer: string;\n clientId: string;\n clientSecret: string;\n /** From the relay. */\n code: string;\n /** From {@link createPkce}, kept server-side. */\n codeVerifier: string;\n /** The redirect URI used on the authorize request; sent when given and must match. */\n redirectUri?: string;\n}\n\n/** The token endpoint's response. `accessToken` and `apiKey` are the same key. */\nexport interface TokenResponse {\n accessToken: string;\n tokenType: string;\n expiresIn: number;\n scope: string;\n apiKey: string;\n apiBaseUrl: string;\n /** The tenant subject the key reads for. */\n user: string;\n}\n\ninterface TokenResponseWire {\n access_token?: string;\n token_type?: string;\n expires_in?: number;\n scope?: string;\n apiKey?: string;\n apiBaseUrl?: string;\n user?: string;\n}\n\n/** Exchanges the relayed code for the key, server to server, with HTTP Basic client authentication. */\nexport async function exchangeCode(options: ExchangeCodeOptions): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: \"authorization_code\",\n code: options.code,\n code_verifier: options.codeVerifier,\n });\n if (options.redirectUri) body.set(\"redirect_uri\", options.redirectUri);\n\n const response = await post(\n endpoint(options.issuer, \"/oauth/token\"),\n body,\n {\n Authorization: basicAuth(options.clientId, options.clientSecret),\n Accept: \"application/json\",\n },\n options,\n );\n await throwIfOAuthError(response);\n\n const wire = (await response.json()) as TokenResponseWire;\n const accessToken = wire.access_token ?? wire.apiKey;\n if (!accessToken)\n throw new OAuthError(\n response.status,\n \"invalid_response\",\n \"The token response carries no access token\",\n );\n return {\n accessToken,\n tokenType: wire.token_type ?? \"Bearer\",\n expiresIn: wire.expires_in ?? 0,\n scope: wire.scope ?? \"\",\n apiKey: wire.apiKey ?? accessToken,\n apiBaseUrl: wire.apiBaseUrl ?? trimSlash(options.issuer),\n user: wire.user ?? \"\",\n };\n}\n\nexport interface RevokeTokenOptions extends HttpOptions {\n issuer: string;\n clientId: string;\n clientSecret: string;\n /** The key to revoke. Only keys issued to this client are touched; an unknown key still succeeds. */\n token: string;\n /**\n * Bank consents to close in the same call, with the decrypted Enable Banking session id of each.\n * Validated before the key is revoked: a refusal leaves the key alive.\n */\n closeConsents?: { connectionId: string; ebSessionId: string }[];\n}\n\n/** RFC 7009 revocation. Resolves on 200; throws {@link OAuthError} on a client-authentication failure. */\nexport async function revokeToken(options: RevokeTokenOptions): Promise<void> {\n const body = new URLSearchParams({ token: options.token, token_type_hint: \"access_token\" });\n for (const c of options.closeConsents ?? []) {\n body.append(\"connection_id\", c.connectionId);\n body.append(\"eb_session_id\", c.ebSessionId);\n }\n const response = await post(\n endpoint(options.issuer, \"/oauth/revoke\"),\n body,\n {\n Authorization: basicAuth(options.clientId, options.clientSecret),\n },\n options,\n );\n await throwIfOAuthError(response);\n}\n\nexport interface UserinfoOptions extends HttpOptions {\n issuer: string;\n accessToken: string;\n}\n\nexport interface Userinfo {\n sub: string;\n email: string;\n partnerId: string | null;\n clientId: string | null;\n scope: string;\n expiresAt: string | null;\n}\n\ninterface UserinfoWire {\n sub: string;\n email: string;\n partner_id: string | null;\n client_id: string | null;\n scope: string;\n expires_at: string | null;\n}\n\n/** What a key reads for. Throws {@link OAuthError} with status 401 when the key is revoked or expired. */\nexport async function userinfo(options: UserinfoOptions): Promise<Userinfo> {\n const response = await request(\n endpoint(options.issuer, \"/oauth/userinfo\"),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${options.accessToken}`,\n Accept: \"application/json\",\n \"User-Agent\": USER_AGENT,\n },\n },\n options,\n );\n await throwIfOAuthError(response);\n const wire = (await response.json()) as UserinfoWire;\n return {\n sub: wire.sub,\n email: wire.email,\n partnerId: wire.partner_id ?? null,\n clientId: wire.client_id ?? null,\n scope: wire.scope,\n expiresAt: wire.expires_at ?? null,\n };\n}\n\n/** RFC 8414 metadata with the `open_banking_io` extension. */\nexport interface ServerMetadata {\n issuer: string;\n authorization_endpoint: string;\n token_endpoint: string;\n revocation_endpoint: string;\n scopes_supported: string[];\n response_types_supported: string[];\n response_modes_supported: string[];\n grant_types_supported: string[];\n token_endpoint_auth_methods_supported: string[];\n revocation_endpoint_auth_methods_supported?: string[];\n code_challenge_methods_supported: string[];\n authorization_response_iss_parameter_supported?: boolean;\n service_documentation?: string;\n open_banking_io: {\n userinfo_endpoint: string;\n api_base_url: string;\n api_key_header: string;\n bearer_supported: boolean;\n login_challenges_supported?: string[];\n key_relay: { response_mode: string; fields: string[] };\n /** The server accepts a partner-held decryption key (always true on current servers). */\n recipient_key_supported?: boolean;\n /** Every partner must hold one before it can register a client or start an authorization. */\n recipient_key_required?: boolean;\n documentation: string;\n };\n}\n\nconst discoveryCache = new Map<string, { metadata: ServerMetadata; expiresAt: number }>();\nconst DISCOVERY_TTL_MS = 60 * 60 * 1000;\n\n/** Fetches `/.well-known/oauth-authorization-server`, cached per issuer for an hour. */\nexport async function discover(issuer: string, options: HttpOptions = {}): Promise<ServerMetadata> {\n const key = trimSlash(issuer);\n const cached = discoveryCache.get(key);\n if (cached && cached.expiresAt > Date.now()) return cached.metadata;\n\n const response = await request(\n `${key}/.well-known/oauth-authorization-server`,\n {\n method: \"GET\",\n headers: { Accept: \"application/json\", \"User-Agent\": USER_AGENT },\n },\n options,\n );\n if (!response.ok)\n throw new OAuthError(response.status, \"discovery_failed\", `HTTP ${response.status}`);\n const metadata = (await response.json()) as ServerMetadata;\n if (typeof metadata.issuer !== \"string\" || trimSlash(metadata.issuer) !== key) {\n throw new OAuthError(\n response.status,\n \"discovery_failed\",\n `Issuer mismatch: ${String(metadata.issuer)}`,\n );\n }\n discoveryCache.set(key, { metadata, expiresAt: Date.now() + DISCOVERY_TTL_MS });\n return metadata;\n}\n\n/** The credentials bundle the data client reads with: the key plus the relayed private key. */\nexport function bundleFromToken(token: TokenResponse, privateKey: string): CredentialsBundle {\n return {\n service: \"open-banking.io\",\n apiBaseUrl: token.apiBaseUrl,\n user: token.user,\n apiKey: token.accessToken,\n encryptionKey: { scheme: \"ecdh-p256-hkdf-aes-256-gcm\", curve: \"P-256\", privateKey },\n };\n}\n\nfunction endpoint(issuer: string, path: string): string {\n return trimSlash(issuer) + path;\n}\n\nfunction trimSlash(value: string): string {\n let end = value.length;\n while (end > 0 && value[end - 1] === \"/\") end--;\n return value.slice(0, end);\n}\n\nfunction basicAuth(clientId: string, clientSecret: string): string {\n const pair = `${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`;\n return `Basic ${Buffer.from(pair, \"utf8\").toString(\"base64\")}`;\n}\n\nfunction constantTimeEqual(a: string, b: string): boolean {\n const x = createHash(\"sha256\").update(a, \"utf8\").digest();\n const y = createHash(\"sha256\").update(b, \"utf8\").digest();\n return timingSafeEqual(x, y) && a.length === b.length;\n}\n\nfunction toRecord(input: RelayInput): Record<string, unknown> {\n if (typeof input === \"string\") {\n const trimmed = input.trim();\n if (trimmed.startsWith(\"{\")) return JSON.parse(trimmed) as Record<string, unknown>;\n return Object.fromEntries(new URLSearchParams(trimmed));\n }\n if (input instanceof URLSearchParams) return Object.fromEntries(input);\n if (input instanceof FormData) {\n const record: Record<string, unknown> = {};\n input.forEach((value, name) => {\n if (typeof value === \"string\") record[name] = value;\n });\n return record;\n }\n return input;\n}\n\nasync function post(\n url: string,\n body: URLSearchParams,\n headers: Record<string, string>,\n options: HttpOptions,\n): Promise<Response> {\n return request(\n url,\n {\n method: \"POST\",\n headers: {\n ...headers,\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": USER_AGENT,\n },\n body: body.toString(),\n },\n options,\n );\n}\n\nasync function request(url: string, init: RequestInit, options: HttpOptions): Promise<Response> {\n const fetchImpl = options.fetch ?? fetch;\n return fetchImpl(url, {\n ...init,\n signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n });\n}\n\nasync function throwIfOAuthError(response: Response): Promise<void> {\n if (response.ok) return;\n let error = \"http_error\";\n let description: string | undefined = `HTTP ${response.status}`;\n try {\n const body = (await response.json()) as { error?: string; error_description?: string };\n if (body.error) {\n error = body.error;\n description = body.error_description;\n }\n } catch {\n // A non-JSON error body keeps the HTTP status as the description.\n }\n throw new OAuthError(response.status, error, description);\n}\n","{\n \"name\": \"@open-banking-io/client\",\n \"version\": \"1.3.0\",\n \"description\": \"Server-to-server client for open-banking.io: API-key auth + client-side decryption of the zero-knowledge data envelopes with your exported private key.\",\n \"type\": \"module\",\n \"license\": \"MIT\",\n \"author\": \"open-banking.io\",\n \"keywords\": [\n \"open-banking\",\n \"psd2\",\n \"zero-knowledge\",\n \"encryption\",\n \"fintech\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/open-banking-io/clients\"\n },\n \"engines\": {\n \"node\": \">=20\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n }\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"test\": \"vitest run\",\n \"coverage\": \"vitest run --coverage\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format:check\": \"prettier --check .\"\n },\n \"overrides\": {\n \"esbuild\": \"^0.28.1\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^10.0.1\",\n \"@types/node\": \"^25.9.3\",\n \"@vitest/coverage-v8\": \"^4.1.9\",\n \"eslint\": \"^10.5.0\",\n \"prettier\": \"^3.8.4\",\n \"tsup\": \"^8.5.1\",\n \"typescript\": \"^6.0.3\",\n \"typescript-eslint\": \"^8.61.1\",\n \"vitest\": \"^4.1.9\"\n },\n \"homepage\": \"https://open-banking.io\"\n}\n","// The package version, sourced from package.json so it can never drift. tsup inlines the JSON at\n// build time (tree-shaken to the single string), and vitest/tsx resolve the import directly — so\n// this stays ESM/CJS-safe without a runtime file read.\nimport pkg from \"../package.json\" with { type: \"json\" };\n\nexport const VERSION: string = pkg.version;\n\n/** The `User-Agent` sent on every request: `open-banking-io/node/<version>`. */\nexport const USER_AGENT = `open-banking-io/node/${VERSION}`;\n","import { bundleFromToken, type TokenResponse } from \"./connect.js\";\nimport { readFileSync } from \"node:fs\";\nimport { decryptTo, importPrivateKey, type CryptoKey } from \"./envelope.js\";\nimport { SyncError } from \"./errors.js\";\nimport { USER_AGENT } from \"./version.js\";\nimport type {\n Account,\n AccountEnc,\n AccountWire,\n BalanceEnc,\n Connection,\n ConnectionWire,\n CredentialsBundle,\n DisplayNameEnc,\n OpenBankingClientOptions,\n PsuHeaders,\n SyncAllResult,\n SyncAllResultWire,\n SyncFailure,\n SyncOptions,\n SyncResult,\n SyncResultWire,\n Transaction,\n TransactionEnc,\n TransactionPage,\n TransactionPageWire,\n TransactionQuery,\n TransactionWire,\n UidEnc,\n} from \"./models.js\";\n\n/**\n * Server-to-server client for open-banking.io. Authenticates with an API key (`X-Api-Key`) and\n * decrypts the zero-knowledge data envelopes locally with the exported private key — the service\n * only ever returns ciphertext it cannot read.\n */\nexport class OpenBankingClient {\n /** Default per-request timeout (30s) when {@link OpenBankingClientOptions.timeoutMs} is unset. */\n static readonly DEFAULT_TIMEOUT_MS = 30_000;\n\n private readonly baseUrl: string;\n private readonly apiKey: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly privateKey: Promise<CryptoKey>;\n\n constructor(options: OpenBankingClientOptions) {\n const { apiBaseUrl, apiKey, privateKeyPkcs8, timeoutMs } = options;\n if (!apiBaseUrl?.trim()) throw new Error(\"apiBaseUrl is required\");\n if (!apiKey?.trim()) throw new Error(\"apiKey is required\");\n if (!privateKeyPkcs8?.trim()) throw new Error(\"privateKeyPkcs8 is required\");\n\n // Strip all trailing \"/\" without a backtracking regex (avoids ReDoS on long inputs).\n let end = apiBaseUrl.length;\n while (end > 0 && apiBaseUrl.charCodeAt(end - 1) === 47 /* \"/\" */) end--;\n this.baseUrl = apiBaseUrl.slice(0, end);\n this.apiKey = apiKey;\n this.timeoutMs = timeoutMs ?? OpenBankingClient.DEFAULT_TIMEOUT_MS;\n this.fetchImpl = options.fetch ?? fetch;\n this.privateKey = importPrivateKey(privateKeyPkcs8);\n }\n\n /**\n * Builds a client from a credentials-bundle JSON string or a path to a bundle file.\n *\n * `overrides` (optional) lets the bundle path set the same transport knobs as the\n * constructor — e.g. a custom {@link OpenBankingClientOptions.fetch} or\n * {@link OpenBankingClientOptions.timeoutMs}.\n */\n static fromCredentials(\n jsonOrPath: string,\n overrides: Partial<Pick<OpenBankingClientOptions, \"fetch\" | \"timeoutMs\">> = {},\n ): OpenBankingClient {\n let json = jsonOrPath;\n if (!jsonOrPath.trimStart().startsWith(\"{\")) {\n json = readFileSync(jsonOrPath, \"utf8\");\n }\n const bundle = JSON.parse(json) as CredentialsBundle;\n return OpenBankingClient.fromBundle(bundle, overrides);\n }\n\n static fromBundle(\n bundle: CredentialsBundle,\n overrides: Partial<Pick<OpenBankingClientOptions, \"fetch\" | \"timeoutMs\">> = {},\n ): OpenBankingClient {\n if (!bundle.apiKey?.trim()) throw new Error(\"The credentials bundle has no apiKey\");\n return new OpenBankingClient({\n apiBaseUrl: bundle.apiBaseUrl,\n apiKey: bundle.apiKey,\n privateKeyPkcs8: bundle.encryptionKey.privateKey,\n timeoutMs: overrides.timeoutMs,\n fetch: overrides.fetch,\n });\n }\n\n /**\n * Builds a client from a Partner Connect token response and the private key the consent page\n * relayed — see {@link exchangeCode} and {@link parseRelay}.\n */\n static fromTokenResponse(\n token: TokenResponse,\n privateKey: string,\n overrides: Partial<Pick<OpenBankingClientOptions, \"fetch\" | \"timeoutMs\">> = {},\n ): OpenBankingClient {\n return OpenBankingClient.fromBundle(bundleFromToken(token, privateKey), overrides);\n }\n\n /** Lists the user's accounts with all sensitive fields decrypted. */\n async getAccounts(): Promise<Account[]> {\n const wires = await this.getAccountWires();\n return Promise.all(wires.map((w) => this.mapAccount(w)));\n }\n\n /** Returns a page of an account's statement, newest first, with decrypted fields. */\n async getTransactions(accountId: string, query: TransactionQuery = {}): Promise<TransactionPage> {\n const qs = new URLSearchParams();\n if (query.from != null) qs.set(\"from\", query.from);\n if (query.to != null) qs.set(\"to\", query.to);\n if (query.limit != null) qs.set(\"limit\", String(query.limit));\n if (query.offset != null) qs.set(\"offset\", String(query.offset));\n const suffix = qs.toString() ? `?${qs.toString()}` : \"\";\n\n const page = await this.getJson<TransactionPageWire>(\n `/api/accounts/${encodeURIComponent(accountId)}/transactions${suffix}`,\n );\n\n const items = await Promise.all((page.items ?? []).map((t) => this.mapTransaction(t)));\n return { items, total: page.total };\n }\n\n /** Lists the user's bank connections. */\n async getConnections(): Promise<Connection[]> {\n const wires = await this.getJson<ConnectionWire[]>(\"/api/connections\");\n return wires.map((c) => ({\n sessionId: c.sessionId,\n aspspName: c.aspspName,\n aspspCountry: c.aspspCountry,\n validUntil: c.validUntil,\n status: c.status,\n accountCount: c.accountCount,\n lastSyncedAt: c.lastSyncedAt ?? null,\n psuType: c.psuType ?? null,\n isLive: c.isLive ?? (c.status === \"Active\" && Date.parse(c.validUntil) > Date.now()),\n accountIds: c.accountIds ?? [],\n }));\n }\n\n /**\n * Triggers an online sync of one account: decrypts that account's Enable Banking uid and posts\n * it, so the service can fetch fresh data without ever holding the uid in plaintext.\n *\n * A refusal throws {@link SyncError}. A uid a renewal replaced (`uid_outdated`) is re-read and\n * retried once.\n */\n async sync(accountId: string, options: SyncOptions = {}): Promise<SyncResult> {\n for (let attempt = 0; ; attempt++) {\n const wires = await this.getAccountWires();\n const account = wires.find((a) => a.id === accountId);\n if (!account) throw new Error(`Account ${accountId} not found`);\n\n const uid = account.needsReconnect ? null : await this.decryptUid(account);\n if (uid == null) {\n throw new SyncError(\n \"Account has no active session (reconnect required) — cannot sync\",\n 409,\n \"reconnect_needed\",\n );\n }\n\n try {\n const result = await this.postJson<SyncResultWire>(\n `/api/accounts/${encodeURIComponent(accountId)}/sync`,\n { uid },\n psuHeaders(options.psu),\n );\n return { newTransactions: result.newTransactions, totalFetched: result.totalFetched };\n } catch (e) {\n if (attempt === 0 && e instanceof SyncError && e.reason === \"uid_outdated\") continue;\n throw e;\n }\n }\n }\n\n /**\n * Triggers an online sync of every account that has an active session. Per-account refusals are\n * in `failures`, and so is every account whose consent needs renewing (`reconnect_needed`, never\n * sent); accounts answering `uid_outdated` are re-read and retried once.\n */\n async syncAll(options: SyncOptions = {}): Promise<SyncAllResult> {\n const read = await this.syncItems();\n const first = await this.postSyncAll(read.items, options);\n first.failures.push(...read.lapsed);\n const outdated = new Set(\n first.failures.filter((f) => f.reason === \"uid_outdated\").map((f) => f.accountId),\n );\n if (outdated.size === 0) return first;\n\n const reread = await this.syncItems();\n const retryItems = reread.items.filter((i) => outdated.has(i.accountId));\n const lapsedNow = reread.lapsed.filter((f) => outdated.has(f.accountId));\n const settled = new Set([...retryItems, ...lapsedNow].map((i) => i.accountId));\n const kept = first.failures.filter((f) => !settled.has(f.accountId));\n if (retryItems.length === 0) return { ...first, failures: [...kept, ...lapsedNow] };\n\n const second = await this.postSyncAll(retryItems, options);\n return {\n accounts: first.accounts + second.accounts,\n newTransactions: first.newTransactions + second.newTransactions,\n failures: [...kept, ...lapsedNow, ...second.failures],\n };\n }\n\n // ---- internals ---------------------------------------------------------------------------------\n\n private getAccountWires(): Promise<AccountWire[]> {\n return this.getJson<AccountWire[]>(\"/api/accounts\");\n }\n\n private async syncItems(): Promise<{\n items: { accountId: string; uid: string }[];\n lapsed: SyncFailure[];\n }> {\n const wires = await this.getAccountWires();\n const decrypted = await Promise.all(\n wires.map(async (a) => ({\n accountId: a.id,\n needsReconnect: a.needsReconnect,\n uid: a.needsReconnect ? null : await this.decryptUid(a),\n })),\n );\n return {\n items: decrypted\n .filter((x): x is typeof x & { uid: string } => x.uid != null)\n .map((x) => ({ accountId: x.accountId, uid: x.uid })),\n lapsed: decrypted\n .filter((x) => x.uid == null && x.needsReconnect)\n .map((x) => ({ accountId: x.accountId, reason: \"reconnect_needed\", bankErrorCode: null })),\n };\n }\n\n private async postSyncAll(\n items: { accountId: string; uid: string }[],\n options: SyncOptions,\n ): Promise<SyncAllResult> {\n if (items.length === 0) return { accounts: 0, newTransactions: 0, failures: [] };\n const result = await this.postJson<SyncAllResultWire>(\n \"/api/sync\",\n { items },\n psuHeaders(options.psu),\n );\n const failures: SyncFailure[] = (result.failures ?? []).map((f) => ({\n accountId: f.accountId,\n reason: f.reason,\n bankErrorCode: f.bankErrorCode ?? null,\n }));\n return { accounts: result.accounts, newTransactions: result.newTransactions, failures };\n }\n\n private async decryptUid(a: AccountWire): Promise<string | null> {\n const dec = await decryptTo<UidEnc>(await this.privateKey, a.uidEnc);\n return dec?.uid ?? null;\n }\n\n private async mapAccount(a: AccountWire): Promise<Account> {\n const priv = await this.privateKey;\n const acc = await decryptTo<AccountEnc>(priv, a.enc);\n const name = await decryptTo<DisplayNameEnc>(priv, a.displayNameEnc);\n const balances = await Promise.all(\n (a.balances ?? []).map(async (b) => {\n const dec = await decryptTo<BalanceEnc>(priv, b.enc);\n return {\n type: b.type,\n name: dec?.name ?? null,\n amount: dec?.amount ?? \"0\",\n currency: b.currency,\n referenceDate: b.referenceDate ?? null,\n };\n }),\n );\n\n return {\n id: a.id,\n aspspName: a.aspspName,\n aspspCountry: a.aspspCountry,\n currency: a.currency,\n accountType: a.accountType ?? null,\n bic: a.bic ?? null,\n needsReconnect: a.needsReconnect,\n iban: acc?.iban ?? null,\n bban: acc?.bban ?? null,\n ownerName: acc?.ownerName ?? null,\n accountName: acc?.accountName ?? null,\n product: acc?.product ?? null,\n displayName: name?.displayName ?? null,\n balances,\n };\n }\n\n private async mapTransaction(t: TransactionWire): Promise<Transaction> {\n const d = await decryptTo<TransactionEnc>(await this.privateKey, t.enc);\n return {\n id: t.id,\n currency: t.currency,\n creditDebitIndicator: t.creditDebitIndicator,\n status: t.status ?? null,\n bookingDate: t.bookingDate ?? null,\n valueDate: t.valueDate ?? null,\n transactionDate: t.transactionDate ?? null,\n bankTransactionCode: t.bankTransactionCode ?? null,\n amount: d?.amount ?? \"0\",\n creditorName: d?.creditorName ?? null,\n creditorIban: d?.creditorIban ?? null,\n creditorBban: d?.creditorBban ?? null,\n creditorAgentBic: d?.creditorAgentBic ?? null,\n debtorName: d?.debtorName ?? null,\n debtorIban: d?.debtorIban ?? null,\n debtorBban: d?.debtorBban ?? null,\n debtorAgentBic: d?.debtorAgentBic ?? null,\n remittanceInformation: d?.remittanceInformation ?? null,\n note: d?.note ?? null,\n referenceNumber: d?.referenceNumber ?? null,\n exchangeRate: d?.exchangeRate ?? null,\n merchantCategoryCode: d?.merchantCategoryCode ?? null,\n balanceAfterTransaction: d?.balanceAfter ?? null,\n balanceAfterCurrency: d?.balanceAfterCurrency ?? null,\n };\n }\n\n private async getJson<T>(path: string): Promise<T> {\n const res = await this.fetchImpl(this.baseUrl + path, {\n headers: { \"X-Api-Key\": this.apiKey, \"User-Agent\": USER_AGENT },\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n if (!res.ok) {\n throw new Error(`GET ${path} failed: ${res.status} ${res.statusText}`);\n }\n return (await res.json()) as T;\n }\n\n private async postJson<T>(\n path: string,\n body: unknown,\n extraHeaders: Record<string, string> = {},\n ): Promise<T> {\n const res = await this.fetchImpl(this.baseUrl + path, {\n method: \"POST\",\n headers: {\n ...extraHeaders,\n \"X-Api-Key\": this.apiKey,\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n if (!res.ok) {\n const problem = await readProblem(res);\n const retryAfter = Number.parseInt(res.headers.get(\"Retry-After\") ?? \"\", 10);\n throw new SyncError(\n `POST ${path} failed: ${res.status} ${problem.reason ?? res.statusText}`,\n res.status,\n problem.reason,\n problem.bankErrorCode,\n Number.isFinite(retryAfter) ? retryAfter : null,\n );\n }\n return (await res.json()) as T;\n }\n}\n\nasync function readProblem(\n res: Response,\n): Promise<{ reason: string | null; bankErrorCode: string | null }> {\n try {\n const body = (await res.json()) as { reason?: unknown; bankErrorCode?: unknown };\n return {\n reason: typeof body.reason === \"string\" ? body.reason : null,\n bankErrorCode: typeof body.bankErrorCode === \"string\" ? body.bankErrorCode : null,\n };\n } catch {\n return { reason: null, bankErrorCode: null };\n }\n}\n\n/** The `X-Psu-*` request headers for a forwarded {@link PsuHeaders}; empty when none is given. */\nexport function psuHeaders(psu: PsuHeaders | undefined): Record<string, string> {\n if (!psu?.ipAddress || !psu.userAgent) return {};\n const headers: Record<string, string> = {\n \"X-Psu-Ip-Address\": psu.ipAddress,\n \"X-Psu-User-Agent\": psu.userAgent,\n };\n const optional: [string, string | undefined][] = [\n [\"X-Psu-Referer\", psu.referer],\n [\"X-Psu-Accept\", psu.accept],\n [\"X-Psu-Accept-Language\", psu.acceptLanguage],\n [\"X-Psu-Accept-Charset\", psu.acceptCharset],\n [\"X-Psu-Accept-Encoding\", psu.acceptEncoding],\n ];\n for (const [name, value] of optional) if (value) headers[name] = value;\n return headers;\n}\n","import { webcrypto } from \"node:crypto\";\n\nconst { subtle } = webcrypto;\n\n/** Re-export the WebCrypto key type so callers don't depend on the DOM lib. */\nexport type CryptoKey = webcrypto.CryptoKey;\n\nconst VERSION = 0x01;\nconst POINT_LEN = 65;\nconst NONCE_LEN = 12;\nconst TAG_LEN = 16;\n\nconst HKDF_INFO = new TextEncoder().encode(\"bank.core.ci/zk/v1\");\nconst HKDF_SALT = new Uint8Array(32); // 32 zero bytes (must be exactly this).\n\n/**\n * Decrypts open-banking.io's zero-knowledge data envelopes.\n * Scheme: ephemeral ECDH on NIST P-256 -> HKDF-SHA256 -> AES-256-GCM.\n * Wire: `version(1)=0x01 | ephemeralPublicKeyRaw(65) | nonce(12) | tag(16) | ciphertext`.\n * Only the user's private key can decrypt — the service stores ciphertext it cannot read.\n */\nexport async function decryptEnvelope(\n privateKey: CryptoKey,\n envelopeBase64: string,\n): Promise<Uint8Array> {\n const bytes = base64ToBytes(envelopeBase64);\n if (bytes.length < 1 + POINT_LEN + NONCE_LEN + TAG_LEN || bytes[0] !== VERSION) {\n throw new Error(\"Invalid or unsupported envelope\");\n }\n\n const ephPub = bytes.subarray(1, 1 + POINT_LEN);\n const nonce = bytes.subarray(1 + POINT_LEN, 1 + POINT_LEN + NONCE_LEN);\n const tag = bytes.subarray(1 + POINT_LEN + NONCE_LEN, 1 + POINT_LEN + NONCE_LEN + TAG_LEN);\n const ciphertext = bytes.subarray(1 + POINT_LEN + NONCE_LEN + TAG_LEN);\n\n // Guard against invalid-curve attacks: WebCrypto's P-256 `importKey` validates that the raw point\n // lies on the curve and is not the point at infinity, so a forged/off-curve ephemeral public key\n // throws here rather than yielding a derivable (and exploitable) shared secret below.\n const ephKey = await subtle.importKey(\n \"raw\",\n ephPub,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false,\n [],\n );\n\n const shared = new Uint8Array(\n await subtle.deriveBits({ name: \"ECDH\", public: ephKey }, privateKey, 256),\n );\n\n const hkdf = await subtle.importKey(\"raw\", shared, \"HKDF\", false, [\"deriveKey\"]);\n\n const aesKey = await subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: HKDF_SALT, info: HKDF_INFO },\n hkdf,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"decrypt\"],\n );\n\n // Web Crypto AES-GCM expects ciphertext||tag.\n const ctWithTag = new Uint8Array(ciphertext.length + tag.length);\n ctWithTag.set(ciphertext, 0);\n ctWithTag.set(tag, ciphertext.length);\n\n const plaintext = await subtle.decrypt(\n { name: \"AES-GCM\", iv: nonce, tagLength: 128 },\n aesKey,\n ctWithTag,\n );\n\n return new Uint8Array(plaintext);\n}\n\n/** Decrypts a base64 envelope and JSON-parses its payload. `null`/`undefined` in -> `null`. */\nexport async function decryptTo<T>(\n privateKey: CryptoKey,\n envelopeBase64: string | null | undefined,\n): Promise<T | null> {\n if (envelopeBase64 == null) return null;\n const plaintext = await decryptEnvelope(privateKey, envelopeBase64);\n return JSON.parse(new TextDecoder().decode(plaintext)) as T;\n}\n\n/** Imports a base64 PKCS#8 P-256 ECDH private key for use with {@link decryptEnvelope}. */\nexport async function importPrivateKey(pkcs8Base64: string): Promise<CryptoKey> {\n return subtle.importKey(\n \"pkcs8\",\n base64ToBytes(pkcs8Base64),\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false,\n [\"deriveBits\"],\n );\n}\n\nfunction base64ToBytes(b64: string): Uint8Array<ArrayBuffer> {\n return new Uint8Array(Buffer.from(b64, \"base64\"));\n}\n","import type { SyncFailureReason } from \"./models.js\";\n\n/** A sync the service refused. `reason` is the stable code to branch on. */\nexport class SyncError extends Error {\n readonly status: number;\n readonly reason: SyncFailureReason | null;\n readonly bankErrorCode: string | null;\n readonly retryAfterSeconds: number | null;\n\n constructor(\n message: string,\n status: number,\n reason: SyncFailureReason | null,\n bankErrorCode: string | null = null,\n retryAfterSeconds: number | null = null,\n ) {\n super(message);\n this.name = \"SyncError\";\n this.status = status;\n this.reason = reason;\n this.bankErrorCode = bankErrorCode;\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n","import { OAuthError, revokeToken, userinfo, type HttpOptions } from \"./connect.js\";\nimport { decryptTo, importPrivateKey } from \"./envelope.js\";\nimport type { OpenConsentWire, SessionIdEnc } from \"./models.js\";\nimport { USER_AGENT } from \"./version.js\";\n\nexport interface CloseReplacedConsentsOptions extends HttpOptions {\n issuer: string;\n clientId: string;\n clientSecret: string;\n /** The PREVIOUS key — the one issued before the renewal. It is revoked by this call. */\n token: string;\n /** The base64 PKCS#8 private key the consents are sealed to. */\n privateKey: string;\n /** Defaults to the issuer. */\n apiBaseUrl?: string;\n}\n\nexport interface CloseReplacedConsentsResult {\n /** Consents sent to be closed at the bank. */\n closed: number;\n /** Consents listed but not closable (no envelope, or it would not decrypt). */\n failed: number;\n /** Whether the previous key is gone. When false, revoke it yourself. */\n revoked: boolean;\n}\n\n/**\n * After a renewal: closes, at the bank, the consents the previous key still has open, and revokes\n * that key in the same call. Reads `GET /api/connections/open-consents` only — never the live\n * connections, which by now hold the renewal. A key that is already gone, or was issued to another\n * client, closes nothing: the service answers such a revoke with 200 without closing anything. A\n * failure that retrying may clear (5xx, 429) throws, so the key survives for a retry: revoking it\n * without the close would leave the consents open with nothing left that can list them.\n */\nexport async function closeReplacedConsents(\n options: CloseReplacedConsentsOptions,\n): Promise<CloseReplacedConsentsResult> {\n const fetchImpl = options.fetch ?? fetch;\n const base = trimSlash(options.apiBaseUrl ?? options.issuer);\n const nothing = { closed: 0, failed: 0, revoked: false };\n\n let owner: string | null;\n try {\n owner = (await userinfo({ ...options, accessToken: options.token })).clientId;\n } catch (e) {\n if (e instanceof OAuthError && keyRefused(e.status)) return nothing;\n throw e;\n }\n if (owner !== options.clientId) return nothing;\n\n const res = await fetchImpl(`${base}/api/connections/open-consents`, {\n headers: { \"X-Api-Key\": options.token, \"User-Agent\": USER_AGENT },\n signal: AbortSignal.timeout(options.timeoutMs ?? 30_000),\n });\n if (keyRefused(res.status)) return nothing;\n if (!res.ok) throw new Error(`GET /api/connections/open-consents failed: ${res.status}`);\n const open = (await res.json()) as OpenConsentWire[];\n\n const key = await importPrivateKey(options.privateKey);\n const closeConsents: { connectionId: string; ebSessionId: string }[] = [];\n const seen = new Set<string>();\n let failed = 0;\n for (const c of open) {\n if (!c.connectionId || seen.has(c.connectionId)) continue;\n seen.add(c.connectionId);\n if (!c.sessionIdEnc) {\n failed += 1;\n continue;\n }\n let sessionId: string | null | undefined;\n try {\n sessionId = (await decryptTo<SessionIdEnc>(key, c.sessionIdEnc))?.sessionId;\n } catch {\n sessionId = null;\n }\n if (!sessionId) {\n failed += 1;\n continue;\n }\n closeConsents.push({ connectionId: c.connectionId, ebSessionId: sessionId });\n }\n\n try {\n await revokeToken({ ...options, closeConsents });\n } catch (e) {\n if (e instanceof OAuthError && e.status < 500 && e.status !== 429)\n return { closed: 0, failed: failed + closeConsents.length, revoked: false };\n throw e;\n }\n return { closed: closeConsents.length, failed, revoked: true };\n}\n\nconst keyRefused = (status: number) => status === 401 || status === 403;\n\nfunction trimSlash(url: string): string {\n let end = url.length;\n while (end > 0 && url.charCodeAt(end - 1) === 47) end--;\n return url.slice(0, end);\n}\n","import { createHash, webcrypto } from \"node:crypto\";\nimport { decryptTo, importPrivateKey } from \"./envelope.js\";\n\nconst subtle = webcrypto.subtle;\n\n/** A partner's recipient (decryption) key pair. The private half is a credential: never log it. */\nexport interface RecipientKeyPair {\n /** Base64 PKCS#8 — what your deployment loads. */\n privateKeyPkcs8Base64: string;\n /** Base64 raw 65-byte uncompressed P-256 point — what you install on your partner page. */\n publicKeyRawBase64: string;\n}\n\n/**\n * Generates the P-256 pair a partner installs on open-banking.io. The public half goes into\n * `PUT /api/partner/recipient-key` (or the partner page's paste box); keep the private half\n * where your deployment can read it — the service never sees it and cannot recover it.\n */\nexport async function generateRecipientKeyPair(): Promise<RecipientKeyPair> {\n const pair = await subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-256\" }, true, [\n \"deriveBits\",\n ]);\n return {\n privateKeyPkcs8Base64: Buffer.from(await subtle.exportKey(\"pkcs8\", pair.privateKey)).toString(\n \"base64\",\n ),\n publicKeyRawBase64: Buffer.from(await subtle.exportKey(\"raw\", pair.publicKey)).toString(\n \"base64\",\n ),\n };\n}\n\n/**\n * The fingerprint the partner page and the admin show for a key: SHA-256 of the raw 65-byte\n * point, lowercase hex, first 16 characters. Print it at boot and compare after every deploy.\n */\nexport function recipientKeyFingerprint(publicKeyRawBase64: string): string {\n return createHash(\"sha256\")\n .update(Buffer.from(publicKeyRawBase64, \"base64\"))\n .digest(\"hex\")\n .slice(0, 16);\n}\n\n/** The raw public point of a PKCS#8 private key — to fingerprint or re-install the key you hold. */\nexport async function recipientPublicKey(privateKeyPkcs8Base64: string): Promise<string> {\n const key = await subtle.importKey(\n \"pkcs8\",\n Buffer.from(privateKeyPkcs8Base64, \"base64\"),\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"],\n );\n const jwk = await subtle.exportKey(\"jwk\", key);\n if (!jwk.x || !jwk.y) throw new Error(\"The private key carries no public point\");\n return Buffer.concat([\n Buffer.from([0x04]),\n Buffer.from(jwk.x, \"base64url\"),\n Buffer.from(jwk.y, \"base64url\"),\n ]).toString(\"base64\");\n}\n\n/**\n * Answers the possession challenge from `POST /api/partner/recipient-key/challenge`: opens\n * the envelope with the private half and returns the nonce — the `challengeAnswer` for the install.\n */\nexport async function answerRecipientKeyChallenge(\n privateKeyPkcs8Base64: string,\n envelopeBase64: string,\n): Promise<string> {\n const payload = await decryptTo<{ nonce?: unknown }>(\n await importPrivateKey(privateKeyPkcs8Base64),\n envelopeBase64,\n );\n const nonce = payload?.nonce;\n if (typeof nonce !== \"string\" || nonce.length === 0)\n throw new Error(\"The challenge envelope carries no nonce\");\n return nonce;\n}\n"],"mappings":";AAEA,SAAS,YAAY,aAAa,uBAAuB;;;ACFzD;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,QAAU;AAAA,EACV,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,EACT;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,EACF;AAAA,EACA,MAAQ;AAAA,EACR,QAAU;AAAA,EACV,OAAS;AAAA,EACT,SAAW;AAAA,IACT,KAAK;AAAA,MACH,OAAS;AAAA,MACT,QAAU;AAAA,MACV,SAAW;AAAA,IACb;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,IACT,MAAQ;AAAA,IACR,UAAY;AAAA,IACZ,WAAa;AAAA,IACb,MAAQ;AAAA,IACR,gBAAgB;AAAA,EAClB;AAAA,EACA,WAAa;AAAA,IACX,SAAW;AAAA,EACb;AAAA,EACA,iBAAmB;AAAA,IACjB,cAAc;AAAA,IACd,eAAe;AAAA,IACf,uBAAuB;AAAA,IACvB,QAAU;AAAA,IACV,UAAY;AAAA,IACZ,MAAQ;AAAA,IACR,YAAc;AAAA,IACd,qBAAqB;AAAA,IACrB,QAAU;AAAA,EACZ;AAAA,EACA,UAAY;AACd;;;ACrDO,I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AAE,SAAS,QAAQ;AACtB;AAMA,eAAsB,4BACpB,uBACA,gBACiB;AACjB,QAAM,UAAU,MAAM;AAAA,IACpB,MAAM,iBAAiB,qBAAqB;AAAA,IAC5C;AAAA,EACF;AACA,QAAM,QAAQ,SAAS;AACvB,MAAI,OAAO,UAAU,YAAY,MAAM,WAAW;AAChD,UAAM,IAAI,MAAM,yCAAyC;AAC3D,SAAO;AACT;","names":["VERSION","trimSlash","createHash","webcrypto","subtle","webcrypto","createHash"]}
|
|
1
|
+
{"version":3,"sources":["../src/connect.ts","../package.json","../src/version.ts","../src/client.ts","../src/envelope.ts","../src/errors.ts","../src/consents.ts","../src/recipientKey.ts"],"sourcesContent":["// Partner Connect: the OAuth 2.0 authorization-code flow (PKCE, form_post) that hands a partner an\n// API key and the user's private key. Documented at https://open-banking.io/en/docs/partners.\nimport { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport type { CredentialsBundle } from \"./models.js\";\nimport { USER_AGENT } from \"./version.js\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/** The relay fields the consent page form-posts to a redirect URI, in wire order. */\nexport const CONNECT_RELAY_FIELDS = [\"code\", \"state\", \"iss\", \"privateKey\", \"publicKey\"] as const;\n\nexport interface Pkce {\n /** The `code_verifier` to keep server-side and send on the token request. */\n verifier: string;\n /** The `code_challenge` to send on the authorize request. */\n challenge: string;\n method: \"S256\";\n}\n\n/** A fresh PKCE pair (RFC 7636): 32 random bytes, base64url, S256 challenge. */\nexport function createPkce(): Pkce {\n const verifier = randomBytes(32).toString(\"base64url\");\n return { verifier, challenge: pkceChallenge(verifier), method: \"S256\" };\n}\n\n/** The S256 challenge for a verifier — exposed so a stored verifier can be re-checked. */\nexport function pkceChallenge(verifier: string): string {\n return createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\n/** A fresh opaque `state` (16 random bytes, base64url). */\nexport function createState(): string {\n return randomBytes(16).toString(\"base64url\");\n}\n\nexport interface AuthorizeUrlOptions {\n /** The issuer, e.g. `https://open-banking.io`. */\n issuer: string;\n clientId: string;\n /** One of the client's registered redirect URIs, character for character. */\n redirectUri: string;\n state: string;\n /** From {@link createPkce}. */\n codeChallenge: string;\n /** Defaults to `accounts.read`, the only scope. */\n scope?: string;\n /** Prefills the email on the login page; never authenticates. */\n loginHint?: string;\n /** `pin_code` keeps a popup journey inside the popup (typed emailed code instead of a magic link). */\n challenge?: \"pin_code\";\n /** Space-separated locales; the first one the server publishes forces the language of every screen. */\n uiLocales?: string;\n /**\n * A connection's `sessionId` to renew: the user goes straight to that bank, whether its consent\n * is still live or has lapsed.\n */\n renewConnection?: string;\n}\n\n/** The `/oauth/authorize` URL for a top-level browser navigation. */\nexport function buildAuthorizeUrl(options: AuthorizeUrlOptions): string {\n const params = new URLSearchParams({\n response_type: \"code\",\n client_id: options.clientId,\n redirect_uri: options.redirectUri,\n scope: options.scope ?? \"accounts.read\",\n state: options.state,\n code_challenge: options.codeChallenge,\n code_challenge_method: \"S256\",\n response_mode: \"form_post\",\n });\n if (options.loginHint) params.set(\"login_hint\", options.loginHint);\n if (options.challenge) params.set(\"challenge\", options.challenge);\n if (options.uiLocales) params.set(\"ui_locales\", options.uiLocales);\n if (options.renewConnection) params.set(\"renew_connection\", options.renewConnection);\n return `${endpoint(options.issuer, \"/oauth/authorize\")}?${params.toString()}`;\n}\n\n/** What the consent page relayed to the redirect URI. */\nexport interface ConnectRelay {\n code: string;\n state: string;\n /** Present on current servers (RFC 9207); empty string from older ones. */\n iss: string;\n /** The user's base64 PKCS#8 private key. A credential: never log it. */\n privateKey: string;\n publicKey: string;\n}\n\nexport type RelayErrorCode =\n | \"access_denied\"\n | \"oauth_error\"\n | \"state_mismatch\"\n | \"issuer_mismatch\"\n | \"missing_code\"\n | \"missing_private_key\";\n\n/** The `error_description` the server relays when the partner has not installed its decryption key. */\nexport const PARTNER_KEY_MISSING_DESCRIPTION =\n \"this partner has not installed its decryption key; no authorizations can be started until it does\";\n/** The `error_description` the server relays while the partner is suspended. */\nexport const PARTNER_SUSPENDED_DESCRIPTION =\n \"this partner is suspended; no authorizations can be started\";\n\n/**\n * Why a `temporarily_unavailable` was relayed, when the server said so in the pinned words. Both\n * are on your side, not the bank's: install the key on your partner page, or write to us.\n */\nexport type RelayRefusalReason = \"partner_key_missing\" | \"partner_suspended\";\n\nfunction refusalReason(error: string, description: string): RelayRefusalReason | undefined {\n if (error !== \"temporarily_unavailable\") return undefined;\n if (description === PARTNER_KEY_MISSING_DESCRIPTION) return \"partner_key_missing\";\n if (description === PARTNER_SUSPENDED_DESCRIPTION) return \"partner_suspended\";\n return undefined;\n}\n\n/**\n * Thrown by {@link parseRelay}. `code` says why: `access_denied` is the user pressing \"Back to the\n * partner\" or declining (a normal outcome), `oauth_error` any other error the server relayed (the\n * fields are attached), the rest are validation failures on your side.\n */\nexport class RelayError extends Error {\n readonly code: RelayErrorCode;\n readonly error?: string;\n readonly errorDescription?: string;\n /** Set on an `oauth_error` whose description names a partner-side refusal. */\n readonly reason?: RelayRefusalReason;\n\n constructor(\n code: RelayErrorCode,\n message: string,\n oauth?: { error: string; errorDescription?: string },\n ) {\n super(message);\n this.name = \"RelayError\";\n this.code = code;\n this.error = oauth?.error;\n this.errorDescription = oauth?.errorDescription;\n this.reason = oauth ? refusalReason(oauth.error, oauth.errorDescription ?? \"\") : undefined;\n }\n}\n\nexport interface ParseRelayOptions {\n /** The `state` this flow was started with. Compared in constant time. */\n expectedState: string;\n /** When set, `iss` must equal it (trailing slashes ignored). */\n issuer?: string;\n /** Require `iss` to be present even when `issuer` is not checked. Default: only when `issuer` is set. */\n requireIss?: boolean;\n /**\n * Whether the relay must carry the user's private key. A partner that installed its own\n * decryption key receives `privateKey=\"\"` for every user who connected under it and decrypts\n * with that key instead — pass `\"optional\"`. Default `\"required\"`, the 1.1.0 behaviour.\n */\n expectPrivateKey?: \"required\" | \"optional\";\n}\n\n/** A form body, `URLSearchParams`, parsed body object, or JSON string. */\nexport type RelayInput = string | URLSearchParams | FormData | Record<string, unknown>;\n\n/**\n * Validates the form_post relay: `state` (constant time) and `iss` first, so a relayed error is only\n * honoured for this flow from this issuer; then an OAuth error becomes a {@link RelayError}, and\n * `code` and `privateKey` are checked.\n */\nexport function parseRelay(input: RelayInput, options: ParseRelayOptions): ConnectRelay {\n const fields = toRecord(input);\n const read = (name: string): string => {\n const value = fields[name];\n return typeof value === \"string\" ? value : \"\";\n };\n\n if (!options.expectedState || !constantTimeEqual(read(\"state\"), options.expectedState)) {\n throw new RelayError(\"state_mismatch\", \"The relayed state does not match this flow\");\n }\n\n const iss = read(\"iss\");\n const wantIss = options.issuer !== undefined || options.requireIss === true;\n if (wantIss && !iss) throw new RelayError(\"issuer_mismatch\", \"The relay carries no iss\");\n if (\n options.issuer !== undefined &&\n !constantTimeEqual(trimSlash(iss), trimSlash(options.issuer))\n ) {\n throw new RelayError(\"issuer_mismatch\", \"The relayed iss is not the expected issuer\");\n }\n\n const error = read(\"error\");\n if (error) {\n const description = read(\"error_description\");\n throw new RelayError(\n error === \"access_denied\" ? \"access_denied\" : \"oauth_error\",\n description ? `${error}: ${description}` : error,\n {\n error,\n errorDescription: description || undefined,\n },\n );\n }\n\n const code = read(\"code\");\n if (!code) throw new RelayError(\"missing_code\", \"The relay carries no authorization code\");\n const privateKey = read(\"privateKey\");\n if (!privateKey && (options.expectPrivateKey ?? \"required\") === \"required\") {\n throw new RelayError(\"missing_private_key\", \"The relay carries no private key\");\n }\n\n return { code, state: read(\"state\"), iss, privateKey, publicKey: read(\"publicKey\") };\n}\n\n/** An RFC 6749 §5.2 error body from the token or revocation endpoint. */\nexport class OAuthError extends Error {\n readonly status: number;\n readonly error: string;\n readonly errorDescription?: string;\n\n constructor(status: number, error: string, errorDescription?: string) {\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = \"OAuthError\";\n this.status = status;\n this.error = error;\n this.errorDescription = errorDescription;\n }\n}\n\nexport interface HttpOptions {\n /** Custom `fetch`, e.g. for tests. Defaults to the global. */\n fetch?: typeof globalThis.fetch;\n /** Per-request timeout; defaults to 30s. */\n timeoutMs?: number;\n}\n\nexport interface ExchangeCodeOptions extends HttpOptions {\n issuer: string;\n clientId: string;\n clientSecret: string;\n /** From the relay. */\n code: string;\n /** From {@link createPkce}, kept server-side. */\n codeVerifier: string;\n /** The redirect URI used on the authorize request; sent when given and must match. */\n redirectUri?: string;\n}\n\n/** The token endpoint's response. `accessToken` and `apiKey` are the same key. */\nexport interface TokenResponse {\n accessToken: string;\n tokenType: string;\n expiresIn: number;\n scope: string;\n apiKey: string;\n apiBaseUrl: string;\n /** The tenant subject the key reads for. */\n user: string;\n}\n\ninterface TokenResponseWire {\n access_token?: string;\n token_type?: string;\n expires_in?: number;\n scope?: string;\n apiKey?: string;\n apiBaseUrl?: string;\n user?: string;\n}\n\n/** Exchanges the relayed code for the key, server to server, with HTTP Basic client authentication. */\nexport async function exchangeCode(options: ExchangeCodeOptions): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: \"authorization_code\",\n code: options.code,\n code_verifier: options.codeVerifier,\n });\n if (options.redirectUri) body.set(\"redirect_uri\", options.redirectUri);\n\n const response = await post(\n endpoint(options.issuer, \"/oauth/token\"),\n body,\n {\n Authorization: basicAuth(options.clientId, options.clientSecret),\n Accept: \"application/json\",\n },\n options,\n );\n await throwIfOAuthError(response);\n\n const wire = (await response.json()) as TokenResponseWire;\n const accessToken = wire.access_token ?? wire.apiKey;\n if (!accessToken)\n throw new OAuthError(\n response.status,\n \"invalid_response\",\n \"The token response carries no access token\",\n );\n return {\n accessToken,\n tokenType: wire.token_type ?? \"Bearer\",\n expiresIn: wire.expires_in ?? 0,\n scope: wire.scope ?? \"\",\n apiKey: wire.apiKey ?? accessToken,\n apiBaseUrl: wire.apiBaseUrl ?? trimSlash(options.issuer),\n user: wire.user ?? \"\",\n };\n}\n\nexport interface RevokeTokenOptions extends HttpOptions {\n issuer: string;\n clientId: string;\n clientSecret: string;\n /** The key to revoke. Only keys issued to this client are touched; an unknown key still succeeds. */\n token: string;\n /**\n * Bank consents to close in the same call, with the decrypted Enable Banking session id of each.\n * Validated before the key is revoked: a refusal leaves the key alive.\n */\n closeConsents?: { connectionId: string; ebSessionId: string }[];\n}\n\n/** RFC 7009 revocation. Resolves on 200; throws {@link OAuthError} on a client-authentication failure. */\nexport async function revokeToken(options: RevokeTokenOptions): Promise<void> {\n const body = new URLSearchParams({ token: options.token, token_type_hint: \"access_token\" });\n for (const c of options.closeConsents ?? []) {\n body.append(\"connection_id\", c.connectionId);\n body.append(\"eb_session_id\", c.ebSessionId);\n }\n const response = await post(\n endpoint(options.issuer, \"/oauth/revoke\"),\n body,\n {\n Authorization: basicAuth(options.clientId, options.clientSecret),\n },\n options,\n );\n await throwIfOAuthError(response);\n}\n\nexport interface UserinfoOptions extends HttpOptions {\n issuer: string;\n accessToken: string;\n}\n\nexport interface Userinfo {\n sub: string;\n email: string;\n partnerId: string | null;\n clientId: string | null;\n scope: string;\n expiresAt: string | null;\n}\n\ninterface UserinfoWire {\n sub: string;\n email: string;\n partner_id: string | null;\n client_id: string | null;\n scope: string;\n expires_at: string | null;\n}\n\n/** What a key reads for. Throws {@link OAuthError} with status 401 when the key is revoked or expired. */\nexport async function userinfo(options: UserinfoOptions): Promise<Userinfo> {\n const response = await request(\n endpoint(options.issuer, \"/oauth/userinfo\"),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${options.accessToken}`,\n Accept: \"application/json\",\n \"User-Agent\": USER_AGENT,\n },\n },\n options,\n );\n await throwIfOAuthError(response);\n const wire = (await response.json()) as UserinfoWire;\n return {\n sub: wire.sub,\n email: wire.email,\n partnerId: wire.partner_id ?? null,\n clientId: wire.client_id ?? null,\n scope: wire.scope,\n expiresAt: wire.expires_at ?? null,\n };\n}\n\n/** RFC 8414 metadata with the `open_banking_io` extension. */\nexport interface ServerMetadata {\n issuer: string;\n authorization_endpoint: string;\n token_endpoint: string;\n revocation_endpoint: string;\n scopes_supported: string[];\n response_types_supported: string[];\n response_modes_supported: string[];\n grant_types_supported: string[];\n token_endpoint_auth_methods_supported: string[];\n revocation_endpoint_auth_methods_supported?: string[];\n code_challenge_methods_supported: string[];\n authorization_response_iss_parameter_supported?: boolean;\n service_documentation?: string;\n open_banking_io: {\n userinfo_endpoint: string;\n api_base_url: string;\n api_key_header: string;\n bearer_supported: boolean;\n login_challenges_supported?: string[];\n key_relay: { response_mode: string; fields: string[] };\n /** The server accepts a partner-held decryption key (always true on current servers). */\n recipient_key_supported?: boolean;\n /** Every partner must hold one before it can register a client or start an authorization. */\n recipient_key_required?: boolean;\n documentation: string;\n };\n}\n\nconst discoveryCache = new Map<string, { metadata: ServerMetadata; expiresAt: number }>();\nconst DISCOVERY_TTL_MS = 60 * 60 * 1000;\n\n/** Fetches `/.well-known/oauth-authorization-server`, cached per issuer for an hour. */\nexport async function discover(issuer: string, options: HttpOptions = {}): Promise<ServerMetadata> {\n const key = trimSlash(issuer);\n const cached = discoveryCache.get(key);\n if (cached && cached.expiresAt > Date.now()) return cached.metadata;\n\n const response = await request(\n `${key}/.well-known/oauth-authorization-server`,\n {\n method: \"GET\",\n headers: { Accept: \"application/json\", \"User-Agent\": USER_AGENT },\n },\n options,\n );\n if (!response.ok)\n throw new OAuthError(response.status, \"discovery_failed\", `HTTP ${response.status}`);\n const metadata = (await response.json()) as ServerMetadata;\n if (typeof metadata.issuer !== \"string\" || trimSlash(metadata.issuer) !== key) {\n throw new OAuthError(\n response.status,\n \"discovery_failed\",\n `Issuer mismatch: ${String(metadata.issuer)}`,\n );\n }\n discoveryCache.set(key, { metadata, expiresAt: Date.now() + DISCOVERY_TTL_MS });\n return metadata;\n}\n\n/** The credentials bundle the data client reads with: the key plus the relayed private key. */\nexport function bundleFromToken(token: TokenResponse, privateKey: string): CredentialsBundle {\n return {\n service: \"open-banking.io\",\n apiBaseUrl: token.apiBaseUrl,\n user: token.user,\n apiKey: token.accessToken,\n encryptionKey: { scheme: \"ecdh-p256-hkdf-aes-256-gcm\", curve: \"P-256\", privateKey },\n };\n}\n\nfunction endpoint(issuer: string, path: string): string {\n return trimSlash(issuer) + path;\n}\n\nfunction trimSlash(value: string): string {\n let end = value.length;\n while (end > 0 && value[end - 1] === \"/\") end--;\n return value.slice(0, end);\n}\n\nfunction basicAuth(clientId: string, clientSecret: string): string {\n const pair = `${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`;\n return `Basic ${Buffer.from(pair, \"utf8\").toString(\"base64\")}`;\n}\n\nfunction constantTimeEqual(a: string, b: string): boolean {\n const x = createHash(\"sha256\").update(a, \"utf8\").digest();\n const y = createHash(\"sha256\").update(b, \"utf8\").digest();\n return timingSafeEqual(x, y) && a.length === b.length;\n}\n\nfunction toRecord(input: RelayInput): Record<string, unknown> {\n if (typeof input === \"string\") {\n const trimmed = input.trim();\n if (trimmed.startsWith(\"{\")) return JSON.parse(trimmed) as Record<string, unknown>;\n return Object.fromEntries(new URLSearchParams(trimmed));\n }\n if (input instanceof URLSearchParams) return Object.fromEntries(input);\n if (input instanceof FormData) {\n const record: Record<string, unknown> = {};\n input.forEach((value, name) => {\n if (typeof value === \"string\") record[name] = value;\n });\n return record;\n }\n return input;\n}\n\nasync function post(\n url: string,\n body: URLSearchParams,\n headers: Record<string, string>,\n options: HttpOptions,\n): Promise<Response> {\n return request(\n url,\n {\n method: \"POST\",\n headers: {\n ...headers,\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": USER_AGENT,\n },\n body: body.toString(),\n },\n options,\n );\n}\n\nasync function request(url: string, init: RequestInit, options: HttpOptions): Promise<Response> {\n const fetchImpl = options.fetch ?? fetch;\n return fetchImpl(url, {\n ...init,\n signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n });\n}\n\nasync function throwIfOAuthError(response: Response): Promise<void> {\n if (response.ok) return;\n let error = \"http_error\";\n let description: string | undefined = `HTTP ${response.status}`;\n try {\n const body = (await response.json()) as { error?: string; error_description?: string };\n if (body.error) {\n error = body.error;\n description = body.error_description;\n }\n } catch {\n // A non-JSON error body keeps the HTTP status as the description.\n }\n throw new OAuthError(response.status, error, description);\n}\n","{\n \"name\": \"@open-banking-io/client\",\n \"version\": \"2.0.0\",\n \"description\": \"Server-to-server client for open-banking.io: API-key auth + client-side decryption of the zero-knowledge data envelopes with your exported private key.\",\n \"type\": \"module\",\n \"license\": \"MIT\",\n \"author\": \"open-banking.io\",\n \"keywords\": [\n \"open-banking\",\n \"psd2\",\n \"zero-knowledge\",\n \"encryption\",\n \"fintech\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/open-banking-io/clients\"\n },\n \"engines\": {\n \"node\": \">=20\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n }\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"test\": \"vitest run\",\n \"coverage\": \"vitest run --coverage\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format:check\": \"prettier --check .\"\n },\n \"overrides\": {\n \"esbuild\": \"^0.28.1\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^10.0.1\",\n \"@types/node\": \"^26.6.6\",\n \"@vitest/coverage-v8\": \"^5.1.1\",\n \"eslint\": \"^10.5.0\",\n \"prettier\": \"^3.8.4\",\n \"tsup\": \"^9.0.0\",\n \"typescript\": \"^6.0.3\",\n \"typescript-eslint\": \"^8.61.1\",\n \"vitest\": \"^5.1.1\"\n },\n \"homepage\": \"https://open-banking.io\"\n}\n","// The package version, sourced from package.json so it can never drift. tsup inlines the JSON at\n// build time (tree-shaken to the single string), and vitest/tsx resolve the import directly — so\n// this stays ESM/CJS-safe without a runtime file read.\nimport pkg from \"../package.json\" with { type: \"json\" };\n\nexport const VERSION: string = pkg.version;\n\n/** The `User-Agent` sent on every request: `open-banking-io/node/<version>`. */\nexport const USER_AGENT = `open-banking-io/node/${VERSION}`;\n","import { bundleFromToken, type TokenResponse } from \"./connect.js\";\nimport { readFileSync } from \"node:fs\";\nimport { decryptTo, importPrivateKey, type CryptoKey } from \"./envelope.js\";\nimport { SyncError } from \"./errors.js\";\nimport { USER_AGENT } from \"./version.js\";\nimport type {\n Account,\n AccountEnc,\n AccountWire,\n BalanceEnc,\n Connection,\n ConnectionWire,\n CredentialsBundle,\n DisplayNameEnc,\n OpenBankingClientOptions,\n PsuHeaders,\n SyncAllResult,\n SyncAllResultWire,\n SyncFailure,\n SyncOptions,\n SyncResult,\n SyncResultWire,\n Transaction,\n TransactionEnc,\n TransactionPage,\n TransactionPageWire,\n TransactionQuery,\n TransactionWire,\n UidEnc,\n} from \"./models.js\";\n\n/**\n * Server-to-server client for open-banking.io. Authenticates with an API key (`X-Api-Key`) and\n * decrypts the zero-knowledge data envelopes locally with the exported private key — the service\n * only ever returns ciphertext it cannot read.\n */\nexport class OpenBankingClient {\n /** Default per-request timeout (30s) when {@link OpenBankingClientOptions.timeoutMs} is unset. */\n static readonly DEFAULT_TIMEOUT_MS = 30_000;\n\n private readonly baseUrl: string;\n private readonly apiKey: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly privateKey: Promise<CryptoKey>;\n\n constructor(options: OpenBankingClientOptions) {\n const { apiBaseUrl, apiKey, privateKeyPkcs8, timeoutMs } = options;\n if (!apiBaseUrl?.trim()) throw new Error(\"apiBaseUrl is required\");\n if (!apiKey?.trim()) throw new Error(\"apiKey is required\");\n if (!privateKeyPkcs8?.trim()) throw new Error(\"privateKeyPkcs8 is required\");\n\n // Strip all trailing \"/\" without a backtracking regex (avoids ReDoS on long inputs).\n let end = apiBaseUrl.length;\n while (end > 0 && apiBaseUrl.charCodeAt(end - 1) === 47 /* \"/\" */) end--;\n this.baseUrl = apiBaseUrl.slice(0, end);\n this.apiKey = apiKey;\n this.timeoutMs = timeoutMs ?? OpenBankingClient.DEFAULT_TIMEOUT_MS;\n this.fetchImpl = options.fetch ?? fetch;\n this.privateKey = importPrivateKey(privateKeyPkcs8);\n }\n\n /**\n * Builds a client from a credentials-bundle JSON string or a path to a bundle file.\n *\n * `overrides` (optional) lets the bundle path set the same transport knobs as the\n * constructor — e.g. a custom {@link OpenBankingClientOptions.fetch} or\n * {@link OpenBankingClientOptions.timeoutMs}.\n */\n static fromCredentials(\n jsonOrPath: string,\n overrides: Partial<Pick<OpenBankingClientOptions, \"fetch\" | \"timeoutMs\">> = {},\n ): OpenBankingClient {\n let json = jsonOrPath;\n if (!jsonOrPath.trimStart().startsWith(\"{\")) {\n json = readFileSync(jsonOrPath, \"utf8\");\n }\n const bundle = JSON.parse(json) as CredentialsBundle;\n return OpenBankingClient.fromBundle(bundle, overrides);\n }\n\n static fromBundle(\n bundle: CredentialsBundle,\n overrides: Partial<Pick<OpenBankingClientOptions, \"fetch\" | \"timeoutMs\">> = {},\n ): OpenBankingClient {\n if (!bundle.apiKey?.trim()) throw new Error(\"The credentials bundle has no apiKey\");\n return new OpenBankingClient({\n apiBaseUrl: bundle.apiBaseUrl,\n apiKey: bundle.apiKey,\n privateKeyPkcs8: bundle.encryptionKey.privateKey,\n timeoutMs: overrides.timeoutMs,\n fetch: overrides.fetch,\n });\n }\n\n /**\n * Builds a client from a Partner Connect token response and the private key the consent page\n * relayed — see {@link exchangeCode} and {@link parseRelay}.\n */\n static fromTokenResponse(\n token: TokenResponse,\n privateKey: string,\n overrides: Partial<Pick<OpenBankingClientOptions, \"fetch\" | \"timeoutMs\">> = {},\n ): OpenBankingClient {\n return OpenBankingClient.fromBundle(bundleFromToken(token, privateKey), overrides);\n }\n\n /** Lists the user's accounts with all sensitive fields decrypted. */\n async getAccounts(): Promise<Account[]> {\n const wires = await this.getAccountWires();\n return Promise.all(wires.map((w) => this.mapAccount(w)));\n }\n\n /** Returns a page of an account's statement, newest first, with decrypted fields. */\n async getTransactions(accountId: string, query: TransactionQuery = {}): Promise<TransactionPage> {\n const qs = new URLSearchParams();\n if (query.from != null) qs.set(\"from\", query.from);\n if (query.to != null) qs.set(\"to\", query.to);\n if (query.limit != null) qs.set(\"limit\", String(query.limit));\n if (query.offset != null) qs.set(\"offset\", String(query.offset));\n const suffix = qs.toString() ? `?${qs.toString()}` : \"\";\n\n const page = await this.getJson<TransactionPageWire>(\n `/api/accounts/${encodeURIComponent(accountId)}/transactions${suffix}`,\n );\n\n const items = await Promise.all((page.items ?? []).map((t) => this.mapTransaction(t)));\n return { items, total: page.total };\n }\n\n /** Lists the user's bank connections. */\n async getConnections(): Promise<Connection[]> {\n const wires = await this.getJson<ConnectionWire[]>(\"/api/connections\");\n return wires.map((c) => ({\n sessionId: c.sessionId,\n aspspName: c.aspspName,\n aspspCountry: c.aspspCountry,\n validUntil: c.validUntil,\n status: c.status,\n accountCount: c.accountCount,\n lastSyncedAt: c.lastSyncedAt ?? null,\n psuType: c.psuType ?? null,\n isLive: c.isLive ?? (c.status === \"Active\" && Date.parse(c.validUntil) > Date.now()),\n accountIds: c.accountIds ?? [],\n }));\n }\n\n /**\n * Triggers an online sync of one account: decrypts that account's Enable Banking uid and posts\n * it, so the service can fetch fresh data without ever holding the uid in plaintext.\n *\n * A refusal throws {@link SyncError}. A uid a renewal replaced (`uid_outdated`) is re-read and\n * retried once.\n */\n async sync(accountId: string, options: SyncOptions = {}): Promise<SyncResult> {\n for (let attempt = 0; ; attempt++) {\n const wires = await this.getAccountWires();\n const account = wires.find((a) => a.id === accountId);\n if (!account) throw new Error(`Account ${accountId} not found`);\n\n const uid = account.needsReconnect ? null : await this.decryptUid(account);\n if (uid == null) {\n throw new SyncError(\n \"Account has no active session (reconnect required) — cannot sync\",\n 409,\n \"reconnect_needed\",\n );\n }\n\n try {\n const result = await this.postJson<SyncResultWire>(\n `/api/accounts/${encodeURIComponent(accountId)}/sync`,\n { uid },\n psuHeaders(options.psu),\n );\n return { newTransactions: result.newTransactions, totalFetched: result.totalFetched };\n } catch (e) {\n if (attempt === 0 && e instanceof SyncError && e.reason === \"uid_outdated\") continue;\n throw e;\n }\n }\n }\n\n /**\n * Triggers an online sync of every account that has an active session. Per-account refusals are\n * in `failures`, and so is every account whose consent needs renewing (`reconnect_needed`, never\n * sent); accounts answering `uid_outdated` are re-read and retried once.\n */\n async syncAll(options: SyncOptions = {}): Promise<SyncAllResult> {\n const read = await this.syncItems();\n const first = await this.postSyncAll(read.items, options);\n first.failures.push(...read.lapsed);\n const outdated = new Set(\n first.failures.filter((f) => f.reason === \"uid_outdated\").map((f) => f.accountId),\n );\n if (outdated.size === 0) return first;\n\n const reread = await this.syncItems();\n const retryItems = reread.items.filter((i) => outdated.has(i.accountId));\n const lapsedNow = reread.lapsed.filter((f) => outdated.has(f.accountId));\n const settled = new Set([...retryItems, ...lapsedNow].map((i) => i.accountId));\n const kept = first.failures.filter((f) => !settled.has(f.accountId));\n if (retryItems.length === 0) return { ...first, failures: [...kept, ...lapsedNow] };\n\n const second = await this.postSyncAll(retryItems, options);\n return {\n accounts: first.accounts + second.accounts,\n newTransactions: first.newTransactions + second.newTransactions,\n failures: [...kept, ...lapsedNow, ...second.failures],\n };\n }\n\n // ---- internals ---------------------------------------------------------------------------------\n\n private getAccountWires(): Promise<AccountWire[]> {\n return this.getJson<AccountWire[]>(\"/api/accounts\");\n }\n\n private async syncItems(): Promise<{\n items: { accountId: string; uid: string }[];\n lapsed: SyncFailure[];\n }> {\n const wires = await this.getAccountWires();\n const decrypted = await Promise.all(\n wires.map(async (a) => ({\n accountId: a.id,\n needsReconnect: a.needsReconnect,\n uid: a.needsReconnect ? null : await this.decryptUid(a),\n })),\n );\n return {\n items: decrypted\n .filter((x): x is typeof x & { uid: string } => x.uid != null)\n .map((x) => ({ accountId: x.accountId, uid: x.uid })),\n lapsed: decrypted\n .filter((x) => x.uid == null && x.needsReconnect)\n .map((x) => ({ accountId: x.accountId, reason: \"reconnect_needed\", bankErrorCode: null })),\n };\n }\n\n private async postSyncAll(\n items: { accountId: string; uid: string }[],\n options: SyncOptions,\n ): Promise<SyncAllResult> {\n if (items.length === 0) return { accounts: 0, newTransactions: 0, failures: [] };\n const result = await this.postJson<SyncAllResultWire>(\n \"/api/sync\",\n { items },\n psuHeaders(options.psu),\n );\n const failures: SyncFailure[] = (result.failures ?? []).map((f) => ({\n accountId: f.accountId,\n reason: f.reason,\n bankErrorCode: f.bankErrorCode ?? null,\n }));\n return { accounts: result.accounts, newTransactions: result.newTransactions, failures };\n }\n\n private async decryptUid(a: AccountWire): Promise<string | null> {\n const dec = await decryptTo<UidEnc>(await this.privateKey, a.uidEnc);\n return dec?.uid ?? null;\n }\n\n private async mapAccount(a: AccountWire): Promise<Account> {\n const priv = await this.privateKey;\n const acc = await decryptTo<AccountEnc>(priv, a.enc);\n const name = await decryptTo<DisplayNameEnc>(priv, a.displayNameEnc);\n const balances = await Promise.all(\n (a.balances ?? []).map(async (b) => {\n const dec = await decryptTo<BalanceEnc>(priv, b.enc);\n return {\n type: b.type,\n name: dec?.name ?? null,\n amount: dec?.amount ?? \"0\",\n currency: b.currency,\n referenceDate: b.referenceDate ?? null,\n };\n }),\n );\n\n return {\n id: a.id,\n aspspName: a.aspspName,\n aspspCountry: a.aspspCountry,\n currency: a.currency,\n accountType: a.accountType ?? null,\n bic: a.bic ?? null,\n needsReconnect: a.needsReconnect,\n iban: acc?.iban ?? null,\n bban: acc?.bban ?? null,\n ownerName: acc?.ownerName ?? null,\n accountName: acc?.accountName ?? null,\n product: acc?.product ?? null,\n displayName: name?.displayName ?? null,\n balances,\n };\n }\n\n private async mapTransaction(t: TransactionWire): Promise<Transaction> {\n const d = await decryptTo<TransactionEnc>(await this.privateKey, t.enc);\n return {\n id: t.id,\n currency: t.currency,\n creditDebitIndicator: t.creditDebitIndicator,\n status: t.status ?? null,\n bookingDate: t.bookingDate ?? null,\n valueDate: t.valueDate ?? null,\n transactionDate: t.transactionDate ?? null,\n bankTransactionCode: t.bankTransactionCode ?? null,\n amount: d?.amount ?? \"0\",\n creditorName: d?.creditorName ?? null,\n creditorIban: d?.creditorIban ?? null,\n creditorBban: d?.creditorBban ?? null,\n creditorAgentBic: d?.creditorAgentBic ?? null,\n debtorName: d?.debtorName ?? null,\n debtorIban: d?.debtorIban ?? null,\n debtorBban: d?.debtorBban ?? null,\n debtorAgentBic: d?.debtorAgentBic ?? null,\n remittanceInformation: d?.remittanceInformation ?? null,\n note: d?.note ?? null,\n referenceNumber: d?.referenceNumber ?? null,\n exchangeRate: d?.exchangeRate ?? null,\n merchantCategoryCode: d?.merchantCategoryCode ?? null,\n balanceAfterTransaction: d?.balanceAfter ?? null,\n balanceAfterCurrency: d?.balanceAfterCurrency ?? null,\n };\n }\n\n private async getJson<T>(path: string): Promise<T> {\n const res = await this.fetchImpl(this.baseUrl + path, {\n headers: { \"X-Api-Key\": this.apiKey, \"User-Agent\": USER_AGENT },\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n if (!res.ok) {\n throw new Error(`GET ${path} failed: ${res.status} ${res.statusText}`);\n }\n return (await res.json()) as T;\n }\n\n private async postJson<T>(\n path: string,\n body: unknown,\n extraHeaders: Record<string, string> = {},\n ): Promise<T> {\n const res = await this.fetchImpl(this.baseUrl + path, {\n method: \"POST\",\n headers: {\n ...extraHeaders,\n \"X-Api-Key\": this.apiKey,\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n if (!res.ok) {\n const problem = await readProblem(res);\n const retryAfter = Number.parseInt(res.headers.get(\"Retry-After\") ?? \"\", 10);\n throw new SyncError(\n `POST ${path} failed: ${res.status} ${problem.reason ?? res.statusText}`,\n res.status,\n problem.reason,\n problem.bankErrorCode,\n Number.isFinite(retryAfter) ? retryAfter : null,\n );\n }\n return (await res.json()) as T;\n }\n}\n\nasync function readProblem(\n res: Response,\n): Promise<{ reason: string | null; bankErrorCode: string | null }> {\n try {\n const body = (await res.json()) as { reason?: unknown; bankErrorCode?: unknown };\n return {\n reason: typeof body.reason === \"string\" ? body.reason : null,\n bankErrorCode: typeof body.bankErrorCode === \"string\" ? body.bankErrorCode : null,\n };\n } catch {\n return { reason: null, bankErrorCode: null };\n }\n}\n\n/** The `X-Psu-*` request headers for a forwarded {@link PsuHeaders}; empty when none is given. */\nexport function psuHeaders(psu: PsuHeaders | undefined): Record<string, string> {\n if (!psu?.ipAddress || !psu.userAgent) return {};\n const headers: Record<string, string> = {\n \"X-Psu-Ip-Address\": psu.ipAddress,\n \"X-Psu-User-Agent\": psu.userAgent,\n };\n const optional: [string, string | undefined][] = [\n [\"X-Psu-Referer\", psu.referer],\n [\"X-Psu-Accept\", psu.accept],\n [\"X-Psu-Accept-Language\", psu.acceptLanguage],\n [\"X-Psu-Accept-Charset\", psu.acceptCharset],\n [\"X-Psu-Accept-Encoding\", psu.acceptEncoding],\n ];\n for (const [name, value] of optional) if (value) headers[name] = value;\n return headers;\n}\n","import { webcrypto } from \"node:crypto\";\n\nconst { subtle } = webcrypto;\n\n/** Re-export the WebCrypto key type so callers don't depend on the DOM lib. */\nexport type CryptoKey = webcrypto.CryptoKey;\n\nconst VERSION = 0x01;\nconst POINT_LEN = 65;\nconst NONCE_LEN = 12;\nconst TAG_LEN = 16;\n\nconst HKDF_INFO = new TextEncoder().encode(\"bank.core.ci/zk/v1\");\nconst HKDF_SALT = new Uint8Array(32); // 32 zero bytes (must be exactly this).\n\n/**\n * Decrypts open-banking.io's zero-knowledge data envelopes.\n * Scheme: ephemeral ECDH on NIST P-256 -> HKDF-SHA256 -> AES-256-GCM.\n * Wire: `version(1)=0x01 | ephemeralPublicKeyRaw(65) | nonce(12) | tag(16) | ciphertext`.\n * Only the user's private key can decrypt — the service stores ciphertext it cannot read.\n */\nexport async function decryptEnvelope(\n privateKey: CryptoKey,\n envelopeBase64: string,\n): Promise<Uint8Array> {\n const bytes = base64ToBytes(envelopeBase64);\n if (bytes.length < 1 + POINT_LEN + NONCE_LEN + TAG_LEN || bytes[0] !== VERSION) {\n throw new Error(\"Invalid or unsupported envelope\");\n }\n\n const ephPub = bytes.subarray(1, 1 + POINT_LEN);\n const nonce = bytes.subarray(1 + POINT_LEN, 1 + POINT_LEN + NONCE_LEN);\n const tag = bytes.subarray(1 + POINT_LEN + NONCE_LEN, 1 + POINT_LEN + NONCE_LEN + TAG_LEN);\n const ciphertext = bytes.subarray(1 + POINT_LEN + NONCE_LEN + TAG_LEN);\n\n // Guard against invalid-curve attacks: WebCrypto's P-256 `importKey` validates that the raw point\n // lies on the curve and is not the point at infinity, so a forged/off-curve ephemeral public key\n // throws here rather than yielding a derivable (and exploitable) shared secret below.\n const ephKey = await subtle.importKey(\n \"raw\",\n ephPub,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false,\n [],\n );\n\n const shared = new Uint8Array(\n await subtle.deriveBits({ name: \"ECDH\", public: ephKey }, privateKey, 256),\n );\n\n const hkdf = await subtle.importKey(\"raw\", shared, \"HKDF\", false, [\"deriveKey\"]);\n\n const aesKey = await subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: HKDF_SALT, info: HKDF_INFO },\n hkdf,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"decrypt\"],\n );\n\n // Web Crypto AES-GCM expects ciphertext||tag.\n const ctWithTag = new Uint8Array(ciphertext.length + tag.length);\n ctWithTag.set(ciphertext, 0);\n ctWithTag.set(tag, ciphertext.length);\n\n const plaintext = await subtle.decrypt(\n { name: \"AES-GCM\", iv: nonce, tagLength: 128 },\n aesKey,\n ctWithTag,\n );\n\n return new Uint8Array(plaintext);\n}\n\n/** Decrypts a base64 envelope and JSON-parses its payload. `null`/`undefined` in -> `null`. */\nexport async function decryptTo<T>(\n privateKey: CryptoKey,\n envelopeBase64: string | null | undefined,\n): Promise<T | null> {\n if (envelopeBase64 == null) return null;\n const plaintext = await decryptEnvelope(privateKey, envelopeBase64);\n return JSON.parse(new TextDecoder().decode(plaintext)) as T;\n}\n\n/** Imports a base64 PKCS#8 P-256 ECDH private key for use with {@link decryptEnvelope}. */\nexport async function importPrivateKey(pkcs8Base64: string): Promise<CryptoKey> {\n return subtle.importKey(\n \"pkcs8\",\n base64ToBytes(pkcs8Base64),\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false,\n [\"deriveBits\"],\n );\n}\n\nfunction base64ToBytes(b64: string): Uint8Array<ArrayBuffer> {\n return new Uint8Array(Buffer.from(b64, \"base64\"));\n}\n","import type { SyncFailureReason } from \"./models.js\";\n\n/** A sync the service refused. `reason` is the stable code to branch on. */\nexport class SyncError extends Error {\n readonly status: number;\n readonly reason: SyncFailureReason | null;\n readonly bankErrorCode: string | null;\n readonly retryAfterSeconds: number | null;\n\n constructor(\n message: string,\n status: number,\n reason: SyncFailureReason | null,\n bankErrorCode: string | null = null,\n retryAfterSeconds: number | null = null,\n ) {\n super(message);\n this.name = \"SyncError\";\n this.status = status;\n this.reason = reason;\n this.bankErrorCode = bankErrorCode;\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n","import { OAuthError, revokeToken, userinfo, type HttpOptions } from \"./connect.js\";\nimport { decryptTo, importPrivateKey } from \"./envelope.js\";\nimport type { OpenConsentWire, SessionIdEnc } from \"./models.js\";\nimport { USER_AGENT } from \"./version.js\";\n\nexport interface CloseReplacedConsentsOptions extends HttpOptions {\n issuer: string;\n clientId: string;\n clientSecret: string;\n /** The PREVIOUS key — the one issued before the renewal. It is revoked by this call. */\n token: string;\n /** The base64 PKCS#8 private key the consents are sealed to. */\n privateKey: string;\n /** Defaults to the issuer. */\n apiBaseUrl?: string;\n}\n\nexport interface CloseReplacedConsentsResult {\n /** Consents sent to be closed at the bank. */\n closed: number;\n /** Consents listed but not closable (no envelope, or it would not decrypt). */\n failed: number;\n /** Whether the previous key is gone. When false, revoke it yourself. */\n revoked: boolean;\n}\n\n/**\n * After a renewal: closes, at the bank, the consents the previous key still has open, and revokes\n * that key in the same call. Reads `GET /api/connections/open-consents` only — never the live\n * connections, which by now hold the renewal. A key that is already gone, or was issued to another\n * client, closes nothing: the service answers such a revoke with 200 without closing anything. A\n * failure that retrying may clear (5xx, 429) throws, so the key survives for a retry: revoking it\n * without the close would leave the consents open with nothing left that can list them.\n */\nexport async function closeReplacedConsents(\n options: CloseReplacedConsentsOptions,\n): Promise<CloseReplacedConsentsResult> {\n const fetchImpl = options.fetch ?? fetch;\n const base = trimSlash(options.apiBaseUrl ?? options.issuer);\n const nothing = { closed: 0, failed: 0, revoked: false };\n\n let owner: string | null;\n try {\n owner = (await userinfo({ ...options, accessToken: options.token })).clientId;\n } catch (e) {\n if (e instanceof OAuthError && keyRefused(e.status)) return nothing;\n throw e;\n }\n if (owner !== options.clientId) return nothing;\n\n const res = await fetchImpl(`${base}/api/connections/open-consents`, {\n headers: { \"X-Api-Key\": options.token, \"User-Agent\": USER_AGENT },\n signal: AbortSignal.timeout(options.timeoutMs ?? 30_000),\n });\n if (keyRefused(res.status)) return nothing;\n if (!res.ok) throw new Error(`GET /api/connections/open-consents failed: ${res.status}`);\n const open = (await res.json()) as OpenConsentWire[];\n\n const key = await importPrivateKey(options.privateKey);\n const closeConsents: { connectionId: string; ebSessionId: string }[] = [];\n const seen = new Set<string>();\n let failed = 0;\n for (const c of open) {\n if (!c.connectionId || seen.has(c.connectionId)) continue;\n seen.add(c.connectionId);\n if (!c.sessionIdEnc) {\n failed += 1;\n continue;\n }\n let sessionId: string | null | undefined;\n try {\n sessionId = (await decryptTo<SessionIdEnc>(key, c.sessionIdEnc))?.sessionId;\n } catch {\n sessionId = null;\n }\n if (!sessionId) {\n failed += 1;\n continue;\n }\n closeConsents.push({ connectionId: c.connectionId, ebSessionId: sessionId });\n }\n\n try {\n await revokeToken({ ...options, closeConsents });\n } catch (e) {\n if (e instanceof OAuthError && e.status < 500 && e.status !== 429)\n return { closed: 0, failed: failed + closeConsents.length, revoked: false };\n throw e;\n }\n return { closed: closeConsents.length, failed, revoked: true };\n}\n\nconst keyRefused = (status: number) => status === 401 || status === 403;\n\nfunction trimSlash(url: string): string {\n let end = url.length;\n while (end > 0 && url.charCodeAt(end - 1) === 47) end--;\n return url.slice(0, end);\n}\n","import { createHash, webcrypto } from \"node:crypto\";\nimport { decryptTo, importPrivateKey } from \"./envelope.js\";\n\nconst subtle = webcrypto.subtle;\n\n/** A partner's recipient (decryption) key pair. The private half is a credential: never log it. */\nexport interface RecipientKeyPair {\n /** Base64 PKCS#8 — what your deployment loads. */\n privateKeyPkcs8Base64: string;\n /** Base64 raw 65-byte uncompressed P-256 point — what you install on your partner page. */\n publicKeyRawBase64: string;\n}\n\n/**\n * Generates the P-256 pair a partner installs on open-banking.io. The public half goes into\n * `PUT /api/partner/recipient-key` (or the partner page's paste box); keep the private half\n * where your deployment can read it — the service never sees it and cannot recover it.\n */\nexport async function generateRecipientKeyPair(): Promise<RecipientKeyPair> {\n const pair = await subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-256\" }, true, [\n \"deriveBits\",\n ]);\n return {\n privateKeyPkcs8Base64: Buffer.from(await subtle.exportKey(\"pkcs8\", pair.privateKey)).toString(\n \"base64\",\n ),\n publicKeyRawBase64: Buffer.from(await subtle.exportKey(\"raw\", pair.publicKey)).toString(\n \"base64\",\n ),\n };\n}\n\n/**\n * The fingerprint the partner page and the admin show for a key: SHA-256 of the raw 65-byte\n * point, lowercase hex, first 16 characters. Print it at boot and compare after every deploy.\n */\nexport function recipientKeyFingerprint(publicKeyRawBase64: string): string {\n return createHash(\"sha256\")\n .update(Buffer.from(publicKeyRawBase64, \"base64\"))\n .digest(\"hex\")\n .slice(0, 16);\n}\n\n/** The raw public point of a PKCS#8 private key — to fingerprint or re-install the key you hold. */\nexport async function recipientPublicKey(privateKeyPkcs8Base64: string): Promise<string> {\n const key = await subtle.importKey(\n \"pkcs8\",\n Buffer.from(privateKeyPkcs8Base64, \"base64\"),\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"],\n );\n const jwk = await subtle.exportKey(\"jwk\", key);\n if (!jwk.x || !jwk.y) throw new Error(\"The private key carries no public point\");\n return Buffer.concat([\n Buffer.from([0x04]),\n Buffer.from(jwk.x, \"base64url\"),\n Buffer.from(jwk.y, \"base64url\"),\n ]).toString(\"base64\");\n}\n\n/**\n * Answers the possession challenge from `POST /api/partner/recipient-key/challenge`: opens\n * the envelope with the private half and returns the nonce — the `challengeAnswer` for the install.\n */\nexport async function answerRecipientKeyChallenge(\n privateKeyPkcs8Base64: string,\n envelopeBase64: string,\n): Promise<string> {\n const payload = await decryptTo<{ nonce?: unknown }>(\n await importPrivateKey(privateKeyPkcs8Base64),\n envelopeBase64,\n );\n const nonce = payload?.nonce;\n if (typeof nonce !== \"string\" || nonce.length === 0)\n throw new Error(\"The challenge envelope carries no nonce\");\n return nonce;\n}\n"],"mappings":";AAEA,SAAS,YAAY,aAAa,uBAAuB;;;ACFzD;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,QAAU;AAAA,EACV,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,EACT;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,EACF;AAAA,EACA,MAAQ;AAAA,EACR,QAAU;AAAA,EACV,OAAS;AAAA,EACT,SAAW;AAAA,IACT,KAAK;AAAA,MACH,OAAS;AAAA,MACT,QAAU;AAAA,MACV,SAAW;AAAA,IACb;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,IACT,MAAQ;AAAA,IACR,UAAY;AAAA,IACZ,WAAa;AAAA,IACb,MAAQ;AAAA,IACR,gBAAgB;AAAA,EAClB;AAAA,EACA,WAAa;AAAA,IACX,SAAW;AAAA,EACb;AAAA,EACA,iB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C,IAAI,EAAG,OAAM,IAAI,MAAM,yCAAyC;AAC/E,SAAO,OAAO,OAAO;AAAA,IACnB,OAAO,KAAK,CAAC,CAAI,CAAC;AAAA,IAClB,OAAO,KAAK,IAAI,GAAG,WAAW;AAAA,IAC9B,OAAO,KAAK,IAAI,GAAG,WAAW;AAAA,EAChC,CAAC,EAAE,SAAS,QAAQ;AACtB;AAMA,eAAsB,4BACpB,uBACA,gBACiB;AACjB,QAAM,UAAU,MAAM;AAAA,IACpB,MAAM,iBAAiB,qBAAqB;AAAA,IAC5C;AAAA,EACF;AACA,QAAM,QAAQ,SAAS;AACvB,MAAI,OAAO,UAAU,YAAY,MAAM,WAAW;AAChD,UAAM,IAAI,MAAM,yCAAyC;AAC3D,SAAO;AACT;","names":["VERSION","trimSlash","createHash","webcrypto","subtle","webcrypto","createHash"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-banking-io/client",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Server-to-server client for open-banking.io: API-key auth + client-side decryption of the zero-knowledge data envelopes with your exported private key.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -46,14 +46,14 @@
|
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
48
|
"@eslint/js": "^10.0.1",
|
|
49
|
-
"@types/node": "^
|
|
50
|
-
"@vitest/coverage-v8": "^
|
|
49
|
+
"@types/node": "^26.6.6",
|
|
50
|
+
"@vitest/coverage-v8": "^5.1.1",
|
|
51
51
|
"eslint": "^10.5.0",
|
|
52
52
|
"prettier": "^3.8.4",
|
|
53
|
-
"tsup": "^
|
|
53
|
+
"tsup": "^9.0.0",
|
|
54
54
|
"typescript": "^6.0.3",
|
|
55
55
|
"typescript-eslint": "^8.61.1",
|
|
56
|
-
"vitest": "^
|
|
56
|
+
"vitest": "^5.1.1"
|
|
57
57
|
},
|
|
58
58
|
"homepage": "https://open-banking.io"
|
|
59
59
|
}
|