From d046653246d4b397bf81cfadbdfe2d91b46c7e7f Mon Sep 17 00:00:00 2001 From: Sebastian Date: Sun, 21 Apr 2024 14:57:13 -0300 Subject: challenger spa --- packages/challenger-ui/build.mjs | 5 +- packages/challenger-ui/copyleft-header.js | 2 +- packages/challenger-ui/dev.mjs | 8 +- packages/challenger-ui/package.json | 39 ++- packages/challenger-ui/postcss.config.js | 15 ++ packages/challenger-ui/src/Routing.tsx | 178 +++++++++++++ packages/challenger-ui/src/app.tsx | 147 ++++++++++ packages/challenger-ui/src/context/settings.ts | 44 +++ packages/challenger-ui/src/hooks/challenge.ts | 58 ++++ packages/challenger-ui/src/hooks/session.ts | 119 +++++++++ packages/challenger-ui/src/i18n/challenger-ui.pot | 34 +++ packages/challenger-ui/src/i18n/strings.ts | 90 +++++++ packages/challenger-ui/src/index.html | 41 +++ packages/challenger-ui/src/index.tsx | 27 ++ .../challenger-ui/src/pages/AnswerChallenge.tsx | 296 +++++++++++++++++++++ packages/challenger-ui/src/pages/AskChallenge.tsx | 287 ++++++++++++++++++++ .../challenger-ui/src/pages/CallengeCompleted.tsx | 25 ++ packages/challenger-ui/src/pages/Frame.tsx | 69 +++++ packages/challenger-ui/src/pages/MissingParams.tsx | 22 ++ packages/challenger-ui/src/pages/NonceNotFound.tsx | 42 +++ packages/challenger-ui/src/pages/Setup.tsx | 82 ++++++ .../challenger-ui/src/pages/StartChallenge.tsx | 138 ++++++++++ packages/challenger-ui/src/settings.json | 3 + packages/challenger-ui/src/settings.ts | 83 ++++++ packages/challenger-ui/tailwind.config.js | 16 +- packages/challenger-ui/tsconfig.json | 46 ++++ 26 files changed, 1900 insertions(+), 16 deletions(-) create mode 100644 packages/challenger-ui/src/Routing.tsx create mode 100644 packages/challenger-ui/src/app.tsx create mode 100644 packages/challenger-ui/src/context/settings.ts create mode 100644 packages/challenger-ui/src/hooks/challenge.ts create mode 100644 packages/challenger-ui/src/hooks/session.ts create mode 100644 packages/challenger-ui/src/i18n/challenger-ui.pot create mode 100644 packages/challenger-ui/src/i18n/strings.ts create mode 100644 packages/challenger-ui/src/index.html create mode 100644 packages/challenger-ui/src/index.tsx create mode 100644 packages/challenger-ui/src/pages/AnswerChallenge.tsx create mode 100644 packages/challenger-ui/src/pages/AskChallenge.tsx create mode 100644 packages/challenger-ui/src/pages/CallengeCompleted.tsx create mode 100644 packages/challenger-ui/src/pages/Frame.tsx create mode 100644 packages/challenger-ui/src/pages/MissingParams.tsx create mode 100644 packages/challenger-ui/src/pages/NonceNotFound.tsx create mode 100644 packages/challenger-ui/src/pages/Setup.tsx create mode 100644 packages/challenger-ui/src/pages/StartChallenge.tsx create mode 100644 packages/challenger-ui/src/settings.json create mode 100644 packages/challenger-ui/src/settings.ts create mode 100644 packages/challenger-ui/tsconfig.json (limited to 'packages/challenger-ui') diff --git a/packages/challenger-ui/build.mjs b/packages/challenger-ui/build.mjs index 95088628c..166647f79 100755 --- a/packages/challenger-ui/build.mjs +++ b/packages/challenger-ui/build.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node /* This file is part of GNU Taler - (C) 2022 Taler Systems S.A. + (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 @@ -20,10 +20,11 @@ import { build } from "@gnu-taler/web-util/build"; await build({ type: "production", source: { - js: ["src/main.js"], + js: ["src/main.js","src/index.tsx"], assets: [{ base: "src", files: [ + "src/index.html", "src/attempts-exhausted.html", "src/enter-address-form.html", "src/enter-email-form.html", diff --git a/packages/challenger-ui/copyleft-header.js b/packages/challenger-ui/copyleft-header.js index 2635717c5..7fa276bea 100644 --- a/packages/challenger-ui/copyleft-header.js +++ b/packages/challenger-ui/copyleft-header.js @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2022 Taler Systems S.A. + (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 diff --git a/packages/challenger-ui/dev.mjs b/packages/challenger-ui/dev.mjs index 41f6b4210..595c3e99e 100755 --- a/packages/challenger-ui/dev.mjs +++ b/packages/challenger-ui/dev.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node /* This file is part of GNU Taler - (C) 2022 Taler Systems S.A. + (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 @@ -18,13 +18,16 @@ import { serve } from "@gnu-taler/web-util/node"; import { initializeDev } from "@gnu-taler/web-util/build"; +const devEntryPoints = ["src/index.tsx", "src/main.js"]; + const build = initializeDev({ type: "development", source: { - js: ["src/main.js"], + js: devEntryPoints, assets: [{ base: "src", files: [ + "src/index.html", "src/attempts-exhausted.html", "src/enter-address-form.html", "src/enter-email-form.html", @@ -39,6 +42,7 @@ const build = initializeDev({ }], }, destination: "./dist/dev", + public: "/app", css: "postcss", }); diff --git a/packages/challenger-ui/package.json b/packages/challenger-ui/package.json index 4f0428af3..acf04f671 100644 --- a/packages/challenger-ui/package.json +++ b/packages/challenger-ui/package.json @@ -9,11 +9,12 @@ "scripts": { "build": "./build.mjs && ./create_must.sh", "check": "tsc", - "clean": "rm -rf dist lib", - "i18n:extract": "pogen extract", - "i18n:merge": "pogen merge", - "i18n:emit": "pogen emit", - "i18n": "pnpm i18n:extract && pnpm i18n:merge && pnpm i18n:emit", + "compile": "tsc && ./build.mjs", + "test": "./test.mjs && mocha --require source-map-support/register 'dist/test/**/*.test.js' 'dist/test/**/test.js'", + "lint": "eslint 'src/**/*.{js,jsx,ts,tsx}'", + "clean": "rm -rf dist lib tsconfig.tsbuildinfo", + "i18n:strings": "pogen extract && pogen merge", + "i18n:translations": "pogen emit", "pretty": "prettier --write src" }, "eslintConfig": { @@ -31,18 +32,36 @@ ] }, "devDependencies": { + "eslint": "^8.56.0", + "@typescript-eslint/eslint-plugin": "^6.19.0", + "@typescript-eslint/parser": "^6.19.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-react": "^7.33.2", "@gnu-taler/pogen": "^0.0.5", - "@gnu-taler/web-util": "workspace:*", "@tailwindcss/forms": "^0.5.3", "@tailwindcss/typography": "^0.5.9", + "@types/chai": "^4.3.0", + "@types/history": "^4.7.8", + "@types/mocha": "^10.0.1", + "@types/node": "^18.11.17", "autoprefixer": "^10.4.14", + "chai": "^4.3.6", "esbuild": "^0.19.9", + "mocha": "9.2.0", "po2json": "^0.4.5", - "postcss": "^8.4.23", - "postcss-cli": "^10.1.0", - "tailwindcss": "^3.3.2" + "tailwindcss": "^3.3.2", + "typescript": "5.3.3" }, "pogen": { - "domain": "aml-backoffice" + "domain": "challenger-ui" + }, + "dependencies": { + "swr": "2.0.3", + "@gnu-taler/taler-util": "workspace:*", + "@gnu-taler/web-util": "workspace:*", + "date-fns": "2.29.3", + "jed": "1.1.1", + "qrcode-generator": "^1.4.4", + "preact": "10.11.3" } } diff --git a/packages/challenger-ui/postcss.config.js b/packages/challenger-ui/postcss.config.js index 2e7af2b7f..c9a60a43c 100644 --- a/packages/challenger-ui/postcss.config.js +++ b/packages/challenger-ui/postcss.config.js @@ -1,3 +1,18 @@ +/* + 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 + */ export default { plugins: { tailwindcss: {}, diff --git a/packages/challenger-ui/src/Routing.tsx b/packages/challenger-ui/src/Routing.tsx new file mode 100644 index 000000000..e1e9434e5 --- /dev/null +++ b/packages/challenger-ui/src/Routing.tsx @@ -0,0 +1,178 @@ +/* + 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 + */ + +import { + urlPattern, + useCurrentLocation, + useNavigationContext, +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; + +import { assertUnreachable } from "@gnu-taler/taler-util"; +import { AnswerChallenge } from "./pages/AnswerChallenge.js"; +import { AskChallenge } from "./pages/AskChallenge.js"; +import { Frame } from "./pages/Frame.js"; +import { MissingParams } from "./pages/MissingParams.js"; +import { NonceNotFound } from "./pages/NonceNotFound.js"; +import { StartChallenge } from "./pages/StartChallenge.js"; +import { Setup } from "./pages/Setup.js"; +import { CallengeCompleted } from "./pages/CallengeCompleted.js"; + +export function Routing(): VNode { + // check session and defined if this is + // public routing or private + return ( + + + + ); +} + +const publicPages = { + authorize: urlPattern<{ nonce: string }>( + /\/authorize\/(?[a-zA-Z0-9]+)/, + ({ nonce }) => `#/authorize/${nonce}`, + ), + ask: urlPattern<{ nonce: string }>( + /\/ask\/(?[a-zA-Z0-9]+)/, + ({ nonce }) => `#/ask/${nonce}`, + ), + answer: urlPattern<{ nonce: string }>( + /\/answer\/(?[a-zA-Z0-9]+)/, + ({ nonce }) => `#/answer/${nonce}`, + ), + completed: urlPattern<{ nonce: string }>( + /\/completed\/(?[a-zA-Z0-9]+)/, + ({ nonce }) => `#/completed/${nonce}`, + ), + setup: urlPattern<{ client: string }>( + /\/setup\/(?[0-9]+)/, + ({ client }) => `#/setup/${client}`, + ), +}; + +function safeGetParam( + ps: Record, + n: string, +): string | undefined { + if (!ps[n] || ps[n].length == 0) return undefined; + return ps[n][0]; +} + +function safeToURL(s: string | undefined): URL | undefined { + if (s === undefined) return undefined; + try { + return new URL(s); + } catch (e) { + return undefined; + } +} + +function PublicRounting(): VNode { + const location = useCurrentLocation(publicPages); + const { navigateTo } = useNavigationContext(); + + if (location === undefined) { + return ; + } + + switch (location.name) { + case "setup": { + return ( + { + navigateTo(publicPages.ask.url({ nonce })) + //response_type=code + //client_id=1 + //redirect_uri=http://exchange.taler.test:1180/kyc-proof/kyc-provider-wallet + //state=123 + }} + /> + ); + } + case "authorize": { + const responseType = safeGetParam(location.params, "response_type"); + const clientId = safeGetParam(location.params, "client_id"); + const redirectURI = safeToURL( + safeGetParam(location.params, "redirect_uri"), + ); + const state = safeGetParam(location.params, "state"); + // http://localhost:8080/app/#/authorize/ASDASD123?response_type=code&client_id=1&redirect_uri=goog.ecom&state=123 + // + + // http://localhost:8080/app/?response_type=code&client_id=1&redirect_uri=http://exchange.taler.test:1180/kyc-proof/kyc-provider-wallet&state=123#/authorize/X9668AR2CFC26X55H0M87GJZXGM45VD4SZE05C5SNS5FADPWN220 + + if ( + !responseType || + !clientId || + !redirectURI || + !state || + responseType !== "code" + ) { + return ; + } + return ( + { + navigateTo( + publicPages.ask.url({ + nonce: location.values.nonce, + }), + ); + }} + /> + ); + } + case "ask": { + return ( + { + navigateTo( + publicPages.answer.url({ + nonce: location.values.nonce, + }), + ); + }} + /> + ); + } + case "answer": { + return ( + { + navigateTo( + publicPages.completed.url({ + nonce: location.values.nonce, + }), + ); + }} + /> + ); + } + case "completed": { + return ; + } + default: + assertUnreachable(location); + } +} diff --git a/packages/challenger-ui/src/app.tsx b/packages/challenger-ui/src/app.tsx new file mode 100644 index 000000000..d85893c07 --- /dev/null +++ b/packages/challenger-ui/src/app.tsx @@ -0,0 +1,147 @@ +/* + 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 + */ + +import { + canonicalizeBaseUrl, + getGlobalLogLevel, + setGlobalLogLevelFromString, +} from "@gnu-taler/taler-util"; +import { + BrowserHashNavigationProvider, + ChallengerApiProvider, + Loading, + TalerWalletIntegrationBrowserProvider, + TranslationProvider, +} from "@gnu-taler/web-util/browser"; +import { useEffect, useState } from "preact/hooks"; +import { SWRConfig } from "swr"; +import { Routing } from "./Routing.js"; +// import { BankCoreApiProvider } from "./context/config.js"; +// import { BrowserHashNavigationProvider } from "./context/navigation.js"; +import { SettingsProvider } from "./context/settings.js"; +// import { TalerWalletIntegrationBrowserProvider } from "./context/wallet-integration.js"; +import { h } from "preact"; +import { strings } from "./i18n/strings.js"; +import { ChallengerUiSettings, fetchSettings } from "./settings.js"; +import { Frame } from "./pages/Frame.js"; +const WITH_LOCAL_STORAGE_CACHE = false; + +export function App() { + const [settings, setSettings] = useState(); + useEffect(() => { + fetchSettings(setSettings); + }, []); + if (!settings) return ; + + const baseUrl = getInitialBackendBaseURL(settings.backendBaseURL); + return ( + + + + + + + + + + + + + + ); +} + +// @ts-expect-error creating a new property for window object +window.setGlobalLogLevelFromString = setGlobalLogLevelFromString; +// @ts-expect-error creating a new property for window object +window.getGlobalLevel = getGlobalLogLevel; + +function localStorageProvider(): Map { + const map = new Map(JSON.parse(localStorage.getItem("app-cache") || "[]")); + + window.addEventListener("beforeunload", () => { + const appCache = JSON.stringify(Array.from(map.entries())); + localStorage.setItem("app-cache", appCache); + }); + return map; +} + +function getInitialBackendBaseURL( + backendFromSettings: string | undefined, +): string { + const overrideUrl = + typeof localStorage !== "undefined" + ? localStorage.getItem("challenger-base-url") + : undefined; + let result: string; + + if (!overrideUrl) { + // normal path + if (!backendFromSettings) { + console.error( + "ERROR: backendBaseURL was overridden by a setting file and missing. Setting value to 'window.origin'", + ); + result = window.origin; + } else { + result = backendFromSettings; + } + } else { + // testing/development path + result = overrideUrl; + } + try { + return canonicalizeBaseUrl(result); + } catch (e) { + // fall back + return canonicalizeBaseUrl(window.origin); + } +} diff --git a/packages/challenger-ui/src/context/settings.ts b/packages/challenger-ui/src/context/settings.ts new file mode 100644 index 000000000..679359200 --- /dev/null +++ b/packages/challenger-ui/src/context/settings.ts @@ -0,0 +1,44 @@ +/* + 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 + */ + +import { ComponentChildren, createContext, h, VNode } from "preact"; +import { useContext } from "preact/hooks"; +import { ChallengerUiSettings } from "../settings.js"; + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +export type Type = ChallengerUiSettings; + +const initial: ChallengerUiSettings = {}; +const Context = createContext(initial); + +export const useSettingsContext = (): Type => useContext(Context); + +export const SettingsProvider = ({ + children, + value, +}: { + value: ChallengerUiSettings; + children: ComponentChildren; +}): VNode => { + return h(Context.Provider, { + value, + children, + }); +}; diff --git a/packages/challenger-ui/src/hooks/challenge.ts b/packages/challenger-ui/src/hooks/challenge.ts new file mode 100644 index 000000000..3df10e21e --- /dev/null +++ b/packages/challenger-ui/src/hooks/challenge.ts @@ -0,0 +1,58 @@ +/* + 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 + */ +import { + ChallengerResultByMethod, + TalerHttpError, +} from "@gnu-taler/taler-util"; +import { useChallengerApiContext } from "@gnu-taler/web-util/browser"; +import _useSWR, { SWRHook, mutate } from "swr"; +import { SessionId } from "./session.js"; +const useSWR = _useSWR as unknown as SWRHook; + +export function revalidateChallengeSession() { + return mutate( + (key) => Array.isArray(key) && key[key.length - 1] === "login", + undefined, + { revalidate: true }, + ); +} + +export function useChallengeSession( + nonce: string, + session: SessionId | undefined, +) { + const { + lib: { bank: api }, + } = useChallengerApiContext(); + + async function fetcher([n, c, r, s]: [string, string, string, string]) { + return await api.login(n, c, r, s); + } + const { data, error } = useSWR< + ChallengerResultByMethod<"login">, + TalerHttpError + >( + !session + ? undefined + : [nonce, session.clientId, session.redirectURL, session.state, "login"], + fetcher, + {}, + ); + + if (data) return data; + if (error) return error; + return undefined; +} diff --git a/packages/challenger-ui/src/hooks/session.ts b/packages/challenger-ui/src/hooks/session.ts new file mode 100644 index 000000000..4bb1bfbc8 --- /dev/null +++ b/packages/challenger-ui/src/hooks/session.ts @@ -0,0 +1,119 @@ +/* + 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 + */ + +import { + Codec, + buildCodecForObject, + codecForBoolean, + codecForNumber, + codecForString, + codecForStringURL, + codecForURL, + codecOptional, +} from "@gnu-taler/taler-util"; +import { buildStorageKey, useLocalStorage } from "@gnu-taler/web-util/browser"; +import { mutate } from "swr"; + +/** + * Has the information to reach and + * authenticate at the bank's backend. + */ +export type SessionId = { + clientId: string; + redirectURL: string; + state: string; +}; + +export type LastChallengeResponse = { + attemptsLeft: number; + nextSend: string; + transmitted: boolean; +}; + +export type SessionState = SessionId & { + email: string | undefined; + lastTry: LastChallengeResponse | undefined; + completedURL: string | undefined; +}; +export const codecForLastChallengeResponse = (): Codec => + buildCodecForObject() + .property("attemptsLeft", codecForNumber()) + .property("nextSend", codecForString()) + .property("transmitted", codecForBoolean()) + .build("LastChallengeResponse"); + +export const codecForSessionState = (): Codec => + buildCodecForObject() + .property("clientId", codecForString()) + .property("redirectURL", codecForStringURL()) + .property("completedURL", codecOptional(codecForStringURL())) + .property("state", codecForString()) + .property("lastTry", codecOptional(codecForLastChallengeResponse())) + .property("email", codecOptional(codecForString())) + .build("SessionState"); + +export interface SessionStateHandler { + state: SessionState | undefined; + start(s: SessionId): void; + accepted(e: string, l: LastChallengeResponse): void; + completed(e: URL): void; +} + +const SESSION_STATE_KEY = buildStorageKey( + "challenger-session", + codecForSessionState(), +); + +/** + * Return getters and setters for + * login credentials and backend's + * base URL. + */ +export function useSessionState(): SessionStateHandler { + const { value: state, update } = useLocalStorage(SESSION_STATE_KEY); + + return { + state, + start(info) { + update({ + ...info, + lastTry: undefined, + completedURL: undefined, + email: undefined, + }); + cleanAllCache(); + }, + accepted(email, lastTry) { + if (!state) return; + update({ + ...state, + email, + lastTry, + }); + }, + completed(url) { + if (!state) return; + update({ + ...state, + completedURL: url.href, + }); + }, + }; +} + +function cleanAllCache(): void { + mutate(() => true, undefined, { revalidate: false }); +} diff --git a/packages/challenger-ui/src/i18n/challenger-ui.pot b/packages/challenger-ui/src/i18n/challenger-ui.pot new file mode 100644 index 000000000..c44674a56 --- /dev/null +++ b/packages/challenger-ui/src/i18n/challenger-ui.pot @@ -0,0 +1,34 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2016-11-23 00:00+0100\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: src/Routing.tsx:130 +#, c-format +msgid "Wrong credentials for \"%1$s\"" +msgstr "" + +#: src/Routing.tsx:138 +#, c-format +msgid "Account not found" +msgstr "" + +#: src/Routing.tsx:155 +#, c-format +msgid "Welcome to %1$s!" +msgstr "" + diff --git a/packages/challenger-ui/src/i18n/strings.ts b/packages/challenger-ui/src/i18n/strings.ts new file mode 100644 index 000000000..ea13fed2e --- /dev/null +++ b/packages/challenger-ui/src/i18n/strings.ts @@ -0,0 +1,90 @@ +/* + 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 + */ +export interface StringsType { + // X-Domain or 'messages' + domain: string; + lang: string; + completeness: number; + plural_forms: string; + locale_data: { + messages: Record; + }; +} +export const strings: Record = {}; + +strings["it"] = { + locale_data: { + messages: { + "": { + domain: "messages", + plural_forms: "nplurals=2; plural=n != 1;", + lang: "it", + }, + } + }, + domain: "messages", + plural_forms: "nplurals=2; plural=n != 1;", + lang: "it", + completeness: 14, +}; + +strings["es"] = { + locale_data: { + messages: { + "": { + domain: "messages", + plural_forms: "nplurals=2; plural=n != 1;", + lang: "es", + }, + } + }, + domain: "messages", + plural_forms: "nplurals=2; plural=n != 1;", + lang: "es", + completeness: 100, +}; + +strings["en"] = { + locale_data: { + messages: { + "": { + domain: "messages", + plural_forms: "nplurals=2; plural=n != 1;", + lang: "en", + }, + } + }, + domain: "messages", + plural_forms: "nplurals=2; plural=(n != 1);", + lang: "en", + completeness: 100, +}; + +strings["de"] = { + locale_data: { + messages: { + "": { + domain: "messages", + plural_forms: "nplurals=2; plural=n != 1;", + lang: "de", + }, + } + }, + domain: "messages", + plural_forms: "nplurals=2; plural=n != 1;", + lang: "de", + completeness: 4, +}; diff --git a/packages/challenger-ui/src/index.html b/packages/challenger-ui/src/index.html new file mode 100644 index 000000000..18f472045 --- /dev/null +++ b/packages/challenger-ui/src/index.html @@ -0,0 +1,41 @@ + + + + + + + + + + + + + Challenger + + + + + + +
+ + diff --git a/packages/challenger-ui/src/index.tsx b/packages/challenger-ui/src/index.tsx new file mode 100644 index 000000000..f559288a3 --- /dev/null +++ b/packages/challenger-ui/src/index.tsx @@ -0,0 +1,27 @@ +/* + 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 + */ + +import { App } from "./app.js"; +import { h, render } from "preact"; +import "./scss/main.css"; + +const app = document.getElementById("app"); + +if (app) { + render(, app); +} else { + console.error("HTML element with id 'app' not found."); +} diff --git a/packages/challenger-ui/src/pages/AnswerChallenge.tsx b/packages/challenger-ui/src/pages/AnswerChallenge.tsx new file mode 100644 index 000000000..69600e2ba --- /dev/null +++ b/packages/challenger-ui/src/pages/AnswerChallenge.tsx @@ -0,0 +1,296 @@ +/* + 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 + */ +import { + ChallengerApi, + HttpStatusCode, + assertUnreachable, +} 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 { useSessionState } from "../hooks/session.js"; + +export const EMAIL_REGEX = /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/; + +type Props = { + nonce: string; + onComplete: () => void; +}; + +function SolveChallengeForm({ + nonce, + onComplete, +}: { + nonce: string; + onComplete: () => void; +}): VNode { + const { lib } = useChallengerApiContext(); + const { i18n } = useTranslationContext(); + const { state, accepted, completed } = useSessionState(); + const [notification, withErrorHandler] = useLocalNotificationHandler(); + const [pin, setPin] = useState(); + const [lastTryError, setLastTryError] = + useState(); + const errors = undefinedIfEmpty({ + pin: !pin ? i18n.str`Can't be empty` : undefined, + }); + + const onSendAgain = + !state || state.email === undefined + ? undefined + : withErrorHandler( + async () => { + if (!state?.email) return; + return await lib.bank.challenge(nonce, { email: state.email }); + }, + (ok) => { + if ('redirectURL' in ok.body) { + completed(ok.body.redirectURL) + } else { + accepted(state.email!, { + attemptsLeft: ok.body.attempts_left, + nextSend: ok.body.next_tx_time, + transmitted: ok.body.transmitted, + }); + } + return undefined; + }, + (fail) => { + switch (fail.case) { + case HttpStatusCode.BadRequest: + 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 onCheck = + lastTryError && lastTryError.exhausted + ? undefined + : withErrorHandler( + async () => { + return lib.bank.solve(nonce, { pin: pin! }); + }, + (ok) => { + completed(ok.body.redirectURL as URL) + onComplete(); + }, + (fail) => { + switch (fail.case) { + case HttpStatusCode.BadRequest: + return i18n.str`Invalid request`; + case HttpStatusCode.Forbidden: { + setLastTryError(fail.body); + return i18n.str`Invalid pin`; + } + case HttpStatusCode.NotFound: + return i18n.str``; + case HttpStatusCode.NotAcceptable: + return i18n.str``; + case HttpStatusCode.TooManyRequests: + return i18n.str``; + case HttpStatusCode.InternalServerError: + return i18n.str``; + default: + assertUnreachable(fail); + } + }, + ); + + if (!state) { + return
no state
; + } + + if (!state.lastTry) { + return
you should do a challenge first
; + } + + return ( + + + +
+
+

+ + Please enter the TAN you received to authenticate. + +

+

+ {state.lastTry.transmitted ? ( + + A TAN was sent to your address "{state.email}". + + ) : ( + + We recently already sent a TAN to your address " + {state.email}". A new TAN will not be transmitted again + before {state.lastTry.nextSend}. + + )} +

+ {!lastTryError ? undefined : ( +

+ + You can try another PIN but just{" "} + {lastTryError.auth_attempts_left} times more. + +

+ )} +
+
{ + e.preventDefault(); + }} + > +
+
+ +
+ { + 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" + /> + +
+
+ +

+ + You have {state.lastTry.attemptsLeft} attempts left. + +

+
+ +
+ +
+
+ +
+
+
+
+ ); +} + +export function AnswerChallenge({ nonce, onComplete }: Props): VNode { + const { i18n } = useTranslationContext(); + + // const result = useChallengeSession(nonce, clientId, redirectURI, state); + + // if (!result) { + // return ; + // } + // if (result instanceof TalerError) { + // return
; + // } + + // if (result.type === "fail") { + // switch (result.case) { + // case HttpStatusCode.BadRequest: { + // return ( + // + // + // Could not start the challenge, check configuration. + // + // + // ); + // } + // case HttpStatusCode.NotFound: { + // return ( + // + // Nonce not found + // + // ); + // } + // case HttpStatusCode.NotAcceptable: { + // return ( + // + // + // Server has wrong template configuration + // + // + // ); + // } + // case HttpStatusCode.InternalServerError: { + // return ( + // + // Check logs + // + // ); + // } + // default: + // assertUnreachable(result); + // } + // } + + return ; +} + +export function undefinedIfEmpty(obj: T): T | undefined { + return Object.keys(obj).some( + (k) => (obj as Record)[k] !== undefined, + ) + ? obj + : undefined; +} diff --git a/packages/challenger-ui/src/pages/AskChallenge.tsx b/packages/challenger-ui/src/pages/AskChallenge.tsx new file mode 100644 index 000000000..71f45dde3 --- /dev/null +++ b/packages/challenger-ui/src/pages/AskChallenge.tsx @@ -0,0 +1,287 @@ +/* + 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 + */ +import { + Attention, + Button, + Loading, + LocalNotificationBanner, + ShowInputErrorLabel, + useChallengerApiContext, + useLocalNotificationHandler, + useTranslationContext, +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { useChallengeSession } from "../hooks/challenge.js"; +import { + ChallengerApi, + HttpStatusCode, + TalerError, + assertUnreachable, +} from "@gnu-taler/taler-util"; +import { useSessionState } from "../hooks/session.js"; + +type Form = { + email: string; +}; +export const EMAIL_REGEX = /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/; + +type Props = { + nonce: string; + onSendSuccesful: () => void; +}; + +function ChallengeForm({ + nonce, + status, + onSendSuccesful, +}: { + nonce: string; + status: ChallengerApi.ChallengeStatus; + onSendSuccesful: () => void; +}): VNode { + const prevEmail = !status.last_address + ? undefined + : ((status.last_address as any)["email"] as string); + const regexEmail = !status.restrictions + ? undefined + : ((status.restrictions as any)["email"] as { + regex?: string; + hint?: string; + hint_i18n?: string; + }); + + const { lib } = useChallengerApiContext(); + const { i18n } = useTranslationContext(); + const [notification, withErrorHandler] = useLocalNotificationHandler(); + const [email, setEmail] = useState(prevEmail); + const { accepted, completed } = useSessionState(); + const [repeat, setRepeat] = useState(); + + const errors = undefinedIfEmpty({ + email: !email + ? i18n.str`required` + : regexEmail && regexEmail.regex + ? !new RegExp(regexEmail.regex).test(email) + ? regexEmail.hint + ? regexEmail.hint + : `invalid` + : undefined + : !EMAIL_REGEX.test(email) + ? i18n.str`invalid email` + : email !== repeat + ? i18n.str`emails don't match` + : undefined, + repeat: !repeat ? i18n.str`required` : undefined, + }); + + const onSend = withErrorHandler( + async () => { + return lib.bank.challenge(nonce, { email: email! }); + }, + (ok) => { + if ("redirectURL" in ok.body) { + completed(ok.body.redirectURL); + } else { + accepted(email!, { + 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.NotFound: + return i18n.str``; + case HttpStatusCode.NotAcceptable: + return i18n.str``; + case HttpStatusCode.TooManyRequests: + return i18n.str``; + case HttpStatusCode.InternalServerError: + return i18n.str``; + } + }, + ); + + return ( + + + +
+
+

+ Enter contact details +

+

+ + You will receive an email with a TAN code that must be provided on + the next page. + +

+
+
{ + e.preventDefault(); + }} + > +
+
+ +
+ { + setEmail(e.currentTarget.value); + }} + readOnly={status.fix_address} + 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" + /> + +
+
+ +
+ +
+ { + 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" + /> +
+
+ +

+ + You can change your email address another {status.changes_left}{" "} + times. + +

+
+ +
+ +
+
+
+
+ ); +} + +export function AskChallenge({ nonce, onSendSuccesful }: Props): VNode { + const { i18n } = useTranslationContext(); + const { state } = useSessionState(); + + const result = useChallengeSession(nonce, state); + + if (!result) { + return ; + } + if (result instanceof TalerError) { + return
; + } + + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.BadRequest: { + return ( + + + Could not start the challenge, check configuration. + + + ); + } + case HttpStatusCode.NotFound: { + return ( + + Nonce not found + + ); + } + case HttpStatusCode.NotAcceptable: { + return ( + + + Server has wrong template configuration + + + ); + } + case HttpStatusCode.InternalServerError: { + return ( + + Check logs + + ); + } + default: + assertUnreachable(result); + } + } + + return ( + + ); +} + +export function undefinedIfEmpty(obj: T): T | undefined { + return Object.keys(obj).some( + (k) => (obj as Record)[k] !== undefined, + ) + ? obj + : undefined; +} diff --git a/packages/challenger-ui/src/pages/CallengeCompleted.tsx b/packages/challenger-ui/src/pages/CallengeCompleted.tsx new file mode 100644 index 000000000..24a05c67f --- /dev/null +++ b/packages/challenger-ui/src/pages/CallengeCompleted.tsx @@ -0,0 +1,25 @@ +/* + 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 + */ +import { VNode, h } from "preact"; + +type Props = { + nonce: string; +} +export function CallengeCompleted({nonce}:Props):VNode { + return
+ completed +
+} \ No newline at end of file diff --git a/packages/challenger-ui/src/pages/Frame.tsx b/packages/challenger-ui/src/pages/Frame.tsx new file mode 100644 index 000000000..612eced0b --- /dev/null +++ b/packages/challenger-ui/src/pages/Frame.tsx @@ -0,0 +1,69 @@ +/* + 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 + */ + +import { ComponentChildren, Fragment, h, VNode } from "preact"; + +export function Frame({ children }: { children: ComponentChildren }): VNode { + return ( + +
+
+
+
+ + GNU Taler + +
+ + Challenger + +
+
+
+
+
+ +
{children}
+ +
+
+
+

+ Learn more about{" "} + + GNU Taler + +

+
+
+

+ Copyright © 2014—2023 Taler Systems SA.{" "} +

+
+
+
+ ); +} diff --git a/packages/challenger-ui/src/pages/MissingParams.tsx b/packages/challenger-ui/src/pages/MissingParams.tsx new file mode 100644 index 000000000..5eb1e434e --- /dev/null +++ b/packages/challenger-ui/src/pages/MissingParams.tsx @@ -0,0 +1,22 @@ +/* + 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 + */ +import { VNode, h } from "preact"; + +export function MissingParams() :VNode { + return
+ missing params: {window.location.href} +
+} \ No newline at end of file diff --git a/packages/challenger-ui/src/pages/NonceNotFound.tsx b/packages/challenger-ui/src/pages/NonceNotFound.tsx new file mode 100644 index 000000000..16b3d90ef --- /dev/null +++ b/packages/challenger-ui/src/pages/NonceNotFound.tsx @@ -0,0 +1,42 @@ +/* + 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 + */ +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; + +type Form = { + email: string; +}; + +export function NonceNotFound(): VNode { + const { i18n } = useTranslationContext(); + + return ( + +
+
+

+ The URL is wrong +

+

+ Maybe the validation check expired. +

+
+
+
+ ); +} diff --git a/packages/challenger-ui/src/pages/Setup.tsx b/packages/challenger-ui/src/pages/Setup.tsx new file mode 100644 index 000000000..5d23045cf --- /dev/null +++ b/packages/challenger-ui/src/pages/Setup.tsx @@ -0,0 +1,82 @@ +/* + 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 + */ +import { AccessToken, HttpStatusCode, encodeCrock, randomBytes } from "@gnu-taler/taler-util"; +import { + Button, + LocalNotificationBanner, + useChallengerApiContext, + useLocalNotificationHandler, + useTranslationContext, +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useSessionState } from "../hooks/session.js"; + +type Props = { + clientId: string; + onCreated: (nonce:string) => void; +}; +export function Setup({ clientId, onCreated }: Props): VNode { + const { i18n } = useTranslationContext(); + const [notification, withErrorHandler] = useLocalNotificationHandler(); + const { lib } = useChallengerApiContext(); + const { start } = useSessionState(); + + const onStart = withErrorHandler( + async () => { + return lib.bank.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)), + }); + + onCreated(ok.body.nonce); + }, + (fail) => { + switch (fail.case) { + case HttpStatusCode.NotFound: + return i18n.str`Client doesn't exist.`; + } + }, + ); + + return ( + + + +
+
+

+ + Setup new challenge with client ID: "{clientId}" + +

+
+
+ +
+
+
+ ); +} diff --git a/packages/challenger-ui/src/pages/StartChallenge.tsx b/packages/challenger-ui/src/pages/StartChallenge.tsx new file mode 100644 index 000000000..6cf982a3d --- /dev/null +++ b/packages/challenger-ui/src/pages/StartChallenge.tsx @@ -0,0 +1,138 @@ +/* + 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 + */ +import { + Attention, + Button, + Loading, + LocalNotificationBanner, + ShowInputErrorLabel, + useChallengerApiContext, + useLocalNotificationHandler, + useTranslationContext, +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useEffect, useState } from "preact/hooks"; +import { useChallengeSession } from "../hooks/challenge.js"; +import { + ChallengerApi, + HttpStatusCode, + TalerError, + assertUnreachable, +} from "@gnu-taler/taler-util"; +import { useSessionState } from "../hooks/session.js"; + +type Form = { + email: string; +}; +export const EMAIL_REGEX = /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/; + +type Props = { + nonce: string; + clientId: string; + redirectURL: URL; + state: string; + onSendSuccesful: () => void; +}; + + +export function StartChallenge({ + nonce, + clientId, + redirectURL, + state, + onSendSuccesful, +}: Props): VNode { + const { i18n } = useTranslationContext(); + const { start } = useSessionState(); + + const result = useChallengeSession(nonce, { + clientId, + redirectURL: redirectURL.href, + state, + }); + + const session = + result && !(result instanceof TalerError) && result.type === "ok" + ? result.body + : undefined; + + useEffect(() => { + if (session) { + start({ + clientId, + redirectURL: redirectURL.href, + state, + }); + onSendSuccesful(); + } + }, [session]); + + if (!result) { + return ; + } + if (result instanceof TalerError) { + return
; + } + + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.BadRequest: { + return ( + + + Could not start the challenge, check configuration. + + + ); + } + case HttpStatusCode.NotFound: { + return ( + + Nonce not found + + ); + } + case HttpStatusCode.NotAcceptable: { + return ( + + + Server has wrong template configuration + + + ); + } + case HttpStatusCode.InternalServerError: { + return ( + + Check logs + + ); + } + default: + assertUnreachable(result); + } + } + + return ; +} + +export function undefinedIfEmpty(obj: T): T | undefined { + return Object.keys(obj).some( + (k) => (obj as Record)[k] !== undefined, + ) + ? obj + : undefined; +} diff --git a/packages/challenger-ui/src/settings.json b/packages/challenger-ui/src/settings.json new file mode 100644 index 000000000..b3d0476aa --- /dev/null +++ b/packages/challenger-ui/src/settings.json @@ -0,0 +1,3 @@ +{ + "backendBaseURL": "http://challenger.taler.test:1180/" +} diff --git a/packages/challenger-ui/src/settings.ts b/packages/challenger-ui/src/settings.ts new file mode 100644 index 000000000..61d2117fa --- /dev/null +++ b/packages/challenger-ui/src/settings.ts @@ -0,0 +1,83 @@ +/* + 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 + */ + +import { + Codec, + buildCodecForObject, + canonicalizeBaseUrl, + codecForString, + codecOptional +} from "@gnu-taler/taler-util"; + +export interface ChallengerUiSettings { + // Where challenger backend is localted + // default: window.origin without "webui/" + backendBaseURL?: string; + +} + +/** + * Global settings for the bank UI. + */ +const defaultSettings: ChallengerUiSettings = { + backendBaseURL: buildDefaultBackendBaseURL(), +}; + +const codecForChallengerUISettings = (): Codec => + buildCodecForObject() + .property("backendBaseURL", codecOptional(codecForString())) + .build("codecForChallengerUISettings"); + +function removeUndefineField(obj: T): T { + const keys = Object.keys(obj) as Array; + return keys.reduce((prev, cur) => { + if (typeof prev[cur] === "undefined") { + delete prev[cur]; + } + return prev; + }, obj); +} + +export function fetchSettings(listener: (s: ChallengerUiSettings) => void): void { + fetch("./settings.json") + .then((resp) => resp.json()) + .then((json) => codecForChallengerUISettings().decode(json)) + .then((result) => + listener({ + ...defaultSettings, + ...removeUndefineField(result), + }), + ) + .catch((e) => { + console.log("failed to fetch settings", e); + listener(defaultSettings); + }); +} + +function buildDefaultBackendBaseURL(): string | undefined { + if (typeof window !== "undefined") { + const currentLocation = new URL( + window.location.pathname, + window.location.origin, + ).href; + /** + * By default, bank backend serves the html content + * from the /webui root. + */ + return canonicalizeBaseUrl(currentLocation.replace("/webui", "")); + } + throw Error("No default URL"); +} diff --git a/packages/challenger-ui/tailwind.config.js b/packages/challenger-ui/tailwind.config.js index ec51dfbb8..d384690e2 100644 --- a/packages/challenger-ui/tailwind.config.js +++ b/packages/challenger-ui/tailwind.config.js @@ -1,4 +1,18 @@ -/** @type {import('tailwindcss').Config} */ +/* + 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 + */ export default { content: { relative: true, diff --git a/packages/challenger-ui/tsconfig.json b/packages/challenger-ui/tsconfig.json new file mode 100644 index 000000000..9826fac07 --- /dev/null +++ b/packages/challenger-ui/tsconfig.json @@ -0,0 +1,46 @@ +{ + "compilerOptions": { + /* Basic Options */ + "target": "ES2020", + "module": "Node16", + "lib": ["DOM", "ES2020"], + "allowJs": true /* Allow javascript files to be compiled. */, + // "checkJs": true, /* Report errors in .js files. */ + "jsx": "react" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */, + "jsxFactory": "h", + "jsxFragmentFactory": "Fragment", + "noEmit": true /* Do not emit outputs. */, + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + /* Strict Type-Checking Options */ + "strict": true /* Enable all strict type-checking options. */, + "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */, + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + /* Module Resolution Options */ + "moduleResolution": "Node16" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */, + "esModuleInterop": true /* */, + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + "allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */, + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + /* Source Map Options */ + // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + /* Advanced Options */ + "skipLibCheck": true /* Skip type checking of declaration files. */ + }, + "include": ["src/**/*"] +} -- cgit v1.2.3