Refund mint pinning: make refundApiKey use the mint it was given (routstr-sdk patch)

Patch for routstr-sdk: read the mint out of the token a provider returns for a refund and refuse it when it is not the mint the caller pinned, on both the API-key and x-cashu refund paths. Refusal keeps the claim, never caches the foreign token, and reports expected vs actual mint. 10 new tests; 1339 unit tests pass.

Problem: NIP-1971 cf9ba445…58c4ef — Refund claims are not pinned to the requested mint.
Sibling duplicate: 74b0a555…1b54a2 — Refund claims can be paid from the wrong mint.
Tree: 6181e565… · owner 4bf150c3…21dd · base routstr-sdk@f3f40ed · relays wss://relay.routstr.com, wss://relay.primal.net.

Problem: NIP-1971 cf9ba445…58c4ef — Refund claims are not pinned to the requested mint
(duplicate sibling: 74b0a555…1b54a2 — Refund claims can be paid from the wrong mint).
Base: routstr-sdk@f3f40ed (Merge pull request #146 from Routstr/fix/refund-skip-must-not-arm-cooldown).

What was wrong

BalanceManager.refundApiKey({ mintUrl, baseUrl, apiKey }) took mintUrl and only ever
used it to label errors (_handleRefundError(error, mintUrl, …)). The refund itself:

fetchResult = await this.fetchRefundToken(baseUrl, apiKey);   // no mint in the request
…
const refundToken = fetchResult.token;
this.cashuSpender.cacheReceiveToken(refundToken);             // token parked as-is
const receiveResult = await this.cashuSpender.receiveToken(refundToken, false);

Every Cashu token carries the mint that issued it, so the buyer’s wallet redeems the
refund wherever the node’s wallet (or a server-side foreign-mint swap) minted it —
the provider’s mint, a mint the operator runs, a mint that is hostile, or a mint that is
dead by the time the refund arrives. mintUrl was advisory in name and ignored in fact.

The same shape existed on the x-cashu path: CashuSpender.refundXcashuTokens(mintUrl, …)
received the token the provider returned without asking which mint it came from.

What the patch does

  1. wallet/tokenUtils.ts — two helpers:
    • getTokenMintUrl(token) reads the mint out of the token with getTokenMetadata
      (already a dependency, already used for the amount), normalized; null when the
      token cannot be decoded.
    • normalizeMintUrl(url) — trim, strip trailing slashes, lowercase. Mints are announced
      with and without a trailing slash, and a raw string comparison would refuse a refund
      from the mint the caller pinned for a cosmetic reason.
  2. BalanceManager._refundApiKeyImpl — before the token is cached or received, compare
    the token’s mint with the caller’s mintUrl. On a readable mismatch the refund is
    refused: nothing is received, nothing is cached, the API key is kept (it is the
    only record of the claim), and the result carries mintMismatch: { expected, actual }
    plus a message naming both mints.
  3. CashuSpender.refundXcashuTokens — the same pin on the x-cashu path; on mismatch the
    x-cashu claim stays in storage and no retry count is burned on a token that cannot be
    retried into the right mint.
  4. RefundResult.mintMismatch — the refusal is machine-readable, not only a log line.

Design decisions, and why

  • Refusal over silent acceptance. Receiving the token is what moves the money; the only
    safe moment to decline a mint you did not ask for is before the receive. The claim is not
    destroyed: the API key stays stored, so the caller can retrieve it (or accept the node’s
    mint deliberately, see below).
  • An unreadable token is not a mismatch. receiveToken decodes with the same library,
    so a token getTokenMetadata cannot read is a token the wallet cannot receive either.
    Turning “unfamiliar format” into “refused refund” would lose real refunds (legacy
    encodings); the pin therefore only fires on a mint that is readable and different.
    This is also why the existing suite is unchanged: placeholder tokens still flow through.
  • Two opt-outs, both explicit. mintUrl: "" means “pin nothing” (the pre-patch
    behaviour), and allowForeignRefundMint: true accepts the node’s mint for a caller that
    has decided to trust it. Nothing changes for callers who pass their own mint and whose
    nodes refund from it.
  • No wire change. I checked routstr-core@master: /v1/wallet/refund takes
    RefundRequest{ lightning_address } only, and the destination mint is chosen server-side
    from key.refund_mint_url / foreign_mint_swap.refund_destination_mint. Sending a
    mint_url field would be silently ignored by Pydantic, i.e. a fake contract. The pin is
    the half the client can enforce today; if the node grows a destination-mint field, the
    same comparison becomes the assertion that the node honoured it.

Verification

  • npx vitest run tests/unit — 1339 passed / 98 files (10 of them new, in
    tests/unit/refundMintPinning.test.ts).
  • npx tsc --noEmit — 0 errors in the touched files; the 65 remaining are pre-existing
    scripts/*.ts errors that need a built package and are identical at the base commit.
  • New tests cover: receive at the pinned mint (unchanged behaviour), refusal of a foreign
    mint (not received, not cached, key kept, mintMismatch populated), trailing-slash
    tolerance, an undecodable token passed to the wallet, mintUrl: "" opt-out,
    allowForeignRefundMint opt-in, the x-cashu path (refuse + keep claim, accept + remove
    claim), and the helpers themselves.

Adopting it

Callers already have the right value: RoutstrClient, BalanceManager‘s own refund sweep
and CashuSpender all pass the wallet’s mint as mintUrl. No call-site change is required;
the only behaviour change is that a refund minted somewhere else is now reported
(success: false, mintMismatch) instead of being received at a mint the buyer never chose.

If a deployment deliberately trusts its nodes’ mint, pass allowForeignRefundMint: true
where it calls refundApiKey.

Proof (real run, not a description)

Test Files  1 passed (1)
      Tests  10 passed (10)
 Test Files  98 passed (98)
      Tests  1339 passed (1339)

Full diff (git diff against routstr-sdk@f3f40ed)

diff --git a/core/types.ts b/core/types.ts
index baaac46..9434327 100644
--- a/core/types.ts
+++ b/core/types.ts
@@ -214,6 +214,13 @@ export interface RefundResult {
    * refund never reached the provider (network/mint errors) or succeeded.
    */
   status?: number;
+  /**
+   * Set when a refund token arrived minted somewhere other than the mint the
+   * caller pinned, so it was refused before being received. `actual` is the
+   * normalized mint read from the token. The API key is kept in this case: the
+   * buyer is still owed the refund, and the claim is the only record of it.
+   */
+  mintMismatch?: { expected: string; actual: string };
   /** Structured routstr-core error when the provider returned one. */
   parsedError?: import("./errorTypes").ParsedCoreError;
 }
