commit e91aff1074f8442a4fe88c6b0474f47289522932
parent b67126a32aa8bb788d90ebdc06ce17dfc8096690
Author: Florian Dold <dold@taler.net>
Date: Fri, 20 Nov 2026 19:35:19 +0100
harness: persist Riegel keys and lock challenges in a JSON file
Read and write the same key URLs as the Android app. Serialize one-shot
commands with a file lock so simultaneous processes share challenge
slots and cannot overwrite each other’s key selections.
Diffstat:
2 files changed, 525 insertions(+), 0 deletions(-)
diff --git a/packages/taler-harness/src/riegel.test.ts b/packages/taler-harness/src/riegel.test.ts
@@ -0,0 +1,147 @@
+/*
+ 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 assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import {
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { test } from "node:test";
+import { promisify } from "node:util";
+import { encodeCrock } from "@gnu-taler/taler-util";
+import * as door from "./riegel.js";
+
+for (const algorithm of ["3", "4"]) {
+ test(
+ "separate Riegel stores and Android key URLs, algorithm " + algorithm,
+ () => {
+ const lock = door.emptyStore(),
+ key = door.emptyStore();
+ door.template(lock, "taler://pay-template/example.com/door?nfc=1");
+ const id = door.generateKey(key, algorithm, "Front door + key");
+ const pub = door.exportKey(door.findKey(key, id), false);
+ assert.match(
+ pub,
+ new RegExp("^riegel://key/v1/" + algorithm + "/public"),
+ );
+ assert.equal(door.importKey(lock, pub), id);
+ assert.equal(door.findKey(lock, id).label, "Front door + key");
+ assert.throws(() => door.selectKey(lock, "key", id));
+ const uri = door.begin(lock),
+ sig = door.sign(key, uri);
+ assert.equal(sig.length, 103);
+ assert.throws(() => door.verify(lock, uri, "short"));
+ assert.equal(door.verify(lock, uri, sig), "Opened");
+ assert.equal(door.verify(lock, uri, sig), "Opened");
+ const other = door.begin(lock);
+ assert.equal(door.verify(lock, other, sig), "Invalid signature");
+ assert.equal(
+ door.verify(lock, other, door.sign(key, other)),
+ "Invalid signature",
+ );
+ const privateUrl = door.exportKey(door.findKey(key, id), true);
+ assert.equal(door.importKey(lock, privateUrl), id);
+ assert.equal(lock.keys.length, 1);
+ assert.equal(lock.key, id);
+ const pending = door.begin(lock);
+ door.removeKey(lock, id);
+ assert.equal(door.attempt(lock, pending).state, "Cancelled");
+ assert.ok(lock.template.includes("nfc=1"));
+ },
+ );
+}
+
+test("Riegel uses the merchant C implementation's known confirmations", () => {
+ // exchange/src/util/test_crypto_confirmation.c, also used by Android Riegel.
+ const s = door.emptyStore();
+ const ch = encodeCrock(Uint8Array.from({ length: 32 }, (_, i) => 0xf0 - i));
+ door.importKey(
+ s,
+ "041061050R3GG28A1C60T3GF208H44RM2MB1E60S38DHR78Y3WG0",
+ "4",
+ "Merchant",
+ true,
+ );
+ assert.equal(
+ door.sign(s, ch),
+ "VKTQA94GZCQ6R5AWV51X51X4P6Q4EE8F0MXWWZXMGRKJKR2KV2BRBXJG8YV4E0VY56GGCBCG5XAMEV1C1AD9FNXHDBXK4JXNZ008E08",
+ );
+ const ec = door.importKey(
+ s,
+ "0CZV95QR7R1GKGFFDAW2N4ZMAMXTWYF4AHX7XR87F3XW5KZV9C922",
+ "3",
+ );
+ door.selectKey(s, "lock", ec);
+ s.attempts.push({ challenge: ch, state: "Pending", started: Date.now() });
+ assert.equal(
+ door.verify(
+ s,
+ ch,
+ "03Q7RNNBBRPKG4YNH5JH92H557JHHGV92M7MMFXD9MH0MQFJG46QADH7GXNFNGTPD6MD80Y4CC3ESKTRM7AF9PRBXVN4FMYEY7JWMM8",
+ ),
+ "Opened",
+ );
+});
+
+test("one-shot processes share ten slots, persist expiry, and preserve corrupt files", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "riegel-")),
+ path = join(dir, "state.json");
+ try {
+ door.withStore(path, (s) => door.generateKey(s, "4", "Lock"));
+ const moduleUrl = new URL("./riegel.js", import.meta.url).href;
+ const script =
+ "import {withStore,begin} from " +
+ JSON.stringify(moduleUrl) +
+ ";console.log(withStore(process.argv[1],begin));";
+ const calls = await Promise.allSettled(
+ Array.from({ length: 11 }, () =>
+ promisify(execFile)(process.execPath, [
+ "--input-type=module",
+ "-e",
+ script,
+ path,
+ ]),
+ ),
+ );
+ assert.equal(calls.filter((r) => r.status === "fulfilled").length, 10);
+ assert.equal(statSync(path).mode & 0o777, 0o600);
+ const state: door.Store = JSON.parse(readFileSync(path, "utf8"));
+ assert.equal(state.attempts.length, 10);
+ state.attempts[0].started = Date.now() - 120000;
+ writeFileSync(path, JSON.stringify(state));
+ assert.equal(
+ door.withStore(
+ path,
+ (s) => door.attempt(s, state.attempts[0].challenge).state,
+ ),
+ "Expired",
+ );
+ door.withStore(path, door.begin);
+ writeFileSync(path, "corrupt fixture");
+ assert.throws(
+ () => door.withStore(path, door.begin),
+ /Invalid Riegel store/,
+ );
+ assert.equal(readFileSync(path, "utf8"), "corrupt fixture");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/packages/taler-harness/src/riegel.ts b/packages/taler-harness/src/riegel.ts
@@ -0,0 +1,378 @@
+/*
+ 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 { createHash, randomUUID } from "node:crypto";
+import {
+ closeSync,
+ constants,
+ fchmodSync,
+ fsyncSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { spawnSync } from "node:child_process";
+import { URL, URLSearchParams } from "node:url";
+import { homedir } from "node:os";
+import { dirname, join } from "node:path";
+import {
+ ChallengeConfirmationAlgorithm,
+ confirmationPublicKey,
+ decodeConfirmationPublicKey,
+ decodeCrockFixed,
+ encodeCrock,
+ generateConfirmationChallenge,
+ generateConfirmationSecret,
+ parseChallengeConfirmationAlgorithm,
+ signChallengeConfirmation,
+ verifyChallengeConfirmation,
+ TalerUriAction,
+ TalerUris,
+ Result,
+} from "@gnu-taler/taler-util";
+
+type Algorithm = ChallengeConfirmationAlgorithm;
+export interface Key {
+ id: string;
+ label: string;
+ algorithm: Algorithm;
+ publicKey: string;
+ secret?: string;
+}
+type Outcome =
+ | "Pending"
+ | "Opened"
+ | "Expired"
+ | "Cancelled"
+ | "Invalid signature";
+interface Attempt {
+ challenge: string;
+ started: number;
+ state: Outcome;
+}
+export interface Store {
+ version: 1;
+ template: string;
+ keys: Key[];
+ lock?: string;
+ key?: string;
+ attempts: Attempt[];
+}
+
+export function emptyStore(): Store {
+ return {
+ version: 1,
+ template: "taler://pay-template/merchant.example/riegel",
+ keys: [],
+ attempts: [],
+ };
+}
+
+// flock(1) locks the inherited open file description until the parent closes it.
+// A stable sidecar inode keeps the lock valid across atomic JSON replacements.
+export function withStore(
+ path: string | undefined,
+ action: (s: Store) => string,
+): string {
+ path ??= join(
+ process.env.XDG_STATE_HOME || join(homedir(), ".local", "state"),
+ "taler-harness",
+ "riegel.json",
+ );
+ const dir = dirname(path);
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
+ const fd = openSync(
+ path + ".lock",
+ constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW,
+ 0o600,
+ );
+ try {
+ const lock = spawnSync("flock", ["-x", "-w", "10", "3"], {
+ stdio: ["ignore", "ignore", "inherit", fd],
+ });
+ if (lock.error) throw lock.error;
+ if (lock.status !== 0) throw Error("Could not lock Riegel store");
+ let original: string | undefined;
+ try {
+ const jsonFd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
+ try {
+ fchmodSync(jsonFd, 0o600);
+ original = readFileSync(jsonFd, "utf8");
+ } finally {
+ closeSync(jsonFd);
+ }
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
+ }
+ let s: Store;
+ try {
+ s = original === undefined ? emptyStore() : JSON.parse(original);
+ } catch {
+ throw Error("Invalid Riegel store JSON");
+ }
+ if (
+ s?.version !== 1 ||
+ !Array.isArray(s.keys) ||
+ !Array.isArray(s.attempts)
+ )
+ throw Error("Unsupported Riegel store format");
+ const now = Date.now();
+ for (const a of s.attempts) {
+ if (
+ a.state === "Pending" &&
+ (now < a.started || now - a.started >= 120000)
+ )
+ a.state = "Expired";
+ }
+ const result = action(s);
+ const json = JSON.stringify(s, null, 2) + "\n";
+ if (json !== original) {
+ const tmp = path + "." + randomUUID() + ".tmp";
+ const out = openSync(tmp, "wx", 0o600);
+ try {
+ try {
+ writeFileSync(out, json);
+ fsyncSync(out);
+ } finally {
+ closeSync(out);
+ }
+ renameSync(tmp, path);
+ const directory = openSync(dir, "r");
+ try {
+ fsyncSync(directory);
+ } finally {
+ closeSync(directory);
+ }
+ } finally {
+ rmSync(tmp, { force: true });
+ }
+ }
+ return result;
+ } finally {
+ closeSync(fd);
+ }
+}
+
+function material(text: string, size: number): string {
+ const value = text.trim().toUpperCase();
+ if (encodeCrock(decodeCrockFixed(value, size)) !== value)
+ throw Error("Invalid Crockford Base32");
+ return value;
+}
+function label(value: string): string {
+ value = value.trim();
+ if (!value || value.length > 80 || /[\x00-\x1f\x7f-\x9f]/u.test(value))
+ throw Error("Expected a key label of 1–80 printable characters");
+ return value;
+}
+function numberOf(alg: Algorithm) {
+ return alg === "ECDSA_CHALLENGE" ? 3 : 4;
+}
+
+export function addKey(
+ s: Store,
+ algorithm: Algorithm,
+ name: string,
+ input: string,
+ isPrivate: boolean,
+): string {
+ const size = isPrivate || numberOf(algorithm) === 4 ? 32 : 33;
+ const data = material(input, size);
+ const pub = isPrivate ? confirmationPublicKey(algorithm, data) : data;
+ const bytes = decodeConfirmationPublicKey(algorithm, pub);
+ const id = encodeCrock(
+ createHash("sha256")
+ .update(Buffer.from([numberOf(algorithm)]))
+ .update(bytes)
+ .digest(),
+ );
+ const firstSigner = isPrivate && !s.keys.some((k) => k.secret);
+ const first = s.keys.length === 0;
+ const k = s.keys.find((k) => k.id === id) ?? {
+ id,
+ label: "",
+ algorithm,
+ publicKey: pub,
+ };
+ k.label = label(name);
+ if (!s.keys.includes(k)) s.keys.push(k);
+ if (isPrivate) k.secret = data;
+ if (first) s.lock = id;
+ if (firstSigner) s.key = id;
+ return id;
+}
+
+export function generateKey(s: Store, alg: string, name: string) {
+ const algorithm = parseChallengeConfirmationAlgorithm(alg);
+ return addKey(
+ s,
+ algorithm,
+ name,
+ generateConfirmationSecret(algorithm),
+ true,
+ );
+}
+export function importKey(
+ s: Store,
+ input: string,
+ alg?: string,
+ name?: string,
+ isPrivate = false,
+) {
+ if (!input.includes("://")) {
+ if (!alg) throw Error("Raw keys require --algorithm 3 or 4");
+ return addKey(
+ s,
+ parseChallengeConfirmationAlgorithm(alg),
+ name ?? "Imported key",
+ input,
+ isPrivate,
+ );
+ }
+ const u = new URL(input);
+ const m = /^\/v1\/([34])\/(public|private)$/.exec(u.pathname);
+ if (
+ u.protocol !== "riegel:" ||
+ u.host !== "key" ||
+ u.username ||
+ u.password ||
+ !m
+ )
+ throw Error("Invalid Riegel key URL");
+ return addKey(
+ s,
+ parseChallengeConfirmationAlgorithm(m[1]),
+ name ?? u.searchParams.get("label") ?? "Imported key",
+ u.hash.slice(1),
+ m[2] === "private",
+ );
+}
+export function findKey(s: Store, id?: string): Key {
+ const key = s.keys.find((k) => k.id === id);
+ if (!key) throw Error(id ? "Unknown key ID" : "Select a key for this role");
+ return key;
+}
+export function exportKey(k: Key, privatePart: boolean) {
+ if (privatePart && !k.secret) throw Error("Key has no private material");
+ return (
+ "riegel://key/v1/" +
+ numberOf(k.algorithm) +
+ "/" +
+ (privatePart ? "private" : "public") +
+ "?" +
+ new URLSearchParams({ label: k.label }) +
+ "#" +
+ (privatePart ? k.secret : k.publicKey)
+ );
+}
+export function renameKey(s: Store, id: string, name: string) {
+ findKey(s, id).label = label(name);
+ return id;
+}
+function cancelPending(s: Store) {
+ for (const a of s.attempts) if (a.state === "Pending") a.state = "Cancelled";
+}
+export function removeKey(s: Store, id: string) {
+ findKey(s, id);
+ s.keys = s.keys.filter((k) => k.id !== id);
+ if (s.lock === id) {
+ delete s.lock;
+ cancelPending(s);
+ }
+ if (s.key === id) delete s.key;
+ return id;
+}
+export function selectKey(s: Store, role: "key" | "lock", id: string) {
+ const k = findKey(s, id);
+ if (role === "key" && !k.secret)
+ throw Error("Signing requires a private key");
+ if (role === "lock" && s.lock !== id) cancelPending(s);
+ s[role] = id;
+ return id;
+}
+function templateUrl(uri: string): URL {
+ const u = new URL(uri);
+ if (
+ !Result.orUndefined(
+ TalerUris.parseRestricted(uri, TalerUriAction.PayTemplate),
+ ) ||
+ u.hash
+ )
+ throw Error("Expected a payment template URI");
+ return u;
+}
+export function template(s: Store, uri?: string) {
+ if (uri !== undefined && uri !== s.template) {
+ if (templateUrl(uri).searchParams.has("challenge"))
+ throw Error("Template already contains a challenge");
+ s.template = uri;
+ cancelPending(s);
+ }
+ return s.template;
+}
+export function begin(s: Store) {
+ findKey(s, s.lock);
+ if (s.attempts.filter((a) => a.state === "Pending").length >= 10)
+ throw Error("Lock is busy");
+ if (s.attempts.length >= 64)
+ s.attempts.splice(
+ s.attempts.findIndex((a) => a.state !== "Pending"),
+ 1,
+ );
+ const challenge = generateConfirmationChallenge();
+ s.attempts.push({ challenge, started: Date.now(), state: "Pending" });
+ return (
+ s.template +
+ (s.template.includes("?") ? "&" : "?") +
+ "challenge=" +
+ challenge
+ );
+}
+function readChallenge(input: string) {
+ if (!input.includes("://")) return material(input, 32);
+ const values = templateUrl(input).searchParams.getAll("challenge");
+ if (values.length !== 1)
+ throw Error("Expected one challenge in the template URI");
+ return material(values[0], 32);
+}
+export function sign(s: Store, input: string) {
+ const k = findKey(s, s.key);
+ if (!k.secret) throw Error("Signing requires a private key");
+ return signChallengeConfirmation(k.algorithm, k.secret, readChallenge(input));
+}
+export function attempt(s: Store, input: string) {
+ const challenge = readChallenge(input);
+ const a = s.attempts.find((a) => a.challenge === challenge);
+ if (!a) throw Error("Unknown challenge");
+ return a;
+}
+export function verify(s: Store, input: string, response: string) {
+ const a = attempt(s, input);
+ if (a.state === "Pending") {
+ const k = findKey(s, s.lock);
+ a.state = verifyChallengeConfirmation({
+ algorithm: k.algorithm,
+ publicKey: k.publicKey,
+ challenge: a.challenge,
+ confirmation: material(response, 64),
+ })
+ ? "Opened"
+ : "Invalid signature";
+ }
+ return a.state;
+}