@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/README.md CHANGED
@@ -47,6 +47,143 @@ const client = new OpenBankingClient({ apiBaseUrl, apiKey, privateKeyPkcs8 });
47
47
  Every request carries a `User-Agent: open-banking-io/node/<version>` header and a default 30s timeout
48
48
  (override via the `timeoutMs` option) so a hung connection can't block forever.
49
49
 
50
+ ## Partner Connect (OAuth 2.0 + PKCE)
51
+
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.
79
+
80
+ ```ts
81
+ import {
82
+ buildAuthorizeUrl,
83
+ createPkce,
84
+ createState,
85
+ discover,
86
+ exchangeCode,
87
+ parseRelay,
88
+ OpenBankingClient,
89
+ RelayError,
90
+ } from "@open-banking-io/client";
91
+
92
+ const ISSUER = "https://open-banking.io";
93
+
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.
97
+ app.get("/connect", async (req, res) => {
98
+ const pkce = createPkce();
99
+ const state = createState();
100
+ const mode = req.query.mode === "redirect" ? "redirect" : "popup";
101
+ await flows.put(state, {
102
+ state,
103
+ verifier: pkce.verifier,
104
+ sessionId: req.session.id,
105
+ mode,
106
+ expiresAt: Date.now() + 45 * 60_000,
107
+ });
108
+ res.redirect(
109
+ buildAuthorizeUrl({
110
+ issuer: ISSUER,
111
+ clientId: CLIENT_ID,
112
+ redirectUri: `${SELF_URL}/callback`,
113
+ state,
114
+ codeChallenge: pkce.challenge,
115
+ challenge: "pin_code",
116
+ }),
117
+ );
118
+ });
119
+
120
+ // 2. Callback: the consent page form-posts code, state, iss and (empty) privateKey/publicKey — or
121
+ // error=access_denied when the user went back to you. Consume the flow by state first, so a
122
+ // cancel consumes it too; the lookup is what binds the POST to the session that started it.
123
+ app.post("/callback", express.urlencoded({ extended: false }), async (req, res) => {
124
+ const { issuer } = await discover(ISSUER);
125
+ const flow = await flows.take(req.body.state);
126
+ if (!flow || flow.expiresAt < Date.now()) return res.status(400).send("unknown or expired state");
127
+ let relay;
128
+ try {
129
+ relay = parseRelay(req.body, {
130
+ expectedState: flow.state,
131
+ issuer,
132
+ expectPrivateKey: "optional",
133
+ });
134
+ } catch (e) {
135
+ if (e instanceof RelayError && e.code === "access_denied")
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
+ }
143
+ throw e;
144
+ }
145
+ const token = await exchangeCode({
146
+ issuer,
147
+ clientId: CLIENT_ID,
148
+ clientSecret: CLIENT_SECRET,
149
+ code: relay.code,
150
+ codeVerifier: flow.verifier,
151
+ redirectUri: `${SELF_URL}/callback`,
152
+ });
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 });
156
+ finish(res, flow, "connected");
157
+ });
158
+
159
+ // A redirect-mode flow lands back on your page; a popup signals its opener and closes.
160
+ const finish = (res, flow, outcome) =>
161
+ flow.mode === "redirect"
162
+ ? res.redirect(302, `/?connect=${outcome}`)
163
+ : res.send(closePage(outcome));
164
+ const closePage = (
165
+ outcome,
166
+ ) => `<!doctype html><p>${outcome === "connected" ? "Connected — you can close this window." : outcome === "unavailable" ? "Unavailable right now — try again later." : "Cancelled."}</p>
167
+ <script>try{new BroadcastChannel("bank-connect").postMessage(${JSON.stringify(outcome)})}catch{}setTimeout(()=>window.close(),300)</script>`;
168
+
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
+ );
176
+ const accounts = await client.getAccounts();
177
+ ```
178
+
179
+ `parseRelay` throws a `RelayError` (`access_denied` — the user cancelled, a normal outcome —
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.
186
+
50
187
  ## Money
51
188
 
52
189
  Amounts (`balance.amount`, `transaction.amount`, `transaction.balanceAfterTransaction`) are exposed
package/dist/index.cjs CHANGED
@@ -20,84 +20,39 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ CONNECT_RELAY_FIELDS: () => CONNECT_RELAY_FIELDS,
24
+ OAuthError: () => OAuthError,
23
25
  OpenBankingClient: () => OpenBankingClient,
26
+ PARTNER_KEY_MISSING_DESCRIPTION: () => PARTNER_KEY_MISSING_DESCRIPTION,
27
+ PARTNER_SUSPENDED_DESCRIPTION: () => PARTNER_SUSPENDED_DESCRIPTION,
28
+ RelayError: () => RelayError,
29
+ answerRecipientKeyChallenge: () => answerRecipientKeyChallenge,
30
+ buildAuthorizeUrl: () => buildAuthorizeUrl,
31
+ bundleFromToken: () => bundleFromToken,
32
+ createPkce: () => createPkce,
33
+ createState: () => createState,
24
34
  decryptEnvelope: () => decryptEnvelope,
25
35
  decryptTo: () => decryptTo,
26
- importPrivateKey: () => importPrivateKey
36
+ discover: () => discover,
37
+ exchangeCode: () => exchangeCode,
38
+ generateRecipientKeyPair: () => generateRecipientKeyPair,
39
+ importPrivateKey: () => importPrivateKey,
40
+ parseRelay: () => parseRelay,
41
+ pkceChallenge: () => pkceChallenge,
42
+ recipientKeyFingerprint: () => recipientKeyFingerprint,
43
+ recipientPublicKey: () => recipientPublicKey,
44
+ revokeToken: () => revokeToken,
45
+ userinfo: () => userinfo
27
46
  });
