@open-banking-io/client 1.0.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/dist/index.js CHANGED
@@ -1,10 +1,354 @@
1
+ // src/connect.ts
2
+ import { createHash, randomBytes, timingSafeEqual } from "crypto";
3
+
4
+ // package.json
5
+ var package_default = {
6
+ name: "@open-banking-io/client",
7
+ version: "1.2.0",
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
+ type: "module",
10
+ license: "MIT",
11
+ author: "open-banking.io",
12
+ keywords: [
13
+ "open-banking",
14
+ "psd2",
15
+ "zero-knowledge",
16
+ "encryption",
17
+ "fintech"
18
+ ],
19
+ repository: {
20
+ type: "git",
21
+ url: "https://github.com/open-banking-io/clients"
22
+ },
23
+ engines: {
24
+ node: ">=20"
25
+ },
26
+ files: [
27
+ "dist",
28
+ "README.md"
29
+ ],
30
+ main: "./dist/index.cjs",
31
+ module: "./dist/index.js",
32
+ types: "./dist/index.d.ts",
33
+ exports: {
34
+ ".": {
35
+ types: "./dist/index.d.ts",
36
+ import: "./dist/index.js",
37
+ require: "./dist/index.cjs"
38
+ }
39
+ },
40
+ scripts: {
41
+ build: "tsup",
42
+ test: "vitest run",
43
+ coverage: "vitest run --coverage",
44
+ typecheck: "tsc --noEmit",
45
+ lint: "eslint .",
46
+ "format:check": "prettier --check ."
47
+ },
48
+ overrides: {
49
+ esbuild: "^0.28.1"
50
+ },
51
+ devDependencies: {
52
+ "@eslint/js": "^10.0.1",
53
+ "@types/node": "^25.9.3",
54
+ "@vitest/coverage-v8": "^4.1.9",
55
+ eslint: "^10.5.0",
56
+ prettier: "^3.8.4",
57
+ tsup: "^8.5.1",
58
+ typescript: "^6.0.3",
59
+ "typescript-eslint": "^8.61.1",
60
+ vitest: "^4.1.9"
61
+ },
62
+ homepage: "https://open-banking.io"
63
+ };
64
+
65
+ // src/version.ts
66
+ var VERSION = package_default.version;
67
+ var USER_AGENT = `open-banking-io/node/${VERSION}`;
68
+
69
+ // src/connect.ts
70
+ var DEFAULT_TIMEOUT_MS = 3e4;
71
+ var CONNECT_RELAY_FIELDS = ["code", "state", "iss", "privateKey", "publicKey"];
72
+ function createPkce() {
73
+ const verifier = randomBytes(32).toString("base64url");
74
+ return { verifier, challenge: pkceChallenge(verifier), method: "S256" };
75
+ }
76
+ function pkceChallenge(verifier) {
77
+ return createHash("sha256").update(verifier).digest("base64url");
78
+ }
79
+ function createState() {
80
+ return randomBytes(16).toString("base64url");
81
+ }
82
+ function buildAuthorizeUrl(options) {
83
+ const params = new URLSearchParams({
84
+ response_type: "code",
85
+ client_id: options.clientId,
86
+ redirect_uri: options.redirectUri,
87
+ scope: options.scope ?? "accounts.read",
88
+ state: options.state,
89
+ code_challenge: options.codeChallenge,
90
+ code_challenge_method: "S256",
91
+ response_mode: "form_post"
92
+ });
93
+ if (options.loginHint) params.set("login_hint", options.loginHint);
94
+ if (options.challenge) params.set("challenge", options.challenge);
95
+ if (options.uiLocales) params.set("ui_locales", options.uiLocales);
96
+ return `${endpoint(options.issuer, "/oauth/authorize")}?${params.toString()}`;
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
+ }
106
+ var RelayError = class extends Error {
107
+ code;
108
+ error;
109
+ errorDescription;
110
+ /** Set on an `oauth_error` whose description names a partner-side refusal. */
111
+ reason;
112
+ constructor(code, message, oauth) {
113
+ super(message);
114
+ this.name = "RelayError";
115
+ this.code = code;
116
+ this.error = oauth?.error;
117
+ this.errorDescription = oauth?.errorDescription;
118
+ this.reason = oauth ? refusalReason(oauth.error, oauth.errorDescription ?? "") : void 0;
119
+ }
120
+ };
121
+ function parseRelay(input, options) {
122
+ const fields = toRecord(input);
123
+ const read = (name) => {
124
+ const value = fields[name];
125
+ return typeof value === "string" ? value : "";
126
+ };
127
+ if (!options.expectedState || !constantTimeEqual(read("state"), options.expectedState)) {
128
+ throw new RelayError("state_mismatch", "The relayed state does not match this flow");
129
+ }
130
+ const iss = read("iss");
131
+ const wantIss = options.issuer !== void 0 || options.requireIss === true;
132
+ if (wantIss && !iss) throw new RelayError("issuer_mismatch", "The relay carries no iss");
133
+ if (options.issuer !== void 0 && !constantTimeEqual(trimSlash(iss), trimSlash(options.issuer))) {
134
+ throw new RelayError("issuer_mismatch", "The relayed iss is not the expected issuer");
135
+ }
136
+ const error = read("error");
137
+ if (error) {
138
+ const description = read("error_description");
139
+ throw new RelayError(
140
+ error === "access_denied" ? "access_denied" : "oauth_error",
141
+ description ? `${error}: ${description}` : error,
142
+ {
143
+ error,
144
+ errorDescription: description || void 0
145
+ }
146
+ );
147
+ }
148
+ const code = read("code");
149
+ if (!code) throw new RelayError("missing_code", "The relay carries no authorization code");
150
+ const privateKey = read("privateKey");
151
+ if (!privateKey && (options.expectPrivateKey ?? "required") === "required") {
152
+ throw new RelayError("missing_private_key", "The relay carries no private key");
153
+ }
154
+ return { code, state: read("state"), iss, privateKey, publicKey: read("publicKey") };
155
+ }
156
+ var OAuthError = class extends Error {
157
+ status;
158
+ error;
159
+ errorDescription;
160
+ constructor(status, error, errorDescription) {
161
+ super(errorDescription ? `${error}: ${errorDescription}` : error);
162
+ this.name = "OAuthError";
163
+ this.status = status;
164
+ this.error = error;
165
+ this.errorDescription = errorDescription;
166
+ }
167
+ };
168
+ async function exchangeCode(options) {
169
+ const body = new URLSearchParams({
170
+ grant_type: "authorization_code",
171
+ code: options.code,
172
+ code_verifier: options.codeVerifier
173
+ });
174
+ if (options.redirectUri) body.set("redirect_uri", options.redirectUri);
175
+ const response = await post(
176
+ endpoint(options.issuer, "/oauth/token"),
177
+ body,
178
+ {
179
+ Authorization: basicAuth(options.clientId, options.clientSecret),
180
+ Accept: "application/json"
181
+ },
182
+ options
183
+ );
184
+ await throwIfOAuthError(response);
185
+ const wire = await response.json();
186
+ const accessToken = wire.access_token ?? wire.apiKey;
187
+ if (!accessToken)
188
+ throw new OAuthError(
189
+ response.status,
190
+ "invalid_response",
191
+ "The token response carries no access token"
192
+ );
193
+ return {
194
+ accessToken,
195
+ tokenType: wire.token_type ?? "Bearer",
196
+ expiresIn: wire.expires_in ?? 0,
197
+ scope: wire.scope ?? "",
198
+ apiKey: wire.apiKey ?? accessToken,
199
+ apiBaseUrl: wire.apiBaseUrl ?? trimSlash(options.issuer),
200
+ user: wire.user ?? ""
201
+ };
202
+ }
203
+ async function revokeToken(options) {
204
+ const body = new URLSearchParams({ token: options.token, token_type_hint: "access_token" });
205
+ const response = await post(
206
+ endpoint(options.issuer, "/oauth/revoke"),
207
+ body,
208
+ {
209
+ Authorization: basicAuth(options.clientId, options.clientSecret)
210
+ },
211
+ options
212
+ );
213
+ await throwIfOAuthError(response);
214
+ }
215
+ async function userinfo(options) {
216
+ const response = await request(
217
+ endpoint(options.issuer, "/oauth/userinfo"),
218
+ {
219
+ method: "GET",
220
+ headers: {
221
+ Authorization: `Bearer ${options.accessToken}`,
222
+ Accept: "application/json",
223
+ "User-Agent": USER_AGENT
224
+ }
225
+ },
226
+ options
227
+ );
228
+ await throwIfOAuthError(response);
229
+ const wire = await response.json();
230
+ return {
231
+ sub: wire.sub,
232
+ email: wire.email,
233
+ partnerId: wire.partner_id ?? null,
234
+ clientId: wire.client_id ?? null,
235
+ scope: wire.scope,
236
+ expiresAt: wire.expires_at ?? null
237
+ };
238
+ }
239
+ var discoveryCache = /* @__PURE__ */ new Map();
240
+ var DISCOVERY_TTL_MS = 60 * 60 * 1e3;
241
+ async function discover(issuer, options = {}) {
242
+ const key = trimSlash(issuer);
243
+ const cached = discoveryCache.get(key);
244
+ if (cached && cached.expiresAt > Date.now()) return cached.metadata;
245
+ const response = await request(
246
+ `${key}/.well-known/oauth-authorization-server`,
247
+ {
248
+ method: "GET",
249
+ headers: { Accept: "application/json", "User-Agent": USER_AGENT }
250
+ },
251
+ options
252
+ );
253
+ if (!response.ok)
254
+ throw new OAuthError(response.status, "discovery_failed", `HTTP ${response.status}`);
255
+ const metadata = await response.json();
256
+ if (typeof metadata.issuer !== "string" || trimSlash(metadata.issuer) !== key) {
257
+ throw new OAuthError(
258
+ response.status,
259
+ "discovery_failed",
260
+ `Issuer mismatch: ${String(metadata.issuer)}`
261
+ );
262
+ }
263
+ discoveryCache.set(key, { metadata, expiresAt: Date.now() + DISCOVERY_TTL_MS });
264
+ return metadata;
265
+ }
266
+ function bundleFromToken(token, privateKey) {
267
+ return {
268
+ service: "open-banking.io",
269
+ apiBaseUrl: token.apiBaseUrl,
270
+ user: token.user,
271
+ apiKey: token.accessToken,
272
+ encryptionKey: { scheme: "ecdh-p256-hkdf-aes-256-gcm", curve: "P-256", privateKey }
273
+ };
274
+ }
275
+ function endpoint(issuer, path) {
276
+ return trimSlash(issuer) + path;
277
+ }
278
+ function trimSlash(value) {
279
+ let end = value.length;
280
+ while (end > 0 && value[end - 1] === "/") end--;
281
+ return value.slice(0, end);
282
+ }
283
+ function basicAuth(clientId, clientSecret) {
284
+ const pair = `${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`;
285
+ return `Basic ${Buffer.from(pair, "utf8").toString("base64")}`;
286
+ }
287
+ function constantTimeEqual(a, b) {
288
+ const x = createHash("sha256").update(a, "utf8").digest();
289
+ const y = createHash("sha256").update(b, "utf8").digest();
290
+ return timingSafeEqual(x, y) && a.length === b.length;
291
+ }
292
+ function toRecord(input) {
293
+ if (typeof input === "string") {
294
+ const trimmed = input.trim();
295
+ if (trimmed.startsWith("{")) return JSON.parse(trimmed);
296
+ return Object.fromEntries(new URLSearchParams(trimmed));
297
+ }
298
+ if (input instanceof URLSearchParams) return Object.fromEntries(input);
299
+ if (input instanceof FormData) {
300
+ const record = {};
301
+ input.forEach((value, name) => {
302
+ if (typeof value === "string") record[name] = value;
303
+ });
304
+ return record;
305
+ }
306
+ return input;
307
+ }
308
+ async function post(url, body, headers, options) {
309
+ return request(
310
+ url,
311
+ {
312
+ method: "POST",
313
+ headers: {
314
+ ...headers,
315
+ "Content-Type": "application/x-www-form-urlencoded",
316
+ "User-Agent": USER_AGENT
317
+ },
318
+ body: body.toString()
319
+ },
320
+ options
321
+ );
322
+ }
323
+ async function request(url, init, options) {
324
+ const fetchImpl = options.fetch ?? fetch;
325
+ return fetchImpl(url, {
326
+ ...init,
327
+ signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
328
+ });
329
+ }
330
+ async function throwIfOAuthError(response) {
331
+ if (response.ok) return;
332
+ let error = "http_error";
333
+ let description = `HTTP ${response.status}`;
334
+ try {
335
+ const body = await response.json();
336
+ if (body.error) {
337
+ error = body.error;
338
+ description = body.error_description;
339
+ }
340
+ } catch {
341
+ }
342
+ throw new OAuthError(response.status, error, description);
343
+ }
344
+
1
345
  // src/client.ts
