@open-banking-io/client 1.1.0 → 1.3.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,70 @@ 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.
186
+
187
+ ### Sync failures, renewal and the present user
188
+
189
+ ```ts
190
+ import { closeReplacedConsents, SyncError } from "@open-banking-io/client";
191
+
192
+ // Per-account refusals come back in failures; branch on reason, never on the status.
193
+ const { failures } = await client.syncAll();
194
+ for (const f of failures) {
195
+ if (f.reason === "reconnect_needed") promptRenewal(f.accountId);
196
+ if (f.reason === "psu_present_required") askToSyncWhilePresent(f.accountId);
197
+ }
198
+
199
+ // A single-account sync throws SyncError with the same reason (and retryAfterSeconds on a 429).
200
+ // Both calls re-read the account and retry once on uid_outdated.
201
+
202
+ // Some banks only share data while the account holder is present. Forward their own request —
203
+ // only from a request they made, never from a background job.
204
+ await client.syncAll({
205
+ psu: {
206
+ ipAddress: req.ip,
207
+ userAgent: req.get("user-agent"),
208
+ acceptLanguage: req.get("accept-language"),
209
+ },
210
+ });
211
+
212
+ // Renew a consent before validUntil (or after it lapsed): send the user through the same flow
213
+ // with renewConnection, then close what the previous key still holds open and revoke it.
214
+ const expiring = (await client.getConnections()).filter(
215
+ (c) => Date.parse(c.validUntil) - Date.now() < 7 * 86_400_000,
216
+ );
217
+ buildAuthorizeUrl({ ...authorizeOptions, renewConnection: expiring[0].sessionId });
218
+ // …in the callback, after exchangeCode:
219
+ await closeReplacedConsents({
220
+ issuer,
221
+ clientId: CLIENT_ID,
222
+ clientSecret: CLIENT_SECRET,
223
+ token: previousToken.accessToken,
224
+ privateKey: RECIPIENT_PRIVATE_KEY,
225
+ });
226
+ ```
227
+
228
+ `Connection.isLive` is decided by the service's clock; `status` stays `Active` after `validUntil`.
229
+ `Connection.accountIds` names the connection to renew for an account `syncAll` reported.
143
230
 
144
231
  ## Money
145
232
 
package/dist/index.cjs CHANGED
@@ -23,18 +23,27 @@ __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
+ SyncError: () => SyncError,
30
+ answerRecipientKeyChallenge: () => answerRecipientKeyChallenge,
27
31
  buildAuthorizeUrl: () => buildAuthorizeUrl,
28
32
  bundleFromToken: () => bundleFromToken,
33
+ closeReplacedConsents: () => closeReplacedConsents,
29
34
  createPkce: () => createPkce,
30
35
  createState: () => createState,
31
36
  decryptEnvelope: () => decryptEnvelope,
32
37
  decryptTo: () => decryptTo,
33
38
  discover: () => discover,
34
39
  exchangeCode: () => exchangeCode,
40
+ generateRecipientKeyPair: () => generateRecipientKeyPair,
35
41
  importPrivateKey: () => importPrivateKey,
36
42
  parseRelay: () => parseRelay,
37
43
  pkceChallenge: () => pkceChallenge,
44
+ psuHeaders: () => psuHeaders,
45
+ recipientKeyFingerprint: () => recipientKeyFingerprint,
46
+ recipientPublicKey: () => recipientPublicKey,
38
47
  revokeToken: () => revokeToken,
39
48
  userinfo: () => userinfo
40
49
  });
@@ -46,7 +55,7 @@ var import_node_crypto = require("crypto");
46
55
  // package.json
