@gvnrdao/dh-mcp 0.5.12 → 0.5.13

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,19 @@ 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({ attempted: r.value.attempted, transfers: r.value.transfers }, r.source);
41383
+ }
41371
41384
  // ---- meta ----
41372
41385
  world() {
41373
41386
  return {
@@ -42191,6 +42204,42 @@ var World = class {
42191
42204
  c.authorizedSpends.splice(idx, 1);
42192
42205
  return { ok: true, value: { releasedSats: spend.satoshis } };
42193
42206
  }
42207
+ /**
42208
+ * C-46: re-run the withdrawal EXECUTE leg for reservations whose coins have not been
42209
+ * observed moving (`consumed === null`). This is the stranded shape: phase 1 committed
42210
+ * the reservation, phase 2's quantum-stamped signature expired, and the outpoint was
42211
+ * never spent.
42212
+ *
42213
+ * The retry BROADCASTS; it does not observe. `consumed` therefore stays null — that flag
42214
+ * means "seen consumed on Bitcoin", and only MockControl.confirmSpendConsumed (standing
42215
+ * in for the chain) may set it. Conflating the two would let a retry release collateral
42216
+ * against a transaction no one has confirmed, which is the mistake the whole
42217
+ * proof-of-consumption design exists to prevent. So a retry leaves the reservation
42218
+ * holding its balance exactly as before; what it produces is the txid that can LATER
42219
+ * become the invalidator — the proof the stranded state could never generate for itself.
42220
+ */
42221
+ retryWithdrawExecute(p) {
42222
+ const paused = this.pausedReason();
42223
+ if (paused) return { ok: false, reason: paused };
42224
+ const pos = this.state.positions[p.positionId];
42225
+ if (!pos) return { ok: false, reason: `position ${p.positionId} does not exist` };
42226
+ if (pos.borrower.toLowerCase() !== p.borrower.toLowerCase()) {
42227
+ return { ok: false, reason: `caller ${p.borrower} is not the borrower of this position` };
42228
+ }
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 { hash: txid } = this.nextId("btc-withdraw-retry");
42233
+ return {
42234
+ utxoIdentifier: `${spend.txid}:${spend.vout}`,
42235
+ ok: true,
42236
+ txid,
42237
+ amountSentSats: spend.satoshis,
42238
+ destination: spend.targetAddress
42239
+ };
42240
+ });
42241
+ return { ok: true, value: { attempted: transfers.length, transfers } };
42242
+ }
42194
42243
  // ---- Mock Safes (plan 06): REAL verification semantics, no fakes (M6-21/27) ----
42195
42244
  safesMap() {
42196
42245
  return this.state.safes;
@@ -43376,6 +43425,11 @@ var MockUpstreamPlugin = class {
43376
43425
  const r = this.world.recoverStaleSpend(p);
43377
43426
  if (!r.ok) return this.rejected("recoverStaleSpend", r.reason);
43378
43427
  return upOk({ txRef: this.world.nextTxRef(), releasedSats: r.value.releasedSats }, this.src("mock-ops"));
43428
+ }),
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"));
43379
43433
  })
43380
43434
  };
43381
43435
  }
@@ -51615,13 +51669,13 @@ var init_deployment_addresses = __esm2({
51615
51669
  block: 25472956
51616
51670
  },
51617
51671
  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
51672
+ previousImplementation: "0x40c9e8C46C65E0A57BB63da5368868A9E8Df81A5",
51673
+ newImplementation: "0x00D7a47798E8ff169104b748131703B78f23390C",
51674
+ upgradedAt: "2026-09-09T12:05:35.000Z",
51675
+ 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)",
51676
+ 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",
51677
+ executeTx: "0x77cd231966c546177bd8f1a07bd4e705afd5c2dfbd110b096836401679c0c69c",
51678
+ block: 25939703
51625
51679
  },
