diff options
Diffstat (limited to 'packages/challenger-ui/src/pages')
-rw-r--r-- | packages/challenger-ui/src/pages/AnswerChallenge.tsx | 316 | ||||
-rw-r--r-- | packages/challenger-ui/src/pages/AskChallenge.tsx | 465 | ||||
-rw-r--r-- | packages/challenger-ui/src/pages/CallengeCompleted.tsx | 36 | ||||
-rw-r--r-- | packages/challenger-ui/src/pages/Frame.tsx | 153 | ||||
-rw-r--r-- | packages/challenger-ui/src/pages/Setup.tsx | 161 |
5 files changed, 822 insertions, 309 deletions
diff --git a/packages/challenger-ui/src/pages/AnswerChallenge.tsx b/packages/challenger-ui/src/pages/AnswerChallenge.tsx index 5fe2d9743..48f4db477 100644 --- a/packages/challenger-ui/src/pages/AnswerChallenge.tsx +++ b/packages/challenger-ui/src/pages/AnswerChallenge.tsx @@ -14,8 +14,10 @@ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ import { - ChallengerApi, + AbsoluteTime, + EmptyObject, HttpStatusCode, + TalerError, assertUnreachable, } from "@gnu-taler/taler-util"; import { @@ -24,128 +26,268 @@ import { LocalNotificationBanner, RouteDefinition, ShowInputErrorLabel, + Time, useChallengerApiContext, useLocalNotificationHandler, useTranslationContext, } from "@gnu-taler/web-util/browser"; import { Fragment, VNode, h } from "preact"; -import { useState } from "preact/hooks"; -import { useSessionState } from "../hooks/session.js"; - -export const EMAIL_REGEX = /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/; +import { useEffect, useState } from "preact/hooks"; +import { + revalidateChallengeSession, + useChallengeSession, +} from "../hooks/challenge.js"; +import { SessionId, useSessionState } from "../hooks/session.js"; type Props = { - nonce: string; focus?: boolean; + session: SessionId, onComplete: () => void; - routeAsk: RouteDefinition<{ nonce: string }>; + routeAsk: RouteDefinition<EmptyObject>; }; -export function AnswerChallenge({ - focus, - nonce, - onComplete, - routeAsk, -}: Props): VNode { - const { lib } = useChallengerApiContext(); +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 { state, accepted, completed } = useSessionState(); + const { sent, failed, completed } = useSessionState(); const [notification, withErrorHandler] = useLocalNotificationHandler(); const [pin, setPin] = useState<string | undefined>(); - const [lastTryError, setLastTryError] = - useState<ChallengerApi.InvalidPinResponse>(); const errors = undefinedIfEmpty({ pin: !pin ? i18n.str`Can't be empty` : undefined, }); - const lastEmail = !state + const restrictionKeys = !config.restrictions + ? [] + : Object.keys(config.restrictions); + const restrictionKey = !restrictionKeys.length ? undefined - : !state.lastStatus + : restrictionKeys[0]; + + const result = useChallengeSession(session); + + const lastStatus = + result && !(result instanceof TalerError) && result.type !== "fail" + ? result.body + : undefined; + + const deadline = + lastStatus == undefined ? undefined - : !state.lastStatus.last_address - ? undefined - : state.lastStatus.last_address["email"]; + : 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 = - !state || lastEmail === undefined + contact === undefined || + lastStatus == undefined || + lastStatus.pin_transmissions_left === 0 || + !deadline || + !AbsoluteTime.isExpired(deadline) ? undefined : withErrorHandler( async () => { - if (!lastEmail) return; - return await lib.challenger.challenge(nonce, { email: lastEmail }); + return await lib.challenger.challenge(session.nonce, contact); }, (ok) => { if (ok.body.type === "completed") { - completed(new URL(ok.body.redirect_url)); + completed(ok.body); } else { - accepted({ - attemptsLeft: ok.body.attempts_left, - nextSend: ok.body.next_tx_time, - transmitted: ok.body.transmitted, - }); + sent(ok.body); } - return undefined; }, (fail) => { switch (fail.case) { case HttpStatusCode.BadRequest: - return i18n.str``; - case HttpStatusCode.Forbidden: - return i18n.str``; + return i18n.str`The request was not accepted, try reloading the app.`; case HttpStatusCode.NotFound: - return i18n.str``; + return i18n.str`Challenge not found.`; case HttpStatusCode.NotAcceptable: - return i18n.str``; + return i18n.str`Server templates are missing due to misconfiguration.`; case HttpStatusCode.TooManyRequests: - return i18n.str``; + return i18n.str`There have been too many attempts to request challenge transmissions.`; case HttpStatusCode.InternalServerError: - return i18n.str``; + return i18n.str`Server is not able to respond due to internal problems.`; } }, ); const onCheck = - errors !== undefined || (lastTryError && lastTryError.exhausted) + errors !== undefined || + lastStatus == undefined || + lastStatus.auth_attempts_left === 0 ? undefined : withErrorHandler( async () => { - return lib.challenger.solve(nonce, { pin: pin! }); + return lib.challenger.solve(session.nonce, { pin: pin! }); }, (ok) => { if (ok.body.type === "completed") { - completed(new URL(ok.body.redirect_url)); + completed(ok.body); } else { - setLastTryError(ok.body); + failed(ok.body); } onComplete(); }, (fail) => { switch (fail.case) { case HttpStatusCode.BadRequest: - return i18n.str`Invalid request`; + return i18n.str`The request was not accepted, try reloading the app.`; case HttpStatusCode.Forbidden: { - return i18n.str`Too many attemps where made`; + revalidateChallengeSession(); + return i18n.str`Invalid pin.`; } case HttpStatusCode.NotFound: - return i18n.str``; + return i18n.str`Challenge not found.`; case HttpStatusCode.NotAcceptable: - return i18n.str``; - case HttpStatusCode.TooManyRequests: - return i18n.str``; + 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``; + 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 "{lastAddr} + " 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 " + <Time format="dd/MM/yyyy HH:mm:ss" timestamp={deadline} /> + " to send a new one. + </i18n.Translate> + </Attention> + )} + </p> + ); + } - if (!state) { - return <div>no state</div>; + 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'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'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 (!state.lastTry) { - return <div>you should do a challenge first</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 ( @@ -159,33 +301,31 @@ export function AnswerChallenge({ Enter the TAN you received to authenticate. </i18n.Translate> </h2> - <p class="mt-2 text-lg leading-8 text-gray-600"> - {state.lastTry.transmitted ? ( - <i18n.Translate> - A TAN was sent to your address "{lastEmail}". - </i18n.Translate> - ) : ( - <Attention title={i18n.str`Resend failed`} type="warning"> + <LastContactSent /> + + {lastStatus === undefined ? undefined : ( + <p class="mt-2 text-lg leading-8 text-gray-600"> + {lastStatus.auth_attempts_left < 1 ? ( <i18n.Translate> - We recently already sent a TAN to your address " - {lastEmail}". A new TAN will not be transmitted again - before "{state.lastTry.nextSend}". + You can't check the PIN anymore. </i18n.Translate> - </Attention> - )} - </p> - {!lastTryError ? undefined : ( - <p class="mt-2 text-lg leading-8 text-gray-600"> - <i18n.Translate> - You can try another PIN but just{" "} - {lastTryError.auth_attempts_left} times more. - </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-16 max-w-xl sm:mt-20" + class="mx-auto mt-4 max-w-xl" onSubmit={(e) => { e.preventDefault(); }} @@ -219,12 +359,6 @@ export function AnswerChallenge({ /> </div> </div> - - <p class="mt-3 text-sm leading-6 text-gray-400"> - <i18n.Translate> - You have {state.lastTry.attemptsLeft} attempts left. - </i18n.Translate> - </p> </div> <div class="mt-10"> @@ -237,27 +371,9 @@ export function AnswerChallenge({ <i18n.Translate>Check</i18n.Translate> </Button> </div> - <div class="mt-10 flex justify-between"> - <div> - <a - href={routeAsk.url({ nonce })} - class="relative disabled:bg-gray-100 disabled:text-gray-500 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>Change email</i18n.Translate> - </a> - </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 code again</i18n.Translate> - </Button> - </div> - </div> </form> + + <TryAnotherCode /> </div> </Fragment> ); diff --git a/packages/challenger-ui/src/pages/AskChallenge.tsx b/packages/challenger-ui/src/pages/AskChallenge.tsx index 829cdaccc..f034a773b 100644 --- a/packages/challenger-ui/src/pages/AskChallenge.tsx +++ b/packages/challenger-ui/src/pages/AskChallenge.tsx @@ -13,221 +13,418 @@ 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 { HttpStatusCode } from "@gnu-taler/taler-util"; +import { + EmptyObject, + HttpStatusCode, + TalerError, + TranslatedString +} 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 { useState } from "preact/hooks"; -import { useSessionState } from "../hooks/session.js"; +import { useChallengeSession } from "../hooks/challenge.js"; +import { SessionId, useSessionState } from "../hooks/session.js"; import { doAutoFocus } from "./AnswerChallenge.js"; -type Form = { - email: string; -}; export const EMAIL_REGEX = /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/; type Props = { - nonce: string; onSendSuccesful: () => void; - routeSolveChallenge: RouteDefinition<{ nonce: string }>; + session: SessionId; + routeSolveChallenge: RouteDefinition<EmptyObject>; focus?: boolean; }; export function AskChallenge({ - nonce, onSendSuccesful, routeSolveChallenge, + session, focus, }: Props): VNode { - const { state, accepted, completed } = useSessionState(); - const status = state?.lastStatus; - const prevEmail = - !status || !status.last_address ? undefined : status.last_address["email"]; - const regexEmail = - !status || !status.restrictions ? undefined : status.restrictions["email"]; + const { state, sent, saveAddress, completed } = useSessionState(); + const { lib, config } = useChallengerApiContext(); - const { lib } = useChallengerApiContext(); const { i18n } = useTranslationContext(); const [notification, withErrorHandler] = useLocalNotificationHandler(); - const [email, setEmail] = useState<string | undefined>(); + const [address, setEmail] = useState<string | undefined>(); const [repeat, setRepeat] = useState<string | undefined>(); + const [remember, setRemember] = useState<boolean>(false); + const [addrIndex, setAddrIndex] = useState<number | undefined>(); + + const restrictionKeys = !config.restrictions + ? [] + : Object.keys(config.restrictions); + const restrictionKey = !restrictionKeys.length + ? undefined + : restrictionKeys[0]; + const result = useChallengeSession(session); + + if (!restrictionKey) { + return ( + <div> + invalid server configuration, there is no restriction in /config + </div> + ); + } + + const regexEmail = !config.restrictions + ? undefined + : config.restrictions[restrictionKey]; const regexTest = regexEmail && regexEmail.regex ? new RegExp(regexEmail.regex) : EMAIL_REGEX; const regexHint = regexEmail && regexEmail.hint ? regexEmail.hint : i18n.str`invalid email`; + const lastStatus = + result && !(result instanceof TalerError) && result.type !== "fail" + ? result.body + : undefined; + + const prevAddr = !lastStatus?.last_address + ? undefined + : lastStatus.last_address[restrictionKey]; + const errors = undefinedIfEmpty({ - email: !email + address: !address ? i18n.str`required` - : !regexTest.test(email) + : !regexTest.test(address) ? regexHint - : prevEmail !== undefined && email === prevEmail - ? i18n.str`email should be different` + : prevAddr !== undefined && address === prevAddr + ? i18n.str`can't use the same address` : undefined, repeat: !repeat ? i18n.str`required` - : email !== repeat - ? i18n.str`emails doesn't match` + : address !== repeat + ? i18n.str`doesn't match` : undefined, }); - const onSend = errors - ? undefined - : withErrorHandler( - async () => { - return lib.challenger.challenge(nonce, { email: email! }); - }, - (ok) => { - if (ok.body.type === "completed") { - completed(new URL(ok.body.redirect_url)); - } else { - accepted({ - attemptsLeft: ok.body.attempts_left, - nextSend: ok.body.next_tx_time, - transmitted: ok.body.transmitted, - }); - } - onSendSuccesful(); - }, - (fail) => { - switch (fail.case) { - case HttpStatusCode.BadRequest: - return i18n.str``; - case HttpStatusCode.Forbidden: - return i18n.str``; - case HttpStatusCode.NotFound: - return i18n.str``; - case HttpStatusCode.NotAcceptable: - return i18n.str``; - case HttpStatusCode.TooManyRequests: - return i18n.str``; - case HttpStatusCode.InternalServerError: - return i18n.str``; - } - }, - ); + const contact = address ? { [restrictionKey]: address } : undefined; - if (!status) { + const usableAddrs = + !state?.lastAddress || !state.lastAddress.length + ? [] + : state.lastAddress.filter((d) => !!d.address[restrictionKey]); + + const onSend = + errors || !contact + ? undefined + : withErrorHandler( + async () => { + return lib.challenger.challenge(session.nonce, contact); + }, + (ok) => { + if (ok.body.type === "completed") { + completed(ok.body); + } else { + if (remember) { + saveAddress(config.address_type, contact); + } + sent(ok.body); + } + onSendSuccesful(); + }, + (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.`; + } + }, + ); + + if (!lastStatus) { return <div>no status loaded</div>; } return ( <Fragment> - <LocalNotificationBanner notification={notification} /> + <LocalNotificationBanner notification={notification} showDebug={true} /> <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 contact details</i18n.Translate> </h2> - <p class="mt-2 text-lg leading-8 text-gray-600"> - <i18n.Translate> - You will receive an email with a TAN code that must be provided on - the next page. - </i18n.Translate> - </p> + {config.address_type === "email" ? ( + <p class="mt-2 text-lg leading-8 text-gray-600"> + <i18n.Translate> + You will receive an email with a TAN code that must be provided + on the next page. + </i18n.Translate> + </p> + ) : config.address_type === "phone" ? ( + <p class="mt-2 text-lg leading-8 text-gray-600"> + <i18n.Translate> + You will receive an SMS with a TAN code that must be provided on + the next page. + </i18n.Translate> + </p> + ) : ( + <p class="mt-2 text-lg leading-8 text-gray-600"> + <i18n.Translate> + You will receive an message with a TAN code that must be + provided on the next page. + </i18n.Translate> + </p> + )} </div> - {state.lastTry && ( + + {lastStatus?.last_address && ( <Fragment> - <Attention title={i18n.str`A code has been sent to ${prevEmail}`}> + <Attention title={i18n.str`A code has been sent to ${prevAddr}`}> <i18n.Translate> - <a href={routeSolveChallenge.url({ nonce })} class="underline"> + <a href={routeSolveChallenge.url({})} class="underline"> <i18n.Translate>Complete the challenge here.</i18n.Translate> </a> </i18n.Translate> </Attention> </Fragment> )} + + {!usableAddrs.length ? undefined : ( + <div class="mx-auto max-w-xl mt-4"> + <h3> + <i18n.Translate>Previous address</i18n.Translate> + </h3> + <fieldset> + <div class="relative -space-y-px rounded-md bg-white"> + {usableAddrs.map((addr, idx) => { + return ( + <label + data-checked={addrIndex === idx} + key={idx} + class="relative flex border-gray-200 data-[checked=true]:z-10 data-[checked=true]:bg-indigo-50 cursor-pointer flex-col rounded-tl-md rounded-tr-md border p-4 focus:outline-none md:grid md:grid-cols-2 md:pl-4 md:pr-6" + > + <span class="flex items-center text-sm"> + <input + type="radio" + name={`addr-${idx}`} + value={addr.address[restrictionKey]} + checked={addrIndex === idx} + onClick={() => { + setAddrIndex(idx); + setEmail(addr.address[restrictionKey]); + setRepeat(addr.address[restrictionKey]); + }} + class="h-4 w-4 border-gray-300 text-indigo-600 focus:ring-indigo-600 active:ring-2 active:ring-indigo-600 active:ring-offset-2" + /> + <span + data-checked={addrIndex === idx} + class="ml-3 font-medium text-gray-900 data-[checked=true]:text-indigo-900 " + > + {addr.address[restrictionKey]} + </span> + </span> + <span + data-checked={addrIndex === idx} + class="ml-6 pl-1 text-sm md:ml-0 md:pl-0 md:text-right text-gray-500 data-[checked=true]:text-indigo-700" + > + <i18n.Translate> + Last used at{" "} + <Time + format="dd/MM/yyyy HH:mm:ss" + timestamp={addr.savedAt} + /> + </i18n.Translate> + </span> + </label> + ); + })} + <label + data-checked={addrIndex === undefined} + class="relative rounded-bl-md rounded-br-md flex border-gray-200 data-[checked=true]:z-10 data-[checked=true]:bg-indigo-50 cursor-pointer flex-col rounded-tl-md rounded-tr-md border p-4 focus:outline-none md:grid md:grid-cols-2 md:pl-4 md:pr-6" + > + <span class="flex items-center text-sm"> + <input + type="radio" + name="new-addr" + value="new-addr" + checked={addrIndex === undefined} + onClick={() => { + setAddrIndex(undefined); + setEmail(undefined); + setRepeat(undefined); + }} + class="h-4 w-4 border-gray-300 text-indigo-600 focus:ring-indigo-600 active:ring-2 active:ring-indigo-600 active:ring-offset-2" + /> + <span + data-checked={addrIndex === undefined} + class="ml-3 font-medium text-gray-900 data-[checked=true]:text-indigo-900 " + > + <i18n.Translate>Use new address</i18n.Translate> + </span> + </span> + </label> + </div> + </fieldset> + </div> + )} + <form method="POST" - class="mx-auto mt-16 max-w-xl sm:mt-20" + 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="address" + class="block text-sm font-semibold leading-6 text-gray-900" + > + {(function (): TranslatedString { + switch (config.address_type) { + case "email": + return i18n.str`Email`; + case "phone": + return i18n.str`Phone`; + } + })()} + </label> + <div class="mt-2.5"> + <input + type="text" + name="address" + id="address" + ref={focus ? doAutoFocus : undefined} + maxLength={512} + autocomplete={(function (): string { + switch (config.address_type) { + case "email": + return "email"; + case "phone": + return "phone"; + } + })()} + value={address ?? ""} + onChange={(e) => { + setEmail(e.currentTarget.value); + }} + placeholder={prevAddr} + readOnly={lastStatus.fix_address || addrIndex !== undefined} + class="block w-full read-only:bg-slate-200 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?.address} + isDirty={address !== undefined} + /> + </div> + </div> + + {lastStatus.fix_address || addrIndex !== undefined ? undefined : ( <div class="sm:col-span-2"> <label - for="email" + for="repeat-address" class="block text-sm font-semibold leading-6 text-gray-900" > - <i18n.Translate>Email</i18n.Translate> + {(function (): TranslatedString { + switch (config.address_type) { + case "email": + return i18n.str`Repeat email`; + case "phone": + return i18n.str`Repeat phone`; + } + })()} </label> <div class="mt-2.5"> <input - type="email" - name="email" - id="email" - ref={focus ? doAutoFocus : undefined} - maxLength={512} - autocomplete="email" - value={email} + type="text" + name="repeat-address" + id="repeat-address" + value={repeat ?? ""} onChange={(e) => { - setEmail(e.currentTarget.value); + setRepeat(e.currentTarget.value); }} - placeholder={prevEmail} - readOnly={status.fix_address} - class="block w-full read-only:bg-slate-200 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" + autocomplete={(function (): string { + switch (config.address_type) { + case "email": + return "email"; + case "phone": + return "phone"; + } + })()} + 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?.email} - isDirty={email !== undefined} + message={errors?.repeat} + isDirty={repeat !== undefined} /> </div> </div> + )} - {status.fix_address ? undefined : ( - <div class="sm:col-span-2"> - <label - for="repeat-email" - class="block text-sm font-semibold leading-6 text-gray-900" - > - <i18n.Translate>Repeat email</i18n.Translate> - </label> - <div class="mt-2.5"> - <input - type="email" - name="repeat-email" - id="repeat-email" - value={repeat} - onChange={(e) => { - setRepeat(e.currentTarget.value); - }} - autocomplete="email" - 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?.repeat} - isDirty={repeat !== undefined} - /> - </div> - </div> - )} + {lastStatus === undefined ? undefined : ( + <p class="mt-2 text-sm leading-6 text-gray-400"> + {lastStatus.changes_left < 1 ? ( + <i18n.Translate> + You can'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> + )} - {!status.changes_left ? ( - <p class="mt-3 text-sm leading-6 text-gray-400"> - <i18n.Translate>No more changes left</i18n.Translate> - </p> - ) : ( - <p class="mt-3 text-sm leading-6 text-gray-400"> + <div class="flex items-center justify-between py-2"> + <span class="flex flex-grow flex-col"> + <span + class="text-sm text-black font-medium leading-6 " + id="availability-label" + > <i18n.Translate> - You can change your email address another{" "} - {status.changes_left} times. + Remember this address for future challenges. </i18n.Translate> - </p> - )} + </span> + </span> + <button + type="button" + name={`remember switch`} + data-enabled={remember} + class="bg-indigo-600 data-[enabled=false]:bg-gray-200 relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-indigo-600 focus:ring-offset-2" + role="switch" + aria-checked="false" + aria-labelledby="availability-label" + aria-describedby="availability-description" + onClick={() => { + setRemember(!remember); + }} + > + <span + aria-hidden="true" + data-enabled={remember} + class="translate-x-5 data-[enabled=false]:translate-x-0 pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out" + ></span> + </button> </div> - - {!prevEmail ? ( + </form> + <div class="mx-auto mt-4 max-w-xl "> + {!prevAddr ? ( <div class="mt-10"> <Button type="submit" @@ -235,7 +432,14 @@ export function AskChallenge({ 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={onSend} > - <i18n.Translate>Send email</i18n.Translate> + {(function (): TranslatedString { + switch (config.address_type) { + case "email": + return i18n.str`Send email`; + case "phone": + return i18n.str`Send SMS`; + } + })()} </Button> </div> ) : ( @@ -246,11 +450,18 @@ export function AskChallenge({ 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={onSend} > - <i18n.Translate>Change email</i18n.Translate> + {(function (): TranslatedString { + switch (config.address_type) { + case "email": + return i18n.str`Change email`; + case "phone": + return i18n.str`Change phone`; + } + })()} </Button> </div> )} - </form> + </div> </div> </Fragment> ); diff --git a/packages/challenger-ui/src/pages/CallengeCompleted.tsx b/packages/challenger-ui/src/pages/CallengeCompleted.tsx index f8cd7ce60..bff7b68f5 100644 --- a/packages/challenger-ui/src/pages/CallengeCompleted.tsx +++ b/packages/challenger-ui/src/pages/CallengeCompleted.tsx @@ -13,14 +13,32 @@ 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 { VNode, h } from "preact"; +import { Attention, useTranslationContext } from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useSessionState } from "../hooks/session.js"; +import { useEffect } from "preact/hooks"; -type Props = { - nonce: string; -} -export function CallengeCompleted({nonce}:Props):VNode { +export function CallengeCompleted(): VNode { + const { state } = useSessionState(); + + const { i18n } = useTranslationContext(); - return <div> - completed {nonce} - </div> -}
\ No newline at end of file + useEffect(() => { + window.location.href = state?.completedURL ?? "#" + },[]) + + return ( + <div class="m-4"> + <Attention + title={i18n.str`Challenge completed`} + type="success" + > + <i18n.Translate> + You will be redirected to <a href={state?.completedURL} class="break-all">" + {state?.completedURL} + "</a> + </i18n.Translate> + </Attention> + </div> + ); +} diff --git a/packages/challenger-ui/src/pages/Frame.tsx b/packages/challenger-ui/src/pages/Frame.tsx index 612eced0b..7f81b9d77 100644 --- a/packages/challenger-ui/src/pages/Frame.tsx +++ b/packages/challenger-ui/src/pages/Frame.tsx @@ -14,56 +14,121 @@ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ -import { ComponentChildren, Fragment, h, VNode } from "preact"; +import { TranslatedString } from "@gnu-taler/taler-util"; +import { + Footer, + Header, + ToastBanner, + notifyError, + notifyException, + useTranslationContext, +} from "@gnu-taler/web-util/browser"; +import { ComponentChildren, Fragment, VNode, h } from "preact"; +import { useEffect, useErrorBoundary } from "preact/hooks"; +import { + getAllBooleanPreferences, + getLabelForPreferences, + usePreferences, +} from "../context/preferences.js"; +import { useSettingsContext } from "../context/settings.js"; + +const GIT_HASH = typeof __GIT_HASH__ !== "undefined" ? __GIT_HASH__ : undefined; +const VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : undefined; export function Frame({ children }: { children: ComponentChildren }): VNode { + const settings = useSettingsContext(); + const [preferences, updatePreferences] = usePreferences(); + + const [error, resetError] = useErrorBoundary(); + const { i18n } = useTranslationContext(); + useEffect(() => { + if (error) { + if (error instanceof Error) { + console.log("Internal error, please report", error); + notifyException(i18n.str`Internal error, please report.`, error); + } else { + console.log("Internal error, please report", error); + notifyError( + i18n.str`Internal error, please report.`, + String(error) as TranslatedString, + ); + } + resetError(); + } + }, [error]); + return ( - <Fragment> - <header class="bg-indigo-600 w-full mx-auto px-2 border-b border-opacity-25 border-indigo-400"> - <div class="flex flex-row h-16 items-center "> - <div class="flex px-2 justify-start"> - <div class="flex-shrink-0 bg-white rounded-lg"> - <a href="#"> - <img - class="h-8 w-auto" - src='data:image/svg+xml,<?xml version="1.0" encoding="UTF-8" standalone="no"?>%0A<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 201 90">%0A <g fill="%230042b3" fill-rule="evenodd" stroke-width=".3">%0A <path d="M86.7 1.1c15.6 0 29 9.4 36 23.2h-5.9A35.1 35.1 0 0086.7 6.5C67 6.5 51 23.6 51 44.7c0 10.4 3.8 19.7 10 26.6a31.4 31.4 0 01-4.2 3A45.2 45.2 0 0146 44.7c0-24 18.2-43.6 40.7-43.6zm35.8 64.3a40.4 40.4 0 01-39 22.8c3-1.5 6-3.5 8.6-5.7a35.6 35.6 0 0024.6-17.1z" />%0A <path d="M64.2 1.1l3.1.1c-3 1.6-5.9 3.5-8.5 5.8a37.5 37.5 0 00-30.2 37.7c0 14.3 7.3 26.7 18 33.3a29.6 29.6 0 01-8.5.2c-9-8-14.6-20-14.6-33.5 0-24 18.2-43.6 40.7-43.6zm5.4 81.4a35.6 35.6 0 0024.6-17.1h5.9a40.4 40.4 0 01-39 22.8c3-1.5 5.9-3.5 8.5-5.7zm24.8-58.2a37 37 0 00-12.6-12.8 29.6 29.6 0 018.5-.2c4 3.6 7.4 8 9.9 13z" />%0A <path d="M41.8 1.1c1 0 2 0 3.1.2-3 1.5-5.9 3.4-8.5 5.6A37.5 37.5 0 006.1 44.7c0 21.1 16 38.3 35.7 38.3 12.6 0 23.6-7 30-17.6h5.8a40.4 40.4 0 01-35.8 23C19.3 88.4 1 68.8 1 44.7c0-24 18.2-43.6 40.7-43.6zm30.1 23.2a38.1 38.1 0 00-4.5-6.1c1.3-1.2 2.7-2.2 4.3-3 2.3 2.7 4.4 5.8 6 9.1z" />%0A </g>%0A <path d="M76.1 34.4h9.2v-5H61.9v5H71v26h5.1zM92.6 52.9h13.7l3 7.4h5.3l-12.7-31.2h-4.7L84.5 60.3h5.2zm11.8-4.9h-9.9l5-12.4zM123.8 29.4h-4.6v31h20.6v-5h-16zM166.5 29.4H145v31h21.6v-5H150v-8.3h14.5v-4.9h-14.5v-8h16.4zM191.2 39.5c0 1.6-.5 2.8-1.6 3.8s-2.6 1.4-4.4 1.4h-7.4V34.3h7.4c1.9 0 3.4.4 4.4 1.3 1 .9 1.6 2.2 1.6 3.9zm6 20.8l-7.7-11.7c1-.3 1.9-.7 2.7-1.3a8.8 8.8 0 003.6-4.6c.4-1 .5-2.2.5-3.5 0-1.5-.2-2.9-.7-4.1a8.4 8.4 0 00-2.1-3.1c-1-.8-2-1.5-3.4-2-1.3-.4-2.8-.6-4.5-.6h-12.9v31h5V49.4h6.5l7 10.8z" />%0A</svg>' - alt="GNU Taler" - style="height: 1.5rem; margin: 0.5rem;" - /> - </a> - </div> - <span class="flex items-center text-white text-lg font-bold ml-4"> - Challenger - </span> + <div + class="min-h-full flex flex-col m-0 bg-slate-200" + style="min-height: 100vh;" + > + <Header + title="Challenger" + onLogout={undefined} + iconLinkURL="#" + sites={preferences.showChallangeSetup ? [ + ["New challenge","#/setup/1"] + ] :[]} + supportedLangs={["en"]} + > + <li> + <div class="text-xs font-semibold leading-6 text-gray-400"> + <i18n.Translate>Preferences</i18n.Translate> </div> - <div class="block flex-1 ml-6 "></div> - <div class="flex justify-end"></div> + <ul role="list" class="space-y-4"> + {getAllBooleanPreferences().map((set) => { + const isOn: boolean = !!preferences[set]; + return ( + <li key={set} class="pl-2"> + <div class="flex items-center justify-between"> + <span class="flex flex-grow flex-col"> + <span + class="text-sm text-black font-medium leading-6 " + id="availability-label" + > + {getLabelForPreferences(set, i18n)} + </span> + </span> + <button + type="button" + name={`${set} switch`} + data-enabled={isOn} + class="bg-indigo-600 data-[enabled=false]:bg-gray-200 relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-indigo-600 focus:ring-offset-2" + role="switch" + aria-checked="false" + aria-labelledby="availability-label" + aria-describedby="availability-description" + onClick={() => { + updatePreferences(set, !isOn); + }} + > + <span + aria-hidden="true" + data-enabled={isOn} + class="translate-x-5 data-[enabled=false]:translate-x-0 pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out" + ></span> + </button> + </div> + </li> + ); + })} + </ul> + </li> + </Header> + + <div class="fixed z-20 top-14 w-full"> + <div class="mx-auto w-4/5"> + <ToastBanner /> </div> - </header> + </div> <main class="flex-1">{children}</main> - - <footer class="bottom-4 mb-4"> - <div class="mt-8 mx-8 md:order-1 md:mt-0"> - <div> - <p class="text-xs leading-5 text-gray-400"> - Learn more about{" "} - <a - target="_blank" - rel="noreferrer noopener" - class="font-semibold text-gray-500 hover:text-gray-400" - href="https://taler.net" - > - GNU Taler - </a> - </p> - </div> - <div style="flex-grow: 1;"></div> - <p class="text-xs leading-5 text-gray-400"> - Copyright © 2014—2023 Taler Systems SA.{" "} - </p> - </div> - </footer> - </Fragment> + + <Footer + testingUrlKey="challenger-base-url" + GIT_HASH={GIT_HASH} + VERSION={VERSION} + /> + </div> ); } diff --git a/packages/challenger-ui/src/pages/Setup.tsx b/packages/challenger-ui/src/pages/Setup.tsx index f431835aa..c7395f605 100644 --- a/packages/challenger-ui/src/pages/Setup.tsx +++ b/packages/challenger-ui/src/pages/Setup.tsx @@ -13,47 +13,84 @@ 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 { AccessToken, HttpStatusCode, encodeCrock, randomBytes } from "@gnu-taler/taler-util"; +import { + HttpStatusCode, + createClientSecretAccessToken, + createRFC8959AccessTokenEncoded, + encodeCrock, + randomBytes, +} from "@gnu-taler/taler-util"; import { Button, LocalNotificationBanner, + ShowInputErrorLabel, useChallengerApiContext, useLocalNotificationHandler, useTranslationContext, } from "@gnu-taler/web-util/browser"; import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { safeToURL } from "../Routing.js"; import { useSessionState } from "../hooks/session.js"; +import { doAutoFocus, undefinedIfEmpty } from "./AnswerChallenge.js"; type Props = { clientId: string; - onCreated: (nonce:string) => void; + secret: string | undefined; + redirectURL: URL | undefined; + onCreated: () => void; + focus?: boolean; }; -export function Setup({ clientId, onCreated }: Props): VNode { +export function Setup({ + clientId, + secret, + redirectURL, + focus, + onCreated, +}: Props): VNode { const { i18n } = useTranslationContext(); const [notification, withErrorHandler] = useLocalNotificationHandler(); const { lib } = useChallengerApiContext(); const { start } = useSessionState(); + const [password, setPassword] = useState<string | undefined>(secret); + const [url, setUrl] = useState<string | undefined>(redirectURL?.href); - const onStart = withErrorHandler( - async () => { - return lib.challenger.setup(clientId, "secret-token:chal-secret" as AccessToken); - }, - (ok) => { - start({ - clientId, - redirectURL: "http://exchange.taler.test:1180/kyc-proof/kyc-provider-wallet", - state: encodeCrock(randomBytes(32)), - }); + const errors = undefinedIfEmpty({ + password: !password ? i18n.str`required` : undefined, + url: !url + ? i18n.str`required` + : !safeToURL(url) + ? i18n.str`invalid format` + : undefined, + }); - onCreated(ok.body.nonce); - }, - (fail) => { - switch (fail.case) { - case HttpStatusCode.NotFound: - return i18n.str`Client doesn't exist.`; - } - }, - ); + const onStart = + !!errors || password === undefined || url === undefined + ? undefined + : withErrorHandler( + async () => { + return lib.challenger.setup( + clientId, + createRFC8959AccessTokenEncoded(password), + ); + }, + (ok) => { + start({ + nonce: ok.body.nonce, + clientId, + redirectURL: url, + state: encodeCrock(randomBytes(32)), + }); + + onCreated(); + }, + (fail) => { + switch (fail.case) { + case HttpStatusCode.NotFound: + return i18n.str`Client doesn't exist.`; + } + }, + ); return ( <Fragment> @@ -67,15 +104,81 @@ export function Setup({ clientId, onCreated }: Props): VNode { </i18n.Translate> </h2> </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" - handler={onStart} + + <form + method="POST" + class="mx-auto mt-4 max-w-xl sm:mt-20" + onSubmit={(e) => { + e.preventDefault(); + }} + > + <div class="sm:col-span-2"> + <label + for="email" + class="block text-sm font-semibold leading-6 text-gray-900" > - <i18n.Translate>Start</i18n.Translate> - </Button> + <i18n.Translate>Password</i18n.Translate> + </label> + <div class="mt-2.5"> + <input + type="password" + name="password" + id="password" + ref={focus ? doAutoFocus : undefined} + maxLength={512} + autocomplete="password" + value={password} + onChange={(e) => { + setPassword(e.currentTarget.value); + }} + readOnly={secret !== undefined} + class="block w-full read-only:bg-slate-200 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?.password} + isDirty={password !== undefined} + /> + </div> </div> + + <div class="sm:col-span-2"> + <label + for="email" + class="block text-sm font-semibold leading-6 text-gray-900" + > + <i18n.Translate>Redirect URL</i18n.Translate> + </label> + <div class="mt-2.5"> + <input + type="text" + name="redirect_url" + id="redirect_url" + maxLength={512} + autocomplete="redirect_url" + value={url} + onChange={(e) => { + setUrl(e.currentTarget.value); + }} + readOnly={redirectURL !== undefined} + class="block w-full read-only:bg-slate-200 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?.url} + isDirty={url !== undefined} + /> + </div> + </div> + </form> + <div class="mt-10"> + <Button + type="submit" + disabled={!onStart} + 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={onStart} + > + <i18n.Translate>Start</i18n.Translate> + </Button> + </div> </div> </Fragment> ); |