@gvnrdao/dh-mcp 0.5.13 → 0.5.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/boundary.js CHANGED
@@ -41379,7 +41379,10 @@ var BoundaryCore = class {
41379
41379
  borrower: auth.borrower
41380
41380
  });
41381
41381
  if (!r.ok) return errEnvelope(failureToError(r.failure));
41382
- return okEnvelope({ attempted: r.value.attempted, transfers: r.value.transfers }, r.source);
41382
+ return okEnvelope(
41383
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...r.value.authorization ? { authorization: r.value.authorization } : {} },
41384
+ r.source
41385
+ );
41383
41386
  }
41384
41387
  // ---- meta ----
41385
41388
  world() {
@@ -42226,20 +42229,56 @@ var World = class {
42226
42229
  if (pos.borrower.toLowerCase() !== p.borrower.toLowerCase()) {
42227
42230
  return { ok: false, reason: `caller ${p.borrower} is not the borrower of this position` };
42228
42231
  }
42229
- const c = this.state.collateral[p.positionId];
42230
- const pending = (c?.authorizedSpends ?? []).filter((s) => s.consumed === null);
42231
- const transfers = pending.map((spend) => {
42232
+ const fee = BigInt(p.networkFeeSats);
42233
+ const transfers = this.pendingSpends(p.positionId).map((spend) => {
42234
+ const utxoIdentifier = `${spend.txid}:${spend.vout}`;
42235
+ const refusal = this.retryFeeRefusal(spend, p.networkFeeSats);
42236
+ if (refusal) return { utxoIdentifier, ok: false, error: refusal };
42232
42237
  const { hash: txid } = this.nextId("btc-withdraw-retry");
42233
42238
  return {
42234
- utxoIdentifier: `${spend.txid}:${spend.vout}`,
42239
+ utxoIdentifier,
42235
42240
  ok: true,
42236
42241
  txid,
42237
- amountSentSats: spend.satoshis,
42242
+ // NET of the fee: what the destination actually receives. The fee is carved OUT of
42243
+ // the authorized amount, never added on top — the same semantics `withdraw` above
42244
+ // models and `IBTCSpendAuthorizer` enforces (the recipient receives
42245
+ // targetAmount − networkFee). Reporting the gross figure as "sent" would hide
42246
+ // whether the fee was honoured at all.
42247
+ amountSentSats: (BigInt(spend.satoshis) - fee).toString(),
42238
42248
  destination: spend.targetAddress
42239
42249
  };
42240
42250
  });
42241
42251
  return { ok: true, value: { attempted: transfers.length, transfers } };
42242
42252
  }
42253
+ /** Reservations whose coins have not been observed moving — the set phase 2 re-executes. */
42254
+ pendingSpends(positionId) {
42255
+ return (this.state.collateral[positionId]?.authorizedSpends ?? []).filter((s) => s.consumed === null);
42256
+ }
42257
+ /**
42258
+ * The fee cap the SDK applies to a reservation BEFORE it signs anything
42259
+ * (`diamond-hands-sdk.ts` `executeBTCWithdrawal`, above `buildBtcExecuteEnvelope`):
42260
+ *
42261
+ * if (request.networkFee * 2 >= request.targetAmount) { … refuse … }
42262
+ *
42263
+ * — audit M-E, a griefing cap, deliberately far tighter than "leaves something to send".
42264
+ * A reservation's `satoshis` here IS the authorized `targetAmount`, so the same arithmetic
42265
+ * applies per reservation. Returns the refusal, or null when phase 2 would proceed.
42266
+ */
42267
+ retryFeeRefusal(spend, networkFeeSats) {
42268
+ const target = BigInt(spend.satoshis);
42269
+ if (BigInt(networkFeeSats) * 2n >= target) {
42270
+ return `network fee ${networkFeeSats} sats is \u2265 50% of the ${target.toString()}-sat authorized amount on ${spend.txid}:${spend.vout} \u2014 the fee comes OUT of the authorized amount, and the protocol refuses to broadcast above that cap (real Bitcoin fees are typically <1% of value)`;
42271
+ }
42272
+ return null;
42273
+ }
42274
+ /**
42275
+ * How many of this position's outstanding reservations phase 2 would actually attempt at
42276
+ * this fee. Zero means the SDK never reaches `executeBTCWithdrawal`'s signing step, so the
42277
+ * wallet is never opened — which is what the mock's ceremony gate reads.
42278
+ */
42279
+ retryExecutableCount(positionId, networkFeeSats) {
42280
+ return this.pendingSpends(positionId).filter((s) => this.retryFeeRefusal(s, networkFeeSats) === null).length;
42281
+ }
42243
42282
  // ---- Mock Safes (plan 06): REAL verification semantics, no fakes (M6-21/27) ----
42244
42283
  safesMap() {
42245
42284
  return this.state.safes;
@@ -43426,11 +43465,7 @@ var MockUpstreamPlugin = class {
43426
43465
  if (!r.ok) return this.rejected("recoverStaleSpend", r.reason);
43427
43466
  return upOk({ txRef: this.world.nextTxRef(), releasedSats: r.value.releasedSats }, this.src("mock-ops"));
43428
43467
  }),
43429
- retryWithdrawExecute: (p) => this.write("retryWithdrawExecute", () => {
43430
- const r = this.world.retryWithdrawExecute({ positionId: p.positionId, borrower: p.borrower });
43431
- if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
43432
- return upOk({ attempted: r.value.attempted, transfers: r.value.transfers }, this.src("mock-ops"));
43433
- })
43468
+ retryWithdrawExecute: (p) => this.opRetryWithdrawExecute(p)
43434
43469
  };
43435
43470
  }
43436
43471
  indexer;
@@ -43705,6 +43740,46 @@ var MockUpstreamPlugin = class {
43705
43740
  );
43706
43741
  });
43707
43742
  }
43743
+ /**
43744
+ * C-46 retry, and it takes the SAME ceremony `opWithdraw` takes.
43745
+ *
43746
+ * The first version of this op skipped all three gates: no `noneRefusal`, no wallet
43747
+ * ceremony, no `applyAuthorized`. It moved mock BTC on nothing but `confirmed: true`, so a
43748
+ * user who DECLINED in their wallet still saw the retry succeed. The real adapter does sign
43749
+ * — the SDK's phase 2 raises the blind-hash card before it broadcasts — so the mock was
43750
+ * passing requests the real protocol would refuse, which is the one thing a practice world
43751
+ * must never do.
43752
+ *
43753
+ * The ceremony is nonetheless PREFLIGHTED, because the SDK signs strictly less often than
43754
+ * "once per call": `executePendingBtcTransfers` reads the authorizer and `return []`s on an
43755
+ * empty set without entering `executeBTCWithdrawal` at all, and `executeBTCWithdrawal`'s own
43756
+ * fee cap refuses above `buildBtcExecuteEnvelope` — the only thing that touches the signer.
43757
+ * So a retry with nothing executable opens NO wallet on the real adapter, and a mock that
43758
+ * raised a ceremony there would teach a user to approve a popup the protocol never shows.
43759
+ */
43760
+ async opRetryWithdrawExecute(p) {
43761
+ const none = this.noneRefusal();
43762
+ if (none) return none;
43763
+ const executable = this.world.retryExecutableCount(p.positionId, p.networkFeeSats);
43764
+ const card = `re-run the BTC withdrawal EXECUTE step for ${executable} outstanding reservation(s) on ${p.positionId}`;
43765
+ const cer = executable > 0 ? this.ceremonyNow() : null;
43766
+ const auth = cer ? await cer.authorizeTypedData({ action: "withdraw", borrower: p.borrower, detail: card }) : null;
43767
+ if (auth && !auth.ok) return auth.failure;
43768
+ if (auth?.ok) this.bindIfDiscovering(auth.authorization);
43769
+ return this.write("retryWithdrawExecute", () => {
43770
+ const sig = executable === 0 ? null : auth ?? this.sign("withdraw", p.borrower, card);
43771
+ if (sig && !sig.ok) return sig.failure;
43772
+ const r = this.applyAuthorized(
43773
+ sig ? sig.authorization : void 0,
43774
+ () => this.world.retryWithdrawExecute({ positionId: p.positionId, networkFeeSats: p.networkFeeSats, borrower: p.borrower })
43775
+ );
43776
+ if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
43777
+ return upOk(
43778
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...sig ? { authorization: sig.authorization } : {} },
43779
+ this.src("mock-ops")
43780
+ );
43781
+ });
43782
+ }
43708
43783
  /** BWAR mirror ceremony (plan 06 E3): a SAFE borrower allowlists a BTC destination via
43709
43784
  * a Safe transaction (owner signatures, durable — async collection is honest here). On
43710
43785
  * mock, EOA borrowers have no allowlist gate; refusing beats faking success. */
