@gvnrdao/dh-mcp 0.5.20 → 0.5.22

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
@@ -13422,6 +13422,12 @@ var require_follow_redirects = __commonJS({
13422
13422
  RedirectableRequest.prototype._sanitizeOptions = function(options) {
13423
13423
  if (!options.headers) {
13424
13424
  options.headers = {};
13425
+ } else if (Array.isArray(options.headers)) {
13426
+ var headerList = options.headers;
13427
+ options.headers = {};
13428
+ for (var i = 0; i < headerList.length; i += 2) {
13429
+ options.headers[headerList[i]] = headerList[i + 1];
13430
+ }
13425
13431
  }
13426
13432
  if (!isArray2(options.sensitiveHeaders)) {
13427
13433
  options.sensitiveHeaders = [];
@@ -13696,7 +13702,7 @@ var require_follow_redirects = __commonJS({
13696
13702
  return URL3 && value instanceof URL3;
13697
13703
  }
13698
13704
  function escapeRegex(regex) {
13699
- return regex.replace(/[\]\\/()*+?.$]/g, "\\$&");
13705
+ return regex.replace(/[[\]\\/()*+?.^$|]/g, "\\$&");
13700
13706
  }
13701
13707
  module2.exports = wrap({ http: http4, https: https2 });
13702
13708
  module2.exports.wrap = wrap;
@@ -14688,6 +14694,32 @@ var require_pkg_src = __commonJS({
14688
14694
  deployedAt: 1790246264563,
14689
14695
  size: 69219,
14690
14696
  hash: "bda048d8cd6b5a39c2774bcf1320e82d1eea935c2a521006fb8b887e13b6dd8d"
14697
+ },
14698
+ carryCollateralAttestation: {
14699
+ cid: "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8",
14700
+ authorizedCidHex: cidToHex(
14701
+ "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8"
14702
+ ),
14703
+ name: "Carry Collateral Attestation",
14704
+ description: "LoanCarryVault collateral attestation (borrower, BTC vault, confirmed BTC)",
14705
+ version: "1.0.0",
14706
+ deployed: true,
14707
+ deployedAt: 1790927734070,
14708
+ size: 21156,
14709
+ hash: "05b177e0bb36b0483db4a42d33c1bbbf47eb9ef34ae278459397d51a7f8957ff"
14710
+ },
14711
+ carryFundingAttestation: {
14712
+ cid: "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W",
14713
+ authorizedCidHex: cidToHex(
14714
+ "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W"
14715
+ ),
14716
+ name: "Carry Funding Attestation",
14717
+ description: "LoanCarryVault funding attestation (Hyperliquid BTC windowed hourly average)",
14718
+ version: "1.0.0",
14719
+ deployed: true,
14720
+ deployedAt: 1790925699980,
14721
+ size: 7193,
14722
+ hash: "4944ada61610cf64b32e33b5be62087088dcf5e821040c69e67942e643ce74c9"
14691
14723
  }
14692
14724
  };
14693
14725
  function getDeploymentsForNetwork(network) {
@@ -15431,7 +15463,7 @@ ${errorReport}`);
15431
15463
  }
15432
15464
  init_debug_logger();
15433
15465
  init_session_signature_cache();
15434
- var import_ethers50 = require("ethers");
15466
+ var import_ethers53 = require("ethers");
15435
15467
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
15436
15468
  var GRACE_PERIOD_DAYS = 30;
15437
15469
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -18427,12 +18459,12 @@ ${auth.clientId}`;
18427
18459
  }
18428
18460
  async function executeVaultSnapshot(params) {
18429
18461
  global.ethers = {
18430
- ...import_ethers50.ethers,
18462
+ ...import_ethers53.ethers,
18431
18463
  providers: {
18432
- StaticJsonRpcProvider: import_ethers50.ethers.JsonRpcProvider
18464
+ StaticJsonRpcProvider: import_ethers53.ethers.JsonRpcProvider
18433
18465
  },
18434
- Contract: import_ethers50.ethers.Contract,
18435
- utils: import_ethers50.ethers
18466
+ Contract: import_ethers53.ethers.Contract,
18467
+ utils: import_ethers53.ethers
18436
18468
  // v6 moved utils to top level
18437
18469
  };
18438
18470
  global.Lit = {
@@ -27312,7 +27344,7 @@ var require_lit_ops_module = __commonJS({
27312
27344
  break;
27313
27345
  case 11155111:
27314
27346
  chain = "sepolia";
27315
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27347
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27316
27348
  break;
27317
27349
  case 1337:
27318
27350
  // Hardhat local testnet (actual deployment chainId)
@@ -27501,7 +27533,7 @@ var require_lit_ops_module = __commonJS({
27501
27533
  break;
27502
27534
  case 11155111:
27503
27535
  chain = "sepolia";
27504
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27536
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27505
27537
  break;
27506
27538
  case 1337:
27507
27539
  // Hardhat local testnet (actual deployment chainId)
@@ -27692,7 +27724,7 @@ var require_lit_ops_module = __commonJS({
27692
27724
  break;
27693
27725
  case 11155111:
27694
27726
  chain = "sepolia";
27695
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27727
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27696
27728
  break;
27697
27729
  case 1337:
27698
27730
  case 31337:
@@ -27840,7 +27872,7 @@ var require_lit_ops_module = __commonJS({
27840
27872
  break;
27841
27873
  case 11155111:
27842
27874
  chain = "sepolia";
27843
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27875
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27844
27876
  break;
27845
27877
  case 1337:
27846
27878
  // Hardhat local testnet (actual deployment chainId)
@@ -28060,7 +28092,7 @@ var require_lit_ops_module = __commonJS({
28060
28092
  bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://mempool.space/api";
28061
28093
  break;
28062
28094
  case 11155111:
28063
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
28095
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
28064
28096
  break;
28065
28097
  case 1337:
28066
28098
  // Hardhat local testnet (actual deployment chainId)
@@ -28276,7 +28308,7 @@ var require_lit_ops_module = __commonJS({
28276
28308
  async chipotleCreateWalletAndAddToGroup(accountApiKey) {
28277
28309
  const baseUrl = _LitOps.LIT_CORE_API_BASE;
28278
28310
  const createResp = await fetch(`${baseUrl}/create_wallet`, {
28279
- method: "GET",
28311
+ method: "POST",
28280
28312
  headers: {
28281
28313
  "X-Api-Key": accountApiKey
28282
28314
  }
@@ -40696,6 +40728,7 @@ __export(wc_transport_exports, {
40696
40728
  WC_DAPP_METADATA: () => WC_DAPP_METADATA,
40697
40729
  WC_SESSION_METHODS: () => WC_SESSION_METHODS,
40698
40730
  WcTransport: () => WcTransport,
40731
+ guardRelayFatal: () => guardRelayFatal,
40699
40732
  newIsolatedCore: () => newIsolatedCore,
40700
40733
  wcSessionNamespaces: () => wcSessionNamespaces,
40701
40734
  withEip712DomainType: () => withEip712DomainType
@@ -40729,7 +40762,27 @@ function newIsolatedCore(cfg, label) {
40729
40762
  });
40730
40763
  return { core, scratch };
40731
40764
  }
40732
- var import_core, import_sign_client, os, path3, import_node_fs, WC_SESSION_METHODS, WC_DAPP_METADATA, EVENTS, WcTransport;
40765
+ function guardRelayFatal(core, health, onFatal) {
40766
+ const relayer = core.relayer;
40767
+ const register = relayer.registerProviderListeners;
40768
+ if (typeof register !== "function") {
40769
+ throw new Error(
40770
+ "@walletconnect/core no longer exposes relayer.registerProviderListeners \u2014 the fatal-close guard (D-4) cannot be installed. Re-verify the relay error path for this WalletConnect version before shipping it."
40771
+ );
40772
+ }
40773
+ const record = (e) => {
40774
+ if (health.fatal !== null) return;
40775
+ health.fatal = e.message;
40776
+ console.error(`[dh-mcp] WalletConnect relay failed fatally: ${e.message}`);
40777
+ onFatal(e.message);
40778
+ };
40779
+ relayer.on("relayer_error", record);
40780
+ relayer.registerProviderListeners = () => {
40781
+ register.call(relayer);
40782
+ relayer.provider.on("error", record);
40783
+ };
40784
+ }
40785
+ var import_core, import_sign_client, os, path3, import_node_fs, import_ethers50, WC_SESSION_METHODS, WC_DAPP_METADATA, EVENTS, WcTransport;
40733
40786
  var init_wc_transport = __esm({
40734
40787
  "src/boundary/upstream/shared/external-bridge/wc-transport.ts"() {
40735
40788
  "use strict";
@@ -40738,6 +40791,7 @@ var init_wc_transport = __esm({
40738
40791
  os = __toESM(require("os"));
40739
40792
  path3 = __toESM(require("path"));
40740
40793
  import_node_fs = require("fs");
40794
+ import_ethers50 = require("ethers");
40741
40795
  WC_SESSION_METHODS = ["personal_sign", "eth_signTypedData_v4", "eth_sendTransaction"];
40742
40796
  WC_DAPP_METADATA = {
40743
40797
  name: "Diamond Hands MCP",
@@ -40747,25 +40801,50 @@ var init_wc_transport = __esm({
40747
40801
  };
40748
40802
  EVENTS = ["accountsChanged", "chainChanged"];
40749
40803
  WcTransport = class _WcTransport {
40750
- constructor(client, cfg, scratch) {
40804
+ constructor(client, cfg, scratch, health) {
40751
40805
  this.client = client;
40752
40806
  this.cfg = cfg;
40753
40807
  this.scratch = scratch;
40754
- client.on("session_delete", () => {
40808
+ this.health = health;
40809
+ client.on("session_delete", ({ topic }) => {
40810
+ const pending = this.candidates.get(topic);
40811
+ if (pending) pending.deleted = true;
40812
+ if (this.session === null || this.session.topic !== topic) return;
40755
40813
  this.session = null;
40756
40814
  this.sessionListener?.(null);
40757
40815
  });
40758
40816
  }
40759
40817
  session = null;
40760
40818
  sessionListener = null;
40819
+ /** Sessions announced but not yet adopted (awaiting a deferred verdict), by topic. */
40820
+ candidates = /* @__PURE__ */ new Map();
40761
40821
  static async create(cfg) {
40762
40822
  const { core, scratch } = newIsolatedCore(cfg, "dh-wc-dapp");
40823
+ const health = { fatal: null };
40824
+ let transport = null;
40825
+ guardRelayFatal(core, health, () => transport?.dropForFatal());
40763
40826
  const client = await import_sign_client.default.init({
40764
40827
  core,
40765
40828
  projectId: cfg.projectId,
40766
- metadata: WC_DAPP_METADATA
40829
+ metadata: cfg.metadata ?? WC_DAPP_METADATA
40767
40830
  });
40768
- return new _WcTransport(client, cfg, scratch);
40831
+ transport = new _WcTransport(client, cfg, scratch, health);
40832
+ return transport;
40833
+ }
40834
+ /** The relay is gone for good: no adopted session may outlive it. Listeners hear a
40835
+ * disconnect, exactly as if the wallet had left. */
40836
+ dropForFatal() {
40837
+ if (this.session === null) return;
40838
+ this.session = null;
40839
+ void this.sessionListener?.(null);
40840
+ }
40841
+ /** Refuse to start new work over a relay that has failed fatally — naming why. */
40842
+ assertRelayHealthy() {
40843
+ if (this.health.fatal !== null) {
40844
+ throw new Error(
40845
+ `the WalletConnect relay refused this connector (${this.health.fatal}) \u2014 mobile-wallet signing is unavailable until the relay accepts its project id (DH_WC_PROJECT_ID); use the browser-wallet approval page instead`
40846
+ );
40847
+ }
40769
40848
  }
40770
40849
  /** Wallet-session state changes (connect/disconnect) — the bridge mirrors them. */
40771
40850
  onSession(cb) {
@@ -40776,22 +40855,59 @@ var init_wc_transport = __esm({
40776
40855
  }
40777
40856
  /** Create a pairing URI; resolves the session in the background when a wallet approves. */
40778
40857
  async createPairing() {
40858
+ this.assertRelayHealthy();
40779
40859
  const { uri, approval } = await this.client.connect({
40780
40860
  // sign-client 2.21 deprecates requiredNamespaces (auto-downgraded to optional).
40781
40861
  optionalNamespaces: wcSessionNamespaces(this.cfg.chainId)
40782
40862
  });
40783
40863
  if (!uri) throw new Error("WalletConnect returned no pairing URI");
40784
- void approval().then((session) => {
40864
+ const pairingId = /^wc:([0-9a-f]+)@/i.exec(uri)?.[1];
40865
+ if (!pairingId) throw new Error(`WalletConnect pairing URI has no recognisable topic: ${uri.slice(0, 12)}\u2026`);
40866
+ let candidateTopic = null;
40867
+ void approval().then(async (session) => {
40785
40868
  const first = session.namespaces["eip155"]?.accounts[0];
40786
40869
  if (!first) throw new Error("WalletConnect session carries no eip155 account");
40787
40870
  const [, chainIdStr, account] = first.split(":");
40788
- this.session = { topic: session.topic, account, chainId: Number(chainIdStr) };
40789
- this.sessionListener?.(this.active());
40790
- }).catch((e) => console.error(`[dh-mcp] WalletConnect pairing failed: ${e.message}`));
40791
- return { uri };
40871
+ candidateTopic = session.topic;
40872
+ const candidate = { topic: session.topic, account, chainId: Number(chainIdStr) };
40873
+ const prove = async (statement) => {
40874
+ this.assertRelayHealthy();
40875
+ return await this.client.request({
40876
+ topic: candidate.topic,
40877
+ chainId: `eip155:${candidate.chainId}`,
40878
+ request: { method: "personal_sign", params: [import_ethers50.ethers.hexlify(import_ethers50.ethers.toUtf8Bytes(statement)), candidate.account] }
40879
+ });
40880
+ };
40881
+ const state = { deleted: false };
40882
+ const live = () => !state.deleted && this.health.fatal === null;
40883
+ const previous = this.session;
40884
+ this.session = candidate;
40885
+ this.candidates.set(candidate.topic, state);
40886
+ const verdict = this.sessionListener?.({ account: candidate.account, chainId: candidate.chainId, pairingId, prove, live });
40887
+ let adopted;
40888
+ if (verdict instanceof Promise) {
40889
+ this.session = previous;
40890
+ adopted = await verdict.finally(() => this.candidates.delete(candidate.topic)).then((v) => v !== false);
40891
+ if (adopted) this.session = candidate;
40892
+ } else {
40893
+ this.candidates.delete(candidate.topic);
40894
+ adopted = verdict !== false;
40895
+ if (!adopted) this.session = previous;
40896
+ }
40897
+ if (!adopted) {
40898
+ void this.client.disconnect({ topic: session.topic, reason: { code: 6e3, message: "session refused by the bridge" } }).catch(() => void 0);
40899
+ }
40900
+ }).catch((e) => {
40901
+ console.error(`[dh-mcp] WalletConnect pairing failed: ${e.message}`);
40902
+ if (candidateTopic !== null && this.session?.topic !== candidateTopic) {
40903
+ void this.client.disconnect({ topic: candidateTopic, reason: { code: 6e3, message: "session not adopted" } }).catch(() => void 0);
40904
+ }
40905
+ });
40906
+ return { uri, pairingId };
40792
40907
  }
40793
40908
  /** Route one wallet request over the active session. Throws on user rejection. */
40794
40909
  async request(method, params) {
40910
+ this.assertRelayHealthy();
40795
40911
  if (!this.session) throw new Error("no active WalletConnect session");
40796
40912
  return this.client.request({
40797
40913
  topic: this.session.topic,
@@ -40823,6 +40939,7 @@ var import_node_crypto8 = require("crypto");
40823
40939
  var fs5 = __toESM(require("fs"));
40824
40940
  var os2 = __toESM(require("os"));
40825
40941
  var path4 = __toESM(require("path"));
40942
+ var import_ethers52 = require("ethers");
40826
40943
 
40827
40944
  // src/boundary/envelope.ts
40828
40945
  function okEnvelope(data, source, warnings = []) {
@@ -43321,8 +43438,13 @@ var SignerManager = class {
43321
43438
  mode: deps.initialMode,
43322
43439
  borrower: deps.configuredBorrower ?? null
43323
43440
  };
43441
+ if (deps.authenticatedBorrower) this.state = { ...this.state, borrower: deps.authenticatedBorrower };
43324
43442
  }
43325
43443
  state;
43444
+ /** True when the borrower is the signed-in identity and cannot be swapped. */
43445
+ identityPinned() {
43446
+ return this.deps.authenticatedBorrower !== void 0;
43447
+ }
43326
43448
  mode() {
43327
43449
  return this.state.mode;
43328
43450
  }
@@ -43362,7 +43484,7 @@ var SignerManager = class {
43362
43484
  this.deps.persistence.save(this.state);
43363
43485
  }
43364
43486
  resetBorrower() {
43365
- this.state = { ...this.state, borrower: null };
43487
+ this.state = { ...this.state, borrower: this.deps.authenticatedBorrower ?? null };
43366
43488
  this.deps.persistence.save(this.state);
43367
43489
  }
43368
43490
  async use(mode, opts) {
@@ -51742,11 +51864,11 @@ var init_deployment_addresses = __esm2({
51742
51864
  reason: "Shared upgrade script: AdminModule implementation update"
51743
51865
  },
51744
51866
  PositionManagerViews: {
51745
- previousImplementation: "0x1EB2B1d058006ACd9033E01e846D73eDE686b620",
51746
- newImplementation: "0xA455B542cFb36AF8451fc420dB89e590E5c87cef",
51747
- upgradedAt: "2026-07-03T20:11:25.817Z",
51748
- upgradedBy: "0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6",
51749
- reason: "Shared upgrade script: PositionManagerViews implementation update"
51867
+ previousImplementation: "0xA455B542cFb36AF8451fc420dB89e590E5c87cef",
51868
+ newImplementation: "0x8cEB3F1c07fDB3301f55b96a5B9aDb33C8d36Da3",
51869
+ upgradedAt: "2026-10-02T17:04:25.853Z",
51870
+ upgradedBy: "0x0f8f23674cc90Ef7107930a4437341fD8B460362",
51871
+ reason: "1.1.2: getBackingVaults (PoR backing set) + implementation lock (constructor)"
51750
51872
  },
51751
51873
  TestPositionManager: {
51752
51874
  previousImplementation: "0x0B46Ee1a9C6b42559758B7FF78294Cd867BB08f8",
@@ -53206,6 +53328,32 @@ var require_pkg_src2 = __commonJS2({
53206
53328
  deployedAt: 1790246264563,
53207
53329
  size: 69219,
53208
53330
  hash: "bda048d8cd6b5a39c2774bcf1320e82d1eea935c2a521006fb8b887e13b6dd8d"
53331
+ },
53332
+ carryCollateralAttestation: {
53333
+ cid: "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8",
53334
+ authorizedCidHex: cidToHex(
53335
+ "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8"
53336
+ ),
53337
+ name: "Carry Collateral Attestation",
53338
+ description: "LoanCarryVault collateral attestation (borrower, BTC vault, confirmed BTC)",
53339
+ version: "1.0.0",
53340
+ deployed: true,
53341
+ deployedAt: 1790927734070,
53342
+ size: 21156,
53343
+ hash: "05b177e0bb36b0483db4a42d33c1bbbf47eb9ef34ae278459397d51a7f8957ff"
53344
+ },
53345
+ carryFundingAttestation: {
53346
+ cid: "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W",
53347
+ authorizedCidHex: cidToHex(
53348
+ "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W"
53349
+ ),
53350
+ name: "Carry Funding Attestation",
53351
+ description: "LoanCarryVault funding attestation (Hyperliquid BTC windowed hourly average)",
53352
+ version: "1.0.0",
53353
+ deployed: true,
53354
+ deployedAt: 1790925699980,
53355
+ size: 7193,
53356
+ hash: "4944ada61610cf64b32e33b5be62087088dcf5e821040c69e67942e643ce74c9"
53209
53357
  }
53210
53358
  };
53211
53359
  function getDeploymentsForNetwork(network) {
@@ -82616,7 +82764,7 @@ var RealUpstreamPlugin = class {
82616
82764
  }
82617
82765
  if (mode === "external") {
82618
82766
  const borrower = await rt.manager.resolveBorrowerForWrite();
82619
- if (!borrower) {
82767
+ if (!borrower || this.pinnedWalletUnreachable(borrower, { allowCachedLogin: false })) {
82620
82768
  return {
82621
82769
  ok: false,
82622
82770
  failure: {
@@ -82666,6 +82814,20 @@ var RealUpstreamPlugin = class {
82666
82814
  }
82667
82815
  };
82668
82816
  }
82817
+ /** Hosted tier: the SIWE borrower is bound from boot, so "bound" no longer implies a
82818
+ * wallet can sign. Refuse as "no wallet is connected" instead of starting a ceremony
82819
+ * nobody can answer.
82820
+ *
82821
+ * `allowCachedLogin` is for `connectExternal` ONLY: a still-valid lit-ops login lets it
82822
+ * succeed without a wallet (it signs nothing). A WRITE always needs a fresh wallet
82823
+ * signature (ExternalEoaDHSigner), so a cached JWT must not admit it — that would queue
82824
+ * an approval with no wallet attached to sign it. */
82825
+ pinnedWalletUnreachable(borrower, opts) {
82826
+ if (!this.runtime?.manager.identityPinned()) return false;
82827
+ if (this.runtime.bridge.walletState() !== null) return false;
82828
+ if (!opts.allowCachedLogin) return true;
82829
+ return !this.sessionCache.get(`external:${borrower.toLowerCase()}`)?.hasValidToken();
82830
+ }
82669
82831
  /** The EXPLICIT login action (plan 10 OV-10 / A0.7): the ONLY path that may summon the
82670
82832
  * wallet for a lit-ops login outside a write ceremony. Binds the borrower on success —
82671
82833
  * the first verified ceremony fixes the identity. */
@@ -82676,7 +82838,7 @@ var RealUpstreamPlugin = class {
82676
82838
  return { ok: false, reason: `the active mode is '${manager.mode()}' \u2014 run signer_setup action 'use' mode 'external' first` };
82677
82839
  }
82678
82840
  const borrower = manager.borrowerForWrite();
82679
- if (!borrower) {
82841
+ if (!borrower || this.pinnedWalletUnreachable(borrower, { allowCachedLogin: true })) {
82680
82842
  return { ok: false, reason: "no wallet is connected \u2014 open the approval page (signer_setup action 'status') and connect your wallet first" };
82681
82843
  }
82682
82844
  const key = `external:${borrower.toLowerCase()}`;
@@ -83213,6 +83375,81 @@ var RealUpstreamPlugin = class {
83213
83375
  var fs4 = __toESM(require("fs"));
83214
83376
  var http3 = __toESM(require("http"));
83215
83377
  var import_node_crypto7 = require("crypto");
83378
+ var import_ethers51 = require("ethers");
83379
+
83380
+ // src/util/brand-assets.ts
83381
+ var FAVICON_SVG = `<svg width="512" height="512" viewBox="-6 -11 88 88" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Diamond Hands"><path d="M1.08325 20.7041L37.9038 64.4967L74.2886 20.7041L61.8699 0.877686H13.502L1.08325 20.7041Z" fill="#C9F284" stroke="#34440E" stroke-width="1.75559"/><path d="M13.9385 0.877441L37.9045 64.2785" stroke="#34440E" stroke-width="1.75559"/><path d="M61.6553 0.877441L37.9071 64.4964" stroke="#34440E" stroke-width="1.75559"/><path d="M1.08276 20.7029H74.2882" stroke="#34440E" stroke-width="1.75559"/></svg>`;
83382
+ var FAVICON_DATA_URI = `data:image/svg+xml,${encodeURIComponent(FAVICON_SVG).replace(/'/g, "%27")}`;
83383
+ var GVNR_PILL_LOGO_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAACXCAYAAABjhOMoAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAOdEVYdFNvZnR3YXJlAEZpZ21hnrGWYwAAJTxJREFUeAHtnV92E0myxiMyS6bhPrRmBS0e5xzbWCtArKDdK2izgoZz7pjp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IAiCkBR+f78oi7fKHtBH1S9ruOiL3lzmshxBEARBSI3R7o2jZc39MsCRvujLXpYjCIIgCCnhT/xbF1+MjDQvBMClvuhLO6hDEARBEFLicsMufW4uZhoUAoDaUo4Op/BRgEpGEwqCIAiCEI7Rhl0002S0v8RFJ0CjVqipx9ALsHFidkUECIIgCEJN+ad5+ni0e+Po6Z+4EAAUBbAjc6oR8UHZowkFQRAEQVick/ynTYtuZ/i1debJ5e6SX8zxujTukHU0oSAIgiAIYaFW3S4DCv0PG9cdrant9uXnfTEMKMdsdDhKMZrwJN+V/gCCIAiCEDlk4h/d/Gk/zz6ZsVMnvxAAlArQaO6NigBU+Ip7KpEgCIIgCNfn2Ow+yLT+bPOnaaaTBkvhpB9EA3KM029HJ+U5cF1j7P12Q2ajC4IgCEIM0Kl/0MOnM3xs2uY/eM5kSATkLns54gkYcpAb80SEgCAIgiBUw7iNn/AH93eNT2Zr2kjpKwXAEJoDDYhfpAAoIgAOD8CZd8baI2j0ZKytIAiCIASGptNCr9HSqrHh0G4oVFSld2lkPZ6hs09W9aPns/zMmQQAQdGAnlU7ONJRSBAEQRCEKHidfTIPp536R5lZAAwZCgGFeHfUHyAIgiAIQpngmXXml5Vz93yejf/iv4YFOHVPO9bCBiJ5BLDlf9g3PjHQBEEQBEEQAoI+ve5+8wfvI+dT70rB0RoW03wFQRAEQRBm5/8BP0+mvgFrTN4AAAAASUVORK5CYII=";
83384
+
83385
+ // src/util/house-style.ts
83386
+ var APP_BACKGROUND_ORIGIN = "https://images.diamondhands.credit";
83387
+ var APP_BACKGROUND_URL = `${APP_BACKGROUND_ORIGIN}/bg-diamond-hands.png`;
83388
+ var FONT_ORIGIN = "https://images.gvnr.xyz";
83389
+ var MANROPE_BASE = `${FONT_ORIGIN}/fonts/manrope`;
83390
+ var HOUSE_CSP_EXTRA = {
83391
+ "img-src": [APP_BACKGROUND_ORIGIN, "data:"],
83392
+ "font-src": [FONT_ORIGIN]
83393
+ };
83394
+ var HOUSE_HEAD_LINKS = `<link rel="icon" type="image/svg+xml" href="${FAVICON_DATA_URI}">
83395
+ <link rel="apple-touch-icon" href="${FAVICON_DATA_URI}">`;
83396
+ var MANROPE_WEIGHTS = [
83397
+ [300, "Light"],
83398
+ [400, "Regular"],
83399
+ [500, "Medium"],
83400
+ [600, "SemiBold"],
83401
+ [700, "Bold"]
83402
+ ];
83403
+ var HOUSE_BASE_CSS = `
83404
+ ${MANROPE_WEIGHTS.map(([w, n]) => `@font-face { font-family: "Manrope"; font-weight: ${w}; font-display: swap; src: url("${MANROPE_BASE}/Manrope-${n}.ttf") format("truetype"); }`).join("\n")}
83405
+ * { box-sizing: border-box; }
83406
+ html { min-height: 100%; background: #000006; }
83407
+ body { margin: 0; min-height: 100vh; color: #fff; font: 14px/1.5 "Manrope", system-ui, -apple-system, "Segoe UI", sans-serif;
83408
+ background: #000006 url("${APP_BACKGROUND_URL}") center / cover no-repeat fixed; }
83409
+ .house-header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 1rem; }
83410
+ @media (min-width: 768px) { .house-header { padding: 1rem 2.5rem; } }
83411
+ .house-header > img { height: 1.92rem; width: auto; display: block; flex: none; }
83412
+ /* Narrow viewports: the chip may shrink (its label ellipsises), and below 400px the label
83413
+ is dropped so logo + chip icon always fit a 320px phone with no horizontal page scroll. */
83414
+ .house-header .chip { min-width: 0; }
83415
+ .chip-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
83416
+ /* ".house-header .chip", not ".chip": the base .chip rule below declares padding too, and at
83417
+ equal specificity the LATER rule wins regardless of the media query; this selector outranks it. */
83418
+ @media (max-width: 400px) { .chip-label { display: none; } .house-header .chip { padding: 0.4rem 0.6rem; } }
83419
+ .chip { display: inline-flex; align-items: center; gap: 0.45rem; padding: 0.4rem 0.85rem; border-radius: 999px;
83420
+ background: rgba(0, 0, 0, 0.3); border: 1px solid rgba(255, 255, 255, 0.1); backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px);
83421
+ font-size: 0.8rem; font-weight: 600; color: #dbff91; white-space: nowrap; }
83422
+ .chip img { height: 1rem; }
83423
+ main { max-width: 34rem; margin: 2.5rem auto 3rem; padding: 0 1rem; }
83424
+ .panel { background: #121212; border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 1rem;
83425
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05); }
83426
+ @media (min-width: 768px) { .panel { padding: 1.25rem; } }
83427
+ h1 { font-size: 1.25rem; font-weight: 600; line-height: 1.375; color: #fafafa; margin: 0 0 1rem; }
83428
+ @media (min-width: 768px) { h1 { font-size: 1.5rem; margin-bottom: 1.25rem; } }
83429
+ h2 { font-size: 1rem; font-weight: 600; line-height: 1.375; color: #fafafa; margin: 0 0 0.75rem; }
83430
+ p { margin: 0 0 1rem; color: #e5e5e5; font-size: 0.875rem; font-weight: 300; line-height: 1.5; }
83431
+ button { font: inherit; font-size: 0.875rem; cursor: pointer; border: 0; display: inline-flex; align-items: center; justify-content: center;
83432
+ min-height: 2.75rem; padding: 0.65rem 1.25rem; transition: opacity 0.2s, background-color 0.2s; }
83433
+ button:focus-visible { outline: 2px solid #84cc16; outline-offset: 2px; }
83434
+ button:disabled { opacity: 0.5; cursor: not-allowed; }
83435
+ /* Primary = lime-700 (#4d7c0f): white 14px text on it is 4.99:1 (WCAG AA needs 4.5:1; the
83436
+ brighter #65a30d was 3.09:1). Hover = lime-800 (#3f6212), 7.08:1. A test recomputes both. */
83437
+ .btn-primary { background: #4d7c0f; color: #fff; font-weight: 700; letter-spacing: 0.025em; border-radius: 12px; box-shadow: 0 4px 18px rgba(74, 222, 128, 0.2); }
83438
+ .btn-primary:hover:not(:disabled) { background: #3f6212; }
83439
+ .btn-secondary { background: #34440e; color: #dbff91; font-weight: 500; border-radius: 20px; }
83440
+ .btn-secondary:hover:not(:disabled) { background: #3d5210; }
83441
+ .btn-danger { background: transparent; color: #fca5a5; font-weight: 600; border-radius: 12px; border: 1px solid rgba(248, 113, 113, 0.45); }
83442
+ .btn-danger:hover:not(:disabled) { background: rgba(220, 38, 38, 0.15); }
83443
+ /* A QR needs dark-on-light to scan: it keeps a white plate on the dark page. */
83444
+ .qr-plate { max-width: 16rem; margin-top: 1rem; background: #fff; border-radius: 12px; padding: 0.5rem; }
83445
+ .qr-plate svg { width: 100%; height: auto; display: block; }
83446
+ `;
83447
+ function houseHeader(label) {
83448
+ return `<header class="house-header">
83449
+ <img src="${GVNR_PILL_LOGO_DATA_URI}" alt="GVNR">
83450
+ <span class="chip"><img src="${FAVICON_DATA_URI}" alt=""><span class="chip-label">${label}</span></span>
83451
+ </header>`;
83452
+ }
83216
83453
 
83217
83454
  // src/boundary/upstream/shared/external-bridge/approval-page.ts
83218
83455
  function renderApprovalPage(sessionId, nonce) {
@@ -83222,47 +83459,48 @@ function renderApprovalPage(sessionId, nonce) {
83222
83459
  <meta charset="utf-8">
83223
83460
  <meta name="viewport" content="width=device-width, initial-scale=1">
83224
83461
  <title>Diamond Hands \u2014 signature approval</title>
83462
+ ${HOUSE_HEAD_LINKS}
83225
83463
  <style>
83226
- :root { --bg:#0d1117; --panel:#161b22; --line:#30363d; --text:#e6edf3; --dim:#8b949e;
83227
- --accent:#58a6ff; --approve:#238636; --reject:#da3633; }
83228
- * { box-sizing:border-box; }
83229
- body { margin:0; font:15px/1.5 system-ui,sans-serif; background:var(--bg); color:var(--text);
83230
- display:flex; min-height:100vh; align-items:center; justify-content:center; }
83231
- main { width:min(560px,94vw); }
83232
- h1 { font-size:18px; font-weight:600; letter-spacing:.02em; }
83233
- h1 span { color:var(--accent); }
83234
- .panel { background:var(--panel); border:1px solid var(--line); border-radius:10px; padding:20px; margin-top:12px; }
83235
- .status { color:var(--dim); font-size:13px; }
83236
- .card { white-space:pre-wrap; font-family:ui-monospace,monospace; font-size:14px;
83237
- background:var(--bg); border:1px solid var(--line); border-radius:8px; padding:14px; margin:14px 0; }
83238
- .action { text-transform:uppercase; letter-spacing:.08em; font-size:12px; color:var(--accent); }
83239
- button { border:0; border-radius:8px; padding:10px 22px; font-size:15px; color:#fff; cursor:pointer; }
83240
- #approve { background:var(--approve); margin-right:10px; }
83241
- #reject { background:var(--reject); }
83242
- #wallet { font-family:ui-monospace,monospace; font-size:12px; color:var(--dim); margin-top:10px; }
83464
+ ${HOUSE_BASE_CSS}
83465
+ /* \u2500\u2500 approval page only \u2500\u2500 */
83466
+ main { max-width: 36rem; }
83467
+ .status { color:#a1a1a1; font-size:0.875rem; }
83468
+ .action { text-transform:uppercase; letter-spacing:.08em; font-size:0.75rem; font-weight:600; color:#dbff91; margin-top:0.25rem; }
83469
+ /* The decoded card IS the operation (decode-equivalence): kept monospace and pre-wrapped
83470
+ exactly as the server rendered it, on an inset well darker than the panel. */
83471
+ .card { white-space:pre-wrap; font-family:ui-monospace,SFMono-Regular,Menlo,monospace; font-size:0.875rem; color:#fafafa;
83472
+ background:#0a0a0a; border:1px solid rgba(255,255,255,0.1); border-radius:10px; padding:14px; margin:0.75rem 0 1rem; }
83473
+ .actions { display:flex; flex-wrap:wrap; gap:0.75rem; }
83474
+ #deadline { margin-bottom:1rem; }
83475
+ #wallet { font-family:ui-monospace,SFMono-Regular,Menlo,monospace; font-size:0.75rem; color:#a1a1a1; margin-top:1rem; }
83476
+ #wallet:empty { display:none; }
83477
+ #wc { margin-top:1.25rem; border-top:1px solid rgba(255,255,255,0.06); padding-top:1rem; }
83478
+ #wc-uri { user-select:all; word-break:break-all; font-size:0.75rem; }
83479
+ #wc-hint { margin-top:0.75rem; }
83243
83480
  .hidden { display:none; }
83244
83481
  </style>
83245
83482
  </head>
83246
83483
  <body>
83484
+ ${houseHeader("Diamond Hands \xB7 signature approval")}
83247
83485
  <main>
83248
- <h1><span>\u25C6</span> Diamond Hands \u2014 signature approval</h1>
83486
+ <h1>Signature approval</h1>
83249
83487
  <div class="panel">
83250
83488
  <div id="status" class="status">Connecting to your wallet\u2026</div>
83251
83489
  <div id="request" class="hidden">
83252
83490
  <div id="action" class="action"></div>
83253
83491
  <div id="card" class="card"></div>
83254
83492
  <div id="deadline" class="status hidden"></div>
83255
- <button id="approve">Approve in wallet</button>
83256
- <button id="reject">Reject</button>
83493
+ <div class="actions">
83494
+ <button id="approve" class="btn-primary">Approve in wallet</button>
83495
+ <button id="reject" class="btn-danger">Reject</button>
83496
+ </div>
83257
83497
  </div>
83258
83498
  <div id="wallet"></div>
83259
- <div id="wc" style="margin-top:14px; border-top:1px solid var(--line); padding-top:12px;">
83260
- <button id="wc-connect" style="background:var(--panel); border:1px solid var(--line); color:var(--text);">
83261
- Use a mobile wallet instead (WalletConnect)
83262
- </button>
83263
- <div id="wc-qr" class="hidden" style="background:#fff; border-radius:8px; padding:8px; margin-top:10px; max-width:280px;"></div>
83264
- <div id="wc-uri" class="card hidden" style="user-select:all; word-break:break-all; font-size:12px;"></div>
83265
- <div id="wc-hint" class="status hidden">Scan the QR with your wallet app (or open the app \u2192 WalletConnect \u2192 paste the pairing code). Approvals then happen on your phone.</div>
83499
+ <div id="wc">
83500
+ <button id="wc-connect" class="btn-secondary">Use a mobile wallet instead (WalletConnect)</button>
83501
+ <div id="wc-qr" class="qr-plate hidden"></div>
83502
+ <div id="wc-uri" class="card hidden"></div>
83503
+ <div id="wc-hint" class="status hidden">Scan the QR with your wallet app (or open the app \u2192 WalletConnect \u2192 paste the pairing code). Your wallet first asks you to sign a short statement proving the wallet is yours \u2014 it moves no funds. Approvals then happen on your phone.</div>
83266
83504
  </div>
83267
83505
  </div>
83268
83506
  </main>
@@ -83336,21 +83574,63 @@ async function healChain() {
83336
83574
  }).catch(() => undefined);
83337
83575
  }
83338
83576
  await readWallet();
83339
- await post(BASE + "hello", { account: account, chainId: chainId });
83577
+ await sayHello();
83340
83578
  showWallet();
83341
83579
  }
83342
83580
 
83581
+ function utf8Hex(text) {
83582
+ return "0x" + Array.from(new TextEncoder().encode(text)).map((b) => b.toString(16).padStart(2, "0")).join("");
83583
+ }
83584
+
83585
+ // Presence proof: the bridge only believes a wallet is at this page once the wallet has
83586
+ // SIGNED a short statement naming this page's origin, the chain and a per-page nonce. Saying
83587
+ // an address proves nothing (it is public); signing proves the key is here. One prompt per
83588
+ // page session: once this account has proven itself the bridge accepts later hellos for it
83589
+ // (a chain switch) without asking the wallet again.
83590
+ let provenFor = null;
83591
+ async function sayHello() {
83592
+ let signature;
83593
+ if (provenFor === null || provenFor.toLowerCase() !== String(account).toLowerCase()) {
83594
+ const ch = await fetch(BASE + "challenge?s=" + SESSION + "&chainId=" + chainId).then((r) => r.json());
83595
+ showIdleStatus("Sign the short statement in your wallet to prove it is yours \u2014 it moves no funds.");
83596
+ signature = await window.ethereum.request({ method: "personal_sign", params: [utf8Hex(ch.statement), account] });
83597
+ }
83598
+ const r = await post(BASE + "hello", { account: account, chainId: chainId, signature: signature });
83599
+ if (!r.ok) {
83600
+ const b = await r.json().catch(() => ({}));
83601
+ showStatus("This wallet was not accepted: " + (b.error || "HTTP " + r.status));
83602
+ return false;
83603
+ }
83604
+ provenFor = account;
83605
+ return true;
83606
+ }
83607
+
83608
+ // The stream opens at load, so a card can be on screen BEFORE connect() finishes. The status
83609
+ // line then belongs to that card (its review / mobile-wallet guidance), and connection
83610
+ // progress must not overwrite it. Connection progress lines (idle / "sign the statement", whose
83611
+ // wallet popup is self-explanatory) go through here; failures (a refused hello, a lost
83612
+ // stream, a wrong network) still show unconditionally.
83613
+ function showIdleStatus(text) {
83614
+ if (current !== null) return;
83615
+ showStatus(text);
83616
+ }
83617
+
83343
83618
  async function connect() {
83344
- if (!window.ethereum) { showStatus("No wallet detected \u2014 install MetaMask (or open this page in a wallet browser)."); return; }
83619
+ if (!window.ethereum) {
83620
+ // The event stream is already open (see the bottom of this script) \u2014 a phone paired
83621
+ // below still mirrors its cards here.
83622
+ showIdleStatus("No browser wallet detected \u2014 use the mobile wallet option below, or install MetaMask (or open this page in a wallet browser).");
83623
+ return;
83624
+ }
83345
83625
  await window.ethereum.request({ method: "eth_requestAccounts" });
83346
83626
  await readWallet();
83347
- await post(BASE + "hello", { account: account, chainId: chainId });
83627
+ const accepted = await sayHello();
83348
83628
  showWallet();
83349
83629
  window.ethereum.on("accountsChanged", onAccountsChanged);
83350
83630
  window.ethereum.on("chainChanged", onChainChanged);
83631
+ if (!accepted) return;
83351
83632
  await healChain();
83352
- showStatus("Connected. Waiting for a signature request\u2026");
83353
- listen();
83633
+ showIdleStatus("Connected. Waiting for a signature request\u2026");
83354
83634
  }
83355
83635
 
83356
83636
  // Handlers trust the EVENT payloads \u2014 re-reading eth_accounts/eth_chainId here races the
@@ -83360,6 +83640,8 @@ async function onAccountsChanged(accounts) {
83360
83640
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
83361
83641
  showWallet();
83362
83642
  invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
83643
+ // The bridge adopts no account from an event alone \u2014 a different account proves itself.
83644
+ if (account) await sayHello();
83363
83645
  }
83364
83646
 
83365
83647
  async function onChainChanged(cid) {
@@ -83369,8 +83651,14 @@ async function onChainChanged(cid) {
83369
83651
  invalidatePageRequests("Network changed \u2014 pending request invalidated.");
83370
83652
  }
83371
83653
 
83654
+ // ONE stream per page, opened at load whatever wallet this browser has: a phone paired
83655
+ // through WalletConnect needs no injected wallet, and its read-only mirror arrives on this
83656
+ // stream. Opening it proves nothing \u2014 the bridge sends this page NOTHING until a person is
83657
+ // proven (a signed hello, or a pairing a phone answered).
83658
+ let es = null;
83372
83659
  function listen() {
83373
- const es = new EventSource(BASE + "events?s=" + SESSION);
83660
+ if (es !== null) return;
83661
+ es = new EventSource(BASE + "events?s=" + SESSION);
83374
83662
  es.onmessage = (ev) => {
83375
83663
  const next = JSON.parse(ev.data);
83376
83664
  // A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
@@ -83559,9 +83847,10 @@ document.getElementById("wc-connect").onclick = async () => {
83559
83847
  qrEl.classList.remove("hidden");
83560
83848
  }
83561
83849
  document.getElementById("wc-hint").classList.remove("hidden");
83562
- showStatus("Scan the QR (or paste the code) in your mobile wallet \u2014 it becomes the signing wallet.");
83850
+ showIdleStatus("Scan the QR (or paste the code) in your mobile wallet, then sign the short statement it shows (it proves the wallet is yours and moves no funds) \u2014 it then becomes the signing wallet.");
83563
83851
  };
83564
83852
 
83853
+ listen();
83565
83854
  connect();
83566
83855
  </script>
83567
83856
  </body>
@@ -83670,6 +83959,22 @@ function htmlPageSecurityHeaders(extra) {
83670
83959
 
83671
83960
  // src/boundary/upstream/shared/external-bridge/bridge.ts
83672
83961
  var MAX_SESSIONS = 16;
83962
+ function presenceStatement(origin2, chainId, nonce) {
83963
+ return [
83964
+ "Diamond Hands approval page",
83965
+ "Sign to prove this wallet is yours. This moves no funds and approves no operation.",
83966
+ `Origin: ${origin2}`,
83967
+ `Chain ID: ${chainId}`,
83968
+ `Session nonce: ${nonce}`
83969
+ ].join("\n");
83970
+ }
83971
+ function recoverPresenceSigner(statement, signature) {
83972
+ try {
83973
+ return import_ethers51.ethers.verifyMessage(statement, signature);
83974
+ } catch {
83975
+ return null;
83976
+ }
83977
+ }
83673
83978
  var DEFAULT_EXPIRY_MS = 5 * 60 * 1e3;
83674
83979
  var DEFAULT_ATTACH_GRACE_MS = 60 * 1e3;
83675
83980
  var DEFAULT_HOSTED_ATTACH_GRACE_MS = 180 * 1e3;
@@ -83683,6 +83988,7 @@ function wcDeclineOrFault(e) {
83683
83988
  }
83684
83989
  var SignatureBridge = class {
83685
83990
  clock;
83991
+ sweepIntervalMs;
83686
83992
  /** Lowercased at construction so every comparison is case-flat — EIP-55 checksum casing
83687
83993
  * differs between what SIWE signs and what a wallet reports for the SAME address. */
83688
83994
  boundAccount;
@@ -83713,13 +84019,24 @@ var SignatureBridge = class {
83713
84019
  wcTransport = null;
83714
84020
  /** True while a WalletConnect session is THE wallet — ceremonies route over WC. */
83715
84021
  wcActive = false;
83716
- /** Page session that most recently asked for a pairing QR — see `serveWcPairing`. */
83717
- pairingSessionId = null;
84022
+ /** Which page session asked for which pairing (pairing id → session id). The transport's
84023
+ * `onSession` says WHICH PAIRING a phone answered; this says whose it was. The previous
84024
+ * "most recent asker" guess let a second session claim the credit for a QR the user's
84025
+ * phone scanned (Sentinel 2 PoC-B). */
84026
+ pairingOwners = /* @__PURE__ */ new Map();
84027
+ /** The page session the ADMITTED WalletConnect session's proof was made for — the one page
84028
+ * credited with `wcPaired`. The credit lasts exactly as long as that session: it moves when
84029
+ * another proven session replaces it and ends when the wallet disconnects. */
84030
+ wcCreditedSession = null;
83718
84031
  keystoreUnlock;
83719
84032
  unlockToken = null;
83720
84033
  unlockSession = null;
83721
84034
  constructor(opts) {
83722
84035
  this.clock = opts?.clock ?? Date.now;
84036
+ this.sweepIntervalMs = opts?.sweepIntervalMs ?? 1e3;
84037
+ if (!Number.isInteger(this.sweepIntervalMs) || this.sweepIntervalMs < 0) {
84038
+ throw new Error(`bridge sweepIntervalMs must be a non-negative integer (got ${String(opts?.sweepIntervalMs)})`);
84039
+ }
83723
84040
  this.boundAccount = opts?.boundAccount?.toLowerCase();
83724
84041
  this.expiryMs = opts?.expiryMs ?? DEFAULT_EXPIRY_MS;
83725
84042
  this.maxPending = opts?.maxPending ?? null;
@@ -83755,8 +84072,10 @@ var SignatureBridge = class {
83755
84072
  this.server = server;
83756
84073
  }
83757
84074
  this.started = true;
83758
- this.sweepTimer = setInterval(() => this.sweep(), 1e3);
83759
- this.sweepTimer.unref();
84075
+ if (this.sweepIntervalMs > 0) {
84076
+ this.sweepTimer = setInterval(() => this.sweep(), this.sweepIntervalMs);
84077
+ this.sweepTimer.unref();
84078
+ }
83760
84079
  if (this.urlFile) fs4.writeFileSync(this.urlFile, this.url());
83761
84080
  }
83762
84081
  /** Plan 12 C1: the outer server's dispatch entry for a MOUNTED bridge — `req.url`
@@ -83816,6 +84135,16 @@ var SignatureBridge = class {
83816
84135
  pendingCount() {
83817
84136
  return this.pending.size;
83818
84137
  }
84138
+ /** A request lives for the bridge's expiry OR until its payload dies, whichever is first.
84139
+ * The BTC-withdraw execute leg's payload dies inside a sub-minute quantum window; holding
84140
+ * the ceremony open for the full five minutes kept a dead card on screen and let the phone
84141
+ * be asked to sign something the protocol would refuse. */
84142
+ deadlineFor(request, nowMs) {
84143
+ const bridgeDeadline = nowMs + this.expiryMs;
84144
+ if (request.expiresAtSec === void 0) return bridgeDeadline;
84145
+ if (!Number.isFinite(request.expiresAtSec)) throw new Error(`request ${request.id} carries a non-finite expiresAtSec`);
84146
+ return Math.min(bridgeDeadline, request.expiresAtSec * 1e3);
84147
+ }
83819
84148
  /**
83820
84149
  * Enqueue a request and resolve on the human's decision (or expiry/invalidation).
83821
84150
  * Chain-id mismatch with an already-connected wallet refuses BEFORE the wallet is asked.
@@ -83838,7 +84167,7 @@ var SignatureBridge = class {
83838
84167
  const now = this.clock();
83839
84168
  const entry = {
83840
84169
  request,
83841
- deadlineMs: now + this.expiryMs,
84170
+ deadlineMs: this.deadlineFor(request, now),
83842
84171
  enqueuedMs: now,
83843
84172
  resolve,
83844
84173
  settled: false,
@@ -83869,7 +84198,7 @@ var SignatureBridge = class {
83869
84198
  const now = this.clock();
83870
84199
  const entry = {
83871
84200
  request,
83872
- deadlineMs: now + this.expiryMs,
84201
+ deadlineMs: this.deadlineFor(request, now),
83873
84202
  enqueuedMs: now,
83874
84203
  resolve,
83875
84204
  settled: false,
@@ -83921,6 +84250,7 @@ var SignatureBridge = class {
83921
84250
  return;
83922
84251
  }
83923
84252
  try {
84253
+ if (this.expireIfOverdue(entry)) return;
83924
84254
  if (req.kind === "transaction") {
83925
84255
  this.pushEntry(entry);
83926
84256
  const tx2 = req.tx;
@@ -83932,15 +84262,23 @@ var SignatureBridge = class {
83932
84262
  } else if (req.kind === "personal-sign") {
83933
84263
  if (entry.finalize) {
83934
84264
  const fresh = await entry.finalize();
84265
+ if (entry.settled) return;
84266
+ if (entry.owner !== "wc") return;
84267
+ const live = transport.active();
84268
+ if (!this.wcActive || !live || live.account.toLowerCase() !== account.toLowerCase()) {
84269
+ this.settle(entry, {
84270
+ status: "invalidated",
84271
+ reason: "the WalletConnect wallet changed while this payload was being prepared \u2014 the phone was not asked. Reconnect your wallet and retry the operation."
84272
+ });
84273
+ return;
84274
+ }
83935
84275
  req.personalSign = fresh.personalSign;
83936
84276
  req.card = fresh.card;
83937
84277
  }
84278
+ if (this.expireIfOverdue(entry)) return;
83938
84279
  const ps = req.personalSign;
83939
- if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
83940
- this.settle(entry, {
83941
- status: "invalidated",
83942
- reason: `this step signs a 32-byte hash your wallet cannot decode, and no approval page is open to show you what it authorizes \u2014 open ${this.url()} and re-run the withdrawal with loan_withdraw_retry (it re-signs with a fresh stamp; your coins stay in the vault meanwhile)`
83943
- });
84280
+ if (!this.pageAttached()) {
84281
+ this.settle(entry, { status: "invalidated", reason: this.noPageReason(ps.layout === RAW_HASH_LAYOUT) });
83944
84282
  return;
83945
84283
  }
83946
84284
  this.pushEntry(entry);
@@ -83965,6 +84303,16 @@ var SignatureBridge = class {
83965
84303
  }
83966
84304
  }
83967
84305
  }
84306
+ /** Refusal for a WalletConnect personal_sign with no proven approval page attached.
84307
+ *
84308
+ * The remedy names BOTH halves, because opening the link alone does not fix it: a freshly
84309
+ * opened page is a stranger until a phone answers a pairing it showed (or its wallet signs
84310
+ * the presence statement), so it receives no card. Following "just reopen the URL" looped
84311
+ * (Sentinel 2 PoC-C). */
84312
+ noPageReason(blindHash) {
84313
+ const what = blindHash ? "this step signs a 32-byte hash your wallet cannot decode" : "this step asks your wallet to sign a message your phone shows only as a hash";
84314
+ return `${what}, and no approval page linked to your wallet is open to show you what it authorizes \u2014 open ${this.url()} in a browser AND, on that page, re-scan the WalletConnect QR with your phone (or reconnect your wallet there) so the page is tied to your wallet, then retry with loan_withdraw_retry for a withdrawal or re-run the operation (it re-signs with a fresh stamp; your coins stay in the vault meanwhile)`;
84315
+ }
83968
84316
  /** A live attachment that could still decide a request: an open approval-page SSE
83969
84317
  * stream (real page or headless driver) or an active WalletConnect session. PUBLIC
83970
84318
  * (plan 17 E1): the connector's idle-eviction predicate reads it — a tenant world
@@ -84048,6 +84396,7 @@ var SignatureBridge = class {
84048
84396
  void this.wcTransport?.close().catch(() => void 0);
84049
84397
  this.wcTransport = null;
84050
84398
  this.wcActive = false;
84399
+ this.pairingOwners.clear();
84051
84400
  }
84052
84401
  // ---- HTTP plumbing ----
84053
84402
  route(req, res) {
@@ -84055,6 +84404,7 @@ var SignatureBridge = class {
84055
84404
  const url2 = new URL(req.url ?? "/", this.mount ? this.mount.origin : `http://127.0.0.1:${this.port}`);
84056
84405
  if (req.method === "GET" && url2.pathname === "/") return this.servePage(url2, res);
84057
84406
  if (req.method === "GET" && url2.pathname === "/config") return this.serveConfig(url2, res);
84407
+ if (req.method === "GET" && url2.pathname === "/challenge") return this.serveChallenge(url2, res);
84058
84408
  if (req.method === "GET" && url2.pathname === "/wc-pairing") return void this.serveWcPairing(url2, res);
84059
84409
  if (req.method === "GET" && url2.pathname === "/unlock") return this.serveUnlockPage(url2, res);
84060
84410
  if (req.method === "POST" && url2.pathname === "/unlock-submit")
@@ -84114,8 +84464,16 @@ var SignatureBridge = class {
84114
84464
  return;
84115
84465
  }
84116
84466
  const sessionId = (0, import_node_crypto7.randomBytes)(24).toString("hex");
84117
- this.sessions.set(sessionId, { wallet: null, sse: null, refused: null, lastSeenMs: this.clock(), wcPaired: false });
84118
- const page = htmlPageSecurityHeaders();
84467
+ this.sessions.set(sessionId, {
84468
+ wallet: null,
84469
+ sse: null,
84470
+ refused: null,
84471
+ lastSeenMs: this.clock(),
84472
+ wcPaired: false,
84473
+ presenceNonce: (0, import_node_crypto7.randomBytes)(16).toString("hex"),
84474
+ provenAccount: null
84475
+ });
84476
+ const page = htmlPageSecurityHeaders(HOUSE_CSP_EXTRA);
84119
84477
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
84120
84478
  res.end(renderApprovalPage(sessionId, page.nonce));
84121
84479
  }
@@ -84125,11 +84483,29 @@ var SignatureBridge = class {
84125
84483
  res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
84126
84484
  res.end(JSON.stringify({ network: this.network ?? null }));
84127
84485
  }
84486
+ /** The origin this bridge is served from — what a presence statement names. */
84487
+ publicOrigin() {
84488
+ return this.mount ? this.mount.origin : `http://127.0.0.1:${this.port}`;
84489
+ }
84490
+ /** The presence statement for this session + chain (session-gated). The page signs exactly
84491
+ * this text in its wallet; the bridge rebuilds it on `hello` rather than trusting any text
84492
+ * the client sends back. */
84493
+ serveChallenge(url2, res) {
84494
+ const session = this.sessionOf(url2.searchParams.get("s"), res);
84495
+ if (!session) return;
84496
+ const chainId = Number(url2.searchParams.get("chainId"));
84497
+ if (!Number.isInteger(chainId)) {
84498
+ this.deny(res, 400, "challenge requires an integer chainId");
84499
+ return;
84500
+ }
84501
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
84502
+ res.end(JSON.stringify({ statement: presenceStatement(this.publicOrigin(), chainId, session.presenceNonce) }));
84503
+ }
84128
84504
  /** WalletConnect pairing (D2, session-gated): lazily boots the WC transport and serves a
84129
84505
  * fresh pairing URI. A wallet approving the pairing becomes THE wallet. */
84130
84506
  async serveWcPairing(url2, res) {
84131
84507
  if (!this.checkSession(url2.searchParams.get("s"), res)) return;
84132
- this.pairingSessionId = url2.searchParams.get("s");
84508
+ const askingSession = url2.searchParams.get("s");
84133
84509
  if (!this.wcConfig) {
84134
84510
  this.deny(res, 404, "WalletConnect is not configured (set DH_WC_PROJECT_ID)");
84135
84511
  return;
@@ -84140,36 +84516,17 @@ var SignatureBridge = class {
84140
84516
  const { WcTransport: WcTransport2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
84141
84517
  return WcTransport2.create(cfg);
84142
84518
  });
84143
- this.wcTransport = await factory2(this.wcConfig);
84144
- this.wcTransport.onSession((info) => {
84145
- const refusal = info ? this.accountRefusal(info.account) : null;
84146
- if (info && refusal) {
84147
- this.wcActive = false;
84148
- this.rebuildSharedWallet();
84149
- this.demoteWcEntries();
84150
- process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
84151
- `);
84152
- return;
84153
- }
84154
- this.wcActive = info !== null;
84155
- this.wallet = info ? { account: info.account, chainId: info.chainId } : null;
84156
- if (info && this.pairingSessionId) {
84157
- const paired = this.sessions.get(this.pairingSessionId);
84158
- if (paired) paired.wcPaired = true;
84159
- }
84160
- if (info === null) {
84161
- for (const entry of this.pending.values()) {
84162
- if (!entry.settled && !entry.collect) {
84163
- this.settle(entry, {
84164
- status: "invalidated",
84165
- reason: entry.dispatched && entry.request.kind === "transaction" ? "the WalletConnect session disconnected after being asked to send this transaction \u2014 it may have broadcast. Check the chain (or your wallet's activity) before retrying, or you may pay twice." : "the WalletConnect session disconnected"
84166
- });
84167
- }
84168
- }
84169
- }
84170
- });
84519
+ const transport = await factory2(this.wcConfig);
84520
+ this.wcTransport = transport;
84521
+ transport.onSession((info) => info === null ? this.onWcDisconnect() : this.admitWcSession(info, transport));
84522
+ }
84523
+ const { uri, pairingId } = await this.wcTransport.createPairing();
84524
+ if (pairingId) {
84525
+ for (const [pending, owner] of this.pairingOwners) {
84526
+ if (owner === askingSession || !this.sessions.has(owner)) this.pairingOwners.delete(pending);
84527
+ }
84528
+ this.pairingOwners.set(pairingId, askingSession);
84171
84529
  }
84172
- const { uri } = await this.wcTransport.createPairing();
84173
84530
  const { default: qrcode } = await import("qrcode-generator");
84174
84531
  const qr = qrcode(0, "M");
84175
84532
  qr.addData(uri);
@@ -84257,6 +84614,29 @@ var SignatureBridge = class {
84257
84614
  this.deny(res, 403, refusal);
84258
84615
  return;
84259
84616
  }
84617
+ const alreadyProven = session.provenAccount !== null && session.provenAccount.toLowerCase() === account.toLowerCase();
84618
+ if (!alreadyProven) {
84619
+ const signature = body["signature"];
84620
+ if (typeof signature !== "string" || signature === "") {
84621
+ this.deny(
84622
+ res,
84623
+ 403,
84624
+ `hello requires a signature proving this page controls ${account} \u2014 an address alone proves nothing. Approve the short signing prompt in your wallet (the approval page asks for it on connect); reload the page if it did not appear.`
84625
+ );
84626
+ return;
84627
+ }
84628
+ const statement = presenceStatement(this.publicOrigin(), chainId, session.presenceNonce);
84629
+ const recovered = recoverPresenceSigner(statement, signature);
84630
+ if (recovered === null || recovered.toLowerCase() !== account.toLowerCase()) {
84631
+ this.deny(
84632
+ res,
84633
+ 403,
84634
+ `the presence signature was not made by ${account} for this page's statement \u2014 sign the statement the approval page shows with that account (EOA wallets only; contract wallets cannot prove presence here).`
84635
+ );
84636
+ return;
84637
+ }
84638
+ session.provenAccount = account;
84639
+ }
84260
84640
  session.wallet = { account, chainId };
84261
84641
  this.wallet = { account, chainId };
84262
84642
  this.replayPending(session);
@@ -84298,17 +84678,21 @@ var SignatureBridge = class {
84298
84678
  if (refusedSwitch) {
84299
84679
  this.quarantine(session, switchRefusal);
84300
84680
  } else {
84301
- session.wallet = offered;
84681
+ const sameProven = offered !== null && session.provenAccount !== null && offered.account.toLowerCase() === session.provenAccount.toLowerCase();
84682
+ session.wallet = sameProven ? offered : null;
84302
84683
  if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
84303
84684
  this.wallet = session.wallet;
84685
+ } else if (this.wallet === null && prev === null && session.wallet !== null) {
84686
+ this.wallet = session.wallet;
84304
84687
  }
84305
84688
  }
84306
- const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
84307
- if (unchanged) {
84689
+ const reported = refusedSwitch ? null : offered;
84690
+ const unchanged = prev !== null && reported !== null && prev.account.toLowerCase() === reported.account.toLowerCase() && prev.chainId === reported.chainId;
84691
+ if (unchanged || prev === null) {
84308
84692
  this.ok(res);
84309
84693
  return;
84310
84694
  }
84311
- 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";
84695
+ const reason = refusedSwitch ? "the wallet switched to an account this session is not signed in as" : prev && reported && prev.account.toLowerCase() !== reported.account.toLowerCase() ? "the wallet account changed while approval was pending" : prev && reported && prev.chainId !== reported.chainId ? "the wallet network changed while approval was pending" : "the wallet disconnected while approval was pending";
84312
84696
  for (const entry of this.pending.values()) {
84313
84697
  if (entry.settled || entry.collect) continue;
84314
84698
  if (this.ownedByWc(entry)) continue;
@@ -84333,6 +84717,100 @@ var SignatureBridge = class {
84333
84717
  * Those entries instead fail fast at the per-entry grace, since `attachedFor` now reads
84334
84718
  * false for them, and `unattendedReason` says plainly that the phone may already have
84335
84719
  * acted. */
84720
+ /**
84721
+ * C-47, the THIRD door: a wallet announced a WalletConnect session. `requestSignature`
84722
+ * PREFERS the WalletConnect wallet over the approval page (see the `wcActive` branch there),
84723
+ * so an account admitted here does not merely become the candidate — it becomes the SIGNER,
84724
+ * and the page that showed its QR becomes the page that sees every card.
84725
+ *
84726
+ * The account a WalletConnect session carries is the wallet's own UNSIGNED claim — the
84727
+ * protocol validates its format, never its ownership. Admitting on that claim let anyone
84728
+ * holding the approval link answer their own QR with a scripted wallet claiming the user's
84729
+ * public address: it took the signer seat, its page saw every card, and an extension-only
84730
+ * user's ceremonies were routed to it (Sentinel 2 PoC-D). So this door now asks for the same
84731
+ * proof `hello` does: the wallet signs the presence statement of the page whose QR it
84732
+ * answered, and the signature must recover to the account it claims.
84733
+ *
84734
+ * Resolves `false` to refuse — the transport then keeps what it held and drops the wallet. If
84735
+ * the wallet declines the proof (or the request fails) the promise rejects and the transport
84736
+ * ends the session unadopted; nothing here is adopted before the proof checks out.
84737
+ */
84738
+ async admitWcSession(info, transport) {
84739
+ const refusal = this.accountRefusal(info.account);
84740
+ if (refusal) return this.refuseWcSession(refusal);
84741
+ const ownerId = info.pairingId ? this.pairingOwners.get(info.pairingId) : void 0;
84742
+ if (info.pairingId) this.pairingOwners.delete(info.pairingId);
84743
+ const owner = ownerId ? this.sessions.get(ownerId) : void 0;
84744
+ if (!ownerId || !owner) {
84745
+ return this.refuseWcSession(
84746
+ "the wallet answered no QR code that an open approval page of this bridge showed \u2014 open the approval page and scan the QR code it shows"
84747
+ );
84748
+ }
84749
+ if (!info.prove || !info.live) {
84750
+ return this.refuseWcSession(
84751
+ "this WalletConnect transport cannot ask the wallet to prove its account (or report whether its session is still live), so no session can be admitted"
84752
+ );
84753
+ }
84754
+ const statement = presenceStatement(this.publicOrigin(), info.chainId, owner.presenceNonce);
84755
+ const signature = await info.prove(statement);
84756
+ const recovered = recoverPresenceSigner(statement, signature);
84757
+ if (recovered === null || recovered.toLowerCase() !== info.account.toLowerCase()) {
84758
+ return this.refuseWcSession(
84759
+ `the wallet claimed ${info.account} but ${recovered === null ? "returned no valid signature" : `signed with ${recovered}`} for the approval page's presence statement \u2014 an address alone proves nothing`
84760
+ );
84761
+ }
84762
+ if (this.wcTransport !== transport) {
84763
+ return this.refuseWcSession("the bridge's WalletConnect connection was replaced while the wallet was proving its account");
84764
+ }
84765
+ if (!info.live()) {
84766
+ return this.refuseWcSession("the wallet's WalletConnect session ended (or the relay failed) while it was proving its account \u2014 scan the QR again");
84767
+ }
84768
+ const lateRefusal = this.accountRefusal(info.account);
84769
+ if (lateRefusal) return this.refuseWcSession(lateRefusal);
84770
+ const page = this.sessions.get(ownerId);
84771
+ if (!page || page.refused) {
84772
+ return this.refuseWcSession("the approval page that showed this QR code closed while the wallet was proving its account \u2014 reopen it and scan again");
84773
+ }
84774
+ if (this.wcCreditedSession !== null && this.wcCreditedSession !== ownerId) {
84775
+ const previous = this.sessions.get(this.wcCreditedSession);
84776
+ if (previous) previous.wcPaired = false;
84777
+ }
84778
+ this.wcActive = true;
84779
+ this.wallet = { account: info.account, chainId: info.chainId };
84780
+ page.wcPaired = true;
84781
+ page.provenAccount = info.account;
84782
+ this.wcCreditedSession = ownerId;
84783
+ this.replayPending(page);
84784
+ return true;
84785
+ }
84786
+ /** Refuse a WalletConnect session — see `admitWcSession`. */
84787
+ refuseWcSession(reason) {
84788
+ if (!this.wcActive) {
84789
+ this.rebuildSharedWallet();
84790
+ this.demoteWcEntries();
84791
+ }
84792
+ process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${reason}
84793
+ `);
84794
+ return false;
84795
+ }
84796
+ /** The admitted WalletConnect wallet went away. */
84797
+ onWcDisconnect() {
84798
+ this.wcActive = false;
84799
+ this.wallet = null;
84800
+ for (const entry of this.pending.values()) {
84801
+ if (!entry.settled && !entry.collect) {
84802
+ this.settle(entry, {
84803
+ status: "invalidated",
84804
+ reason: entry.dispatched && entry.request.kind === "transaction" ? "the WalletConnect session disconnected after being asked to send this transaction \u2014 it may have broadcast. Check the chain (or your wallet's activity) before retrying, or you may pay twice." : "the WalletConnect session disconnected"
84805
+ });
84806
+ }
84807
+ }
84808
+ if (this.wcCreditedSession !== null) {
84809
+ const credited = this.sessions.get(this.wcCreditedSession);
84810
+ if (credited) credited.wcPaired = false;
84811
+ this.wcCreditedSession = null;
84812
+ }
84813
+ }
84336
84814
  demoteWcEntries() {
84337
84815
  for (const entry of this.pending.values()) {
84338
84816
  if (entry.settled || entry.owner !== "wc" || entry.dispatched) continue;
@@ -84351,6 +84829,10 @@ var SignatureBridge = class {
84351
84829
  this.deny(res, 404, "unknown or already-settled requestId");
84352
84830
  return;
84353
84831
  }
84832
+ if (this.expireIfOverdue(entry)) {
84833
+ this.deny(res, 410, "this request has expired \u2014 retry the operation");
84834
+ return;
84835
+ }
84354
84836
  if (entry.request.kind !== "personal-sign") {
84355
84837
  this.deny(res, 400, "finalize applies only to personal-sign requests");
84356
84838
  return;
@@ -84377,6 +84859,10 @@ var SignatureBridge = class {
84377
84859
  this.deny(res, 404, "request settled while finalizing");
84378
84860
  return;
84379
84861
  }
84862
+ if (this.expireIfOverdue(entry)) {
84863
+ this.deny(res, 410, "this request expired while its payload was being prepared \u2014 retry the operation");
84864
+ return;
84865
+ }
84380
84866
  entry.request.personalSign = fresh.personalSign;
84381
84867
  entry.request.card = fresh.card;
84382
84868
  }
@@ -84390,6 +84876,10 @@ var SignatureBridge = class {
84390
84876
  this.deny(res, 404, "unknown or already-settled requestId");
84391
84877
  return;
84392
84878
  }
84879
+ if (this.expireIfOverdue(entry)) {
84880
+ this.deny(res, 410, "this request has expired \u2014 retry the operation");
84881
+ return;
84882
+ }
84393
84883
  if (body["approved"] !== true) {
84394
84884
  if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
84395
84885
  this.settle(entry, {
@@ -84438,6 +84928,16 @@ var SignatureBridge = class {
84438
84928
  this.ok(res);
84439
84929
  }
84440
84930
  // ---- helpers ----
84931
+ /** Accept-time deadline check. The 1 s sweep is only the backstop: between the deadline and
84932
+ * the next tick a late click on /finalize or /result — or a WalletConnect dispatch — would
84933
+ * otherwise still ask for or accept a signature over a payload the protocol will refuse.
84934
+ * Settles the entry `expired` (the same outcome the sweep gives) and reports it. */
84935
+ expireIfOverdue(entry) {
84936
+ if (entry.settled) return true;
84937
+ if (this.clock() < entry.deadlineMs) return false;
84938
+ this.settle(entry, { status: "expired" });
84939
+ return true;
84940
+ }
84441
84941
  settle(entry, outcome) {
84442
84942
  entry.settled = true;
84443
84943
  this.pending.delete(entry.request.id);
@@ -85029,6 +85529,7 @@ async function createRealBoundary(config, wallet, overrides) {
85029
85529
  const manager = new SignerManager({
85030
85530
  persistence: overrides?.signerPersistence?.(config.network) ?? fileSignerPersistence(stateFile),
85031
85531
  initialMode,
85532
+ ...overrides?.boundBorrower ? { authenticatedBorrower: import_ethers52.ethers.getAddress(overrides.boundBorrower) } : {},
85032
85533
  candidate: () => bridge.walletState()?.account ?? null,
85033
85534
  pendingCeremonies: () => bridge.pendingCount(),
85034
85535
  keystore