51626
51680
  PositionManager: {
51627
51681
  previousImplementation: "0x600Dc0D1C2c0F94882B6Bc09172f8650047Ad5B1",
@@ -51724,7 +51778,7 @@ var init_deployment_addresses = __esm2({
51724
51778
  ADMIN_MODULE: "0x0023B71B586795eE5fa4E83E384345C1EC8Bb946",
51725
51779
  ADMIN_MODULE_IMPL: "0xb4C5C7E051A1e672F014B25CB5D55B225Aa0D512",
51726
51780
  BTC_SPEND_AUTHORIZER: "0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",
51727
- BTC_SPEND_AUTHORIZER_IMPL: "0x40c9e8C46C65E0A57BB63da5368868A9E8Df81A5",
51781
+ BTC_SPEND_AUTHORIZER_IMPL: "0x00D7a47798E8ff169104b748131703B78f23390C",
51728
51782
  POSITION_MANAGER_VIEWS: "0x8B57954eA338c6A6bfF1457f71080e25baFF3937",
51729
51783
  POSITION_MANAGER_VIEWS_IMPL: "0xE68DC096A65Ecddbc6A9b5c6e5f878e2CE143Bfe",
51730
51784
  POSITION_MANAGER: "0x12A1836e56139ccaD8722B89519d84233efc224B",
@@ -57794,9 +57848,27 @@ var LOGIN_TYPES_WITH_AUDIENCE2 = {
57794
57848
  { name: "audience", type: "string" }
57795
57849
  ]
57796
57850
  };
57797
- async function buildSignedLoginPayload(signer, chainId, audience, reuse) {
57851
+ var LOGIN_TYPES_WITH_STATEMENT = {
57852
+ DiamondHands: [
57853
+ { name: "statement", type: "string" },
57854
+ { name: "address", type: "address" },
57855
+ { name: "issuedAt", type: "uint256" },
57856
+ { name: "nonce", type: "bytes32" },
57857
+ { name: "audience", type: "string" }
57858
+ ]
57859
+ };
57860
+ 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.";
57861
+ function canonicalLoginStatement(audience) {
57862
+ const host = /^https?:\/\/([^/?#]+)/i.exec(audience)?.[1];
57863
+ if (!host)
57864
+ return null;
57865
+ return LOGIN_STATEMENT_TEMPLATE.replace("{host}", host);
57866
+ }
57867
+ async function buildSignedLoginPayload(signer, chainId, audience, reuse, withStatement = false) {
57798
57868
  const address = await signer.getAddress();
57869
+ const statement = withStatement && audience ? canonicalLoginStatement(audience) : null;
57799
57870
  const message = {
57871
+ ...statement ? { statement } : {},
57800
57872
  address,
57801
57873
  issuedAt: reuse?.issuedAt ?? Math.floor(Date.now() / 1e3),
57802
57874
  nonce: reuse?.nonce ?? (0, import_ethers17.hexlify)((0, import_ethers17.randomBytes)(32)),
@@ -57804,7 +57876,7 @@ async function buildSignedLoginPayload(signer, chainId, audience, reuse) {
57804
57876
  };
57805
57877
  const signature = await signer.signTypedData(
57806
57878
  buildLoginDomain(chainId),
57807
- audience ? LOGIN_TYPES_WITH_AUDIENCE2 : LOGIN_TYPES2,
57879
+ statement ? LOGIN_TYPES_WITH_STATEMENT : audience ? LOGIN_TYPES_WITH_AUDIENCE2 : LOGIN_TYPES2,
57808
57880
  message
57809
57881
  );
57810
57882
  return { chainId, message, signature };
@@ -57973,6 +58045,8 @@ var ServerSession = class {
57973
58045
  signer;
57974
58046
  serviceEndpoint;
57975
58047
  loginAudience;
58048
+ /** Whether this session's login carries the human-readable statement. */
58049
+ withStatement;
57976
58050
  chainId;
57977
58051
  store;
57978
58052
  onSignaturePrompt;
@@ -58014,6 +58088,13 @@ var ServerSession = class {
58014
58088
  /\/+$/,
58015
58089
  ""
58016
58090
  );
58091
+ const explicitAudience = typeof opts.loginAudience === "string" && opts.loginAudience.length > 0;
58092
+ this.withStatement = opts.withStatement === true && explicitAudience;
58093
+ if (opts.withStatement === true && !explicitAudience) {
58094
+ console.warn(
58095
+ "[dh-sdk] withStatement ignored: it requires an explicit loginAudience, since the servers rebuild the expected sentence from the audience host"
58096
+ );
58097
+ }
58017
58098
  this.chainId = opts.chainId;
58018
58099
  this.store = opts.persistSession === false ? null : opts.sessionStore ?? createDefaultSessionStore();
58019
58100
  this.onSignaturePrompt = opts.onSignaturePrompt;
@@ -58267,12 +58348,16 @@ var ServerSession = class {
58267
58348
  this.signer,
58268
58349
  this.chainId,
58269
58350
  this.loginAudience,
58270
- reuse
58351
+ reuse,
58352
+ reuse ? reuse.withStatement === true : this.withStatement
58271
58353
  );
58272
58354
  if (storeKey && !reuse) {
58273
58355
  store.savePending?.(storeKey, {
58274
58356
  issuedAt: payload.message.issuedAt,
58275
- nonce: payload.message.nonce
58357
+ nonce: payload.message.nonce,
58358
+ // Recorded so a resume reproduces this digest even if the
58359
+ // capability flag changes before the owners finish signing.
58360
+ withStatement: this.withStatement
58276
58361
  });
58277
58362
  }
58278
58363
  session = await this.login(payload);
@@ -70483,6 +70568,9 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
70483
70568
  signer: config.authSigner ?? config.contractSigner,
70484
70569
  serviceEndpoint: config.serviceEndpoint,
70485
70570
  loginAudience: config.loginAudience,
70571
+ // Only meaningful alongside an audience; the servers derive the expected
70572
+ // sentence from its host. Defaults off so Node callers are untouched.
70573
+ withStatement: config.loginStatement === true,
70486
70574
  chainId: config.chainId,
70487
70575
  persistSession: config.sessionPersistence?.enabled,
70488
70576
  sessionStore: config.sessionPersistence?.store,
@@ -79328,7 +79416,33 @@ function buildWriteOps(deps) {
79328
79416
  kind: "unavailable",
79329
79417
  source: SOURCE5,
79330
79418
  message: "recoverStaleSpend is not wired in this delivery (permissionless recovery \u2014 planned follow-up)."
79331
- })
79419
+ }),
79420
+ retryWithdrawExecute: async (p) => {
79421
+ const sdk = deps.getWriteSdk();
79422
+ if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
79423
+ let rows;
79424
+ try {
79425
+ rows = await sdk.executePendingBtcTransfers(p.positionId, p.networkFeeSats);
79426
+ } catch (e) {
79427
+ return failed("retryWithdrawExecute", e);
79428
+ }
79429
+ const gate = rows.find((r) => !r.success && !r.utxoIdentifier);
79430
+ if (gate) return declined("retryWithdrawExecute", gate.error ?? "pending-transfer execution refused before any reservation was attempted");
79431
+ return upOk(
79432
+ {
79433
+ attempted: rows.length,
79434
+ transfers: rows.map((r) => ({
79435
+ utxoIdentifier: r.utxoIdentifier ?? "",
79436
+ ok: r.success,
79437
+ ...r.txid ? { txid: r.txid } : {},
79438
+ ...r.amountSent !== void 0 ? { amountSentSats: String(r.amountSent) } : {},
79439
+ ...r.destination ? { destination: r.destination } : {},
79440
+ ...r.error ? { error: r.error } : {}
79441
+ }))
79442
+ },
79443
+ { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
79444
+ );
79445
+ }
79332
79446
  };
79333
79447
  }
79334
79448
 
@@ -79853,7 +79967,8 @@ var RealUpstreamPlugin = class {
79853
79967
  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
79968
  })
79855
79969
  ),
79856
- recoverStaleSpend: () => readOnly("recoverStaleSpend")
79970
+ recoverStaleSpend: () => readOnly("recoverStaleSpend"),
79971
+ retryWithdrawExecute: () => readOnly("retryWithdrawExecute")
79857
79972
  };
79858
79973
  }