@@ -81096,7 +81171,7 @@ var SignatureBridge = class {
81096
81171
  connectedAccounts() {
81097
81172
  const seen = /* @__PURE__ */ new Map();
81098
81173
  for (const s of this.sessions.values()) {
81099
- if (s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
81174
+ if (!s.refused && s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
81100
81175
  }
81101
81176
  if (this.wcActive && this.wallet) seen.set(this.wallet.account.toLowerCase(), this.wallet.account);
81102
81177
  return [...seen.values()];
@@ -81357,7 +81432,7 @@ var SignatureBridge = class {
81357
81432
  return;
81358
81433
  }
81359
81434
  const sessionId = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81360
- this.sessions.set(sessionId, { wallet: null, sse: null });
81435
+ this.sessions.set(sessionId, { wallet: null, sse: null, refused: null });
81361
81436
  const page = htmlPageSecurityHeaders();
81362
81437
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
81363
81438
  res.end(renderApprovalPage(sessionId, page.nonce));
@@ -81387,7 +81462,7 @@ var SignatureBridge = class {
81387
81462
  const refusal = info ? this.accountRefusal(info.account) : null;
81388
81463
  if (info && refusal) {
81389
81464
  this.wcActive = false;
81390
- this.wallet = null;
81465
+ this.rebuildSharedWallet();
81391
81466
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
81392
81467
  `);
81393
81468
  return;
@@ -81491,6 +81566,7 @@ var SignatureBridge = class {
81491
81566
  }
81492
81567
  const refusal = this.accountRefusal(account);
81493
81568
  if (refusal) {
81569
+ this.quarantine(session, refusal);
81494
81570
  this.deny(res, 403, refusal);
81495
81571
  return;
81496
81572
  }
@@ -81529,10 +81605,15 @@ var SignatureBridge = class {
81529
81605
  const chainId = Number(body["chainId"]);
81530
81606
  const prev = session.wallet;
81531
81607
  const offered = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
81532
- const refusedSwitch = offered !== null && this.accountRefusal(offered.account) !== null;
81533
- session.wallet = refusedSwitch ? null : offered;
81534
- if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
81535
- this.wallet = session.wallet;
81608
+ const switchRefusal = offered !== null ? this.accountRefusal(offered.account) : null;
81609
+ const refusedSwitch = switchRefusal !== null;
81610
+ if (refusedSwitch) {
81611
+ this.quarantine(session, switchRefusal);
81612
+ } else {
81613
+ session.wallet = offered;
81614
+ if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
81615
+ this.wallet = session.wallet;
81616
+ }
81536
81617
  }
81537
81618
  const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
81538
81619
  if (unchanged) {
@@ -81629,7 +81710,7 @@ var SignatureBridge = class {
81629
81710
  const data = `data: ${JSON.stringify(request)}
81630
81711
 
81631
81712
  `;
81632
- for (const s of this.sessions.values()) s.sse?.write(data);
81713
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
81633
81714
  }
81634
81715
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
81635
81716
  pushProgress(payload) {
@@ -81637,7 +81718,48 @@ var SignatureBridge = class {
81637
81718
  data: ${JSON.stringify(payload)}
81638
81719
 
81639
81720
  `;
81640
- for (const s of this.sessions.values()) s.sse?.write(data);
81721
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
81722
+ }
81723
+ /**
81724
+ * C-47: `this.wallet` is DERIVED, never guessed.
81725
+ *
81726
+ * It is the shared last-wallet view `candidate()` reads, and an earlier fix decided its
81727
+ * ownership from the `wcActive` flag — "while that is true the wallet came from
81728
+ * WalletConnect". That is false: an approval page can say hello AFTER a WC session is
81729
+ * live, so the page owned the wallet while the flag still said WC did. A refused pairing
81730
+ * then blanked a perfectly good page session, turning someone scanning the QR with the
81731
+ * wrong account into a disconnect for the legitimate user.
81732
+ *
81733
+ * Deriving it from live state removes the guess. Preference order matches
81734
+ * `requestSignature`, which routes to WalletConnect ahead of the page.
81735
+ */
81736
+ rebuildSharedWallet() {
81737
+ if (this.wcActive && this.wcTransport) {
81738
+ const wc = this.wcTransport.active();
81739
+ if (wc && !this.accountRefusal(wc.account)) {
81740
+ this.wallet = { account: wc.account, chainId: wc.chainId };
81741
+ return;
81742
+ }
81743
+ }
81744
+ let latest = null;
81745
+ for (const s of this.sessions.values()) if (!s.refused && s.wallet) latest = s.wallet;
81746
+ this.wallet = latest;
81747
+ }
81748
+ /**
81749
+ * C-47: the ONE way a page session is refused. Setting `refused` alone was not enough —
81750
+ * an ALREADY-ADMITTED session that later offers a wrong account kept its `wallet`, so it
81751
+ * still answered `connectedAccounts()` for quorum and could still be the shared candidate.
81752
+ * Quarantine therefore does all four things together: mark it, drop its wallet, close its
81753
+ * stream, and re-derive the shared view without it.
81754
+ */
81755
+ quarantine(session, reason) {
81756
+ session.refused = reason;
81757
+ session.wallet = null;
81758
+ if (session.sse) {
81759
+ session.sse.end();
81760
+ session.sse = null;
81761
+ }
81762
+ this.rebuildSharedWallet();
81641
81763
  }
81642
81764
  sessionOf(candidate, res) {
81643
81765
  const session = typeof candidate === "string" ? this.sessions.get(candidate) ?? null : null;
@@ -81645,6 +81767,10 @@ data: ${JSON.stringify(payload)}
81645
81767
  this.deny(res, 403, "missing or wrong session");
81646
81768
  return null;
81647
81769
  }
81770
+ if (session.refused) {
81771
+ this.deny(res, 403, session.refused);
81772
+ return null;
81773
+ }
81648
81774
  return session;
81649
81775
  }
81650
81776
  checkSession(candidate, res) {
@@ -41036,7 +41036,7 @@ function htmlPageSecurityHeaders(extra) {
41036
41036
  }
41037
41037
 
41038
41038
  // src/version.ts
41039
- var SERVER_VERSION = "0.5.13";
41039
+ var SERVER_VERSION = "0.5.14";
41040
41040
 
41041
41041
  // src/connector/siwe-oauth.ts
41042
41042
  var import_node_crypto2 = require("crypto");
@@ -42500,7 +42500,10 @@ var BoundaryCore = class {
42500
42500
  borrower: auth.borrower
42501
42501
  });
42502
42502
  if (!r.ok) return errEnvelope(failureToError(r.failure));
42503
- return okEnvelope({ attempted: r.value.attempted, transfers: r.value.transfers }, r.source);
42503
+ return okEnvelope(
42504
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...r.value.authorization ? { authorization: r.value.authorization } : {} },
42505
+ r.source
42506
+ );
42504
42507
  }
42505
42508
  // ---- meta ----
42506
42509
  world() {
@@ -43347,20 +43350,56 @@ var World = class {
43347
43350
  if (pos.borrower.toLowerCase() !== p.borrower.toLowerCase()) {
43348
43351
  return { ok: false, reason: `caller ${p.borrower} is not the borrower of this position` };
43349
43352
  }
43350
- const c = this.state.collateral[p.positionId];
43351
- const pending = (c?.authorizedSpends ?? []).filter((s) => s.consumed === null);
43352
- const transfers = pending.map((spend) => {
43353
+ const fee = BigInt(p.networkFeeSats);
43354
+ const transfers = this.pendingSpends(p.positionId).map((spend) => {
43355
+ const utxoIdentifier = `${spend.txid}:${spend.vout}`;
43356
+ const refusal = this.retryFeeRefusal(spend, p.networkFeeSats);
43357
+ if (refusal) return { utxoIdentifier, ok: false, error: refusal };
43353
43358
  const { hash: txid } = this.nextId("btc-withdraw-retry");
43354
43359
  return {
43355
- utxoIdentifier: `${spend.txid}:${spend.vout}`,
43360
+ utxoIdentifier,
43356
43361
  ok: true,
43357
43362
  txid,
43358
- amountSentSats: spend.satoshis,
43363
+ // NET of the fee: what the destination actually receives. The fee is carved OUT of
43364
+ // the authorized amount, never added on top — the same semantics `withdraw` above
43365
+ // models and `IBTCSpendAuthorizer` enforces (the recipient receives
43366
+ // targetAmount − networkFee). Reporting the gross figure as "sent" would hide
43367
+ // whether the fee was honoured at all.
43368
+ amountSentSats: (BigInt(spend.satoshis) - fee).toString(),
43359
43369
  destination: spend.targetAddress
43360
43370
  };
43361
43371
  });
43362
43372
  return { ok: true, value: { attempted: transfers.length, transfers } };
43363
43373
  }
43374
+ /** Reservations whose coins have not been observed moving — the set phase 2 re-executes. */
43375
+ pendingSpends(positionId) {
43376
+ return (this.state.collateral[positionId]?.authorizedSpends ?? []).filter((s) => s.consumed === null);
43377
+ }
43378
+ /**
43379
+ * The fee cap the SDK applies to a reservation BEFORE it signs anything
43380
+ * (`diamond-hands-sdk.ts` `executeBTCWithdrawal`, above `buildBtcExecuteEnvelope`):
43381
+ *
43382
+ * if (request.networkFee * 2 >= request.targetAmount) { … refuse … }
43383
+ *
43384
+ * — audit M-E, a griefing cap, deliberately far tighter than "leaves something to send".
43385
+ * A reservation's `satoshis` here IS the authorized `targetAmount`, so the same arithmetic
43386
+ * applies per reservation. Returns the refusal, or null when phase 2 would proceed.
43387
+ */
43388
+ retryFeeRefusal(spend, networkFeeSats) {
43389
+ const target = BigInt(spend.satoshis);
43390
+ if (BigInt(networkFeeSats) * 2n >= target) {
43391
+ return `network fee ${networkFeeSats} sats is \u2265 50% of the ${target.toString()}-sat authorized amount on ${spend.txid}:${spend.vout} \u2014 the fee comes OUT of the authorized amount, and the protocol refuses to broadcast above that cap (real Bitcoin fees are typically <1% of value)`;
43392
+ }
43393
+ return null;
43394
+ }
43395
+ /**
43396
+ * How many of this position's outstanding reservations phase 2 would actually attempt at
43397
+ * this fee. Zero means the SDK never reaches `executeBTCWithdrawal`'s signing step, so the
43398
+ * wallet is never opened — which is what the mock's ceremony gate reads.
43399
+ */
43400
+ retryExecutableCount(positionId, networkFeeSats) {
43401
+ return this.pendingSpends(positionId).filter((s) => this.retryFeeRefusal(s, networkFeeSats) === null).length;
43402
+ }
43364
43403
  // ---- Mock Safes (plan 06): REAL verification semantics, no fakes (M6-21/27) ----
43365
43404
  safesMap() {
43366
43405
  return this.state.safes;
@@ -44556,11 +44595,7 @@ var MockUpstreamPlugin = class {
44556
44595
  if (!r.ok) return this.rejected("recoverStaleSpend", r.reason);
44557
44596
  return upOk({ txRef: this.world.nextTxRef(), releasedSats: r.value.releasedSats }, this.src("mock-ops"));
44558
44597
  }),
44559
- retryWithdrawExecute: (p) => this.write("retryWithdrawExecute", () => {
44560
- const r = this.world.retryWithdrawExecute({ positionId: p.positionId, borrower: p.borrower });
44561
- if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
44562
- return upOk({ attempted: r.value.attempted, transfers: r.value.transfers }, this.src("mock-ops"));
44563
- })
44598
+ retryWithdrawExecute: (p) => this.opRetryWithdrawExecute(p)
44564
44599
  };
44565
44600
  }
44566
44601
  indexer;
@@ -44835,6 +44870,46 @@ var MockUpstreamPlugin = class {
44835
44870
  );
44836
44871
  });
44837
44872
  }