2
346
  import { readFileSync } from "fs";
3
347
 
4
348
  // src/envelope.ts
5
349
  import { webcrypto } from "crypto";
6
350
  var { subtle } = webcrypto;
7
- var VERSION = 1;
351
+ var VERSION2 = 1;
8
352
  var POINT_LEN = 65;
9
353
  var NONCE_LEN = 12;
10
354
  var TAG_LEN = 16;
@@ -12,7 +356,7 @@ var HKDF_INFO = new TextEncoder().encode("bank.core.ci/zk/v1");
12
356
  var HKDF_SALT = new Uint8Array(32);
13
357
  async function decryptEnvelope(privateKey, envelopeBase64) {
14
358
  const bytes = base64ToBytes(envelopeBase64);
15
- if (bytes.length < 1 + POINT_LEN + NONCE_LEN + TAG_LEN || bytes[0] !== VERSION) {
359
+ if (bytes.length < 1 + POINT_LEN + NONCE_LEN + TAG_LEN || bytes[0] !== VERSION2) {
16
360
  throw new Error("Invalid or unsupported envelope");
17
361
  }
18
362
  const ephPub = bytes.subarray(1, 1 + POINT_LEN);
@@ -65,71 +409,6 @@ function base64ToBytes(b64) {
65
409
  return new Uint8Array(Buffer.from(b64, "base64"));
66
410
  }
67
411
 
68
- // package.json
69
- var package_default = {
70
- name: "@open-banking-io/client",
71
- version: "1.0.0",
72
- 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.",
73
- type: "module",
74
- license: "MIT",
75
- author: "open-banking.io",
76
- keywords: [
77
- "open-banking",
78
- "psd2",
79
- "zero-knowledge",
80
- "encryption",
81
- "fintech"
82
- ],
83
- repository: {
84
- type: "git",
85
- url: "https://github.com/open-banking-io/clients"
86
- },
87
- engines: {
88
- node: ">=20"
89
- },
90
- files: [
91
- "dist",
92
- "README.md"
93
- ],
94
- main: "./dist/index.cjs",
95
- module: "./dist/index.js",
96
- types: "./dist/index.d.ts",
97
- exports: {
98
- ".": {
99
- types: "./dist/index.d.ts",
100
- import: "./dist/index.js",
101
- require: "./dist/index.cjs"
102
- }
103
- },
104
- scripts: {
105
- build: "tsup",
106
- test: "vitest run",
107
- coverage: "vitest run --coverage",
108
- typecheck: "tsc --noEmit",
109
- lint: "eslint .",
110
- "format:check": "prettier --check ."
111
- },
112
- overrides: {
113
- esbuild: "^0.28.1"
114
- },
115
- devDependencies: {
116
- "@eslint/js": "^10.0.1",
117
- "@types/node": "^25.9.3",
118
- "@vitest/coverage-v8": "^4.1.9",
119
- eslint: "^10.5.0",
120
- prettier: "^3.8.4",
121
- tsup: "^8.5.1",
122
- typescript: "^6.0.3",
123
- "typescript-eslint": "^8.61.1",
124
- vitest: "^4.1.9"
125
- },
126
- homepage: "https://open-banking.io"
127
- };
128
-
129
- // src/version.ts
130
- var VERSION2 = package_default.version;
131
- var USER_AGENT = `open-banking-io/node/${VERSION2}`;
132
-
133
412
  // src/client.ts
134
413
  var OpenBankingClient = class _OpenBankingClient {
135
414
  /** Default per-request timeout (30s) when {@link OpenBankingClientOptions.timeoutMs} is unset. */
@@ -177,6 +456,13 @@ var OpenBankingClient = class _OpenBankingClient {
177
456
  fetch: overrides.fetch
178
457
  });
179
458
  }
459
+ /**
460
+ * Builds a client from a Partner Connect token response and the private key the consent page
461
+ * relayed — see {@link exchangeCode} and {@link parseRelay}.
462
+ */
463
+ static fromTokenResponse(token, privateKey, overrides = {}) {
464
+ return _OpenBankingClient.fromBundle(bundleFromToken(token, privateKey), overrides);
465
+ }
180
466
  /** Lists the user's accounts with all sensitive fields decrypted. */
181
467
  async getAccounts() {
182
468
  const wires = await this.getAccountWires();
@@ -335,10 +621,75 @@ var OpenBankingClient = class _OpenBankingClient {
335
621
  return await res.json();
336
622
  }
337
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
+ }
338
670
  export {
671
+ CONNECT_RELAY_FIELDS,
672
+ OAuthError,
339
673
  OpenBankingClient,
674
+ PARTNER_KEY_MISSING_DESCRIPTION,
675
+ PARTNER_SUSPENDED_DESCRIPTION,
676
+ RelayError,
677
+ answerRecipientKeyChallenge,
678
+ buildAuthorizeUrl,
679
+ bundleFromToken,
680
+ createPkce,
681
+ createState,
340
682
  decryptEnvelope,
341
683
  decryptTo,
342
- importPrivateKey
684
+ discover,
685
+ exchangeCode,
686
+ generateRecipientKeyPair,
687
+ importPrivateKey,
688
+ parseRelay,
689
+ pkceChallenge,
690
+ recipientKeyFingerprint,
691
+ recipientPublicKey,
692
+ revokeToken,
693
+ userinfo
343
694
  };
344
695
  //# sourceMappingURL=index.js.map