@gvnrdao/dh-mcp 0.5.12 → 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
@@ -41368,6 +41368,22 @@ var BoundaryCore = class {
41368
41368
  if (!r.ok) return errEnvelope(failureToError(r.failure));
41369
41369
  return okEnvelope({ releasedSats: r.value.releasedSats }, r.source);
41370
41370
  }
41371
+ /** C-46. Unlike `recoverStaleSpend` this is NOT permissionless: re-running phase 2 signs
41372
+ * for the vault, so it takes the same borrower gate every fund-moving op takes. */
41373
+ async retryWithdrawExecute(p) {
41374
+ const auth = await this.requireBorrower();
41375
+ if (!auth.ok) return errEnvelope(auth.error);
41376
+ const r = await this.deps.plugin.ops.retryWithdrawExecute({
41377
+ positionId: p.positionId,
41378
+ networkFeeSats: p.networkFeeSats,
41379
+ borrower: auth.borrower
41380
+ });
41381
+ if (!r.ok) return errEnvelope(failureToError(r.failure));
41382
+ return okEnvelope(
41383
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...r.value.authorization ? { authorization: r.value.authorization } : {} },
41384
+ r.source
41385
+ );
41386
+ }
41371
41387
  // ---- meta ----
41372
41388
  world() {
41373
41389
  return {
@@ -42191,6 +42207,78 @@ var World = class {
42191
42207
  c.authorizedSpends.splice(idx, 1);
42192
42208
  return { ok: true, value: { releasedSats: spend.satoshis } };
42193
42209
  }
42210
+ /**
42211
+ * C-46: re-run the withdrawal EXECUTE leg for reservations whose coins have not been
42212
+ * observed moving (`consumed === null`). This is the stranded shape: phase 1 committed
42213
+ * the reservation, phase 2's quantum-stamped signature expired, and the outpoint was
42214
+ * never spent.
42215
+ *
42216
+ * The retry BROADCASTS; it does not observe. `consumed` therefore stays null — that flag
42217
+ * means "seen consumed on Bitcoin", and only MockControl.confirmSpendConsumed (standing
42218
+ * in for the chain) may set it. Conflating the two would let a retry release collateral
42219
+ * against a transaction no one has confirmed, which is the mistake the whole
42220
+ * proof-of-consumption design exists to prevent. So a retry leaves the reservation
42221
+ * holding its balance exactly as before; what it produces is the txid that can LATER
42222
+ * become the invalidator — the proof the stranded state could never generate for itself.
42223
+ */
42224
+ retryWithdrawExecute(p) {
42225
+ const paused = this.pausedReason();
42226
+ if (paused) return { ok: false, reason: paused };
42227
+ const pos = this.state.positions[p.positionId];
42228
+ if (!pos) return { ok: false, reason: `position ${p.positionId} does not exist` };
42229
+ if (pos.borrower.toLowerCase() !== p.borrower.toLowerCase()) {
42230
+ return { ok: false, reason: `caller ${p.borrower} is not the borrower of this position` };
42231
+ }
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 };
42237
+ const { hash: txid } = this.nextId("btc-withdraw-retry");
42238
+ return {
42239
+ utxoIdentifier,
42240
+ ok: true,
42241
+ txid,
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(),
42248
+ destination: spend.targetAddress
42249
+ };
42250
+ });
42251
+ return { ok: true, value: { attempted: transfers.length, transfers } };
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
+ }
42194
42282
  // ---- Mock Safes (plan 06): REAL verification semantics, no fakes (M6-21/27) ----
42195
42283
  safesMap() {
42196
42284
  return this.state.safes;
@@ -43376,7 +43464,8 @@ var MockUpstreamPlugin = class {
43376
43464
  const r = this.world.recoverStaleSpend(p);
43377
43465
  if (!r.ok) return this.rejected("recoverStaleSpend", r.reason);
43378
43466
  return upOk({ txRef: this.world.nextTxRef(), releasedSats: r.value.releasedSats }, this.src("mock-ops"));
43379
- })
43467
+ }),
43468
+ retryWithdrawExecute: (p) => this.opRetryWithdrawExecute(p)
43380
43469
  };
43381
43470
  }
43382
43471
  indexer;
@@ -43651,6 +43740,46 @@ var MockUpstreamPlugin = class {
43651
43740
  );