28
47
  module.exports = __toCommonJS(index_exports);
29
48
 
30
- // src/client.ts
31
- var import_node_fs = require("fs");
32
-
33
- // src/envelope.ts
49
+ // src/connect.ts
34
50
  var import_node_crypto = require("crypto");
35
- var { subtle } = import_node_crypto.webcrypto;
36
- var VERSION = 1;
37
- var POINT_LEN = 65;
38
- var NONCE_LEN = 12;
39
- var TAG_LEN = 16;
40
- var HKDF_INFO = new TextEncoder().encode("bank.core.ci/zk/v1");
41
- var HKDF_SALT = new Uint8Array(32);
42
- async function decryptEnvelope(privateKey, envelopeBase64) {
43
- const bytes = base64ToBytes(envelopeBase64);
44
- if (bytes.length < 1 + POINT_LEN + NONCE_LEN + TAG_LEN || bytes[0] !== VERSION) {
45
- throw new Error("Invalid or unsupported envelope");
46
- }
47
- const ephPub = bytes.subarray(1, 1 + POINT_LEN);
48
- const nonce = bytes.subarray(1 + POINT_LEN, 1 + POINT_LEN + NONCE_LEN);
49
- const tag = bytes.subarray(1 + POINT_LEN + NONCE_LEN, 1 + POINT_LEN + NONCE_LEN + TAG_LEN);
50
- const ciphertext = bytes.subarray(1 + POINT_LEN + NONCE_LEN + TAG_LEN);
51
- const ephKey = await subtle.importKey(
52
- "raw",
53
- ephPub,
54
- { name: "ECDH", namedCurve: "P-256" },
55
- false,
56
- []
57
- );
58
- const shared = new Uint8Array(
59
- await subtle.deriveBits({ name: "ECDH", public: ephKey }, privateKey, 256)
60
- );
61
- const hkdf = await subtle.importKey("raw", shared, "HKDF", false, ["deriveKey"]);
62
- const aesKey = await subtle.deriveKey(
63
- { name: "HKDF", hash: "SHA-256", salt: HKDF_SALT, info: HKDF_INFO },
64
- hkdf,
65
- { name: "AES-GCM", length: 256 },
66
- false,
67
- ["decrypt"]
68
- );
69
- const ctWithTag = new Uint8Array(ciphertext.length + tag.length);
70
- ctWithTag.set(ciphertext, 0);
71
- ctWithTag.set(tag, ciphertext.length);
72
- const plaintext = await subtle.decrypt(
73
- { name: "AES-GCM", iv: nonce, tagLength: 128 },
74
- aesKey,
75
- ctWithTag
76
- );
77
- return new Uint8Array(plaintext);
78
- }
79
- async function decryptTo(privateKey, envelopeBase64) {
80
- if (envelopeBase64 == null) return null;
81
- const plaintext = await decryptEnvelope(privateKey, envelopeBase64);
82
- return JSON.parse(new TextDecoder().decode(plaintext));
83
- }
84
- async function importPrivateKey(pkcs8Base64) {
85
- return subtle.importKey(
86
- "pkcs8",
87
- base64ToBytes(pkcs8Base64),
88
- { name: "ECDH", namedCurve: "P-256" },
89
- false,
90
- ["deriveBits"]
91
- );
92
- }
93
- function base64ToBytes(b64) {
94
- return new Uint8Array(Buffer.from(b64, "base64"));
95
- }
96
51
 