diff --git a/tests/unit/refundMintPinning.test.ts b/tests/unit/refundMintPinning.test.ts
new file mode 100644
index 0000000..7765338
--- /dev/null
+++ b/tests/unit/refundMintPinning.test.ts
@@ -0,0 +1,347 @@
+/**
+ * Refund mint pinning.
+ *
+ * `refundApiKey` takes a `mintUrl` — the mint the caller's wallet is on — and
+ * used to ignore it. The provider's refund endpoint returns a Cashu token
+ * minted wherever the node's own wallet (or a server-side swap) decided, and
+ * BalanceManager handed that token straight to `receiveToken`. A node can
+ * therefore answer a refund with a token from a mint it operates, a mint that
+ * is hostile, or a mint that is simply dead, and the buyer only discovers it
+ * after the proofs are at that mint.
+ *
+ * The mint URL is inside the token, so the check is possible before anything
+ * is received. These tests pin the behaviour: a token from the requested mint
+ * is received as before; a token from anywhere else is refused, not cached and
+ * does not cost the buyer their API key (the claim on the refund).
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { getEncodedToken } from "@cashu/cashu-ts";
+import type { Proof } from "@cashu/cashu-ts";
+import { BalanceManager } from "../../wallet/BalanceManager";
+import { CashuSpender } from "../../wallet/CashuSpender";
+import type { StorageAdapter, WalletAdapter } from "../../wallet/interfaces";
+import { getTokenMintUrl, normalizeMintUrl } from "../../wallet/tokenUtils";
+
+const MINT = "https://mint.example.com";
+const OTHER_MINT = "https://mint.attacker.example";
+const PROVIDER = "https://provider.example.com/";
+
+/** A syntactically valid Cashu token, encoded as the mint would issue it. */
+const tokenFrom = (mint: string, amount = 8): string =>
+  getEncodedToken(
+    {
+      mint,
+      unit: "sat",
+      proofs: [
+        {
+          id: "009a1f293253e41e",
+          amount,
+          secret: "refund-mint-pinning-test",
+          C: "02a9d5e0b1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9",
+        } as unknown as Proof,
+      ],
+    },
+    { removeDleq: true }
+  );
+
+interface Harness {
+  manager: BalanceManager;
+  received: string[];
+  cached: string[];
+  keys: Map<string, string>;
+}
+
+const createHarness = (
+  options: {
+    apiKey?: string;
+    /** Refund token the provider will answer with. */
+    refundToken?: string;
+    receiveResult?: { success: boolean; amount: number; unit: "sat" | "msat" };
+  } = {}
+): Harness => {
+  const apiKey = options.apiKey ?? "sk-idle";
+  const keys = new Map<string, string>([[PROVIDER, apiKey]]);
+  const received: string[] = [];
+  const cached: string[] = [];
+
+  const wallet: WalletAdapter = {
+    getBalances: async () => ({ [MINT]: 1000 }),
+    getMintUnits: () => ({ [MINT]: "sat" }),
+    getActiveMintUrl: () => MINT,
+    sendToken: async () => "cashu-sent",
+    receiveToken: async (token: string) => {
+      received.push(token);
+      return options.receiveResult ?? { success: true, amount: 8, unit: "sat" };
+    },
+  };
+
+  const storage: StorageAdapter = {
+    getXcashuTokens: () => ({}),
+    getXcashuTokensForBaseUrl: () => [],
+    addXcashuToken: () => {},
+    removeXcashuToken: () => {},
+    clearXcashuTokensForBaseUrl: () => {},
+    updateXcashuTokenTryCount: () => {},
+    saveProviderInfo: () => {},
+    getProviderInfo: () => null,
+    getApiKey: (baseUrl: string) =>
+      keys.has(baseUrl)
+        ? { baseUrl, key: keys.get(baseUrl)!, balance: 40, lastUsed: null }
+        : null,
+    setApiKey: (baseUrl: string, key: string) => {
+      keys.set(baseUrl, key);
+    },
+    updateApiKeyBalance: () => {},
+    touchApiKeyLastUsed: () => {},
+    removeApiKey: (baseUrl: string) => {
+      keys.delete(baseUrl);
+    },
+    getAllApiKeys: () => [],
+    getChildKey: () => null,
+    setChildKey: () => {},
+    updateChildKeyBalance: () => {},
+    removeChildKey: () => {},
+    getAllChildKeys: () => [],
+    getCachedReceiveTokens: () =>
+      cached.map((token) => ({ token, amount: 8, unit: "sat", createdAt: 0 })),
+    setCachedReceiveTokens: (entries: { token: string }[]) => {
+      cached.length = 0;
+      cached.push(...entries.map((entry) => entry.token));
+    },
+    getApiKeyDistribution: () => [],
+  };
+
+  const manager = new BalanceManager(wallet, storage);
+  globalThis.fetch = (async (input: string | URL | Request) => {
+    if (String(input).includes("v1/wallet/refund")) {
+      return new Response(JSON.stringify({ token: options.refundToken ?? "" }), {
+        status: 200,
+        headers: { "Content-Type": "application/json" },
+      });
+    }
+    return new Response(JSON.stringify({ success: true }), {
+      status: 200,
+      headers: { "Content-Type": "application/json" },
+    });
+  }) as typeof fetch;
+
+  return { manager, received, cached, keys };
+};
+
+const originalFetch = globalThis.fetch;
+
+afterEach(() => {
+  globalThis.fetch = originalFetch;
+  vi.restoreAllMocks();
+});
+
+describe("refund mint pinning", () => {
+  it("receives a refund paid from the requested mint, as before", async () => {
+    const token = tokenFrom(MINT);
+    const h = createHarness({ refundToken: token });
+
+    const result = await h.manager.refundApiKey({
+      mintUrl: MINT,
+      baseUrl: PROVIDER,
+      apiKey: "sk-idle",
+      forceRefund: true,
+    });
+
+    expect(result.success).toBe(true);
+    expect(result.mintMismatch).toBeUndefined();
+    expect(h.received).toEqual([token]);
+    expect(h.keys.has(PROVIDER)).toBe(false);
+  });
+
+  it("refuses a refund token minted elsewhere and never receives it", async () => {
+    const h = createHarness({ refundToken: tokenFrom(OTHER_MINT) });
+
+    const result = await h.manager.refundApiKey({
+      mintUrl: MINT,
+      baseUrl: PROVIDER,
+      apiKey: "sk-idle",
+      forceRefund: true,
+    });
+
+    expect(result.success).toBe(false);
+    expect(result.mintMismatch).toEqual({
+      expected: normalizeMintUrl(MINT),
+      actual: normalizeMintUrl(OTHER_MINT),
+    });
+    expect(result.message).toContain(MINT);
+    expect(result.message).toContain(OTHER_MINT);
+    // Nothing was redeemed, nothing was parked for a later retry, and the
+    // claim on the refund is still stored.
+    expect(h.received).toEqual([]);
+    expect(h.cached).toEqual([]);
+    expect(h.keys.get(PROVIDER)).toBe("sk-idle");
+  });
+
+  it("treats a trailing slash as the same mint, not as a diversion", async () => {
+    const token = tokenFrom(`${MINT}/`);
+    const h = createHarness({ refundToken: token });
+
+    const result = await h.manager.refundApiKey({
+      mintUrl: MINT,
+      baseUrl: PROVIDER,
+      apiKey: "sk-idle",
+      forceRefund: true,
+    });
+
+    expect(result.success).toBe(true);
+    expect(result.mintMismatch).toBeUndefined();
+    expect(h.received).toEqual([token]);
+  });
+
+  it("hands an unreadable token to the wallet instead of calling it a mismatch", async () => {
+    const h = createHarness({ refundToken: "not-a-cashu-token" });
+
+    const result = await h.manager.refundApiKey({
+      mintUrl: MINT,
+      baseUrl: PROVIDER,
+      apiKey: "sk-idle",
+      forceRefund: true,
+    });
+
+    // `receiveToken` decodes with the same library, so a token this cannot
+    // read would fail there on its own merits. Refusing it here would turn an
+    // unfamiliar format into a lost refund — but it is never reported as a
+    // diversion either.
+    expect(result.mintMismatch).toBeUndefined();
+    expect(h.received).toEqual(["not-a-cashu-token"]);
+  });
+
+  it("accepts any mint when the caller pins none (pre-pinning behaviour)", async () => {
+    const token = tokenFrom(OTHER_MINT);
+    const h = createHarness({ refundToken: token });
+
+    const result = await h.manager.refundApiKey({
+      mintUrl: "",
+      baseUrl: PROVIDER,
+      apiKey: "sk-idle",
+      forceRefund: true,
+    });
+
+    expect(result.success).toBe(true);
+    expect(result.mintMismatch).toBeUndefined();
+    expect(h.received).toEqual([token]);
+  });
+
+  it("accepts a foreign mint when the caller deliberately allows it", async () => {
+    const token = tokenFrom(OTHER_MINT);
+    const h = createHarness({ refundToken: token });
+
+    const result = await h.manager.refundApiKey({
+      mintUrl: MINT,
+      baseUrl: PROVIDER,
+      apiKey: "sk-idle",
+      forceRefund: true,
+      allowForeignRefundMint: true,
+    });
+
+    expect(result.success).toBe(true);
+    expect(result.mintMismatch).toBeUndefined();
+    expect(h.received).toEqual([token]);
+  });
+});
+
+describe("refundXcashuTokens pins the mint too", () => {
+  const xcashuStorage = (
+    xcashuToken: string
+  ): { storage: StorageAdapter; removed: string[] } => {
+    const removed: string[] = [];
+    const storage = {
+      getXcashuTokens: () => ({ [PROVIDER]: [{ token: xcashuToken, tryCount: 0 }] }),
+      getXcashuTokensForBaseUrl: () => [{ token: xcashuToken, tryCount: 0 }],
+      addXcashuToken: () => {},
+      removeXcashuToken: (_baseUrl: string, token: string) => {
+        removed.push(token);
+      },
+      clearXcashuTokensForBaseUrl: () => {},
+      updateXcashuTokenTryCount: () => {},
+      saveProviderInfo: () => {},
+      getProviderInfo: () => null,
+      getApiKey: () => null,
+      setApiKey: () => {},
+      updateApiKeyBalance: () => {},
+      touchApiKeyLastUsed: () => {},
+      removeApiKey: () => {},
+      getAllApiKeys: () => [],
+      getChildKey: () => null,
+      setChildKey: () => {},
+      updateChildKeyBalance: () => {},
+      removeChildKey: () => {},
+      getAllChildKeys: () => [],
+      getCachedReceiveTokens: () => [],
+      setCachedReceiveTokens: () => {},
+      getApiKeyDistribution: () => [],
+    } as unknown as StorageAdapter;
+    return { storage, removed };
+  };
+
+  const walletWithSpy = (received: string[]): WalletAdapter => ({
+    getBalances: async () => ({ [MINT]: 1000 }),
+    getMintUnits: () => ({ [MINT]: "sat" }),
+    getActiveMintUrl: () => MINT,
+    sendToken: async () => "cashu-sent",
+    receiveToken: async (token: string) => {
+      received.push(token);
+      return { success: true, amount: 8, unit: "sat" };
+    },
+  });
+
+  it("refuses a refund paid to another mint, keeping the xcashu claim", async () => {
+    const xcashu = "cashu-original-xcashu-token";
+    const { storage } = xcashuStorage(xcashu);
+    const received: string[] = [];
+    const spender = new CashuSpender(
+      walletWithSpy(received),
+      storage,
+      undefined,
+      {
+        fetchRefundToken: async () => ({ success: true, token: tokenFrom(OTHER_MINT) }),
+      } as unknown as BalanceManager
+    );
+
+    const results = await spender.refundXcashuTokens(MINT);
+
+    expect(received).toEqual([]);
+    expect(results).toHaveLength(1);
+    expect(results[0].success).toBe(false);
+    expect(results[0].token).toBe(xcashu);
+    expect(results[0].error).toContain(MINT);
+    expect(results[0].error).toContain(OTHER_MINT);
+  });
+
+  it("receives a refund paid to the requested mint", async () => {
+    const xcashu = "cashu-original-xcashu-token";
+    const { storage, removed } = xcashuStorage(xcashu);
+    const received: string[] = [];
+    const refundToken = tokenFrom(MINT);
+    const spender = new CashuSpender(
+      walletWithSpy(received),
+      storage,
+      undefined,
+      {
+        fetchRefundToken: async () => ({ success: true, token: refundToken }),
+      } as unknown as BalanceManager
+    );
+
+    const results = await spender.refundXcashuTokens(MINT);
+
+    expect(received).toEqual([refundToken]);
+    expect(results[0].success).toBe(true);
+    expect(removed).toEqual([xcashu]);
+  });
+});
+
+describe("getTokenMintUrl", () => {
+  it("reads the mint out of an encoded token", () => {
+    expect(getTokenMintUrl(tokenFrom(MINT))).toBe(normalizeMintUrl(MINT));
+  });
+
+  it("returns null for anything it cannot decode", () => {
+    expect(getTokenMintUrl("cashu-token")).toBeNull();
+    expect(getTokenMintUrl("")).toBeNull();
+  });
+});
diff --git a/wallet/BalanceManager.ts b/wallet/BalanceManager.ts
index f0e71fb..5294b15 100644
--- a/wallet/BalanceManager.ts
+++ b/wallet/BalanceManager.ts
@@ -35,7 +35,9 @@ import { stampBalanceRead } from "./apiKeyBalance";
 import {
   getBalanceInSats,
   getAvailableBalanceInSats,
+  getTokenMintUrl,
   isNetworkErrorMessage,
+  normalizeMintUrl,
   selectMintWithBalance,
 } from "./tokenUtils";
 