43652
43741
  });
43653
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
+ }
43654
43783
  /** BWAR mirror ceremony (plan 06 E3): a SAFE borrower allowlists a BTC destination via
43655
43784
  * a Safe transaction (owner signatures, durable — async collection is honest here). On
43656
43785
  * mock, EOA borrowers have no allowlist gate; refusing beats faking success. */
@@ -51615,13 +51744,13 @@ var init_deployment_addresses = __esm2({
51615
51744
  block: 25472956
51616
51745
  },
51617
51746
  BTCSpendAuthorizer: {
51618
- previousImplementation: "0xb003ed89F695E8819a85513fE17260b805B3c478",
51619
- newImplementation: "0x40c9e8C46C65E0A57BB63da5368868A9E8Df81A5",
51620
- upgradedAt: "2026-07-06T10:40:59.000Z",
51621
- upgradedBy: "AdminModule/Safe audit-batch upgradeToAndCall; executed by 0xEba7BfAeB35ee18408b424Ee0BB45AdDf776589f in tx 0xe1b1884a7e76c7fd569522545a04e49d5128d83d27b3892cda59f143b53b5281 (block 25472957)",
51622
- reason: "Reconciled from chain \u2014 mainnet audit rollout batch (cross-ref onchain-auth/.safe-batches/mainnet-audit-execute.json)",
51623
- executeTx: "0xe1b1884a7e76c7fd569522545a04e49d5128d83d27b3892cda59f143b53b5281",
51624
- block: 25472957
51747
+ previousImplementation: "0x40c9e8C46C65E0A57BB63da5368868A9E8Df81A5",
51748
+ newImplementation: "0x00D7a47798E8ff169104b748131703B78f23390C",
51749
+ upgradedAt: "2026-09-09T12:05:35.000Z",
51750
+ upgradedBy: "AdminModule generic op 0xc0214ff38bb454864a34f6482dcd03570b3fd04171c84be2c20184afb1a2e161 (bsa-1-7-0 ceremony: proposed by seat 0x3030C0414B6d95aA9d5A57269E51a347fCBaB472 2026-09-08T11:35:23Z, 3/3 seat signatures, 24h timelock); executeGenericAdminOperation sent by 0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6 in tx 0x77cd231966c546177bd8f1a07bd4e705afd5c2dfbd110b096836401679c0c69c (block 25939703)",
51751
+ reason: "BTCSpendAuthorizer 1.6.0 -> 1.7.0: allow a full-vault sweep (targetAmount == satoshis); TargetMustLeaveFeeRoom -> TargetExceedsInputValue (PR #849; mainnet incidents 2026-09-04 and 2026-09-07). Impl deployed by 0xEba7BfAeB35ee18408b424Ee0BB45AdDf776589f at nonce 430 from source 0a7c535a1 (contracts/src identical to main 99b335f77). Cross-ref onchain-auth/.safe-batches/mainnet-bsa-1-7-0-{propose,sign,execute}.json and docs/mainnet-bsa-1-7-0-ceremony-2026-09-08.md",
51752
+ executeTx: "0x77cd231966c546177bd8f1a07bd4e705afd5c2dfbd110b096836401679c0c69c",
51753
+ block: 25939703
51625
51754
  },
51626
51755
  PositionManager: {
51627
51756
  previousImplementation: "0x600Dc0D1C2c0F94882B6Bc09172f8650047Ad5B1",
@@ -51724,7 +51853,7 @@ var init_deployment_addresses = __esm2({
51724
51853
  ADMIN_MODULE: "0x0023B71B586795eE5fa4E83E384345C1EC8Bb946",
51725
51854
  ADMIN_MODULE_IMPL: "0xb4C5C7E051A1e672F014B25CB5D55B225Aa0D512",
51726
51855
  BTC_SPEND_AUTHORIZER: "0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",
51727
- BTC_SPEND_AUTHORIZER_IMPL: "0x40c9e8C46C65E0A57BB63da5368868A9E8Df81A5",
51856
+ BTC_SPEND_AUTHORIZER_IMPL: "0x00D7a47798E8ff169104b748131703B78f23390C",
51728
51857
  POSITION_MANAGER_VIEWS: "0x8B57954eA338c6A6bfF1457f71080e25baFF3937",
51729
51858
  POSITION_MANAGER_VIEWS_IMPL: "0xE68DC096A65Ecddbc6A9b5c6e5f878e2CE143Bfe",
51730
51859
  POSITION_MANAGER: "0x12A1836e56139ccaD8722B89519d84233efc224B",
@@ -57794,9 +57923,27 @@ var LOGIN_TYPES_WITH_AUDIENCE2 = {
57794
57923
  { name: "audience", type: "string" }
57795
57924
  ]
57796
57925
  };
57797
- async function buildSignedLoginPayload(signer, chainId, audience, reuse) {
57926
+ var LOGIN_TYPES_WITH_STATEMENT = {
57927
+ DiamondHands: [
57928
+ { name: "statement", type: "string" },
57929
+ { name: "address", type: "address" },
57930
+ { name: "issuedAt", type: "uint256" },
57931
+ { name: "nonce", type: "bytes32" },
57932
+ { name: "audience", type: "string" }
57933
+ ]
57934
+ };
57935
+ var LOGIN_STATEMENT_TEMPLATE = "{host} is verifying you own this wallet. Signing proves control of the address so we can show your loans and positions. It authorizes no transaction, moves no funds, and costs no gas.";
57936
+ function canonicalLoginStatement(audience) {
57937
+ const host = /^https?:\/\/([^/?#]+)/i.exec(audience)?.[1];
57938
+ if (!host)
57939
+ return null;
57940
+ return LOGIN_STATEMENT_TEMPLATE.replace("{host}", host);
57941
+ }
57942
+ async function buildSignedLoginPayload(signer, chainId, audience, reuse, withStatement = false) {
57798
57943
  const address = await signer.getAddress();
57944
+ const statement = withStatement && audience ? canonicalLoginStatement(audience) : null;
57799
57945
  const message = {
57946
+ ...statement ? { statement } : {},
57800
57947
  address,
57801
57948
  issuedAt: reuse?.issuedAt ?? Math.floor(Date.now() / 1e3),
57802
57949
  nonce: reuse?.nonce ?? (0, import_ethers17.hexlify)((0, import_ethers17.randomBytes)(32)),
@@ -57804,7 +57951,7 @@ async function buildSignedLoginPayload(signer, chainId, audience, reuse) {
57804
57951
  };
57805
57952
  const signature = await signer.signTypedData(
57806
57953
  buildLoginDomain(chainId),
57807
- audience ? LOGIN_TYPES_WITH_AUDIENCE2 : LOGIN_TYPES2,
57954
+ statement ? LOGIN_TYPES_WITH_STATEMENT : audience ? LOGIN_TYPES_WITH_AUDIENCE2 : LOGIN_TYPES2,
57808
57955
  message
57809
57956
  );
57810
57957
  return { chainId, message, signature };
@@ -57973,6 +58120,8 @@ var ServerSession = class {
57973
58120
  signer;
57974
58121
  serviceEndpoint;
57975
58122
  loginAudience;
58123
+ /** Whether this session's login carries the human-readable statement. */
58124
+ withStatement;
57976
58125
  chainId;
57977
58126
  store;
57978
58127
  onSignaturePrompt;
@@ -58014,6 +58163,13 @@ var ServerSession = class {
58014
58163
  /\/+$/,
58015
58164
  ""
58016
58165
  );
58166
+ const explicitAudience = typeof opts.loginAudience === "string" && opts.loginAudience.length > 0;
58167
+ this.withStatement = opts.withStatement === true && explicitAudience;
58168
+ if (opts.withStatement === true && !explicitAudience) {
58169
+ console.warn(
58170
+ "[dh-sdk] withStatement ignored: it requires an explicit loginAudience, since the servers rebuild the expected sentence from the audience host"
58171
+ );
58172
+ }
58017
58173
  this.chainId = opts.chainId;
58018
58174
  this.store = opts.persistSession === false ? null : opts.sessionStore ?? createDefaultSessionStore();
58019
58175
  this.onSignaturePrompt = opts.onSignaturePrompt;
@@ -58267,12 +58423,16 @@ var ServerSession = class {
58267
58423
  this.signer,
58268
58424
  this.chainId,
58269
58425
  this.loginAudience,
58270
- reuse
58426
+ reuse,
58427
+ reuse ? reuse.withStatement === true : this.withStatement
58271
58428
  );
58272
58429
  if (storeKey && !reuse) {
58273
58430
  store.savePending?.(storeKey, {
58274
58431
  issuedAt: payload.message.issuedAt,
58275
- nonce: payload.message.nonce
58432
+ nonce: payload.message.nonce,
58433
+ // Recorded so a resume reproduces this digest even if the
58434
+ // capability flag changes before the owners finish signing.
58435
+ withStatement: this.withStatement
58276
58436
  });
58277
58437
  }
58278
58438
  session = await this.login(payload);
@@ -70483,6 +70643,9 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
70483
70643
  signer: config.authSigner ?? config.contractSigner,
70484
70644
  serviceEndpoint: config.serviceEndpoint,
70485
70645
  loginAudience: config.loginAudience,
70646
+ // Only meaningful alongside an audience; the servers derive the expected
70647
+ // sentence from its host. Defaults off so Node callers are untouched.
70648
+ withStatement: config.loginStatement === true,
70486
70649
  chainId: config.chainId,
70487
70650
  persistSession: config.sessionPersistence?.enabled,
70488
70651
  sessionStore: config.sessionPersistence?.store,
@@ -79328,7 +79491,33 @@ function buildWriteOps(deps) {
79328
79491
  kind: "unavailable",
79329
79492
  source: SOURCE5,
79330
79493
  message: "recoverStaleSpend is not wired in this delivery (permissionless recovery \u2014 planned follow-up)."
79331
- })
79494
+ }),
79495
+ retryWithdrawExecute: async (p) => {
79496
+ const sdk = deps.getWriteSdk();
79497
+ if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
79498
+ let rows;
79499
+ try {
79500
+ rows = await sdk.executePendingBtcTransfers(p.positionId, p.networkFeeSats);
79501
+ } catch (e) {
79502
+ return failed("retryWithdrawExecute", e);
79503
+ }
79504
+ const gate = rows.find((r) => !r.success && !r.utxoIdentifier);
79505
+ if (gate) return declined("retryWithdrawExecute", gate.error ?? "pending-transfer execution refused before any reservation was attempted");
79506
+ return upOk(
79507
+ {
79508
+ attempted: rows.length,
79509
+ transfers: rows.map((r) => ({
79510
+ utxoIdentifier: r.utxoIdentifier ?? "",
79511
+ ok: r.success,
79512
+ ...r.txid ? { txid: r.txid } : {},
79513
+ ...r.amountSent !== void 0 ? { amountSentSats: String(r.amountSent) } : {},
79514
+ ...r.destination ? { destination: r.destination } : {},
79515
+ ...r.error ? { error: r.error } : {}
79516
+ }))
79517
+ },
79518
+ { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
79519
+ );
79520
+ }
79332
79521
  };
79333
79522
  }
79334
79523
 
@@ -79853,7 +80042,8 @@ var RealUpstreamPlugin = class {
79853
80042
  message: "no signer configured \u2014 psmSwap signs two on-chain transactions (exact-amount approve, then swap/redeem) with the keystore signer. Set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD to enable it."
79854
80043
  })
79855
80044
  ),
79856
- recoverStaleSpend: () => readOnly("recoverStaleSpend")
80045
+ recoverStaleSpend: () => readOnly("recoverStaleSpend"),
80046
+ retryWithdrawExecute: () => readOnly("retryWithdrawExecute")
79857
80047
  };
79858
80048
  }
79859
80049
  }
