@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.
@@ -41036,7 +41036,7 @@ function htmlPageSecurityHeaders(extra) {
41036
41036
  }
41037
41037
 
41038
41038
  // src/version.ts
41039
- var SERVER_VERSION = "0.5.12";
41039
+ var SERVER_VERSION = "0.5.14";
41040
41040
 
41041
41041
  // src/connector/siwe-oauth.ts
41042
41042
  var import_node_crypto2 = require("crypto");
@@ -42489,6 +42489,22 @@ var BoundaryCore = class {
42489
42489
  if (!r.ok) return errEnvelope(failureToError(r.failure));
42490
42490
  return okEnvelope({ releasedSats: r.value.releasedSats }, r.source);
42491
42491
  }
42492
+ /** C-46. Unlike `recoverStaleSpend` this is NOT permissionless: re-running phase 2 signs
42493
+ * for the vault, so it takes the same borrower gate every fund-moving op takes. */
42494
+ async retryWithdrawExecute(p) {
42495
+ const auth = await this.requireBorrower();
42496
+ if (!auth.ok) return errEnvelope(auth.error);
42497
+ const r = await this.deps.plugin.ops.retryWithdrawExecute({
42498
+ positionId: p.positionId,
42499
+ networkFeeSats: p.networkFeeSats,
42500
+ borrower: auth.borrower
42501
+ });
42502
+ if (!r.ok) return errEnvelope(failureToError(r.failure));
42503
+ return okEnvelope(
42504
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...r.value.authorization ? { authorization: r.value.authorization } : {} },
42505
+ r.source
42506
+ );
42507
+ }
42492
42508
  // ---- meta ----
42493
42509
  world() {
42494
42510
  return {
@@ -43312,6 +43328,78 @@ var World = class {
43312
43328
  c.authorizedSpends.splice(idx, 1);
43313
43329
  return { ok: true, value: { releasedSats: spend.satoshis } };
43314
43330
  }
43331
+ /**
43332
+ * C-46: re-run the withdrawal EXECUTE leg for reservations whose coins have not been
43333
+ * observed moving (`consumed === null`). This is the stranded shape: phase 1 committed
43334
+ * the reservation, phase 2's quantum-stamped signature expired, and the outpoint was
43335
+ * never spent.
43336
+ *
43337
+ * The retry BROADCASTS; it does not observe. `consumed` therefore stays null — that flag
43338
+ * means "seen consumed on Bitcoin", and only MockControl.confirmSpendConsumed (standing
43339
+ * in for the chain) may set it. Conflating the two would let a retry release collateral
43340
+ * against a transaction no one has confirmed, which is the mistake the whole
43341
+ * proof-of-consumption design exists to prevent. So a retry leaves the reservation
43342
+ * holding its balance exactly as before; what it produces is the txid that can LATER
43343
+ * become the invalidator — the proof the stranded state could never generate for itself.
43344
+ */
43345
+ retryWithdrawExecute(p) {
43346
+ const paused = this.pausedReason();
43347
+ if (paused) return { ok: false, reason: paused };
43348
+ const pos = this.state.positions[p.positionId];
43349
+ if (!pos) return { ok: false, reason: `position ${p.positionId} does not exist` };
43350
+ if (pos.borrower.toLowerCase() !== p.borrower.toLowerCase()) {
43351
+ return { ok: false, reason: `caller ${p.borrower} is not the borrower of this position` };
43352
+ }
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 };
43358
+ const { hash: txid } = this.nextId("btc-withdraw-retry");
43359
+ return {
43360
+ utxoIdentifier,
43361
+ ok: true,
43362
+ txid,
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(),
43369
+ destination: spend.targetAddress
43370
+ };
43371
+ });
43372
+ return { ok: true, value: { attempted: transfers.length, transfers } };
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
+ }
43315
43403
  // ---- Mock Safes (plan 06): REAL verification semantics, no fakes (M6-21/27) ----
43316
43404
  safesMap() {
43317
43405
  return this.state.safes;
@@ -44506,7 +44594,8 @@ var MockUpstreamPlugin = class {
44506
44594
  const r = this.world.recoverStaleSpend(p);
44507
44595
  if (!r.ok) return this.rejected("recoverStaleSpend", r.reason);
44508
44596
  return upOk({ txRef: this.world.nextTxRef(), releasedSats: r.value.releasedSats }, this.src("mock-ops"));
44509
- })
44597
+ }),
44598
+ retryWithdrawExecute: (p) => this.opRetryWithdrawExecute(p)
44510
44599
  };
44511
44600
  }
44512
44601
  indexer;
@@ -44781,6 +44870,46 @@ var MockUpstreamPlugin = class {
44781
44870
  );
44782
44871
  });
44783
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
+ }
44784
44913
  /** BWAR mirror ceremony (plan 06 E3): a SAFE borrower allowlists a BTC destination via
44785
44914
  * a Safe transaction (owner signatures, durable — async collection is honest here). On
44786
44915
  * mock, EOA borrowers have no allowlist gate; refusing beats faking success. */
