@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 +104 -17
- package/dist/index.cjs +279 -25
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +149 -4
- package/dist/index.d.ts +149 -4
- package/dist/index.js +270 -25
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -70,14 +70,50 @@ interface Connection {
|
|
|
70
70
|
accountCount: number;
|
|
71
71
|
lastSyncedAt: string | null;
|
|
72
72
|
psuType: string | null;
|
|
73
|
+
/** Whether the consent still works, by the service's clock. `status` stays `Active` after `validUntil`. */
|
|
74
|
+
isLive: boolean;
|
|
75
|
+
/** The accounts this connection holds. */
|
|
76
|
+
accountIds: string[];
|
|
73
77
|
}
|
|
74
78
|
interface SyncResult {
|
|
75
79
|
newTransactions: number;
|
|
76
80
|
totalFetched: number;
|
|
77
81
|
}
|
|
82
|
+
/**
|
|
83
|
+
* The stable reason a sync failed. Branch on this, never on the HTTP status.
|
|
84
|
+
* A reason added later arrives as its raw string.
|
|
85
|
+
*/
|
|
86
|
+
type SyncFailureReason = "reconnect_needed" | "consent_withdrawn" | "uid_outdated" | "psu_present_required" | "rate_limited" | "bank_error" | "transient" | "partner_app_inactive" | (string & {});
|
|
87
|
+
interface SyncFailure {
|
|
88
|
+
accountId: string;
|
|
89
|
+
reason: SyncFailureReason;
|
|
90
|
+
bankErrorCode: string | null;
|
|
91
|
+
}
|
|
78
92
|
interface SyncAllResult {
|
|
79
93
|
accounts: number;
|
|
80
94
|
newTransactions: number;
|
|
95
|
+
/** The accounts that did not sync, and why. */
|
|
96
|
+
failures: SyncFailure[];
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* The account holder's own request, forwarded while they are on your page: some banks only share
|
|
100
|
+
* data with the person present. Never send it from a background job. The service honours it only
|
|
101
|
+
* from a key a Connect client issued, and only with a public IP address and a user agent — behind a
|
|
102
|
+
* proxy, take the address from the header your proxy sets. Without both, nothing is sent.
|
|
103
|
+
*/
|
|
104
|
+
interface PsuHeaders {
|
|
105
|
+
/** The user's public IP address. */
|
|
106
|
+
ipAddress: string;
|
|
107
|
+
userAgent: string;
|
|
108
|
+
referer?: string;
|
|
109
|
+
accept?: string;
|
|
110
|
+
acceptLanguage?: string;
|
|
111
|
+
acceptCharset?: string;
|
|
112
|
+
acceptEncoding?: string;
|
|
113
|
+
}
|
|
114
|
+
interface SyncOptions {
|
|
115
|
+
/** The present user's request details; see {@link PsuHeaders}. */
|
|
116
|
+
psu?: PsuHeaders;
|
|
81
117
|
}
|
|
82
118
|
/** Options for {@link OpenBankingClient.getTransactions}. */
|
|
83
119
|
interface TransactionQuery {
|
|
@@ -164,6 +200,11 @@ interface AuthorizeUrlOptions {
|
|
|
164
200
|
challenge?: "pin_code";
|
|
165
201
|
/** Space-separated locales; the first one the server publishes forces the language of every screen. */
|
|
166
202
|
uiLocales?: string;
|
|
203
|
+
/**
|
|
204
|
+
* A connection's `sessionId` to renew: the user goes straight to that bank, whether its consent
|
|
205
|
+
* is still live or has lapsed.
|
|
206
|
+
*/
|
|
207
|
+
renewConnection?: string;
|
|
167
208
|
}
|
|
168
209
|
/** The `/oauth/authorize` URL for a top-level browser navigation. */
|
|
169
210
|
declare function buildAuthorizeUrl(options: AuthorizeUrlOptions): string;
|
|
@@ -178,6 +219,15 @@ interface ConnectRelay {
|
|
|
178
219
|
publicKey: string;
|
|
179
220
|
}
|
|
180
221
|
type RelayErrorCode = "access_denied" | "oauth_error" | "state_mismatch" | "issuer_mismatch" | "missing_code" | "missing_private_key";
|
|
222
|
+
/** The `error_description` the server relays when the partner has not installed its decryption key. */
|
|
223
|
+
declare const PARTNER_KEY_MISSING_DESCRIPTION = "this partner has not installed its decryption key; no authorizations can be started until it does";
|
|
224
|
+
/** The `error_description` the server relays while the partner is suspended. */
|
|
225
|
+
declare const PARTNER_SUSPENDED_DESCRIPTION = "this partner is suspended; no authorizations can be started";
|
|
226
|
+
/**
|
|
227
|
+
* Why a `temporarily_unavailable` was relayed, when the server said so in the pinned words. Both
|
|
228
|
+
* are on your side, not the bank's: install the key on your partner page, or write to us.
|
|
229
|
+
*/
|
|
230
|
+
type RelayRefusalReason = "partner_key_missing" | "partner_suspended";
|
|
181
231
|
/**
|
|
182
232
|
* Thrown by {@link parseRelay}. `code` says why: `access_denied` is the user pressing "Back to the
|
|
183
233
|
* partner" or declining (a normal outcome), `oauth_error` any other error the server relayed (the
|
|
@@ -187,6 +237,8 @@ declare class RelayError extends Error {
|
|
|
187
237
|
readonly code: RelayErrorCode;
|
|
188
238
|
readonly error?: string;
|
|
189
239
|
readonly errorDescription?: string;
|
|
240
|
+
/** Set on an `oauth_error` whose description names a partner-side refusal. */
|
|
241
|
+
readonly reason?: RelayRefusalReason;
|
|
190
242
|
constructor(code: RelayErrorCode, message: string, oauth?: {
|
|
191
243
|
error: string;
|
|
192
244
|
errorDescription?: string;
|
|
@@ -199,6 +251,12 @@ interface ParseRelayOptions {
|
|
|
199
251
|
issuer?: string;
|
|
200
252
|
/** Require `iss` to be present even when `issuer` is not checked. Default: only when `issuer` is set. */
|
|
201
253
|
requireIss?: boolean;
|
|
254
|
+
/**
|
|
255
|
+
* Whether the relay must carry the user's private key. A partner that installed its own
|
|
256
|
+
* decryption key receives `privateKey=""` for every user who connected under it and decrypts
|
|
257
|
+
* with that key instead — pass `"optional"`. Default `"required"`, the 1.1.0 behaviour.
|
|
258
|
+
*/
|
|
259
|
+
expectPrivateKey?: "required" | "optional";
|
|
202
260
|
}
|
|
203
261
|
/** A form body, `URLSearchParams`, parsed body object, or JSON string. */
|
|
204
262
|
type RelayInput = string | URLSearchParams | FormData | Record<string, unknown>;
|
|
@@ -251,6 +309,14 @@ interface RevokeTokenOptions extends HttpOptions {
|
|
|
251
309
|
clientSecret: string;
|
|
252
310
|
/** The key to revoke. Only keys issued to this client are touched; an unknown key still succeeds. */
|
|
253
311
|
token: string;
|
|
312
|
+
/**
|
|
313
|
+
* Bank consents to close in the same call, with the decrypted Enable Banking session id of each.
|
|
314
|
+
* Validated before the key is revoked: a refusal leaves the key alive.
|
|
315
|
+
*/
|
|
316
|
+
closeConsents?: {
|
|
317
|
+
connectionId: string;
|
|
318
|
+
ebSessionId: string;
|
|
319
|
+
}[];
|
|
254
320
|
}
|
|
255
321
|
/** RFC 7009 revocation. Resolves on 200; throws {@link OAuthError} on a client-authentication failure. */
|
|
256
322
|
declare function revokeToken(options: RevokeTokenOptions): Promise<void>;
|
|
@@ -293,6 +359,10 @@ interface ServerMetadata {
|
|
|
293
359
|
response_mode: string;
|
|
294
360
|
fields: string[];
|
|
295
361
|
};
|
|
362
|
+
/** The server accepts a partner-held decryption key (always true on current servers). */
|
|
363
|
+
recipient_key_supported?: boolean;
|
|
364
|
+
/** Every partner must hold one before it can register a client or start an authorization. */
|
|
365
|
+
recipient_key_required?: boolean;
|
|
296
366
|
documentation: string;
|
|
297
367
|
};
|
|
298
368
|
}
|
|
@@ -338,17 +408,66 @@ declare class OpenBankingClient {
|
|
|
338
408
|
/**
|
|
339
409
|
* Triggers an online sync of one account: decrypts that account's Enable Banking uid and posts
|
|
340
410
|
* it, so the service can fetch fresh data without ever holding the uid in plaintext.
|
|
411
|
+
*
|
|
412
|
+
* A refusal throws {@link SyncError}. A uid a renewal replaced (`uid_outdated`) is re-read and
|
|
413
|
+
* retried once.
|
|
414
|
+
*/
|
|
415
|
+
sync(accountId: string, options?: SyncOptions): Promise<SyncResult>;
|
|
416
|
+
/**
|
|
417
|
+
* Triggers an online sync of every account that has an active session. Per-account refusals are
|
|
418
|
+
* in `failures`, and so is every account whose consent needs renewing (`reconnect_needed`, never
|
|
419
|
+
* sent); accounts answering `uid_outdated` are re-read and retried once.
|
|
341
420
|
*/
|
|
342
|
-
|
|
343
|
-
/** Triggers an online sync of every account that has an active session. */
|
|
344
|
-
syncAll(): Promise<SyncAllResult>;
|
|
421
|
+
syncAll(options?: SyncOptions): Promise<SyncAllResult>;
|
|
345
422
|
private getAccountWires;
|
|
423
|
+
private syncItems;
|
|
424
|
+
private postSyncAll;
|
|
346
425
|
private decryptUid;
|
|
347
426
|
private mapAccount;
|
|
348
427
|
private mapTransaction;
|
|
349
428
|
private getJson;
|
|
350
429
|
private postJson;
|
|
351
430
|
}
|
|
431
|
+
/** The `X-Psu-*` request headers for a forwarded {@link PsuHeaders}; empty when none is given. */
|
|
432
|
+
declare function psuHeaders(psu: PsuHeaders | undefined): Record<string, string>;
|
|
433
|
+
|
|
434
|
+
/** A sync the service refused. `reason` is the stable code to branch on. */
|
|
435
|
+
declare class SyncError extends Error {
|
|
436
|
+
readonly status: number;
|
|
437
|
+
readonly reason: SyncFailureReason | null;
|
|
438
|
+
readonly bankErrorCode: string | null;
|
|
439
|
+
readonly retryAfterSeconds: number | null;
|
|
440
|
+
constructor(message: string, status: number, reason: SyncFailureReason | null, bankErrorCode?: string | null, retryAfterSeconds?: number | null);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
interface CloseReplacedConsentsOptions extends HttpOptions {
|
|
444
|
+
issuer: string;
|
|
445
|
+
clientId: string;
|
|
446
|
+
clientSecret: string;
|
|
447
|
+
/** The PREVIOUS key — the one issued before the renewal. It is revoked by this call. */
|
|
448
|
+
token: string;
|
|
449
|
+
/** The base64 PKCS#8 private key the consents are sealed to. */
|
|
450
|
+
privateKey: string;
|
|
451
|
+
/** Defaults to the issuer. */
|
|
452
|
+
apiBaseUrl?: string;
|
|
453
|
+
}
|
|
454
|
+
interface CloseReplacedConsentsResult {
|
|
455
|
+
/** Consents sent to be closed at the bank. */
|
|
456
|
+
closed: number;
|
|
457
|
+
/** Consents listed but not closable (no envelope, or it would not decrypt). */
|
|
458
|
+
failed: number;
|
|
459
|
+
/** Whether the previous key is gone. When false, revoke it yourself. */
|
|
460
|
+
revoked: boolean;
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* After a renewal: closes, at the bank, the consents the previous key still has open, and revokes
|
|
464
|
+
* that key in the same call. Reads `GET /api/connections/open-consents` only — never the live
|
|
465
|
+
* connections, which by now hold the renewal. A key that is already gone, or was issued to another
|
|
466
|
+
* client, closes nothing: the service answers such a revoke with 200 without closing anything. A
|
|
467
|
+
* failure that retrying may clear (5xx, 429) throws, so the key survives for a retry: revoking it
|
|
468
|
+
* without the close would leave the consents open with nothing left that can list them.
|
|
469
|
+
*/
|
|
470
|
+
declare function closeReplacedConsents(options: CloseReplacedConsentsOptions): Promise<CloseReplacedConsentsResult>;
|
|
352
471
|
|
|
353
472
|
/** Re-export the WebCrypto key type so callers don't depend on the DOM lib. */
|
|
354
473
|
type CryptoKey = webcrypto.CryptoKey;
|
|
@@ -364,4 +483,30 @@ declare function decryptTo<T>(privateKey: CryptoKey, envelopeBase64: string | nu
|
|
|
364
483
|
/** Imports a base64 PKCS#8 P-256 ECDH private key for use with {@link decryptEnvelope}. */
|
|
365
484
|
declare function importPrivateKey(pkcs8Base64: string): Promise<CryptoKey>;
|
|
366
485
|
|
|
367
|
-
|
|
486
|
+
/** A partner's recipient (decryption) key pair. The private half is a credential: never log it. */
|
|
487
|
+
interface RecipientKeyPair {
|
|
488
|
+
/** Base64 PKCS#8 — what your deployment loads. */
|
|
489
|
+
privateKeyPkcs8Base64: string;
|
|
490
|
+
/** Base64 raw 65-byte uncompressed P-256 point — what you install on your partner page. */
|
|
491
|
+
publicKeyRawBase64: string;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Generates the P-256 pair a partner installs on open-banking.io. The public half goes into
|
|
495
|
+
* `PUT /api/partner/recipient-key` (or the partner page's paste box); keep the private half
|
|
496
|
+
* where your deployment can read it — the service never sees it and cannot recover it.
|
|
497
|
+
*/
|
|
498
|
+
declare function generateRecipientKeyPair(): Promise<RecipientKeyPair>;
|
|
499
|
+
/**
|
|
500
|
+
* The fingerprint the partner page and the admin show for a key: SHA-256 of the raw 65-byte
|
|
501
|
+
* point, lowercase hex, first 16 characters. Print it at boot and compare after every deploy.
|
|
502
|
+
*/
|
|
503
|
+
declare function recipientKeyFingerprint(publicKeyRawBase64: string): string;
|
|
504
|
+
/** The raw public point of a PKCS#8 private key — to fingerprint or re-install the key you hold. */
|
|
505
|
+
declare function recipientPublicKey(privateKeyPkcs8Base64: string): Promise<string>;
|
|
506
|
+
/**
|
|
507
|
+
* Answers the possession challenge from `POST /api/partner/recipient-key/challenge`: opens
|
|
508
|
+
* the envelope with the private half and returns the nonce — the `challengeAnswer` for the install.
|
|
509
|
+
*/
|
|
510
|
+
declare function answerRecipientKeyChallenge(privateKeyPkcs8Base64: string, envelopeBase64: string): Promise<string>;
|
|
511
|
+
|
|
512
|
+
export { type Account, type AuthorizeUrlOptions, type Balance, CONNECT_RELAY_FIELDS, type CloseReplacedConsentsOptions, type CloseReplacedConsentsResult, 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 PsuHeaders, type RecipientKeyPair, RelayError, type RelayErrorCode, type RelayInput, type RelayRefusalReason, type RevokeTokenOptions, type ServerMetadata, type SyncAllResult, SyncError, type SyncFailure, type SyncFailureReason, type SyncOptions, type SyncResult, type TokenResponse, type Transaction, type TransactionPage, type TransactionQuery, type Userinfo, type UserinfoOptions, answerRecipientKeyChallenge, buildAuthorizeUrl, bundleFromToken, closeReplacedConsents, createPkce, createState, decryptEnvelope, decryptTo, discover, exchangeCode, generateRecipientKeyPair, importPrivateKey, parseRelay, pkceChallenge, psuHeaders, 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.
|
|
7
|
+
version: "1.3.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",
|
|
@@ -93,18 +93,30 @@ function buildAuthorizeUrl(options) {
|
|
|
93
93
|
if (options.loginHint) params.set("login_hint", options.loginHint);
|
|
94
94
|
if (options.challenge) params.set("challenge", options.challenge);
|
|
95
95
|
if (options.uiLocales) params.set("ui_locales", options.uiLocales);
|
|
96
|
+
if (options.renewConnection) params.set("renew_connection", options.renewConnection);
|
|
96
97
|
return `${endpoint(options.issuer, "/oauth/authorize")}?${params.toString()}`;
|
|
97
98
|
}
|
|
99
|
+
var PARTNER_KEY_MISSING_DESCRIPTION = "this partner has not installed its decryption key; no authorizations can be started until it does";
|
|
100
|
+
var PARTNER_SUSPENDED_DESCRIPTION = "this partner is suspended; no authorizations can be started";
|
|
101
|
+
function refusalReason(error, description) {
|
|
102
|
+
if (error !== "temporarily_unavailable") return void 0;
|
|
103
|
+
if (description === PARTNER_KEY_MISSING_DESCRIPTION) return "partner_key_missing";
|
|
104
|
+
if (description === PARTNER_SUSPENDED_DESCRIPTION) return "partner_suspended";
|
|
105
|
+
return void 0;
|
|
106
|
+
}
|
|
98
107
|
var RelayError = class extends Error {
|
|
99
108
|
code;
|
|
100
109
|
error;
|
|
101
110
|
errorDescription;
|
|
111
|
+
/** Set on an `oauth_error` whose description names a partner-side refusal. */
|
|
112
|
+
reason;
|
|
102
113
|
constructor(code, message, oauth) {
|
|
103
114
|
super(message);
|
|
104
115
|
this.name = "RelayError";
|
|
105
116
|
this.code = code;
|
|
106
117
|
this.error = oauth?.error;
|
|
107
118
|
this.errorDescription = oauth?.errorDescription;
|
|
119
|
+
this.reason = oauth ? refusalReason(oauth.error, oauth.errorDescription ?? "") : void 0;
|
|
108
120
|
}
|
|
109
121
|
};
|
|
110
122
|
function parseRelay(input, options) {
|
|
@@ -137,7 +149,9 @@ function parseRelay(input, options) {
|
|
|
137
149
|
const code = read("code");
|
|
138
150
|
if (!code) throw new RelayError("missing_code", "The relay carries no authorization code");
|
|
139
151
|
const privateKey = read("privateKey");
|
|
140
|
-
if (!privateKey
|
|
152
|
+
if (!privateKey && (options.expectPrivateKey ?? "required") === "required") {
|
|
153
|
+
throw new RelayError("missing_private_key", "The relay carries no private key");
|
|
154
|
+
}
|
|
141
155
|
return { code, state: read("state"), iss, privateKey, publicKey: read("publicKey") };
|
|
142
156
|
}
|
|
143
157
|
var OAuthError = class extends Error {
|
|
@@ -189,6 +203,10 @@ async function exchangeCode(options) {
|
|
|
189
203
|
}
|
|
190
204
|
async function revokeToken(options) {
|
|
191
205
|
const body = new URLSearchParams({ token: options.token, token_type_hint: "access_token" });
|
|
206
|
+
for (const c of options.closeConsents ?? []) {
|
|
207
|
+
body.append("connection_id", c.connectionId);
|
|
208
|
+
body.append("eb_session_id", c.ebSessionId);
|
|
209
|
+
}
|
|
192
210
|
const response = await post(
|
|
193
211
|
endpoint(options.issuer, "/oauth/revoke"),
|
|
194
212
|
body,
|
|
@@ -396,6 +414,22 @@ function base64ToBytes(b64) {
|
|
|
396
414
|
return new Uint8Array(Buffer.from(b64, "base64"));
|
|
397
415
|
}
|
|
398
416
|
|
|
417
|
+
// src/errors.ts
|
|
418
|
+
var SyncError = class extends Error {
|
|
419
|
+
status;
|
|
420
|
+
reason;
|
|
421
|
+
bankErrorCode;
|
|
422
|
+
retryAfterSeconds;
|
|
423
|
+
constructor(message, status, reason, bankErrorCode = null, retryAfterSeconds = null) {
|
|
424
|
+
super(message);
|
|
425
|
+
this.name = "SyncError";
|
|
426
|
+
this.status = status;
|
|
427
|
+
this.reason = reason;
|
|
428
|
+
this.bankErrorCode = bankErrorCode;
|
|
429
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
|
|
399
433
|
// src/client.ts
|
|
400
434
|
var OpenBankingClient = class _OpenBankingClient {
|
|
401
435
|
/** Default per-request timeout (30s) when {@link OpenBankingClientOptions.timeoutMs} is unset. */
|
|
@@ -480,41 +514,102 @@ var OpenBankingClient = class _OpenBankingClient {
|
|
|
480
514
|
status: c.status,
|
|
481
515
|
accountCount: c.accountCount,
|
|
482
516
|
lastSyncedAt: c.lastSyncedAt ?? null,
|
|
483
|
-
psuType: c.psuType ?? null
|
|
517
|
+
psuType: c.psuType ?? null,
|
|
518
|
+
isLive: c.isLive ?? (c.status === "Active" && Date.parse(c.validUntil) > Date.now()),
|
|
519
|
+
accountIds: c.accountIds ?? []
|
|
484
520
|
}));
|
|
485
521
|
}
|
|
486
522
|
/**
|
|
487
523
|
* Triggers an online sync of one account: decrypts that account's Enable Banking uid and posts
|
|
488
524
|
* it, so the service can fetch fresh data without ever holding the uid in plaintext.
|
|
525
|
+
*
|
|
526
|
+
* A refusal throws {@link SyncError}. A uid a renewal replaced (`uid_outdated`) is re-read and
|
|
527
|
+
* retried once.
|
|
489
528
|
*/
|
|
490
|
-
async sync(accountId) {
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
529
|
+
async sync(accountId, options = {}) {
|
|
530
|
+
for (let attempt = 0; ; attempt++) {
|
|
531
|
+
const wires = await this.getAccountWires();
|
|
532
|
+
const account = wires.find((a) => a.id === accountId);
|
|
533
|
+
if (!account) throw new Error(`Account ${accountId} not found`);
|
|
534
|
+
const uid = account.needsReconnect ? null : await this.decryptUid(account);
|
|
535
|
+
if (uid == null) {
|
|
536
|
+
throw new SyncError(
|
|
537
|
+
"Account has no active session (reconnect required) \u2014 cannot sync",
|
|
538
|
+
409,
|
|
539
|
+
"reconnect_needed"
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
try {
|
|
543
|
+
const result = await this.postJson(
|
|
544
|
+
`/api/accounts/${encodeURIComponent(accountId)}/sync`,
|
|
545
|
+
{ uid },
|
|
546
|
+
psuHeaders(options.psu)
|
|
547
|
+
);
|
|
548
|
+
return { newTransactions: result.newTransactions, totalFetched: result.totalFetched };
|
|
549
|
+
} catch (e) {
|
|
550
|
+
if (attempt === 0 && e instanceof SyncError && e.reason === "uid_outdated") continue;
|
|
551
|
+
throw e;
|
|
552
|
+
}
|
|
497
553
|
}
|
|
498
|
-
const result = await this.postJson(
|
|
499
|
-
`/api/accounts/${encodeURIComponent(accountId)}/sync`,
|
|
500
|
-
{ uid }
|
|
501
|
-
);
|
|
502
|
-
return { newTransactions: result.newTransactions, totalFetched: result.totalFetched };
|
|
503
554
|
}
|
|
504
|
-
/**
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
555
|
+
/**
|
|
556
|
+
* Triggers an online sync of every account that has an active session. Per-account refusals are
|
|
557
|
+
* in `failures`, and so is every account whose consent needs renewing (`reconnect_needed`, never
|
|
558
|
+
* sent); accounts answering `uid_outdated` are re-read and retried once.
|
|
559
|
+
*/
|
|
560
|
+
async syncAll(options = {}) {
|
|
561
|
+
const read = await this.syncItems();
|
|
562
|
+
const first = await this.postSyncAll(read.items, options);
|
|
563
|
+
first.failures.push(...read.lapsed);
|
|
564
|
+
const outdated = new Set(
|
|
565
|
+
first.failures.filter((f) => f.reason === "uid_outdated").map((f) => f.accountId)
|
|
509
566
|
);
|
|
510
|
-
|
|
511
|
-
const
|
|
512
|
-
|
|
567
|
+
if (outdated.size === 0) return first;
|
|
568
|
+
const reread = await this.syncItems();
|
|
569
|
+
const retryItems = reread.items.filter((i) => outdated.has(i.accountId));
|
|
570
|
+
const lapsedNow = reread.lapsed.filter((f) => outdated.has(f.accountId));
|
|
571
|
+
const settled = new Set([...retryItems, ...lapsedNow].map((i) => i.accountId));
|
|
572
|
+
const kept = first.failures.filter((f) => !settled.has(f.accountId));
|
|
573
|
+
if (retryItems.length === 0) return { ...first, failures: [...kept, ...lapsedNow] };
|
|
574
|
+
const second = await this.postSyncAll(retryItems, options);
|
|
575
|
+
return {
|
|
576
|
+
accounts: first.accounts + second.accounts,
|
|
577
|
+
newTransactions: first.newTransactions + second.newTransactions,
|
|
578
|
+
failures: [...kept, ...lapsedNow, ...second.failures]
|
|
579
|
+
};
|
|
513
580
|
}
|
|
514
581
|
// ---- internals ---------------------------------------------------------------------------------
|
|
515
582
|
getAccountWires() {
|
|
516
583
|
return this.getJson("/api/accounts");
|
|
517
584
|
}
|
|
585
|
+
async syncItems() {
|
|
586
|
+
const wires = await this.getAccountWires();
|
|
587
|
+
const decrypted = await Promise.all(
|
|
588
|
+
wires.map(async (a) => ({
|
|
589
|
+
accountId: a.id,
|
|
590
|
+
needsReconnect: a.needsReconnect,
|
|
591
|
+
uid: a.needsReconnect ? null : await this.decryptUid(a)
|
|
592
|
+
}))
|
|
593
|
+
);
|
|
594
|
+
return {
|
|
595
|
+
items: decrypted.filter((x) => x.uid != null).map((x) => ({ accountId: x.accountId, uid: x.uid })),
|
|
596
|
+
lapsed: decrypted.filter((x) => x.uid == null && x.needsReconnect).map((x) => ({ accountId: x.accountId, reason: "reconnect_needed", bankErrorCode: null }))
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
async postSyncAll(items, options) {
|
|
600
|
+
if (items.length === 0) return { accounts: 0, newTransactions: 0, failures: [] };
|
|
601
|
+
const result = await this.postJson(
|
|
602
|
+
"/api/sync",
|
|
603
|
+
{ items },
|
|
604
|
+
psuHeaders(options.psu)
|
|
605
|
+
);
|
|
606
|
+
const failures = (result.failures ?? []).map((f) => ({
|
|
607
|
+
accountId: f.accountId,
|
|
608
|
+
reason: f.reason,
|
|
609
|
+
bankErrorCode: f.bankErrorCode ?? null
|
|
610
|
+
}));
|
|
611
|
+
return { accounts: result.accounts, newTransactions: result.newTransactions, failures };
|
|
612
|
+
}
|
|
518
613
|
async decryptUid(a) {
|
|
519
614
|
const dec = await decryptTo(await this.privateKey, a.uidEnc);
|
|
520
615
|
return dec?.uid ?? null;
|
|
@@ -591,10 +686,11 @@ var OpenBankingClient = class _OpenBankingClient {
|
|
|
591
686
|
}
|
|
592
687
|
return await res.json();
|
|
593
688
|
}
|
|
594
|
-
async postJson(path, body) {
|
|
689
|
+
async postJson(path, body, extraHeaders = {}) {
|
|
595
690
|
const res = await this.fetchImpl(this.baseUrl + path, {
|
|
596
691
|
method: "POST",
|
|
597
692
|
headers: {
|
|
693
|
+
...extraHeaders,
|
|
598
694
|
"X-Api-Key": this.apiKey,
|
|
599
695
|
"Content-Type": "application/json",
|
|
600
696
|
"User-Agent": USER_AGENT
|
|
@@ -603,27 +699,176 @@ var OpenBankingClient = class _OpenBankingClient {
|
|
|
603
699
|
signal: AbortSignal.timeout(this.timeoutMs)
|
|
604
700
|
});
|
|
605
701
|
if (!res.ok) {
|
|
606
|
-
|
|
702
|
+
const problem = await readProblem(res);
|
|
703
|
+
const retryAfter = Number.parseInt(res.headers.get("Retry-After") ?? "", 10);
|
|
704
|
+
throw new SyncError(
|
|
705
|
+
`POST ${path} failed: ${res.status} ${problem.reason ?? res.statusText}`,
|
|
706
|
+
res.status,
|
|
707
|
+
problem.reason,
|
|
708
|
+
problem.bankErrorCode,
|
|
709
|
+
Number.isFinite(retryAfter) ? retryAfter : null
|
|
710
|
+
);
|
|
607
711
|
}
|
|
608
712
|
return await res.json();
|
|
609
713
|
}
|
|
610
714
|
};
|
|
715
|
+
async function readProblem(res) {
|
|
716
|
+
try {
|
|
717
|
+
const body = await res.json();
|
|
718
|
+
return {
|
|
719
|
+
reason: typeof body.reason === "string" ? body.reason : null,
|
|
720
|
+
bankErrorCode: typeof body.bankErrorCode === "string" ? body.bankErrorCode : null
|
|
721
|
+
};
|
|
722
|
+
} catch {
|
|
723
|
+
return { reason: null, bankErrorCode: null };
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
function psuHeaders(psu) {
|
|
727
|
+
if (!psu?.ipAddress || !psu.userAgent) return {};
|
|
728
|
+
const headers = {
|
|
729
|
+
"X-Psu-Ip-Address": psu.ipAddress,
|
|
730
|
+
"X-Psu-User-Agent": psu.userAgent
|
|
731
|
+
};
|
|
732
|
+
const optional = [
|
|
733
|
+
["X-Psu-Referer", psu.referer],
|
|
734
|
+
["X-Psu-Accept", psu.accept],
|
|
735
|
+
["X-Psu-Accept-Language", psu.acceptLanguage],
|
|
736
|
+
["X-Psu-Accept-Charset", psu.acceptCharset],
|
|
737
|
+
["X-Psu-Accept-Encoding", psu.acceptEncoding]
|
|
738
|
+
];
|
|
739
|
+
for (const [name, value] of optional) if (value) headers[name] = value;
|
|
740
|
+
return headers;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// src/consents.ts
|
|
744
|
+
async function closeReplacedConsents(options) {
|
|
745
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
746
|
+
const base = trimSlash2(options.apiBaseUrl ?? options.issuer);
|
|
747
|
+
const nothing = { closed: 0, failed: 0, revoked: false };
|
|
748
|
+
let owner;
|
|
749
|
+
try {
|
|
750
|
+
owner = (await userinfo({ ...options, accessToken: options.token })).clientId;
|
|
751
|
+
} catch (e) {
|
|
752
|
+
if (e instanceof OAuthError && keyRefused(e.status)) return nothing;
|
|
753
|
+
throw e;
|
|
754
|
+
}
|
|
755
|
+
if (owner !== options.clientId) return nothing;
|
|
756
|
+
const res = await fetchImpl(`${base}/api/connections/open-consents`, {
|
|
757
|
+
headers: { "X-Api-Key": options.token, "User-Agent": USER_AGENT },
|
|
758
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? 3e4)
|
|
759
|
+
});
|
|
760
|
+
if (keyRefused(res.status)) return nothing;
|
|
761
|
+
if (!res.ok) throw new Error(`GET /api/connections/open-consents failed: ${res.status}`);
|
|
762
|
+
const open = await res.json();
|
|
763
|
+
const key = await importPrivateKey(options.privateKey);
|
|
764
|
+
const closeConsents = [];
|
|
765
|
+
const seen = /* @__PURE__ */ new Set();
|
|
766
|
+
let failed = 0;
|
|
767
|
+
for (const c of open) {
|
|
768
|
+
if (!c.connectionId || seen.has(c.connectionId)) continue;
|
|
769
|
+
seen.add(c.connectionId);
|
|
770
|
+
if (!c.sessionIdEnc) {
|
|
771
|
+
failed += 1;
|
|
772
|
+
continue;
|
|
773
|
+
}
|
|
774
|
+
let sessionId;
|
|
775
|
+
try {
|
|
776
|
+
sessionId = (await decryptTo(key, c.sessionIdEnc))?.sessionId;
|
|
777
|
+
} catch {
|
|
778
|
+
sessionId = null;
|
|
779
|
+
}
|
|
780
|
+
if (!sessionId) {
|
|
781
|
+
failed += 1;
|
|
782
|
+
continue;
|
|
783
|
+
}
|
|
784
|
+
closeConsents.push({ connectionId: c.connectionId, ebSessionId: sessionId });
|
|
785
|
+
}
|
|
786
|
+
try {
|
|
787
|
+
await revokeToken({ ...options, closeConsents });
|
|
788
|
+
} catch (e) {
|
|
789
|
+
if (e instanceof OAuthError && e.status < 500 && e.status !== 429)
|
|
790
|
+
return { closed: 0, failed: failed + closeConsents.length, revoked: false };
|
|
791
|
+
throw e;
|
|
792
|
+
}
|
|
793
|
+
return { closed: closeConsents.length, failed, revoked: true };
|
|
794
|
+
}
|
|
795
|
+
var keyRefused = (status) => status === 401 || status === 403;
|
|
796
|
+
function trimSlash2(url) {
|
|
797
|
+
let end = url.length;
|
|
798
|
+
while (end > 0 && url.charCodeAt(end - 1) === 47) end--;
|
|
799
|
+
return url.slice(0, end);
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
// src/recipientKey.ts
|
|
803
|
+
import { createHash as createHash2, webcrypto as webcrypto2 } from "crypto";
|
|
804
|
+
var subtle2 = webcrypto2.subtle;
|
|
805
|
+
async function generateRecipientKeyPair() {
|
|
806
|
+
const pair = await subtle2.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, [
|
|
807
|
+
"deriveBits"
|
|
808
|
+
]);
|
|
809
|
+
return {
|
|
810
|
+
privateKeyPkcs8Base64: Buffer.from(await subtle2.exportKey("pkcs8", pair.privateKey)).toString(
|
|
811
|
+
"base64"
|
|
812
|
+
),
|
|
813
|
+
publicKeyRawBase64: Buffer.from(await subtle2.exportKey("raw", pair.publicKey)).toString(
|
|
814
|
+
"base64"
|
|
815
|
+
)
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
function recipientKeyFingerprint(publicKeyRawBase64) {
|
|
819
|
+
return createHash2("sha256").update(Buffer.from(publicKeyRawBase64, "base64")).digest("hex").slice(0, 16);
|
|
820
|
+
}
|
|
821
|
+
async function recipientPublicKey(privateKeyPkcs8Base64) {
|
|
822
|
+
const key = await subtle2.importKey(
|
|
823
|
+
"pkcs8",
|
|
824
|
+
Buffer.from(privateKeyPkcs8Base64, "base64"),
|
|
825
|
+
{ name: "ECDH", namedCurve: "P-256" },
|
|
826
|
+
true,
|
|
827
|
+
["deriveBits"]
|
|
828
|
+
);
|
|
829
|
+
const jwk = await subtle2.exportKey("jwk", key);
|
|
830
|
+
if (!jwk.x || !jwk.y) throw new Error("The private key carries no public point");
|
|
831
|
+
return Buffer.concat([
|
|
832
|
+
Buffer.from([4]),
|
|
833
|
+
Buffer.from(jwk.x, "base64url"),
|
|
834
|
+
Buffer.from(jwk.y, "base64url")
|
|
835
|
+
]).toString("base64");
|
|
836
|
+
}
|
|
837
|
+
async function answerRecipientKeyChallenge(privateKeyPkcs8Base64, envelopeBase64) {
|
|
838
|
+
const payload = await decryptTo(
|
|
839
|
+
await importPrivateKey(privateKeyPkcs8Base64),
|
|
840
|
+
envelopeBase64
|
|
841
|
+
);
|
|
842
|
+
const nonce = payload?.nonce;
|
|
843
|
+
if (typeof nonce !== "string" || nonce.length === 0)
|
|
844
|
+
throw new Error("The challenge envelope carries no nonce");
|
|
845
|
+
return nonce;
|
|
846
|
+
}
|
|
611
847
|
export {
|
|
612
848
|
CONNECT_RELAY_FIELDS,
|
|
613
849
|
OAuthError,
|
|
614
850
|
OpenBankingClient,
|
|
851
|
+
PARTNER_KEY_MISSING_DESCRIPTION,
|
|
852
|
+
PARTNER_SUSPENDED_DESCRIPTION,
|
|
615
853
|
RelayError,
|
|
854
|
+
SyncError,
|
|
855
|
+
answerRecipientKeyChallenge,
|
|
616
856
|
buildAuthorizeUrl,
|
|
617
857
|
bundleFromToken,
|
|
858
|
+
closeReplacedConsents,
|
|
618
859
|
createPkce,
|
|
619
860
|
createState,
|
|
620
861
|
decryptEnvelope,
|
|
621
862
|
decryptTo,
|
|
622
863
|
discover,
|
|
623
864
|
exchangeCode,
|
|
865
|
+
generateRecipientKeyPair,
|
|
624
866
|
importPrivateKey,
|
|
625
867
|
parseRelay,
|
|
626
868
|
pkceChallenge,
|
|
869
|
+
psuHeaders,
|
|
870
|
+
recipientKeyFingerprint,
|
|
871
|
+
recipientPublicKey,
|
|
627
872
|
revokeToken,
|
|
628
873
|
userinfo
|
|
629
874
|
};
|