@coderoftime/fints 0.0.0-stage → 0.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.
Files changed (249) hide show
  1. package/CHANGELOG.md +152 -0
  2. package/LICENSE +28 -0
  3. package/README.md +246 -2
  4. package/dist/client.d.ts +48 -0
  5. package/dist/client.d.ts.map +1 -0
  6. package/dist/client.js +199 -0
  7. package/dist/client.js.map +1 -0
  8. package/dist/core/account.d.ts +168 -0
  9. package/dist/core/account.d.ts.map +1 -0
  10. package/dist/core/account.js +245 -0
  11. package/dist/core/account.js.map +1 -0
  12. package/dist/core/amount.d.ts +63 -0
  13. package/dist/core/amount.d.ts.map +1 -0
  14. package/dist/core/amount.js +192 -0
  15. package/dist/core/amount.js.map +1 -0
  16. package/dist/core/balance.d.ts +55 -0
  17. package/dist/core/balance.d.ts.map +1 -0
  18. package/dist/core/balance.js +54 -0
  19. package/dist/core/balance.js.map +1 -0
  20. package/dist/core/bank-info.d.ts +49 -0
  21. package/dist/core/bank-info.d.ts.map +1 -0
  22. package/dist/core/bank-info.js +52 -0
  23. package/dist/core/bank-info.js.map +1 -0
  24. package/dist/core/client.d.ts +161 -0
  25. package/dist/core/client.d.ts.map +1 -0
  26. package/dist/core/client.js +2 -0
  27. package/dist/core/client.js.map +1 -0
  28. package/dist/core/config.d.ts +80 -0
  29. package/dist/core/config.d.ts.map +1 -0
  30. package/dist/core/config.js +153 -0
  31. package/dist/core/config.js.map +1 -0
  32. package/dist/core/errors.d.ts +153 -0
  33. package/dist/core/errors.d.ts.map +1 -0
  34. package/dist/core/errors.js +247 -0
  35. package/dist/core/errors.js.map +1 -0
  36. package/dist/core/feedback.d.ts +72 -0
  37. package/dist/core/feedback.d.ts.map +1 -0
  38. package/dist/core/feedback.js +127 -0
  39. package/dist/core/feedback.js.map +1 -0
  40. package/dist/core/transaction.d.ts +103 -0
  41. package/dist/core/transaction.d.ts.map +1 -0
  42. package/dist/core/transaction.js +96 -0
  43. package/dist/core/transaction.js.map +1 -0
  44. package/dist/core/transport.d.ts +64 -0
  45. package/dist/core/transport.d.ts.map +1 -0
  46. package/dist/core/transport.js +149 -0
  47. package/dist/core/transport.js.map +1 -0
  48. package/dist/formats/camt.d.ts +32 -0
  49. package/dist/formats/camt.d.ts.map +1 -0
  50. package/dist/formats/camt.js +242 -0
  51. package/dist/formats/camt.js.map +1 -0
  52. package/dist/formats/mt940.d.ts +54 -0
  53. package/dist/formats/mt940.d.ts.map +1 -0
  54. package/dist/formats/mt940.js +376 -0
  55. package/dist/formats/mt940.js.map +1 -0
  56. package/dist/formats/readers.d.ts +15 -0
  57. package/dist/formats/readers.d.ts.map +1 -0
  58. package/dist/formats/readers.js +42 -0
  59. package/dist/formats/readers.js.map +1 -0
  60. package/dist/formats/record-budget.d.ts +7 -0
  61. package/dist/formats/record-budget.d.ts.map +1 -0
  62. package/dist/formats/record-budget.js +17 -0
  63. package/dist/formats/record-budget.js.map +1 -0
  64. package/dist/formats/sepa-purpose.d.ts +28 -0
  65. package/dist/formats/sepa-purpose.d.ts.map +1 -0
  66. package/dist/formats/sepa-purpose.js +89 -0
  67. package/dist/formats/sepa-purpose.js.map +1 -0
  68. package/dist/index.d.ts +28 -0
  69. package/dist/index.d.ts.map +1 -0
  70. package/dist/index.js +27 -0
  71. package/dist/index.js.map +1 -0
  72. package/dist/session/app-approval.d.ts +66 -0
  73. package/dist/session/app-approval.d.ts.map +1 -0
  74. package/dist/session/app-approval.js +226 -0
  75. package/dist/session/app-approval.js.map +1 -0
  76. package/dist/session/dialog-runner.d.ts +31 -0
  77. package/dist/session/dialog-runner.d.ts.map +1 -0
  78. package/dist/session/dialog-runner.js +111 -0
  79. package/dist/session/dialog-runner.js.map +1 -0
  80. package/dist/session/login-guard.d.ts +78 -0
  81. package/dist/session/login-guard.d.ts.map +1 -0
  82. package/dist/session/login-guard.js +181 -0
  83. package/dist/session/login-guard.js.map +1 -0
  84. package/dist/session/sepa-accounts.d.ts +40 -0
  85. package/dist/session/sepa-accounts.d.ts.map +1 -0
  86. package/dist/session/sepa-accounts.js +112 -0
  87. package/dist/session/sepa-accounts.js.map +1 -0
  88. package/dist/session/session-setup.d.ts +80 -0
  89. package/dist/session/session-setup.d.ts.map +1 -0
  90. package/dist/session/session-setup.js +182 -0
  91. package/dist/session/session-setup.js.map +1 -0
  92. package/dist/session/session-state.d.ts +50 -0
  93. package/dist/session/session-state.d.ts.map +1 -0
  94. package/dist/session/session-state.js +182 -0
  95. package/dist/session/session-state.js.map +1 -0
  96. package/dist/session/signed-dialog.d.ts +77 -0
  97. package/dist/session/signed-dialog.d.ts.map +1 -0
  98. package/dist/session/signed-dialog.js +170 -0
  99. package/dist/session/signed-dialog.js.map +1 -0
  100. package/dist/session/tan-selection.d.ts +96 -0
  101. package/dist/session/tan-selection.d.ts.map +1 -0
  102. package/dist/session/tan-selection.js +189 -0
  103. package/dist/session/tan-selection.js.map +1 -0
  104. package/dist/session/user-prompts.d.ts +65 -0
  105. package/dist/session/user-prompts.d.ts.map +1 -0
  106. package/dist/session/user-prompts.js +184 -0
  107. package/dist/session/user-prompts.js.map +1 -0
  108. package/dist/tan/challenge.d.ts +135 -0
  109. package/dist/tan/challenge.d.ts.map +1 -0
  110. package/dist/tan/challenge.js +184 -0
  111. package/dist/tan/challenge.js.map +1 -0
  112. package/dist/tan/flicker.d.ts +42 -0
  113. package/dist/tan/flicker.d.ts.map +1 -0
  114. package/dist/tan/flicker.js +296 -0
  115. package/dist/tan/flicker.js.map +1 -0
  116. package/dist/tan/tan-image.d.ts +22 -0
  117. package/dist/tan/tan-image.d.ts.map +1 -0
  118. package/dist/tan/tan-image.js +43 -0
  119. package/dist/tan/tan-image.js.map +1 -0
  120. package/dist/tan/tan-models.d.ts +149 -0
  121. package/dist/tan/tan-models.d.ts.map +1 -0
  122. package/dist/tan/tan-models.js +153 -0
  123. package/dist/tan/tan-models.js.map +1 -0
  124. package/dist/util/async.d.ts +22 -0
  125. package/dist/util/async.d.ts.map +1 -0
  126. package/dist/util/async.js +45 -0
  127. package/dist/util/async.js.map +1 -0
  128. package/dist/util/bytes.d.ts +22 -0
  129. package/dist/util/bytes.d.ts.map +1 -0
  130. package/dist/util/bytes.js +128 -0
  131. package/dist/util/bytes.js.map +1 -0
  132. package/dist/util/call-context.d.ts +12 -0
  133. package/dist/util/call-context.d.ts.map +1 -0
  134. package/dist/util/call-context.js +30 -0
  135. package/dist/util/call-context.js.map +1 -0
  136. package/dist/util/dates.d.ts +55 -0
  137. package/dist/util/dates.d.ts.map +1 -0
  138. package/dist/util/dates.js +189 -0
  139. package/dist/util/dates.js.map +1 -0
  140. package/dist/util/errors.d.ts +17 -0
  141. package/dist/util/errors.d.ts.map +1 -0
  142. package/dist/util/errors.js +24 -0
  143. package/dist/util/errors.js.map +1 -0
  144. package/dist/util/immutable-map.d.ts +16 -0
  145. package/dist/util/immutable-map.d.ts.map +1 -0
  146. package/dist/util/immutable-map.js +38 -0
  147. package/dist/util/immutable-map.js.map +1 -0
  148. package/dist/util/json.d.ts +17 -0
  149. package/dist/util/json.d.ts.map +1 -0
  150. package/dist/util/json.js +62 -0
  151. package/dist/util/json.js.map +1 -0
  152. package/dist/util/text.d.ts +37 -0
  153. package/dist/util/text.d.ts.map +1 -0
  154. package/dist/util/text.js +107 -0
  155. package/dist/util/text.js.map +1 -0
  156. package/dist/util/xml.d.ts +36 -0
  157. package/dist/util/xml.d.ts.map +1 -0
  158. package/dist/util/xml.js +194 -0
  159. package/dist/util/xml.js.map +1 -0
  160. package/dist/v3/account-extension.d.ts +25 -0
  161. package/dist/v3/account-extension.d.ts.map +1 -0
  162. package/dist/v3/account-extension.js +173 -0
  163. package/dist/v3/account-extension.js.map +1 -0
  164. package/dist/v3/bank-connection.d.ts +34 -0
  165. package/dist/v3/bank-connection.d.ts.map +1 -0
  166. package/dist/v3/bank-connection.js +58 -0
  167. package/dist/v3/bank-connection.js.map +1 -0
  168. package/dist/v3/dialog.d.ts +112 -0
  169. package/dist/v3/dialog.d.ts.map +1 -0
  170. package/dist/v3/dialog.js +241 -0
  171. package/dist/v3/dialog.js.map +1 -0
  172. package/dist/v3/message.d.ts +85 -0
  173. package/dist/v3/message.d.ts.map +1 -0
  174. package/dist/v3/message.js +303 -0
  175. package/dist/v3/message.js.map +1 -0
  176. package/dist/v3/parameter-store.d.ts +75 -0
  177. package/dist/v3/parameter-store.d.ts.map +1 -0
  178. package/dist/v3/parameter-store.js +143 -0
  179. package/dist/v3/parameter-store.js.map +1 -0
  180. package/dist/v3/parameters.d.ts +105 -0
  181. package/dist/v3/parameters.d.ts.map +1 -0
  182. package/dist/v3/parameters.js +450 -0
  183. package/dist/v3/parameters.js.map +1 -0
  184. package/dist/v3/protocol.d.ts +61 -0
  185. package/dist/v3/protocol.d.ts.map +1 -0
  186. package/dist/v3/protocol.js +113 -0
  187. package/dist/v3/protocol.js.map +1 -0
  188. package/dist/v3/queries.d.ts +51 -0
  189. package/dist/v3/queries.d.ts.map +1 -0
  190. package/dist/v3/queries.js +120 -0
  191. package/dist/v3/queries.js.map +1 -0
  192. package/dist/v3/segments.d.ts +106 -0
  193. package/dist/v3/segments.d.ts.map +1 -0
  194. package/dist/v3/segments.js +325 -0
  195. package/dist/v3/segments.js.map +1 -0
  196. package/dist/v3/syntax.d.ts +127 -0
  197. package/dist/v3/syntax.d.ts.map +1 -0
  198. package/dist/v3/syntax.js +367 -0
  199. package/dist/v3/syntax.js.map +1 -0
  200. package/package.json +67 -4
  201. package/src/client.ts +252 -0
  202. package/src/core/account.ts +323 -0
  203. package/src/core/amount.ts +211 -0
  204. package/src/core/balance.ts +85 -0
  205. package/src/core/bank-info.ts +66 -0
  206. package/src/core/client.ts +186 -0
  207. package/src/core/config.ts +182 -0
  208. package/src/core/errors.ts +277 -0
  209. package/src/core/feedback.ts +140 -0
  210. package/src/core/transaction.ts +161 -0
  211. package/src/core/transport.ts +189 -0
  212. package/src/formats/camt.ts +266 -0
  213. package/src/formats/mt940.ts +419 -0
  214. package/src/formats/readers.ts +49 -0
  215. package/src/formats/record-budget.ts +18 -0
  216. package/src/formats/sepa-purpose.ts +94 -0
  217. package/src/index.ts +70 -0
  218. package/src/session/app-approval.ts +278 -0
  219. package/src/session/dialog-runner.ts +122 -0
  220. package/src/session/login-guard.ts +221 -0
  221. package/src/session/sepa-accounts.ts +115 -0
  222. package/src/session/session-setup.ts +184 -0
  223. package/src/session/session-state.ts +204 -0
  224. package/src/session/signed-dialog.ts +192 -0
  225. package/src/session/tan-selection.ts +203 -0
  226. package/src/session/user-prompts.ts +193 -0
  227. package/src/tan/challenge.ts +261 -0
  228. package/src/tan/flicker.ts +308 -0
  229. package/src/tan/tan-image.ts +38 -0
  230. package/src/tan/tan-models.ts +252 -0
  231. package/src/util/async.ts +48 -0
  232. package/src/util/bytes.ts +129 -0
  233. package/src/util/call-context.ts +41 -0
  234. package/src/util/dates.ts +210 -0
  235. package/src/util/errors.ts +27 -0
  236. package/src/util/immutable-map.ts +47 -0
  237. package/src/util/json.ts +67 -0
  238. package/src/util/text.ts +112 -0
  239. package/src/util/xml.ts +183 -0
  240. package/src/v3/account-extension.ts +185 -0
  241. package/src/v3/bank-connection.ts +67 -0
  242. package/src/v3/dialog.ts +283 -0
  243. package/src/v3/message.ts +373 -0
  244. package/src/v3/parameter-store.ts +160 -0
  245. package/src/v3/parameters.ts +524 -0
  246. package/src/v3/protocol.ts +148 -0
  247. package/src/v3/queries.ts +190 -0
  248. package/src/v3/segments.ts +374 -0
  249. package/src/v3/syntax.ts +369 -0