79859
79974
  }
@@ -80021,7 +80136,8 @@ var RealUpstreamPlugin = class {
80021
80136
  psmSwap: call("psmSwap"),
80022
80137
  delegationSetup: call("delegationSetup"),
80023
80138
  delegationGrant: call("delegationGrant"),
80024
- recoverStaleSpend: call("recoverStaleSpend")
80139
+ recoverStaleSpend: call("recoverStaleSpend"),
80140
+ retryWithdrawExecute: call("retryWithdrawExecute")
80025
80141
  };
80026
80142
  }
80027
80143
  async resolveOpsGateway() {
@@ -80860,6 +80976,9 @@ function wcDeclineOrFault(e) {
80860
80976
  }
80861
80977
  var SignatureBridge = class {
80862
80978
  clock;
80979
+ /** Lowercased at construction so every comparison is case-flat — EIP-55 checksum casing
80980
+ * differs between what SIWE signs and what a wallet reports for the SAME address. */
80981
+ boundAccount;
80863
80982
  expiryMs;
80864
80983
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
80865
80984
  maxPending;
@@ -80895,6 +81014,7 @@ var SignatureBridge = class {
80895
81014
  unlockSession = null;
80896
81015
  constructor(opts) {
80897
81016
  this.clock = opts?.clock ?? Date.now;
81017
+ this.boundAccount = opts?.boundAccount?.toLowerCase();
80898
81018
  this.expiryMs = opts?.expiryMs ?? DEFAULT_EXPIRY_MS;
80899
81019
  this.maxPending = opts?.maxPending ?? null;
80900
81020
  this.attachGraceMs = opts?.attachGraceMs ?? (opts?.mount ? DEFAULT_HOSTED_ATTACH_GRACE_MS : DEFAULT_ATTACH_GRACE_MS);
@@ -81264,6 +81384,14 @@ var SignatureBridge = class {
81264
81384
  });
81265
81385
  this.wcTransport = await factory2(this.wcConfig);
81266
81386
  this.wcTransport.onSession((info) => {
81387
+ const refusal = info ? this.accountRefusal(info.account) : null;
81388
+ if (info && refusal) {
81389
+ this.wcActive = false;
81390
+ this.wallet = null;
81391
+ process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
81392
+ `);
81393
+ return;
81394
+ }
81267
81395
  this.wcActive = info !== null;
81268
81396
  this.wallet = info ? { account: info.account, chainId: info.chainId } : null;
81269
81397
  if (info === null) {
@@ -81361,10 +81489,36 @@ var SignatureBridge = class {
81361
81489
  this.deny(res, 400, "hello requires account (0x address) and integer chainId");
81362
81490
  return;
81363
81491
  }
81492
+ const refusal = this.accountRefusal(account);
81493
+ if (refusal) {
81494
+ this.deny(res, 403, refusal);
81495
+ return;
81496
+ }
81364
81497
  session.wallet = { account, chainId };
81365
81498
  this.wallet = { account, chainId };
81366
81499
  this.ok(res);
81367
81500
  }
81501
+ /** C-47: the single predicate every wallet account is admitted through. There are THREE
81502
+ * doors into the account this bridge will sign with — `hello`, `accountsChanged`, and the
81503
+ * WalletConnect `onSession` callback — and all three call this. The first version of this
81504
+ * fix guarded only the first two while this docstring already claimed to be "the single
81505
+ * place", which is how the WC door survived a green suite: the claim was in prose, not in a
81506
+ * test. T-EXT-BIND-01/02/04 now pin one door each, so adding a fourth writer of
81507
+ * `this.wallet` without coming through here fails a test rather than a review.
81508
+ *
81509
+ * Returns the refusal reason, or
81510
+ * null when the account may be adopted.
81511
+ *
81512
+ * Both addresses are named because the pre-fix failure surfaced much later as an opaque
81513
+ * signature-recovery error (`external-eoa.ts:230-233`) that named neither and read as a
81514
+ * wallet fault. A user with several accounts in one wallet extension hits this by
81515
+ * accident far more often than any attacker does, and "wrong account" is only actionable
81516
+ * if it says WHICH. */
81517
+ accountRefusal(account) {
81518
+ if (!this.boundAccount) return null;
81519
+ if (account.toLowerCase() === this.boundAccount) return null;
81520
+ 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.`;
81521
+ }
81368
81522
  /** accountsChanged / chainChanged: a wallet-state CHANGE mid-request invalidates every
81369
81523
  * pending request — what the human saw approved is no longer what would sign. Wallets
81370
81524
  * also deliver late no-op echoes of these events; an unchanged state invalidates nothing. */
@@ -81374,7 +81528,9 @@ var SignatureBridge = class {
81374
81528
  const account = String(body["account"] ?? "");
81375
81529
  const chainId = Number(body["chainId"]);
81376
81530
  const prev = session.wallet;
81377
- session.wallet = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
81531
+ 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;
81378
81534
  if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
81379
81535
  this.wallet = session.wallet;
81380
81536
  }
@@ -81383,7 +81539,7 @@ var SignatureBridge = class {
81383
81539
  this.ok(res);
81384
81540
  return;
81385
81541
  }
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";
81542
+ 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
81543
  for (const entry of this.pending.values()) {
81388
81544
  if (!entry.settled && !entry.collect) this.settle(entry, { status: "invalidated", reason });
81389
81545
  }
@@ -81898,6 +82054,11 @@ async function createRealBoundary(config, wallet, overrides) {
81898
82054
  // tenant — one bridge per tenant world, so the bridge cap IS the tenant cap. The
81899
82055
  // loopback tier keeps its unbounded pending (multi-owner Safe pages need it).
81900
82056
  ...overrides?.bridgeMount ? { mount: overrides.bridgeMount(config.network), maxPending: 1 } : {},
82057
+ // C-47: the authenticated identity governs the write path. Passed separately from
82058
+ // `bridgeMount` although the hosted tier sets both — they answer different questions
82059
+ // ("where does the page live" vs "whose wallet may sign"), and fusing them would make
82060
+ // an unbound hosted bridge impossible to express in a test.
82061
+ ...overrides?.boundBorrower ? { boundAccount: overrides.boundBorrower } : {},
81901
82062
  // M12-12: no unlock closures without a provider — the unlock endpoints answer with
81902
82063
  // their loud not-wired refusal instead of ever touching key material.
81903
82064
  ...keystore ? {