@@ -80021,7 +80211,8 @@ var RealUpstreamPlugin = class {
80021
80211
  psmSwap: call("psmSwap"),
80022
80212
  delegationSetup: call("delegationSetup"),
80023
80213
  delegationGrant: call("delegationGrant"),
80024
- recoverStaleSpend: call("recoverStaleSpend")
80214
+ recoverStaleSpend: call("recoverStaleSpend"),
80215
+ retryWithdrawExecute: call("retryWithdrawExecute")
80025
80216
  };
80026
80217
  }
80027
80218
  async resolveOpsGateway() {
@@ -80860,6 +81051,9 @@ function wcDeclineOrFault(e) {
80860
81051
  }
80861
81052
  var SignatureBridge = class {
80862
81053
  clock;
81054
+ /** Lowercased at construction so every comparison is case-flat — EIP-55 checksum casing
81055
+ * differs between what SIWE signs and what a wallet reports for the SAME address. */
81056
+ boundAccount;
80863
81057
  expiryMs;
80864
81058
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
80865
81059
  maxPending;
@@ -80895,6 +81089,7 @@ var SignatureBridge = class {
80895
81089
  unlockSession = null;
80896
81090
  constructor(opts) {
80897
81091
  this.clock = opts?.clock ?? Date.now;
81092
+ this.boundAccount = opts?.boundAccount?.toLowerCase();
80898
81093
  this.expiryMs = opts?.expiryMs ?? DEFAULT_EXPIRY_MS;
80899
81094
  this.maxPending = opts?.maxPending ?? null;
80900
81095
  this.attachGraceMs = opts?.attachGraceMs ?? (opts?.mount ? DEFAULT_HOSTED_ATTACH_GRACE_MS : DEFAULT_ATTACH_GRACE_MS);
@@ -80976,7 +81171,7 @@ var SignatureBridge = class {
80976
81171
  connectedAccounts() {
80977
81172
  const seen = /* @__PURE__ */ new Map();
80978
81173
  for (const s of this.sessions.values()) {
80979
- 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);
80980
81175
  }
80981
81176
  if (this.wcActive && this.wallet) seen.set(this.wallet.account.toLowerCase(), this.wallet.account);
80982
81177
  return [...seen.values()];
@@ -81237,7 +81432,7 @@ var SignatureBridge = class {
81237
81432
  return;
81238
81433
  }
81239
81434
  const sessionId = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81240
- this.sessions.set(sessionId, { wallet: null, sse: null });
81435
+ this.sessions.set(sessionId, { wallet: null, sse: null, refused: null });
81241
81436
  const page = htmlPageSecurityHeaders();
81242
81437
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
81243
81438
  res.end(renderApprovalPage(sessionId, page.nonce));
@@ -81264,6 +81459,14 @@ var SignatureBridge = class {
81264
81459
  });
81265
81460
  this.wcTransport = await factory2(this.wcConfig);
81266
81461
  this.wcTransport.onSession((info) => {
81462
+ const refusal = info ? this.accountRefusal(info.account) : null;
81463
+ if (info && refusal) {
81464
+ this.wcActive = false;
81465
+ this.rebuildSharedWallet();
81466
+ process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
81467
+ `);
81468
+ return;
81469
+ }
81267
81470
  this.wcActive = info !== null;
81268
81471
  this.wallet = info ? { account: info.account, chainId: info.chainId } : null;
81269
81472
  if (info === null) {
@@ -81361,10 +81564,37 @@ var SignatureBridge = class {
81361
81564
  this.deny(res, 400, "hello requires account (0x address) and integer chainId");
81362
81565
  return;
81363
81566
  }
81567
+ const refusal = this.accountRefusal(account);
81568
+ if (refusal) {
81569
+ this.quarantine(session, refusal);
81570
+ this.deny(res, 403, refusal);
81571
+ return;
81572
+ }
81364
81573
  session.wallet = { account, chainId };
81365
81574
  this.wallet = { account, chainId };
81366
81575
  this.ok(res);
81367
81576
  }
81577
+ /** C-47: the single predicate every wallet account is admitted through. There are THREE
81578
+ * doors into the account this bridge will sign with — `hello`, `accountsChanged`, and the
81579
+ * WalletConnect `onSession` callback — and all three call this. The first version of this
81580
+ * fix guarded only the first two while this docstring already claimed to be "the single
81581
+ * place", which is how the WC door survived a green suite: the claim was in prose, not in a
81582
+ * test. T-EXT-BIND-01/02/04 now pin one door each, so adding a fourth writer of
81583
+ * `this.wallet` without coming through here fails a test rather than a review.
81584
+ *
81585
+ * Returns the refusal reason, or
81586
+ * null when the account may be adopted.
81587
+ *
81588
+ * Both addresses are named because the pre-fix failure surfaced much later as an opaque
81589
+ * signature-recovery error (`external-eoa.ts:230-233`) that named neither and read as a
81590
+ * wallet fault. A user with several accounts in one wallet extension hits this by
81591
+ * accident far more often than any attacker does, and "wrong account" is only actionable
81592
+ * if it says WHICH. */
81593
+ accountRefusal(account) {
81594
+ if (!this.boundAccount) return null;
81595
+ if (account.toLowerCase() === this.boundAccount) return null;
81596
+ return `this session is signed in as ${this.boundAccount} but the wallet offered ${account.toLowerCase()} \u2014 the account that signs must be the account that signed in. Switch your wallet to the signed-in account, or start a new session with this one.`;
81597
+ }
81368
81598
  /** accountsChanged / chainChanged: a wallet-state CHANGE mid-request invalidates every
81369
81599
  * pending request — what the human saw approved is no longer what would sign. Wallets
81370
81600
  * also deliver late no-op echoes of these events; an unchanged state invalidates nothing. */
@@ -81374,16 +81604,23 @@ var SignatureBridge = class {
81374
81604
  const account = String(body["account"] ?? "");
81375
81605
  const chainId = Number(body["chainId"]);
81376
81606
  const prev = session.wallet;
81377
- session.wallet = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
81378
- if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
81379
- this.wallet = session.wallet;
81607
+ const offered = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
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
+ }
81380
81617
  }
81381
81618
  const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
81382
81619
  if (unchanged) {
81383
81620
  this.ok(res);
81384
81621
  return;
81385
81622
  }
81386
- const reason = prev && session.wallet && prev.account.toLowerCase() !== session.wallet.account.toLowerCase() ? "the wallet account changed while approval was pending" : prev && session.wallet && prev.chainId !== session.wallet.chainId ? "the wallet network changed while approval was pending" : "the wallet disconnected while approval was pending";
81623
+ const reason = refusedSwitch ? "the wallet switched to an account this session is not signed in as" : prev && session.wallet && prev.account.toLowerCase() !== session.wallet.account.toLowerCase() ? "the wallet account changed while approval was pending" : prev && session.wallet && prev.chainId !== session.wallet.chainId ? "the wallet network changed while approval was pending" : "the wallet disconnected while approval was pending";
81387
81624
  for (const entry of this.pending.values()) {
81388
81625
  if (!entry.settled && !entry.collect) this.settle(entry, { status: "invalidated", reason });
81389
81626
  }
@@ -81473,7 +81710,7 @@ var SignatureBridge = class {
81473
81710
  const data = `data: ${JSON.stringify(request)}
81474
81711
 
81475
81712
  `;
81476
- 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);
81477
81714
  }
81478
81715
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
81479
81716
  pushProgress(payload) {
@@ -81481,7 +81718,48 @@ var SignatureBridge = class {
81481
81718
  data: ${JSON.stringify(payload)}
81482
81719
 
81483
81720
  `;
81484
- 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();
81485
81763
  }
81486
81764
  sessionOf(candidate, res) {
81487
81765
  const session = typeof candidate === "string" ? this.sessions.get(candidate) ?? null : null;
@@ -81489,6 +81767,10 @@ data: ${JSON.stringify(payload)}
81489
81767
  this.deny(res, 403, "missing or wrong session");
81490
81768
  return null;
81491
81769
  }
81770
+ if (session.refused) {
81771
+ this.deny(res, 403, session.refused);
81772
+ return null;
81773
+ }
81492
81774
  return session;
81493
81775
  }
81494
81776
  checkSession(candidate, res) {
@@ -81898,6 +82180,11 @@ async function createRealBoundary(config, wallet, overrides) {
81898
82180
  // tenant — one bridge per tenant world, so the bridge cap IS the tenant cap. The
81899
82181
  // loopback tier keeps its unbounded pending (multi-owner Safe pages need it).
81900
82182
  ...overrides?.bridgeMount ? { mount: overrides.bridgeMount(config.network), maxPending: 1 } : {},
82183
+ // C-47: the authenticated identity governs the write path. Passed separately from
82184
+ // `bridgeMount` although the hosted tier sets both — they answer different questions
82185
+ // ("where does the page live" vs "whose wallet may sign"), and fusing them would make
82186
+ // an unbound hosted bridge impossible to express in a test.
82187
+ ...overrides?.boundBorrower ? { boundAccount: overrides.boundBorrower } : {},
81901
82188
  // M12-12: no unlock closures without a provider — the unlock endpoints answer with
81902
82189
  // their loud not-wired refusal instead of ever touching key material.
81903
82190
  ...keystore ? {