@coderoftime/fints 0.0.0-stage → 0.1.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/CHANGELOG.md +11 -0
- package/LICENSE +28 -0
- package/README.md +156 -2
- package/dist/core/account.d.ts +140 -0
- package/dist/core/account.d.ts.map +1 -0
- package/dist/core/account.js +174 -0
- package/dist/core/account.js.map +1 -0
- package/dist/core/amount.d.ts +62 -0
- package/dist/core/amount.d.ts.map +1 -0
- package/dist/core/amount.js +189 -0
- package/dist/core/amount.js.map +1 -0
- package/dist/core/balance.d.ts +54 -0
- package/dist/core/balance.d.ts.map +1 -0
- package/dist/core/balance.js +53 -0
- package/dist/core/balance.js.map +1 -0
- package/dist/core/bank-info.d.ts +49 -0
- package/dist/core/bank-info.d.ts.map +1 -0
- package/dist/core/bank-info.js +52 -0
- package/dist/core/bank-info.js.map +1 -0
- package/dist/core/client.d.ts +126 -0
- package/dist/core/client.d.ts.map +1 -0
- package/dist/core/client.js +2 -0
- package/dist/core/client.js.map +1 -0
- package/dist/core/config.d.ts +68 -0
- package/dist/core/config.d.ts.map +1 -0
- package/dist/core/config.js +113 -0
- package/dist/core/config.js.map +1 -0
- package/dist/core/errors.d.ts +91 -0
- package/dist/core/errors.d.ts.map +1 -0
- package/dist/core/errors.js +182 -0
- package/dist/core/errors.js.map +1 -0
- package/dist/core/feedback.d.ts +69 -0
- package/dist/core/feedback.d.ts.map +1 -0
- package/dist/core/feedback.js +124 -0
- package/dist/core/feedback.js.map +1 -0
- package/dist/core/transaction.d.ts +98 -0
- package/dist/core/transaction.d.ts.map +1 -0
- package/dist/core/transaction.js +91 -0
- package/dist/core/transaction.js.map +1 -0
- package/dist/core/transport.d.ts +37 -0
- package/dist/core/transport.d.ts.map +1 -0
- package/dist/core/transport.js +92 -0
- package/dist/core/transport.js.map +1 -0
- package/dist/formats/camt.d.ts +12 -0
- package/dist/formats/camt.d.ts.map +1 -0
- package/dist/formats/camt.js +159 -0
- package/dist/formats/camt.js.map +1 -0
- package/dist/formats/mt940.d.ts +42 -0
- package/dist/formats/mt940.d.ts.map +1 -0
- package/dist/formats/mt940.js +297 -0
- package/dist/formats/mt940.js.map +1 -0
- package/dist/formats/readers.d.ts +11 -0
- package/dist/formats/readers.d.ts.map +1 -0
- package/dist/formats/readers.js +47 -0
- package/dist/formats/readers.js.map +1 -0
- package/dist/formats/sepa-purpose.d.ts +22 -0
- package/dist/formats/sepa-purpose.d.ts.map +1 -0
- package/dist/formats/sepa-purpose.js +68 -0
- package/dist/formats/sepa-purpose.js.map +1 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/dist/session/app-approval.d.ts +60 -0
- package/dist/session/app-approval.d.ts.map +1 -0
- package/dist/session/app-approval.js +215 -0
- package/dist/session/app-approval.js.map +1 -0
- package/dist/session/bank-connection.d.ts +28 -0
- package/dist/session/bank-connection.d.ts.map +1 -0
- package/dist/session/bank-connection.js +48 -0
- package/dist/session/bank-connection.js.map +1 -0
- package/dist/session/dialog-runner.d.ts +34 -0
- package/dist/session/dialog-runner.d.ts.map +1 -0
- package/dist/session/dialog-runner.js +112 -0
- package/dist/session/dialog-runner.js.map +1 -0
- package/dist/session/login-guard.d.ts +73 -0
- package/dist/session/login-guard.d.ts.map +1 -0
- package/dist/session/login-guard.js +109 -0
- package/dist/session/login-guard.js.map +1 -0
- package/dist/session/parameter-data.d.ts +83 -0
- package/dist/session/parameter-data.d.ts.map +1 -0
- package/dist/session/parameter-data.js +68 -0
- package/dist/session/parameter-data.js.map +1 -0
- package/dist/session/pin-tan-client.d.ts +54 -0
- package/dist/session/pin-tan-client.d.ts.map +1 -0
- package/dist/session/pin-tan-client.js +153 -0
- package/dist/session/pin-tan-client.js.map +1 -0
- package/dist/session/pin-tan-dialog.d.ts +71 -0
- package/dist/session/pin-tan-dialog.d.ts.map +1 -0
- package/dist/session/pin-tan-dialog.js +124 -0
- package/dist/session/pin-tan-dialog.js.map +1 -0
- package/dist/session/protocol.d.ts +209 -0
- package/dist/session/protocol.d.ts.map +1 -0
- package/dist/session/protocol.js +75 -0
- package/dist/session/protocol.js.map +1 -0
- package/dist/session/response-handler.d.ts +48 -0
- package/dist/session/response-handler.d.ts.map +1 -0
- package/dist/session/response-handler.js +121 -0
- package/dist/session/response-handler.js.map +1 -0
- package/dist/session/sepa-accounts.d.ts +34 -0
- package/dist/session/sepa-accounts.d.ts.map +1 -0
- package/dist/session/sepa-accounts.js +96 -0
- package/dist/session/sepa-accounts.js.map +1 -0
- package/dist/session/session-setup.d.ts +72 -0
- package/dist/session/session-setup.d.ts.map +1 -0
- package/dist/session/session-setup.js +160 -0
- package/dist/session/session-setup.js.map +1 -0
- package/dist/session/session-state.d.ts +47 -0
- package/dist/session/session-state.d.ts.map +1 -0
- package/dist/session/session-state.js +147 -0
- package/dist/session/session-state.js.map +1 -0
- package/dist/session/tan-selection.d.ts +88 -0
- package/dist/session/tan-selection.d.ts.map +1 -0
- package/dist/session/tan-selection.js +178 -0
- package/dist/session/tan-selection.js.map +1 -0
- package/dist/session/user-prompts.d.ts +61 -0
- package/dist/session/user-prompts.d.ts.map +1 -0
- package/dist/session/user-prompts.js +164 -0
- package/dist/session/user-prompts.js.map +1 -0
- package/dist/tan/challenge.d.ts +114 -0
- package/dist/tan/challenge.d.ts.map +1 -0
- package/dist/tan/challenge.js +185 -0
- package/dist/tan/challenge.js.map +1 -0
- package/dist/tan/flicker.d.ts +36 -0
- package/dist/tan/flicker.d.ts.map +1 -0
- package/dist/tan/flicker.js +262 -0
- package/dist/tan/flicker.js.map +1 -0
- package/dist/tan/tan-image.d.ts +21 -0
- package/dist/tan/tan-image.d.ts.map +1 -0
- package/dist/tan/tan-image.js +41 -0
- package/dist/tan/tan-image.js.map +1 -0
- package/dist/tan/tan-models.d.ts +145 -0
- package/dist/tan/tan-models.d.ts.map +1 -0
- package/dist/tan/tan-models.js +148 -0
- package/dist/tan/tan-models.js.map +1 -0
- package/dist/util/async.d.ts +24 -0
- package/dist/util/async.d.ts.map +1 -0
- package/dist/util/async.js +49 -0
- package/dist/util/async.js.map +1 -0
- package/dist/util/bytes.d.ts +23 -0
- package/dist/util/bytes.d.ts.map +1 -0
- package/dist/util/bytes.js +136 -0
- package/dist/util/bytes.js.map +1 -0
- package/dist/util/call-context.d.ts +12 -0
- package/dist/util/call-context.d.ts.map +1 -0
- package/dist/util/call-context.js +29 -0
- package/dist/util/call-context.js.map +1 -0
- package/dist/util/dates.d.ts +62 -0
- package/dist/util/dates.d.ts.map +1 -0
- package/dist/util/dates.js +169 -0
- package/dist/util/dates.js.map +1 -0
- package/dist/util/errors.d.ts +9 -0
- package/dist/util/errors.d.ts.map +1 -0
- package/dist/util/errors.js +15 -0
- package/dist/util/errors.js.map +1 -0
- package/dist/util/immutable-map.d.ts +16 -0
- package/dist/util/immutable-map.d.ts.map +1 -0
- package/dist/util/immutable-map.js +38 -0
- package/dist/util/immutable-map.js.map +1 -0
- package/dist/util/json.d.ts +13 -0
- package/dist/util/json.d.ts.map +1 -0
- package/dist/util/json.js +44 -0
- package/dist/util/json.js.map +1 -0
- package/dist/util/text.d.ts +20 -0
- package/dist/util/text.d.ts.map +1 -0
- package/dist/util/text.js +78 -0
- package/dist/util/text.js.map +1 -0
- package/dist/util/xml.d.ts +35 -0
- package/dist/util/xml.d.ts.map +1 -0
- package/dist/util/xml.js +183 -0
- package/dist/util/xml.js.map +1 -0
- package/dist/v3/account-extension.d.ts +25 -0
- package/dist/v3/account-extension.d.ts.map +1 -0
- package/dist/v3/account-extension.js +176 -0
- package/dist/v3/account-extension.js.map +1 -0
- package/dist/v3/client.d.ts +24 -0
- package/dist/v3/client.d.ts.map +1 -0
- package/dist/v3/client.js +16 -0
- package/dist/v3/client.js.map +1 -0
- package/dist/v3/dialog.d.ts +78 -0
- package/dist/v3/dialog.d.ts.map +1 -0
- package/dist/v3/dialog.js +138 -0
- package/dist/v3/dialog.js.map +1 -0
- package/dist/v3/message.d.ts +72 -0
- package/dist/v3/message.d.ts.map +1 -0
- package/dist/v3/message.js +259 -0
- package/dist/v3/message.js.map +1 -0
- package/dist/v3/parameters.d.ts +79 -0
- package/dist/v3/parameters.d.ts.map +1 -0
- package/dist/v3/parameters.js +396 -0
- package/dist/v3/parameters.js.map +1 -0
- package/dist/v3/protocol.d.ts +68 -0
- package/dist/v3/protocol.d.ts.map +1 -0
- package/dist/v3/protocol.js +263 -0
- package/dist/v3/protocol.js.map +1 -0
- package/dist/v3/segments.d.ts +89 -0
- package/dist/v3/segments.d.ts.map +1 -0
- package/dist/v3/segments.js +283 -0
- package/dist/v3/segments.js.map +1 -0
- package/dist/v3/syntax.d.ts +76 -0
- package/dist/v3/syntax.d.ts.map +1 -0
- package/dist/v3/syntax.js +301 -0
- package/dist/v3/syntax.js.map +1 -0
- package/package.json +63 -4
- package/src/core/account.ts +250 -0
- package/src/core/amount.ts +209 -0
- package/src/core/balance.ts +84 -0
- package/src/core/bank-info.ts +66 -0
- package/src/core/client.ts +149 -0
- package/src/core/config.ts +141 -0
- package/src/core/errors.ts +203 -0
- package/src/core/feedback.ts +137 -0
- package/src/core/transaction.ts +156 -0
- package/src/core/transport.ts +114 -0
- package/src/formats/camt.ts +169 -0
- package/src/formats/mt940.ts +333 -0
- package/src/formats/readers.ts +56 -0
- package/src/formats/sepa-purpose.ts +75 -0
- package/src/index.ts +68 -0
- package/src/session/app-approval.ts +265 -0
- package/src/session/bank-connection.ts +51 -0
- package/src/session/dialog-runner.ts +119 -0
- package/src/session/login-guard.ts +135 -0
- package/src/session/parameter-data.ts +137 -0
- package/src/session/pin-tan-client.ts +186 -0
- package/src/session/pin-tan-dialog.ts +160 -0
- package/src/session/protocol.ts +311 -0
- package/src/session/response-handler.ts +130 -0
- package/src/session/sepa-accounts.ts +97 -0
- package/src/session/session-setup.ts +165 -0
- package/src/session/session-state.ts +170 -0
- package/src/session/tan-selection.ts +192 -0
- package/src/session/user-prompts.ts +174 -0
- package/src/tan/challenge.ts +252 -0
- package/src/tan/flicker.ts +270 -0
- package/src/tan/tan-image.ts +36 -0
- package/src/tan/tan-models.ts +247 -0
- package/src/util/async.ts +53 -0
- package/src/util/bytes.ts +135 -0
- package/src/util/call-context.ts +40 -0
- package/src/util/dates.ts +193 -0
- package/src/util/errors.ts +16 -0
- package/src/util/immutable-map.ts +47 -0
- package/src/util/json.ts +51 -0
- package/src/util/text.ts +82 -0
- package/src/util/xml.ts +172 -0
- package/src/v3/account-extension.ts +190 -0
- package/src/v3/client.ts +29 -0
- package/src/v3/dialog.ts +199 -0
- package/src/v3/message.ts +321 -0
- package/src/v3/parameters.ts +451 -0
- package/src/v3/protocol.ts +331 -0
- package/src/v3/segments.ts +331 -0
- package/src/v3/syntax.ts +307 -0
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import type { BankMessage } from '../core/bank-info.js';
|
|
2
|
+
import type { FinTsClientOptions, MessageLogger } from '../core/client.js';
|
|
3
|
+
import { FinTsStateError } from '../core/errors.js';
|
|
4
|
+
import type { FinTsFeedback } from '../core/feedback.js';
|
|
5
|
+
import type { TanAnswer, TanChallenge } from '../tan/challenge.js';
|
|
6
|
+
import type { TanMedium, TanMethod } from '../tan/tan-models.js';
|
|
7
|
+
import { Deferred } from '../util/async.js';
|
|
8
|
+
import { invalidArgument } from '../util/errors.js';
|
|
9
|
+
|
|
10
|
+
function closedError(): FinTsStateError {
|
|
11
|
+
return new FinTsStateError('The FinTS client is closed');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Everything a session tells the app, asks of it or waits for: the bank's messages, warnings and log, the TAN callback,
|
|
16
|
+
* the selectors and the pauses between status requests.
|
|
17
|
+
*
|
|
18
|
+
* Once the client is closed nothing is told or asked, and every wait ends with `FinTsStateError`. Errors of the
|
|
19
|
+
* callbacks that only inform the app wait for `reportingCallbackErrors`, as `FinTsClientOptions` promises.
|
|
20
|
+
*/
|
|
21
|
+
export class UserPrompts {
|
|
22
|
+
private closed = false;
|
|
23
|
+
|
|
24
|
+
/** The first error an informing callback threw during the running call. */
|
|
25
|
+
private callbackError: { error: unknown } | undefined;
|
|
26
|
+
|
|
27
|
+
/** Aborts the waits under way; each wait removes its abort when it is over. */
|
|
28
|
+
private readonly aborts = new Set<() => void>();
|
|
29
|
+
|
|
30
|
+
constructor(private readonly options: FinTsClientOptions) {}
|
|
31
|
+
|
|
32
|
+
/** Ends every wait; the client calls it once. */
|
|
33
|
+
close(): void {
|
|
34
|
+
this.closed = true;
|
|
35
|
+
for (const abort of [...this.aborts]) abort();
|
|
36
|
+
this.aborts.clear();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Throws `FinTsStateError` once `close` was called. */
|
|
40
|
+
checkOpen(): void {
|
|
41
|
+
if (this.closed) throw closedError();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Runs `call` and then fails it with the first error an informing callback threw meanwhile; an error of `call` itself
|
|
46
|
+
* takes precedence.
|
|
47
|
+
*/
|
|
48
|
+
async reportingCallbackErrors<T>(call: () => Promise<T>): Promise<T> {
|
|
49
|
+
this.callbackError = undefined;
|
|
50
|
+
const result = await call();
|
|
51
|
+
// Set by a callback while `call` ran, which the compiler cannot see.
|
|
52
|
+
const failure = this.callbackError as { error: unknown } | undefined;
|
|
53
|
+
if (failure !== undefined) throw failure.error;
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The app's logger, whose errors are kept for `reportingCallbackErrors`; `undefined` without one. */
|
|
58
|
+
get logger(): MessageLogger | undefined {
|
|
59
|
+
const logger = this.options.logger;
|
|
60
|
+
if (logger === undefined) return undefined;
|
|
61
|
+
return (direction, message) => {
|
|
62
|
+
this.inform(() => {
|
|
63
|
+
logger(direction, message);
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Passes the bank's `message` to the app, unless the client is closed. */
|
|
69
|
+
showBankMessage(message: BankMessage): void {
|
|
70
|
+
const handler = this.options.onBankMessage;
|
|
71
|
+
if (handler !== undefined && !this.closed) {
|
|
72
|
+
this.inform(() => {
|
|
73
|
+
handler(message);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Passes the bank's `warning` to the app, unless the client is closed. */
|
|
79
|
+
showWarning(warning: FinTsFeedback): void {
|
|
80
|
+
const handler = this.options.onWarning;
|
|
81
|
+
if (handler !== undefined && !this.closed) {
|
|
82
|
+
this.inform(() => {
|
|
83
|
+
handler(warning);
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private inform(callback: () => void): void {
|
|
89
|
+
try {
|
|
90
|
+
callback();
|
|
91
|
+
} catch (error) {
|
|
92
|
+
this.callbackError ??= { error };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Shows `challenge` through the TAN callback and returns its answer. */
|
|
97
|
+
askTan(challenge: TanChallenge): Promise<TanAnswer> {
|
|
98
|
+
return this.unlessClosed(() => this.options.tanCallback(challenge));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Waits for `delayMs` milliseconds, or until `interrupt` settles. */
|
|
102
|
+
pause(delayMs: number, interrupt?: Promise<unknown>): Promise<void> {
|
|
103
|
+
if (this.closed) return Promise.reject(closedError());
|
|
104
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
105
|
+
const elapsed = new Promise<void>((resolve) => {
|
|
106
|
+
timer = setTimeout(resolve, Math.max(0, delayMs));
|
|
107
|
+
});
|
|
108
|
+
// Neither an interrupted wait nor a closed client may leave a timer behind that keeps the process alive.
|
|
109
|
+
return this.unlessClosed(() =>
|
|
110
|
+
Promise.race([elapsed, ...(interrupt === undefined ? [] : [interrupt.then(() => undefined)])]),
|
|
111
|
+
).finally(() => {
|
|
112
|
+
clearTimeout(timer);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The TAN method to use among `candidates`: the app's choice, or the first without a selector or an answer.
|
|
118
|
+
*
|
|
119
|
+
* Throws `TypeError` if the selector returns a method that is not among `candidates`.
|
|
120
|
+
*/
|
|
121
|
+
async chooseMethod(candidates: readonly TanMethod[]): Promise<TanMethod> {
|
|
122
|
+
const selector = this.options.tanMethodSelector;
|
|
123
|
+
if (candidates.length === 1 || selector === undefined) return candidates[0]!;
|
|
124
|
+
const chosen = await this.unlessClosed(() => selector(candidates));
|
|
125
|
+
if (chosen === undefined) return candidates[0]!;
|
|
126
|
+
const match = candidates.find((m) => m.securityFunction === chosen.securityFunction);
|
|
127
|
+
if (match === undefined) throw invalidArgument('Returned a TAN method the bank did not offer', 'tanMethodSelector');
|
|
128
|
+
return match;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The TAN medium to use among the active `media`: the app's choice, or the first without a selector or an answer.
|
|
133
|
+
*
|
|
134
|
+
* Throws `TypeError` if the selector returns a medium that is not among `media`.
|
|
135
|
+
*/
|
|
136
|
+
async chooseMedium(media: readonly TanMedium[]): Promise<TanMedium> {
|
|
137
|
+
const selector = this.options.tanMediumSelector;
|
|
138
|
+
if (media.length === 1 || selector === undefined) return media[0]!;
|
|
139
|
+
const chosen = await this.unlessClosed(() => selector(media));
|
|
140
|
+
if (chosen === undefined) return media[0]!;
|
|
141
|
+
const match = media.find((m) => m.name === chosen.name);
|
|
142
|
+
if (match === undefined) throw invalidArgument('Returned a TAN medium the bank did not list', 'tanMediumSelector');
|
|
143
|
+
return match;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Starts `wait` and ends it with `FinTsStateError` if `close` is called before it is over.
|
|
148
|
+
*
|
|
149
|
+
* Once the client is closed, the returned promise rejects rather than this function throwing: a caller that starts
|
|
150
|
+
* several waits at once would otherwise leave the failure of those started first unheard.
|
|
151
|
+
*/
|
|
152
|
+
private unlessClosed<T>(wait: () => T | Promise<T>): Promise<T> {
|
|
153
|
+
if (this.closed) return Promise.reject(closedError());
|
|
154
|
+
const result = new Deferred<T>();
|
|
155
|
+
const abort = (): void => {
|
|
156
|
+
result.reject(closedError());
|
|
157
|
+
};
|
|
158
|
+
this.aborts.add(abort);
|
|
159
|
+
// Runs `wait` at once, as far as its first `await`, and turns an error it throws into a rejection.
|
|
160
|
+
const started = (async (): Promise<T> => wait())();
|
|
161
|
+
started
|
|
162
|
+
.then(
|
|
163
|
+
(value) => {
|
|
164
|
+
result.resolve(value);
|
|
165
|
+
},
|
|
166
|
+
(error: unknown) => {
|
|
167
|
+
result.reject(error);
|
|
168
|
+
},
|
|
169
|
+
)
|
|
170
|
+
.finally(() => this.aborts.delete(abort))
|
|
171
|
+
.catch(() => undefined);
|
|
172
|
+
return result.promise;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { latin1Decode } from '../util/bytes.js';
|
|
2
|
+
import { challengeInstruction, FlickerCode, hasEmbeddedFlickerCode } from './flicker.js';
|
|
3
|
+
import { TanImage } from './tan-image.js';
|
|
4
|
+
import type { TanMedium, TanMethod } from './tan-models.js';
|
|
5
|
+
|
|
6
|
+
/** Challenge text banks send when there is nothing to show. */
|
|
7
|
+
const noChallenge = 'nochallenge';
|
|
8
|
+
|
|
9
|
+
/** `message`, or `undefined` where it is empty or the filler banks send when there is nothing to show. */
|
|
10
|
+
export function challengeText(message: string | undefined): string | undefined {
|
|
11
|
+
return message === undefined || message === '' || message === noChallenge ? undefined : message;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const printableAscii = /^[\x20-\x7E]+$/;
|
|
15
|
+
const lineBreak = /<br\b[^<>]*>/gi;
|
|
16
|
+
const blockTag = /<\/?(?:p|li)\b[^<>]*>/gi;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The formatting tags a structured challenge may carry besides line breaks, paragraphs and list items (PIN/TAN, Data
|
|
20
|
+
* Dictionary "Challenge"). Angle brackets around anything else, such as `<50 EUR>`, are part of the text the user
|
|
21
|
+
* approves, so they stay. Excluding `<` and `>` from the tag keeps the search linear.
|
|
22
|
+
*/
|
|
23
|
+
const formattingTag = /<\/?(?:b|i|u|ul|ol)\b[^<>]*>/gi;
|
|
24
|
+
const entityReference = /&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g;
|
|
25
|
+
const blankLines = /\n{3,}/g;
|
|
26
|
+
|
|
27
|
+
const namedEntities: Record<string, string> = {
|
|
28
|
+
amp: '&',
|
|
29
|
+
lt: '<',
|
|
30
|
+
gt: '>',
|
|
31
|
+
quot: '"',
|
|
32
|
+
apos: "'",
|
|
33
|
+
nbsp: ' ',
|
|
34
|
+
auml: 'ä',
|
|
35
|
+
ouml: 'ö',
|
|
36
|
+
uuml: 'ü',
|
|
37
|
+
Auml: 'Ä',
|
|
38
|
+
Ouml: 'Ö',
|
|
39
|
+
Uuml: 'Ü',
|
|
40
|
+
szlig: 'ß',
|
|
41
|
+
euro: '€',
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The character `name` refers to; `undefined` for an unknown name and for a number that is not a character, as XML
|
|
46
|
+
* defines them: `NUL`, half a surrogate pair, or beyond Unicode.
|
|
47
|
+
*/
|
|
48
|
+
function decodeEntity(name: string): string | undefined {
|
|
49
|
+
if (name.startsWith('#')) {
|
|
50
|
+
const isHex = name.startsWith('#x') || name.startsWith('#X');
|
|
51
|
+
const digits = name.substring(isHex ? 2 : 1);
|
|
52
|
+
const code = (isHex ? /^[0-9a-fA-F]+$/ : /^[0-9]+$/).test(digits) ? parseInt(digits, isHex ? 16 : 10) : NaN;
|
|
53
|
+
const isCharacter = code > 0 && (code < 0xd800 || code > 0xdfff) && code <= 0x10ffff;
|
|
54
|
+
return isCharacter ? String.fromCodePoint(code) : undefined;
|
|
55
|
+
}
|
|
56
|
+
return Object.hasOwn(namedEntities, name) ? namedEntities[name] : undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** What `TanChallenge` takes. */
|
|
60
|
+
export interface TanChallengeInit {
|
|
61
|
+
method: TanMethod;
|
|
62
|
+
reference: string;
|
|
63
|
+
message?: string | undefined;
|
|
64
|
+
hhdUc?: Uint8Array | undefined;
|
|
65
|
+
flickerCode?: FlickerCode | undefined;
|
|
66
|
+
image?: TanImage | undefined;
|
|
67
|
+
isDecoupled?: boolean;
|
|
68
|
+
validUntil?: Date | undefined;
|
|
69
|
+
tanMediumName?: string | undefined;
|
|
70
|
+
attempt?: number;
|
|
71
|
+
resolved?: Promise<void> | undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A request from the bank to authorize an action with a TAN or an app approval. */
|
|
75
|
+
export class TanChallenge {
|
|
76
|
+
/** The TAN method the challenge is for. */
|
|
77
|
+
readonly method: TanMethod;
|
|
78
|
+
|
|
79
|
+
/** Bank reference of the pending action. */
|
|
80
|
+
readonly reference: string;
|
|
81
|
+
|
|
82
|
+
/** Challenge text as sent by the bank; may contain simple HTML. See `plainMessage`. */
|
|
83
|
+
readonly message: string | undefined;
|
|
84
|
+
|
|
85
|
+
/** Raw challenge data for TAN generators (HHD_UC). */
|
|
86
|
+
readonly hhdUc: Uint8Array | undefined;
|
|
87
|
+
|
|
88
|
+
/** chipTAN optical flicker code, if the challenge contains one. */
|
|
89
|
+
readonly flickerCode: FlickerCode | undefined;
|
|
90
|
+
|
|
91
|
+
/** photoTAN / QR-TAN image, if the challenge contains one. */
|
|
92
|
+
readonly image: TanImage | undefined;
|
|
93
|
+
|
|
94
|
+
/** Approval happens in a separate app; see `TanCallback` for what to answer. */
|
|
95
|
+
readonly isDecoupled: boolean;
|
|
96
|
+
|
|
97
|
+
/** The exact moment until which the bank accepts the TAN or the approval, where it states date and time of day. */
|
|
98
|
+
readonly validUntil: Date | undefined;
|
|
99
|
+
|
|
100
|
+
/** Name of the TAN medium the bank sent the challenge to. */
|
|
101
|
+
readonly tanMediumName: string | undefined;
|
|
102
|
+
|
|
103
|
+
/** Counts repeated prompts for the same decoupled approval. */
|
|
104
|
+
readonly attempt: number;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Settles when the client needs no more answer to this challenge: the bank confirmed the approval, or the approval
|
|
108
|
+
* failed, timed out or was cancelled. Set where the client asks the bank by itself while the callback shows the
|
|
109
|
+
* challenge (`TanCallback`), `undefined` otherwise. It never rejects.
|
|
110
|
+
*/
|
|
111
|
+
readonly resolved: Promise<void> | undefined;
|
|
112
|
+
|
|
113
|
+
/** A challenge as the bank sent it. Use `TanChallenge.create` to have a flicker code or image detected in the data. */
|
|
114
|
+
constructor(init: TanChallengeInit) {
|
|
115
|
+
this.method = init.method;
|
|
116
|
+
this.reference = init.reference;
|
|
117
|
+
this.message = init.message;
|
|
118
|
+
this.hhdUc = init.hhdUc;
|
|
119
|
+
this.flickerCode = init.flickerCode;
|
|
120
|
+
this.image = init.image;
|
|
121
|
+
this.isDecoupled = init.isDecoupled ?? false;
|
|
122
|
+
this.validUntil = init.validUntil;
|
|
123
|
+
this.tanMediumName = init.tanMediumName;
|
|
124
|
+
this.attempt = init.attempt ?? 1;
|
|
125
|
+
this.resolved = init.resolved;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Builds a challenge and detects a photoTAN image or chipTAN flicker code in `hhdUc` or `message`. */
|
|
129
|
+
static create(init: Omit<TanChallengeInit, 'flickerCode' | 'image' | 'resolved'>): TanChallenge {
|
|
130
|
+
let image: TanImage | undefined;
|
|
131
|
+
let flicker: FlickerCode | undefined;
|
|
132
|
+
const data = init.hhdUc !== undefined && init.hhdUc.length > 0 ? init.hhdUc : undefined;
|
|
133
|
+
if (data !== undefined) {
|
|
134
|
+
image = TanImage.tryParse(data);
|
|
135
|
+
if (image === undefined) {
|
|
136
|
+
const text = latin1Decode(data);
|
|
137
|
+
if (printableAscii.test(text)) flicker = FlickerCode.tryParse(text);
|
|
138
|
+
}
|
|
139
|
+
} else if (init.message !== undefined && hasEmbeddedFlickerCode(init.message)) {
|
|
140
|
+
flicker = FlickerCode.tryParse(init.message);
|
|
141
|
+
}
|
|
142
|
+
return new TanChallenge({
|
|
143
|
+
...init,
|
|
144
|
+
message: challengeText(init.message),
|
|
145
|
+
hhdUc: data,
|
|
146
|
+
flickerCode: flicker,
|
|
147
|
+
image,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Whether the user can report the approval in the banking app; `false` where only the bank's confirmation completes
|
|
153
|
+
* it, which `TanCallback` tells how to handle.
|
|
154
|
+
*/
|
|
155
|
+
get manualConfirmation(): boolean {
|
|
156
|
+
return !this.isDecoupled || this.method.decoupledManualConfirmation;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* `message` as the user reads it.
|
|
161
|
+
*
|
|
162
|
+
* A method with structured challenges (`TanMethod.structuredChallenge`) may use the formatting tags the specification
|
|
163
|
+
* defines. Line breaks, paragraphs and list items become new lines. Bold, italics, underlining and list tags are
|
|
164
|
+
* removed, and the entity references of such markup are resolved. Any other challenge stays as the bank sent it,
|
|
165
|
+
* which is how the specification wants it shown.
|
|
166
|
+
*/
|
|
167
|
+
get plainMessage(): string | undefined {
|
|
168
|
+
const text = this.message;
|
|
169
|
+
if (text === undefined) return undefined;
|
|
170
|
+
const instruction = challengeInstruction(text);
|
|
171
|
+
if (!this.method.structuredChallenge) return instruction;
|
|
172
|
+
return instruction
|
|
173
|
+
.replace(lineBreak, '\n')
|
|
174
|
+
.replace(blockTag, '\n')
|
|
175
|
+
.replace(formattingTag, '')
|
|
176
|
+
.replace(entityReference, (match, name: string) => decodeEntity(name) ?? match)
|
|
177
|
+
.replace(blankLines, '\n\n')
|
|
178
|
+
.trim();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Copies of a challenge for the prompts of one approval. Not methods of `TanChallenge`, so that they are not part of its
|
|
183
|
+
// API; they stand beside the class, so that a field added to it is added here as well.
|
|
184
|
+
|
|
185
|
+
/** `challenge` again, counted as the next prompt for the same approval, with the bank's new instructions `message`. */
|
|
186
|
+
export function nextAttempt(challenge: TanChallenge, message?: string): TanChallenge {
|
|
187
|
+
return copyChallenge(challenge, { attempt: challenge.attempt + 1, message: message ?? challenge.message });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** `challenge` with `TanChallenge.resolved` set to `resolved`. */
|
|
191
|
+
export function withResolved(challenge: TanChallenge, resolved: Promise<void>): TanChallenge {
|
|
192
|
+
return copyChallenge(challenge, { resolved });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function copyChallenge(challenge: TanChallenge, changes: Partial<TanChallengeInit>): TanChallenge {
|
|
196
|
+
return new TanChallenge({
|
|
197
|
+
method: challenge.method,
|
|
198
|
+
reference: challenge.reference,
|
|
199
|
+
message: challenge.message,
|
|
200
|
+
hhdUc: challenge.hhdUc,
|
|
201
|
+
flickerCode: challenge.flickerCode,
|
|
202
|
+
image: challenge.image,
|
|
203
|
+
isDecoupled: challenge.isDecoupled,
|
|
204
|
+
validUntil: challenge.validUntil,
|
|
205
|
+
tanMediumName: challenge.tanMediumName,
|
|
206
|
+
attempt: challenge.attempt,
|
|
207
|
+
resolved: challenge.resolved,
|
|
208
|
+
...changes,
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The user's answer to a `TanChallenge`: `TanAnswer.tan(…)`, `TanAnswer.approved` or `TanAnswer.cancelled`. */
|
|
213
|
+
export type TanAnswer =
|
|
214
|
+
/** The TAN the user entered; an empty one cancels. */
|
|
215
|
+
| { readonly kind: 'tan'; readonly tan: string }
|
|
216
|
+
/** The user reports the approval in the banking app (`TanChallenge.isDecoupled`); the client then asks the bank. */
|
|
217
|
+
| { readonly kind: 'approved' }
|
|
218
|
+
/** The user cancels: the client ends the bank dialog, and the call fails with `FinTsTanCancelledError`. */
|
|
219
|
+
| { readonly kind: 'cancelled' };
|
|
220
|
+
|
|
221
|
+
const approvedAnswer: TanAnswer = Object.freeze({ kind: 'approved' });
|
|
222
|
+
const cancelledAnswer: TanAnswer = Object.freeze({ kind: 'cancelled' });
|
|
223
|
+
|
|
224
|
+
/** The answers a `TanCallback` returns. */
|
|
225
|
+
export const TanAnswer = Object.freeze({
|
|
226
|
+
/** The TAN the user entered; an empty one cancels. */
|
|
227
|
+
tan: (tan: string): TanAnswer => Object.freeze({ kind: 'tan', tan }),
|
|
228
|
+
/** The user reports the approval in the banking app (`TanChallenge.isDecoupled`); the client then asks the bank. */
|
|
229
|
+
approved: approvedAnswer,
|
|
230
|
+
/** The user cancels: the client ends the bank dialog, and the call fails with `FinTsTanCancelledError`. */
|
|
231
|
+
cancelled: cancelledAnswer,
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Shows the `TanChallenge` to the user and returns the `TanAnswer`: `TanAnswer.tan(…)` for a TAN, `TanAnswer.approved`
|
|
236
|
+
* once the user reports an approval in the banking app (`TanChallenge.isDecoupled`), `TanAnswer.cancelled` to cancel
|
|
237
|
+
* either. An answer that does not fit the challenge fails the call with a `TypeError`.
|
|
238
|
+
*
|
|
239
|
+
* Where the client polls the bank by itself, it sets `TanChallenge.resolved`: close the prompt when it settles, the
|
|
240
|
+
* callback's result is no longer waited for then. If the bank has not confirmed a reported approval yet, the callback is
|
|
241
|
+
* called again with the next `TanChallenge.attempt`. Where `TanChallenge.manualConfirmation` is `false`, offer no
|
|
242
|
+
* confirm button: any answer but `TanAnswer.cancelled` is ignored.
|
|
243
|
+
*/
|
|
244
|
+
export type TanCallback = (challenge: TanChallenge) => TanAnswer | Promise<TanAnswer>;
|
|
245
|
+
|
|
246
|
+
/** Picks one of several allowed TAN methods; the first is used when this returns `undefined`. */
|
|
247
|
+
export type TanMethodSelector = (
|
|
248
|
+
methods: readonly TanMethod[],
|
|
249
|
+
) => TanMethod | undefined | Promise<TanMethod | undefined>;
|
|
250
|
+
|
|
251
|
+
/** Picks one of several active TAN media; the first is used when this returns `undefined`. */
|
|
252
|
+
export type TanMediumSelector = (media: readonly TanMedium[]) => TanMedium | undefined | Promise<TanMedium | undefined>;
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { FormatError } from '../util/errors.js';
|
|
2
|
+
import { withoutWhitespace } from '../util/text.js';
|
|
3
|
+
|
|
4
|
+
/** Version of the chipTAN HHD specification a flicker code follows: 1.3, or 1.4, which adds control bytes. */
|
|
5
|
+
export type HhdVersion = 'hhd13' | 'hhd14';
|
|
6
|
+
|
|
7
|
+
// A combined challenge embeds the flicker code in the challenge text:
|
|
8
|
+
// `CHLGUC` + four-digit length + code + `CHLGTEXT` + four digits + instruction text.
|
|
9
|
+
const codeMarker = 'CHLGUC';
|
|
10
|
+
const textMarker = 'CHLGTEXT';
|
|
11
|
+
const markerLengthDigits = 4;
|
|
12
|
+
|
|
13
|
+
/** Whether `message` is a combined challenge with an embedded flicker code. */
|
|
14
|
+
export function hasEmbeddedFlickerCode(message: string): boolean {
|
|
15
|
+
return message.includes(codeMarker);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The instruction text of a combined challenge; `message` itself if it is none. */
|
|
19
|
+
export function challengeInstruction(message: string): string {
|
|
20
|
+
const start = message.indexOf(textMarker);
|
|
21
|
+
if (start < 0) return message;
|
|
22
|
+
const textStart = start + textMarker.length + markerLengthDigits;
|
|
23
|
+
return textStart < message.length ? message.substring(textStart) : '';
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Digit counts of the challenge length (LC) and of the data element lengths (LDE) to try when parsing.
|
|
28
|
+
*
|
|
29
|
+
* HHD 1.4 states the LC with three digits, HHD 1.3 with two.
|
|
30
|
+
*/
|
|
31
|
+
const layouts = [
|
|
32
|
+
{ lcDigits: 3, lengthDigits: 2 },
|
|
33
|
+
{ lcDigits: 3, lengthDigits: 3 },
|
|
34
|
+
{ lcDigits: 2, lengthDigits: 2 },
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
function hex(value: number, width: number): string {
|
|
38
|
+
return value.toString(16).toUpperCase().padStart(width, '0');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A chipTAN optical challenge (flicker code) in HHD 1.3 or 1.4 format. */
|
|
42
|
+
export class FlickerCode {
|
|
43
|
+
private constructor(
|
|
44
|
+
/** The HHD version the code follows, told by the control bytes of its start code. */
|
|
45
|
+
readonly version: HhdVersion,
|
|
46
|
+
/** Length of the challenge (LC) as stated at the start of the code. */
|
|
47
|
+
readonly lc: number,
|
|
48
|
+
private readonly startCode: StartCode,
|
|
49
|
+
private readonly dataElements: readonly DataElement[],
|
|
50
|
+
) {}
|
|
51
|
+
|
|
52
|
+
/** Parses the challenge data sent by the bank; throws `FormatError` if it is not a flicker code. */
|
|
53
|
+
static parse(code: string): FlickerCode {
|
|
54
|
+
const cleaned = extractCode(code);
|
|
55
|
+
for (const layout of layouts) {
|
|
56
|
+
try {
|
|
57
|
+
return FlickerCode.parseLayout(new Reader(cleaned), layout.lcDigits, layout.lengthDigits);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
// Not this layout; try the next one.
|
|
60
|
+
if (!(error instanceof FormatError)) throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
throw new FormatError('Invalid flicker code', code);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Parses `code`, or returns `undefined` if it is not a flicker code. */
|
|
67
|
+
static tryParse(code: string): FlickerCode | undefined {
|
|
68
|
+
try {
|
|
69
|
+
return FlickerCode.parse(code);
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (error instanceof FormatError) return undefined;
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
private static parseLayout(code: Reader, lcDigits: number, lengthDigits: number): FlickerCode {
|
|
77
|
+
const lc = code.decimal(lcDigits);
|
|
78
|
+
const challenge = new Reader(code.take(lc));
|
|
79
|
+
// The start code has a hex length field whose top bit announces control bytes (HHD 1.4); the top bit of each
|
|
80
|
+
// control byte announces another one.
|
|
81
|
+
const startLength = challenge.hex(2);
|
|
82
|
+
const controlBytes: number[] = [];
|
|
83
|
+
if ((startLength & 0x80) !== 0) {
|
|
84
|
+
do {
|
|
85
|
+
controlBytes.push(challenge.hex(2));
|
|
86
|
+
} while ((controlBytes.at(-1)! & 0x80) !== 0 && controlBytes.length < 10);
|
|
87
|
+
}
|
|
88
|
+
const startCode = new StartCode(challenge.take(startLength & 0x3f), controlBytes);
|
|
89
|
+
const dataElements: DataElement[] = [];
|
|
90
|
+
for (let i = 0; i < 3; i++) {
|
|
91
|
+
dataElements.push(
|
|
92
|
+
new DataElement(challenge.isAtEnd ? undefined : challenge.take(challenge.decimal(lengthDigits) & 0x3f)),
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
// The fields fill exactly the LC characters; a layout that reads them otherwise is the wrong one.
|
|
96
|
+
if (!challenge.isAtEnd) throw new FormatError('Flicker code fields do not match its length');
|
|
97
|
+
return new FlickerCode(controlBytes.length === 0 ? 'hhd13' : 'hhd14', lc, startCode, dataElements);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The data of the start code, which opens the challenge. */
|
|
101
|
+
get startCodeData(): string {
|
|
102
|
+
return this.startCode.data ?? '';
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The first data element of the challenge; `undefined` if the code leaves it out. */
|
|
106
|
+
get dataElement1(): string | undefined {
|
|
107
|
+
return this.dataElements[0]?.data;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The second data element of the challenge; `undefined` if the code leaves it out. */
|
|
111
|
+
get dataElement2(): string | undefined {
|
|
112
|
+
return this.dataElements[1]?.data;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The third data element of the challenge; `undefined` if the code leaves it out. */
|
|
116
|
+
get dataElement3(): string | undefined {
|
|
117
|
+
return this.dataElements[2]?.data;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The hex string transmitted to the TAN generator, including checksums. */
|
|
121
|
+
render(): string {
|
|
122
|
+
const payload = this.payload();
|
|
123
|
+
return `${payload}${this.luhnChecksum()}${xorChecksum(payload)}`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private payload(): string {
|
|
127
|
+
let s = this.startCode.renderLength(this.version);
|
|
128
|
+
for (const c of this.startCode.controlBytes) s += hex(c, 2);
|
|
129
|
+
s += this.startCode.renderData();
|
|
130
|
+
for (const element of this.dataElements) {
|
|
131
|
+
s += element.renderLength(this.version);
|
|
132
|
+
s += element.renderData();
|
|
133
|
+
}
|
|
134
|
+
return `${hex(Math.floor((s.length + 2) / 2), 2)}${s}`;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private luhnChecksum(): string {
|
|
138
|
+
let s = '';
|
|
139
|
+
for (const c of this.startCode.controlBytes) s += hex(c, 2);
|
|
140
|
+
s += this.startCode.renderData();
|
|
141
|
+
for (const element of this.dataElements) if (element.data !== undefined) s += element.renderData();
|
|
142
|
+
let sum = 0;
|
|
143
|
+
for (let i = 0; i + 1 < s.length; i += 2) {
|
|
144
|
+
sum += parseInt(s[i]!, 16) + digitSum(2 * parseInt(s[i + 1]!, 16));
|
|
145
|
+
}
|
|
146
|
+
const mod = sum % 10;
|
|
147
|
+
return mod === 0 ? '0' : hex(10 - mod, 1);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Frames to animate: each is `[clock, bit0, bit1, bit2, bit3]` for the five bars. */
|
|
151
|
+
frames(): boolean[][] {
|
|
152
|
+
const code = `0FFF${this.render()}`;
|
|
153
|
+
const result: boolean[][] = [];
|
|
154
|
+
for (let i = 0; i + 1 < code.length; i += 2) {
|
|
155
|
+
for (const nibble of [code[i + 1]!, code[i]!]) {
|
|
156
|
+
const v = parseInt(nibble, 16);
|
|
157
|
+
const bits = [(v & 1) !== 0, (v & 2) !== 0, (v & 4) !== 0, (v & 8) !== 0];
|
|
158
|
+
result.push([true, ...bits]);
|
|
159
|
+
result.push([false, ...bits]);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return result;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The code of a combined challenge, or `code` itself without whitespace. */
|
|
167
|
+
function extractCode(code: string): string {
|
|
168
|
+
const compact = withoutWhitespace(code);
|
|
169
|
+
const start = compact.indexOf(codeMarker);
|
|
170
|
+
const codeStart = start + codeMarker.length + markerLengthDigits;
|
|
171
|
+
const end = compact.indexOf(textMarker);
|
|
172
|
+
return start >= 0 && end >= codeStart ? compact.substring(codeStart, end) : compact;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function xorChecksum(payload: string): string {
|
|
176
|
+
let x = 0;
|
|
177
|
+
for (const c of payload) x ^= parseInt(c, 16);
|
|
178
|
+
return hex(x, 1);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function digitSum(n: number): number {
|
|
182
|
+
let sum = 0;
|
|
183
|
+
while (n !== 0) {
|
|
184
|
+
sum += n % 10;
|
|
185
|
+
n = Math.floor(n / 10);
|
|
186
|
+
}
|
|
187
|
+
return sum;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Reads the fields of a flicker code from left to right; throws `FormatError` when a field is missing or malformed. */
|
|
191
|
+
class Reader {
|
|
192
|
+
private position = 0;
|
|
193
|
+
|
|
194
|
+
constructor(private readonly code: string) {}
|
|
195
|
+
|
|
196
|
+
get remaining(): number {
|
|
197
|
+
return this.code.length - this.position;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
get isAtEnd(): boolean {
|
|
201
|
+
return this.remaining === 0;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
take(length: number): string {
|
|
205
|
+
if (length > this.remaining) throw new FormatError('Flicker code too short');
|
|
206
|
+
const field = this.code.substring(this.position, this.position + length);
|
|
207
|
+
this.position += length;
|
|
208
|
+
return field;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
decimal(digits: number): number {
|
|
212
|
+
return parseInt(Reader.match(/^[0-9]+$/, this.take(digits)), 10);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
hex(digits: number): number {
|
|
216
|
+
return parseInt(Reader.match(/^[0-9A-Fa-f]+$/, this.take(digits)), 16);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private static match(pattern: RegExp, field: string): string {
|
|
220
|
+
if (!pattern.test(field)) throw new FormatError('Invalid length field', field);
|
|
221
|
+
return field;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* A data element of the flicker code: a length field (LDE) followed by the data; `undefined` data if the code leaves
|
|
227
|
+
* the element out.
|
|
228
|
+
*/
|
|
229
|
+
class DataElement {
|
|
230
|
+
constructor(readonly data: string | undefined) {}
|
|
231
|
+
|
|
232
|
+
get isBcd(): boolean {
|
|
233
|
+
return this.data === undefined || /^[0-9]+$/.test(this.data);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
renderData(): string {
|
|
237
|
+
const d = this.data;
|
|
238
|
+
if (d === undefined) return '';
|
|
239
|
+
if (!this.isBcd) {
|
|
240
|
+
let ascii = '';
|
|
241
|
+
for (let i = 0; i < d.length; i++) ascii += hex(d.charCodeAt(i), 2);
|
|
242
|
+
return ascii;
|
|
243
|
+
}
|
|
244
|
+
return d.length % 2 === 1 ? `${d}F` : d;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
renderLength(version: HhdVersion): string {
|
|
248
|
+
if (this.data === undefined) return '';
|
|
249
|
+
const length = Math.floor(this.renderData().length / 2);
|
|
250
|
+
if (this.isBcd) return hex(length, 2);
|
|
251
|
+
if (version === 'hhd14') return hex(length + 0x40, 2);
|
|
252
|
+
return `1${hex(length, 1)}`;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** The start code: a data element whose length field may announce control bytes (HHD 1.4). */
|
|
257
|
+
class StartCode extends DataElement {
|
|
258
|
+
constructor(
|
|
259
|
+
data: string | undefined,
|
|
260
|
+
readonly controlBytes: readonly number[],
|
|
261
|
+
) {
|
|
262
|
+
super(data);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
override renderLength(version: HhdVersion): string {
|
|
266
|
+
const s = super.renderLength(version);
|
|
267
|
+
if (version === 'hhd13' || this.controlBytes.length === 0) return s;
|
|
268
|
+
return hex(parseInt(s, 16) + 0x80, 2);
|
|
269
|
+
}
|
|
270
|
+
}
|