taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit 1332484f91551aa724512c439b5c5d57b3fee08a
parent 217cbeb018e5fd65141e491b97d2b029f221949c
Author: Florian Dold <dold@taler.net>
Date:   Mon, 23 Nov 2026 17:35:25 +0100

merchant web UI: provision P-256 and Ed25519 payment devices

Diffstat:
Mpackages/taler-merchant-webui/src/api/hooks.test.ts | 22++++++++++++++++++++++
Mpackages/taler-merchant-webui/src/api/hooks/useOtpDevices.ts | 40++++++++++++++++++++++++++++++----------
Mpackages/taler-merchant-webui/src/api/merchantBackendFeatures.test.ts | 13+++++++++++++
Mpackages/taler-merchant-webui/src/api/merchantBackendFeatures.ts | 5+++++
Mpackages/taler-merchant-webui/src/routes/CreateDeviceRoute.tsx | 7++++++-
Mpackages/taler-merchant-webui/src/screens/CreateDeviceScreen.tsx | 137++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Mpackages/taler-merchant-webui/src/screens/DeviceSetupScreen.test.tsx | 26++++++++++++++++++++++++++
Mpackages/taler-merchant-webui/src/screens/DevicesScreen.tsx | 56+++++++++++++++++++++++---------------------------------
Apackages/taler-merchant-webui/src/utils/otpDevices.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
9 files changed, 273 insertions(+), 80 deletions(-)