@@ -0,0 +1,115 @@
1
+ import { Account, AccountIndex } from '../core/account.js';
2
+ import { FinTsUnsupportedError, tryLookUp } from '../core/errors.js';
3
+ import type { ParameterStore } from '../v3/parameter-store.js';
4
+ import { sepaAccountsQuery } from '../v3/queries.js';
5
+ import type { DialogRunner } from './dialog-runner.js';
6
+ import type { SessionState } from './session-state.js';
7
+
8
+ /**
9
+ * IBAN and BIC of the user's accounts, from the bank's SEPA account list where the user parameter data lack them
10
+ * (Formals F.3.4), and the accounts the app passes completed from both.
11
+ *
12
+ * The list is read once per version of the user parameter data and kept in the saved state. Under version 0, which
13
+ * holds for one dialog only (Formals E.2), without user parameter data, or where the bank rejects the list, also by
14
+ * ending the dialog, or names no account in it, it is kept for this client only: an empty list completes nothing, and
15
+ * saved it would outlast a fault of a single answer until the bank changes its user parameter data.
16
+ */
17
+ export class SepaAccounts {
18
+ /**
19
+ * The list this client keeps unsaved, with the version of the user parameter data it was read under; empty where the
20
+ * bank rejected it or named no account.
21
+ */
22
+ private unsaved: { updVersion: number | undefined; accounts: readonly Account[] } | undefined;
23
+
24
+ constructor(
25
+ private readonly parameters: ParameterStore,
26
+ private readonly state: SessionState,
27
+ private readonly dialogs: DialogRunner,
28
+ ) {}
29
+
30
+ /** The accounts of the user parameter data completed with IBAN and BIC, then the accounts only the list names. */
31
+ async completedAccounts(): Promise<Account[]> {
32
+ const sepa = await this.list();
33
+ const accounts = this.parameters.userParameters?.accounts ?? [];
34
+ const listed = new AccountIndex(sepa);
35
+ const known = new AccountIndex(accounts);
36
+ return [
37
+ ...accounts.map((account) => withSepaDetails(account, listed.find(account))),
38
+ ...sepa.filter((s) => known.find(s) === undefined),
39
+ ];
40
+ }
41
+
42
+ /**
43
+ * `account` as the bank knows it: the one of `completedAccounts` it matches, with what the bank states of it first,
44
+ * so that an account the app has built itself, such as from an IBAN alone, goes out with the account number, the
45
+ * sub-account and the BIC the bank's orders take, and the currency of its statements. Where the bank names none it
46
+ * matches, only what identifies `account`, and its currency: the rest, such as the transactions it permits, only the
47
+ * bank can state.
48
+ *
49
+ * Throws `FinTsUnsupportedError` for such an account where the user parameter data list all permitted transactions:
50
+ * they permit nothing for an account they leave out, and the client cannot tell it from a mistyped one.
51
+ */
52
+ async complete(account: Account): Promise<Account> {
53
+ const known = (await this.completedAccounts()).find((a) => account.matches(a));
54
+ if (known !== undefined) {
55
+ // A sub-account belongs to the account number it comes with.
56
+ const national = known.accountNumber === undefined ? account : known;
57
+ return known.copyWith({
58
+ accountNumber: national.accountNumber,
59
+ subAccount: national.subAccount,
60
+ iban: known.iban ?? account.iban,
61
+ bic: known.bic ?? account.bic,
62
+ currency: known.currency ?? account.currency,
63
+ });
64
+ }
65
+ if (this.parameters.userParameters?.listsAllTransactions === true) {
66
+ throw new FinTsUnsupportedError("The bank does not name this account among the user's, and so permits nothing");
67
+ }
68
+ return new Account({
69
+ accountNumber: account.accountNumber,
70
+ subAccount: account.subAccount,
71
+ bankCode: account.bankCode,
72
+ countryCode: account.countryCode,
73
+ iban: account.iban,
74
+ bic: account.bic,
75
+ currency: account.currency,
76
+ });
77
+ }
78
+
79
+ /** The list, read in the session's dialog, whose start delivers the user parameter data it is cached for. */
80
+ private async list(): Promise<readonly Account[]> {
81
+ await this.dialogs.open();
82
+ const upd = this.parameters.userParameters;
83
+ if (
84
+ upd !== undefined &&
85
+ upd.accounts.length > 0 &&
86
+ upd.accounts.every((a) => a.iban !== undefined && a.bic !== undefined)
87
+ ) {
88
+ return [];
89
+ }
90
+ const updVersion = upd?.version;
91
+ const saved = this.state.sepaAccounts(updVersion);
92
+ if (saved !== undefined) return saved;
93
+ if (this.unsaved !== undefined && this.unsaved.updVersion === updVersion) return this.unsaved.accounts;
94
+ const query = sepaAccountsQuery(this.parameters);
95
+ if (query === undefined) return [];
96
+ // Where the bank rejects the list, also by ending the dialog, the accounts stay as the user parameter data state
97
+ // them: asked again, a bank that ends the dialog in answer would cost each call a login.
98
+ const accounts = await tryLookUp(() => this.dialogs.query(() => query));
99
+ if (accounts !== undefined && accounts.length > 0 && updVersion !== undefined && updVersion > 0) {
100
+ this.state.cacheSepaAccounts(accounts, updVersion);
101
+ } else {
102
+ this.unsaved = { updVersion, accounts: accounts ?? [] };
103
+ }
104
+ return accounts ?? [];
105
+ }
106
+ }
107
+
108
+ /**
109
+ * A copy of `account`, which shares no date with the user parameter data, with the IBAN and BIC of `match`, its entry
110
+ * in the SEPA account list, if any.
111
+ */
112
+ function withSepaDetails(account: Account, match: Account | undefined): Account {
113
+ // A BIC of the list takes precedence over the one of the user parameter data (Formals E.3.1.1, "BIC").
114
+ return account.copyWith({ iban: account.iban ?? match?.iban, bic: match?.bic ?? account.bic });
115
+ }
@@ -0,0 +1,184 @@
1
+ import type { BankInfo } from '../core/bank-info.js';
2
+ import { FinTsError, FinTsProtocolError, FinTsTransportError, parseBankData, tryLookUp } from '../core/errors.js';
3
+ import { hasErrors } from '../core/feedback.js';
4
+ import type { TanMedium, TanMethod } from '../tan/tan-models.js';
5
+ import { FinTs3Dialog } from '../v3/dialog.js';
6
+ import type { IncomingMessage3 } from '../v3/message.js';
7
+ import { requireBankParameters } from '../v3/parameters.js';
8
+ import type { FinTs3Protocol } from '../v3/protocol.js';
9
+ import { tanMediaQuery } from '../v3/queries.js';
10
+ import type { RefusalReason } from './login-guard.js';
11
+ import { SignedDialog, type SessionParts } from './signed-dialog.js';
12
+ import type { TanSelection } from './tan-selection.js';
13
+
14
+ /**
15
+ * What has to be settled before a login: the bank parameter data, the synchronization, and through `TanSelection` the
16
+ * TAN method and medium. Each of the dialogs this takes serves one purpose only.
17
+ *
18
+ * Where the bank refuses a login for a reason the session can take care of, `remedied` does so and logs in again.
19
+ */
20
+ export class SessionSetup {
21
+ constructor(
22
+ private readonly session: SessionParts,
23
+ private readonly protocol: FinTs3Protocol,
24
+ private readonly tans: TanSelection,
25
+ ) {}
26
+
27
+ /**
28
+ * The bank's general information: from an anonymous dialog where the bank answers one, else from the synchronization.
29
+ * No TAN method or medium is chosen for it.
30
+ */
31
+ async bankInfo(): Promise<BankInfo> {
32
+ if (this.session.parameters.bankParameters === undefined) await this.fetchBankParametersAnonymously();
33
+ if (this.session.parameters.bankParameters === undefined) await this.synchronizeIfDue();
34
+ return requireBankParameters(this.session.parameters.bankParameters).bankInfo;
35
+ }
36
+
37
+ /** The TAN methods the bank allows for this user, which the synchronization reports. */
38
+ async methods(): Promise<TanMethod[]> {
39
+ await this.loadParameters();
40
+ return this.tans.available();
41
+ }
42
+
43
+ /**
44
+ * Settles what is still open: the bank parameter data, the synchronization, the TAN method and medium. Returns the TAN
45
+ * media it looked up to choose the medium; `undefined` where it looked up none, or the bank listed none.
46
+ */
47
+ async prepare(): Promise<TanMedium[] | undefined> {
48
+ await this.loadParameters();
49
+ await this.tans.ensureMethodChosen();
50
+ if (!this.tans.mediumToLookUp) return undefined;
51
+ const media = await this.lookUpTanMedia();
52
+ await this.tans.chooseMedium(media);
53
+ return media;
54
+ }
55
+
56
+ /** A new dialog signed with the TAN method and medium in use, once `prepare` has settled them. */
57
+ async newDialog(): Promise<SignedDialog> {
58
+ await this.prepare();
59
+ return new SignedDialog(this.tans.newDialog(), this.session);
60
+ }
61
+
62
+ /** Runs `attempt`, which may log in, once more after each refused login `remedy` takes care of. */
63
+ remedied<T>(attempt: () => Promise<T>): Promise<T> {
64
+ return this.session.guard.remedied(attempt, (reason, rejected) => this.remedy(reason, rejected));
65
+ }
66
+
67
+ /**
68
+ * Takes care of `reason`, given for refusing a login signed with `rejected`, with another TAN method or a new
69
+ * synchronization; returns whether it could.
70
+ */
71
+ private async remedy(reason: RefusalReason, rejected: TanMethod): Promise<boolean> {
72
+ switch (reason) {
73
+ case 'tanMethodNotAllowed':
74
+ // The parameter data name the methods to choose from; the refusal may be the first to deliver them.
75
+ if (this.session.parameters.bankParameters === undefined) await this.fetchBankParametersAnonymously();
76
+ return this.tans.replace(rejected);
77
+ case 'systemIdRejected':
78
+ // Without a customer system ID there is none to lose, and logging in once more would only send the PIN again.
79
+ return this.session.parameters.forgetSystemId();
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Loads the bank parameter data if they are missing, then synchronizes if that is due.
85
+ *
86
+ * The bank parameter data come first, from an anonymous dialog: the dialogs signed with the PIN need them for the
87
+ * dialog language, the PIN length and the TAN methods (PIN/TAN B.4.3.1, Formals C.3.1.3). A bank that does not answer
88
+ * anonymously delivers them with the synchronization.
89
+ *
90
+ * After a refused login it throws the refusal right away, before the user is asked for a TAN method or medium.
91
+ */
92
+ private async loadParameters(): Promise<void> {
93
+ this.session.guard.check();
94
+ if (this.session.parameters.bankParameters === undefined) await this.fetchBankParametersAnonymously();
95
+ await this.synchronizeIfDue();
96
+ }
97
+
98
+ /**
99
+ * Asks for the bank parameter data without logging in, keeps them where there are none from a dialog signed with the
100
+ * PIN (`ParameterStore.keepAnonymous`), and passes the bank's messages on: all an anonymous dialog tells, since the
101
+ * TAN methods it lists are not those of a user. A bank that does not answer anonymously is no error, but a failed
102
+ * connection is: the synchronization would only wait for the same server again.
103
+ */
104
+ private async fetchBankParametersAnonymously(): Promise<void> {
105
+ try {
106
+ const response = await this.requestBankParametersAnonymously();
107
+ this.session.parameters.keepAnonymous(response);
108
+ for (const message of response.bankMessages) this.session.prompts.showBankMessage(message);
109
+ } catch (error) {
110
+ // Optional: the login delivers the parameters as well.
111
+ if (error instanceof FinTsTransportError || !(error instanceof FinTsError)) throw error;
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Asks for the bank parameter data in an anonymous dialog that announces strong customer authentication; a bank that
117
+ * rejects the announcement, with a return code or by failing on it, is asked again without it.
118
+ *
119
+ * A timeout or a broken connection is not a reason to ask again: it would only double the wait.
120
+ */
121
+ private async requestBankParametersAnonymously(): Promise<IncomingMessage3> {
122
+ let announced: IncomingMessage3;
123
+ try {
124
+ announced = await this.anonymousDialog(true);
125
+ } catch (error) {
126
+ if (error instanceof FinTsTransportError && error.statusCode === undefined) throw error;
127
+ if (!(error instanceof FinTsError)) throw error;
128
+ return this.anonymousDialog(false);
129
+ }
130
+ if (!hasErrors(announced.feedback) || announced.find('HIBPA') !== undefined) return announced;
131
+ return this.anonymousDialog(false);
132
+ }
133
+
134
+ private async anonymousDialog(announceSca: boolean): Promise<IncomingMessage3> {
135
+ const dialog = FinTs3Dialog.anonymous(this.protocol);
136
+ try {
137
+ return await dialog.requestBankParameters(announceSca);
138
+ } finally {
139
+ await dialog.end();
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Runs the synchronization, a login in a dialog of its own, while there is no customer system ID, without which no
145
+ * regular dialog starts. It runs before the TAN method and medium are settled (`TanSelection.synchronizationDialog`
146
+ * tells which method signs it).
147
+ */
148
+ private async synchronizeIfDue(): Promise<void> {
149
+ if (this.session.parameters.systemId !== undefined) return;
150
+ await this.once(this.tans.synchronizationDialog(), (dialog) => dialog.login(true));
151
+ // Set by the synchronization, which the compiler cannot see.
152
+ if ((this.session.parameters.systemId as string | undefined) === undefined) {
153
+ throw new FinTsProtocolError('The bank did not complete the synchronization');
154
+ }
155
+ }
156
+
157
+ /**
158
+ * The TAN media of the method in use; `undefined` if the bank does not list them or rejects the list, after which the
159
+ * client reports a missing medium before the login.
160
+ *
161
+ * The lookup runs in a dialog of its own, whose start asks for the list, since the regular dialog start needs the
162
+ * medium the list tells (PIN/TAN B.4.3.1.3).
163
+ */
164
+ private async lookUpTanMedia(): Promise<TanMedium[] | undefined> {
165
+ const query = tanMediaQuery(this.session.parameters);
166
+ if (query === undefined) return undefined;
167
+ return tryLookUp(() =>
168
+ this.once(this.tans.lookupDialog(), async (dialog) => {
169
+ const answers = await dialog.loginWith(query.order(undefined));
170
+ return parseBankData(() => query.read(answers));
171
+ }),
172
+ );
173
+ }
174
+
175
+ /** Runs `use` in `dialog`, a dialog of its own, and ends it afterwards, however `use` ends. */
176
+ private async once<T>(dialog: FinTs3Dialog, use: (dialog: SignedDialog) => Promise<T>): Promise<T> {
177
+ const signed = new SignedDialog(dialog, this.session);
178
+ try {
179
+ return await use(signed);
180
+ } finally {
181
+ await signed.end();
182
+ }
183
+ }
184
+ }
@@ -0,0 +1,204 @@
1
+ import { Account } from '../core/account.js';
2
+ import { hostOf, type FinTsConfig } from '../core/config.js';
3
+ import { FinTsFeedback } from '../core/feedback.js';
4
+ import { FormatError } from '../util/errors.js';
5
+ import {
6
+ isJsonObject,
7
+ isString,
8
+ readObject,
9
+ readOptionalInt,
10
+ readOptionalObject,
11
+ readOptionalList,
12
+ readOptionalString,
13
+ type JsonObject,
14
+ } from '../util/json.js';
15
+ import type { ParameterStore } from '../v3/parameter-store.js';
16
+ import type { LoginGuard, LoginGuardState } from './login-guard.js';
17
+
18
+ /** Layout of the saved session; a state of another layout is ignored. */
19
+ const stateFormat = 1;
20
+
21
+ /** The protocol version the state is for, named as the Dart package names it, so that both read each other's states. */
22
+ const protocolVersion = 'v300';
23
+
24
+ /** The session, the parameter data and the guard's refusal as JSON, which `restoreSession` reads. */
25
+ export function saveSession(parameters: ParameterStore, guard: LoginGuard, session: SessionState): string {
26
+ return JSON.stringify({
27
+ format: stateFormat,
28
+ version: protocolVersion,
29
+ owner: ownerOf(parameters.config),
30
+ session: session.toJson(),
31
+ // Under the key the Dart package reads as well.
32
+ protocol: parameters.saveState(),
33
+ loginGuard: guardStateToJson(guard.saveState()),
34
+ });
35
+ }
36
+
37
+ /**
38
+ * The session saved in `json`, and the parameter data and the guard's refused login restored from it.
39
+ *
40
+ * A missing or damaged state, or one saved for another user, bank, server or protocol version, gives a new session,
41
+ * which only costs a new synchronization. The refused login belongs to the user at the bank, so it comes first: it holds
42
+ * for another server or protocol version as well, and where the rest is damaged; a state saved by the Dart package or
43
+ * an earlier version has none.
44
+ */
45
+ export function restoreSession(json: string | undefined, parameters: ParameterStore, guard: LoginGuard): SessionState {
46
+ if (json === undefined) return new SessionState();
47
+ try {
48
+ const saved: unknown = JSON.parse(json);
49
+ if (!isJsonObject(saved) || saved.format !== stateFormat) return new SessionState();
50
+ const [server, ...user] = readOptionalList(saved, 'owner', isString) ?? [];
51
+ const expected = userOf(parameters.config);
52
+ if (user.length !== expected.length || user.some((value, i) => value !== expected[i])) return new SessionState();
53
+ const loginGuard = readOptionalObject(saved, 'loginGuard');
54
+ if (loginGuard !== undefined) guard.restoreState(guardStateFromJson(loginGuard));
55
+ if (server !== hostOf(parameters.config.url) || saved.version !== protocolVersion) return new SessionState();
56
+ const session = SessionState.fromJson(readObject(saved, 'session'));
57
+ parameters.restoreState(readObject(saved, 'protocol'));
58
+ return session;
59
+ } catch (error) {
60
+ // Damaged JSON, base64 or parameter data, and values of the wrong type, only cost a new synchronization.
61
+ if (error instanceof FormatError || error instanceof SyntaxError) return new SessionState();
62
+ throw error;
63
+ }
64
+ }
65
+
66
+ /** Whose data a state holds, so that the state of another user or bank is never used: the server, then `userOf`. */
67
+ function ownerOf(config: FinTsConfig): string[] {
68
+ return [hostOf(config.url), ...userOf(config)];
69
+ }
70
+
71
+ /** The user at the bank, whom a refused login belongs to. */
72
+ function userOf(config: FinTsConfig): string[] {
73
+ return [config.bankCode, config.userId, config.customerId];
74
+ }
75
+
76
+ /**
77
+ * The session data saved between app starts: the allowed TAN methods, the TAN method and medium in use, and the SEPA
78
+ * account list.
79
+ */
80
+ export class SessionState {
81
+ private allowedMethodsValue: readonly string[] | undefined;
82
+ private tanMethodValue: string | undefined;
83
+ private tanMediumValue: string | undefined;
84
+ private sepaAccountsValue: readonly Account[] | undefined;
85
+ private sepaUpdVersion: number | undefined;
86
+
87
+ /** TAN methods the bank allows for this user (return code 3920); `undefined` until the bank has said. */
88
+ get allowedMethods(): readonly string[] | undefined {
89
+ return this.allowedMethodsValue;
90
+ }
91
+
92
+ /** Security function of the TAN method in use. */
93
+ get tanMethod(): string | undefined {
94
+ return this.tanMethodValue;
95
+ }
96
+
97
+ /** Name of the TAN medium in use. */
98
+ get tanMedium(): string | undefined {
99
+ return this.tanMediumValue;
100
+ }
101
+
102
+ /** Keeps the TAN methods the bank reports as allowed for this user. */
103
+ rememberAllowedMethods(securityFunctions: readonly string[]): void {
104
+ this.allowedMethodsValue = Object.freeze([...securityFunctions]);
105
+ }
106
+
107
+ /**
108
+ * Switches to the TAN method `securityFunction` and the TAN `medium` together, so that no medium of another method
109
+ * stays behind; `undefined` leaves the choice to the next login.
110
+ */
111
+ useTanMethod(securityFunction: string | undefined, medium?: string): void {
112
+ this.tanMethodValue = securityFunction;
113
+ this.tanMediumValue = medium;
114
+ }
115
+
116
+ /** Switches to the TAN `medium` of the method in use. */
117
+ useTanMedium(medium: string | undefined): void {
118
+ this.tanMediumValue = medium;
119
+ }
120
+
121
+ /** The SEPA account list read under the user parameter data of `updVersion`, if it is cached. */
122
+ sepaAccounts(updVersion: number | undefined): readonly Account[] | undefined {
123
+ return updVersion !== undefined && updVersion === this.sepaUpdVersion ? this.sepaAccountsValue : undefined;
124
+ }
125
+
126
+ /** Caches the SEPA account list `accounts`, read under the user parameter data of `updVersion`. */
127
+ cacheSepaAccounts(accounts: readonly Account[], updVersion: number | undefined): void {
128
+ this.sepaAccountsValue = Object.freeze([...accounts]);
129
+ this.sepaUpdVersion = updVersion;
130
+ }
131
+
132
+ /** Reads what `toJson` wrote; throws `FormatError` if `json` is damaged. */
133
+ static fromJson(json: JsonObject): SessionState {
134
+ const allowedMethods = readOptionalList(json, 'allowedMethods', isString);
135
+ const sepaAccounts = readOptionalList(json, 'sepaAccounts', isJsonObject)?.map(accountFromJson);
136
+ const sepaUpdVersion = readOptionalInt(json, 'sepaUpdVersion');
137
+ const state = new SessionState();
138
+ state.useTanMethod(readOptionalString(json, 'tanMethod'), readOptionalString(json, 'tanMedium'));
139
+ if (allowedMethods !== undefined) state.rememberAllowedMethods(allowedMethods);
140
+ if (sepaAccounts !== undefined) state.cacheSepaAccounts(sepaAccounts, sepaUpdVersion);
141
+ return state;
142
+ }
143
+
144
+ /** The session as JSON data. */
145
+ toJson(): JsonObject {
146
+ return {
147
+ allowedMethods: this.allowedMethodsValue ?? null,
148
+ tanMethod: this.tanMethodValue ?? null,
149
+ tanMedium: this.tanMediumValue ?? null,
150
+ sepaUpdVersion: this.sepaUpdVersion ?? null,
151
+ sepaAccounts: this.sepaAccountsValue?.map(accountToJson) ?? null,
152
+ };
153
+ }
154
+ }
155
+
156
+ function accountToJson(a: Account): JsonObject {
157
+ return {
158
+ iban: a.iban ?? null,
159
+ bic: a.bic ?? null,
160
+ accountNumber: a.accountNumber ?? null,
161
+ subAccount: a.subAccount ?? null,
162
+ countryCode: a.countryCode,
163
+ bankCode: a.bankCode,
164
+ };
165
+ }
166
+
167
+ function accountFromJson(json: JsonObject): Account {
168
+ const bankCode = readOptionalString(json, 'bankCode');
169
+ if (bankCode === undefined) throw new FormatError('Saved state: account without bank code');
170
+ return new Account({
171
+ iban: readOptionalString(json, 'iban'),
172
+ bic: readOptionalString(json, 'bic'),
173
+ accountNumber: readOptionalString(json, 'accountNumber'),
174
+ subAccount: readOptionalString(json, 'subAccount'),
175
+ countryCode: readOptionalString(json, 'countryCode'),
176
+ bankCode,
177
+ });
178
+ }
179
+
180
+ function guardStateToJson(state: LoginGuardState): JsonObject {
181
+ return { refusal: state.refusal?.map(feedbackToJson) ?? null, unreadLogins: state.unreadLogins };
182
+ }
183
+
184
+ function guardStateFromJson(json: JsonObject): LoginGuardState {
185
+ return {
186
+ refusal: readOptionalList(json, 'refusal', isJsonObject)?.map(feedbackFromJson),
187
+ unreadLogins: readOptionalInt(json, 'unreadLogins') ?? 0,
188
+ };
189
+ }
190
+
191
+ function feedbackToJson(f: FinTsFeedback): JsonObject {
192
+ return { code: f.code, reference: f.reference ?? null, text: f.text, parameters: [...f.parameters] };
193
+ }
194
+
195
+ function feedbackFromJson(json: JsonObject): FinTsFeedback {
196
+ const code = readOptionalString(json, 'code');
197
+ if (code === undefined) throw new FormatError('Saved state: return code without code');
198
+ return new FinTsFeedback({
199
+ code,
200
+ reference: readOptionalString(json, 'reference'),
201
+ text: readOptionalString(json, 'text') ?? '',
202
+ parameters: readOptionalList(json, 'parameters', isString) ?? [],
203
+ });
204
+ }