@@ -52745,13 +52874,13 @@ var init_deployment_addresses = __esm2({
52745
52874
  block: 25472956
52746
52875
  },
52747
52876
  BTCSpendAuthorizer: {
52748
- previousImplementation: "0xb003ed89F695E8819a85513fE17260b805B3c478",
52749
- newImplementation: "0x40c9e8C46C65E0A57BB63da5368868A9E8Df81A5",
52750
- upgradedAt: "2026-07-06T10:40:59.000Z",
52751
- upgradedBy: "AdminModule/Safe audit-batch upgradeToAndCall; executed by 0xEba7BfAeB35ee18408b424Ee0BB45AdDf776589f in tx 0xe1b1884a7e76c7fd569522545a04e49d5128d83d27b3892cda59f143b53b5281 (block 25472957)",
52752
- reason: "Reconciled from chain \u2014 mainnet audit rollout batch (cross-ref onchain-auth/.safe-batches/mainnet-audit-execute.json)",
52753
- executeTx: "0xe1b1884a7e76c7fd569522545a04e49d5128d83d27b3892cda59f143b53b5281",
52754
- block: 25472957
52877
+ previousImplementation: "0x40c9e8C46C65E0A57BB63da5368868A9E8Df81A5",
52878
+ newImplementation: "0x00D7a47798E8ff169104b748131703B78f23390C",
52879
+ upgradedAt: "2026-09-09T12:05:35.000Z",
52880
+ 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)",
52881
+ 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",
52882
+ executeTx: "0x77cd231966c546177bd8f1a07bd4e705afd5c2dfbd110b096836401679c0c69c",
52883
+ block: 25939703
52755
52884
  },
52756
52885
  PositionManager: {
52757
52886
  previousImplementation: "0x600Dc0D1C2c0F94882B6Bc09172f8650047Ad5B1",
@@ -52854,7 +52983,7 @@ var init_deployment_addresses = __esm2({
52854
52983
  ADMIN_MODULE: "0x0023B71B586795eE5fa4E83E384345C1EC8Bb946",
52855
52984
  ADMIN_MODULE_IMPL: "0xb4C5C7E051A1e672F014B25CB5D55B225Aa0D512",
52856
52985
  BTC_SPEND_AUTHORIZER: "0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",
52857
- BTC_SPEND_AUTHORIZER_IMPL: "0x40c9e8C46C65E0A57BB63da5368868A9E8Df81A5",
52986
+ BTC_SPEND_AUTHORIZER_IMPL: "0x00D7a47798E8ff169104b748131703B78f23390C",
52858
52987
  POSITION_MANAGER_VIEWS: "0x8B57954eA338c6A6bfF1457f71080e25baFF3937",
52859
52988
  POSITION_MANAGER_VIEWS_IMPL: "0xE68DC096A65Ecddbc6A9b5c6e5f878e2CE143Bfe",
52860
52989
  POSITION_MANAGER: "0x12A1836e56139ccaD8722B89519d84233efc224B",
@@ -58924,9 +59053,27 @@ var LOGIN_TYPES_WITH_AUDIENCE2 = {
58924
59053
  { name: "audience", type: "string" }
58925
59054
  ]
58926
59055
  };
58927
- async function buildSignedLoginPayload(signer, chainId, audience, reuse) {
59056
+ var LOGIN_TYPES_WITH_STATEMENT = {
59057
+ DiamondHands: [
59058
+ { name: "statement", type: "string" },
59059
+ { name: "address", type: "address" },
59060
+ { name: "issuedAt", type: "uint256" },
59061
+ { name: "nonce", type: "bytes32" },
59062
+ { name: "audience", type: "string" }
59063
+ ]
59064
+ };
59065
+ 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.";
59066
+ function canonicalLoginStatement(audience) {
59067
+ const host = /^https?:\/\/([^/?#]+)/i.exec(audience)?.[1];
59068
+ if (!host)
59069
+ return null;
59070
+ return LOGIN_STATEMENT_TEMPLATE.replace("{host}", host);
59071
+ }
59072
+ async function buildSignedLoginPayload(signer, chainId, audience, reuse, withStatement = false) {
58928
59073
  const address = await signer.getAddress();
59074
+ const statement = withStatement && audience ? canonicalLoginStatement(audience) : null;
58929
59075
  const message = {
59076
+ ...statement ? { statement } : {},
58930
59077
  address,
58931
59078
  issuedAt: reuse?.issuedAt ?? Math.floor(Date.now() / 1e3),
58932
59079
  nonce: reuse?.nonce ?? (0, import_ethers18.hexlify)((0, import_ethers18.randomBytes)(32)),
@@ -58934,7 +59081,7 @@ async function buildSignedLoginPayload(signer, chainId, audience, reuse) {
58934
59081
  };
58935
59082
  const signature = await signer.signTypedData(
58936
59083
  buildLoginDomain(chainId),
58937
- audience ? LOGIN_TYPES_WITH_AUDIENCE2 : LOGIN_TYPES2,
59084
+ statement ? LOGIN_TYPES_WITH_STATEMENT : audience ? LOGIN_TYPES_WITH_AUDIENCE2 : LOGIN_TYPES2,
58938
59085
  message
58939
59086
  );
58940
59087
  return { chainId, message, signature };
@@ -59103,6 +59250,8 @@ var ServerSession = class {
59103
59250
  signer;
59104
59251
  serviceEndpoint;
59105
59252
  loginAudience;
59253
+ /** Whether this session's login carries the human-readable statement. */
59254
+ withStatement;
59106
59255
  chainId;
59107
59256
  store;
59108
59257
  onSignaturePrompt;
@@ -59144,6 +59293,13 @@ var ServerSession = class {
59144
59293
  /\/+$/,
59145
59294
  ""
59146
59295
  );
59296
+ const explicitAudience = typeof opts.loginAudience === "string" && opts.loginAudience.length > 0;
59297
+ this.withStatement = opts.withStatement === true && explicitAudience;
59298
+ if (opts.withStatement === true && !explicitAudience) {
59299
+ console.warn(
59300
+ "[dh-sdk] withStatement ignored: it requires an explicit loginAudience, since the servers rebuild the expected sentence from the audience host"
59301
+ );
59302
+ }
59147
59303
  this.chainId = opts.chainId;
59148
59304
  this.store = opts.persistSession === false ? null : opts.sessionStore ?? createDefaultSessionStore();
59149
59305
  this.onSignaturePrompt = opts.onSignaturePrompt;
@@ -59397,12 +59553,16 @@ var ServerSession = class {
59397
59553
  this.signer,
59398
59554
  this.chainId,
59399
59555
  this.loginAudience,
59400
- reuse
59556
+ reuse,
59557
+ reuse ? reuse.withStatement === true : this.withStatement
59401
59558
  );
59402
59559
  if (storeKey && !reuse) {
59403
59560
  store.savePending?.(storeKey, {
59404
59561
  issuedAt: payload.message.issuedAt,
59405
- nonce: payload.message.nonce
59562
+ nonce: payload.message.nonce,
59563
+ // Recorded so a resume reproduces this digest even if the
59564
+ // capability flag changes before the owners finish signing.
59565
+ withStatement: this.withStatement
59406
59566
  });
59407
59567
  }
59408
59568
  session = await this.login(payload);
@@ -71613,6 +71773,9 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
71613
71773
  signer: config.authSigner ?? config.contractSigner,
71614
71774
  serviceEndpoint: config.serviceEndpoint,
71615
71775
  loginAudience: config.loginAudience,
71776
+ // Only meaningful alongside an audience; the servers derive the expected
71777
+ // sentence from its host. Defaults off so Node callers are untouched.
71778
+ withStatement: config.loginStatement === true,
71616
71779
  chainId: config.chainId,
71617
71780
  persistSession: config.sessionPersistence?.enabled,
71618
71781
  sessionStore: config.sessionPersistence?.store,
@@ -80458,7 +80621,33 @@ function buildWriteOps(deps) {
80458
80621
  kind: "unavailable",
80459
80622
  source: SOURCE5,
80460
80623
  message: "recoverStaleSpend is not wired in this delivery (permissionless recovery \u2014 planned follow-up)."
80461
- })
80624
+ }),
80625
+ retryWithdrawExecute: async (p) => {
80626
+ const sdk = deps.getWriteSdk();
80627
+ if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
80628
+ let rows;
80629
+ try {
80630
+ rows = await sdk.executePendingBtcTransfers(p.positionId, p.networkFeeSats);
80631
+ } catch (e) {
80632
+ return failed("retryWithdrawExecute", e);
80633
+ }
80634
+ const gate = rows.find((r) => !r.success && !r.utxoIdentifier);
80635
+ if (gate) return declined("retryWithdrawExecute", gate.error ?? "pending-transfer execution refused before any reservation was attempted");
80636
+ return upOk(
80637
+ {
80638
+ attempted: rows.length,
80639
+ transfers: rows.map((r) => ({
80640
+ utxoIdentifier: r.utxoIdentifier ?? "",
80641
+ ok: r.success,
80642
+ ...r.txid ? { txid: r.txid } : {},
80643
+ ...r.amountSent !== void 0 ? { amountSentSats: String(r.amountSent) } : {},
80644
+ ...r.destination ? { destination: r.destination } : {},
80645
+ ...r.error ? { error: r.error } : {}
80646
+ }))
80647
+ },
80648
+ { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
80649
+ );
80650
+ }
80462
80651
  };
80463
80652
  }
80464
80653
 
@@ -80983,7 +81172,8 @@ var RealUpstreamPlugin = class {
80983
81172
  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."
80984
81173
  })
80985
81174
  ),
80986
- recoverStaleSpend: () => readOnly("recoverStaleSpend")
81175
+ recoverStaleSpend: () => readOnly("recoverStaleSpend"),
81176
+ retryWithdrawExecute: () => readOnly("retryWithdrawExecute")
80987
81177
  };
80988
81178
  }