diff --git a/packages/taler-merchant-webui/src/api/hooks.test.ts b/packages/taler-merchant-webui/src/api/hooks.test.ts @@ -594,6 +594,8 @@ test("an OTP device reports the algorithm the backend recorded", () => { assert.strictEqual(otpAlgorithmKey(0), "none"); assert.strictEqual(otpAlgorithmKey(1), "totp"); assert.strictEqual(otpAlgorithmKey(2), "totp_price"); + assert.strictEqual(otpAlgorithmKey(3), "ecdsa_challenge"); + assert.strictEqual(otpAlgorithmKey(4), "eddsa_challenge"); assert.strictEqual(otpAlgorithmKey(undefined), "unknown"); assert.strictEqual(otpAlgorithmKey(7), "unknown"); }); @@ -636,3 +638,23 @@ test("new OTP devices have no public fallback credential", () => { }, ); }); + +test("signature device requests omit a shared secret on creation and rename", () => { + for (const algorithm of [3, 4]) { + const device = { + id: "door", + name: "Door", + algorithm, + secretKey: "stale TOTP draft", + }; + assert.deepEqual(buildOtpDeviceAddDetails(device), { + otp_device_id: "door", + otp_device_description: "Door", + otp_algorithm: algorithm, + }); + assert.deepEqual(buildOtpDevicePatchDetails(device.id, device), { + otp_device_description: "Door", + otp_algorithm: algorithm, + }); + } +}); diff --git a/packages/taler-merchant-webui/src/api/hooks/useOtpDevices.ts b/packages/taler-merchant-webui/src/api/hooks/useOtpDevices.ts @@ -14,6 +14,7 @@ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ +import { isTotpDevice } from "../../utils/otpDevices.js"; import { useMerchantSWR as useSWR } from "../swr.js"; import type { AccessToken, TalerMerchantApi } from "@gnu-taler/taler-util"; import { merchantClient } from "../client.js"; @@ -28,19 +29,22 @@ export interface OtpDeviceItemHook { id: string; name: string; algorithm?: number; + publicKey?: string; detailError?: ApiFailure; } export function buildOtpDeviceAddDetails(device: { id: string; name: string; - secretKey: string; + secretKey?: string; algorithm: number; }): TalerMerchantApi.OtpDeviceAddDetails { return { otp_device_id: device.id, otp_device_description: device.name, - otp_key: device.secretKey, + ...(isTotpDevice(device.algorithm) && device.secretKey !== undefined + ? { otp_key: device.secretKey } + : {}), otp_algorithm: device.algorithm, }; } @@ -55,14 +59,22 @@ export function buildOtpDevicePatchDetails( ): TalerMerchantApi.OtpDevicePatchDetails { return { otp_device_description: device.name, - ...(device.secretKey === undefined ? {} : { otp_key: device.secretKey }), + ...(!isTotpDevice(device.algorithm) || device.secretKey === undefined + ? {} + : { otp_key: device.secretKey }), otp_algorithm: device.algorithm, }; } export function otpAlgorithmKey( algorithm: number | undefined, -): "none" | "totp" | "totp_price" | "unknown" { +): + | "none" + | "totp" + | "totp_price" + | "ecdsa_challenge" + | "eddsa_challenge" + | "unknown" { switch (algorithm) { case 0: return "none"; @@ -70,6 +82,10 @@ export function otpAlgorithmKey( return "totp"; case 2: return "totp_price"; + case 3: + return "ecdsa_challenge"; + case 4: + return "eddsa_challenge"; default: return "unknown"; } @@ -101,6 +117,7 @@ export function useOtpDevices() { await client.getOtpDeviceDetails(token as AccessToken, e.id), ); e.algorithm = detail.otp_algorithm; + e.publicKey = detail.otp_device_pub; if (detail.device_description !== undefined) e.name = detail.device_description; } catch (cause) { @@ -115,17 +132,20 @@ export function useOtpDevices() { const addOtpDevice = async (device: { id: string; name: string; - secretKey: string; + secretKey?: string; algorithm: number; }) => { - if (!token) return; + if (!token) throw new Error("No authenticated merchant session"); const client = merchantClient(config); const res = await client.addOtpDevice( token as AccessToken, buildOtpDeviceAddDetails(device), ); - unwrapEmpty(res); - await mutate(); + const body = unwrap<TalerMerchantApi.OtpDeviceCreateResponse | undefined>( + res, + ); + void mutate().catch(() => {}); + return body?.otp_device_pub; }; const updateOtpDevice = async ( @@ -136,7 +156,7 @@ export function useOtpDevices() { algorithm: number; }, ) => { - if (!token) return; + if (!token) throw new Error("No authenticated merchant session"); const client = merchantClient(config); const res = await client.updateOtpDevice( token as AccessToken, @@ -148,7 +168,7 @@ export function useOtpDevices() { }; const deleteOtpDevice = async (deviceId: string) => { - if (!token) return; + if (!token) throw new Error("No authenticated merchant session"); const client = merchantClient(config); const res = await client.deleteOtpDevice(token as AccessToken, deviceId); unwrapEmpty(res); diff --git a/packages/taler-merchant-webui/src/api/merchantBackendFeatures.test.ts b/packages/taler-merchant-webui/src/api/merchantBackendFeatures.test.ts @@ -24,3 +24,16 @@ test("report delivery endpoints require a backend supporting protocol v45", () = assert.equal(getMerchantBackendFeatures(version).reportDeliveries, true); } }); + +test("challenge signatures require merchant protocol v43", () => { + for (const [version, signing] of [ + [undefined, false], + ["42:0:30", false], + ["43:0:31", true], + ["44:0:32", true], + ["45:0:33", true], + ] as const) { + const features = getMerchantBackendFeatures(version); + assert.equal(features.challengeSignatures, signing); + } +}); diff --git a/packages/taler-merchant-webui/src/api/merchantBackendFeatures.ts b/packages/taler-merchant-webui/src/api/merchantBackendFeatures.ts @@ -11,6 +11,7 @@ import { LibtoolVersion } from "@gnu-taler/taler-util"; export interface MerchantBackendFeatures { reportDeliveries: boolean; + challengeSignatures: boolean; salesFunnel: boolean; } @@ -23,6 +24,10 @@ export function getMerchantBackendFeatures( // supported merchant API. Replace this constant with a version comparison // once the endpoint is assigned a released protocol version. salesFunnel: false, + challengeSignatures: LibtoolVersion.isCompatible( + "43:0:0", + protocolVersion ?? "", + ), reportDeliveries: LibtoolVersion.isCompatible( "45:0:0", protocolVersion ?? "", diff --git a/packages/taler-merchant-webui/src/routes/CreateDeviceRoute.tsx b/packages/taler-merchant-webui/src/routes/CreateDeviceRoute.tsx @@ -15,13 +15,18 @@ */ import type { VNode } from "preact"; -import { useOtpDevices } from "../api/hooks.js"; +import { getMerchantBackendFeatures } from "../api/merchantBackendFeatures.js"; +import { useMerchantConfig, useOtpDevices } from "../api/hooks.js"; import { CreateDeviceScreen } from "../screens/CreateDeviceScreen.js"; export function CreateDeviceRoute({ editId }: { editId?: string } = {}): VNode { const { devices, resource, addOtpDevice, updateOtpDevice } = useOtpDevices(); + const { config } = useMerchantConfig(); return ( <CreateDeviceScreen + challengeSignatures={ + getMerchantBackendFeatures(config?.version).challengeSignatures + } devices={devices} editId={editId} devicesResource={resource} diff --git a/packages/taler-merchant-webui/src/screens/CreateDeviceScreen.tsx b/packages/taler-merchant-webui/src/screens/CreateDeviceScreen.tsx @@ -27,6 +27,12 @@ import { Header } from "../ui/Header.js"; import { FormActionFooter, useFormFeedback } from "../ui/FormActionFooter.js"; import { ApiErrorBanner } from "../ui/ApiErrorBanner.js"; import type { OtpDeviceItemHook } from "../api/hooks.js"; +import { + algorithmLabel, + isSignatureDevice, + isTotpDevice, +} from "../utils/otpDevices.js"; +import { Button } from "../ui/Button.js"; import type { DeviceItem } from "./DevicesScreen.js"; import { useTranslation, type TranslateFn } from "../context/translation.js"; import { formatErrorMessage } from "../utils/errors.js"; @@ -40,6 +46,7 @@ import { InitialLoadingState } from "../ui/InitialLoadingState.js"; import { ReadErrorBanner } from "../ui/ReadErrorBanner.js"; export interface CreateDeviceScreenProps { + challengeSignatures?: boolean; editId?: string; authenticators?: DeviceItem[]; onSave?: (device: DeviceItem) => void | Promise<void>; @@ -49,50 +56,72 @@ export interface CreateDeviceScreenProps { onAddDevice?: (device: { id: string; name: string; - secretKey: string; + secretKey?: string; algorithm: number; - }) => Promise<unknown>; + }) => Promise<string | void>; onUpdateDevice?: ( id: string, device: { name: string; algorithm: number }, ) => Promise<unknown>; } -/** - * The choices the backend actually stores, as `otp_algorithm`. - * - * The form used to offer four schemes — 8-digit TOTP, counter-based HOTP, an - * HMAC-SHA256 signature — none of which the API has, and then sent algorithm 1 - * whatever was picked. Algorithm 0 is not offered: a machine that computes no - * confirmation code has no reason to be registered here. - * - * `post-private-otp-devices.rst:48-75` also documents `ECDSA_CHALLENGE` (3) - * and `EDDSA_CHALLENGE` (4), but both are marked "since protocol - * **vChallengeConfirmation**", which `api-merchant.rst:70-73` lists under - * *upcoming* versions. Offering them now would mean offering a setting no - * released backend accepts, so these two are what a merchant can pick until - * that version ships. - * - * A factory rather than a module-level constant because `t` only exists inside - * a component, and pogen extracts only strings written as t`` templates. - */ function methodOptions( t: TranslateFn, ): { key: number; label: string; description: string }[] { return [ { key: 1, - label: t`Time-based code`, + label: algorithmLabel(1, t), description: t`The machine and the wallet compute the same code from the time.`, }, { key: 2, - label: t`Time-based code, covering the price`, + label: algorithmLabel(2, t), description: t`As above, but the amount paid is part of what the code covers.`, }, + { + key: 3, + label: algorithmLabel(3, t), + description: t`Verify a merchant-signed challenge with the device’s public key.`, + }, + { + key: 4, + label: algorithmLabel(4, t), + description: t`Verify a merchant-signed challenge with the device’s public key.`, + }, ]; } +function VerificationKey({ value }: { value?: string }): VNode { + const { t } = useTranslation(); + const { copy, copied, error } = useClipboard(); + return ( + <section class="space-y-3 rounded-xl border bg-white p-6"> + <label + for="device-public-key" + class="block font-bold" + >{t`Public verification key`}</label> + {value ? ( + <> + <p class="text-sm">{t`Copy this public key to the device that verifies payment confirmations.`}</p> + <input + id="device-public-key" + readOnly + value={value} + class="w-full rounded border px-3 py-2 font-mono text-sm" + /> + <Button variant="secondary" onClick={() => void copy(value)}> + {copied ? t`✓ Copied` : t`Copy key`} + </Button> + <ApiErrorBanner compact error={error} /> + </> + ) : ( + <p role="status">{t`Public key unavailable. Reopen the device to retrieve it.`}</p> + )} + </section> + ); +} + /** Mount the draft only after authoritative detail is available. */ export function CreateDeviceScreen(props: CreateDeviceScreenProps): VNode { const { t } = useTranslation(); @@ -158,6 +187,7 @@ export function CreateDeviceScreen(props: CreateDeviceScreenProps): VNode { } function CreateDeviceForm({ + challengeSignatures = false, editId, authenticators = [], onSave, @@ -169,6 +199,10 @@ function CreateDeviceForm({ const { t } = useTranslation(); const [, setLocation] = useLocation(); const [created, setCreated] = useState<CreatedDeviceSetup | null>(null); + const [signatureSetup, setSignatureSetup] = useState<{ + publicKey?: string; + name: string; + }>(); const submitting = useRef(false); const [isSubmitting, setIsSubmitting] = useState<boolean>(false); const { @@ -197,7 +231,10 @@ function CreateDeviceForm({ // A new device starts with its name. When editing, no field in particular // comes first. const nameInput = useRef<HTMLInputElement>(null); - useFocusScope({ active: !editingId, initialFocus: () => nameInput.current }); + useFocusScope({ + active: !editingId && !created && !signatureSetup, + initialFocus: () => nameInput.current, + }); const [deviceId, setDeviceId] = useState<string>(existingDevice?.id || ""); const [manualId, setManualId] = useState<boolean>( Boolean(existingDevice?.id), @@ -223,14 +260,22 @@ function CreateDeviceForm({ }; const isEdit = !!editingId; + const signature = isSignatureDevice(method); + + const fixedMethod = isEdit && !isTotpDevice(existingDevice?.algorithm); + const availableMethods = methodOptions(t).filter(({ key }) => { + if (fixedMethod) return key === existingDevice?.algorithm; + return isTotpDevice(key) || (!isEdit && challengeSignatures); + }); const handleSubmit = async (e: Event) => { e.preventDefault(); - if (submitting.current || created || !name.trim()) return; + if (submitting.current || created || signatureSetup || !name.trim()) return; setErrorMsg(""); - const cleanKey = isEdit ? undefined : normalizeRfc3548Base32Key(secretKey); - if (!isEdit && !cleanKey) { + const cleanKey = + isEdit || signature ? undefined : normalizeRfc3548Base32Key(secretKey); + if (!isEdit && !signature && !cleanKey) { setErrorMsg( t`Secret key must contain exactly 32 Base32 characters (A–Z and 2–7).`, "auth_secret_custom", @@ -251,6 +296,7 @@ function CreateDeviceForm({ ...(cleanKey === undefined ? {} : { secretKey: cleanKey }), }; + let publicKey: string | void = undefined; if (onSave) { await onSave(savedDevice); } else if (editingId && onUpdateDevice) { @@ -259,15 +305,13 @@ function CreateDeviceForm({ algorithm: method, }); } else { - await onAddDevice?.({ - id: finalId, - name, - secretKey: cleanKey as string, - algorithm: method, - }); + publicKey = await onAddDevice?.({ ...savedDevice, algorithm: method }); } if (isEdit) { setLocation("/authenticators"); + } else if (signature) { + setSecretKey(""); + setSignatureSetup({ publicKey: publicKey || undefined, name }); } else { setSecretKey(""); setCreated({ @@ -293,6 +337,21 @@ function CreateDeviceForm({ } }; + if (signatureSetup) + return ( + <div class="max-w-3xl space-y-6"> + <Header + onBack={() => setLocation("/authenticators")} + backLabel={t`Offline payment devices`} + title={signatureSetup.name} + subtitle={algorithmLabel(method, t)} + /> + <VerificationKey value={signatureSetup.publicKey} /> + <Button + onClick={() => setLocation("/authenticators")} + >{t`Done`}</Button> + </div> + ); if (created) { return ( <DeviceSetupScreen @@ -315,7 +374,7 @@ function CreateDeviceForm({ ? t`Edit offline payment device` : t`Add offline payment device` } - subtitle={t`Configure an offline vending machine or hardware terminal. The device shares a secret key to verify payment codes without internet access.`} + subtitle={t`Configure how an offline device verifies payment confirmations.`} /> <form onSubmit={handleSubmit} class="space-y-6"> @@ -388,11 +447,13 @@ function CreateDeviceForm({ <div class="bg-white p-6 rounded-xl border border-gray-200 shadow-xs space-y-4"> <div class="border-b border-gray-100 pb-3"> <h3 class="text-base font-bold text-gray-900">{t`2. Verification Method`}</h3> - <p class="text-xs text-gray-500">{t`How the physical machine checks payment codes displayed by wallet.`}</p> + {!fixedMethod && ( + <p class="text-xs text-gray-500">{t`Choose the verification method supported by the device.`}</p> + )} </div> <div class="space-y-3"> - {methodOptions(t).map((opt) => ( + {availableMethods.map((opt) => ( <label key={opt.key} htmlFor={`auth_method_${opt.key}`} @@ -407,6 +468,7 @@ function CreateDeviceForm({ id={`auth_method_${opt.key}`} name="auth_verification_method" value={opt.key} + disabled={fixedMethod} checked={method === opt.key} onChange={() => setMethod(opt.key)} class="mt-1 text-blue-600 focus:ring-blue-500" @@ -427,7 +489,10 @@ function CreateDeviceForm({ </div> </div> - {!isEdit && ( + {isEdit && signature && ( + <VerificationKey value={existingDevice?.publicKey} /> + )} + {!isEdit && !signature && ( <div class="bg-white p-6 rounded-xl border border-gray-200 shadow-xs space-y-4"> <div class="border-b border-gray-100 pb-3 flex items-center justify-between"> <div> diff --git a/packages/taler-merchant-webui/src/screens/DeviceSetupScreen.test.tsx b/packages/taler-merchant-webui/src/screens/DeviceSetupScreen.test.tsx @@ -245,3 +245,29 @@ test("failed creation preserves the draft; async onSave success resets on accoun session.value = originalSession; } }); + +test("a TOTP device keeps its verification methods when edited on a signing-capable merchant", () => { + const container = document.createElement("div"); + try { + act(() => render(<CreateDeviceScreen />, container)); + assert.equal(container.querySelectorAll("input[type=radio]").length, 2); + act(() => + render( + <CreateDeviceScreen + challengeSignatures + editId="counter" + devices={[{ id: "counter", name: "Counter", algorithm: 2 }]} + />, + container, + ), + ); + assert.equal(container.querySelectorAll("input[type=radio]").length, 2); + assert.equal( + container.querySelector<HTMLInputElement>("#auth_method_2")?.checked, + true, + ); + assert.equal(container.querySelector("#auth_method_3"), null); + } finally { + act(() => render(null, container)); + } +}); diff --git a/packages/taler-merchant-webui/src/screens/DevicesScreen.tsx b/packages/taler-merchant-webui/src/screens/DevicesScreen.tsx @@ -35,8 +35,10 @@ import { ReadErrorBanner } from "../ui/ReadErrorBanner.js"; import { InitialLoadingState } from "../ui/InitialLoadingState.js"; import { randomRfc3548Base32Key } from "@gnu-taler/taler-util"; import { resourcePath } from "../routing/resourcePath.js"; +import { algorithmLabel, isTotpDevice } from "../utils/otpDevices.js"; export interface DeviceItem { + publicKey?: string; id: string; name: string; algorithm?: number; @@ -45,22 +47,6 @@ export interface DeviceItem { secretKey?: string; } -function algorithmLabel( - algorithm: number | undefined, - t: (s: TemplateStringsArray | string, ...v: any[]) => string, -): string { - switch (algorithm) { - case 0: - return t`No confirmation code`; - case 1: - return t`Time-based code`; - case 2: - return t`Time-based code, covering the price`; - default: - return t`Unknown`; - } -} - export interface DevicesScreenProps { authenticators?: DeviceItem[]; authenticatorsResource?: RemoteResource<DeviceItem[]>; @@ -132,7 +118,7 @@ export function DevicesScreen({ const handleConfirmRotateKey = async () => { if (!rotatingKeyDevice || isRotating) return; - if (rotatingKeyDevice.algorithm === undefined) { + if (!isTotpDevice(rotatingKeyDevice.algorithm)) { setRotateError(new Error(t`Could not load offline payment devices`)); return; } @@ -235,14 +221,16 @@ export function DevicesScreen({ href={`#${resourcePath("/authenticators", dev.id, "edit")}`} class={rowActionClass} >{t`Edit`}</a> - <button - type="button" - onClick={() => { - setRotateError(undefined); - setRotatingKeyDevice(dev); - }} - class={rowActionClass} - >{t`Replace secret key`}</button> + {isTotpDevice(dev.algorithm) && ( + <button + type="button" + onClick={() => { + setRotateError(undefined); + setRotatingKeyDevice(dev); + }} + class={rowActionClass} + >{t`Replace secret key`}</button> + )} <button type="button" onClick={() => setDeletingDevice(dev)} @@ -317,14 +305,16 @@ export function DevicesScreen({ href={`#${resourcePath("/authenticators", dev.id, "edit")}`} class={rowActionClass} >{t`Edit`}</a> - <button - type="button" - onClick={() => { - setRotateError(undefined); - setRotatingKeyDevice(dev); - }} - class={rowActionClass} - >{t`Replace secret key`}</button> + {isTotpDevice(dev.algorithm) && ( + <button + type="button" + onClick={() => { + setRotateError(undefined); + setRotatingKeyDevice(dev); + }} + class={rowActionClass} + >{t`Replace secret key`}</button> + )} <button type="button" onClick={() => setDeletingDevice(dev)} diff --git a/packages/taler-merchant-webui/src/utils/otpDevices.ts b/packages/taler-merchant-webui/src/utils/otpDevices.ts @@ -0,0 +1,47 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +import type { TranslateFn } from "../context/translation.js"; + +export function isTotpDevice( + algorithm: number | undefined, +): algorithm is 1 | 2 { + return algorithm === 1 || algorithm === 2; +} + +export function isSignatureDevice(algorithm: number | undefined): boolean { + return algorithm === 3 || algorithm === 4; +} + +export function algorithmLabel( + algorithm: number | undefined, + t: TranslateFn, +): string { + switch (algorithm) { + case 0: + return t`No confirmation code`; + case 1: + return t`Time-based code`; + case 2: + return t`Time-based code, covering the price`; + case 3: + return t`Challenge signature (P-256)`; + case 4: + return t`Challenge signature (Ed25519)`; + default: + return t`Unknown`; + } +}