@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,278 @@
1
+ import { FinTsDecoupledTimeoutError, FinTsTanCancelledError } from '../core/errors.js';
2
+ import { FeedbackCodes, hasCode, type FinTsFeedback } from '../core/feedback.js';
3
+ import { nextAttempt, withResolved, type TanAnswer, type TanChallenge } from '../tan/challenge.js';
4
+ import type { TanMethod } from '../tan/tan-models.js';
5
+ import { Deferred } from '../util/async.js';
6
+ import { invalidArgument } from '../util/errors.js';
7
+ import type { Approval } from '../v3/dialog.js';
8
+
9
+ /** What a wait reads of the bank's answer to a status request: its return codes. */
10
+ interface StatusAnswer {
11
+ readonly feedback: readonly FinTsFeedback[];
12
+ }
13
+
14
+ /** How long to wait for an app approval when the bank does not say. */
15
+ const defaultMaxStatusPolls = 60;
16
+ const defaultFirstPollDelayMs = 2_000;
17
+ const defaultPollIntervalMs = 2_000;
18
+
19
+ /** Bounds for the bank's polling parameters, against faulty parameter data. */
20
+ const minPollIntervalMs = 1_000;
21
+ const maxPollDelayMs = 60_000;
22
+ const maxApprovalWaitMs = 10 * 60_000;
23
+
24
+ /** Shows a challenge and returns the user's answer. */
25
+ type AskUser = (challenge: TanChallenge) => Promise<TanAnswer>;
26
+
27
+ /** Waits for `delayMs`, or until `interrupt` settles. */
28
+ type Pause = (delayMs: number, interrupt?: Promise<unknown>) => Promise<void>;
29
+
30
+ /** What an `AppApprovalWait` needs: `ask` shows a challenge, `pause` waits, `receive` takes in each status response. */
31
+ export interface AppApprovalHooks<R> {
32
+ readonly ask: AskUser;
33
+ readonly pause: Pause;
34
+ /** Takes in each status response; throws if it reports errors. */
35
+ readonly receive: (response: R) => void;
36
+ }
37
+
38
+ /**
39
+ * Waits for the user to approve a message in the banking app, and for the bank to confirm it (PIN/TAN B.4.2.2).
40
+ *
41
+ * The bank's parameters decide who triggers the status requests:
42
+ * - The client polls by itself while the callback shows the instructions (`PollingWhileShown`) where the bank allows
43
+ * automatic status requests and announces no push message (3957), and also where the user cannot report the
44
+ * approval: then polling is the one way left to complete it, whatever the other parameters say (step 2a).
45
+ * - Otherwise the client asks after each report of the user (`PollingAfterReports`), which stands in for the push
46
+ * message the client cannot receive.
47
+ *
48
+ * The bank's limit on status requests holds either way, and two requests are at least a second apart. One instance
49
+ * handles one `Approval`; `run` may be called once. A failure of `ask` or `pause`, such as a closed client, ends the
50
+ * wait.
51
+ */
52
+ export function appApprovalWait<R extends StatusAnswer>(
53
+ approval: Approval<R>,
54
+ hooks: AppApprovalHooks<R>,
55
+ ): AppApprovalWait<R> {
56
+ const method = approval.challenge.method;
57
+ const automatic = !method.decoupledManualConfirmation || (method.decoupledAutomaticPolling && !approval.waitForPush);
58
+ return automatic ? new PollingWhileShown(approval, hooks) : new PollingAfterReports(approval, hooks);
59
+ }
60
+
61
+ export abstract class AppApprovalWait<R extends StatusAnswer> {
62
+ private requests = 0;
63
+
64
+ /** The time the client waited by itself, which counts towards the longest wait. */
65
+ protected waitedMs = 0;
66
+
67
+ constructor(
68
+ protected readonly approval: Approval<R>,
69
+ protected readonly hooks: AppApprovalHooks<R>,
70
+ ) {}
71
+
72
+ /**
73
+ * Returns the bank's response once the approval is through. Throws `FinTsTanCancelledError` if the user cancels and
74
+ * `FinTsDecoupledTimeoutError` if the approval takes too long.
75
+ */
76
+ abstract run(): Promise<R>;
77
+
78
+ protected get method(): TanMethod {
79
+ return this.approval.challenge.method;
80
+ }
81
+
82
+ /** Whether the user may report the approval (PIN/TAN, "Manuelle Bestätigung möglich"). */
83
+ protected get userConfirms(): boolean {
84
+ return this.method.decoupledManualConfirmation;
85
+ }
86
+
87
+ protected get pollIntervalMs(): number {
88
+ return clamp(
89
+ seconds(this.method.decoupledPollIntervalSeconds) ?? defaultPollIntervalMs,
90
+ minPollIntervalMs,
91
+ maxPollDelayMs,
92
+ );
93
+ }
94
+
95
+ protected get firstPollDelayMs(): number {
96
+ return clamp(seconds(this.method.decoupledFirstPollDelaySeconds) ?? defaultFirstPollDelayMs, 0, maxPollDelayMs);
97
+ }
98
+
99
+ /**
100
+ * Sends the next status request and returns the answer, once `receive` has taken it in.
101
+ *
102
+ * Throws if the answer reports errors, and `FinTsDecoupledTimeoutError` if the approval is still pending after as
103
+ * many requests as the bank allows, or after the longest wait.
104
+ */
105
+ protected async requestStatus(): Promise<R> {
106
+ const response = await this.approval.checkStatus();
107
+ this.requests++;
108
+ this.hooks.receive(response);
109
+ // A maximum of 0 allows any number of requests (PIN/TAN, "Maximale Anzahl Statusabfragen Decoupled").
110
+ const maxRequests = this.method.decoupledMaxPolls ?? defaultMaxStatusPolls;
111
+ if (
112
+ isPending(response) &&
113
+ ((maxRequests > 0 && this.requests >= maxRequests) || this.waitedMs >= maxApprovalWaitMs)
114
+ ) {
115
+ throw new FinTsDecoupledTimeoutError();
116
+ }
117
+ return response;
118
+ }
119
+
120
+ /**
121
+ * `challenge` as the next prompt, with the new instructions of `pending`, the last status answer, where it gives any
122
+ * (PIN/TAN B.4.2.2.1, step 2b).
123
+ */
124
+ protected nextPrompt(challenge: TanChallenge, pending: R): TanChallenge {
125
+ return nextAttempt(challenge, this.approval.instructionsIn(pending));
126
+ }
127
+ }
128
+
129
+ /**
130
+ * The client polls by itself while the callback shows the instructions, and settles the `TanChallenge.resolved` of a
131
+ * prompt when it needs no more answer to it.
132
+ *
133
+ * `run` shows the prompt, waits the bank's first delay, then asks the bank until it confirms, waiting the interval in
134
+ * between. A status answer with new instructions replaces the prompt with one that shows them. The callback's answer
135
+ * only records what the user did, and counts while its prompt is shown:
136
+ * - `stopped` settles on a cancel, a TAN or a failing callback; the loop stops before its next request.
137
+ * - `report` settles on a report of the approval, which cuts the current wait short once, though not below a second.
138
+ * The report closed the prompt, so it is shown anew while the bank has not confirmed yet.
139
+ * - A user who cannot report the approval has every answer but `TanAnswer.cancelled` ignored.
140
+ */
141
+ class PollingWhileShown<R extends StatusAnswer> extends AppApprovalWait<R> {
142
+ /** Settles when the prompt shown now needs no more answer, which its `TanChallenge.resolved` tells the callback. */
143
+ private shown: Deferred<void> | undefined;
144
+
145
+ /** Settles when the user cancels or the callback fails; `stopReason` holds the error that ends the wait. */
146
+ private readonly stopped = new Deferred<void>();
147
+ private stopReason: { error: unknown } | undefined;
148
+
149
+ /** Settles when the user reports the approval in the prompt shown now; `undefined` once the report was used. */
150
+ private report: Deferred<void> | undefined;
151
+
152
+ async run(): Promise<R> {
153
+ let challenge = this.approval.challenge;
154
+ this.show(challenge);
155
+ try {
156
+ await this.sleep(this.firstPollDelayMs);
157
+ for (;;) {
158
+ this.throwIfStopped();
159
+ // A request under way is awaited even when the user cancels meanwhile; its answer counts.
160
+ const response = await this.requestStatus();
161
+ if (!isPending(response)) return response;
162
+ this.throwIfStopped();
163
+ // A report closed the prompt, but the bank has not confirmed the approval yet; or the bank's instructions changed.
164
+ const reported = this.userConfirms && this.report === undefined;
165
+ const next = this.nextPrompt(challenge, response);
166
+ if (reported || next.message !== challenge.message) this.show((challenge = next));
167
+ await this.sleep(this.pollIntervalMs, minPollIntervalMs);
168
+ }
169
+ } finally {
170
+ this.shown?.resolve();
171
+ }
172
+ }
173
+
174
+ /** Shows `challenge` in place of the prompt before, without waiting for the answer. */
175
+ private show(challenge: TanChallenge): void {
176
+ this.shown?.resolve();
177
+ const shown = (this.shown = new Deferred<void>());
178
+ const report = (this.report = this.userConfirms ? new Deferred<void>() : undefined);
179
+ // Asked a microtask later: the app closes the prompt before on its `resolved` first, and then opens this one.
180
+ void Promise.resolve()
181
+ .then(() => this.hooks.ask(withResolved(challenge, shown.promise)))
182
+ .then(
183
+ (answer) => {
184
+ if (shown.isCompleted) return;
185
+ switch (answer.kind) {
186
+ case 'cancelled':
187
+ this.stop(new FinTsTanCancelledError());
188
+ break;
189
+ case 'approved':
190
+ report?.resolve();
191
+ break;
192
+ case 'tan':
193
+ if (report !== undefined) this.stop(tanForApproval());
194
+ break;
195
+ // The user cannot report the approval: the client waits for the bank.
196
+ }
197
+ },
198
+ (error: unknown) => {
199
+ if (!shown.isCompleted) this.stop(error);
200
+ },
201
+ );
202
+ }
203
+
204
+ private stop(error: unknown): void {
205
+ if (this.stopped.isCompleted) return;
206
+ this.stopReason = { error };
207
+ this.stopped.resolve();
208
+ }
209
+
210
+ private throwIfStopped(): void {
211
+ if (this.stopReason !== undefined) throw this.stopReason.error;
212
+ }
213
+
214
+ /**
215
+ * Waits for `delayMs`, or until the user cancels or reports the approval; a report does not cut the wait below
216
+ * `floorMs`. A wait cut short counts towards the longest wait with its floor only.
217
+ */
218
+ private async sleep(delayMs: number, floorMs = 0): Promise<void> {
219
+ const report = this.report;
220
+ if (floorMs > 0) await this.hooks.pause(floorMs, this.stopped.promise);
221
+ const interrupt =
222
+ report === undefined ? this.stopped.promise : Promise.race([this.stopped.promise, report.promise]);
223
+ await this.hooks.pause(delayMs - floorMs, interrupt);
224
+ const cutShort = report?.isCompleted ?? false;
225
+ this.waitedMs += cutShort ? floorMs : delayMs;
226
+ // One report, one early request.
227
+ if (cutShort) this.report = undefined;
228
+ }
229
+ }
230
+
231
+ /**
232
+ * The client asks the bank after each report of the user; while the approval is pending, the user is asked again with
233
+ * the bank's latest instructions.
234
+ */
235
+ class PollingAfterReports<R extends StatusAnswer> extends AppApprovalWait<R> {
236
+ async run(): Promise<R> {
237
+ let challenge = this.approval.challenge;
238
+ await this.confirm(challenge);
239
+ for (;;) {
240
+ const response = await this.requestStatus();
241
+ if (!isPending(response)) return response;
242
+ challenge = this.nextPrompt(challenge, response);
243
+ // The prompt comes back at once; however fast the user reports again, the next request waits a second.
244
+ await Promise.all([this.confirm(challenge), this.hooks.pause(minPollIntervalMs)]);
245
+ this.waitedMs += minPollIntervalMs;
246
+ }
247
+ }
248
+
249
+ /** Shows `challenge` and waits until the user reports the approval or cancels. */
250
+ private async confirm(challenge: TanChallenge): Promise<void> {
251
+ const answer = await this.hooks.ask(challenge);
252
+ switch (answer.kind) {
253
+ case 'approved':
254
+ return;
255
+ case 'cancelled':
256
+ throw new FinTsTanCancelledError();
257
+ case 'tan':
258
+ throw tanForApproval();
259
+ }
260
+ }
261
+ }
262
+
263
+ /** Whether `response` tells that the approval is still pending (return code 3956). */
264
+ function isPending(response: StatusAnswer): boolean {
265
+ return hasCode(response.feedback, FeedbackCodes.decoupledStillPending);
266
+ }
267
+
268
+ function tanForApproval(): TypeError {
269
+ return invalidArgument('Answered an approval in the banking app with a TAN', 'tanCallback');
270
+ }
271
+
272
+ function seconds(value: number | undefined): number | undefined {
273
+ return value === undefined ? undefined : value * 1000;
274
+ }
275
+
276
+ function clamp(value: number, min: number, max: number): number {
277
+ return value < min ? min : value > max ? max : value;
278
+ }
@@ -0,0 +1,122 @@
1
+ import { FinTsBankError, FinTsProtocolError, parseBankData } from '../core/errors.js';
2
+ import { continuations, FeedbackCodes, hasCode } from '../core/feedback.js';
3
+ import type { IncomingMessage3 } from '../v3/message.js';
4
+ import type { Query } from '../v3/queries.js';
5
+ import type { SegmentSpec } from '../v3/syntax.js';
6
+ import type { SessionSetup } from './session-setup.js';
7
+ import type { SignedDialog } from './signed-dialog.js';
8
+
9
+ /** Most pages the client fetches for one query, far more than banks send. */
10
+ const maxPages = 1000;
11
+
12
+ /**
13
+ * Most data one query may hold, summed over its pages as `IncomingMessage3.size` measures it: the transport and the
14
+ * parser bound a single response only. The statements and transactions read from them have a budget of their own
15
+ * (`RecordBudget`).
16
+ */
17
+ const maxQueryMebibytes = 128;
18
+
19
+ /**
20
+ * Keeps one dialog open for all calls and runs the queries in it.
21
+ *
22
+ * A dialog the bank has ended is not used again: the call that learns of it fails, and the next call logs in anew. The
23
+ * client does not repeat the call by itself, since the bank's answer cannot tell a dialog that had ended before from an
24
+ * order it refuses along with ending the dialog, and a new login may cost the user another approval.
25
+ */
26
+ export class DialogRunner {
27
+ private dialog: SignedDialog | undefined;
28
+
29
+ constructor(private readonly setup: SessionSetup) {}
30
+
31
+ /** The open dialog, or a new one once the setup is complete and the user has passed strong authentication. */
32
+ async open(): Promise<SignedDialog> {
33
+ const current = this.dialog;
34
+ if (current?.isActive === true) return current;
35
+ this.dialog = undefined;
36
+ const dialog = await this.setup.remedied(() => this.login());
37
+ this.dialog = dialog;
38
+ return dialog;
39
+ }
40
+
41
+ private async login(): Promise<SignedDialog> {
42
+ const dialog = await this.setup.newDialog();
43
+ try {
44
+ await dialog.login();
45
+ return dialog;
46
+ } catch (error) {
47
+ // After a refused login the dialog is discarded already, and ending it sends nothing. After any other failure,
48
+ // such as a cancelled TAN, the bank still knows the dialog.
49
+ await dialog.end();
50
+ throw error;
51
+ }
52
+ }
53
+
54
+ /** Ends the open dialog, if there is one. */
55
+ async end(): Promise<void> {
56
+ const dialog = this.dialog;
57
+ this.dialog = undefined;
58
+ await dialog?.end();
59
+ }
60
+
61
+ /**
62
+ * Runs the query `build` returns in the session's dialog and reads all its pages.
63
+ *
64
+ * The query is built once the dialog is open, since building it takes the parameter data.
65
+ */
66
+ async query<T>(build: () => Query<T>): Promise<T> {
67
+ const dialog = await this.open();
68
+ const query = build();
69
+ const pages = await this.fetchPages(dialog, query.order);
70
+ return parseBankData(() => query.read(pages));
71
+ }
72
+
73
+ /** Sends `order` in `dialog` and completes its approval, which only the `firstPage` of a query may ask for. */
74
+ private async run(dialog: SignedDialog, order: SegmentSpec, firstPage: boolean): Promise<IncomingMessage3> {
75
+ try {
76
+ return firstPage ? await dialog.send(order) : await dialog.sendFurtherPage(order);
77
+ } catch (error) {
78
+ // The bank rejected the order and the dialog stays usable, or the bank ended the dialog or rejected the PIN and
79
+ // the dialog is discarded already. A cancelled or failed approval, or a broken connection, leaves the dialog in an
80
+ // unknown state.
81
+ if (!(error instanceof FinTsBankError)) await this.end();
82
+ throw error;
83
+ }
84
+ }
85
+
86
+ /** Sends the order built by `order` until the bank has delivered all pages (Formals B.6.3, "Aufsetzpunkt"). */
87
+ private async fetchPages(
88
+ dialog: SignedDialog,
89
+ order: (continuation: string | undefined) => SegmentSpec,
90
+ ): Promise<IncomingMessage3[]> {
91
+ const pages: IncomingMessage3[] = [];
92
+ const seen = new Set<string>();
93
+ let size = 0;
94
+ let continuation: string | undefined;
95
+ for (;;) {
96
+ const page = await this.run(dialog, order(continuation), continuation === undefined);
97
+ pages.push(page);
98
+ size += page.size;
99
+ if (size > maxQueryMebibytes * 1024 * 1024) {
100
+ throw new FinTsProtocolError(
101
+ `The bank sends more than ${maxQueryMebibytes} MiB for one query; ask for a shorter period`,
102
+ );
103
+ }
104
+ const positions = [...continuations(page.feedback)];
105
+ // A message carries one order, so the bank names one position at most.
106
+ if (positions.length > 1) throw new FinTsProtocolError('The bank names several positions to continue at');
107
+ continuation = positions[0];
108
+ if (continuation === undefined) {
109
+ // Read as the last page, more data without a position would look like all there is.
110
+ if (hasCode(page.feedback, FeedbackCodes.moreData)) {
111
+ throw new FinTsProtocolError('The bank has more data, but names no position to continue at');
112
+ }
113
+ return pages;
114
+ }
115
+ // A repeated position or endless pages would keep the client busy forever.
116
+ if (seen.has(continuation) || pages.length === maxPages) {
117
+ throw new FinTsProtocolError('The bank does not stop sending pages');
118
+ }
119
+ seen.add(continuation);
120
+ }
121
+ }
122
+ }
@@ -0,0 +1,221 @@
1
+ import {
2
+ clientClosedError,
3
+ FinTsLoginDataChangedError,
4
+ FinTsLoginRefusedError,
5
+ FinTsPinError,
6
+ loginRefusalFor,
7
+ type FinTsBankError,
8
+ } from '../core/errors.js';
9
+ import { allowedTanMethodsIn, FeedbackCodes, hasCode, type FinTsFeedback } from '../core/feedback.js';
10
+ import type { TanMethod } from '../tan/tan-models.js';
11
+ import type { PinGuard } from '../v3/protocol.js';
12
+
13
+ /**
14
+ * The kind of request a bank response answers, which decides what its errors mean for the login (`LoginGuard.judge`)
15
+ * and whether they can reject a TAN:
16
+ * - `login`: the login that opens a dialog, which carries no order;
17
+ * - `order`: an order in a dialog the bank has opened;
18
+ * - `approval`: a message that completes an approval, the TAN or the question whether the user approved in the app.
19
+ */
20
+ export type RequestKind = 'login' | 'order' | 'approval';
21
+
22
+ /**
23
+ * A reason for a refused login that the session can take care of by itself, after which it logs in once more: the user
24
+ * may not use the TAN method the login was signed with, or the bank no longer accepts the customer system ID.
25
+ */
26
+ export type RefusalReason = 'tanMethodNotAllowed' | 'systemIdRejected';
27
+
28
+ /** What the saved state keeps of the guard: the return codes of the bank's refusal, and `unreadLogins`. */
29
+ export interface LoginGuardState {
30
+ readonly refusal: readonly FinTsFeedback[] | undefined;
31
+ readonly unreadLogins: number;
32
+ }
33
+
34
+ /**
35
+ * Logins in a row whose answer the client could not read, after which it sends the PIN no more: one may be a glitch of
36
+ * the connection, but with two the client would not learn of a wrong PIN before the bank locks the access.
37
+ */
38
+ const maxUnreadLogins = 2;
39
+
40
+ /**
41
+ * Holds the PIN and hands it out only while no login is refused (`pin`), so that a retrying app cannot lock the user's
42
+ * access. `FinTsLoginRefusedError` tells which logins count as refused; `judge` decides it for each answer.
43
+ *
44
+ * A refusal counts at once and fails closed: only `remedied` lifts it, within the call that met it (`runCall`), once
45
+ * the session has taken care of a reason it names, each reason once per call, so that a call sends at most three
46
+ * logins the bank refuses. A refusal that outlasts the call is final, and the guard forgets the PIN; only a PIN the
47
+ * user enters anew lifts it (`replacePin`), unless it brings new login data.
48
+ */
49
+ export class LoginGuard implements PinGuard {
50
+ // ECMAScript private, so that neither `util.inspect` nor `JSON.stringify` of the client reaches it.
51
+ #pin: string | undefined;
52
+
53
+ private refusalValue: FinTsLoginRefusedError | undefined;
54
+
55
+ /** The TAN method of the login `refusalValue` refused, which a restored refusal does not tell. */
56
+ private refusedMethod: TanMethod | undefined;
57
+
58
+ /** Logins sent since the bank last took the PIN whose answer the client has not read. */
59
+ private unreadLogins = 0;
60
+
61
+ /** The refusal of `maxUnreadLogins` unread logins, kept so that `check` throws the same error each time. */
62
+ private unreadLoginsRefusal: FinTsLoginRefusedError | undefined;
63
+
64
+ /** The reasons `remedied` has lifted a refusal for in the running call. */
65
+ private readonly pardonedReasons = new Set<RefusalReason>();
66
+
67
+ constructor(pin: string) {
68
+ this.#pin = pin;
69
+ }
70
+
71
+ /** The PIN to sign a message with; throws the refusal instead (`check`), and `FinTsStateError` once closed. */
72
+ get pin(): string {
73
+ this.check();
74
+ if (this.#pin === undefined) throw clientClosedError();
75
+ return this.#pin;
76
+ }
77
+
78
+ /** Throws the refusal, if there is one. */
79
+ check(): void {
80
+ const refusal = this.refusal;
81
+ if (refusal !== undefined) throw refusal;
82
+ }
83
+
84
+ /** The bank's refusal, else that of `maxUnreadLogins` unread logins; `undefined` while there is none. */
85
+ get refusal(): FinTsLoginRefusedError | undefined {
86
+ if (this.refusalValue !== undefined || this.unreadLogins < maxUnreadLogins) return this.refusalValue;
87
+ this.unreadLoginsRefusal ??= new FinTsLoginRefusedError(
88
+ [],
89
+ `The answers to the last ${maxUnreadLogins} logins were lost or unreadable, and the bank may have counted them ` +
90
+ 'as failed attempts',
91
+ );
92
+ return this.unreadLoginsRefusal;
93
+ }
94
+
95
+ /** Counts a login signed with the PIN as unread until `judge` reads its answer. */
96
+ loginSent(): void {
97
+ this.unreadLogins++;
98
+ }
99
+
100
+ /**
101
+ * Judges `error`, if the answer to a request of `kind` in a dialog signed with `method` has one: returns the refusal
102
+ * of the login it amounts to, and records it unless the guard holds one already. Any error refuses a login; after the
103
+ * login only one that refuses it itself, a rejected PIN or new login data, since the bank checked the PIN before.
104
+ */
105
+ judge(error: FinTsBankError | undefined, kind: RequestKind, method: TanMethod): FinTsLoginRefusedError | undefined {
106
+ const refused = error instanceof FinTsLoginRefusedError || (error !== undefined && kind === 'login');
107
+ if (kind === 'login') this.unreadLogins = refused ? Math.max(0, this.unreadLogins - 1) : 0;
108
+ if (!refused) return undefined;
109
+ const refusal = loginRefusalFor(error.feedback);
110
+ if (this.refusalValue === undefined) {
111
+ this.refusalValue = refusal;
112
+ this.refusedMethod = method;
113
+ }
114
+ return refusal;
115
+ }
116
+
117
+ /** Runs `call`, one call of the client; a refusal that outlasts it is final, and the next call remedies anew. */
118
+ async runCall<T>(call: () => Promise<T>): Promise<T> {
119
+ try {
120
+ return await call();
121
+ } finally {
122
+ this.pardonedReasons.clear();
123
+ this.forgetPinIfRefused();
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Runs `attempt`, which may log in, and runs it once more each time `remedy` takes care of a reason the refusal it
129
+ * failed with names; `remedy` gets the reason and the TAN method of the refused login, and returns whether it could.
130
+ */
131
+ async remedied<T>(
132
+ attempt: () => Promise<T>,
133
+ remedy: (reason: RefusalReason, rejected: TanMethod) => Promise<boolean>,
134
+ ): Promise<T> {
135
+ // A refusal of an earlier call stops the attempt before it sends the PIN; there is nothing to remedy.
136
+ if (this.refusal !== undefined) return attempt();
137
+ for (;;) {
138
+ try {
139
+ return await attempt();
140
+ } catch (error) {
141
+ const refusal = this.refusalValue;
142
+ const rejected = this.refusedMethod;
143
+ // Only the bank's refusal the guard holds names reasons; any other error, a second refusal too, fails the call.
144
+ if (refusal === undefined || error !== refusal || rejected === undefined) throw error;
145
+ const reason = remediableReasons(refusal, rejected).find((r) => !this.pardonedReasons.has(r));
146
+ if (reason === undefined || !(await remedy(reason, rejected))) throw error;
147
+ this.pardonedReasons.add(reason);
148
+ // A closed client keeps the refusal.
149
+ if (this.#pin !== undefined) this.liftRefusal();
150
+ }
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Signs with `pin` from now on, a PIN the user has entered anew and the protocol can send, and lifts the refusal.
156
+ * Throws the refusal instead where it brings new login data, which end the old ones for good.
157
+ */
158
+ replacePin(pin: string): void {
159
+ if (this.refusalValue instanceof FinTsLoginDataChangedError) throw this.refusalValue;
160
+ this.#pin = pin;
161
+ this.liftRefusal();
162
+ this.unreadLogins = 0;
163
+ this.unreadLoginsRefusal = undefined;
164
+ }
165
+
166
+ /** Forgets the PIN; the client calls it once it is closed. */
167
+ close(): void {
168
+ this.#pin = undefined;
169
+ }
170
+
171
+ saveState(): LoginGuardState {
172
+ return { refusal: this.refusalValue?.feedback, unreadLogins: this.unreadLogins };
173
+ }
174
+
175
+ /** Restores what `saveState` returned; a restored refusal is final. */
176
+ restoreState(saved: LoginGuardState): void {
177
+ if (saved.refusal !== undefined) this.refusalValue = loginRefusalFor(saved.refusal);
178
+ this.unreadLogins = Math.max(0, saved.unreadLogins);
179
+ this.forgetPinIfRefused();
180
+ }
181
+
182
+ private liftRefusal(): void {
183
+ this.refusalValue = undefined;
184
+ this.refusedMethod = undefined;
185
+ }
186
+
187
+ private forgetPinIfRefused(): void {
188
+ if (this.refusal !== undefined) this.#pin = undefined;
189
+ }
190
+ }
191
+
192
+ /**
193
+ * The reasons `refusal`, of a login signed with `method`, names that the session can take care of: a TAN method the
194
+ * refusal names as not allowed (`refusesMethod`), and 9391. None for a rejected PIN or new login data.
195
+ */
196
+ function remediableReasons(refusal: FinTsLoginRefusedError, method: TanMethod): RefusalReason[] {
197
+ if (refusal instanceof FinTsPinError || refusal instanceof FinTsLoginDataChangedError) return [];
198
+ const reasons: RefusalReason[] = [];
199
+ if (refusesMethod(refusal.feedback, method)) reasons.push('tanMethodNotAllowed');
200
+ if (hasCode(refusal.feedback, FeedbackCodes.newSystemIdRequired)) reasons.push('systemIdRejected');
201
+ return reasons;
202
+ }
203
+
204
+ /** Error codes that only say that the message failed, not why: 9050 (the message contains errors) and 9800. */
205
+ const unspecificErrors = new Set(['9050', FeedbackCodes.dialogAborted]);
206
+
207
+ /**
208
+ * Whether `feedback`, which refuses a login signed with `method`, names the method as the reason: a 3920 that lists the
209
+ * methods the user may use without it, or 9075 after the one-step method.
210
+ *
211
+ * Only the return codes of the refusal itself count: TAN methods listed earlier say nothing about this login. Banks
212
+ * list two-step methods only, so a 3920 always leaves the one-step method out, also where the login succeeds. After
213
+ * the one-step method a 3920 counts only where the bank names no other error than an unspecific one: any other, such
214
+ * as "Anmeldung fehlgeschlagen", may be about the PIN.
215
+ */
216
+ function refusesMethod(feedback: readonly FinTsFeedback[], method: TanMethod): boolean {
217
+ if (method.isOneStep && hasCode(feedback, FeedbackCodes.scaRequired)) return true;
218
+ const allowed = allowedTanMethodsIn(feedback);
219
+ if (allowed.length === 0 || allowed.includes(method.securityFunction)) return false;
220
+ return !method.isOneStep || feedback.every((f) => !f.isError || unspecificErrors.has(f.code));
221
+ }