44873
+ /**
44874
+ * C-46 retry, and it takes the SAME ceremony `opWithdraw` takes.
44875
+ *
44876
+ * The first version of this op skipped all three gates: no `noneRefusal`, no wallet
44877
+ * ceremony, no `applyAuthorized`. It moved mock BTC on nothing but `confirmed: true`, so a
44878
+ * user who DECLINED in their wallet still saw the retry succeed. The real adapter does sign
44879
+ * — the SDK's phase 2 raises the blind-hash card before it broadcasts — so the mock was
44880
+ * passing requests the real protocol would refuse, which is the one thing a practice world
44881
+ * must never do.
44882
+ *
44883
+ * The ceremony is nonetheless PREFLIGHTED, because the SDK signs strictly less often than
44884
+ * "once per call": `executePendingBtcTransfers` reads the authorizer and `return []`s on an
44885
+ * empty set without entering `executeBTCWithdrawal` at all, and `executeBTCWithdrawal`'s own
44886
+ * fee cap refuses above `buildBtcExecuteEnvelope` — the only thing that touches the signer.
44887
+ * So a retry with nothing executable opens NO wallet on the real adapter, and a mock that
44888
+ * raised a ceremony there would teach a user to approve a popup the protocol never shows.
44889
+ */
44890
+ async opRetryWithdrawExecute(p) {
44891
+ const none = this.noneRefusal();
44892
+ if (none) return none;
44893
+ const executable = this.world.retryExecutableCount(p.positionId, p.networkFeeSats);
44894
+ const card = `re-run the BTC withdrawal EXECUTE step for ${executable} outstanding reservation(s) on ${p.positionId}`;
44895
+ const cer = executable > 0 ? this.ceremonyNow() : null;
44896
+ const auth = cer ? await cer.authorizeTypedData({ action: "withdraw", borrower: p.borrower, detail: card }) : null;
44897
+ if (auth && !auth.ok) return auth.failure;
44898
+ if (auth?.ok) this.bindIfDiscovering(auth.authorization);
44899
+ return this.write("retryWithdrawExecute", () => {
44900
+ const sig = executable === 0 ? null : auth ?? this.sign("withdraw", p.borrower, card);
44901
+ if (sig && !sig.ok) return sig.failure;
44902
+ const r = this.applyAuthorized(
44903
+ sig ? sig.authorization : void 0,
44904
+ () => this.world.retryWithdrawExecute({ positionId: p.positionId, networkFeeSats: p.networkFeeSats, borrower: p.borrower })
44905
+ );
44906
+ if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
44907
+ return upOk(
44908
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...sig ? { authorization: sig.authorization } : {} },
44909
+ this.src("mock-ops")
44910
+ );
44911
+ });
44912
+ }
44838
44913
  /** BWAR mirror ceremony (plan 06 E3): a SAFE borrower allowlists a BTC destination via
44839
44914
  * a Safe transaction (owner signatures, durable — async collection is honest here). On
44840
44915
  * mock, EOA borrowers have no allowlist gate; refusing beats faking success. */