97
52
  // package.json
98
53
  var package_default = {
99
54
  name: "@open-banking-io/client",
100
- version: "1.0.0",
55
+ version: "1.2.0",
101
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.",
102
57
  type: "module",
103
58
  license: "MIT",
@@ -156,8 +111,351 @@ var package_default = {
156
111
  };
157
112
 
158
113
  // src/version.ts
159
- var VERSION2 = package_default.version;
160
- var USER_AGENT = `open-banking-io/node/${VERSION2}`;
114
+ var VERSION = package_default.version;
115
+ var USER_AGENT = `open-banking-io/node/${VERSION}`;
116
+
117
+ // src/connect.ts
118
+ var DEFAULT_TIMEOUT_MS = 3e4;
119
+ var CONNECT_RELAY_FIELDS = ["code", "state", "iss", "privateKey", "publicKey"];
120
+ function createPkce() {
121
+ const verifier = (0, import_node_crypto.randomBytes)(32).toString("base64url");
122
+ return { verifier, challenge: pkceChallenge(verifier), method: "S256" };
123
+ }
124
+ function pkceChallenge(verifier) {
125
+ return (0, import_node_crypto.createHash)("sha256").update(verifier).digest("base64url");
126
+ }
127
+ function createState() {
128
+ return (0, import_node_crypto.randomBytes)(16).toString("base64url");
129
+ }
130
+ function buildAuthorizeUrl(options) {
131
+ const params = new URLSearchParams({
132
+ response_type: "code",
133
+ client_id: options.clientId,
134
+ redirect_uri: options.redirectUri,
135
+ scope: options.scope ?? "accounts.read",
136
+ state: options.state,
137
+ code_challenge: options.codeChallenge,
138
+ code_challenge_method: "S256",
139
+ response_mode: "form_post"
140
+ });
141
+ if (options.loginHint) params.set("login_hint", options.loginHint);
142
+ if (options.challenge) params.set("challenge", options.challenge);
143
+ if (options.uiLocales) params.set("ui_locales", options.uiLocales);
144
+ return `${endpoint(options.issuer, "/oauth/authorize")}?${params.toString()}`;
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
+ }
154
+ var RelayError = class extends Error {
155
+ code;
156
+ error;
157
+ errorDescription;
158
+ /** Set on an `oauth_error` whose description names a partner-side refusal. */
159
+ reason;
160
+ constructor(code, message, oauth) {
161
+ super(message);
162
+ this.name = "RelayError";
163
+ this.code = code;
164
+ this.error = oauth?.error;
165
+ this.errorDescription = oauth?.errorDescription;
166
+ this.reason = oauth ? refusalReason(oauth.error, oauth.errorDescription ?? "") : void 0;
167
+ }
168
+ };
169
+ function parseRelay(input, options) {
170
+ const fields = toRecord(input);
171
+ const read = (name) => {
172
+ const value = fields[name];
173
+ return typeof value === "string" ? value : "";
174
+ };
175
+ if (!options.expectedState || !constantTimeEqual(read("state"), options.expectedState)) {
176
+ throw new RelayError("state_mismatch", "The relayed state does not match this flow");
177
+ }
178
+ const iss = read("iss");
179
+ const wantIss = options.issuer !== void 0 || options.requireIss === true;
180
+ if (wantIss && !iss) throw new RelayError("issuer_mismatch", "The relay carries no iss");
181
+ if (options.issuer !== void 0 && !constantTimeEqual(trimSlash(iss), trimSlash(options.issuer))) {
182
+ throw new RelayError("issuer_mismatch", "The relayed iss is not the expected issuer");
183
+ }
184
+ const error = read("error");
185
+ if (error) {
186
+ const description = read("error_description");
187
+ throw new RelayError(
188
+ error === "access_denied" ? "access_denied" : "oauth_error",
189
+ description ? `${error}: ${description}` : error,
190
+ {
191
+ error,
192
+ errorDescription: description || void 0
193
+ }
194
+ );
195
+ }
196
+ const code = read("code");
197
+ if (!code) throw new RelayError("missing_code", "The relay carries no authorization code");
198
+ const privateKey = read("privateKey");
199
+ if (!privateKey && (options.expectPrivateKey ?? "required") === "required") {
200
+ throw new RelayError("missing_private_key", "The relay carries no private key");
201
+ }
202
+ return { code, state: read("state"), iss, privateKey, publicKey: read("publicKey") };
203
+ }
204
+ var OAuthError = class extends Error {
205
+ status;
206
+ error;
207
+ errorDescription;
208
+ constructor(status, error, errorDescription) {
209
+ super(errorDescription ? `${error}: ${errorDescription}` : error);
210
+ this.name = "OAuthError";
211
+ this.status = status;
212
+ this.error = error;
213
+ this.errorDescription = errorDescription;
214
+ }
215
+ };
216
+ async function exchangeCode(options) {
217
+ const body = new URLSearchParams({
218
+ grant_type: "authorization_code",
219
+ code: options.code,
220
+ code_verifier: options.codeVerifier
221
+ });
222
+ if (options.redirectUri) body.set("redirect_uri", options.redirectUri);
223
+ const response = await post(
224
+ endpoint(options.issuer, "/oauth/token"),
225
+ body,
226
+ {
227
+ Authorization: basicAuth(options.clientId, options.clientSecret),
228
+ Accept: "application/json"
229
+ },
230
+ options
231
+ );
232
+ await throwIfOAuthError(response);
233
+ const wire = await response.json();
234
+ const accessToken = wire.access_token ?? wire.apiKey;
235
+ if (!accessToken)
236
+ throw new OAuthError(
237
+ response.status,
238
+ "invalid_response",
239
+ "The token response carries no access token"
240
+ );
241
+ return {
242
+ accessToken,
243
+ tokenType: wire.token_type ?? "Bearer",
244
+ expiresIn: wire.expires_in ?? 0,
245
+ scope: wire.scope ?? "",
246
+ apiKey: wire.apiKey ?? accessToken,
247
+ apiBaseUrl: wire.apiBaseUrl ?? trimSlash(options.issuer),
248
+ user: wire.user ?? ""
249
+ };
250
+ }
251
+ async function revokeToken(options) {
252
+ const body = new URLSearchParams({ token: options.token, token_type_hint: "access_token" });
253
+ const response = await post(
254
+ endpoint(options.issuer, "/oauth/revoke"),
255
+ body,
256
+ {
257
+ Authorization: basicAuth(options.clientId, options.clientSecret)
258
+ },
259
+ options
260
+ );
261
+ await throwIfOAuthError(response);
262
+ }
263
+ async function userinfo(options) {
264
+ const response = await request(
265
+ endpoint(options.issuer, "/oauth/userinfo"),
266
+ {
267
+ method: "GET",
268
+ headers: {
269
+ Authorization: `Bearer ${options.accessToken}`,
270
+ Accept: "application/json",
271
+ "User-Agent": USER_AGENT
272
+ }
273
+ },
274
+ options
275
+ );
276
+ await throwIfOAuthError(response);
277
+ const wire = await response.json();
278
+ return {
279
+ sub: wire.sub,
280
+ email: wire.email,
281
+ partnerId: wire.partner_id ?? null,
282
+ clientId: wire.client_id ?? null,
283
+ scope: wire.scope,
284
+ expiresAt: wire.expires_at ?? null
285
+ };
286
+ }
287
+ var discoveryCache = /* @__PURE__ */ new Map();
288
+ var DISCOVERY_TTL_MS = 60 * 60 * 1e3;
289
+ async function discover(issuer, options = {}) {
290
+ const key = trimSlash(issuer);
291
+ const cached = discoveryCache.get(key);
292
+ if (cached && cached.expiresAt > Date.now()) return cached.metadata;
293
+ const response = await request(
294
+ `${key}/.well-known/oauth-authorization-server`,
295
+ {
296
+ method: "GET",
297
+ headers: { Accept: "application/json", "User-Agent": USER_AGENT }
298
+ },
299
+ options
300
+ );
301
+ if (!response.ok)
302
+ throw new OAuthError(response.status, "discovery_failed", `HTTP ${response.status}`);
303
+ const metadata = await response.json();
304
+ if (typeof metadata.issuer !== "string" || trimSlash(metadata.issuer) !== key) {
305
+ throw new OAuthError(
306
+ response.status,
307
+ "discovery_failed",
308
+ `Issuer mismatch: ${String(metadata.issuer)}`
309
+ );
310
+ }
311
+ discoveryCache.set(key, { metadata, expiresAt: Date.now() + DISCOVERY_TTL_MS });
312
+ return metadata;
313
+ }
314
+ function bundleFromToken(token, privateKey) {
315
+ return {
316
+ service: "open-banking.io",
317
+ apiBaseUrl: token.apiBaseUrl,
318
+ user: token.user,
319
+ apiKey: token.accessToken,
320
+ encryptionKey: { scheme: "ecdh-p256-hkdf-aes-256-gcm", curve: "P-256", privateKey }
321
+ };
322
+ }
323
+ function endpoint(issuer, path) {
324
+ return trimSlash(issuer) + path;
325
+ }
326
+ function trimSlash(value) {
327
+ let end = value.length;
328
+ while (end > 0 && value[end - 1] === "/") end--;
329
+ return value.slice(0, end);
330
+ }
331
+ function basicAuth(clientId, clientSecret) {
332
+ const pair = `${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`;
333
+ return `Basic ${Buffer.from(pair, "utf8").toString("base64")}`;
334
+ }
335
+ function constantTimeEqual(a, b) {
336
+ const x = (0, import_node_crypto.createHash)("sha256").update(a, "utf8").digest();
337
+ const y = (0, import_node_crypto.createHash)("sha256").update(b, "utf8").digest();
338
+ return (0, import_node_crypto.timingSafeEqual)(x, y) && a.length === b.length;
339
+ }
340
+ function toRecord(input) {
341
+ if (typeof input === "string") {
342
+ const trimmed = input.trim();
343
+ if (trimmed.startsWith("{")) return JSON.parse(trimmed);
344
+ return Object.fromEntries(new URLSearchParams(trimmed));
345
+ }
346
+ if (input instanceof URLSearchParams) return Object.fromEntries(input);
347
+ if (input instanceof FormData) {
348
+ const record = {};
349
+ input.forEach((value, name) => {
350
+ if (typeof value === "string") record[name] = value;
351
+ });
352
+ return record;
353
+ }
354
+ return input;
355
+ }
356
+ async function post(url, body, headers, options) {
357
+ return request(
358
+ url,
359
+ {
360
+ method: "POST",
361
+ headers: {
362
+ ...headers,
363
+ "Content-Type": "application/x-www-form-urlencoded",
364
+ "User-Agent": USER_AGENT
365
+ },
366
+ body: body.toString()
367
+ },
368
+ options
369
+ );
370
+ }
371
+ async function request(url, init, options) {
372
+ const fetchImpl = options.fetch ?? fetch;
373
+ return fetchImpl(url, {
374
+ ...init,
375
+ signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
376
+ });
377
+ }
378
+ async function throwIfOAuthError(response) {
379
+ if (response.ok) return;
380
+ let error = "http_error";
381
+ let description = `HTTP ${response.status}`;
382
+ try {
383
+ const body = await response.json();
384
+ if (body.error) {
385
+ error = body.error;
386
+ description = body.error_description;
387
+ }
388
+ } catch {
389
+ }
390
+ throw new OAuthError(response.status, error, description);
391
+ }
392
+
393
+ // src/client.ts
394
+ var import_node_fs = require("fs");
395
+
396
+ // src/envelope.ts
397
+ var import_node_crypto2 = require("crypto");
398
+ var { subtle } = import_node_crypto2.webcrypto;
399
+ var VERSION2 = 1;
400
+ var POINT_LEN = 65;
401
+ var NONCE_LEN = 12;
402
+ var TAG_LEN = 16;
403
+ var HKDF_INFO = new TextEncoder().encode("bank.core.ci/zk/v1");
404
+ var HKDF_SALT = new Uint8Array(32);
405
+ async function decryptEnvelope(privateKey, envelopeBase64) {
406
+ const bytes = base64ToBytes(envelopeBase64);
407
+ if (bytes.length < 1 + POINT_LEN + NONCE_LEN + TAG_LEN || bytes[0] !== VERSION2) {
408
+ throw new Error("Invalid or unsupported envelope");
409
+ }
410
+ const ephPub = bytes.subarray(1, 1 + POINT_LEN);
411
+ const nonce = bytes.subarray(1 + POINT_LEN, 1 + POINT_LEN + NONCE_LEN);
412
+ const tag = bytes.subarray(1 + POINT_LEN + NONCE_LEN, 1 + POINT_LEN + NONCE_LEN + TAG_LEN);
413
+ const ciphertext = bytes.subarray(1 + POINT_LEN + NONCE_LEN + TAG_LEN);
414
+ const ephKey = await subtle.importKey(
415
+ "raw",
416
+ ephPub,
417
+ { name: "ECDH", namedCurve: "P-256" },
418
+ false,
419
+ []
420
+ );
421
+ const shared = new Uint8Array(
422
+ await subtle.deriveBits({ name: "ECDH", public: ephKey }, privateKey, 256)
423
+ );
424
+ const hkdf = await subtle.importKey("raw", shared, "HKDF", false, ["deriveKey"]);
425
+ const aesKey = await subtle.deriveKey(
426
+ { name: "HKDF", hash: "SHA-256", salt: HKDF_SALT, info: HKDF_INFO },
427
+ hkdf,
428
+ { name: "AES-GCM", length: 256 },
429
+ false,
430
+ ["decrypt"]
431
+ );
432
+ const ctWithTag = new Uint8Array(ciphertext.length + tag.length);
433
+ ctWithTag.set(ciphertext, 0);
434
+ ctWithTag.set(tag, ciphertext.length);
435
+ const plaintext = await subtle.decrypt(
436
+ { name: "AES-GCM", iv: nonce, tagLength: 128 },
437
+ aesKey,
438
+ ctWithTag
439
+ );
440
+ return new Uint8Array(plaintext);
441
+ }
442
+ async function decryptTo(privateKey, envelopeBase64) {
443
+ if (envelopeBase64 == null) return null;
444
+ const plaintext = await decryptEnvelope(privateKey, envelopeBase64);
445
+ return JSON.parse(new TextDecoder().decode(plaintext));
446
+ }
447
+ async function importPrivateKey(pkcs8Base64) {
448
+ return subtle.importKey(
449
+ "pkcs8",
450
+ base64ToBytes(pkcs8Base64),
451
+ { name: "ECDH", namedCurve: "P-256" },
452
+ false,
453
+ ["deriveBits"]
454
+ );
455
+ }
456
+ function base64ToBytes(b64) {
457
+ return new Uint8Array(Buffer.from(b64, "base64"));
458
+ }
161
459
 
162
460
  // src/client.ts
163
461
  var OpenBankingClient = class _OpenBankingClient {
@@ -206,6 +504,13 @@ var OpenBankingClient = class _OpenBankingClient {
206
504
  fetch: overrides.fetch
207
505
  });
208
506
  }