47
56
  var package_default = {
48
57
  name: "@open-banking-io/client",
49
- version: "1.1.0",
58
+ version: "1.3.0",
50
59
  description: "Server-to-server client for open-banking.io: API-key auth + client-side decryption of the zero-knowledge data envelopes with your exported private key.",
51
60
  type: "module",
52
61
  license: "MIT",
@@ -135,18 +144,30 @@ function buildAuthorizeUrl(options) {
135
144
  if (options.loginHint) params.set("login_hint", options.loginHint);
136
145
  if (options.challenge) params.set("challenge", options.challenge);
137
146
  if (options.uiLocales) params.set("ui_locales", options.uiLocales);
147
+ if (options.renewConnection) params.set("renew_connection", options.renewConnection);
138
148
  return `${endpoint(options.issuer, "/oauth/authorize")}?${params.toString()}`;
139
149
  }
150
+ var PARTNER_KEY_MISSING_DESCRIPTION = "this partner has not installed its decryption key; no authorizations can be started until it does";
151
+ var PARTNER_SUSPENDED_DESCRIPTION = "this partner is suspended; no authorizations can be started";
152
+ function refusalReason(error, description) {
153
+ if (error !== "temporarily_unavailable") return void 0;
154
+ if (description === PARTNER_KEY_MISSING_DESCRIPTION) return "partner_key_missing";
155
+ if (description === PARTNER_SUSPENDED_DESCRIPTION) return "partner_suspended";
156
+ return void 0;
157
+ }
140
158
  var RelayError = class extends Error {
141
159
  code;
142
160
  error;
143
161
  errorDescription;
162
+ /** Set on an `oauth_error` whose description names a partner-side refusal. */
163
+ reason;
144
164
  constructor(code, message, oauth) {
145
165
  super(message);
146
166
  this.name = "RelayError";
147
167
  this.code = code;
148
168
  this.error = oauth?.error;
149
169
  this.errorDescription = oauth?.errorDescription;
170
+ this.reason = oauth ? refusalReason(oauth.error, oauth.errorDescription ?? "") : void 0;
150
171
  }
151
172
  };
152
173
  function parseRelay(input, options) {
@@ -179,7 +200,9 @@ function parseRelay(input, options) {
179
200
  const code = read("code");
180
201
  if (!code) throw new RelayError("missing_code", "The relay carries no authorization code");
181
202
  const privateKey = read("privateKey");
182
- if (!privateKey) throw new RelayError("missing_private_key", "The relay carries no private key");
203
+ if (!privateKey && (options.expectPrivateKey ?? "required") === "required") {
204
+ throw new RelayError("missing_private_key", "The relay carries no private key");
205
+ }
183
206
  return { code, state: read("state"), iss, privateKey, publicKey: read("publicKey") };
184
207
  }
185
208
  var OAuthError = class extends Error {
@@ -231,6 +254,10 @@ async function exchangeCode(options) {
231
254
  }
232
255
  async function revokeToken(options) {
233
256
  const body = new URLSearchParams({ token: options.token, token_type_hint: "access_token" });
257
+ for (const c of options.closeConsents ?? []) {
258
+ body.append("connection_id", c.connectionId);
259
+ body.append("eb_session_id", c.ebSessionId);
260
+ }
234
261
  const response = await post(
235
262
  endpoint(options.issuer, "/oauth/revoke"),
236
263
  body,
@@ -438,6 +465,22 @@ function base64ToBytes(b64) {
438
465
  return new Uint8Array(Buffer.from(b64, "base64"));
439
466
  }
440
467
 
468
+ // src/errors.ts
469
+ var SyncError = class extends Error {
470
+ status;
471
+ reason;
472
+ bankErrorCode;
473
+ retryAfterSeconds;
474
+ constructor(message, status, reason, bankErrorCode = null, retryAfterSeconds = null) {
475
+ super(message);
476
+ this.name = "SyncError";
477
+ this.status = status;
478
+ this.reason = reason;
479
+ this.bankErrorCode = bankErrorCode;
480
+ this.retryAfterSeconds = retryAfterSeconds;
481
+ }
482
+ };
483
+
441
484
  // src/client.ts
442
485
  var OpenBankingClient = class _OpenBankingClient {
443
486
  /** Default per-request timeout (30s) when {@link OpenBankingClientOptions.timeoutMs} is unset. */
@@ -522,41 +565,102 @@ var OpenBankingClient = class _OpenBankingClient {
522
565
  status: c.status,
523
566
  accountCount: c.accountCount,
524
567
  lastSyncedAt: c.lastSyncedAt ?? null,
525
- psuType: c.psuType ?? null
568
+ psuType: c.psuType ?? null,
569
+ isLive: c.isLive ?? (c.status === "Active" && Date.parse(c.validUntil) > Date.now()),
570
+ accountIds: c.accountIds ?? []
526
571
  }));
527
572
  }
528
573
  /**
529
574
  * Triggers an online sync of one account: decrypts that account's Enable Banking uid and posts
530
575
  * it, so the service can fetch fresh data without ever holding the uid in plaintext.
576
+ *
577
+ * A refusal throws {@link SyncError}. A uid a renewal replaced (`uid_outdated`) is re-read and
578
+ * retried once.
531
579
  */
532
- async sync(accountId) {
533
- const wires = await this.getAccountWires();
534
- const account = wires.find((a) => a.id === accountId);
535
- if (!account) throw new Error(`Account ${accountId} not found`);
536
- const uid = await this.decryptUid(account);
537
- if (uid == null) {
538
- throw new Error("Account has no active session (reconnect required) \u2014 cannot sync");
580
+ async sync(accountId, options = {}) {
581
+ for (let attempt = 0; ; attempt++) {
582
+ const wires = await this.getAccountWires();
583
+ const account = wires.find((a) => a.id === accountId);
584
+ if (!account) throw new Error(`Account ${accountId} not found`);
585
+ const uid = account.needsReconnect ? null : await this.decryptUid(account);
586
+ if (uid == null) {
587
+ throw new SyncError(
588
+ "Account has no active session (reconnect required) \u2014 cannot sync",
589
+ 409,
590
+ "reconnect_needed"
591
+ );
592
+ }
593
+ try {
594
+ const result = await this.postJson(
595
+ `/api/accounts/${encodeURIComponent(accountId)}/sync`,
596
+ { uid },
597
+ psuHeaders(options.psu)
598
+ );
599
+ return { newTransactions: result.newTransactions, totalFetched: result.totalFetched };
600
+ } catch (e) {
601
+ if (attempt === 0 && e instanceof SyncError && e.reason === "uid_outdated") continue;
602
+ throw e;
603
+ }
539
604
  }
540
- const result = await this.postJson(
541
- `/api/accounts/${encodeURIComponent(accountId)}/sync`,
542
- { uid }
543
- );
544
- return { newTransactions: result.newTransactions, totalFetched: result.totalFetched };
545
605
  }
546
- /** Triggers an online sync of every account that has an active session. */
547
- async syncAll() {
548
- const wires = await this.getAccountWires();
549
- const decrypted = await Promise.all(
550
- wires.map(async (a) => ({ accountId: a.id, uid: await this.decryptUid(a) }))
606
+ /**
607
+ * Triggers an online sync of every account that has an active session. Per-account refusals are
608
+ * in `failures`, and so is every account whose consent needs renewing (`reconnect_needed`, never
609
+ * sent); accounts answering `uid_outdated` are re-read and retried once.
610
+ */
611
+ async syncAll(options = {}) {
612
+ const read = await this.syncItems();
613
+ const first = await this.postSyncAll(read.items, options);
614
+ first.failures.push(...read.lapsed);
615
+ const outdated = new Set(
616
+ first.failures.filter((f) => f.reason === "uid_outdated").map((f) => f.accountId)
551
617
  );
552
- const items = decrypted.filter((x) => x.uid != null).map((x) => ({ accountId: x.accountId, uid: x.uid }));
553
- const result = await this.postJson("/api/sync", { items });
554
- return { accounts: result.accounts, newTransactions: result.newTransactions };
618
+ if (outdated.size === 0) return first;
619
+ const reread = await this.syncItems();
620
+ const retryItems = reread.items.filter((i) => outdated.has(i.accountId));
621
+ const lapsedNow = reread.lapsed.filter((f) => outdated.has(f.accountId));
622
+ const settled = new Set([...retryItems, ...lapsedNow].map((i) => i.accountId));
623
+ const kept = first.failures.filter((f) => !settled.has(f.accountId));
624
+ if (retryItems.length === 0) return { ...first, failures: [...kept, ...lapsedNow] };
625
+ const second = await this.postSyncAll(retryItems, options);
626
+ return {
627
+ accounts: first.accounts + second.accounts,
628
+ newTransactions: first.newTransactions + second.newTransactions,
629
+ failures: [...kept, ...lapsedNow, ...second.failures]
630
+ };
555
631
  }
556
632
  // ---- internals ---------------------------------------------------------------------------------
557
633
  getAccountWires() {
558
634
  return this.getJson("/api/accounts");
559
635
  }
636
+ async syncItems() {
637
+ const wires = await this.getAccountWires();
638
+ const decrypted = await Promise.all(
639
+ wires.map(async (a) => ({
640
+ accountId: a.id,
641
+ needsReconnect: a.needsReconnect,
642
+ uid: a.needsReconnect ? null : await this.decryptUid(a)
643
+ }))
644
+ );
645
+ return {
646
+ items: decrypted.filter((x) => x.uid != null).map((x) => ({ accountId: x.accountId, uid: x.uid })),
647
+ lapsed: decrypted.filter((x) => x.uid == null && x.needsReconnect).map((x) => ({ accountId: x.accountId, reason: "reconnect_needed", bankErrorCode: null }))
648
+ };
649
+ }
650
+ async postSyncAll(items, options) {
651
+ if (items.length === 0) return { accounts: 0, newTransactions: 0, failures: [] };
652
+ const result = await this.postJson(
653
+ "/api/sync",
654
+ { items },
655
+ psuHeaders(options.psu)
656
+ );
657
+ const failures = (result.failures ?? []).map((f) => ({
658
+ accountId: f.accountId,
659
+ reason: f.reason,
660
+ bankErrorCode: f.bankErrorCode ?? null
661
+ }));
662
+ return { accounts: result.accounts, newTransactions: result.newTransactions, failures };
663
+ }
560
664
  async decryptUid(a) {
561
665
  const dec = await decryptTo(await this.privateKey, a.uidEnc);
562
666
  return dec?.uid ?? null;
@@ -633,10 +737,11 @@ var OpenBankingClient = class _OpenBankingClient {
633
737
  }
634
738
  return await res.json();
635
739
  }
636
- async postJson(path, body) {
740
+ async postJson(path, body, extraHeaders = {}) {
637
741
  const res = await this.fetchImpl(this.baseUrl + path, {
638
742
  method: "POST",
639
743
  headers: {
744
+ ...extraHeaders,
640
745
  "X-Api-Key": this.apiKey,
641
746
  "Content-Type": "application/json",
642
747
  "User-Agent": USER_AGENT
@@ -645,28 +750,177 @@ var OpenBankingClient = class _OpenBankingClient {
645
750
  signal: AbortSignal.timeout(this.timeoutMs)
646
751
  });
647
752
  if (!res.ok) {
648
- throw new Error(`POST ${path} failed: ${res.status} ${res.statusText}`);
753
+ const problem = await readProblem(res);
754
+ const retryAfter = Number.parseInt(res.headers.get("Retry-After") ?? "", 10);
755
+ throw new SyncError(
756
+ `POST ${path} failed: ${res.status} ${problem.reason ?? res.statusText}`,
757
+ res.status,
758
+ problem.reason,
759
+ problem.bankErrorCode,
760
+ Number.isFinite(retryAfter) ? retryAfter : null
761
+ );
649
762
  }
650
763
  return await res.json();
651
764
  }
652
765
  };
766
+ async function readProblem(res) {
767
+ try {
768
+ const body = await res.json();
769
+ return {
770
+ reason: typeof body.reason === "string" ? body.reason : null,
771
+ bankErrorCode: typeof body.bankErrorCode === "string" ? body.bankErrorCode : null
772
+ };
773
+ } catch {
774
+ return { reason: null, bankErrorCode: null };
775
+ }
776
+ }
777
+ function psuHeaders(psu) {
778
+ if (!psu?.ipAddress || !psu.userAgent) return {};
779
+ const headers = {
780
+ "X-Psu-Ip-Address": psu.ipAddress,
781
+ "X-Psu-User-Agent": psu.userAgent
782
+ };
783
+ const optional = [
784
+ ["X-Psu-Referer", psu.referer],
785
+ ["X-Psu-Accept", psu.accept],
786
+ ["X-Psu-Accept-Language", psu.acceptLanguage],
787
+ ["X-Psu-Accept-Charset", psu.acceptCharset],
788
+ ["X-Psu-Accept-Encoding", psu.acceptEncoding]
789
+ ];
790
+ for (const [name, value] of optional) if (value) headers[name] = value;
791
+ return headers;
792
+ }
793
+
794
+ // src/consents.ts
795
+ async function closeReplacedConsents(options) {
796
+ const fetchImpl = options.fetch ?? fetch;
797
+ const base = trimSlash2(options.apiBaseUrl ?? options.issuer);
798
+ const nothing = { closed: 0, failed: 0, revoked: false };
799
+ let owner;
800
+ try {
801
+ owner = (await userinfo({ ...options, accessToken: options.token })).clientId;
802
+ } catch (e) {
803
+ if (e instanceof OAuthError && keyRefused(e.status)) return nothing;
804
+ throw e;
805
+ }
806
+ if (owner !== options.clientId) return nothing;
807
+ const res = await fetchImpl(`${base}/api/connections/open-consents`, {
808
+ headers: { "X-Api-Key": options.token, "User-Agent": USER_AGENT },
809
+ signal: AbortSignal.timeout(options.timeoutMs ?? 3e4)
810
+ });
811
+ if (keyRefused(res.status)) return nothing;
812
+ if (!res.ok) throw new Error(`GET /api/connections/open-consents failed: ${res.status}`);
813
+ const open = await res.json();
814
+ const key = await importPrivateKey(options.privateKey);
815
+ const closeConsents = [];
816
+ const seen = /* @__PURE__ */ new Set();
817
+ let failed = 0;
818
+ for (const c of open) {
819
+ if (!c.connectionId || seen.has(c.connectionId)) continue;
820
+ seen.add(c.connectionId);
821
+ if (!c.sessionIdEnc) {
822
+ failed += 1;
823
+ continue;
824
+ }
825
+ let sessionId;
826
+ try {
827
+ sessionId = (await decryptTo(key, c.sessionIdEnc))?.sessionId;
828
+ } catch {
829
+ sessionId = null;
830
+ }
831
+ if (!sessionId) {
832
+ failed += 1;
833
+ continue;
834
+ }
835
+ closeConsents.push({ connectionId: c.connectionId, ebSessionId: sessionId });
836
+ }
837
+ try {
838
+ await revokeToken({ ...options, closeConsents });
839
+ } catch (e) {
840
+ if (e instanceof OAuthError && e.status < 500 && e.status !== 429)
841
+ return { closed: 0, failed: failed + closeConsents.length, revoked: false };
842
+ throw e;
843
+ }
844
+ return { closed: closeConsents.length, failed, revoked: true };
845
+ }
846
+ var keyRefused = (status) => status === 401 || status === 403;
847
+ function trimSlash2(url) {
848
+ let end = url.length;
849
+ while (end > 0 && url.charCodeAt(end - 1) === 47) end--;
850
+ return url.slice(0, end);
851
+ }
852
+
853
+ // src/recipientKey.ts
854
+ var import_node_crypto3 = require("crypto");
855
+ var subtle2 = import_node_crypto3.webcrypto.subtle;
856
+ async function generateRecipientKeyPair() {
857
+ const pair = await subtle2.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, [
858
+ "deriveBits"
859
+ ]);
860
+ return {
861
+ privateKeyPkcs8Base64: Buffer.from(await subtle2.exportKey("pkcs8", pair.privateKey)).toString(
862
+ "base64"
863
+ ),
864
+ publicKeyRawBase64: Buffer.from(await subtle2.exportKey("raw", pair.publicKey)).toString(
865
+ "base64"
866
+ )
867
+ };
868
+ }
869
+ function recipientKeyFingerprint(publicKeyRawBase64) {
870
+ return (0, import_node_crypto3.createHash)("sha256").update(Buffer.from(publicKeyRawBase64, "base64")).digest("hex").slice(0, 16);
871
+ }
872
+ async function recipientPublicKey(privateKeyPkcs8Base64) {
873
+ const key = await subtle2.importKey(
874
+ "pkcs8",
875
+ Buffer.from(privateKeyPkcs8Base64, "base64"),
876
+ { name: "ECDH", namedCurve: "P-256" },
877
+ true,
878
+ ["deriveBits"]
879
+ );
880
+ const jwk = await subtle2.exportKey("jwk", key);
881
+ if (!jwk.x || !jwk.y) throw new Error("The private key carries no public point");
882
+ return Buffer.concat([
883
+ Buffer.from([4]),
884
+ Buffer.from(jwk.x, "base64url"),
885
+ Buffer.from(jwk.y, "base64url")
886
+ ]).toString("base64");
887
+ }
888
+ async function answerRecipientKeyChallenge(privateKeyPkcs8Base64, envelopeBase64) {
889
+ const payload = await decryptTo(
890
+ await importPrivateKey(privateKeyPkcs8Base64),
891
+ envelopeBase64
892
+ );
893
+ const nonce = payload?.nonce;
894
+ if (typeof nonce !== "string" || nonce.length === 0)
895
+ throw new Error("The challenge envelope carries no nonce");
896
+ return nonce;
897
+ }
653
898
  // Annotate the CommonJS export names for ESM import in node:
654
899
  0 && (module.exports = {
655
900
  CONNECT_RELAY_FIELDS,
656
901
  OAuthError,
657
902
  OpenBankingClient,
903
+ PARTNER_KEY_MISSING_DESCRIPTION,
904
+ PARTNER_SUSPENDED_DESCRIPTION,
658
905
  RelayError,
906
+ SyncError,
907
+ answerRecipientKeyChallenge,
659
908
  buildAuthorizeUrl,
660
909
  bundleFromToken,
910
+ closeReplacedConsents,
661
911
  createPkce,
662
912
  createState,
663
913
  decryptEnvelope,
664
914
  decryptTo,
665
915
  discover,
666
916
  exchangeCode,
917
+ generateRecipientKeyPair,
667
918
  importPrivateKey,
668
919
  parseRelay,
669
920
  pkceChallenge,
921
+ psuHeaders,
922
+ recipientKeyFingerprint,
923
+ recipientPublicKey,
670
924
  revokeToken,
671
925
  userinfo
672
926
  });