aboutsummaryrefslogtreecommitdiff
path: root/packages/challenger-ui/src/pages/AnswerChallenge.tsx
blob: 48f4db47757441ec7f6af18d3189ccf22c903d6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*
 This file is part of GNU Taler
 (C) 2022-2024 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */
import {
  AbsoluteTime,
  EmptyObject,
  HttpStatusCode,
  TalerError,
  assertUnreachable,
} from "@gnu-taler/taler-util";
import {
  Attention,
  Button,
  LocalNotificationBanner,
  RouteDefinition,
  ShowInputErrorLabel,
  Time,
  useChallengerApiContext,
  useLocalNotificationHandler,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { Fragment, VNode, h } from "preact";
import { useEffect, useState } from "preact/hooks";
import {
  revalidateChallengeSession,
  useChallengeSession,
} from "../hooks/challenge.js";
import { SessionId, useSessionState } from "../hooks/session.js";

type Props = {
  focus?: boolean;
  session: SessionId,
  onComplete: () => void;
  routeAsk: RouteDefinition<EmptyObject>;
};

function useReloadOnDeadline(deadline: AbsoluteTime): void {
  const [, set] = useState(false);
  function toggle(): void {
    set((s) => !s);
  }
  useEffect(() => {
    if (AbsoluteTime.isExpired(deadline)) {
      return;
    }
    const diff = AbsoluteTime.difference(AbsoluteTime.now(), deadline);
    if (diff.d_ms === "forever") return;
    const timer = setTimeout(toggle, diff.d_ms);
    return () => {
      clearTimeout(timer);
    };
  }, [deadline]);
}

export function AnswerChallenge({ session, focus, onComplete, routeAsk }: Props): VNode {
  const { config, lib } = useChallengerApiContext();
  const { i18n } = useTranslationContext();
  const { sent, failed, completed } = useSessionState();
  const [notification, withErrorHandler] = useLocalNotificationHandler();
  const [pin, setPin] = useState<string | undefined>();
  const errors = undefinedIfEmpty({
    pin: !pin ? i18n.str`Can't be empty` : undefined,
  });

  const restrictionKeys = !config.restrictions
    ? []
    : Object.keys(config.restrictions);
  const restrictionKey = !restrictionKeys.length
    ? undefined
    : restrictionKeys[0];

  const result = useChallengeSession(session);

  const lastStatus =
    result && !(result instanceof TalerError) && result.type !== "fail"
      ? result.body
      : undefined;

  const deadline =
    lastStatus == undefined
      ? undefined
      : AbsoluteTime.fromProtocolTimestamp(lastStatus.retransmission_time);

  useReloadOnDeadline(deadline ?? AbsoluteTime.never());

  if (!restrictionKey) {
    return (
      <div>
        invalid server configuration, there is no restriction in /config
      </div>
    );
  }

  const lastAddr = !lastStatus?.last_address
    ? undefined
    : lastStatus.last_address[restrictionKey];

  const unableToChangeAddr = !lastStatus || lastStatus.changes_left < 1;
  const contact = lastAddr ? { [restrictionKey]: lastAddr } : undefined;

  const onSendAgain =
    contact === undefined ||
    lastStatus == undefined ||
    lastStatus.pin_transmissions_left === 0 ||
    !deadline ||
    !AbsoluteTime.isExpired(deadline)
      ? undefined
      : withErrorHandler(
          async () => {
            return await lib.challenger.challenge(session.nonce, contact);
          },
          (ok) => {
            if (ok.body.type === "completed") {
              completed(ok.body);
            } else {
              sent(ok.body);
            }
          },
          (fail) => {
            switch (fail.case) {
              case HttpStatusCode.BadRequest:
                return i18n.str`The request was not accepted, try reloading the app.`;
              case HttpStatusCode.NotFound:
                return i18n.str`Challenge not found.`;
              case HttpStatusCode.NotAcceptable:
                return i18n.str`Server templates are missing due to misconfiguration.`;
              case HttpStatusCode.TooManyRequests:
                return i18n.str`There have been too many attempts to request challenge transmissions.`;
              case HttpStatusCode.InternalServerError:
                return i18n.str`Server is not able to respond due to internal problems.`;
            }
          },
        );

  const onCheck =
    errors !== undefined ||
    lastStatus == undefined ||
    lastStatus.auth_attempts_left === 0
      ? undefined
      : withErrorHandler(
          async () => {
            return lib.challenger.solve(session.nonce, { pin: pin! });
          },
          (ok) => {
            if (ok.body.type === "completed") {
              completed(ok.body);
            } else {
              failed(ok.body);
            }
            onComplete();
          },
          (fail) => {
            switch (fail.case) {
              case HttpStatusCode.BadRequest:
                return i18n.str`The request was not accepted, try reloading the app.`;
              case HttpStatusCode.Forbidden: {
                revalidateChallengeSession();
                return i18n.str`Invalid pin.`;
              }
              case HttpStatusCode.NotFound:
                return i18n.str`Challenge not found.`;
              case HttpStatusCode.NotAcceptable:
                return i18n.str`Server templates are missing due to misconfiguration.`;
              case HttpStatusCode.TooManyRequests: {
                revalidateChallengeSession();
                return i18n.str`There have been too many attempts to request challenge transmissions.`;
              }
              case HttpStatusCode.InternalServerError:
                return i18n.str`Server is not able to respond due to internal problems.`;
              default:
                assertUnreachable(fail);
            }
          },
        );
  const cantTryAnymore = lastStatus?.auth_attempts_left === 0;

  function LastContactSent(): VNode {
    return (
      <p class="mt-2 text-lg leading-8 text-gray-600">
        {!lastStatus || !deadline || AbsoluteTime.isExpired(deadline) ? (
          <i18n.Translate>
            Last TAN code was sent to your address &quot;{lastAddr}
            &quot; is not valid anymore.
          </i18n.Translate>
        ) : (
          <Attention
            title={i18n.str`A TAN code was sent to your address "${lastAddr}"`}
          >
            <i18n.Translate>
              You should wait until &quot;
              <Time format="dd/MM/yyyy HH:mm:ss" timestamp={deadline} />
              &quot; to send a new one.
            </i18n.Translate>
          </Attention>
        )}
      </p>
    );
  }

  function TryAnotherCode(): VNode {
    return (
      <div class="mx-auto mt-4 max-w-xl flex justify-between">
        <div>
          <a
            data-disabled={unableToChangeAddr}
            href={unableToChangeAddr ? undefined : routeAsk.url({})}
            class="relative data-[disabled=true]:bg-gray-300 data-[disabled=true]:text-white data-[disabled=true]:cursor-default inline-flex items-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus-visible:outline-offset-0"
          >
            <i18n.Translate>Try with another address</i18n.Translate>
          </a>
          {lastStatus === undefined ? undefined : (
            <p class="mt-2 text-sm leading-6 text-gray-400">
              {lastStatus.changes_left < 1 ? (
                <i18n.Translate>
                  You can&#39;t change the contact address anymore.
                </i18n.Translate>
              ) : lastStatus.changes_left === 1 ? (
                <i18n.Translate>
                  You can change the contact address one last time.
                </i18n.Translate>
              ) : (
                <i18n.Translate>
                  You can change the contact address {lastStatus.changes_left}{" "}
                  more times.
                </i18n.Translate>
              )}
            </p>
          )}
        </div>
        <div>
          <Button
            type="submit"
            disabled={!onSendAgain}
            class="block w-full disabled:bg-gray-300 rounded-md bg-indigo-600 px-3.5 py-2.5 text-center text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
            handler={onSendAgain}
          >
            <i18n.Translate>Send new code</i18n.Translate>
          </Button>
          {lastStatus === undefined ? undefined : (
            <p class="mt-2 text-sm leading-6 text-gray-400">
              {lastStatus.pin_transmissions_left < 1 ? (
                <i18n.Translate>
                  We can&#39;t send you the code anymore.
                </i18n.Translate>
              ) : lastStatus.pin_transmissions_left === 1 ? (
                <i18n.Translate>
                  We can send the code one last time.
                </i18n.Translate>
              ) : (
                <i18n.Translate>
                  We can send the code {lastStatus.pin_transmissions_left} more
                  times.
                </i18n.Translate>
              )}
            </p>
          )}
        </div>
      </div>
    );
  }

  if (cantTryAnymore) {
    return (
      <Fragment>
        <LocalNotificationBanner notification={notification} />
        <div class="isolate bg-white px-6 py-12">
          <div class="mx-auto max-w-2xl text-center">
            <h2 class="text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl">
              <i18n.Translate>Last TAN code can not be used.</i18n.Translate>
            </h2>

            <LastContactSent />
          </div>

          <TryAnotherCode />
        </div>
      </Fragment>
    );
  }

  return (
    <Fragment>
      <LocalNotificationBanner notification={notification} />

      <div class="isolate bg-white px-6 py-12">
        <div class="mx-auto max-w-2xl text-center">
          <h2 class="text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl">
            <i18n.Translate>
              Enter the TAN you received to authenticate.
            </i18n.Translate>
          </h2>
          <LastContactSent />

          {lastStatus === undefined ? undefined : (
            <p class="mt-2 text-lg leading-8 text-gray-600">
              {lastStatus.auth_attempts_left < 1 ? (
                <i18n.Translate>
                  You can&#39;t check the PIN anymore.
                </i18n.Translate>
              ) : lastStatus.auth_attempts_left === 1 ? (
                <i18n.Translate>
                  You can check the PIN one last time.
                </i18n.Translate>
              ) : (
                <i18n.Translate>
                  You can check the PIN {lastStatus.auth_attempts_left} more
                  times.
                </i18n.Translate>
              )}
            </p>
          )}
        </div>

        <form
          method="POST"
          class="mx-auto mt-4 max-w-xl"
          onSubmit={(e) => {
            e.preventDefault();
          }}
        >
          <div class="grid grid-cols-1 gap-x-8 gap-y-6">
            <div class="sm:col-span-2">
              <label
                for="pin"
                class="block text-sm font-semibold leading-6 text-gray-900"
              >
                <i18n.Translate>TAN code</i18n.Translate>
              </label>
              <div class="mt-2.5">
                <input
                  autoFocus
                  ref={focus ? doAutoFocus : undefined}
                  type="number"
                  name="pin"
                  id="pin"
                  maxLength={64}
                  value={pin}
                  onChange={(e) => {
                    setPin(e.currentTarget.value);
                  }}
                  placeholder="12345678"
                  class="block w-full rounded-md border-0 px-3.5 py-2 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
                />
                <ShowInputErrorLabel
                  message={errors?.pin}
                  isDirty={pin !== undefined}
                />
              </div>
            </div>
          </div>

          <div class="mt-10">
            <Button
              type="submit"
              class="block w-full disabled:bg-gray-300 rounded-md bg-indigo-600 px-3.5 py-2.5 text-center text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
              disabled={!onCheck}
              handler={onCheck}
            >
              <i18n.Translate>Check</i18n.Translate>
            </Button>
          </div>
        </form>

        <TryAnotherCode />
      </div>
    </Fragment>
  );
}

/**
 * Show the element when the load ended
 * @param element
 */
export function doAutoFocus(element: HTMLElement | null): void {
  if (element) {
    setTimeout(() => {
      element.focus({ preventScroll: true });
      element.scrollIntoView({
        behavior: "smooth",
        block: "center",
        inline: "center",
      });
    }, 100);
  }
}

export function undefinedIfEmpty<T extends object>(obj: T): T | undefined {
  return Object.keys(obj).some(
    (k) => (obj as Record<string, T>)[k] !== undefined,
  )
    ? obj
    : undefined;
}