507
+ /**
508
+ * Builds a client from a Partner Connect token response and the private key the consent page
509
+ * relayed — see {@link exchangeCode} and {@link parseRelay}.
510
+ */
511
+ static fromTokenResponse(token, privateKey, overrides = {}) {
512
+ return _OpenBankingClient.fromBundle(bundleFromToken(token, privateKey), overrides);
513
+ }
209
514
  /** Lists the user's accounts with all sensitive fields decrypted. */
210
515
  async getAccounts() {
211
516
  const wires = await this.getAccountWires();
@@ -364,11 +669,76 @@ var OpenBankingClient = class _OpenBankingClient {
364
669
  return await res.json();
365
670
  }
366
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
+ }
367
718
  // Annotate the CommonJS export names for ESM import in node:
368
719
  0 && (module.exports = {
720
+ CONNECT_RELAY_FIELDS,
721
+ OAuthError,
369
722
  OpenBankingClient,
723
+ PARTNER_KEY_MISSING_DESCRIPTION,
724
+ PARTNER_SUSPENDED_DESCRIPTION,
725
+ RelayError,
726
+ answerRecipientKeyChallenge,
727
+ buildAuthorizeUrl,
728
+ bundleFromToken,
729
+ createPkce,
730
+ createState,
370
731
  decryptEnvelope,
371
732
  decryptTo,
372
- importPrivateKey
733
+ discover,
734
+ exchangeCode,
735
+ generateRecipientKeyPair,
736
+ importPrivateKey,
737
+ parseRelay,
738
+ pkceChallenge,
739
+ recipientKeyFingerprint,
740
+ recipientPublicKey,
741
+ revokeToken,
742
+ userinfo
373
743
  });
374
744
  //# sourceMappingURL=index.cjs.map