@@ -82198,7 +82273,7 @@ var SignatureBridge = class {
82198
82273
  connectedAccounts() {
82199
82274
  const seen = /* @__PURE__ */ new Map();
82200
82275
  for (const s of this.sessions.values()) {
82201
- if (s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
82276
+ if (!s.refused && s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
82202
82277
  }
82203
82278
  if (this.wcActive && this.wallet) seen.set(this.wallet.account.toLowerCase(), this.wallet.account);
82204
82279
  return [...seen.values()];
@@ -82459,7 +82534,7 @@ var SignatureBridge = class {
82459
82534
  return;
82460
82535
  }
82461
82536
  const sessionId = (0, import_node_crypto8.randomBytes)(24).toString("hex");
82462
- this.sessions.set(sessionId, { wallet: null, sse: null });
82537
+ this.sessions.set(sessionId, { wallet: null, sse: null, refused: null });
82463
82538
  const page = htmlPageSecurityHeaders();
82464
82539
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
82465
82540
  res.end(renderApprovalPage(sessionId, page.nonce));
@@ -82489,7 +82564,7 @@ var SignatureBridge = class {
82489
82564
  const refusal = info ? this.accountRefusal(info.account) : null;
82490
82565
  if (info && refusal) {
82491
82566
  this.wcActive = false;
82492
- this.wallet = null;
82567
+ this.rebuildSharedWallet();
82493
82568
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
82494
82569
  `);
82495
82570
  return;
@@ -82593,6 +82668,7 @@ var SignatureBridge = class {
82593
82668
  }
82594
82669
  const refusal = this.accountRefusal(account);
82595
82670
  if (refusal) {
82671
+ this.quarantine(session, refusal);
82596
82672
  this.deny(res, 403, refusal);
82597
82673
  return;
82598
82674
  }
@@ -82631,10 +82707,15 @@ var SignatureBridge = class {
82631
82707
  const chainId = Number(body["chainId"]);
82632
82708
  const prev = session.wallet;
82633
82709
  const offered = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
82634
- const refusedSwitch = offered !== null && this.accountRefusal(offered.account) !== null;
82635
- session.wallet = refusedSwitch ? null : offered;
82636
- if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
82637
- this.wallet = session.wallet;
82710
+ const switchRefusal = offered !== null ? this.accountRefusal(offered.account) : null;
82711
+ const refusedSwitch = switchRefusal !== null;
82712
+ if (refusedSwitch) {
82713
+ this.quarantine(session, switchRefusal);
82714
+ } else {
82715
+ session.wallet = offered;
82716
+ if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
82717
+ this.wallet = session.wallet;
82718
+ }
82638
82719
  }
82639
82720
  const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
82640
82721
  if (unchanged) {
@@ -82731,7 +82812,7 @@ var SignatureBridge = class {
82731
82812
  const data = `data: ${JSON.stringify(request)}
82732
82813
 
82733
82814
  `;
82734
- for (const s of this.sessions.values()) s.sse?.write(data);
82815
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
82735
82816
  }
82736
82817
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
82737
82818
  pushProgress(payload) {
@@ -82739,7 +82820,48 @@ var SignatureBridge = class {
82739
82820
  data: ${JSON.stringify(payload)}
82740
82821
 
82741
82822
  `;
82742
- for (const s of this.sessions.values()) s.sse?.write(data);
82823
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
82824
+ }
82825
+ /**
82826
+ * C-47: `this.wallet` is DERIVED, never guessed.
82827
+ *
82828
+ * It is the shared last-wallet view `candidate()` reads, and an earlier fix decided its
82829
+ * ownership from the `wcActive` flag — "while that is true the wallet came from
82830
+ * WalletConnect". That is false: an approval page can say hello AFTER a WC session is
82831
+ * live, so the page owned the wallet while the flag still said WC did. A refused pairing
82832
+ * then blanked a perfectly good page session, turning someone scanning the QR with the
82833
+ * wrong account into a disconnect for the legitimate user.
82834
+ *
82835
+ * Deriving it from live state removes the guess. Preference order matches
82836
+ * `requestSignature`, which routes to WalletConnect ahead of the page.
82837
+ */
82838
+ rebuildSharedWallet() {
82839
+ if (this.wcActive && this.wcTransport) {
82840
+ const wc = this.wcTransport.active();
82841
+ if (wc && !this.accountRefusal(wc.account)) {
82842
+ this.wallet = { account: wc.account, chainId: wc.chainId };
82843
+ return;
82844
+ }
82845
+ }
82846
+ let latest = null;
82847
+ for (const s of this.sessions.values()) if (!s.refused && s.wallet) latest = s.wallet;
82848
+ this.wallet = latest;
82849
+ }
82850
+ /**
82851
+ * C-47: the ONE way a page session is refused. Setting `refused` alone was not enough —
82852
+ * an ALREADY-ADMITTED session that later offers a wrong account kept its `wallet`, so it
82853
+ * still answered `connectedAccounts()` for quorum and could still be the shared candidate.
82854
+ * Quarantine therefore does all four things together: mark it, drop its wallet, close its
82855
+ * stream, and re-derive the shared view without it.
82856
+ */
82857
+ quarantine(session, reason) {
82858
+ session.refused = reason;
82859
+ session.wallet = null;
82860
+ if (session.sse) {
82861
+ session.sse.end();
82862
+ session.sse = null;
82863
+ }
82864
+ this.rebuildSharedWallet();
82743
82865
  }
82744
82866
  sessionOf(candidate, res) {
82745
82867
  const session = typeof candidate === "string" ? this.sessions.get(candidate) ?? null : null;
@@ -82747,6 +82869,10 @@ data: ${JSON.stringify(payload)}
82747
82869
  this.deny(res, 403, "missing or wrong session");
82748
82870
  return null;
82749
82871
  }
82872
+ if (session.refused) {
82873
+ this.deny(res, 403, session.refused);
82874
+ return null;
82875
+ }
82750
82876
  return session;
82751
82877
  }
82752
82878
  checkSession(candidate, res) {
@@ -83561,7 +83687,11 @@ on the real adapter and the mock.
83561
83687
  attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
83562
83688
  back. Warn the user: a second or third identical card is the retry, NOT a duplicate
83563
83689
  charge and NOT an attack \u2014 but they should still read it, and each attempt is a new
83564
- signature. The blind execute popup happens once.
83690
+ signature. The EXECUTE popup comes once PER ATTEMPT too, and \`loan_withdraw_retry\` raises
83691
+ it again \u2014 re-signing with a fresh stamp is the whole of what a retry does. What that popup
83692
+ LOOKS like depends on the adapter: on the real adapter it is the blind 32-byte hash above;
83693
+ in a practice world (adapter \`mock\`) every ceremony, retries included, is a readable
83694
+ typed-data card. Promise the unreadable one only where it is real.
83565
83695
  - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
83566
83696
  (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
83567
83697
  hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
@@ -83604,6 +83734,14 @@ Connections / Connected sites).`,
83604
83734
  \`loan_withdraw_retry {positionId, confirmed:true}\`, which re-runs that second step with a
83605
83735
  fresh stamp using the destination and amount the CHAIN already holds. Check
83606
83736
  \`position_pending_withdrawals\` first, and tell the user it re-sends real BTC.
83737
+ WARN THEM WHAT THEY WILL SEE: the retry raises the SAME popup the original attempt's
83738
+ execute step raised, on the same sub-minute clock \u2014 on the real adapter that is the opaque
83739
+ 32-byte hash the wallet cannot decode; in a practice world it is a readable typed-data card.
83740
+ Say which one before they open the page, not after the popup surprises them.
83741
+ A retry with nothing outstanding pops NO wallet at all: both adapters look the
83742
+ reservations up first and answer \`attempted: 0\` without ever asking for a signature.
83743
+ The fee is taken OUT of the already-authorized amount, so a retry can never send more than
83744
+ the original withdrawal authorized.
83607
83745
  7. **Watch it** \u2014 \`position_status\` (one), \`position_list\` (all),
83608
83746
  \`position_events\` (history), \`btc_price\`, \`protocol_status\`.
83609
83747
 
package/dist/connector.js CHANGED
@@ -41030,7 +41030,7 @@ function htmlPageSecurityHeaders(extra) {
41030
41030
  }
41031
41031
 
41032
41032
  // src/version.ts
41033
- var SERVER_VERSION = "0.5.13";
41033
+ var SERVER_VERSION = "0.5.14";
41034
41034
 
41035
41035
  // src/connector/siwe-oauth.ts
41036
41036
  var import_node_crypto2 = require("crypto");
@@ -42494,7 +42494,10 @@ var BoundaryCore = class {
42494
42494
  borrower: auth.borrower
42495
42495
  });
42496
42496
  if (!r.ok) return errEnvelope(failureToError(r.failure));
42497
- return okEnvelope({ attempted: r.value.attempted, transfers: r.value.transfers }, r.source);
42497
+ return okEnvelope(
42498
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...r.value.authorization ? { authorization: r.value.authorization } : {} },
42499
+ r.source
42500
+ );
42498
42501
  }
42499
42502
  // ---- meta ----
42500
42503
  world() {
@@ -43341,20 +43344,56 @@ var World = class {
43341
43344
  if (pos.borrower.toLowerCase() !== p.borrower.toLowerCase()) {
43342
43345
  return { ok: false, reason: `caller ${p.borrower} is not the borrower of this position` };
43343
43346
  }
43344
- const c = this.state.collateral[p.positionId];
43345
- const pending = (c?.authorizedSpends ?? []).filter((s) => s.consumed === null);
43346
- const transfers = pending.map((spend) => {
43347
+ const fee = BigInt(p.networkFeeSats);
43348
+ const transfers = this.pendingSpends(p.positionId).map((spend) => {
43349
+ const utxoIdentifier = `${spend.txid}:${spend.vout}`;
43350
+ const refusal = this.retryFeeRefusal(spend, p.networkFeeSats);
43351
+ if (refusal) return { utxoIdentifier, ok: false, error: refusal };
43347
43352
  const { hash: txid } = this.nextId("btc-withdraw-retry");
43348
43353
  return {
43349
- utxoIdentifier: `${spend.txid}:${spend.vout}`,
43354
+ utxoIdentifier,
43350
43355
  ok: true,
43351
43356
  txid,
43352
- amountSentSats: spend.satoshis,
43357
+ // NET of the fee: what the destination actually receives. The fee is carved OUT of
43358
+ // the authorized amount, never added on top — the same semantics `withdraw` above
43359
+ // models and `IBTCSpendAuthorizer` enforces (the recipient receives
43360
+ // targetAmount − networkFee). Reporting the gross figure as "sent" would hide
43361
+ // whether the fee was honoured at all.
43362
+ amountSentSats: (BigInt(spend.satoshis) - fee).toString(),
43353
43363
  destination: spend.targetAddress
43354
43364
  };
43355
43365
  });
43356
43366
  return { ok: true, value: { attempted: transfers.length, transfers } };
43357
43367
  }
43368
+ /** Reservations whose coins have not been observed moving — the set phase 2 re-executes. */
43369
+ pendingSpends(positionId) {
43370
+ return (this.state.collateral[positionId]?.authorizedSpends ?? []).filter((s) => s.consumed === null);
43371
+ }
43372
+ /**
43373
+ * The fee cap the SDK applies to a reservation BEFORE it signs anything
43374
+ * (`diamond-hands-sdk.ts` `executeBTCWithdrawal`, above `buildBtcExecuteEnvelope`):
43375
+ *
43376
+ * if (request.networkFee * 2 >= request.targetAmount) { … refuse … }
43377
+ *
43378
+ * — audit M-E, a griefing cap, deliberately far tighter than "leaves something to send".
43379
+ * A reservation's `satoshis` here IS the authorized `targetAmount`, so the same arithmetic
43380
+ * applies per reservation. Returns the refusal, or null when phase 2 would proceed.
43381
+ */
43382
+ retryFeeRefusal(spend, networkFeeSats) {
43383
+ const target = BigInt(spend.satoshis);
43384
+ if (BigInt(networkFeeSats) * 2n >= target) {
43385
+ return `network fee ${networkFeeSats} sats is \u2265 50% of the ${target.toString()}-sat authorized amount on ${spend.txid}:${spend.vout} \u2014 the fee comes OUT of the authorized amount, and the protocol refuses to broadcast above that cap (real Bitcoin fees are typically <1% of value)`;
43386
+ }
43387
+ return null;
43388
+ }
43389
+ /**
43390
+ * How many of this position's outstanding reservations phase 2 would actually attempt at
43391
+ * this fee. Zero means the SDK never reaches `executeBTCWithdrawal`'s signing step, so the
43392
+ * wallet is never opened — which is what the mock's ceremony gate reads.
43393
+ */
43394
+ retryExecutableCount(positionId, networkFeeSats) {
43395
+ return this.pendingSpends(positionId).filter((s) => this.retryFeeRefusal(s, networkFeeSats) === null).length;
43396
+ }
43358
43397
  // ---- Mock Safes (plan 06): REAL verification semantics, no fakes (M6-21/27) ----
43359
43398
  safesMap() {
43360
43399
  return this.state.safes;
@@ -44550,11 +44589,7 @@ var MockUpstreamPlugin = class {
44550
44589
  if (!r.ok) return this.rejected("recoverStaleSpend", r.reason);
44551
44590
  return upOk({ txRef: this.world.nextTxRef(), releasedSats: r.value.releasedSats }, this.src("mock-ops"));
44552
44591
  }),
44553
- retryWithdrawExecute: (p) => this.write("retryWithdrawExecute", () => {
44554
- const r = this.world.retryWithdrawExecute({ positionId: p.positionId, borrower: p.borrower });
44555
- if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
44556
- return upOk({ attempted: r.value.attempted, transfers: r.value.transfers }, this.src("mock-ops"));
44557
- })
44592
+ retryWithdrawExecute: (p) => this.opRetryWithdrawExecute(p)
44558
44593
  };
44559
44594
  }
44560
44595
  indexer;
@@ -44829,6 +44864,46 @@ var MockUpstreamPlugin = class {
44829
44864
  );
44830
44865
  });
44831
44866
  }
44867
+ /**
44868
+ * C-46 retry, and it takes the SAME ceremony `opWithdraw` takes.
44869
+ *
44870
+ * The first version of this op skipped all three gates: no `noneRefusal`, no wallet
44871
+ * ceremony, no `applyAuthorized`. It moved mock BTC on nothing but `confirmed: true`, so a
44872
+ * user who DECLINED in their wallet still saw the retry succeed. The real adapter does sign
44873
+ * — the SDK's phase 2 raises the blind-hash card before it broadcasts — so the mock was
44874
+ * passing requests the real protocol would refuse, which is the one thing a practice world
44875
+ * must never do.
44876
+ *
44877
+ * The ceremony is nonetheless PREFLIGHTED, because the SDK signs strictly less often than
44878
+ * "once per call": `executePendingBtcTransfers` reads the authorizer and `return []`s on an
44879
+ * empty set without entering `executeBTCWithdrawal` at all, and `executeBTCWithdrawal`'s own
44880
+ * fee cap refuses above `buildBtcExecuteEnvelope` — the only thing that touches the signer.
44881
+ * So a retry with nothing executable opens NO wallet on the real adapter, and a mock that
44882
+ * raised a ceremony there would teach a user to approve a popup the protocol never shows.
44883
+ */
44884
+ async opRetryWithdrawExecute(p) {
44885
+ const none = this.noneRefusal();
44886
+ if (none) return none;
44887
+ const executable = this.world.retryExecutableCount(p.positionId, p.networkFeeSats);
44888
+ const card = `re-run the BTC withdrawal EXECUTE step for ${executable} outstanding reservation(s) on ${p.positionId}`;
44889
+ const cer = executable > 0 ? this.ceremonyNow() : null;
44890
+ const auth = cer ? await cer.authorizeTypedData({ action: "withdraw", borrower: p.borrower, detail: card }) : null;
44891
+ if (auth && !auth.ok) return auth.failure;
44892
+ if (auth?.ok) this.bindIfDiscovering(auth.authorization);
44893
+ return this.write("retryWithdrawExecute", () => {
44894
+ const sig = executable === 0 ? null : auth ?? this.sign("withdraw", p.borrower, card);
44895
+ if (sig && !sig.ok) return sig.failure;
44896
+ const r = this.applyAuthorized(
44897
+ sig ? sig.authorization : void 0,
44898
+ () => this.world.retryWithdrawExecute({ positionId: p.positionId, networkFeeSats: p.networkFeeSats, borrower: p.borrower })
44899
+ );
44900
+ if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
44901
+ return upOk(
44902
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...sig ? { authorization: sig.authorization } : {} },
44903
+ this.src("mock-ops")
44904
+ );
44905
+ });
44906
+ }
44832
44907
  /** BWAR mirror ceremony (plan 06 E3): a SAFE borrower allowlists a BTC destination via
44833
44908
  * a Safe transaction (owner signatures, durable — async collection is honest here). On
44834
44909
  * mock, EOA borrowers have no allowlist gate; refusing beats faking success. */
@@ -82192,7 +82267,7 @@ var SignatureBridge = class {
82192
82267
  connectedAccounts() {
82193
82268
  const seen = /* @__PURE__ */ new Map();
82194
82269
  for (const s of this.sessions.values()) {
82195
- if (s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
82270
+ if (!s.refused && s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
82196
82271
  }
82197
82272
  if (this.wcActive && this.wallet) seen.set(this.wallet.account.toLowerCase(), this.wallet.account);
82198
82273
  return [...seen.values()];
@@ -82453,7 +82528,7 @@ var SignatureBridge = class {
82453
82528
  return;
82454
82529
  }
82455
82530
  const sessionId = (0, import_node_crypto8.randomBytes)(24).toString("hex");
82456
- this.sessions.set(sessionId, { wallet: null, sse: null });
82531
+ this.sessions.set(sessionId, { wallet: null, sse: null, refused: null });
82457
82532
  const page = htmlPageSecurityHeaders();
82458
82533
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
82459
82534
  res.end(renderApprovalPage(sessionId, page.nonce));
@@ -82483,7 +82558,7 @@ var SignatureBridge = class {
82483
82558
  const refusal = info ? this.accountRefusal(info.account) : null;
82484
82559
  if (info && refusal) {
82485
82560
  this.wcActive = false;
82486
- this.wallet = null;
82561
+ this.rebuildSharedWallet();
82487
82562
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
82488
82563
  `);
82489
82564
  return;
@@ -82587,6 +82662,7 @@ var SignatureBridge = class {
82587
82662
  }
82588
82663
  const refusal = this.accountRefusal(account);
82589
82664
  if (refusal) {
82665
+ this.quarantine(session, refusal);
82590
82666
  this.deny(res, 403, refusal);
82591
82667
  return;
82592
82668
  }
@@ -82625,10 +82701,15 @@ var SignatureBridge = class {
82625
82701
  const chainId = Number(body["chainId"]);
82626
82702
  const prev = session.wallet;
82627
82703
  const offered = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
82628
- const refusedSwitch = offered !== null && this.accountRefusal(offered.account) !== null;
82629
- session.wallet = refusedSwitch ? null : offered;
82630
- if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
82631
- this.wallet = session.wallet;
82704
+ const switchRefusal = offered !== null ? this.accountRefusal(offered.account) : null;
82705
+ const refusedSwitch = switchRefusal !== null;
82706
+ if (refusedSwitch) {
82707
+ this.quarantine(session, switchRefusal);
82708
+ } else {
82709
+ session.wallet = offered;
82710
+ if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
82711
+ this.wallet = session.wallet;
82712
+ }
82632
82713
  }
82633
82714
  const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
82634
82715
  if (unchanged) {
@@ -82725,7 +82806,7 @@ var SignatureBridge = class {
82725
82806
  const data = `data: ${JSON.stringify(request)}
82726
82807
 
82727
82808
  `;
82728
- for (const s of this.sessions.values()) s.sse?.write(data);
82809
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
82729
82810
  }
82730
82811
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
82731
82812
  pushProgress(payload) {
@@ -82733,7 +82814,48 @@ var SignatureBridge = class {
82733
82814
  data: ${JSON.stringify(payload)}
82734
82815
 
82735
82816
  `;
82736
- for (const s of this.sessions.values()) s.sse?.write(data);
82817
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
82818
+ }
82819
+ /**
82820
+ * C-47: `this.wallet` is DERIVED, never guessed.
82821
+ *
82822
+ * It is the shared last-wallet view `candidate()` reads, and an earlier fix decided its
82823
+ * ownership from the `wcActive` flag — "while that is true the wallet came from
82824
+ * WalletConnect". That is false: an approval page can say hello AFTER a WC session is
82825
+ * live, so the page owned the wallet while the flag still said WC did. A refused pairing
82826
+ * then blanked a perfectly good page session, turning someone scanning the QR with the
82827
+ * wrong account into a disconnect for the legitimate user.
82828
+ *
82829
+ * Deriving it from live state removes the guess. Preference order matches
82830
+ * `requestSignature`, which routes to WalletConnect ahead of the page.
82831
+ */
82832
+ rebuildSharedWallet() {
82833
+ if (this.wcActive && this.wcTransport) {
82834
+ const wc = this.wcTransport.active();
82835
+ if (wc && !this.accountRefusal(wc.account)) {
82836
+ this.wallet = { account: wc.account, chainId: wc.chainId };
82837
+ return;
82838
+ }
82839
+ }
82840
+ let latest = null;
82841
+ for (const s of this.sessions.values()) if (!s.refused && s.wallet) latest = s.wallet;
82842
+ this.wallet = latest;
82843
+ }
82844
+ /**
82845
+ * C-47: the ONE way a page session is refused. Setting `refused` alone was not enough —
82846
+ * an ALREADY-ADMITTED session that later offers a wrong account kept its `wallet`, so it
82847
+ * still answered `connectedAccounts()` for quorum and could still be the shared candidate.
82848
+ * Quarantine therefore does all four things together: mark it, drop its wallet, close its
82849
+ * stream, and re-derive the shared view without it.
82850
+ */
82851
+ quarantine(session, reason) {
82852
+ session.refused = reason;
82853
+ session.wallet = null;
82854
+ if (session.sse) {
82855
+ session.sse.end();
82856
+ session.sse = null;
82857
+ }
82858
+ this.rebuildSharedWallet();
82737
82859
  }
82738
82860
  sessionOf(candidate, res) {
82739
82861
  const session = typeof candidate === "string" ? this.sessions.get(candidate) ?? null : null;
@@ -82741,6 +82863,10 @@ data: ${JSON.stringify(payload)}
82741
82863
  this.deny(res, 403, "missing or wrong session");
82742
82864
  return null;
82743
82865
  }
82866
+ if (session.refused) {
82867
+ this.deny(res, 403, session.refused);
82868
+ return null;
82869
+ }
82744
82870
  return session;
82745
82871
  }
82746
82872
  checkSession(candidate, res) {
@@ -83555,7 +83681,11 @@ on the real adapter and the mock.
83555
83681
  attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
83556
83682
  back. Warn the user: a second or third identical card is the retry, NOT a duplicate
83557
83683
  charge and NOT an attack \u2014 but they should still read it, and each attempt is a new
83558
- signature. The blind execute popup happens once.
83684
+ signature. The EXECUTE popup comes once PER ATTEMPT too, and \`loan_withdraw_retry\` raises
83685
+ it again \u2014 re-signing with a fresh stamp is the whole of what a retry does. What that popup
83686
+ LOOKS like depends on the adapter: on the real adapter it is the blind 32-byte hash above;
83687
+ in a practice world (adapter \`mock\`) every ceremony, retries included, is a readable
83688
+ typed-data card. Promise the unreadable one only where it is real.
83559
83689
  - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
83560
83690
  (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
83561
83691
  hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
@@ -83598,6 +83728,14 @@ Connections / Connected sites).`,
83598
83728
  \`loan_withdraw_retry {positionId, confirmed:true}\`, which re-runs that second step with a
83599
83729
  fresh stamp using the destination and amount the CHAIN already holds. Check
83600
83730
  \`position_pending_withdrawals\` first, and tell the user it re-sends real BTC.
83731
+ WARN THEM WHAT THEY WILL SEE: the retry raises the SAME popup the original attempt's
83732
+ execute step raised, on the same sub-minute clock \u2014 on the real adapter that is the opaque
83733
+ 32-byte hash the wallet cannot decode; in a practice world it is a readable typed-data card.
83734
+ Say which one before they open the page, not after the popup surprises them.
83735
+ A retry with nothing outstanding pops NO wallet at all: both adapters look the
83736
+ reservations up first and answer \`attempted: 0\` without ever asking for a signature.
83737
+ The fee is taken OUT of the already-authorized amount, so a retry can never send more than
83738
+ the original withdrawal authorized.
83601
83739
  7. **Watch it** \u2014 \`position_status\` (one), \`position_list\` (all),
83602
83740
  \`position_events\` (history), \`btc_price\`, \`protocol_status\`.
83603
83741
 
package/dist/index.js CHANGED
@@ -41585,7 +41585,10 @@ var BoundaryCore = class {
41585
41585
  borrower: auth.borrower
41586
41586
  });
41587
41587
  if (!r.ok) return errEnvelope(failureToError(r.failure));
41588
- return okEnvelope({ attempted: r.value.attempted, transfers: r.value.transfers }, r.source);
41588
+ return okEnvelope(
41589
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...r.value.authorization ? { authorization: r.value.authorization } : {} },
41590
+ r.source
41591
+ );
41589
41592
  }
41590
41593
  // ---- meta ----
41591
41594
  world() {
@@ -42432,20 +42435,56 @@ var World = class {
42432
42435
  if (pos.borrower.toLowerCase() !== p.borrower.toLowerCase()) {
42433
42436
  return { ok: false, reason: `caller ${p.borrower} is not the borrower of this position` };
42434
42437
  }
42435
- const c = this.state.collateral[p.positionId];
42436
- const pending = (c?.authorizedSpends ?? []).filter((s) => s.consumed === null);
42437
- const transfers = pending.map((spend) => {
42438
+ const fee = BigInt(p.networkFeeSats);
42439
+ const transfers = this.pendingSpends(p.positionId).map((spend) => {
42440
+ const utxoIdentifier = `${spend.txid}:${spend.vout}`;
42441
+ const refusal = this.retryFeeRefusal(spend, p.networkFeeSats);
42442
+ if (refusal) return { utxoIdentifier, ok: false, error: refusal };
42438
42443
  const { hash: txid } = this.nextId("btc-withdraw-retry");
42439
42444
  return {
42440
- utxoIdentifier: `${spend.txid}:${spend.vout}`,
42445
+ utxoIdentifier,
42441
42446
  ok: true,
42442
42447
  txid,
42443
- amountSentSats: spend.satoshis,
42448
+ // NET of the fee: what the destination actually receives. The fee is carved OUT of
42449
+ // the authorized amount, never added on top — the same semantics `withdraw` above
42450
+ // models and `IBTCSpendAuthorizer` enforces (the recipient receives
42451
+ // targetAmount − networkFee). Reporting the gross figure as "sent" would hide
42452
+ // whether the fee was honoured at all.
42453
+ amountSentSats: (BigInt(spend.satoshis) - fee).toString(),
42444
42454
  destination: spend.targetAddress
42445
42455
  };
42446
42456
  });
42447
42457
  return { ok: true, value: { attempted: transfers.length, transfers } };
42448
42458
  }
42459
+ /** Reservations whose coins have not been observed moving — the set phase 2 re-executes. */
42460
+ pendingSpends(positionId) {
42461
+ return (this.state.collateral[positionId]?.authorizedSpends ?? []).filter((s) => s.consumed === null);
42462
+ }
42463
+ /**
42464
+ * The fee cap the SDK applies to a reservation BEFORE it signs anything
42465
+ * (`diamond-hands-sdk.ts` `executeBTCWithdrawal`, above `buildBtcExecuteEnvelope`):
42466
+ *
42467
+ * if (request.networkFee * 2 >= request.targetAmount) { … refuse … }
42468
+ *
42469
+ * — audit M-E, a griefing cap, deliberately far tighter than "leaves something to send".
42470
+ * A reservation's `satoshis` here IS the authorized `targetAmount`, so the same arithmetic
42471
+ * applies per reservation. Returns the refusal, or null when phase 2 would proceed.
42472
+ */
42473
+ retryFeeRefusal(spend, networkFeeSats) {
42474
+ const target = BigInt(spend.satoshis);
42475
+ if (BigInt(networkFeeSats) * 2n >= target) {
42476
+ return `network fee ${networkFeeSats} sats is \u2265 50% of the ${target.toString()}-sat authorized amount on ${spend.txid}:${spend.vout} \u2014 the fee comes OUT of the authorized amount, and the protocol refuses to broadcast above that cap (real Bitcoin fees are typically <1% of value)`;
42477
+ }
42478
+ return null;
42479
+ }
42480
+ /**
42481
+ * How many of this position's outstanding reservations phase 2 would actually attempt at
42482
+ * this fee. Zero means the SDK never reaches `executeBTCWithdrawal`'s signing step, so the
42483
+ * wallet is never opened — which is what the mock's ceremony gate reads.
42484
+ */
42485
+ retryExecutableCount(positionId, networkFeeSats) {
42486
+ return this.pendingSpends(positionId).filter((s) => this.retryFeeRefusal(s, networkFeeSats) === null).length;
42487
+ }
42449
42488
  // ---- Mock Safes (plan 06): REAL verification semantics, no fakes (M6-21/27) ----
42450
42489
  safesMap() {
42451
42490
  return this.state.safes;
@@ -43632,11 +43671,7 @@ var MockUpstreamPlugin = class {
43632
43671
  if (!r.ok) return this.rejected("recoverStaleSpend", r.reason);
43633
43672
  return upOk({ txRef: this.world.nextTxRef(), releasedSats: r.value.releasedSats }, this.src("mock-ops"));
43634
43673
  }),
43635
- retryWithdrawExecute: (p) => this.write("retryWithdrawExecute", () => {
43636
- const r = this.world.retryWithdrawExecute({ positionId: p.positionId, borrower: p.borrower });
43637
- if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
43638
- return upOk({ attempted: r.value.attempted, transfers: r.value.transfers }, this.src("mock-ops"));
43639
- })
43674
+ retryWithdrawExecute: (p) => this.opRetryWithdrawExecute(p)
43640
43675
  };
43641
43676
  }
43642
43677
  indexer;
@@ -43911,6 +43946,46 @@ var MockUpstreamPlugin = class {
43911
43946
  );
43912
43947
  });
43913
43948
  }
43949
+ /**
43950
+ * C-46 retry, and it takes the SAME ceremony `opWithdraw` takes.
43951
+ *
43952
+ * The first version of this op skipped all three gates: no `noneRefusal`, no wallet
43953
+ * ceremony, no `applyAuthorized`. It moved mock BTC on nothing but `confirmed: true`, so a
43954
+ * user who DECLINED in their wallet still saw the retry succeed. The real adapter does sign
43955
+ * — the SDK's phase 2 raises the blind-hash card before it broadcasts — so the mock was
43956
+ * passing requests the real protocol would refuse, which is the one thing a practice world
43957
+ * must never do.
43958
+ *
43959
+ * The ceremony is nonetheless PREFLIGHTED, because the SDK signs strictly less often than
43960
+ * "once per call": `executePendingBtcTransfers` reads the authorizer and `return []`s on an
43961
+ * empty set without entering `executeBTCWithdrawal` at all, and `executeBTCWithdrawal`'s own
43962
+ * fee cap refuses above `buildBtcExecuteEnvelope` — the only thing that touches the signer.
43963
+ * So a retry with nothing executable opens NO wallet on the real adapter, and a mock that
43964
+ * raised a ceremony there would teach a user to approve a popup the protocol never shows.
43965
+ */
43966
+ async opRetryWithdrawExecute(p) {
43967
+ const none = this.noneRefusal();
43968
+ if (none) return none;
43969
+ const executable = this.world.retryExecutableCount(p.positionId, p.networkFeeSats);
43970
+ const card = `re-run the BTC withdrawal EXECUTE step for ${executable} outstanding reservation(s) on ${p.positionId}`;
43971
+ const cer = executable > 0 ? this.ceremonyNow() : null;
43972
+ const auth = cer ? await cer.authorizeTypedData({ action: "withdraw", borrower: p.borrower, detail: card }) : null;
43973
+ if (auth && !auth.ok) return auth.failure;
43974
+ if (auth?.ok) this.bindIfDiscovering(auth.authorization);
43975
+ return this.write("retryWithdrawExecute", () => {
43976
+ const sig = executable === 0 ? null : auth ?? this.sign("withdraw", p.borrower, card);
43977
+ if (sig && !sig.ok) return sig.failure;
43978
+ const r = this.applyAuthorized(
43979
+ sig ? sig.authorization : void 0,
43980
+ () => this.world.retryWithdrawExecute({ positionId: p.positionId, networkFeeSats: p.networkFeeSats, borrower: p.borrower })
43981
+ );
43982
+ if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
43983
+ return upOk(
43984
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...sig ? { authorization: sig.authorization } : {} },
43985
+ this.src("mock-ops")
43986
+ );
43987
+ });
43988
+ }
43914
43989
  /** BWAR mirror ceremony (plan 06 E3): a SAFE borrower allowlists a BTC destination via
43915
43990
  * a Safe transaction (owner signatures, durable — async collection is honest here). On
43916
43991
  * mock, EOA borrowers have no allowlist gate; refusing beats faking success. */
@@ -81302,7 +81377,7 @@ var SignatureBridge = class {
81302
81377
  connectedAccounts() {
81303
81378
  const seen = /* @__PURE__ */ new Map();
81304
81379
  for (const s of this.sessions.values()) {
81305
- if (s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
81380
+ if (!s.refused && s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
81306
81381
  }
81307
81382
  if (this.wcActive && this.wallet) seen.set(this.wallet.account.toLowerCase(), this.wallet.account);
81308
81383
  return [...seen.values()];
@@ -81563,7 +81638,7 @@ var SignatureBridge = class {
81563
81638
  return;
81564
81639
  }
81565
81640
  const sessionId = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81566
- this.sessions.set(sessionId, { wallet: null, sse: null });
81641
+ this.sessions.set(sessionId, { wallet: null, sse: null, refused: null });
81567
81642
  const page = htmlPageSecurityHeaders();
81568
81643
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
81569
81644
  res.end(renderApprovalPage(sessionId, page.nonce));
@@ -81593,7 +81668,7 @@ var SignatureBridge = class {
81593
81668
  const refusal = info ? this.accountRefusal(info.account) : null;
81594
81669
  if (info && refusal) {
81595
81670
  this.wcActive = false;
81596
- this.wallet = null;
81671
+ this.rebuildSharedWallet();
81597
81672
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
81598
81673
  `);
81599
81674
  return;
@@ -81697,6 +81772,7 @@ var SignatureBridge = class {
81697
81772
  }
81698
81773
  const refusal = this.accountRefusal(account);
81699
81774
  if (refusal) {
81775
+ this.quarantine(session, refusal);
81700
81776
  this.deny(res, 403, refusal);
81701
81777
  return;
81702
81778
  }
@@ -81735,10 +81811,15 @@ var SignatureBridge = class {
81735
81811
  const chainId = Number(body["chainId"]);
81736
81812
  const prev = session.wallet;
81737
81813
  const offered = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
81738
- const refusedSwitch = offered !== null && this.accountRefusal(offered.account) !== null;
81739
- session.wallet = refusedSwitch ? null : offered;
81740
- if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
81741
- this.wallet = session.wallet;
81814
+ const switchRefusal = offered !== null ? this.accountRefusal(offered.account) : null;
81815
+ const refusedSwitch = switchRefusal !== null;
81816
+ if (refusedSwitch) {
81817
+ this.quarantine(session, switchRefusal);
81818
+ } else {
81819
+ session.wallet = offered;
81820
+ if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
81821
+ this.wallet = session.wallet;
81822
+ }
81742
81823
  }
81743
81824
  const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
81744
81825
  if (unchanged) {
@@ -81835,7 +81916,7 @@ var SignatureBridge = class {
81835
81916
  const data = `data: ${JSON.stringify(request)}
81836
81917
 
81837
81918
  `;
81838
- for (const s of this.sessions.values()) s.sse?.write(data);
81919
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
81839
81920
  }
81840
81921
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
81841
81922
  pushProgress(payload) {
@@ -81843,7 +81924,48 @@ var SignatureBridge = class {
81843
81924
  data: ${JSON.stringify(payload)}
81844
81925
 
81845
81926
  `;
81846
- for (const s of this.sessions.values()) s.sse?.write(data);
81927
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
81928
+ }
81929
+ /**
81930
+ * C-47: `this.wallet` is DERIVED, never guessed.
81931
+ *
81932
+ * It is the shared last-wallet view `candidate()` reads, and an earlier fix decided its
81933
+ * ownership from the `wcActive` flag — "while that is true the wallet came from
81934
+ * WalletConnect". That is false: an approval page can say hello AFTER a WC session is
81935
+ * live, so the page owned the wallet while the flag still said WC did. A refused pairing
81936
+ * then blanked a perfectly good page session, turning someone scanning the QR with the
81937
+ * wrong account into a disconnect for the legitimate user.
81938
+ *
81939
+ * Deriving it from live state removes the guess. Preference order matches
81940
+ * `requestSignature`, which routes to WalletConnect ahead of the page.
81941
+ */
81942
+ rebuildSharedWallet() {
81943
+ if (this.wcActive && this.wcTransport) {
81944
+ const wc = this.wcTransport.active();
81945
+ if (wc && !this.accountRefusal(wc.account)) {
81946
+ this.wallet = { account: wc.account, chainId: wc.chainId };
81947
+ return;
81948
+ }
81949
+ }
81950
+ let latest = null;
81951
+ for (const s of this.sessions.values()) if (!s.refused && s.wallet) latest = s.wallet;
81952
+ this.wallet = latest;
81953
+ }
81954
+ /**
81955
+ * C-47: the ONE way a page session is refused. Setting `refused` alone was not enough —
81956
+ * an ALREADY-ADMITTED session that later offers a wrong account kept its `wallet`, so it
81957
+ * still answered `connectedAccounts()` for quorum and could still be the shared candidate.
81958
+ * Quarantine therefore does all four things together: mark it, drop its wallet, close its
81959
+ * stream, and re-derive the shared view without it.
81960
+ */
81961
+ quarantine(session, reason) {
81962
+ session.refused = reason;
81963
+ session.wallet = null;
81964
+ if (session.sse) {
81965
+ session.sse.end();
81966
+ session.sse = null;
81967
+ }
81968
+ this.rebuildSharedWallet();
81847
81969
  }
81848
81970
  sessionOf(candidate, res) {
81849
81971
  const session = typeof candidate === "string" ? this.sessions.get(candidate) ?? null : null;
@@ -81851,6 +81973,10 @@ data: ${JSON.stringify(payload)}
81851
81973
  this.deny(res, 403, "missing or wrong session");
81852
81974
  return null;
81853
81975
  }
81976
+ if (session.refused) {
81977
+ this.deny(res, 403, session.refused);
81978
+ return null;
81979
+ }
81854
81980
  return session;
81855
81981
  }
81856
81982
  checkSession(candidate, res) {
@@ -82665,7 +82791,11 @@ on the real adapter and the mock.
82665
82791
  attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
82666
82792
  back. Warn the user: a second or third identical card is the retry, NOT a duplicate
82667
82793
  charge and NOT an attack \u2014 but they should still read it, and each attempt is a new
82668
- signature. The blind execute popup happens once.
82794
+ signature. The EXECUTE popup comes once PER ATTEMPT too, and \`loan_withdraw_retry\` raises
82795
+ it again \u2014 re-signing with a fresh stamp is the whole of what a retry does. What that popup
82796
+ LOOKS like depends on the adapter: on the real adapter it is the blind 32-byte hash above;
82797
+ in a practice world (adapter \`mock\`) every ceremony, retries included, is a readable
82798
+ typed-data card. Promise the unreadable one only where it is real.
82669
82799
  - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
82670
82800
  (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
82671
82801
  hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
@@ -82708,6 +82838,14 @@ Connections / Connected sites).`,
82708
82838
  \`loan_withdraw_retry {positionId, confirmed:true}\`, which re-runs that second step with a
82709
82839
  fresh stamp using the destination and amount the CHAIN already holds. Check
82710
82840
  \`position_pending_withdrawals\` first, and tell the user it re-sends real BTC.
82841
+ WARN THEM WHAT THEY WILL SEE: the retry raises the SAME popup the original attempt's
82842
+ execute step raised, on the same sub-minute clock \u2014 on the real adapter that is the opaque
82843
+ 32-byte hash the wallet cannot decode; in a practice world it is a readable typed-data card.
82844
+ Say which one before they open the page, not after the popup surprises them.
82845
+ A retry with nothing outstanding pops NO wallet at all: both adapters look the
82846
+ reservations up first and answer \`attempted: 0\` without ever asking for a signature.
82847
+ The fee is taken OUT of the already-authorized amount, so a retry can never send more than
82848
+ the original withdrawal authorized.
82711
82849
  7. **Watch it** \u2014 \`position_status\` (one), \`position_list\` (all),
82712
82850
  \`position_events\` (history), \`btc_price\`, \`protocol_status\`.
82713
82851
 
@@ -84501,7 +84639,7 @@ function registerBoundaryInfoResource(server, getB) {
84501
84639
  }
84502
84640
 
84503
84641
  // src/version.ts
84504
- var SERVER_VERSION = "0.5.13";
84642
+ var SERVER_VERSION = "0.5.14";
84505
84643
 
84506
84644
  // src/server.ts
84507
84645
  var SERVER_INSTRUCTIONS = "Diamond Hands MCP \u2014 Bitcoin-collateralized borrowing. Before promising ANY flow, read the boundary://info resource and honor its `capabilities` block: it states which network this server is on, whether money is real (practiceWorld), whether writes are enabled (and the true reason when they are not), and which signer modes this build actually offers \u2014 never describe a flow outside it. State the network and whether funds are real when the user first acts. Authorization is chosen by conversation via the signer_setup tool (when listed); writes always require confirmed:true after showing the human-readable card. For walkthroughs consult the guide tool / guide:// resources instead of inventing steps; when a tool refuses, relay its stated reason and remedy \u2014 do not improvise alternatives. When a network_switch tool is listed, the network can change mid-session \u2014 after ANY switch, re-read boundary://info and state the new network and money reality to the user before doing anything else. When the user asks to disconnect / log out / sign out / forget or remove their wallet, call signer_setup action 'disconnect' (the full flush) \u2014 never treat 'reset-borrower' as a disconnect; it only swaps identity. READING DATA: a payload's fields and notes are authoritative \u2014 state what they say, never speculate past them, and when the data does not carry something, say 'the data does not carry X'. Field meanings live in guide topic 'reading-data'; `reading` notes inside a result are interpretation instructions for that exact payload \u2014 follow them over any prior assumption.";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gvnrdao/dh-mcp",
3
- "version": "0.5.13",
3
+ "version": "0.5.14",
4
4
  "description": "MCP server for the Diamond Hands protocol",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {