@open-banking-io/client 1.1.0 → 1.2.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/README.md CHANGED
@@ -49,10 +49,33 @@ Every request carries a `User-Agent: open-banking-io/node/<version>` header and
49
49
 
50
50
  ## Partner Connect (OAuth 2.0 + PKCE)
51
51
 
52
- Partners let their users connect banks through open-banking.io and receive a delegated key plus the
53
- user's private key — a standard authorization-code flow with PKCE and `form_post`, documented at
54
- [open-banking.io/en/docs/partners](https://open-banking.io/en/docs/partners). The `connect` helpers
55
- cover every step; keep the client secret and the verifier on your server.
52
+ Partners let their users connect banks through open-banking.io — a standard authorization-code
53
+ flow with PKCE and `form_post`, documented at
54
+ [open-banking.io/en/docs/partners](https://open-banking.io/en/docs/partners). You hold your own
55
+ **decryption key**: every user who connects through your client is encrypted to it, and you
56
+ decrypt their data with the one private half your deployment loads. The service keeps only the
57
+ public half and cannot recover the private one. Install it first — until you do, a Connect
58
+ client cannot be registered and every authorization answers `temporarily_unavailable`.
59
+
60
+ ```ts
61
+ import {
62
+ answerRecipientKeyChallenge,
63
+ generateRecipientKeyPair,
64
+ recipientKeyFingerprint,
65
+ recipientPublicKey,
66
+ } from "@open-banking-io/client";
67
+
68
+ // 0. Once: generate the pair, keep privateKeyPkcs8Base64 in your secret store, and install
69
+ // publicKeyRawBase64 on your partner page (https://open-banking.io/app/partner#decryption-key
70
+ // does all of this in the browser, if you prefer). Print the fingerprint at boot and compare it
71
+ // with the one the partner page shows after every deploy.
72
+ const pair = await generateRecipientKeyPair();
73
+ console.log(recipientKeyFingerprint(pair.publicKeyRawBase64));
74
+ // Bringing a key generated elsewhere? The partner page hands you an envelope to prove you hold it:
75
+ const answer = await answerRecipientKeyChallenge(RECIPIENT_PRIVATE_KEY, envelope);
76
+ ```
77
+
78
+ The flow itself: keep the client secret and the verifier on your server.
56
79
 
57
80
  ```ts
58
81
  import {
@@ -69,6 +92,8 @@ import {
69
92
  const ISSUER = "https://open-banking.io";
70
93
 
71
94
  // 1. Start: keep the verifier server-side, keyed by state, and send the browser to the URL.
95
+ // challenge: "pin_code" gives the user a typed code instead of a magic link — recommended for
96
+ // every journey, and required for a popup.
72
97
  app.get("/connect", async (req, res) => {
73
98
  const pkce = createPkce();
74
99
  const state = createState();
@@ -78,7 +103,7 @@ app.get("/connect", async (req, res) => {
78
103
  verifier: pkce.verifier,
79
104
  sessionId: req.session.id,
80
105
  mode,
81
- expiresAt: Date.now() + 600_000,
106
+ expiresAt: Date.now() + 45 * 60_000,
82
107
  });
83
108
  res.redirect(
84
109
  buildAuthorizeUrl({
@@ -87,12 +112,12 @@ app.get("/connect", async (req, res) => {
87
112
  redirectUri: `${SELF_URL}/callback`,
88
113
  state,
89
114
  codeChallenge: pkce.challenge,
90
- ...(mode === "popup" && { challenge: "pin_code" }),
115
+ challenge: "pin_code",
91
116
  }),
92
117
  );
93
118
  });
94
119
 
95
- // 2. Callback: the consent page form-posts code, state, iss, privateKey and publicKey — or
120
+ // 2. Callback: the consent page form-posts code, state, iss and (empty) privateKey/publicKey — or
96
121
  // error=access_denied when the user went back to you. Consume the flow by state first, so a
97
122
  // cancel consumes it too; the lookup is what binds the POST to the session that started it.
98
123
  app.post("/callback", express.urlencoded({ extended: false }), async (req, res) => {
@@ -101,10 +126,20 @@ app.post("/callback", express.urlencoded({ extended: false }), async (req, res)
101
126
  if (!flow || flow.expiresAt < Date.now()) return res.status(400).send("unknown or expired state");
102
127
  let relay;
103
128
  try {
104
- relay = parseRelay(req.body, { expectedState: flow.state, issuer });
129
+ relay = parseRelay(req.body, {
130
+ expectedState: flow.state,
131
+ issuer,
132
+ expectPrivateKey: "optional",
133
+ });
105
134
  } catch (e) {
106
135
  if (e instanceof RelayError && e.code === "access_denied")
107
136
  return finish(res, flow, "cancelled");
137
+ if (e instanceof RelayError && e.reason) {
138
+ // partner_key_missing or partner_suspended: your side, not the bank's — install the key on
139
+ // your partner page, or write to us. The user only sees "unavailable".
140
+ console.error("connect refused:", e.reason);
141
+ return finish(res, flow, "unavailable");
142
+ }
108
143
  throw e;
109
144
  }
110
145
  const token = await exchangeCode({
@@ -115,7 +150,9 @@ app.post("/callback", express.urlencoded({ extended: false }), async (req, res)
115
150
  codeVerifier: flow.verifier,
116
151
  redirectUri: `${SELF_URL}/callback`,
117
152
  });
118
- await bundles.put(flow.sessionId, { token, privateKey: relay.privateKey });
153
+ // One key per deployment, so store the token alone. A user who connected before your key was
154
+ // installed still relays their own private key — keep it with their token when present.
155
+ await bundles.put(flow.sessionId, { token, legacyPrivateKey: relay.privateKey || undefined });
119
156
  finish(res, flow, "connected");
120
157
  });
121
158
 
@@ -126,20 +163,26 @@ const finish = (res, flow, outcome) =>
126
163
  : res.send(closePage(outcome));
127
164
  const closePage = (
128
165
  outcome,
129
- ) => `<!doctype html><p>${outcome === "connected" ? "Connected — you can close this window." : "Cancelled."}</p>
166
+ ) => `<!doctype html><p>${outcome === "connected" ? "Connected — you can close this window." : outcome === "unavailable" ? "Unavailable right now — try again later." : "Cancelled."}</p>
130
167
  <script>try{new BroadcastChannel("bank-connect").postMessage(${JSON.stringify(outcome)})}catch{}setTimeout(()=>window.close(),300)</script>`;
131
168
 
132
- // 3. Read (inside any handler that has the stored pair): the token plus the relayed private key
133
- // is a complete credentials bundle.
134
- const { token, privateKey } = await bundles.get(req.session.id);
135
- const client = OpenBankingClient.fromTokenResponse(token, privateKey);
169
+ // 3. Read (inside any handler that has the stored token): the token plus your decryption key —
170
+ // or the user's own key, for the few who connected before you had one — is a complete bundle.
171
+ const { token, legacyPrivateKey } = await bundles.get(req.session.id);
172
+ const client = OpenBankingClient.fromTokenResponse(
173
+ token,
174
+ legacyPrivateKey ?? RECIPIENT_PRIVATE_KEY,
175
+ );
136
176
  const accounts = await client.getAccounts();
137
177
  ```
138
178
 
139
179
  `parseRelay` throws a `RelayError` (`access_denied` — the user cancelled, a normal outcome —
140
- `oauth_error`, `state_mismatch`, `issuer_mismatch`, `missing_code`, `missing_private_key`) and compares `state` and `iss` in constant time;
141
- `exchangeCode`, `revokeToken` and `userinfo` throw an `OAuthError` carrying the RFC 6749 `error`
142
- and `error_description`. An `invalid_grant` is terminal for that code — restart the flow.
180
+ `oauth_error`, `state_mismatch`, `issuer_mismatch`, `missing_code`, `missing_private_key`) and
181
+ compares `state` and `iss` in constant time. On an `oauth_error`, `reason` is `partner_key_missing`
182
+ or `partner_suspended` when the server said so in as many words. `exchangeCode`, `revokeToken` and
183
+ `userinfo` throw an `OAuthError` carrying the RFC 6749 `error` and `error_description`. An
184
+ `invalid_grant` is terminal for that code — restart the flow. A flow is valid for 45 minutes on the
185
+ server; keep your own `state` at least that long.
143
186
 
144
187
  ## Money
145
188
 
package/dist/index.cjs CHANGED
@@ -23,7 +23,10 @@ __export(index_exports, {
23
23
  CONNECT_RELAY_FIELDS: () => CONNECT_RELAY_FIELDS,
24
24
  OAuthError: () => OAuthError,
25
25
  OpenBankingClient: () => OpenBankingClient,
26
+ PARTNER_KEY_MISSING_DESCRIPTION: () => PARTNER_KEY_MISSING_DESCRIPTION,
27
+ PARTNER_SUSPENDED_DESCRIPTION: () => PARTNER_SUSPENDED_DESCRIPTION,
26
28
  RelayError: () => RelayError,
29
+ answerRecipientKeyChallenge: () => answerRecipientKeyChallenge,
27
30
  buildAuthorizeUrl: () => buildAuthorizeUrl,
28
31
  bundleFromToken: () => bundleFromToken,
29
32
  createPkce: () => createPkce,
@@ -32,9 +35,12 @@ __export(index_exports, {
32
35
  decryptTo: () => decryptTo,
33
36
  discover: () => discover,
34
37
  exchangeCode: () => exchangeCode,
38
+ generateRecipientKeyPair: () => generateRecipientKeyPair,
35
39
  importPrivateKey: () => importPrivateKey,
36
40
  parseRelay: () => parseRelay,
37
41
  pkceChallenge: () => pkceChallenge,
42
+ recipientKeyFingerprint: () => recipientKeyFingerprint,
43
+ recipientPublicKey: () => recipientPublicKey,
38
44
  revokeToken: () => revokeToken,
39
45
  userinfo: () => userinfo
40
46
  });
@@ -46,7 +52,7 @@ var import_node_crypto = require("crypto");
46
52
  // package.json
47
53
  var package_default = {
48
54
  name: "@open-banking-io/client",
49
- version: "1.1.0",
55
+ version: "1.2.0",
50
56
  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.",
51
57
  type: "module",
52
58
  license: "MIT",
@@ -137,16 +143,27 @@ function buildAuthorizeUrl(options) {
137
143
  if (options.uiLocales) params.set("ui_locales", options.uiLocales);
138
144
  return `${endpoint(options.issuer, "/oauth/authorize")}?${params.toString()}`;
139
145
  }
146
+ var PARTNER_KEY_MISSING_DESCRIPTION = "this partner has not installed its decryption key; no authorizations can be started until it does";
147
+ var PARTNER_SUSPENDED_DESCRIPTION = "this partner is suspended; no authorizations can be started";
148
+ function refusalReason(error, description) {
149
+ if (error !== "temporarily_unavailable") return void 0;
150
+ if (description === PARTNER_KEY_MISSING_DESCRIPTION) return "partner_key_missing";
151
+ if (description === PARTNER_SUSPENDED_DESCRIPTION) return "partner_suspended";
152
+ return void 0;
153
+ }
140
154
  var RelayError = class extends Error {
141
155
  code;
142
156
  error;
143
157
  errorDescription;
158
+ /** Set on an `oauth_error` whose description names a partner-side refusal. */
159
+ reason;
144
160
  constructor(code, message, oauth) {
145
161
  super(message);
146
162
  this.name = "RelayError";
147
163
  this.code = code;
148
164
  this.error = oauth?.error;
149
165
  this.errorDescription = oauth?.errorDescription;
166
+ this.reason = oauth ? refusalReason(oauth.error, oauth.errorDescription ?? "") : void 0;
150
167
  }
151
168
  };
152
169
  function parseRelay(input, options) {
@@ -179,7 +196,9 @@ function parseRelay(input, options) {
179
196
  const code = read("code");
180
197
  if (!code) throw new RelayError("missing_code", "The relay carries no authorization code");
181
198
  const privateKey = read("privateKey");
182
- if (!privateKey) throw new RelayError("missing_private_key", "The relay carries no private key");
199
+ if (!privateKey && (options.expectPrivateKey ?? "required") === "required") {
200
+ throw new RelayError("missing_private_key", "The relay carries no private key");
201
+ }
183
202
  return { code, state: read("state"), iss, privateKey, publicKey: read("publicKey") };
184
203
  }
185
204
  var OAuthError = class extends Error {
@@ -650,12 +669,61 @@ var OpenBankingClient = class _OpenBankingClient {
650
669
  return await res.json();
651
670
  }
652
671
  };
672
+
673
+ // src/recipientKey.ts
674
+ var import_node_crypto3 = require("crypto");
675
+ var subtle2 = import_node_crypto3.webcrypto.subtle;
676
+ async function generateRecipientKeyPair() {
677
+ const pair = await subtle2.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, [
678
+ "deriveBits"
679
+ ]);
680
+ return {
681
+ privateKeyPkcs8Base64: Buffer.from(await subtle2.exportKey("pkcs8", pair.privateKey)).toString(
682
+ "base64"
683
+ ),
684
+ publicKeyRawBase64: Buffer.from(await subtle2.exportKey("raw", pair.publicKey)).toString(
685
+ "base64"
686
+ )
687
+ };
688
+ }
689
+ function recipientKeyFingerprint(publicKeyRawBase64) {
690
+ return (0, import_node_crypto3.createHash)("sha256").update(Buffer.from(publicKeyRawBase64, "base64")).digest("hex").slice(0, 16);
691
+ }
692
+ async function recipientPublicKey(privateKeyPkcs8Base64) {
693
+ const key = await subtle2.importKey(
694
+ "pkcs8",
695
+ Buffer.from(privateKeyPkcs8Base64, "base64"),
696
+ { name: "ECDH", namedCurve: "P-256" },
697
+ true,
698
+ ["deriveBits"]
699
+ );
700
+ const jwk = await subtle2.exportKey("jwk", key);
701
+ if (!jwk.x || !jwk.y) throw new Error("The private key carries no public point");
702
+ return Buffer.concat([
703
+ Buffer.from([4]),
704
+ Buffer.from(jwk.x, "base64url"),
705
+ Buffer.from(jwk.y, "base64url")
706
+ ]).toString("base64");
707
+ }
708
+ async function answerRecipientKeyChallenge(privateKeyPkcs8Base64, envelopeBase64) {
709
+ const payload = await decryptTo(
710
+ await importPrivateKey(privateKeyPkcs8Base64),
711
+ envelopeBase64
712
+ );
713
+ const nonce = payload?.nonce;
714
+ if (typeof nonce !== "string" || nonce.length === 0)
715
+ throw new Error("The challenge envelope carries no nonce");
716
+ return nonce;
717
+ }
653
718
  // Annotate the CommonJS export names for ESM import in node:
654
719
  0 && (module.exports = {
655
720
  CONNECT_RELAY_FIELDS,
656
721
  OAuthError,
657
722
  OpenBankingClient,
723
+ PARTNER_KEY_MISSING_DESCRIPTION,
724
+ PARTNER_SUSPENDED_DESCRIPTION,
658
725
  RelayError,
726
+ answerRecipientKeyChallenge,
659
727
  buildAuthorizeUrl,
660
728
  bundleFromToken,
661
729
  createPkce,
@@ -664,9 +732,12 @@ var OpenBankingClient = class _OpenBankingClient {
664
732
  decryptTo,
665
733
  discover,
666
734
  exchangeCode,
735
+ generateRecipientKeyPair,
667
736
  importPrivateKey,
668
737
  parseRelay,
669
738
  pkceChallenge,
739
+ recipientKeyFingerprint,
740
+ recipientPublicKey,
670
741
  revokeToken,
671
742
  userinfo
672
743
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/connect.ts","../package.json","../src/version.ts","../src/client.ts","../src/envelope.ts"],"sourcesContent":["export { OpenBankingClient } from \"./client.js\";\nexport { decryptEnvelope, decryptTo, importPrivateKey } from \"./envelope.js\";\nexport {\n buildAuthorizeUrl,\n bundleFromToken,\n CONNECT_RELAY_FIELDS,\n createPkce,\n createState,\n discover,\n exchangeCode,\n OAuthError,\n parseRelay,\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 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 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\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 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/**\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\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 }\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\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) throw new RelayError(\"missing_private_key\", \"The relay carries no private key\");\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\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 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 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.1.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 { 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 SyncAllResult,\n SyncAllResultWire,\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 }));\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 async sync(accountId: string): Promise<SyncResult> {\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 = await this.decryptUid(account);\n if (uid == null) {\n throw new Error(\"Account has no active session (reconnect required) — cannot sync\");\n }\n\n const result = await this.postJson<SyncResultWire>(\n `/api/accounts/${encodeURIComponent(accountId)}/sync`,\n { uid },\n );\n return { newTransactions: result.newTransactions, totalFetched: result.totalFetched };\n }\n\n /** Triggers an online sync of every account that has an active session. */\n async syncAll(): Promise<SyncAllResult> {\n const wires = await this.getAccountWires();\n const decrypted = await Promise.all(\n wires.map(async (a) => ({ accountId: a.id, uid: await this.decryptUid(a) })),\n );\n const items = decrypted\n .filter((x): x is { accountId: string; uid: string } => x.uid != null)\n .map((x) => ({ accountId: x.accountId, uid: x.uid }));\n\n const result = await this.postJson<SyncAllResultWire>(\"/api/sync\", { items });\n return { accounts: result.accounts, newTransactions: result.newTransactions };\n }\n\n // ---- internals ---------------------------------------------------------------------------------\n\n private getAccountWires(): Promise<AccountWire[]> {\n return this.getJson<AccountWire[]>(\"/api/accounts\");\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>(path: string, body: unknown): Promise<T> {\n const res = await this.fetchImpl(this.baseUrl + path, {\n method: \"POST\",\n headers: {\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 throw new Error(`POST ${path} failed: ${res.status} ${res.statusText}`);\n }\n return (await res.json()) as T;\n }\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;A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MAAc,MAA2B;AACjE,UAAM,MAAM,MAAM,KAAK,UAAU,KAAK,UAAU,MAAM;AAAA,MACpD,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,aAAa,KAAK;AAAA,QAClB,gBAAgB;AAAA,QAChB,cAAc;AAAA,MAChB;AAAA,MACA,MAAM,KAAK,UAAU,IAAI;AAAA,MACzB,QAAQ,YAAY,QAAQ,KAAK,SAAS;AAAA,IAC5C,CAAC;AACD,QAAI,CAAC,IAAI,IAAI;AACX,YAAM,IAAI,MAAM,QAAQ,IAAI,YAAY,IAAI,MAAM,IAAI,IAAI,UAAU,EAAE;AAAA,IACxE;AACA,WAAQ,MAAM,IAAI,KAAK;AAAA,EACzB;AACF;","names":["import_node_crypto","VERSION"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/connect.ts","../package.json","../src/version.ts","../src/client.ts","../src/envelope.ts","../src/recipientKey.ts"],"sourcesContent":["export { OpenBankingClient } from \"./client.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 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\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 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\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 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.2.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 { 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 SyncAllResult,\n SyncAllResultWire,\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 }));\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 async sync(accountId: string): Promise<SyncResult> {\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 = await this.decryptUid(account);\n if (uid == null) {\n throw new Error(\"Account has no active session (reconnect required) — cannot sync\");\n }\n\n const result = await this.postJson<SyncResultWire>(\n `/api/accounts/${encodeURIComponent(accountId)}/sync`,\n { uid },\n );\n return { newTransactions: result.newTransactions, totalFetched: result.totalFetched };\n }\n\n /** Triggers an online sync of every account that has an active session. */\n async syncAll(): Promise<SyncAllResult> {\n const wires = await this.getAccountWires();\n const decrypted = await Promise.all(\n wires.map(async (a) => ({ accountId: a.id, uid: await this.decryptUid(a) })),\n );\n const items = decrypted\n .filter((x): x is { accountId: string; uid: string } => x.uid != null)\n .map((x) => ({ accountId: x.accountId, uid: x.uid }));\n\n const result = await this.postJson<SyncAllResultWire>(\"/api/sync\", { items });\n return { accounts: result.accounts, newTransactions: result.newTransactions };\n }\n\n // ---- internals ---------------------------------------------------------------------------------\n\n private getAccountWires(): Promise<AccountWire[]> {\n return this.getJson<AccountWire[]>(\"/api/accounts\");\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>(path: string, body: unknown): Promise<T> {\n const res = await this.fetchImpl(this.baseUrl + path, {\n method: \"POST\",\n headers: {\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 throw new Error(`POST ${path} failed: ${res.status} ${res.statusText}`);\n }\n return (await res.json()) as T;\n }\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 { 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;;;ACEA,yBAAyD;;;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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178,15 @@ interface ConnectRelay {
178
178
  publicKey: string;
179
179
  }
180
180
  type RelayErrorCode = "access_denied" | "oauth_error" | "state_mismatch" | "issuer_mismatch" | "missing_code" | "missing_private_key";
181
+ /** The `error_description` the server relays when the partner has not installed its decryption key. */
182
+ declare const PARTNER_KEY_MISSING_DESCRIPTION = "this partner has not installed its decryption key; no authorizations can be started until it does";
183
+ /** The `error_description` the server relays while the partner is suspended. */
184
+ declare const PARTNER_SUSPENDED_DESCRIPTION = "this partner is suspended; no authorizations can be started";
185
+ /**
186
+ * Why a `temporarily_unavailable` was relayed, when the server said so in the pinned words. Both
187
+ * are on your side, not the bank's: install the key on your partner page, or write to us.
188
+ */
189
+ type RelayRefusalReason = "partner_key_missing" | "partner_suspended";
181
190
  /**
182
191
  * Thrown by {@link parseRelay}. `code` says why: `access_denied` is the user pressing "Back to the
183
192
  * partner" or declining (a normal outcome), `oauth_error` any other error the server relayed (the
@@ -187,6 +196,8 @@ declare class RelayError extends Error {
187
196
  readonly code: RelayErrorCode;
188
197
  readonly error?: string;
189
198
  readonly errorDescription?: string;
199
+ /** Set on an `oauth_error` whose description names a partner-side refusal. */
200
+ readonly reason?: RelayRefusalReason;
190
201
  constructor(code: RelayErrorCode, message: string, oauth?: {
191
202
  error: string;
192
203
  errorDescription?: string;
@@ -199,6 +210,12 @@ interface ParseRelayOptions {
199
210
  issuer?: string;
200
211
  /** Require `iss` to be present even when `issuer` is not checked. Default: only when `issuer` is set. */
201
212
  requireIss?: boolean;
213
+ /**
214
+ * Whether the relay must carry the user's private key. A partner that installed its own
215
+ * decryption key receives `privateKey=""` for every user who connected under it and decrypts
216
+ * with that key instead — pass `"optional"`. Default `"required"`, the 1.1.0 behaviour.
217
+ */
218
+ expectPrivateKey?: "required" | "optional";
202
219
  }
203
220
  /** A form body, `URLSearchParams`, parsed body object, or JSON string. */
204
221
  type RelayInput = string | URLSearchParams | FormData | Record<string, unknown>;
@@ -293,6 +310,10 @@ interface ServerMetadata {
293
310
  response_mode: string;
294
311
  fields: string[];
295
312
  };
313
+ /** The server accepts a partner-held decryption key (always true on current servers). */
314
+ recipient_key_supported?: boolean;
315
+ /** Every partner must hold one before it can register a client or start an authorization. */
316
+ recipient_key_required?: boolean;
296
317
  documentation: string;
297
318
  };
298
319
  }
@@ -364,4 +385,30 @@ declare function decryptTo<T>(privateKey: CryptoKey, envelopeBase64: string | nu
364
385
  /** Imports a base64 PKCS#8 P-256 ECDH private key for use with {@link decryptEnvelope}. */
365
386
  declare function importPrivateKey(pkcs8Base64: string): Promise<CryptoKey>;
366
387
 
367
- export { type Account, type AuthorizeUrlOptions, type Balance, CONNECT_RELAY_FIELDS, type ConnectRelay, type Connection, type CredentialsBundle, type EncryptionKey, type ExchangeCodeOptions, type HttpOptions, OAuthError, OpenBankingClient, type OpenBankingClientOptions, type ParseRelayOptions, type Pkce, RelayError, type RelayErrorCode, type RelayInput, type RevokeTokenOptions, type ServerMetadata, type SyncAllResult, type SyncResult, type TokenResponse, type Transaction, type TransactionPage, type TransactionQuery, type Userinfo, type UserinfoOptions, buildAuthorizeUrl, bundleFromToken, createPkce, createState, decryptEnvelope, decryptTo, discover, exchangeCode, importPrivateKey, parseRelay, pkceChallenge, revokeToken, userinfo };
388
+ /** A partner's recipient (decryption) key pair. The private half is a credential: never log it. */
389
+ interface RecipientKeyPair {
390
+ /** Base64 PKCS#8 — what your deployment loads. */
391
+ privateKeyPkcs8Base64: string;
392
+ /** Base64 raw 65-byte uncompressed P-256 point — what you install on your partner page. */
393
+ publicKeyRawBase64: string;
394
+ }
395
+ /**
396
+ * Generates the P-256 pair a partner installs on open-banking.io. The public half goes into
397
+ * `PUT /api/partner/recipient-key` (or the partner page's paste box); keep the private half
398
+ * where your deployment can read it — the service never sees it and cannot recover it.
399
+ */
400
+ declare function generateRecipientKeyPair(): Promise<RecipientKeyPair>;
401
+ /**
402
+ * The fingerprint the partner page and the admin show for a key: SHA-256 of the raw 65-byte
403
+ * point, lowercase hex, first 16 characters. Print it at boot and compare after every deploy.
404
+ */
405
+ declare function recipientKeyFingerprint(publicKeyRawBase64: string): string;
406
+ /** The raw public point of a PKCS#8 private key — to fingerprint or re-install the key you hold. */
407
+ declare function recipientPublicKey(privateKeyPkcs8Base64: string): Promise<string>;
408
+ /**
409
+ * Answers the possession challenge from `POST /api/partner/recipient-key/challenge`: opens
410
+ * the envelope with the private half and returns the nonce — the `challengeAnswer` for the install.
411
+ */
412
+ declare function answerRecipientKeyChallenge(privateKeyPkcs8Base64: string, envelopeBase64: string): Promise<string>;
413
+
414
+ export { type Account, type AuthorizeUrlOptions, type Balance, CONNECT_RELAY_FIELDS, type ConnectRelay, type Connection, type CredentialsBundle, type EncryptionKey, type ExchangeCodeOptions, type HttpOptions, OAuthError, OpenBankingClient, type OpenBankingClientOptions, PARTNER_KEY_MISSING_DESCRIPTION, PARTNER_SUSPENDED_DESCRIPTION, type ParseRelayOptions, type Pkce, type RecipientKeyPair, RelayError, type RelayErrorCode, type RelayInput, type RelayRefusalReason, type RevokeTokenOptions, type ServerMetadata, type SyncAllResult, type SyncResult, type TokenResponse, type Transaction, type TransactionPage, type TransactionQuery, type Userinfo, type UserinfoOptions, answerRecipientKeyChallenge, buildAuthorizeUrl, bundleFromToken, createPkce, createState, decryptEnvelope, decryptTo, discover, exchangeCode, generateRecipientKeyPair, importPrivateKey, parseRelay, pkceChallenge, recipientKeyFingerprint, recipientPublicKey, revokeToken, userinfo };
package/dist/index.d.ts CHANGED
@@ -178,6 +178,15 @@ interface ConnectRelay {
178
178
  publicKey: string;
179
179
  }
180
180
  type RelayErrorCode = "access_denied" | "oauth_error" | "state_mismatch" | "issuer_mismatch" | "missing_code" | "missing_private_key";
181
+ /** The `error_description` the server relays when the partner has not installed its decryption key. */
182
+ declare const PARTNER_KEY_MISSING_DESCRIPTION = "this partner has not installed its decryption key; no authorizations can be started until it does";
183
+ /** The `error_description` the server relays while the partner is suspended. */
184
+ declare const PARTNER_SUSPENDED_DESCRIPTION = "this partner is suspended; no authorizations can be started";
185
+ /**
186
+ * Why a `temporarily_unavailable` was relayed, when the server said so in the pinned words. Both
187
+ * are on your side, not the bank's: install the key on your partner page, or write to us.
188
+ */
189
+ type RelayRefusalReason = "partner_key_missing" | "partner_suspended";
181
190
  /**
182
191
  * Thrown by {@link parseRelay}. `code` says why: `access_denied` is the user pressing "Back to the
183
192
  * partner" or declining (a normal outcome), `oauth_error` any other error the server relayed (the
@@ -187,6 +196,8 @@ declare class RelayError extends Error {
187
196
  readonly code: RelayErrorCode;
188
197
  readonly error?: string;
189
198
  readonly errorDescription?: string;
199
+ /** Set on an `oauth_error` whose description names a partner-side refusal. */
200
+ readonly reason?: RelayRefusalReason;
190
201
  constructor(code: RelayErrorCode, message: string, oauth?: {
191
202
  error: string;
192
203
  errorDescription?: string;
@@ -199,6 +210,12 @@ interface ParseRelayOptions {
199
210
  issuer?: string;
200
211
  /** Require `iss` to be present even when `issuer` is not checked. Default: only when `issuer` is set. */
201
212
  requireIss?: boolean;
213
+ /**
214
+ * Whether the relay must carry the user's private key. A partner that installed its own
215
+ * decryption key receives `privateKey=""` for every user who connected under it and decrypts
216
+ * with that key instead — pass `"optional"`. Default `"required"`, the 1.1.0 behaviour.
217
+ */
218
+ expectPrivateKey?: "required" | "optional";
202
219
  }
203
220
  /** A form body, `URLSearchParams`, parsed body object, or JSON string. */
204
221
  type RelayInput = string | URLSearchParams | FormData | Record<string, unknown>;
@@ -293,6 +310,10 @@ interface ServerMetadata {
293
310
  response_mode: string;
294
311
  fields: string[];
295
312
  };
313
+ /** The server accepts a partner-held decryption key (always true on current servers). */
314
+ recipient_key_supported?: boolean;
315
+ /** Every partner must hold one before it can register a client or start an authorization. */
316
+ recipient_key_required?: boolean;
296
317
  documentation: string;
297
318
  };
298
319
  }
@@ -364,4 +385,30 @@ declare function decryptTo<T>(privateKey: CryptoKey, envelopeBase64: string | nu
364
385
  /** Imports a base64 PKCS#8 P-256 ECDH private key for use with {@link decryptEnvelope}. */
365
386
  declare function importPrivateKey(pkcs8Base64: string): Promise<CryptoKey>;
366
387
 
367
- export { type Account, type AuthorizeUrlOptions, type Balance, CONNECT_RELAY_FIELDS, type ConnectRelay, type Connection, type CredentialsBundle, type EncryptionKey, type ExchangeCodeOptions, type HttpOptions, OAuthError, OpenBankingClient, type OpenBankingClientOptions, type ParseRelayOptions, type Pkce, RelayError, type RelayErrorCode, type RelayInput, type RevokeTokenOptions, type ServerMetadata, type SyncAllResult, type SyncResult, type TokenResponse, type Transaction, type TransactionPage, type TransactionQuery, type Userinfo, type UserinfoOptions, buildAuthorizeUrl, bundleFromToken, createPkce, createState, decryptEnvelope, decryptTo, discover, exchangeCode, importPrivateKey, parseRelay, pkceChallenge, revokeToken, userinfo };
388
+ /** A partner's recipient (decryption) key pair. The private half is a credential: never log it. */
389
+ interface RecipientKeyPair {
390
+ /** Base64 PKCS#8 — what your deployment loads. */
391
+ privateKeyPkcs8Base64: string;
392
+ /** Base64 raw 65-byte uncompressed P-256 point — what you install on your partner page. */
393
+ publicKeyRawBase64: string;
394
+ }
395
+ /**
396
+ * Generates the P-256 pair a partner installs on open-banking.io. The public half goes into
397
+ * `PUT /api/partner/recipient-key` (or the partner page's paste box); keep the private half
398
+ * where your deployment can read it — the service never sees it and cannot recover it.
399
+ */
400
+ declare function generateRecipientKeyPair(): Promise<RecipientKeyPair>;
401
+ /**
402
+ * The fingerprint the partner page and the admin show for a key: SHA-256 of the raw 65-byte
403
+ * point, lowercase hex, first 16 characters. Print it at boot and compare after every deploy.
404
+ */
405
+ declare function recipientKeyFingerprint(publicKeyRawBase64: string): string;
406
+ /** The raw public point of a PKCS#8 private key — to fingerprint or re-install the key you hold. */
407
+ declare function recipientPublicKey(privateKeyPkcs8Base64: string): Promise<string>;
408
+ /**
409
+ * Answers the possession challenge from `POST /api/partner/recipient-key/challenge`: opens
410
+ * the envelope with the private half and returns the nonce — the `challengeAnswer` for the install.
411
+ */
412
+ declare function answerRecipientKeyChallenge(privateKeyPkcs8Base64: string, envelopeBase64: string): Promise<string>;
413
+
414
+ export { type Account, type AuthorizeUrlOptions, type Balance, CONNECT_RELAY_FIELDS, type ConnectRelay, type Connection, type CredentialsBundle, type EncryptionKey, type ExchangeCodeOptions, type HttpOptions, OAuthError, OpenBankingClient, type OpenBankingClientOptions, PARTNER_KEY_MISSING_DESCRIPTION, PARTNER_SUSPENDED_DESCRIPTION, type ParseRelayOptions, type Pkce, type RecipientKeyPair, RelayError, type RelayErrorCode, type RelayInput, type RelayRefusalReason, type RevokeTokenOptions, type ServerMetadata, type SyncAllResult, type SyncResult, type TokenResponse, type Transaction, type TransactionPage, type TransactionQuery, type Userinfo, type UserinfoOptions, answerRecipientKeyChallenge, buildAuthorizeUrl, bundleFromToken, createPkce, createState, decryptEnvelope, decryptTo, discover, exchangeCode, generateRecipientKeyPair, importPrivateKey, parseRelay, pkceChallenge, recipientKeyFingerprint, recipientPublicKey, revokeToken, userinfo };
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: "1.1.0",
7
+ version: "1.2.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",
@@ -95,16 +95,27 @@ function buildAuthorizeUrl(options) {
95
95
  if (options.uiLocales) params.set("ui_locales", options.uiLocales);
96
96
  return `${endpoint(options.issuer, "/oauth/authorize")}?${params.toString()}`;
97
97
  }
98
+ var PARTNER_KEY_MISSING_DESCRIPTION = "this partner has not installed its decryption key; no authorizations can be started until it does";
99
+ var PARTNER_SUSPENDED_DESCRIPTION = "this partner is suspended; no authorizations can be started";
100
+ function refusalReason(error, description) {
101
+ if (error !== "temporarily_unavailable") return void 0;
102
+ if (description === PARTNER_KEY_MISSING_DESCRIPTION) return "partner_key_missing";
103
+ if (description === PARTNER_SUSPENDED_DESCRIPTION) return "partner_suspended";
104
+ return void 0;
105
+ }
98
106
  var RelayError = class extends Error {
99
107
  code;
100
108
  error;
101
109
  errorDescription;
110
+ /** Set on an `oauth_error` whose description names a partner-side refusal. */
111
+ reason;
102
112
  constructor(code, message, oauth) {
103
113
  super(message);
104
114
  this.name = "RelayError";
105
115
  this.code = code;
106
116
  this.error = oauth?.error;
107
117
  this.errorDescription = oauth?.errorDescription;
118
+ this.reason = oauth ? refusalReason(oauth.error, oauth.errorDescription ?? "") : void 0;
108
119
  }
109
120
  };
110
121
  function parseRelay(input, options) {
@@ -137,7 +148,9 @@ function parseRelay(input, options) {
137
148
  const code = read("code");
138
149
  if (!code) throw new RelayError("missing_code", "The relay carries no authorization code");
139
150
  const privateKey = read("privateKey");
140
- if (!privateKey) throw new RelayError("missing_private_key", "The relay carries no private key");
151
+ if (!privateKey && (options.expectPrivateKey ?? "required") === "required") {
152
+ throw new RelayError("missing_private_key", "The relay carries no private key");
153
+ }
141
154
  return { code, state: read("state"), iss, privateKey, publicKey: read("publicKey") };
142
155
  }
143
156
  var OAuthError = class extends Error {
@@ -608,11 +621,60 @@ var OpenBankingClient = class _OpenBankingClient {
608
621
  return await res.json();
609
622
  }
610
623
  };
624
+
625
+ // src/recipientKey.ts
626
+ import { createHash as createHash2, webcrypto as webcrypto2 } from "crypto";
627
+ var subtle2 = webcrypto2.subtle;
628
+ async function generateRecipientKeyPair() {
629
+ const pair = await subtle2.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, [
630
+ "deriveBits"
631
+ ]);
632
+ return {
633
+ privateKeyPkcs8Base64: Buffer.from(await subtle2.exportKey("pkcs8", pair.privateKey)).toString(
634
+ "base64"
635
+ ),
636
+ publicKeyRawBase64: Buffer.from(await subtle2.exportKey("raw", pair.publicKey)).toString(
637
+ "base64"
638
+ )
639
+ };
640
+ }
641
+ function recipientKeyFingerprint(publicKeyRawBase64) {
642
+ return createHash2("sha256").update(Buffer.from(publicKeyRawBase64, "base64")).digest("hex").slice(0, 16);
643
+ }
644
+ async function recipientPublicKey(privateKeyPkcs8Base64) {
645
+ const key = await subtle2.importKey(
646
+ "pkcs8",
647
+ Buffer.from(privateKeyPkcs8Base64, "base64"),
648
+ { name: "ECDH", namedCurve: "P-256" },
649
+ true,
650
+ ["deriveBits"]
651
+ );
652
+ const jwk = await subtle2.exportKey("jwk", key);
653
+ if (!jwk.x || !jwk.y) throw new Error("The private key carries no public point");
654
+ return Buffer.concat([
655
+ Buffer.from([4]),
656
+ Buffer.from(jwk.x, "base64url"),
657
+ Buffer.from(jwk.y, "base64url")
658
+ ]).toString("base64");
659
+ }
660
+ async function answerRecipientKeyChallenge(privateKeyPkcs8Base64, envelopeBase64) {
661
+ const payload = await decryptTo(
662
+ await importPrivateKey(privateKeyPkcs8Base64),
663
+ envelopeBase64
664
+ );
665
+ const nonce = payload?.nonce;
666
+ if (typeof nonce !== "string" || nonce.length === 0)
667
+ throw new Error("The challenge envelope carries no nonce");
668
+ return nonce;
669
+ }
611
670
  export {
612
671
  CONNECT_RELAY_FIELDS,
613
672
  OAuthError,
614
673
  OpenBankingClient,
674
+ PARTNER_KEY_MISSING_DESCRIPTION,
675
+ PARTNER_SUSPENDED_DESCRIPTION,
615
676
  RelayError,
677
+ answerRecipientKeyChallenge,
616
678
  buildAuthorizeUrl,
617
679
  bundleFromToken,
618
680
  createPkce,
@@ -621,9 +683,12 @@ export {
621
683
  decryptTo,
622
684
  discover,
623
685
  exchangeCode,
686
+ generateRecipientKeyPair,
624
687
  importPrivateKey,
625
688
  parseRelay,
626
689
  pkceChallenge,
690
+ recipientKeyFingerprint,
691
+ recipientPublicKey,
627
692
  revokeToken,
628
693
  userinfo
629
694
  };
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"],"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\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 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/**\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\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 }\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\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) throw new RelayError(\"missing_private_key\", \"The relay carries no private key\");\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\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 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 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.1.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 { 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 SyncAllResult,\n SyncAllResultWire,\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 }));\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 async sync(accountId: string): Promise<SyncResult> {\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 = await this.decryptUid(account);\n if (uid == null) {\n throw new Error(\"Account has no active session (reconnect required) — cannot sync\");\n }\n\n const result = await this.postJson<SyncResultWire>(\n `/api/accounts/${encodeURIComponent(accountId)}/sync`,\n { uid },\n );\n return { newTransactions: result.newTransactions, totalFetched: result.totalFetched };\n }\n\n /** Triggers an online sync of every account that has an active session. */\n async syncAll(): Promise<SyncAllResult> {\n const wires = await this.getAccountWires();\n const decrypted = await Promise.all(\n wires.map(async (a) => ({ accountId: a.id, uid: await this.decryptUid(a) })),\n );\n const items = decrypted\n .filter((x): x is { accountId: string; uid: string } => x.uid != null)\n .map((x) => ({ accountId: x.accountId, uid: x.uid }));\n\n const result = await this.postJson<SyncAllResultWire>(\"/api/sync\", { items });\n return { accounts: result.accounts, newTransactions: result.newTransactions };\n }\n\n // ---- internals ---------------------------------------------------------------------------------\n\n private getAccountWires(): Promise<AccountWire[]> {\n return this.getJson<AccountWire[]>(\"/api/accounts\");\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>(path: string, body: unknown): Promise<T> {\n const res = await this.fetchImpl(this.baseUrl + path, {\n method: \"POST\",\n headers: {\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 throw new Error(`POST ${path} failed: ${res.status} ${res.statusText}`);\n }\n return (await res.json()) as T;\n }\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"],"mappings":";AAEA,SAAS,YAAY,aAAa,uBAAuB;;;ACFzD;AAAA,EACE,MAAQ;AAAA,EACR,S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Ac;AAAA,MAChB;AAAA,MACA,MAAM,KAAK,UAAU,IAAI;AAAA,MACzB,QAAQ,YAAY,QAAQ,KAAK,SAAS;AAAA,IAC5C,CAAC;AACD,QAAI,CAAC,IAAI,IAAI;AACX,YAAM,IAAI,MAAM,QAAQ,IAAI,YAAY,IAAI,MAAM,IAAI,IAAI,UAAU,EAAE;AAAA,IACxE;AACA,WAAQ,MAAM,IAAI,KAAK;AAAA,EACzB;AACF;","names":["VERSION"]}
1
+ {"version":3,"sources":["../src/connect.ts","../package.json","../src/version.ts","../src/client.ts","../src/envelope.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\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 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\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 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.2.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 { 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 SyncAllResult,\n SyncAllResultWire,\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 }));\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 async sync(accountId: string): Promise<SyncResult> {\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 = await this.decryptUid(account);\n if (uid == null) {\n throw new Error(\"Account has no active session (reconnect required) — cannot sync\");\n }\n\n const result = await this.postJson<SyncResultWire>(\n `/api/accounts/${encodeURIComponent(accountId)}/sync`,\n { uid },\n );\n return { newTransactions: result.newTransactions, totalFetched: result.totalFetched };\n }\n\n /** Triggers an online sync of every account that has an active session. */\n async syncAll(): Promise<SyncAllResult> {\n const wires = await this.getAccountWires();\n const decrypted = await Promise.all(\n wires.map(async (a) => ({ accountId: a.id, uid: await this.decryptUid(a) })),\n );\n const items = decrypted\n .filter((x): x is { accountId: string; uid: string } => x.uid != null)\n .map((x) => ({ accountId: x.accountId, uid: x.uid }));\n\n const result = await this.postJson<SyncAllResultWire>(\"/api/sync\", { items });\n return { accounts: result.accounts, newTransactions: result.newTransactions };\n }\n\n // ---- internals ---------------------------------------------------------------------------------\n\n private getAccountWires(): Promise<AccountWire[]> {\n return this.getJson<AccountWire[]>(\"/api/accounts\");\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>(path: string, body: unknown): Promise<T> {\n const res = await this.fetchImpl(this.baseUrl + path, {\n method: \"POST\",\n headers: {\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 throw new Error(`POST ${path} failed: ${res.status} ${res.statusText}`);\n }\n return (await res.json()) as T;\n }\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 { 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,EAC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MAAM,WAAW;AAChD,UAAM,IAAI,MAAM,yCAAyC;AAC3D,SAAO;AACT;","names":["VERSION","createHash","webcrypto","subtle","webcrypto","createHash"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-banking-io/client",
3
- "version": "1.1.0",
3
+ "version": "1.2.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",