80989
81179
  }
@@ -81151,7 +81341,8 @@ var RealUpstreamPlugin = class {
81151
81341
  psmSwap: call("psmSwap"),
81152
81342
  delegationSetup: call("delegationSetup"),
81153
81343
  delegationGrant: call("delegationGrant"),
81154
- recoverStaleSpend: call("recoverStaleSpend")
81344
+ recoverStaleSpend: call("recoverStaleSpend"),
81345
+ retryWithdrawExecute: call("retryWithdrawExecute")
81155
81346
  };
81156
81347
  }
81157
81348
  async resolveOpsGateway() {
@@ -81962,6 +82153,9 @@ function wcDeclineOrFault(e) {
81962
82153
  }
81963
82154
  var SignatureBridge = class {
81964
82155
  clock;
82156
+ /** Lowercased at construction so every comparison is case-flat — EIP-55 checksum casing
82157
+ * differs between what SIWE signs and what a wallet reports for the SAME address. */
82158
+ boundAccount;
81965
82159
  expiryMs;
81966
82160
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
81967
82161
  maxPending;
@@ -81997,6 +82191,7 @@ var SignatureBridge = class {
81997
82191
  unlockSession = null;
81998
82192
  constructor(opts) {
81999
82193
  this.clock = opts?.clock ?? Date.now;
82194
+ this.boundAccount = opts?.boundAccount?.toLowerCase();
82000
82195
  this.expiryMs = opts?.expiryMs ?? DEFAULT_EXPIRY_MS;
82001
82196
  this.maxPending = opts?.maxPending ?? null;
82002
82197
  this.attachGraceMs = opts?.attachGraceMs ?? (opts?.mount ? DEFAULT_HOSTED_ATTACH_GRACE_MS : DEFAULT_ATTACH_GRACE_MS);
@@ -82078,7 +82273,7 @@ var SignatureBridge = class {
82078
82273
  connectedAccounts() {
82079
82274
  const seen = /* @__PURE__ */ new Map();
82080
82275
  for (const s of this.sessions.values()) {
82081
- 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);
82082
82277
  }
82083
82278
  if (this.wcActive && this.wallet) seen.set(this.wallet.account.toLowerCase(), this.wallet.account);
82084
82279
  return [...seen.values()];
@@ -82339,7 +82534,7 @@ var SignatureBridge = class {
82339
82534
  return;
82340
82535
  }
82341
82536
  const sessionId = (0, import_node_crypto8.randomBytes)(24).toString("hex");
82342
- this.sessions.set(sessionId, { wallet: null, sse: null });
82537
+ this.sessions.set(sessionId, { wallet: null, sse: null, refused: null });
82343
82538
  const page = htmlPageSecurityHeaders();
82344
82539
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
82345
82540
  res.end(renderApprovalPage(sessionId, page.nonce));
@@ -82366,6 +82561,14 @@ var SignatureBridge = class {
82366
82561
  });
82367
82562
  this.wcTransport = await factory2(this.wcConfig);
82368
82563
  this.wcTransport.onSession((info) => {
82564
+ const refusal = info ? this.accountRefusal(info.account) : null;
82565
+ if (info && refusal) {
82566
+ this.wcActive = false;
82567
+ this.rebuildSharedWallet();
82568
+ process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
82569
+ `);
82570
+ return;
82571
+ }
82369
82572
  this.wcActive = info !== null;
82370
82573
  this.wallet = info ? { account: info.account, chainId: info.chainId } : null;
82371
82574
  if (info === null) {
@@ -82463,10 +82666,37 @@ var SignatureBridge = class {
82463
82666
  this.deny(res, 400, "hello requires account (0x address) and integer chainId");
82464
82667
  return;
82465
82668
  }
82669
+ const refusal = this.accountRefusal(account);
82670
+ if (refusal) {
82671
+ this.quarantine(session, refusal);
82672
+ this.deny(res, 403, refusal);
82673
+ return;
82674
+ }
82466
82675
  session.wallet = { account, chainId };
82467
82676
  this.wallet = { account, chainId };
82468
82677
  this.ok(res);
82469
82678
  }
82679
+ /** C-47: the single predicate every wallet account is admitted through. There are THREE
82680
+ * doors into the account this bridge will sign with — `hello`, `accountsChanged`, and the
82681
+ * WalletConnect `onSession` callback — and all three call this. The first version of this
82682
+ * fix guarded only the first two while this docstring already claimed to be "the single
82683
+ * place", which is how the WC door survived a green suite: the claim was in prose, not in a
82684
+ * test. T-EXT-BIND-01/02/04 now pin one door each, so adding a fourth writer of
82685
+ * `this.wallet` without coming through here fails a test rather than a review.
82686
+ *
82687
+ * Returns the refusal reason, or
82688
+ * null when the account may be adopted.
82689
+ *
82690
+ * Both addresses are named because the pre-fix failure surfaced much later as an opaque
82691
+ * signature-recovery error (`external-eoa.ts:230-233`) that named neither and read as a
82692
+ * wallet fault. A user with several accounts in one wallet extension hits this by
82693
+ * accident far more often than any attacker does, and "wrong account" is only actionable
82694
+ * if it says WHICH. */
82695
+ accountRefusal(account) {
82696
+ if (!this.boundAccount) return null;
82697
+ if (account.toLowerCase() === this.boundAccount) return null;
82698
+ 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.`;
82699
+ }
82470
82700
  /** accountsChanged / chainChanged: a wallet-state CHANGE mid-request invalidates every
82471
82701
  * pending request — what the human saw approved is no longer what would sign. Wallets
82472
82702
  * also deliver late no-op echoes of these events; an unchanged state invalidates nothing. */
@@ -82476,16 +82706,23 @@ var SignatureBridge = class {
82476
82706
  const account = String(body["account"] ?? "");
82477
82707
  const chainId = Number(body["chainId"]);
82478
82708
  const prev = session.wallet;
82479
- session.wallet = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
82480
- if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
82481
- this.wallet = session.wallet;
82709
+ const offered = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
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
+ }
82482
82719
  }
82483
82720
  const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
82484
82721
  if (unchanged) {
82485
82722
  this.ok(res);
82486
82723
  return;
82487
82724
  }
82488
- 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";
82725
+ 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";
82489
82726
  for (const entry of this.pending.values()) {
82490
82727
  if (!entry.settled && !entry.collect) this.settle(entry, { status: "invalidated", reason });
82491
82728
  }
@@ -82575,7 +82812,7 @@ var SignatureBridge = class {
82575
82812
  const data = `data: ${JSON.stringify(request)}
82576
82813
 
82577
82814
  `;
82578
- 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);
82579
82816
  }
82580
82817
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
82581
82818
  pushProgress(payload) {
@@ -82583,7 +82820,48 @@ var SignatureBridge = class {
82583
82820
  data: ${JSON.stringify(payload)}
82584
82821
 
82585
82822
  `;
82586
- 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();
82587
82865
  }
82588
82866
  sessionOf(candidate, res) {
82589
82867
  const session = typeof candidate === "string" ? this.sessions.get(candidate) ?? null : null;
@@ -82591,6 +82869,10 @@ data: ${JSON.stringify(payload)}
82591
82869
  this.deny(res, 403, "missing or wrong session");
82592
82870
  return null;
82593
82871
  }
82872
+ if (session.refused) {
82873
+ this.deny(res, 403, session.refused);
82874
+ return null;
82875
+ }
82594
82876
  return session;
82595
82877
  }
82596
82878
  checkSession(candidate, res) {
@@ -82795,6 +83077,11 @@ async function createRealBoundary(config, wallet, overrides) {
82795
83077
  // tenant — one bridge per tenant world, so the bridge cap IS the tenant cap. The
82796
83078
  // loopback tier keeps its unbounded pending (multi-owner Safe pages need it).
82797
83079
  ...overrides?.bridgeMount ? { mount: overrides.bridgeMount(config.network), maxPending: 1 } : {},
83080
+ // C-47: the authenticated identity governs the write path. Passed separately from
83081
+ // `bridgeMount` although the hosted tier sets both — they answer different questions
83082
+ // ("where does the page live" vs "whose wallet may sign"), and fusing them would make
83083
+ // an unbound hosted bridge impossible to express in a test.
83084
+ ...overrides?.boundBorrower ? { boundAccount: overrides.boundBorrower } : {},
82798
83085
  // M12-12: no unlock closures without a provider — the unlock endpoints answer with
82799
83086
  // their loud not-wired refusal instead of ever touching key material.
82800
83087
  ...keystore ? {
@@ -83071,6 +83358,32 @@ function offers(d, mode) {
83071
83358
  function signerModeSourceClause(d) {
83072
83359
  return offers(d, "keystore") ? "the set `signer_setup` offers. `boundary://info` reports the NARROWER set the active adapter actually constructs under `capabilities.writes.signerModes` (the real adapter builds `external` + `keystore`; the practice ceremonies are mock-adapter only) \u2014 when the two differ, `boundary://info` is authoritative" : "the same set `signer_setup` offers and `boundary://info` reports under `capabilities.writes.signerModes`";
83073
83360
  }
83361
+ function phoneWalletOffer(d) {
83362
+ return d.walletConnect ? "or scan the WalletConnect QR (or paste the pairing code) to approve on a phone wallet" : "This deployment does NOT offer the WalletConnect phone-wallet leg \u2014 there is no QR to scan and `/wc-pairing` answers 404; a browser-extension wallet is the only path here";
83363
+ }
83364
+ function moneyTruth(d) {
83365
+ const practice = offers(d, "mock-simulated");
83366
+ const sepolia = d.networks.includes("sepolia");
83367
+ const mainnet = d.networks.includes("mainnet");
83368
+ const cases = [];
83369
+ if (practice) cases.push("- Adapter `mock` \u2014 a PRACTICE sandbox. No real money anywhere.");
83370
+ if (sepolia) {
83371
+ cases.push(
83372
+ "- Adapter `real` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on\n the test network: real ceremonies and signatures, PRACTICE money (test funds)."
83373
+ );
83374
+ }
83375
+ if (mainnet) cases.push("- Adapter `real` on MAINNET \u2014 REAL MONEY.");
83376
+ const gate = "Writes are enabled on every build; what stops one is having no signing identity connected\nyet \u2014 `signer_setup` is how that is fixed, and every fund movement still needs the user's\nown wallet signature AND `confirmed: true`.";
83377
+ if (cases.length === 1) {
83378
+ const only = mainnet && !sepolia && !practice ? "This deployment serves MAINNET ONLY \u2014 every fund-moving operation here spends REAL MONEY,\nand there is no practice network on it to fall back to." : `This deployment serves exactly one world:
83379
+ ${cases[0]}`;
83380
+ return `${only}
83381
+ ${gate}`;
83382
+ }
83383
+ return `The money truth on this deployment has ${cases.length === 2 ? "TWO" : "THREE"} cases:
83384
+ ${cases.join("\n")}
83385
+ ${gate}`;
83386
+ }
83074
83387
  var LOCAL_GUIDE_DEPLOYMENT = {
83075
83388
  tier: "local",
83076
83389
  networks: ["sepolia", "mainnet"],
@@ -83078,7 +83391,13 @@ var LOCAL_GUIDE_DEPLOYMENT = {
83078
83391
  // external+keystore and the mock sandbox adds the practice ceremonies, so the guide may
83079
83392
  // speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
83080
83393
  // on the real adapter these modes refuse") carry the narrower adapter axis.
83081
- signerModes: GUIDE_SIGNER_MODES
83394
+ signerModes: GUIDE_SIGNER_MODES,
83395
+ // FALSE, because `DH_WC_PROJECT_ID` is unset in a default install and the WalletConnect
83396
+ // leg genuinely is not there until an operator configures it. The first draft of this line
83397
+ // said `true` "to keep the walkthrough complete", which is exactly the overclaim C-44 is
83398
+ // about — the default rendering would have promised a QR that most installs cannot show.
83399
+ // A live boot derives this from env either way (network-switch.ts).
83400
+ walletConnect: false
83082
83401
  };
83083
83402
  function servedNetworks(d) {
83084
83403
  if (d.networks.length === 0) throw new Error("guide: a deployment must serve at least one network");
@@ -83250,7 +83569,7 @@ function keystoreAbsenceBullet() {
83250
83569
  never ask for a password.`;
83251
83570
  }
83252
83571
  var GUIDE_TOPIC_SOURCES = {
83253
- "getting-started": `# Diamond Hands \u2014 what this is
83572
+ "getting-started": (d) => `# Diamond Hands \u2014 what this is
83254
83573
 
83255
83574
  Diamond Hands lets you BORROW a dollar-pegged token (UCD) against your own BITCOIN,
83256
83575
  without selling it. Your BTC sits in a custody vault tied to your position; you mint UCD
@@ -83258,14 +83577,9 @@ against it, pay it back whenever you like, and take your BTC out again.
83258
83577
 
83259
83578
  **Agent instructions:** answer in the USER'S language, map their words via the \`glossary\`
83260
83579
  topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
83261
- \`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
83262
- are enabled (and the true reason when not), and which signer modes this build offers;
83263
- never promise a capability it does not list. The money truth has THREE cases:
83264
- - Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
83265
- - Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
83266
- the test network: real ceremonies and signatures, PRACTICE money (test funds).
83267
- - Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
83268
- explicitly arms them; the capabilities block states which applies.
83580
+ \`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, which signer
83581
+ modes this build offers, and which mode is active; never promise a capability it does not
83582
+ list. ${moneyTruth(d)}
83269
83583
  SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
83270
83584
 
83271
83585
  A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
@@ -83290,8 +83604,8 @@ signer modes exist; current terms (\`protocol_terms\`).
83290
83604
  **2. Choose HOW to authorize operations** (the user's choice, made by talking):
83291
83605
  - **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
83292
83606
  on the real adapter and the mock. The approval page auto-opens in the browser (its URL
83293
- is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
83294
- / pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
83607
+ is ALSO in the tool result); the user connects MetaMask \u2014 ${phoneWalletOffer(d)} \u2014 and
83608
+ then APPROVES EACH OPERATION in
83295
83609
  their own wallet. The first verified signature binds their wallet address as the
83296
83610
  borrower. Full walkthrough: \`guide connect-wallet\`.
83297
83611
  ${offers(d, "keystore") ? `- **"Sign automatically / no popups"** \u2192 mode \`keystore\`. A local encrypted keystore
@@ -83322,14 +83636,13 @@ The user can switch authorization modes at ANY time by saying so \u2014 repeat s
83322
83636
  "connect-wallet": (d) => `# Connect your wallet \u2014 the external-signer walkthrough
83323
83637
 
83324
83638
  External mode means the user approves every operation in their OWN wallet \u2014 a browser
83325
- extension (MetaMask) or a WalletConnect mobile wallet. It works on the real adapter and
83326
- the mock.
83639
+ extension (MetaMask)${d.walletConnect ? " or a WalletConnect mobile wallet" : ""}. It works
83640
+ on the real adapter and the mock.
83327
83641
 
83328
83642
  **The walkthrough:**
83329
83643
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
83330
83644
  desktop browser; ${approvalPageLocation(d)}
83331
- 2. On the page: connect the browser extension, or \u2014 for a mobile wallet \u2014 scan the
83332
- WalletConnect QR code or paste the pairing code.
83645
+ 2. On the page: connect the browser extension${d.walletConnect ? ", or \u2014 for a mobile wallet \u2014 scan the\n WalletConnect QR code or paste the pairing code." : ". " + phoneWalletOffer(d) + "."}
83333
83646
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
83334
83647
  login ceremony explicitly (one typed-data signature in the wallet).
83335
83648
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -83374,7 +83687,11 @@ the mock.
83374
83687
  attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
83375
83688
  back. Warn the user: a second or third identical card is the retry, NOT a duplicate
83376
83689
  charge and NOT an attack \u2014 but they should still read it, and each attempt is a new
83377
- 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.
83378
83695
  - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
83379
83696
  (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
83380
83697
  hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
@@ -83410,6 +83727,21 @@ Connections / Connected sites).`,
83410
83727
  6. **Withdraw BTC** \u2014 \`loan_withdraw {positionId, btcAddress, amountSats, confirmed:true}\`.
83411
83728
  BTC sends are IRREVERSIBLE \u2014 read the address back to the user before confirming.
83412
83729
  amountSats is gross (fee comes out of it) and may be the whole available balance.
83730
+ The SECOND wallet popup is on a clock of well under a minute; if the user misses it the
83731
+ withdrawal fails with the reservation already committed and their coins still in the
83732
+ vault. That does NOT clear itself and it is not a stale spend \u2014 \`loan_recover_stale_spend\`
83733
+ needs the coins to have MOVED, which is exactly what did not happen. The way out is
83734
+ \`loan_withdraw_retry {positionId, confirmed:true}\`, which re-runs that second step with a
83735
+ fresh stamp using the destination and amount the CHAIN already holds. Check
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.
83413
83745
  7. **Watch it** \u2014 \`position_status\` (one), \`position_list\` (all),
83414
83746
  \`position_events\` (history), \`btc_price\`, \`protocol_status\`.
83415
83747
 
@@ -83672,8 +84004,7 @@ ${connectorStatusTruth(d)}
83672
84004
  **What it is:** instead of installing anything, the user adds Diamond Hands to
83673
84005
  claude.ai as a connector (paste a URL \u2014 zero install, zero Node, zero config files).
83674
84006
  Sign-in IS the wallet: one Sign-In-with-Ethereum signature proves address ownership \u2014
83675
- no password, no email, no account beyond the wallet address. The sign-in page offers a
83676
- WalletConnect QR too, so a phone wallet works without any browser extension.
84007
+ no password, no email, no account beyond the wallet address.${d.walletConnect ? " The sign-in\npage offers a WalletConnect QR too, so a phone wallet works without any browser extension." : "\n" + phoneWalletOffer(d) + "."}
83677
84008
 
83678
84009
  **Signature cadence, plainly:** the FIRST connect costs one SIWE signature (sign-in)
83679
84010
  plus one lit-ops login signature (read access). After that, every operation that moves
@@ -83694,17 +84025,19 @@ honestly when asked "is this safe"):
83694
84025
  is never written to disk. A breach here is privacy-class, never money-class.
83695
84026
  3. **What the assistant narrates.** Tool results shape what the assistant tells you \u2014
83696
84027
  a security concern is filed and audited for exactly this channel.
83697
- 4. **Tenant separation \u2014 and the one binding it does NOT make.** Each signed-in wallet
83698
- gets its own world: its own boundary, its own signer state, its own approval-page
83699
- mount, keyed by that address. What is NOT bound is the mount to that address \u2014 the
83700
- world's borrower is whichever wallet CONNECTS at the mount, so a leaked mount link
83701
- plus an earlier connection would make a different wallet this session's signer. That
83702
- is signing-class, not merely privacy-class; do not tell a user it cannot be. What
83703
- contains it: the mount id is freshly random per world and travels only in the user's
83704
- own tool result (treat the link as a secret), and EVERY fund movement verifies the
83705
- signature against that bound borrower \u2014 no key material exists server-side, so
83706
- whoever reaches the page still cannot sign for anyone else. The gap is filed and
83707
- audited; state it this way rather than claiming a binding that isn't there.
84028
+ 4. **Tenant separation, and what the mount binding does and does not cover.** Each
84029
+ signed-in wallet gets its own world: its own boundary, its own signer state, its own
84030
+ approval-page mount, keyed by that address. The wallet that connects at the mount
84031
+ must BE that address \u2014 a wallet offering any other account is refused at connect
84032
+ time, and switching accounts afterwards is refused the same way rather than silently
84033
+ becoming the new signer. So the account that signs is the account that signed in.
84034
+ None of that makes the mount link safe to pass around: whoever holds it can still
84035
+ load the page and observe or disrupt a pending ceremony, so treat the link as a
84036
+ secret \u2014 it is freshly random per world and travels only in the user's own tool
84037
+ result. What the binding does mean is that a holder cannot become this session's
84038
+ signer. Alongside that,
84039
+ EVERY fund movement still verifies the signature against the bound borrower, and no
84040
+ key material exists server-side.
83708
84041
  5. **Availability and deploy honesty.** Hosted code changes under you: deploys are
83709
84042
  version-pinned, the page bundle is open-source, and \`boundary://info\` capabilities
83710
84043
  reports the exact server version.
@@ -83891,11 +84224,17 @@ function createNetworkSwitchRuntime(opts) {
83891
84224
  }
83892
84225
  };
83893
84226
  }
83894
- function guideDeployment(overrides) {
84227
+ function guideDeployment(overrides, env) {
83895
84228
  return {
83896
84229
  tier: overrides?.bridgeMount ? "hosted" : "local",
83897
84230
  networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
83898
- signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes
84231
+ signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes,
84232
+ // C-44 F8, the fourth derivation. Read from the SAME env var the bridge reads
84233
+ // (boundary/config.ts `DH_WC_PROJECT_ID` → BridgeOptions.wc), so the guide cannot promise
84234
+ // a phone-wallet QR that `/wc-pairing` would answer 404 for. Deriving it rather than
84235
+ // hard-coding a tier default is what keeps the guide and `/auth.md` from disagreeing
84236
+ // about the same server, which is exactly what they did before this line existed.
84237
+ walletConnect: Boolean(env?.["DH_WC_PROJECT_ID"])
83899
84238
  };
83900
84239
  }
83901
84240
  function assembleWorld(opts) {
@@ -83905,7 +84244,7 @@ function assembleWorld(opts) {
83905
84244
  ...boot.mockControl ? { mockControl: boot.mockControl } : {},
83906
84245
  ...boot.signer ? { signer: boot.signer } : {},
83907
84246
  ...opts.overrides?.externalOnly ? { externalOnly: true } : {},
83908
- deployment: guideDeployment(opts.overrides),
84247
+ deployment: guideDeployment(opts.overrides, opts.env),
83909
84248
  ...opts.configResult.ok && opts.configResult.config.adapter === "mock" && opts.configResult.config.chainId ? { chainId: opts.configResult.config.chainId } : {}
83910
84249
  };
83911
84250
  if ((opts.env["DH_ADAPTER"] ?? "real") !== "mock") {
@@ -84217,6 +84556,32 @@ function registerLoanTools(server, getB, adapter2 = "real") {
84217
84556
  return renderEnvelope(await b.boundary.withdrawBtc({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats }));
84218
84557
  })
84219
84558
  );
84559
+ registerBoundaryTool(
84560
+ server,
84561
+ "loan_withdraw_retry",
84562
+ {
84563
+ title: "Re-run a stalled BTC withdrawal's execute step",
84564
+ description: `Finish a withdrawal that authorized but never broadcast. loan_withdraw has two steps: the first commits the reservation on-chain, the second signs a time-stamped hash whose window is under a minute \u2014 often nearer twenty seconds. If that second signature is not given in time the withdrawal fails with the reservation ALREADY committed and the coins still in the vault, and it does not clear itself: loan_recover_stale_spend needs the coins to have MOVED, which is exactly what did not happen. This re-runs the second step alone with a fresh stamp. Destination and amount come from the on-chain record, not from you \u2014 the only figure you supply is the network fee, which is taken OUT of the already-authorized amount and cannot increase what leaves the vault. Use position_pending_withdrawals to see what is outstanding first. Sends real BTC. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
84565
+ inputSchema: {
84566
+ positionId: positionIdSchema,
84567
+ networkFeeSats: import_zod.z.number().int().positive().default(1e3).describe("BTC network fee in sats (declared default 1000); taken FROM the authorized amount, not added on top"),
84568
+ confirmed: confirmedSchema
84569
+ },
84570
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
84571
+ },
84572
+ async ({ positionId, networkFeeSats, confirmed }) => guardedWrite(getB, async () => {
84573
+ const gate = requireConfirmation(
84574
+ confirmed,
84575
+ `re-run the execute step for every outstanding BTC withdrawal reservation on position ${positionId} (this BROADCASTS real BTC to the destination each reservation already authorizes)`
84576
+ );
84577
+ if (gate) return gate;
84578
+ const problem = checkPositionIdHex(positionId) ?? checkSatsAmount(networkFeeSats, "Network fee");
84579
+ if (problem) return validationFailed(problem);
84580
+ const b = getB();
84581
+ if (!b.ok) return renderError(b.error);
84582
+ return renderEnvelope(await b.boundary.retryWithdrawExecute({ positionId, networkFeeSats }));
84583
+ })
84584
+ );
84220
84585
  registerBoundaryTool(
84221
84586
  server,
84222
84587
  "loan_allowlist_destination",
@@ -84242,7 +84607,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
84242
84607
  "loan_delegation_setup",
84243
84608
  {
84244
84609
  title: "Install delegation on the Safe (one owner ceremony)",
84245
- description: `The ONE-TIME Safe delegation batch (signer mode 'safe-module'): your owners sign a single durable Safe transaction \u2014 at their leisure, no time window \u2014 that enables the Safe's AgentModule, binds the agent key, registers it in the delegation registry, and pre-approves the given BTC withdrawal destinations. After it, day-to-day operations (create/mint/pay/extend) run agent-solo; withdrawals always still need the owners' short signing burst, and only to destinations approved here (or later via loan_allowlist_destination \u2014 also owners-only). A revoked agent address burns FOREVER (AR-1) \u2014 rotation means a fresh key. Requires human confirmation (confirmed: true).`,
84610
+ description: `NOT AVAILABLE on the real protocol in this build \u2014 the real adapter answers UPSTREAM_UNAVAILABLE ('not wired in this delivery'). It runs on the practice (mock) adapter only. Say so before a user plans around it. The ONE-TIME Safe delegation batch (signer mode 'safe-module'): your owners sign a single durable Safe transaction \u2014 at their leisure, no time window \u2014 that enables the Safe's AgentModule, binds the agent key, registers it in the delegation registry, and pre-approves the given BTC withdrawal destinations. After it, day-to-day operations (create/mint/pay/extend) run agent-solo; withdrawals always still need the owners' short signing burst, and only to destinations approved here (or later via loan_allowlist_destination \u2014 also owners-only). A revoked agent address burns FOREVER (AR-1) \u2014 rotation means a fresh key. Requires human confirmation (confirmed: true).`,
84246
84611
  inputSchema: {
84247
84612
  btcAddresses: import_zod.z.array(import_zod.z.string().min(1)).describe("BTC withdrawal destinations to pre-approve in the same ceremony (avoids a second owner gathering before the first withdrawal)"),
84248
84613
  confirmed: confirmedSchema
@@ -84262,7 +84627,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
84262
84627
  "loan_delegation_grant",
84263
84628
  {
84264
84629
  title: "Grant the agent per-position scopes (owners sign)",
84265
- description: `Set what the delegated agent may do on ONE position \u2014 RENEW (extend), REPAY (pay down), MINT (borrow, only while the post-mint collateral ratio stays at or above mintFloorBps \u2014 required for MINT, it is the owners' risk bound). Grants are user-only expansion: for a Safe this is a QUORUM signature (durable Safe transaction, owners sign at leisure) \u2014 the agent can never widen its own powers. Omitting a scope leaves it un-granted; a grant with no scopes clears the position's grant. Requires human confirmation (confirmed: true).`,
84630
+ description: `NOT AVAILABLE on the real protocol in this build \u2014 the real adapter answers UPSTREAM_UNAVAILABLE ('not wired in this delivery'). It runs on the practice (mock) adapter only. Say so before a user plans around it. Set what the delegated agent may do on ONE position \u2014 RENEW (extend), REPAY (pay down), MINT (borrow, only while the post-mint collateral ratio stays at or above mintFloorBps \u2014 required for MINT, it is the owners' risk bound). Grants are user-only expansion: for a Safe this is a QUORUM signature (durable Safe transaction, owners sign at leisure) \u2014 the agent can never widen its own powers. Omitting a scope leaves it un-granted; a grant with no scopes clears the position's grant. Requires human confirmation (confirmed: true).`,
84266
84631
  inputSchema: {
84267
84632
  positionId: positionIdSchema,
84268
84633
  renew: import_zod.z.boolean().optional().describe("Allow the agent to extend/renew this position"),
@@ -84292,7 +84657,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
84292
84657
  "loan_recover_stale_spend",
84293
84658
  {
84294
84659
  title: "Recover a stale BTC reservation via LIT-attested proof",
84295
- description: "Clear a stale authorized BTC spend on BTCSpendAuthorizer using a LIT-attested StaleSpendRecovery attestation. The original UTXO must already be consumed on Bitcoin with \u22656 confirmations. `invalidatorTxid` is either the borrower's authorized broadcast (after confirmations) or a PKP self-spend that invalidated the reservation. Permissionless on-chain.",
84660
+ description: "NOT AVAILABLE on the real protocol in this build \u2014 the real adapter answers UPSTREAM_UNAVAILABLE ('not wired in this delivery'); it runs on the practice (mock) adapter only. For a withdrawal that authorized but never broadcast, loan_withdraw_retry is the working path. Clear a stale authorized BTC spend on BTCSpendAuthorizer using a LIT-attested StaleSpendRecovery attestation. The original UTXO must already be consumed on Bitcoin with \u22656 confirmations. `invalidatorTxid` is either the borrower's authorized broadcast (after confirmations) or a PKP self-spend that invalidated the reservation. Permissionless on-chain.",
84296
84661
  inputSchema: {
84297
84662
  positionId: positionIdSchema,
84298
84663
  utxoTxid: import_zod.z.string().describe("The original authorized UTXO's txid"),
@@ -85291,6 +85656,12 @@ function composeConnector(opts, rawPublicOrigin) {
85291
85656
  const overrides = {
85292
85657
  externalOnly: true,
85293
85658
  allowedNetworks,
85659
+ // C-47: `tenantKey` IS the lowercased SIWE address (see the `authImpl.tenant` call
85660
+ // site). Until this line it was a map key and an error string and nothing else, so a
85661
+ // session authenticated as A could write as B by connecting B to the approval page.
85662
+ // The mount is a bearer capability that transits the LLM transcript by design
85663
+ // (C-45), which is what made that reachable rather than merely untidy.
85664
+ boundBorrower: tenantKey,
85294
85665
  bridgeMount: () => ({ baseUrl: `${publicOrigin}/approval/${mountId}`, origin: publicOrigin }),
85295
85666
  signerPersistence: (network) => {
85296
85667
  let s = stores.get(network);