commit 2f9b330275cfeb25b5e88dedd80c525afe09a086
parent d83b7d8ef49ab72bfe5b8ef063a08c0733f68ea2
Author: Florian Dold <dold@taler.net>
Date: Wed, 25 Nov 2026 18:51:12 +0100
wallet web UI: bind observations to their owning port and wallet host
A port can disconnect while registration is still in flight. Keep the
owner and core ID on the running host so cleanup reaches the original
registration even if another port has since reused the public ID.
Issue: https://bugs.taler.net/n/11794
Diffstat:
7 files changed, 342 insertions(+), 93 deletions(-)
diff --git a/packages/wallet-webui/src/api/rpc.ts b/packages/wallet-webui/src/api/rpc.ts
@@ -24,6 +24,7 @@ export type BrowserRpcMessage =
| {
version: typeof BROWSER_RPC_VERSION;
kind: "request";
+ hostId?: string;
mutation: boolean;
request: CoreApiRequestEnvelope;
}
@@ -40,6 +41,7 @@ export type BrowserRpcMessage =
| {
version: typeof BROWSER_RPC_VERSION;
kind: "status";
+ hostId?: string;
status: ConnectionStatus;
};
@@ -72,6 +74,7 @@ export class RpcWalletConnection implements WalletConnection {
readonly client: WalletCoreApiClient;
private nextId = 0;
private closed = false;
+ private hostId?: string;
private status: ConnectionStatus = { state: "connecting" };
private pending = new Map<string, Pending>();
private notificationListeners = new Set<(n: WalletNotification) => void>();
@@ -107,6 +110,7 @@ export class RpcWalletConnection implements WalletConnection {
this.transport.send({
version: BROWSER_RPC_VERSION,
kind: "request",
+ ...(this.hostId && { hostId: this.hostId }),
mutation,
request: { id, operation, args: payload },
});
@@ -163,7 +167,12 @@ export class RpcWalletConnection implements WalletConnection {
if (message.kind === "status") {
if (message.status.state === "disconnected") {
this.disconnect(message.status.reason, message.status.recovery);
- } else this.setStatus(message.status);
+ } else {
+ if (this.hostId && message.hostId && this.hostId !== message.hostId)
+ this.disconnect("wallet host changed");
+ this.hostId = message.hostId;
+ this.setStatus(message.status);
+ }
return;
}
if (message.kind !== "response") return;
@@ -182,6 +191,7 @@ export class RpcWalletConnection implements WalletConnection {
reason: string,
recovery?: Extract<ConnectionStatus, { state: "disconnected" }>["recovery"],
): void {
+ this.hostId = undefined;
const unknownMutationIds: string[] =
this.status.state === "disconnected"
? [...this.status.unknownMutationIds]
diff --git a/packages/wallet-webui/src/platform/extension-background.ts b/packages/wallet-webui/src/platform/extension-background.ts
@@ -3,7 +3,6 @@ import {
RecoveringWalletHost,
existingDatabaseFactory,
} from "./host-recovery.js";
-import { ObservationOwner } from "./observation-owner.js";
import { Result, TalerUriAction, TalerUris } from "@gnu-taler/taler-util";
import {
BROWSER_RPC_VERSION,
@@ -25,12 +24,11 @@ import {
type PageIntegrationConfig,
} from "./page-integration.js";
-const ports = new Set<chrome.runtime.Port>();
-const observationOwners = new Map<chrome.runtime.Port, ObservationOwner>();
+const ports = new Map<chrome.runtime.Port, string>();
function disconnectPort(port: chrome.runtime.Port) {
+ const owner = ports.get(port);
ports.delete(port);
- observationOwners.get(port)?.close();
- observationOwners.delete(port);
+ if (owner) recovery.closeObservationOwner(owner);
}
const inbox = new StoredActionInbox(new ExtensionSessionActionStore());
const recovery = new RecoveringWalletHost(
@@ -39,14 +37,22 @@ const recovery = new RecoveringWalletHost(
recovering ? existingDatabaseFactory(indexedDB) : indexedDB,
notify,
),
- (notification) =>
+ (notification, owner) =>
+ broadcast(
+ {
+ version: BROWSER_RPC_VERSION,
+ kind: "notification",
+ notification,
+ },
+ owner,
+ ),
+ (status) =>
broadcast({
version: BROWSER_RPC_VERSION,
- kind: "notification",
- notification,
+ kind: "status",
+ status,
+ hostId: recovery.instanceId,
}),
- (status) =>
- broadcast({ version: BROWSER_RPC_VERSION, kind: "status", status }),
);
function sendToPort(
@@ -63,15 +69,9 @@ function sendToPort(
}
}
-function broadcast(message: BrowserRpcMessage): void {
- for (const port of ports) {
- if (
- message.kind === "notification" &&
- "observationId" in message.notification &&
- !observationOwners.get(port)?.owns(message.notification.observationId)
- )
- continue;
- sendToPort(port, message);
+function broadcast(message: BrowserRpcMessage, owner?: string): void {
+ for (const [port, portOwner] of ports) {
+ if (owner === undefined || owner === portOwner) sendToPort(port, message);
}
}
@@ -82,16 +82,14 @@ async function getHost(): Promise<RunningWalletHost> {
chrome.runtime.onConnect.addListener((port) => {
if (port.name !== "wallet-ui-v1") return;
- ports.add(port);
- const owner = new ObservationOwner(async (request) =>
- recovery.handle(request),
- );
- observationOwners.set(port, owner);
+ const owner = crypto.randomUUID();
+ ports.set(port, owner);
port.onDisconnect.addListener(() => disconnectPort(port));
sendToPort(port, {
version: BROWSER_RPC_VERSION,
kind: "status",
status: recovery.status,
+ hostId: recovery.instanceId,
});
void getHost().catch(() => {});
port.onMessage.addListener(async (message: BrowserRpcMessage) => {
@@ -106,7 +104,12 @@ chrome.runtime.onConnect.addListener((port) => {
return;
let response;
try {
- response = await owner.handle(message.request);
+ if (recovery.status.state === "connecting") await getHost();
+ if (!ports.has(port)) return;
+ response =
+ message.hostId && recovery.instanceId !== message.hostId
+ ? unavailableCoreResponse(message.request, "wallet host changed")
+ : await recovery.handle(message.request, owner);
} catch {
response = unavailableCoreResponse(
message.request,
diff --git a/packages/wallet-webui/src/platform/host-recovery.ts b/packages/wallet-webui/src/platform/host-recovery.ts
@@ -7,11 +7,10 @@ import {
getErrorDetailFromException,
type CoreApiRequestEnvelope,
type CoreApiResponse,
- type WalletNotification,
} from "@gnu-taler/taler-util";
import type { ConnectionStatus } from "../api/contracts.js";
import { unavailableCoreResponse } from "../api/rpc.js";
-import type { RunningWalletHost } from "./wallet-host.js";
+import type { HostNotificationSink, RunningWalletHost } from "./wallet-host.js";
const delays = [0, 1000, 2000, 4000, 8000, 16000, 32000, 60000];
@@ -33,9 +32,9 @@ export class RecoveringWalletHost implements RunningWalletHost {
constructor(
private create: (
recovering: boolean,
- notify: (n: WalletNotification) => void,
+ notify: HostNotificationSink,
) => Promise<RunningWalletHost>,
- private notify: (n: WalletNotification) => void,
+ private notify: HostNotificationSink,
private changed: (status: ConnectionStatus) => void,
) {}
@@ -99,8 +98,9 @@ export class RecoveringWalletHost implements RunningWalletHost {
if (this.stopped) return;
const reopening = this.opened;
this.opened = true;
- const host = await this.create(reopening, (n) => {
- if (!this.stopped && generation === this.generation) this.notify(n);
+ const host = await this.create(reopening, (n, owner) => {
+ if (!this.stopped && generation === this.generation)
+ this.notify(n, owner);
});
if (this.stopped) {
await host.stop();
@@ -131,7 +131,15 @@ export class RecoveringWalletHost implements RunningWalletHost {
void this.start().catch(() => {});
}
- async handle(request: CoreApiRequestEnvelope) {
+ get instanceId() {
+ return this.current?.instanceId;
+ }
+
+ closeObservationOwner(owner: string) {
+ this.current?.closeObservationOwner?.(owner);
+ }
+
+ async handle(request: CoreApiRequestEnvelope, owner?: string) {
if (this.status.state === "connecting") await this.start().catch(() => {});
const host = this.current;
if (!host || this.stopped)
@@ -141,7 +149,7 @@ export class RecoveringWalletHost implements RunningWalletHost {
);
let response: CoreApiResponse;
try {
- response = await host.handle(request);
+ response = await host.handle(request, owner);
} catch (error) {
response = {
type: "error",
diff --git a/packages/wallet-webui/src/platform/observation-owner.ts b/packages/wallet-webui/src/platform/observation-owner.ts
@@ -4,65 +4,166 @@
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
-import type {
- CoreApiRequestEnvelope,
- CoreApiResponse,
+import {
+ AbsoluteTime,
+ NotificationType,
+ TalerErrorCode,
+ type CoreApiRequestEnvelope,
+ type CoreApiResponse,
+ type RenewObservationsResponse,
+ type WalletNotification,
} from "@gnu-taler/taler-util";
import { WalletApiOperation } from "@gnu-taler/taler-wallet-core";
-/** Cleans up subscriptions even when the port closes during registration. */
-export class ObservationOwner {
- private ids = new Set<string>();
- private closed = false;
- private registering = new Set<string>();
+interface Registration {
+ owner: string;
+ id: string;
+ coreId: string;
+ stopped: boolean;
+}
+
+function validId(id: unknown): id is string {
+ return typeof id === "string" && id.length > 0 && id.length <= 256;
+}
+
+function badRequest(
+ { id, operation }: CoreApiRequestEnvelope,
+ hint: string,
+): CoreApiResponse {
+ return {
+ type: "error",
+ id,
+ operation,
+ error: {
+ code: TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
+ when: AbsoluteTime.now(),
+ hint,
+ },
+ };
+}
+
+/** One routing table per running wallet. A late stop always addresses the original registration. */
+export class ObservationRouter {
+ private byId = new Map<string, Registration>();
+ private byCoreId = new Map<string, Registration>();
+ private nextId = 0;
- owns(id: string): boolean {
- return this.ids.has(id) || this.registering.has(id);
- }
constructor(
private dispatch: (
request: CoreApiRequestEnvelope,
) => Promise<CoreApiResponse>,
) {}
- async handle(request: CoreApiRequestEnvelope): Promise<CoreApiResponse> {
- const args = request.args as { observationId?: unknown } | undefined;
- const id =
- typeof args?.observationId === "string" ? args.observationId : undefined;
- const registering =
- (request.operation === WalletApiOperation.ObserveTransaction ||
- request.operation === WalletApiOperation.ObserveUserAttention ||
- request.operation === WalletApiOperation.ObserveBalanceRefreshInfo) &&
- id !== undefined;
- if (registering) this.registering.add(id);
- let response: CoreApiResponse;
- try {
- response = await this.dispatch(request);
- } finally {
- if (registering) this.registering.delete(id);
- }
- if (registering && response.type !== "error") {
- if (this.closed) this.stop(id);
- else this.ids.add(id);
+ private remove(entry: Registration) {
+ if (this.byId.get(entry.id) === entry) this.byId.delete(entry.id);
+ this.byCoreId.delete(entry.coreId);
+ }
+
+ route(
+ n: WalletNotification,
+ deliver: (n: WalletNotification, owner?: string) => void,
+ ): void {
+ if (!("observationId" in n)) return deliver(n);
+ const entry = this.byCoreId.get(n.observationId);
+ if (!entry) return;
+ if (n.type !== NotificationType.ObservationSnapshot || n.snapshot === null)
+ this.remove(entry);
+ deliver({ ...n, observationId: entry.id }, entry.owner);
+ }
+
+ async handle(
+ owner: string,
+ request: CoreApiRequestEnvelope,
+ ): Promise<CoreApiResponse> {
+ const args = request.args as
+ | { observationId?: unknown; observationIds?: unknown }
+ | undefined;
+ const { operation, id } = request;
+ switch (operation) {
+ case WalletApiOperation.ObserveTransaction:
+ case WalletApiOperation.ObserveBalanceRefreshInfo:
+ case WalletApiOperation.ObserveUserAttention: {
+ const publicId = args?.observationId;
+ if (!validId(publicId))
+ return badRequest(request, "invalid observationId");
+ if (this.byId.has(publicId))
+ return badRequest(request, "observationId is already active");
+ const entry = {
+ owner,
+ id: publicId,
+ coreId: String(++this.nextId),
+ stopped: false,
+ };
+ this.byId.set(publicId, entry);
+ this.byCoreId.set(entry.coreId, entry);
+ try {
+ const response = await this.dispatch({
+ ...request,
+ args: { ...args, observationId: entry.coreId },
+ });
+ if (response.type === "error") this.remove(entry);
+ else if (entry.stopped) this.stop(entry);
+ return response;
+ } catch (error) {
+ this.remove(entry);
+ throw error;
+ }
+ }
+ case WalletApiOperation.StopObservation: {
+ if (!validId(args?.observationId))
+ return badRequest(request, "invalid observationId");
+ const entry = this.byId.get(args.observationId);
+ if (!entry || entry.owner !== owner)
+ return { type: "response", id, operation, result: {} };
+ entry.stopped = true;
+ const response = await this.dispatch({
+ ...request,
+ args: { observationId: entry.coreId },
+ });
+ if (response.type === "response") this.remove(entry);
+ return response;
+ }
+ case WalletApiOperation.RenewObservations: {
+ const ids = args?.observationIds;
+ if (!Array.isArray(ids) || !ids.every(validId))
+ return badRequest(request, "invalid observationIds");
+ const owned = new Map<string, string>();
+ const missing = new Set<string>();
+ for (const id of ids) {
+ const entry = this.byId.get(id);
+ if (entry && entry.owner === owner && !entry.stopped)
+ owned.set(entry.coreId, id);
+ else missing.add(id);
+ }
+ const response = await this.dispatch({
+ ...request,
+ args: { observationIds: [...owned.keys()] },
+ });
+ if (response.type === "error") return response;
+ const result = response.result as RenewObservationsResponse;
+ for (const coreId of result.missingObservationIds)
+ missing.add(owned.get(coreId)!);
+ return { ...response, result: { missingObservationIds: [...missing] } };
+ }
+ default:
+ return this.dispatch(request);
}
- if (
- request.operation === WalletApiOperation.StopObservation &&
- id &&
- response.type !== "error"
- )
- this.ids.delete(id);
- return response;
}
- private stop(id: string) {
+
+ private stop(entry: Registration) {
void this.dispatch({
- id: `stop-${id}`,
+ id: `stop-${entry.coreId}`,
operation: WalletApiOperation.StopObservation,
- args: { observationId: id },
+ args: { observationId: entry.coreId },
}).catch(() => {});
}
- close() {
- this.closed = true;
- for (const id of this.ids) this.stop(id);
- this.ids.clear();
+
+ close(owner: string) {
+ for (const entry of this.byId.values()) {
+ if (entry.owner !== owner) continue;
+ this.remove(entry);
+ entry.stopped = true;
+ this.stop(entry);
+ }
}
}
diff --git a/packages/wallet-webui/src/platform/wallet-host.ts b/packages/wallet-webui/src/platform/wallet-host.ts
@@ -15,15 +15,27 @@ import {
} from "@gnu-taler/taler-wallet-core";
import { BrowserHttpLibrary } from "./browser-http.js";
+import { ObservationRouter } from "./observation-owner.js";
+
+export type HostNotificationSink = (
+ n: WalletNotification,
+ owner?: string,
+) => void;
+
export interface RunningWalletHost {
- handle(request: CoreApiRequestEnvelope): Promise<CoreApiResponse>;
+ readonly instanceId?: string;
+ closeObservationOwner?(owner: string): void;
+ handle(
+ request: CoreApiRequestEnvelope,
+ owner?: string,
+ ): Promise<CoreApiResponse>;
stop(): Promise<void>;
subscribeUnavailable?(listener: (error: Error) => void): () => void;
}
export async function startIndexedDbWalletHost(
factory: IDBFactory,
- notify: (notification: WalletNotification) => void,
+ notify: HostNotificationSink,
): Promise<RunningWalletHost> {
const db = new IdbWalletDbHandle(factory as never);
await db.ensureOpen();
@@ -32,7 +44,7 @@ export async function startIndexedDbWalletHost(
export async function startWalletHost(
db: WalletDbHandle,
- notify: (notification: WalletNotification) => void,
+ notify: HostNotificationSink,
): Promise<RunningWalletHost> {
let wallet: Wallet | undefined;
try {
@@ -62,17 +74,25 @@ export async function startWalletHost(
throw error;
}
const initializedWallet = wallet;
- const unsubscribe = initializedWallet.addNotificationListener(notify);
let stopped = false;
+ const router = new ObservationRouter((request) =>
+ initializedWallet.handleCoreApiRequest(
+ request.operation,
+ request.id,
+ request.args,
+ ),
+ );
+ const unsubscribe = initializedWallet.addNotificationListener((n) => {
+ // Core may already have queued delivery when this instance was retired.
+ if (!stopped) router.route(n, notify);
+ });
return {
+ instanceId: crypto.randomUUID(),
subscribeUnavailable: db.subscribeUnavailable?.bind(db),
- handle(request) {
+ closeObservationOwner: (owner) => router.close(owner),
+ handle(request, owner = "local") {
if (stopped) throw Error("wallet host is stopped");
- return initializedWallet.handleCoreApiRequest(
- request.operation,
- request.id,
- request.args,
- );
+ return router.handle(owner, request);
},
async stop() {
if (!stopped) {
diff --git a/packages/wallet-webui/test/observations.test.ts b/packages/wallet-webui/test/observations.test.ts
@@ -33,7 +33,7 @@ import type {
ConnectionStatus,
WalletConnection,
} from "../src/api/contracts.js";
-import { ObservationOwner } from "../src/platform/observation-owner.js";
+import { ObservationRouter } from "../src/platform/observation-owner.js";
import {
DemoWalletConnection,
demoActionUris,
@@ -245,7 +245,7 @@ test("reconnect replaces registration; errors permit retry and deletion ends it"
test("extension disconnect cleans up registration that completes after disconnect", async () => {
let complete!: (r: CoreApiResponse) => void;
const calls: CoreApiRequestEnvelope[] = [];
- const owner = new ObservationOwner(async (request) => {
+ const router = new ObservationRouter(async (request) => {
calls.push(request);
if (request.operation === WalletApiOperation.ObserveTransaction)
return new Promise((resolve) => (complete = resolve));
@@ -261,8 +261,8 @@ test("extension disconnect cleans up registration that completes after disconnec
id: "register",
args: { observationId: "view", transactionId },
};
- const result = owner.handle(request);
- owner.close();
+ const result = router.handle("port", request);
+ router.close("port");
complete({
type: "response",
id: request.id,
@@ -273,7 +273,7 @@ test("extension disconnect cleans up registration that completes after disconnec
assert.equal(
calls.filter((c) => c.operation === WalletApiOperation.StopObservation)
.length,
- 1,
+ 2,
);
});
@@ -466,3 +466,73 @@ test("a host that lacks lease support receives no registrations", async () => {
handle.dispose();
connection.close();
});
+
+test("routing isolates owners and releases a terminal registration before its acknowledgement", async () => {
+ const calls: CoreApiRequestEnvelope[] = [];
+ let ack!: () => void;
+ const gate = new Promise<void>((r) => (ack = r));
+ const router = new ObservationRouter(async (req) => {
+ calls.push(req);
+ if (req.operation === WalletApiOperation.ObserveUserAttention) await gate;
+ return {
+ type: "response",
+ operation: req.operation,
+ id: req.id,
+ result:
+ req.operation === WalletApiOperation.RenewObservations
+ ? { missingObservationIds: [] }
+ : {},
+ };
+ });
+ const register = (owner: string) =>
+ router.handle(owner, {
+ id: "register",
+ operation: WalletApiOperation.ObserveUserAttention,
+ args: { observationId: "view", lease: true },
+ });
+ const registered = register("first");
+ const coreId = (calls[0].args as { observationId: string }).observationId;
+ assert.equal((await register("second")).type, "error");
+ assert.deepEqual(
+ await router.handle("second", {
+ id: "renew",
+ operation: "renewObservations",
+ args: { observationIds: ["view"] },
+ }),
+ {
+ id: "renew",
+ operation: "renewObservations",
+ type: "response",
+ result: { missingObservationIds: ["view"] },
+ },
+ );
+ assert.deepEqual(calls.at(-1)?.args, { observationIds: [] });
+ await router.handle("second", {
+ id: "stop",
+ operation: "stopObservation",
+ args: { observationId: "view" },
+ });
+ assert.equal(calls.length, 2);
+ const ended = {
+ type: NotificationType.ObservationEnded,
+ observationType: ObservationType.UserAttention,
+ observationId: coreId,
+ reason: "lease-expired",
+ } as const;
+ const recipients: string[] = [];
+ const deliver = (n: WalletNotification, owner?: string) => {
+ assert.ok("observationId" in n && n.observationId === "view");
+ recipients.push(owner!);
+ };
+ router.route(ended, deliver);
+ const replacement = register("second");
+ const nextCoreId = (calls.at(-1)?.args as { observationId: string })
+ .observationId;
+ assert.notEqual(nextCoreId, coreId);
+ ack();
+ await Promise.all([registered, replacement]);
+ router.close("first");
+ router.route(ended, deliver);
+ router.route({ ...ended, observationId: nextCoreId }, deliver);
+ assert.deepEqual(recipients, ["first", "second"]);
+});
diff --git a/packages/wallet-webui/test/rpc.test.ts b/packages/wallet-webui/test/rpc.test.ts
@@ -122,3 +122,40 @@ test("host recovery status preserves unknown outcomes and prevents new sends", a
connection.retryHost();
assert.deepEqual(transport.sent.at(-1), { version: 1, kind: "retry-host" });
});
+
+test("a replacement host invalidates pending calls and receives freshly scoped requests", async () => {
+ const transport = new FakeTransport();
+ const connection = new RpcWalletConnection(transport);
+ const statuses: string[] = [];
+ connection.subscribeStatus((s) => statuses.push(s.state));
+ const connect = (hostId: string) => {
+ for (const listener of transport.messages)
+ listener({
+ version: 1,
+ kind: "status",
+ status: { state: "connected" },
+ hostId,
+ });
+ };
+ connect("first");
+ const pending = connection.client.call(WalletApiOperation.RenewObservations, {
+ observationIds: [],
+ });
+ connect("second");
+ await assert.rejects(pending, HostDisconnectedError);
+ const fresh = connection.client.call(WalletApiOperation.RenewObservations, {
+ observationIds: [],
+ });
+ assert.deepEqual(
+ transport.sent.map((m) => m.kind === "request" && m.hostId),
+ ["first", "second"],
+ );
+ assert.deepEqual(statuses, [
+ "connecting",
+ "connected",
+ "disconnected",
+ "connected",
+ ]);
+ connection.close();
+ await assert.rejects(fresh, HostDisconnectedError);
+});