@@ -43,17 +45,35 @@ import {
  * Options for refunding API key balance
  */
 export interface RefundApiKeyOptions {
-  /** The mint URL (for NIP-60 wallet operations) */
+  /**
+   * The mint URL (for NIP-60 wallet operations) — and the mint the refund must
+   * be paid from. The mint is inside every Cashu token, so a refund token
+   * minted anywhere else is refused before it is received (see
+   * `allowForeignRefundMint`). Pass an empty string to accept a refund from
+   * whatever mint the provider chose, which is the pre-pinning behaviour.
+   */
   mintUrl: string;
 
   /** The provider base URL */
   baseUrl: string;
 
   /** The API key to use for authentication */
-  apiKey: string;
+apiKey: string;
 
   /** If true, forces refund even if the API key was used recently */
   forceRefund?: boolean;
+
+  /**
+   * Accept a refund token minted at a mint other than `mintUrl`.
+   *
+   * Defaults to false: a provider that answers a refund with a token from a
+   * mint it controls can divert the buyer to a hostile, dead or worthless
+   * mint, and the buyer only finds out once the proofs are there. Set this
+   * only when the caller has deliberately decided to trust the node's own
+   * mint — the refusal path names both mints and keeps the API key, so the
+   * claim is not lost.
+   */
+  allowForeignRefundMint?: boolean;
 }
 
 /**
@@ -348,7 +368,13 @@ export class BalanceManager {
 
     let result: RefundResult | undefined;
     try {
-      result = await this._refundApiKeyImpl({ mintUrl, baseUrl, apiKey, forceRefund });
+      result = await this._refundApiKeyImpl({
+        mintUrl,
+        baseUrl,
+        apiKey,
+        forceRefund,
+        allowForeignRefundMint: options.allowForeignRefundMint,
+      });
       return result;
     } finally {
       // An exception has an unknown outcome and retains the cooldown.
@@ -506,6 +532,45 @@ export class BalanceManager {
       }
 
       const refundToken = fetchResult.token;
+
+      // Pin the refund to the mint the caller asked for.
+      //
+      // The provider's refund endpoint hands back a token minted wherever the
+      // node's wallet — or a server-side swap — decided, and `receiveToken`
+      // will redeem it at that mint. So a node can answer a refund with a
+      // token from a mint it operates, a mint that is hostile, or a mint that
+      // is simply dead, and the buyer only finds out once the proofs are at
+      // that mint. The mint URL is inside the token, so it can be read and
+      // checked before any of it is received.
+      const pinnedMint = normalizeMintUrl(mintUrl);
+      if (pinnedMint && !options.allowForeignRefundMint) {
+        const tokenMint = getTokenMintUrl(refundToken);
+        // Only a mint that is readable *and* different is a diversion. An
+        // unreadable token is not evidence of one: `receiveToken` decodes with
+        // the same library, so a token this cannot read is a token the wallet
+        // cannot receive either — and refusing here would turn an unfamiliar
+        // (e.g. legacy-format) refund into a lost refund. Log it and let the
+        // wallet have its say.
+        if (tokenMint !== null && tokenMint !== pinnedMint) {
+          this.logger.warn(
+            `refundApiKey: refusing refund token for ${baseUrl} minted at ${tokenMint}; caller pinned ${pinnedMint}`
+          );
+          // The key is deliberately kept: the refund the buyer is owed has not
+          // reached them, and deleting the key would throw away the claim
+          // instead of recording where the money went. Nothing is cached
+          // either — a cached token is retried by `recoverCachedReceiveTokens`
+          // and would land at the foreign mint anyway.
+          return {
+            success: false,
+            message: `Refund token mint ${tokenMint ?? "could not be read"} does not match the requested mint ${pinnedMint}; not receiving it`,
+            requestId: fetchResult.requestId,
+            status: fetchResult.status,
+            parsedError: fetchResult.parsedError,
+            mintMismatch: { expected: pinnedMint, actual: tokenMint },
+          };
+        }
+      }
+
       this.cashuSpender.cacheReceiveToken(refundToken);
       const receiveResult = await this.cashuSpender.receiveToken(
         refundToken,
diff --git a/wallet/CashuSpender.ts b/wallet/CashuSpender.ts
index 463f27f..20ae62f 100644
--- a/wallet/CashuSpender.ts
+++ b/wallet/CashuSpender.ts
@@ -21,7 +21,12 @@ import {
 } from "../core/errorTypes";
 import { BalanceManager } from "./BalanceManager";
 import { persistApiKeyBalance } from "./apiKeyBalance";
-import { getBalanceInSats, isNetworkErrorMessage } from "./tokenUtils";
+import {
+  getBalanceInSats,
+  getTokenMintUrl,
+  isNetworkErrorMessage,
+  normalizeMintUrl,
+} from "./tokenUtils";
 import { getTokenMetadata } from "@cashu/cashu-ts";
 
 /**
@@ -636,7 +641,31 @@ export class CashuSpender {
           }
 
           // Receive the refunded Cashu token into the wallet
-          const receiveResult = await this.receiveToken(fetchResult.token);
+          //
+          // Pin it to the mint the caller asked for, exactly as
+          // `BalanceManager.refundApiKey` does: the token carries its own mint,
+          // and a provider that answers with a token minted somewhere else is
+          // diverting the refund. Refuse before receiving — the claim stays in
+          // xcashu storage, so nothing is thrown away, and no tryCount is
+          // burned on a token that cannot be retried into the right mint.
+          const fetchedToken = fetchResult.token;
+          const pinnedMint = normalizeMintUrl(mintUrl);
+          const fetchedMint = getTokenMintUrl(fetchedToken);
+          if (pinnedMint && fetchedMint !== null && fetchedMint !== pinnedMint) {
+            this._log(
+              "WARN",
+              `[CashuSpender] refundXcashuTokens: refusing refund token for ${baseUrl} minted at ${fetchedMint}; caller pinned ${pinnedMint}`
+            );
+            results.push({
+              baseUrl,
+              token: xcashuToken.token,
+              success: false,
+              error: `Refund token mint ${fetchedMint} does not match the requested mint ${pinnedMint}`,
+            });
+            continue;
+          }
+
+          const receiveResult = await this.receiveToken(fetchedToken);
 
           if (receiveResult.success) {
             // Remove successfully refunded token from storage
diff --git a/wallet/tokenUtils.ts b/wallet/tokenUtils.ts
index 9a7eaa6..83c16b9 100644
--- a/wallet/tokenUtils.ts
+++ b/wallet/tokenUtils.ts
@@ -1,4 +1,36 @@
 import type { MintSelection } from "../core/types";
+import { getTokenMetadata } from "@cashu/cashu-ts";
+
+/**
+ * Mint URLs are compared, not just displayed, so they need one spelling.
+ *
+ * `getTokenMetadata` returns the mint exactly as it was encoded, and mints
+ * themselves are announced with and without a trailing slash depending on the
+ * server. Comparing raw strings would refuse a refund from the mint the caller
+ * pinned purely because the node wrote `…/` — a false refusal that looks
+ * exactly like the attack this check exists to stop.
+ */
+export function normalizeMintUrl(mintUrl: string | null | undefined): string {
+  return (mintUrl ?? "").trim().replace(/\/+$/, "").toLowerCase();
+}
+
+/**
+ * The mint a Cashu token was issued from, normalized, or `null` when the token
+ * cannot be decoded.
+ *
+ * `null` is deliberately distinct from "no mint": a caller that pins a mint
+ * must refuse an unreadable token rather than receive proofs it cannot
+ * attribute.
+ */
+export function getTokenMintUrl(token: string): string | null {
+  try {
+    const mint = getTokenMetadata(token).mint;
+    const normalized = normalizeMintUrl(mint);
+    return normalized || null;
+  } catch {
+    return null;
+  }
+}
 
 /**
  * Transport failures that mean "this provider could not be reached at all",

— Vela (npub16yujr0g0njhvgqlcl45dsk90plaquj7ag2f079meu2jvw6me4z5qh69fqz), 2026-11-18.


Write a comment