@gvnrdao/dh-mcp 0.5.20 → 0.5.21

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.
@@ -95,7 +95,8 @@ var init_wc_transport = __esm({
95
95
  this.client = client;
96
96
  this.cfg = cfg;
97
97
  this.scratch = scratch;
98
- client.on("session_delete", () => {
98
+ client.on("session_delete", ({ topic }) => {
99
+ if (this.session === null || this.session.topic !== topic) return;
99
100
  this.session = null;
100
101
  this.sessionListener?.(null);
101
102
  });
@@ -107,7 +108,7 @@ var init_wc_transport = __esm({
107
108
  const client = await import_sign_client.default.init({
108
109
  core,
109
110
  projectId: cfg.projectId,
110
- metadata: WC_DAPP_METADATA
111
+ metadata: cfg.metadata ?? WC_DAPP_METADATA
111
112
  });
112
113
  return new _WcTransport(client, cfg, scratch);
113
114
  }
@@ -125,14 +126,21 @@ var init_wc_transport = __esm({
125
126
  optionalNamespaces: wcSessionNamespaces(this.cfg.chainId)
126
127
  });
127
128
  if (!uri) throw new Error("WalletConnect returned no pairing URI");
129
+ const pairingId = /^wc:([0-9a-f]+)@/i.exec(uri)?.[1];
130
+ if (!pairingId) throw new Error(`WalletConnect pairing URI has no recognisable topic: ${uri.slice(0, 12)}\u2026`);
128
131
  void approval().then((session) => {
129
132
  const first = session.namespaces["eip155"]?.accounts[0];
130
133
  if (!first) throw new Error("WalletConnect session carries no eip155 account");
131
134
  const [, chainIdStr, account] = first.split(":");
135
+ const previous = this.session;
132
136
  this.session = { topic: session.topic, account, chainId: Number(chainIdStr) };
133
- this.sessionListener?.(this.active());
137
+ const verdict = this.sessionListener?.({ ...this.active(), pairingId });
138
+ if (verdict === false) {
139
+ this.session = previous;
140
+ void this.client.disconnect({ topic: session.topic, reason: { code: 6e3, message: "session refused by the bridge" } }).catch(() => void 0);
141
+ }
134
142
  }).catch((e) => console.error(`[dh-mcp] WalletConnect pairing failed: ${e.message}`));
135
- return { uri };
143
+ return { uri, pairingId };
136
144
  }
137
145
  /** Route one wallet request over the active session. Throws on user rejection. */
138
146
  async request(method, params) {
@@ -13543,6 +13551,12 @@ var require_follow_redirects = __commonJS({
13543
13551
  RedirectableRequest.prototype._sanitizeOptions = function(options) {
13544
13552
  if (!options.headers) {
13545
13553
  options.headers = {};
13554
+ } else if (Array.isArray(options.headers)) {
13555
+ var headerList = options.headers;
13556
+ options.headers = {};
13557
+ for (var i = 0; i < headerList.length; i += 2) {
13558
+ options.headers[headerList[i]] = headerList[i + 1];
13559
+ }
13546
13560
  }
13547
13561
  if (!isArray2(options.sensitiveHeaders)) {
13548
13562
  options.sensitiveHeaders = [];
@@ -13817,7 +13831,7 @@ var require_follow_redirects = __commonJS({
13817
13831
  return URL3 && value instanceof URL3;
13818
13832
  }
13819
13833
  function escapeRegex(regex) {
13820
- return regex.replace(/[\]\\/()*+?.$]/g, "\\$&");
13834
+ return regex.replace(/[[\]\\/()*+?.^$|]/g, "\\$&");
13821
13835
  }
13822
13836
  module2.exports = wrap({ http: http4, https: https2 });
13823
13837
  module2.exports.wrap = wrap;
@@ -14809,6 +14823,32 @@ var require_pkg_src = __commonJS({
14809
14823
  deployedAt: 1790246264563,
14810
14824
  size: 69219,
14811
14825
  hash: "bda048d8cd6b5a39c2774bcf1320e82d1eea935c2a521006fb8b887e13b6dd8d"
14826
+ },
14827
+ carryCollateralAttestation: {
14828
+ cid: "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8",
14829
+ authorizedCidHex: cidToHex(
14830
+ "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8"
14831
+ ),
14832
+ name: "Carry Collateral Attestation",
14833
+ description: "LoanCarryVault collateral attestation (borrower, BTC vault, confirmed BTC)",
14834
+ version: "1.0.0",
14835
+ deployed: true,
14836
+ deployedAt: 1790927734070,
14837
+ size: 21156,
14838
+ hash: "05b177e0bb36b0483db4a42d33c1bbbf47eb9ef34ae278459397d51a7f8957ff"
14839
+ },
14840
+ carryFundingAttestation: {
14841
+ cid: "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W",
14842
+ authorizedCidHex: cidToHex(
14843
+ "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W"
14844
+ ),
14845
+ name: "Carry Funding Attestation",
14846
+ description: "LoanCarryVault funding attestation (Hyperliquid BTC windowed hourly average)",
14847
+ version: "1.0.0",
14848
+ deployed: true,
14849
+ deployedAt: 1790925699980,
14850
+ size: 7193,
14851
+ hash: "4944ada61610cf64b32e33b5be62087088dcf5e821040c69e67942e643ce74c9"
14812
14852
  }
14813
14853
  };
14814
14854
  function getDeploymentsForNetwork(network) {
@@ -15552,7 +15592,7 @@ ${errorReport}`);
15552
15592
  }
15553
15593
  init_debug_logger();
15554
15594
  init_session_signature_cache();
15555
- var import_ethers54 = require("ethers");
15595
+ var import_ethers56 = require("ethers");
15556
15596
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
15557
15597
  var GRACE_PERIOD_DAYS = 30;
15558
15598
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -18548,12 +18588,12 @@ ${auth.clientId}`;
18548
18588
  }
18549
18589
  async function executeVaultSnapshot(params) {
18550
18590
  global.ethers = {
18551
- ...import_ethers54.ethers,
18591
+ ...import_ethers56.ethers,
18552
18592
  providers: {
18553
- StaticJsonRpcProvider: import_ethers54.ethers.JsonRpcProvider
18593
+ StaticJsonRpcProvider: import_ethers56.ethers.JsonRpcProvider
18554
18594
  },
18555
- Contract: import_ethers54.ethers.Contract,
18556
- utils: import_ethers54.ethers
18595
+ Contract: import_ethers56.ethers.Contract,
18596
+ utils: import_ethers56.ethers
18557
18597
  // v6 moved utils to top level
18558
18598
  };
18559
18599
  global.Lit = {
@@ -27433,7 +27473,7 @@ var require_lit_ops_module = __commonJS({
27433
27473
  break;
27434
27474
  case 11155111:
27435
27475
  chain = "sepolia";
27436
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27476
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27437
27477
  break;
27438
27478
  case 1337:
27439
27479
  // Hardhat local testnet (actual deployment chainId)
@@ -27622,7 +27662,7 @@ var require_lit_ops_module = __commonJS({
27622
27662
  break;
27623
27663
  case 11155111:
27624
27664
  chain = "sepolia";
27625
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27665
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27626
27666
  break;
27627
27667
  case 1337:
27628
27668
  // Hardhat local testnet (actual deployment chainId)
@@ -27813,7 +27853,7 @@ var require_lit_ops_module = __commonJS({
27813
27853
  break;
27814
27854
  case 11155111:
27815
27855
  chain = "sepolia";
27816
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27856
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27817
27857
  break;
27818
27858
  case 1337:
27819
27859
  case 31337:
@@ -27961,7 +28001,7 @@ var require_lit_ops_module = __commonJS({
27961
28001
  break;
27962
28002
  case 11155111:
27963
28003
  chain = "sepolia";
27964
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
28004
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27965
28005
  break;
27966
28006
  case 1337:
27967
28007
  // Hardhat local testnet (actual deployment chainId)
@@ -28181,7 +28221,7 @@ var require_lit_ops_module = __commonJS({
28181
28221
  bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://mempool.space/api";
28182
28222
  break;
28183
28223
  case 11155111:
28184
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
28224
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
28185
28225
  break;
28186
28226
  case 1337:
28187
28227
  // Hardhat local testnet (actual deployment chainId)
@@ -40822,7 +40862,7 @@ module.exports = __toCommonJS(connector_embed_exports);
40822
40862
 
40823
40863
  // src/connector/service.ts
40824
40864
  var import_node_http = require("http");
40825
- var import_node_crypto10 = require("crypto");
40865
+ var import_node_crypto11 = require("crypto");
40826
40866
  var import_express = __toESM(require("express"));
40827
40867
  var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
40828
40868
  var import_router = require("@modelcontextprotocol/sdk/server/auth/router.js");
@@ -40830,7 +40870,7 @@ var import_types4 = require("@modelcontextprotocol/sdk/types.js");
40830
40870
 
40831
40871
  // src/connector/auth-md.ts
40832
40872
  var CHAIN_IDS = { mainnet: 1, sepolia: 11155111 };
40833
- function renderAuthMd({ publicOrigin, networks: networks2, walletConnectEnabled }) {
40873
+ function renderAuthMd({ publicOrigin, networks: networks2, walletConnectEnabled, grants }) {
40834
40874
  const origin2 = publicOrigin.replace(/\/+$/, "");
40835
40875
  const launchNetwork = networks2[0];
40836
40876
  if (launchNetwork === void 0) {
@@ -40843,6 +40883,7 @@ function renderAuthMd({ publicOrigin, networks: networks2, walletConnectEnabled
40843
40883
  );
40844
40884
  }
40845
40885
  const isMainnet = launchNetwork === "mainnet";
40886
+ const grantsLine = (grants.durable ? "- Clients and grants are stored durably, so a service restart does not sign anyone\n out: your client refreshes. Access tokens, sign-in flows and codes stay in memory." : "- All authorization state is held **in memory**. A service restart ends every session\n and the user signs in again. Nothing is persisted at rest.") + (grants.accountApi ? "\n- The wallet owner can see and **revoke** every grant from the Diamond Hands web app\n (Connect \u2192 Connections). A revoked grant stops working within about 30 seconds and\n its refresh token is refused with that reason." : "");
40846
40887
  const wcLine = walletConnectEnabled ? "" : " **Mobile WalletConnect sign-in is not enabled on this deployment** \u2014 browser extension or own-key only.";
40847
40888
  const agentAuth = {
40848
40889
  agent_auth: {
@@ -40931,9 +40972,11 @@ ${JSON.stringify(agentAuth, null, 2)}
40931
40972
 
40932
40973
  ### What the credential is, and is not
40933
40974
 
40934
- The **wallet address is the account.** There are no passwords, no email addresses, and
40935
- no user database. Registration creates an OAuth client, not a Diamond Hands account \u2014
40936
- there is nothing to delete, and no personal data is collected.
40975
+ The **wallet address is the account.** There are no passwords and no email addresses.
40976
+ Registration creates an OAuth client, not a Diamond Hands account. No password or email
40977
+ address is collected. Each completed sign-in is a **grant** that is stored: the wallet
40978
+ address, the client's id and self-declared name, the redirect host, timestamps, and a
40979
+ SHA-256 of the refresh token \u2014 never a token itself.
40937
40980
 
40938
40981
  The access token proves **session identity only**. It can read what that address could
40939
40982
  already read, and it can *stage* a fund-moving operation \u2014 arm a mint, a repayment, a
@@ -40942,8 +40985,7 @@ signature over that specific operation, which the token cannot produce. So it is
40942
40985
  read-only credential, and it is not a spending one either. A stolen token cannot spend.
40943
40986
 
40944
40987
  - Access token: ~1 hour. Refresh token: rotating, expires after inactivity.
40945
- - All authorization state is held **in memory**. A service restart ends every session
40946
- and the user signs in again. Nothing is persisted at rest.
40988
+ ${grantsLine}
40947
40989
  - \`scopes_supported\` is empty and tokens are minted with no scopes \u2014 this
40948
40990
  authorization server does not implement scoped access. Do not request a scope; you
40949
40991
  will not receive one.
@@ -41017,9 +41059,12 @@ source of truth.
41017
41059
  `;
41018
41060
  }
41019
41061
 
41020
- // src/connector/landing-page.ts
41062
+ // src/util/brand-assets.ts
41021
41063
  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>`;
41022
41064
  var FAVICON_DATA_URI = `data:image/svg+xml,${encodeURIComponent(FAVICON_SVG).replace(/'/g, "%27")}`;
41065
+ var GVNR_PILL_LOGO_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAACXCAYAAABjhOMoAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAOdEVYdFNvZnR3YXJlAEZpZ21hnrGWYwAAJTxJREFUeAHtnV92E0myxiMyS6bhPrRmBS0e5xzbWCtArKDdK2izgoZz7pjpOw+Yh+kem3sOsALcKwBWgFmB/zHnPqJewbgfhmmsysybUZLcwkiWZGVUZaXid4axLasNlqoyv4z4IgJhAQ57P3eUUhsIeAcRNvxDLf+nCYIgCIIghOTM/+kCuK518M5ae9Ru/HgAC4AwJ4dup5nZmz8A4gOQzV4QBEEQKsF5MQAOD8y5edK++WMX5mRmAUAbv7I3nyvE70EQBEEQhGhwDvbnFQIzCYBjs/vAb/yP4YsTP55ZZ9+gwgMFcNQDc9bG+VWIIAiCIAiTKaLv8F8bzrgWoOv4Pfmu66fdP8e5nTX96MksPxOn/oXu1iv/aeeznw/wDhF31vAvByAIgiAIQumcuP/dBGcf+I387qVvHeSfzP1p0YCJAuDQ/dzSTr1FwNbIw0c+9/9QNn5BEARBiINT97SDzr0cjQiQP8B8sveuEgFjBcC4zd+H+l/c0X99AIIgCIIgRMep2d2Bfrq+YJoI+EIAjNv8nTX317Mf90EQBEEQhGg5yXc3UeFLGHj2ChGA/2m3cefs8nPV5Qcyp5+Nbv6YQ1s2f0EQBEGIn/Xs0Wu/b9+Dft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s09W9aPns/zMmQQAQdGAnlU7ONJRSBAEQRCEKHidfTIPp536R5lZAAwZCgGFeHfUHyAIgiAIQpngmXXml5Vz93yejf/iv4YFOHVPO9bCBiJ5BLDlf9g3PjHQBEEQBEEQAoI+ve5+8wfvI+dT70rB0RoW03wFQRAEQRBm5/8BP0+mvgFrTN4AAAAASUVORK5CYII=";
41066
+
41067
+ // src/connector/landing-page.ts
41023
41068
  var BACKGROUND_IMAGE_ORIGIN = "https://images.gvnr.xyz";
41024
41069
  var BACKGROUND_IMAGE_URL = `${BACKGROUND_IMAGE_ORIGIN}/images/layout/backgroundCorleoneb.jpg`;
41025
41070
  var escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
@@ -41114,16 +41159,86 @@ function htmlPageSecurityHeaders(extra) {
41114
41159
  }
41115
41160
 
41116
41161
  // src/version.ts
41117
- var SERVER_VERSION = "0.5.20";
41162
+ var SERVER_VERSION = "0.5.21";
41118
41163
 
41119
41164
  // src/connector/siwe-oauth.ts
41120
- var import_node_crypto2 = require("crypto");
41165
+ var import_node_crypto3 = require("crypto");
41121
41166
  var import_ethers = require("ethers");
41122
41167
  var import_errors = require("@modelcontextprotocol/sdk/server/auth/errors.js");
41123
41168
 
41169
+ // src/util/house-style.ts
41170
+ var APP_BACKGROUND_ORIGIN = "https://images.diamondhands.credit";
41171
+ var APP_BACKGROUND_URL = `${APP_BACKGROUND_ORIGIN}/bg-diamond-hands.png`;
41172
+ var FONT_ORIGIN = "https://images.gvnr.xyz";
41173
+ var MANROPE_BASE = `${FONT_ORIGIN}/fonts/manrope`;
41174
+ var HOUSE_CSP_EXTRA = {
41175
+ "img-src": [APP_BACKGROUND_ORIGIN, "data:"],
41176
+ "font-src": [FONT_ORIGIN]
41177
+ };
41178
+ var HOUSE_HEAD_LINKS = `<link rel="icon" type="image/svg+xml" href="${FAVICON_DATA_URI}">
41179
+ <link rel="apple-touch-icon" href="${FAVICON_DATA_URI}">`;
41180
+ var MANROPE_WEIGHTS = [
41181
+ [300, "Light"],
41182
+ [400, "Regular"],
41183
+ [500, "Medium"],
41184
+ [600, "SemiBold"],
41185
+ [700, "Bold"]
41186
+ ];
41187
+ var HOUSE_BASE_CSS = `
41188
+ ${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")}
41189
+ * { box-sizing: border-box; }
41190
+ html { min-height: 100%; background: #000006; }
41191
+ body { margin: 0; min-height: 100vh; color: #fff; font: 14px/1.5 "Manrope", system-ui, -apple-system, "Segoe UI", sans-serif;
41192
+ background: #000006 url("${APP_BACKGROUND_URL}") center / cover no-repeat fixed; }
41193
+ .house-header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 1rem; }
41194
+ @media (min-width: 768px) { .house-header { padding: 1rem 2.5rem; } }
41195
+ .house-header > img { height: 1.92rem; width: auto; display: block; flex: none; }
41196
+ /* Narrow viewports: the chip may shrink (its label ellipsises), and below 400px the label
41197
+ is dropped so logo + chip icon always fit a 320px phone with no horizontal page scroll. */
41198
+ .house-header .chip { min-width: 0; }
41199
+ .chip-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
41200
+ /* ".house-header .chip", not ".chip": the base .chip rule below declares padding too, and at
41201
+ equal specificity the LATER rule wins regardless of the media query; this selector outranks it. */
41202
+ @media (max-width: 400px) { .chip-label { display: none; } .house-header .chip { padding: 0.4rem 0.6rem; } }
41203
+ .chip { display: inline-flex; align-items: center; gap: 0.45rem; padding: 0.4rem 0.85rem; border-radius: 999px;
41204
+ 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);
41205
+ font-size: 0.8rem; font-weight: 600; color: #dbff91; white-space: nowrap; }
41206
+ .chip img { height: 1rem; }
41207
+ main { max-width: 34rem; margin: 2.5rem auto 3rem; padding: 0 1rem; }
41208
+ .panel { background: #121212; border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 1rem;
41209
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05); }
41210
+ @media (min-width: 768px) { .panel { padding: 1.25rem; } }
41211
+ h1 { font-size: 1.25rem; font-weight: 600; line-height: 1.375; color: #fafafa; margin: 0 0 1rem; }
41212
+ @media (min-width: 768px) { h1 { font-size: 1.5rem; margin-bottom: 1.25rem; } }
41213
+ h2 { font-size: 1rem; font-weight: 600; line-height: 1.375; color: #fafafa; margin: 0 0 0.75rem; }
41214
+ p { margin: 0 0 1rem; color: #e5e5e5; font-size: 0.875rem; font-weight: 300; line-height: 1.5; }
41215
+ button { font: inherit; font-size: 0.875rem; cursor: pointer; border: 0; display: inline-flex; align-items: center; justify-content: center;
41216
+ min-height: 2.75rem; padding: 0.65rem 1.25rem; transition: opacity 0.2s, background-color 0.2s; }
41217
+ button:focus-visible { outline: 2px solid #84cc16; outline-offset: 2px; }
41218
+ button:disabled { opacity: 0.5; cursor: not-allowed; }
41219
+ /* Primary = lime-700 (#4d7c0f): white 14px text on it is 4.99:1 (WCAG AA needs 4.5:1; the
41220
+ brighter #65a30d was 3.09:1). Hover = lime-800 (#3f6212), 7.08:1. A test recomputes both. */
41221
+ .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); }
41222
+ .btn-primary:hover:not(:disabled) { background: #3f6212; }
41223
+ .btn-secondary { background: #34440e; color: #dbff91; font-weight: 500; border-radius: 20px; }
41224
+ .btn-secondary:hover:not(:disabled) { background: #3d5210; }
41225
+ .btn-danger { background: transparent; color: #fca5a5; font-weight: 600; border-radius: 12px; border: 1px solid rgba(248, 113, 113, 0.45); }
41226
+ .btn-danger:hover:not(:disabled) { background: rgba(220, 38, 38, 0.15); }
41227
+ /* A QR needs dark-on-light to scan: it keeps a white plate on the dark page. */
41228
+ .qr-plate { max-width: 16rem; margin-top: 1rem; background: #fff; border-radius: 12px; padding: 0.5rem; }
41229
+ .qr-plate svg { width: 100%; height: auto; display: block; }
41230
+ `;
41231
+ function houseHeader(label) {
41232
+ return `<header class="house-header">
41233
+ <img src="${GVNR_PILL_LOGO_DATA_URI}" alt="GVNR">
41234
+ <span class="chip"><img src="${FAVICON_DATA_URI}" alt=""><span class="chip-label">${label}</span></span>
41235
+ </header>`;
41236
+ }
41237
+
41124
41238
  // src/connector/siwe-page.ts
41239
+ var SIWE_PAGE_CSP_EXTRA = HOUSE_CSP_EXTRA;
41125
41240
  function renderSiwePage(opts) {
41126
- const { flowId, redirectHost, nonce } = opts;
41241
+ const { flowId, redirectHost, nonce, walletConnectEnabled } = opts;
41127
41242
  const clientName = clampClientName(opts.clientName);
41128
41243
  return `<!DOCTYPE html>
41129
41244
  <html>
@@ -41131,54 +41246,63 @@ function renderSiwePage(opts) {
41131
41246
  <meta charset="utf-8">
41132
41247
  <meta name="viewport" content="width=device-width, initial-scale=1">
41133
41248
  <title>Diamond Hands \u2014 sign in with your wallet</title>
41249
+ ${HOUSE_HEAD_LINKS}
41134
41250
  <style>
41135
- body { font-family: system-ui, sans-serif; max-width: 30rem; margin: 3rem auto; padding: 0 1rem; color: #1a1a1a; }
41136
- h1 { font-size: 1.2rem; }
41137
- button { font-size: 1rem; padding: 0.6rem 1.2rem; cursor: pointer; margin-right: 0.5rem; }
41138
- #status { margin-top: 1rem; color: #444; min-height: 1.5rem; }
41139
- .err { color: #b00020; }
41140
- .note { font-size: 0.85rem; color: #666; margin-top: 2rem; }
41251
+ ${HOUSE_BASE_CSS}
41252
+ /* \u2500\u2500 sign-in page only \u2500\u2500 */
41253
+ .actions { display: flex; flex-wrap: wrap; gap: 0.75rem; margin-top: 1.25rem; }
41254
+ #qr:empty { display: none; }
41255
+ #status { margin-top: 1rem; color: #a1a1a1; font-size: 0.875rem; font-weight: 400; }
41256
+ #status:empty, #wc-uri:empty { display: none; }
41257
+ .err { color: #f87171; }
41258
+ .note { font-size: 0.75rem; color: #a1a1a1; margin: 1.25rem 0 0; padding-top: 1rem; border-top: 1px solid rgba(255, 255, 255, 0.06); }
41141
41259
  /* "position: relative" is load-bearing, not cosmetic: it puts the consent box in its
41142
41260
  own stacking context so it paints ABOVE the inline content of the paragraph before
41143
41261
  it. Without it, a client name built from stacked combining marks overflows its line
41144
41262
  box downward and paints over this text \u2014 the CSS painting order draws every block
41145
41263
  background first, then all inline content in tree order. */
41146
- .dest { background: #fff8e1; border-left: 3px solid #c77700; padding: 0.7rem 0.9rem; font-size: 0.9rem; position: relative; }
41264
+ .dest { background: rgba(245, 158, 11, 0.12); border-left: 3px solid #f59e0b; border-radius: 0 10px 10px 0; padding: 0.75rem 0.95rem; font-size: 0.875rem; font-weight: 400; color: #f5f5f5; position: relative; }
41147
41265
  /* The destination must stay legible under a host the attacker chose the length of:
41148
41266
  "overflow-wrap: anywhere" lets it wrap mid-label (a dot is not a break opportunity),
41149
41267
  and the isolate keeps any bidi control inside from reordering the sentence around
41150
41268
  it. splitRedirectHost has already bounded the length; this bounds the geometry. */
41151
- .dest code { font-family: ui-monospace, monospace; font-size: 1rem; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; }
41152
- .dest .host-head { color: #5a5a5a; }
41153
- .dest .host-tail { font-weight: 700; color: #000; }
41269
+ .dest code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 1rem; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; }
41270
+ .dest .host-head { color: #a3a3a3; }
41271
+ .dest .host-tail { font-weight: 700; color: #fff; }
41154
41272
  /* The elision is NOT decoration \u2014 it is the page admitting it withheld characters, so
41155
41273
  it must be as visible as the text it replaced. */
41156
- .dest .host-cut { color: #c77700; font-weight: 700; font-style: normal; }
41274
+ .dest .host-cut { color: #fbbf24; font-weight: 700; font-style: normal; }
41157
41275
  /* The attacker-chosen name is clipped to a fixed box: bounded characters alone do not
41158
41276
  bound HEIGHT (combining marks stack vertically), and an isolate stops an unpaired
41159
41277
  RTL override inside the name from reversing the rest of the sentence. */
41160
- .cname { display: inline-block; max-width: 100%; max-height: 4.5em; overflow: hidden; vertical-align: bottom; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; font-weight: 700; }
41161
- #qr { max-width: 16rem; margin-top: 1rem; }
41162
- #qr svg { width: 100%; height: auto; }
41163
- #wc-uri { font-size: 0.7rem; word-break: break-all; color: #888; }
41278
+ .cname { display: inline-block; max-width: 100%; max-height: 4.5em; overflow: hidden; vertical-align: bottom; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; font-weight: 600; color: #fafafa; }
41279
+ #wc-uri { font-size: 0.7rem; word-break: break-all; color: #a1a1a1; }
41164
41280
  </style>
41165
41281
  </head>
41166
41282
  <body>
41283
+ ${houseHeader("Diamond Hands \xB7 wallet sign-in")}
41284
+ <main>
41167
41285
  <h1>Sign in to Diamond Hands</h1>
41286
+ <div class="panel">
41287
+ <h2>Connect your wallet</h2>
41168
41288
  <p><span class="cname" dir="ltr">${escapeHtml2(clientName)}</span> is asking to connect. Signing in proves you own a wallet address \u2014 it authorizes nothing on-chain and can never move funds.</p>
41169
41289
  <p class="dest">When you sign, this connection is handed to <code dir="ltr">${renderRedirectHost(redirectHost)}</code>. Anyone can register a client under any name, so read the host, not the name \u2014 and read it from the <b>bold end</b>, which is the part that decides who actually owns it. If you do not recognize it, close this page; nothing has happened yet.</p>
41170
- <button id="connect">Browser wallet</button>
41171
- <button id="wc">Mobile wallet (QR)</button>
41290
+ <div class="actions">
41291
+ <button id="connect" class="btn-primary">Browser wallet</button>
41292
+ ${walletConnectEnabled ? `<button id="wc" class="btn-secondary">Mobile wallet (QR)</button>
41293
+ ` : ""}</div>
41172
41294
  <div id="status"></div>
41173
- <div id="qr"></div>
41295
+ <div id="qr" class="qr-plate"></div>
41174
41296
  <p id="wc-uri"></p>
41175
- <p class="note">Every future operation that moves funds will still ask for its own approval in your wallet. Two ways in: a browser wallet extension on this device, or scan the QR with a mobile wallet (WalletConnect).</p>
41297
+ <p class="note">Every future operation that moves funds will still ask for its own approval in your wallet. ${walletConnectEnabled ? "Two ways in: a browser wallet extension on this device, or scan the QR with a mobile wallet (WalletConnect)." : "Sign in with a browser wallet extension on this device."}</p>
41298
+ </div>
41299
+ </main>
41176
41300
  <script nonce="${nonce}">
41177
41301
  const FLOW = ${JSON.stringify(flowId)};
41178
41302
  const statusEl = document.getElementById("status");
41179
41303
  function show(text, isErr) { statusEl.textContent = text; statusEl.className = isErr ? "err" : ""; }
41180
41304
  document.getElementById("connect").addEventListener("click", async () => {
41181
- if (!window.ethereum) { show("No browser wallet found - install a wallet extension and reload, or use the mobile QR path.", true); return; }
41305
+ if (!window.ethereum) { show(${JSON.stringify(walletConnectEnabled ? "No browser wallet found - install a wallet extension and reload, or use the mobile QR path." : "No browser wallet found - install a wallet extension and reload.")}, true); return; }
41182
41306
  try {
41183
41307
  const accounts = await window.ethereum.request({ method: "eth_requestAccounts" });
41184
41308
  const address = accounts[0];
@@ -41204,7 +41328,7 @@ document.getElementById("connect").addEventListener("click", async () => {
41204
41328
  show(e && e.code === 4001 ? "You declined in the wallet - nothing was connected." : String(e && e.message || e), true);
41205
41329
  }
41206
41330
  });
41207
- let wcPoll = null;
41331
+ ${walletConnectEnabled ? `let wcPoll = null;
41208
41332
  document.getElementById("wc").addEventListener("click", async () => {
41209
41333
  try {
41210
41334
  show("Creating a WalletConnect pairing\u2026");
@@ -41237,6 +41361,7 @@ document.getElementById("wc").addEventListener("click", async () => {
41237
41361
  show(String(e && e.message || e), true);
41238
41362
  }
41239
41363
  });
41364
+ ` : ""}
41240
41365
  </script>
41241
41366
  </body>
41242
41367
  </html>`;
@@ -41264,51 +41389,138 @@ function renderRedirectHost(host) {
41264
41389
  const cut = elided === 0 ? "" : `<span class="host-cut">\u2026+${elided} chars\u2026</span>`;
41265
41390
  return `<span class="host-head">${escapeHtml2(head)}</span>${cut}<span class="host-tail">${escapeHtml2(tail)}</span>`;
41266
41391
  }
41392
+ function redirectHostForStatement(host) {
41393
+ const { head, elided, tail } = splitRedirectHost(host);
41394
+ return elided === 0 ? `${head}${tail}` : `${head}\u2026+${elided} chars\u2026${tail}`;
41395
+ }
41267
41396
  function clampClientName(name) {
41268
41397
  const points = [...name];
41269
41398
  if (points.length <= MAX_CLIENT_NAME_CHARS) return name;
41270
41399
  return `${points.slice(0, MAX_CLIENT_NAME_CHARS - 1).join("")}\u2026`;
41271
41400
  }
41272
41401
 
41402
+ // src/connector/oauth-store.ts
41403
+ var import_node_crypto2 = require("crypto");
41404
+ function hashToken(token) {
41405
+ return (0, import_node_crypto2.createHash)("sha256").update(token, "utf8").digest("hex");
41406
+ }
41407
+ var DEFAULT_MAX_CLIENTS = 1e3;
41408
+ function memoryOAuthStateStore(opts) {
41409
+ const maxClients = opts?.maxClients ?? DEFAULT_MAX_CLIENTS;
41410
+ const clients = /* @__PURE__ */ new Map();
41411
+ const grants = /* @__PURE__ */ new Map();
41412
+ return {
41413
+ async getClient(clientId, now) {
41414
+ const entry = clients.get(clientId);
41415
+ if (!entry) return null;
41416
+ if (entry.expireAt <= now) {
41417
+ clients.delete(clientId);
41418
+ return null;
41419
+ }
41420
+ return entry.client;
41421
+ },
41422
+ async putClient(client, _now, expireAt) {
41423
+ if (!clients.has(client.client_id)) {
41424
+ while (clients.size >= maxClients) {
41425
+ let victim;
41426
+ let earliest = Infinity;
41427
+ for (const [id, entry] of clients) {
41428
+ if (entry.expireAt < earliest) {
41429
+ victim = id;
41430
+ earliest = entry.expireAt;
41431
+ }
41432
+ }
41433
+ if (victim === void 0) break;
41434
+ clients.delete(victim);
41435
+ }
41436
+ }
41437
+ clients.set(client.client_id, { client, expireAt });
41438
+ },
41439
+ async extendClient(clientId, expireAt) {
41440
+ const entry = clients.get(clientId);
41441
+ if (entry && entry.expireAt < expireAt) entry.expireAt = expireAt;
41442
+ },
41443
+ async createGrant(grant) {
41444
+ grants.set(grant.grantId, { ...grant });
41445
+ },
41446
+ async getGrant(grantId) {
41447
+ const g = grants.get(grantId);
41448
+ return g ? { ...g } : null;
41449
+ },
41450
+ async findGrantByRefreshHash(refreshHash) {
41451
+ for (const g of grants.values()) if (g.refreshHash === refreshHash) return { ...g };
41452
+ return null;
41453
+ },
41454
+ async rotateGrant(grantId, expectedHash, next) {
41455
+ const g = grants.get(grantId);
41456
+ if (!g || g.revokedAt !== null || g.refreshHash !== expectedHash) return false;
41457
+ grants.set(grantId, { ...g, ...next });
41458
+ return true;
41459
+ },
41460
+ async revokeGrant(grantId, now) {
41461
+ const g = grants.get(grantId);
41462
+ if (g && g.revokedAt === null) grants.set(grantId, { ...g, revokedAt: now });
41463
+ },
41464
+ async listGrants(address) {
41465
+ const a = address.toLowerCase();
41466
+ return [...grants.values()].filter((g) => g.address === a).map((g) => ({ ...g }));
41467
+ },
41468
+ async sweep(now) {
41469
+ for (const [id, c] of clients) if (c.expireAt <= now) clients.delete(id);
41470
+ for (const [id, g] of grants) if (g.expireAt <= now) grants.delete(id);
41471
+ }
41472
+ };
41473
+ }
41474
+
41273
41475
  // src/connector/siwe-oauth.ts
41274
41476
  var FLOW_TTL_MS = 10 * 60 * 1e3;
41275
41477
  var CODE_TTL_MS = 60 * 1e3;
41276
41478
  var ACCESS_TTL_S = 3600;
41277
41479
  var DEFAULT_REFRESH_IDLE_MS = 30 * 24 * 60 * 60 * 1e3;
41278
- var DEFAULT_MAX_CLIENTS = 1e3;
41480
+ var UNCLAIMED_CLIENT_TTL_MS = 24 * 60 * 60 * 1e3;
41481
+ var GRANT_RECHECK_MS = 30 * 1e3;
41482
+ var DEFAULT_WC_MAX_GLOBAL_PAIRINGS = 50;
41483
+ var DEFAULT_WC_MAX_PAIRINGS_PER_IP = 3;
41484
+ function resolveWcLimits(limits) {
41485
+ const maxGlobal = limits?.maxGlobal ?? DEFAULT_WC_MAX_GLOBAL_PAIRINGS;
41486
+ const maxPerIp = limits?.maxPerIp ?? DEFAULT_WC_MAX_PAIRINGS_PER_IP;
41487
+ for (const [name, v] of [["wcLimits.maxGlobal", maxGlobal], ["wcLimits.maxPerIp", maxPerIp]]) {
41488
+ if (!Number.isSafeInteger(v) || v < 1) throw new Error(`${name} must be a positive integer, got ${String(v)}`);
41489
+ }
41490
+ return { maxGlobal, maxPerIp };
41491
+ }
41279
41492
  var SiweOAuthProvider = class {
41280
41493
  constructor(opts) {
41281
41494
  this.opts = opts;
41282
41495
  this.clock = opts.clock ?? Date.now;
41283
- this.maxClients = opts.bounds?.maxClients ?? DEFAULT_MAX_CLIENTS;
41284
41496
  this.refreshIdleMs = opts.bounds?.refreshIdleMs ?? DEFAULT_REFRESH_IDLE_MS;
41497
+ const limits = resolveWcLimits(opts.wcLimits);
41498
+ this.wcMaxGlobal = limits.maxGlobal;
41499
+ this.wcMaxPerIp = limits.maxPerIp;
41500
+ this.store = opts.store ?? memoryOAuthStateStore(opts.bounds?.maxClients !== void 0 ? { maxClients: opts.bounds.maxClients } : void 0);
41285
41501
  }
41286
- clients = /* @__PURE__ */ new Map();
41287
41502
  flows = /* @__PURE__ */ new Map();
41288
41503
  codes = /* @__PURE__ */ new Map();
41289
41504
  access = /* @__PURE__ */ new Map();
41290
- refresh = /* @__PURE__ */ new Map();
41505
+ store;
41291
41506
  clock;
41292
- maxClients;
41293
41507
  refreshIdleMs;
41508
+ wcMaxGlobal;
41509
+ wcMaxPerIp;
41294
41510
  get clientsStore() {
41295
- const clients = this.clients;
41296
- const maxClients = this.maxClients;
41511
+ const store = this.store;
41512
+ const clock = this.clock;
41297
41513
  return {
41298
- getClient: (clientId) => clients.get(clientId),
41299
- registerClient: (client) => {
41514
+ getClient: async (clientId) => await store.getClient(clientId, clock()) ?? void 0,
41515
+ registerClient: async (client) => {
41300
41516
  const name = client.client_name;
41301
41517
  if (name !== void 0 && [...name].length > MAX_CLIENT_NAME_CHARS) {
41302
41518
  throw new import_errors.InvalidClientMetadataError(
41303
41519
  `client_name is ${[...name].length} characters \u2014 this authorization server displays it on a consent screen and accepts at most ${MAX_CLIENT_NAME_CHARS}`
41304
41520
  );
41305
41521
  }
41306
- while (clients.size >= maxClients) {
41307
- const oldest = clients.keys().next().value;
41308
- if (oldest === void 0) break;
41309
- clients.delete(oldest);
41310
- }
41311
- clients.set(client.client_id, client);
41522
+ const now = clock();
41523
+ await store.putClient(client, now, now + UNCLAIMED_CLIENT_TTL_MS);
41312
41524
  return client;
41313
41525
  }
41314
41526
  };
@@ -41319,10 +41531,10 @@ var SiweOAuthProvider = class {
41319
41531
  * response carries its own security headers, and the page names the redirect HOST —
41320
41532
  * the consent fact that open registration makes `client_name` unable to carry. */
41321
41533
  async authorize(client, params, res) {
41322
- this.sweep();
41323
- const flowId = (0, import_node_crypto2.randomBytes)(16).toString("hex");
41534
+ await this.sweep();
41535
+ const flowId = (0, import_node_crypto3.randomBytes)(16).toString("hex");
41324
41536
  this.flows.set(flowId, { clientId: client.client_id, params, createdAt: this.clock() });
41325
- const page = htmlPageSecurityHeaders();
41537
+ const page = htmlPageSecurityHeaders(SIWE_PAGE_CSP_EXTRA);
41326
41538
  for (const [name, value] of Object.entries(page.headers)) res.setHeader(name, value);
41327
41539
  res.setHeader(STRICT_TRANSPORT_SECURITY.name, STRICT_TRANSPORT_SECURITY.value);
41328
41540
  res.status(200).type("html").send(
@@ -41333,7 +41545,8 @@ var SiweOAuthProvider = class {
41333
41545
  // redirect_uri (SafeUrlSchema) and, for a request-supplied one, URL.canParse
41334
41546
  // plus a registered-URI match — so this constructor cannot throw here.
41335
41547
  redirectHost: new URL(params.redirectUri).host,
41336
- nonce: page.nonce
41548
+ nonce: page.nonce,
41549
+ walletConnectEnabled: this.opts.wc !== void 0
41337
41550
  })
41338
41551
  );
41339
41552
  }
@@ -41346,17 +41559,22 @@ var SiweOAuthProvider = class {
41346
41559
  if (!flow) return { ok: false, status: 404, reason: "unknown or expired sign-in flow \u2014 restart the connection from claude.ai" };
41347
41560
  if (!import_ethers.ethers.isAddress(address)) return { ok: false, status: 400, reason: "not a valid wallet address" };
41348
41561
  const checksummed = import_ethers.ethers.getAddress(address);
41349
- flow.siwe = { address: checksummed, message: this.mintSiweMessage(checksummed) };
41562
+ flow.siwe = { address: checksummed, message: this.mintSiweMessage(checksummed, flow) };
41350
41563
  return { ok: true, message: flow.siwe.message };
41351
41564
  }
41352
- mintSiweMessage(checksummedAddress) {
41565
+ /** S1-C — the statement carries the redirect HOST (bounded like the sign-in page bounds
41566
+ * it; never the attacker-chosen client name), because on the WalletConnect leg the phone
41567
+ * shows only this text and a relayed pairing QR would otherwise hide where the grant goes.
41568
+ * One line, no newline: EIP-4361 statements cannot contain one, and a URL host cannot. */
41569
+ mintSiweMessage(checksummedAddress, flow) {
41570
+ const redirectHost = redirectHostForStatement(new URL(flow.params.redirectUri).host);
41353
41571
  const origin2 = this.opts.origin();
41354
41572
  const domain = new URL(origin2).host;
41355
- const nonce = (0, import_node_crypto2.randomBytes)(8).toString("hex");
41573
+ const nonce = (0, import_node_crypto3.randomBytes)(8).toString("hex");
41356
41574
  return `${domain} wants you to sign in with your Ethereum account:
41357
41575
  ${checksummedAddress}
41358
41576
 
41359
- Connect Diamond Hands to your AI assistant. This signature only proves you own this wallet - it authorizes nothing on-chain and can never move funds.
41577
+ Connect Diamond Hands to your AI assistant. After you sign, this connection is handed to ${redirectHost}. This signature only proves you own this wallet - it authorizes nothing on-chain and can never move funds.
41360
41578
 
41361
41579
  URI: ${origin2}/authorize
41362
41580
  Version: 1
@@ -41367,12 +41585,42 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41367
41585
  /** Plan 17 A1 — start the mobile (WalletConnect) leg for a flow: one ISOLATED
41368
41586
  * transport per flow, a fresh pairing URI + QR. A re-call replaces the flow's
41369
41587
  * previous pairing (dispose first — no orphaned transports). */
41370
- async wcPairing(flowId) {
41588
+ async wcPairing(flowId, requesterIp) {
41371
41589
  const wcOpts = this.opts.wc;
41372
41590
  if (!wcOpts) return { ok: false, status: 404, reason: "mobile wallet sign-in is not enabled on this deployment" };
41373
41591
  const flow = this.liveFlow(flowId);
41374
41592
  if (!flow) return { ok: false, status: 404, reason: "unknown or expired sign-in flow \u2014 restart the connection from claude.ai" };
41593
+ if (flow.wcSetupInFlight) {
41594
+ return { ok: false, status: 409, reason: "a mobile wallet pairing for this sign-in is already being set up - wait for it to finish" };
41595
+ }
41596
+ let global2 = 0;
41597
+ let perIp = 0;
41598
+ for (const f of this.flows.values()) {
41599
+ if (f === flow || f.wcSlotIp === void 0) continue;
41600
+ global2 += 1;
41601
+ if (f.wcSlotIp === requesterIp) perIp += 1;
41602
+ }
41603
+ if (global2 >= this.wcMaxGlobal) {
41604
+ return { ok: false, status: 429, reason: `mobile wallet sign-in is at capacity (${this.wcMaxGlobal} pairings open on this server) - try again in a few minutes, or sign in with a browser wallet` };
41605
+ }
41606
+ if (perIp >= this.wcMaxPerIp) {
41607
+ return { ok: false, status: 429, reason: `too many mobile wallet sign-ins are pending from your network address (at most ${this.wcMaxPerIp} at once) - finish one, or wait up to 10 minutes for it to expire` };
41608
+ }
41375
41609
  if (flow.wc) this.disposeFlowTransport(flow);
41610
+ flow.wcSlotIp = requesterIp;
41611
+ flow.wcSetupInFlight = true;
41612
+ try {
41613
+ return await this.buildWcPairing(flowId, flow, wcOpts);
41614
+ } catch (e) {
41615
+ this.disposeFlowTransport(flow);
41616
+ throw e;
41617
+ } finally {
41618
+ delete flow.wcSetupInFlight;
41619
+ }
41620
+ }
41621
+ /** The setup steps of `wcPairing` — runs only under that method's slot reservation and
41622
+ * in-flight mark, which also own the failure cleanup. */
41623
+ async buildWcPairing(flowId, flow, wcOpts) {
41376
41624
  const factory2 = wcOpts.transportFactory ?? (async (cfg) => {
41377
41625
  const { WcTransport: WcTransport2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
41378
41626
  return WcTransport2.create(cfg);
@@ -41380,8 +41628,21 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41380
41628
  const transport = await factory2({
41381
41629
  projectId: wcOpts.projectId,
41382
41630
  chainId: this.opts.chainId,
41383
- ...wcOpts.relayUrl ? { relayUrl: wcOpts.relayUrl } : {}
41631
+ ...wcOpts.relayUrl ? { relayUrl: wcOpts.relayUrl } : {},
41632
+ // L-2: the wallet is asked to sign an EIP-4361 message whose domain is THIS origin,
41633
+ // so the dapp it is told it is talking to must be this origin too — a mismatch makes
41634
+ // domain-binding wallets warn on every honest sign-in.
41635
+ metadata: {
41636
+ name: "Diamond Hands \u2014 sign in",
41637
+ description: "Sign in to the Diamond Hands connector \u2014 proves wallet ownership, moves no funds",
41638
+ url: this.opts.origin(),
41639
+ icons: []
41640
+ }
41384
41641
  });
41642
+ if (this.flows.get(flowId) !== flow) {
41643
+ void transport.close().catch(() => void 0);
41644
+ return { ok: false, status: 404, reason: "unknown or expired sign-in flow \u2014 restart the connection from claude.ai" };
41645
+ }
41385
41646
  const record = { transport, uri: "", state: "pairing" };
41386
41647
  flow.wc = record;
41387
41648
  transport.onSession((info) => {
@@ -41424,7 +41685,7 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41424
41685
  return;
41425
41686
  }
41426
41687
  const checksummed = import_ethers.ethers.getAddress(account);
41427
- const message = this.mintSiweMessage(checksummed);
41688
+ const message = this.mintSiweMessage(checksummed, flow);
41428
41689
  flow.siwe = { address: checksummed, message };
41429
41690
  flow.wc.state = "awaiting-signature";
41430
41691
  let signature;
@@ -41451,11 +41712,12 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41451
41712
  void transport.close().catch(() => void 0);
41452
41713
  return;
41453
41714
  }
41454
- const code = (0, import_node_crypto2.randomBytes)(24).toString("hex");
41715
+ const code = (0, import_node_crypto3.randomBytes)(24).toString("hex");
41455
41716
  this.codes.set(code, {
41456
41717
  clientId: flow.clientId,
41457
41718
  address: checksummed,
41458
41719
  codeChallenge: flow.params.codeChallenge,
41720
+ redirectHost: new URL(flow.params.redirectUri).host,
41459
41721
  createdAt: this.clock()
41460
41722
  });
41461
41723
  const redirect = new URL(flow.params.redirectUri);
@@ -41497,6 +41759,7 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41497
41759
  /** Close a flow's WC transport (idempotent). `keepState` preserves the wc state
41498
41760
  * machine for the page's poll — only the TRANSPORT is released. */
41499
41761
  disposeFlowTransport(flow, keepState = false) {
41762
+ delete flow.wcSlotIp;
41500
41763
  const wc = flow.wc;
41501
41764
  if (!wc) return;
41502
41765
  void wc.transport.close().catch(() => void 0);
@@ -41518,11 +41781,12 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41518
41781
  return { ok: false, status: 401, reason: "the signature does not match the connected wallet address" };
41519
41782
  }
41520
41783
  this.deleteFlow(flowId, flow);
41521
- const code = (0, import_node_crypto2.randomBytes)(24).toString("hex");
41784
+ const code = (0, import_node_crypto3.randomBytes)(24).toString("hex");
41522
41785
  this.codes.set(code, {
41523
41786
  clientId: flow.clientId,
41524
41787
  address: flow.siwe.address,
41525
41788
  codeChallenge: flow.params.codeChallenge,
41789
+ redirectHost: new URL(flow.params.redirectUri).host,
41526
41790
  createdAt: this.clock()
41527
41791
  });
41528
41792
  const redirect = new URL(flow.params.redirectUri);
@@ -41539,28 +41803,61 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41539
41803
  const record = this.liveCode(authorizationCode);
41540
41804
  if (!record || record.clientId !== client.client_id) throw new import_errors.InvalidGrantError("unknown, expired, or foreign authorization code");
41541
41805
  this.codes.delete(authorizationCode);
41542
- return this.mintTokens(record.address, client.client_id);
41806
+ const now = this.clock();
41807
+ const refreshToken = (0, import_node_crypto3.randomBytes)(32).toString("hex");
41808
+ const grant = {
41809
+ grantId: (0, import_node_crypto3.randomBytes)(16).toString("hex"),
41810
+ address: record.address.toLowerCase(),
41811
+ clientId: client.client_id,
41812
+ clientName: client.client_name ?? null,
41813
+ redirectHost: record.redirectHost,
41814
+ createdAt: now,
41815
+ lastUsedAt: now,
41816
+ refreshHash: hashToken(refreshToken),
41817
+ revokedAt: null,
41818
+ expireAt: now + this.refreshIdleMs
41819
+ };
41820
+ await this.store.createGrant(grant);
41821
+ await this.store.extendClient(client.client_id, grant.expireAt);
41822
+ return this.mintAccess(grant, refreshToken);
41543
41823
  }
41544
41824
  async exchangeRefreshToken(client, refreshToken) {
41545
- const record = this.refresh.get(refreshToken);
41546
- if (!record || record.clientId !== client.client_id) throw new import_errors.InvalidGrantError("unknown or foreign refresh token");
41547
- if (this.clock() - record.lastUsed > this.refreshIdleMs) {
41548
- this.refresh.delete(refreshToken);
41825
+ const oldHash = hashToken(refreshToken);
41826
+ const grant = await this.store.findGrantByRefreshHash(oldHash);
41827
+ if (!grant || grant.clientId !== client.client_id) throw new import_errors.InvalidGrantError("unknown or foreign refresh token");
41828
+ if (grant.revokedAt !== null) throw new import_errors.InvalidGrantError("this connection was revoked by the wallet owner \u2014 reconnect with a fresh wallet sign-in");
41829
+ const now = this.clock();
41830
+ if (now - grant.lastUsedAt > this.refreshIdleMs) {
41549
41831
  throw new import_errors.InvalidGrantError("refresh token expired after inactivity \u2014 reconnect with a fresh wallet sign-in");
41550
41832
  }
41551
- this.refresh.delete(refreshToken);
41552
- return this.mintTokens(record.address, client.client_id);
41833
+ const nextToken = (0, import_node_crypto3.randomBytes)(32).toString("hex");
41834
+ const next = { refreshHash: hashToken(nextToken), lastUsedAt: now, expireAt: now + this.refreshIdleMs };
41835
+ await this.store.extendClient(client.client_id, next.expireAt);
41836
+ if (!await this.store.rotateGrant(grant.grantId, oldHash, next)) {
41837
+ throw new import_errors.InvalidGrantError("refresh token already used or revoked \u2014 reconnect with a fresh wallet sign-in");
41838
+ }
41839
+ return this.mintAccess({ ...grant, ...next }, nextToken);
41553
41840
  }
41554
41841
  /** SDK contract: throws InvalidTokenError on anything not live. */
41555
41842
  async verifyAccessToken(token) {
41556
- const info = this.lookupAccessToken(token);
41843
+ const info = await this.lookupAccessToken(token);
41557
41844
  if (!info) throw new import_errors.InvalidTokenError("unknown or expired access token");
41558
41845
  return info;
41559
41846
  }
41560
- /** Non-throwing lookup for the connector's own request path (null = 401). */
41561
- lookupAccessToken(token) {
41847
+ /** Non-throwing lookup for the connector's own request path (null = 401). The grant
41848
+ * behind the token is re-confirmed live when the last check is older than D6's bound. */
41849
+ async lookupAccessToken(token) {
41562
41850
  const record = this.access.get(token);
41563
- if (!record || record.expiresAt * 1e3 <= this.clock()) return null;
41851
+ const now = this.clock();
41852
+ if (!record || record.expiresAt * 1e3 <= now) return null;
41853
+ if (now - record.checkedAt > GRANT_RECHECK_MS) {
41854
+ const grant = await this.store.getGrant(record.grantId);
41855
+ if (!grant || !this.grantLive(grant, now)) {
41856
+ this.access.delete(token);
41857
+ return null;
41858
+ }
41859
+ record.checkedAt = now;
41860
+ }
41564
41861
  return {
41565
41862
  token,
41566
41863
  clientId: record.clientId,
@@ -41572,14 +41869,46 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41572
41869
  async revokeToken(client, request) {
41573
41870
  const a = this.access.get(request.token);
41574
41871
  if (a && a.clientId === client.client_id) this.access.delete(request.token);
41575
- const r = this.refresh.get(request.token);
41576
- if (r && r.clientId === client.client_id) this.refresh.delete(request.token);
41577
- }
41578
- mintTokens(address, clientId) {
41579
- const accessToken = (0, import_node_crypto2.randomBytes)(32).toString("hex");
41580
- const refreshToken = (0, import_node_crypto2.randomBytes)(32).toString("hex");
41581
- this.access.set(accessToken, { address, clientId, expiresAt: Math.floor(this.clock() / 1e3) + ACCESS_TTL_S });
41582
- this.refresh.set(refreshToken, { address, clientId, lastUsed: this.clock() });
41872
+ const grant = await this.store.findGrantByRefreshHash(hashToken(request.token));
41873
+ if (grant && grant.clientId === client.client_id) await this.revokeGrantRecord(grant.grantId);
41874
+ }
41875
+ /** Plan 18 — the account API's list: the address's LIVE grants, most recently used first. */
41876
+ async listGrants(address) {
41877
+ const now = this.clock();
41878
+ return (await this.store.listGrants(address.toLowerCase())).filter((g) => this.grantLive(g, now)).sort((x, y) => y.lastUsedAt - x.lastUsedAt).map((g) => ({
41879
+ id: g.grantId,
41880
+ clientId: g.clientId,
41881
+ clientName: g.clientName,
41882
+ redirectHost: g.redirectHost,
41883
+ createdAt: new Date(g.createdAt).toISOString(),
41884
+ lastUsedAt: new Date(g.lastUsedAt).toISOString()
41885
+ }));
41886
+ }
41887
+ /** Plan 18 — the wallet owner revokes one grant. False when the grant is unknown, not
41888
+ * live, or ANOTHER address's: the caller cannot tell those apart (no existence oracle). */
41889
+ async revokeGrantForAddress(address, grantId) {
41890
+ const grant = await this.store.getGrant(grantId);
41891
+ if (!grant || grant.address !== address.toLowerCase() || !this.grantLive(grant, this.clock())) return false;
41892
+ await this.revokeGrantRecord(grantId);
41893
+ return true;
41894
+ }
41895
+ async revokeGrantRecord(grantId) {
41896
+ await this.store.revokeGrant(grantId, this.clock());
41897
+ for (const [t, a] of this.access) if (a.grantId === grantId) this.access.delete(t);
41898
+ }
41899
+ grantLive(grant, now) {
41900
+ return grant.revokedAt === null && now - grant.lastUsedAt <= this.refreshIdleMs;
41901
+ }
41902
+ mintAccess(grant, refreshToken) {
41903
+ const accessToken = (0, import_node_crypto3.randomBytes)(32).toString("hex");
41904
+ const now = this.clock();
41905
+ this.access.set(accessToken, {
41906
+ address: grant.address,
41907
+ clientId: grant.clientId,
41908
+ grantId: grant.grantId,
41909
+ expiresAt: Math.floor(now / 1e3) + ACCESS_TTL_S,
41910
+ checkedAt: now
41911
+ });
41583
41912
  return { access_token: accessToken, token_type: "bearer", expires_in: ACCESS_TTL_S, refresh_token: refreshToken };
41584
41913
  }
41585
41914
  liveFlow(flowId) {
@@ -41601,17 +41930,53 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41601
41930
  return record;
41602
41931
  }
41603
41932
  /** Expired flows/codes/tokens are dropped opportunistically — no timers to leak. An
41604
- * expired flow's WC transport is DISPOSED with it (M17-3); idle refresh tokens die
41605
- * here too (M17-9 — nothing grows forever). */
41606
- sweep() {
41933
+ * expired flow's WC transport is DISPOSED with it (M17-3); expired clients and grants
41934
+ * leave the store here too (M17-9 — nothing grows forever). */
41935
+ async sweep() {
41607
41936
  const now = this.clock();
41608
41937
  for (const [id, f] of this.flows) if (now - f.createdAt > FLOW_TTL_MS) this.deleteFlow(id, f);
41609
41938
  for (const [c, r] of this.codes) if (now - r.createdAt > CODE_TTL_MS) this.codes.delete(c);
41610
41939
  for (const [t, a] of this.access) if (a.expiresAt * 1e3 <= now) this.access.delete(t);
41611
- for (const [t, r] of this.refresh) if (now - r.lastUsed > this.refreshIdleMs) this.refresh.delete(t);
41940
+ await this.store.sweep(now);
41612
41941
  }
41613
41942
  };
41614
41943
 
41944
+ // src/connector/wc-min-version.ts
41945
+ var WC_MIN_SAFE_VERSION = "0.5.21";
41946
+ function parseVersion(label, v) {
41947
+ const m = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.exec(v);
41948
+ if (!m) throw new Error(`${label} '${v}' is not a MAJOR.MINOR.PATCH[-prerelease] version`);
41949
+ return { core: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ? m[4].split(".") : [] };
41950
+ }
41951
+ function compareVersions(a, b) {
41952
+ for (let i = 0; i < 3; i++) {
41953
+ const d = a.core[i] - b.core[i];
41954
+ if (d !== 0) return d;
41955
+ }
41956
+ if (a.pre.length === 0 || b.pre.length === 0) return b.pre.length - a.pre.length;
41957
+ for (let i = 0; i < Math.min(a.pre.length, b.pre.length); i++) {
41958
+ const x = a.pre[i];
41959
+ const y = b.pre[i];
41960
+ if (x === y) continue;
41961
+ const xNum = /^\d+$/.test(x);
41962
+ const yNum = /^\d+$/.test(y);
41963
+ if (xNum && yNum) return Number(x) - Number(y);
41964
+ if (xNum !== yNum) return xNum ? -1 : 1;
41965
+ return x < y ? -1 : 1;
41966
+ }
41967
+ return a.pre.length - b.pre.length;
41968
+ }
41969
+ function assertWcMinSafeVersion(version2, wcArmed) {
41970
+ if (!wcArmed) return;
41971
+ const have = parseVersion("connector version", version2);
41972
+ const need = parseVersion("WC_MIN_SAFE_VERSION", WC_MIN_SAFE_VERSION);
41973
+ if (compareVersions(have, need) < 0) {
41974
+ throw new Error(
41975
+ `refusing to boot: the WalletConnect leg is armed (DH_WC_PROJECT_ID) but this connector is v${version2}, below WC_MIN_SAFE_VERSION v${WC_MIN_SAFE_VERSION} \u2014 the first release carrying the plan-19 WalletConnect fixes. Roll forward, or unset DH_WC_PROJECT_ID.`
41976
+ );
41977
+ }
41978
+ }
41979
+
41615
41980
  // src/boundary/errors.ts
41616
41981
  function boundaryError(code, message, extra) {
41617
41982
  return { code, message, ...extra?.source && { source: extra.source }, ...extra?.details && { details: extra.details } };
@@ -41835,13 +42200,14 @@ function resolveRealConfig(env) {
41835
42200
 
41836
42201
  // src/boot.ts
41837
42202
  var fs6 = __toESM(require("fs"));
41838
- var import_ethers51 = require("ethers");
42203
+ var import_ethers53 = require("ethers");
41839
42204
 
41840
42205
  // src/boundary/index.ts
41841
- var import_node_crypto9 = require("crypto");
42206
+ var import_node_crypto10 = require("crypto");
41842
42207
  var fs5 = __toESM(require("fs"));
41843
42208
  var os2 = __toESM(require("os"));
41844
42209
  var path4 = __toESM(require("path"));
42210
+ var import_ethers52 = require("ethers");
41845
42211
 
41846
42212
  // src/boundary/envelope.ts
41847
42213
  function okEnvelope(data, source, warnings = []) {
@@ -42904,7 +43270,7 @@ var DEFAULT_SEED = {
42904
43270
  };
42905
43271
 
42906
43272
  // src/boundary/upstream/mock/world.ts
42907
- var import_node_crypto3 = require("crypto");
43273
+ var import_node_crypto4 = require("crypto");
42908
43274
  var import_ethers3 = require("ethers");
42909
43275
 
42910
43276
  // src/signer/safe.ts
@@ -43108,7 +43474,7 @@ var World = class {
43108
43474
  nextId(prefix) {
43109
43475
  this.state.counter += 1;
43110
43476
  const n = this.state.counter;
43111
- const hash = (0, import_node_crypto3.createHash)("sha256").update(`${this.state.seed.namespace}:${prefix}:${n}`).digest("hex");
43477
+ const hash = (0, import_node_crypto4.createHash)("sha256").update(`${this.state.seed.namespace}:${prefix}:${n}`).digest("hex");
43112
43478
  return { n, hash };
43113
43479
  }
43114
43480
  nextTxRef() {
@@ -44059,7 +44425,7 @@ var WorldStore = class {
44059
44425
  };
44060
44426
 
44061
44427
  // src/boundary/upstream/mock/signer.ts
44062
- var import_node_crypto4 = require("crypto");
44428
+ var import_node_crypto5 = require("crypto");
44063
44429
  function mockSign(op, borrower, stance) {
44064
44430
  if (stance === "decline") {
44065
44431
  return {
@@ -44074,7 +44440,7 @@ function mockSign(op, borrower, stance) {
44074
44440
  signer: borrower,
44075
44441
  action: op.action,
44076
44442
  card: op.card,
44077
- digest: (0, import_node_crypto4.createHash)("sha256").update(`${borrower}:${op.card}`).digest("hex")
44443
+ digest: (0, import_node_crypto5.createHash)("sha256").update(`${borrower}:${op.card}`).digest("hex")
44078
44444
  }
44079
44445
  };
44080
44446
  }
@@ -44344,8 +44710,13 @@ var SignerManager = class {
44344
44710
  mode: deps.initialMode,
44345
44711
  borrower: deps.configuredBorrower ?? null
44346
44712
  };
44713
+ if (deps.authenticatedBorrower) this.state = { ...this.state, borrower: deps.authenticatedBorrower };
44347
44714
  }
44348
44715
  state;
44716
+ /** True when the borrower is the signed-in identity and cannot be swapped. */
44717
+ identityPinned() {
44718
+ return this.deps.authenticatedBorrower !== void 0;
44719
+ }
44349
44720
  mode() {
44350
44721
  return this.state.mode;
44351
44722
  }
@@ -44385,7 +44756,7 @@ var SignerManager = class {
44385
44756
  this.deps.persistence.save(this.state);
44386
44757
  }
44387
44758
  resetBorrower() {
44388
- this.state = { ...this.state, borrower: null };
44759
+ this.state = { ...this.state, borrower: this.deps.authenticatedBorrower ?? null };
44389
44760
  this.deps.persistence.save(this.state);
44390
44761
  }
44391
44762
  async use(mode, opts) {
@@ -45453,7 +45824,7 @@ var MockUpstreamPlugin = class {
45453
45824
  };
45454
45825
 
45455
45826
  // src/boundary/upstream/mock/external-ceremony.ts
45456
- var import_node_crypto5 = require("crypto");
45827
+ var import_node_crypto6 = require("crypto");
45457
45828
  var import_node_child_process = require("child_process");
45458
45829
  var import_ethers10 = require("ethers");
45459
45830
 
@@ -45700,7 +46071,7 @@ var ExternalCeremony = class {
45700
46071
  validateUnsignedTx({ ...p.tx }, p.expected, this.deps.vctx);
45701
46072
  const card = cardForTx(p.tx);
45702
46073
  const outcome = await this.request({
45703
- id: (0, import_node_crypto5.randomUUID)(),
46074
+ id: (0, import_node_crypto6.randomUUID)(),
45704
46075
  kind: "transaction",
45705
46076
  action: p.action,
45706
46077
  card,
@@ -45745,7 +46116,7 @@ var ExternalCeremony = class {
45745
46116
  message
45746
46117
  };
45747
46118
  const outcome = await this.request({
45748
- id: (0, import_node_crypto5.randomUUID)(),
46119
+ id: (0, import_node_crypto6.randomUUID)(),
45749
46120
  kind: "typed-data",
45750
46121
  action: "login",
45751
46122
  card: cardForTypedData("login", typedData),
@@ -45773,7 +46144,7 @@ var ExternalCeremony = class {
45773
46144
  });
45774
46145
  const card = cardForTypedData(p.action, typedData);
45775
46146
  const outcome = await this.request({
45776
- id: (0, import_node_crypto5.randomUUID)(),
46147
+ id: (0, import_node_crypto6.randomUUID)(),
45777
46148
  kind: "typed-data",
45778
46149
  action: p.action,
45779
46150
  card,
@@ -45948,7 +46319,7 @@ var KeystoreCeremony = class {
45948
46319
  };
45949
46320
 
45950
46321
  // src/boundary/upstream/mock/safe-ceremony.ts
45951
- var import_node_crypto6 = require("crypto");
46322
+ var import_node_crypto7 = require("crypto");
45952
46323
  var import_ethers12 = require("ethers");
45953
46324
  init_tx_validator();
45954
46325
 
@@ -46247,7 +46618,7 @@ var SafeCeremony = class {
46247
46618
  const primaryType = Object.keys(build.payload.types)[0];
46248
46619
  const outcome = await bridge.requestSignatureCollection(
46249
46620
  {
46250
- id: (0, import_node_crypto6.randomUUID)(),
46621
+ id: (0, import_node_crypto7.randomUUID)(),
46251
46622
  kind: "typed-data",
46252
46623
  action,
46253
46624
  card: build.card,
@@ -52765,11 +53136,11 @@ var init_deployment_addresses = __esm2({
52765
53136
  reason: "Shared upgrade script: AdminModule implementation update"
52766
53137
  },
52767
53138
  PositionManagerViews: {
52768
- previousImplementation: "0x1EB2B1d058006ACd9033E01e846D73eDE686b620",
52769
- newImplementation: "0xA455B542cFb36AF8451fc420dB89e590E5c87cef",
52770
- upgradedAt: "2026-07-03T20:11:25.817Z",
52771
- upgradedBy: "0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6",
52772
- reason: "Shared upgrade script: PositionManagerViews implementation update"
53139
+ previousImplementation: "0xA455B542cFb36AF8451fc420dB89e590E5c87cef",
53140
+ newImplementation: "0x8cEB3F1c07fDB3301f55b96a5B9aDb33C8d36Da3",
53141
+ upgradedAt: "2026-10-02T17:04:25.853Z",
53142
+ upgradedBy: "0x0f8f23674cc90Ef7107930a4437341fD8B460362",
53143
+ reason: "1.1.2: getBackingVaults (PoR backing set) + implementation lock (constructor)"
52773
53144
  },
52774
53145
  TestPositionManager: {
52775
53146
  previousImplementation: "0x0B46Ee1a9C6b42559758B7FF78294Cd867BB08f8",
@@ -54229,6 +54600,32 @@ var require_pkg_src2 = __commonJS2({
54229
54600
  deployedAt: 1790246264563,
54230
54601
  size: 69219,
54231
54602
  hash: "bda048d8cd6b5a39c2774bcf1320e82d1eea935c2a521006fb8b887e13b6dd8d"
54603
+ },
54604
+ carryCollateralAttestation: {
54605
+ cid: "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8",
54606
+ authorizedCidHex: cidToHex(
54607
+ "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8"
54608
+ ),
54609
+ name: "Carry Collateral Attestation",
54610
+ description: "LoanCarryVault collateral attestation (borrower, BTC vault, confirmed BTC)",
54611
+ version: "1.0.0",
54612
+ deployed: true,
54613
+ deployedAt: 1790927734070,
54614
+ size: 21156,
54615
+ hash: "05b177e0bb36b0483db4a42d33c1bbbf47eb9ef34ae278459397d51a7f8957ff"
54616
+ },
54617
+ carryFundingAttestation: {
54618
+ cid: "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W",
54619
+ authorizedCidHex: cidToHex(
54620
+ "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W"
54621
+ ),
54622
+ name: "Carry Funding Attestation",
54623
+ description: "LoanCarryVault funding attestation (Hyperliquid BTC windowed hourly average)",
54624
+ version: "1.0.0",
54625
+ deployed: true,
54626
+ deployedAt: 1790925699980,
54627
+ size: 7193,
54628
+ hash: "4944ada61610cf64b32e33b5be62087088dcf5e821040c69e67942e643ce74c9"
54232
54629
  }
54233
54630
  };
54234
54631
  function getDeploymentsForNetwork(network) {
@@ -82916,7 +83313,7 @@ var EoaDHSigner = class {
82916
83313
  };
82917
83314
 
82918
83315
  // src/signer/external-eoa.ts
82919
- var import_node_crypto7 = require("crypto");
83316
+ var import_node_crypto8 = require("crypto");
82920
83317
  var import_ethers49 = require("ethers");
82921
83318
 
82922
83319
  // src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
@@ -83010,7 +83407,7 @@ var ExternalEoaDHSigner = class {
83010
83407
  let used = { quantumTs: initialTs, fields: initial.fields };
83011
83408
  const outcome = await this.deps.bridge.requestSignature(
83012
83409
  {
83013
- id: (0, import_node_crypto7.randomUUID)(),
83410
+ id: (0, import_node_crypto8.randomUUID)(),
83014
83411
  kind: "personal-sign",
83015
83412
  action: spec.action,
83016
83413
  card: initial.card,
@@ -83044,7 +83441,7 @@ var ExternalEoaDHSigner = class {
83044
83441
  const approved = toApprovedTx(outerTx, this.deps.chainId);
83045
83442
  const gas = outerTx.gasLimit != null ? import_ethers49.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
83046
83443
  const outcome = await this.deps.bridge.requestSignature({
83047
- id: (0, import_node_crypto7.randomUUID)(),
83444
+ id: (0, import_node_crypto8.randomUUID)(),
83048
83445
  kind: "transaction",
83049
83446
  action: ctx.action,
83050
83447
  card: ctx.card,
@@ -83098,7 +83495,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers49.ether
83098
83495
  const expiresAtSec = nextQuantumTimestamp(nowMs);
83099
83496
  const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
83100
83497
  const outcome = await this.deps.bridge.requestSignature({
83101
- id: (0, import_node_crypto7.randomUUID)(),
83498
+ id: (0, import_node_crypto8.randomUUID)(),
83102
83499
  kind: "personal-sign",
83103
83500
  action: "btc-withdrawal EXECUTE step (blind hash)",
83104
83501
  card: [
@@ -83137,7 +83534,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers49.ether
83137
83534
  message: value
83138
83535
  };
83139
83536
  const outcome = await this.deps.bridge.requestSignature({
83140
- id: (0, import_node_crypto7.randomUUID)(),
83537
+ id: (0, import_node_crypto8.randomUUID)(),
83141
83538
  kind: "typed-data",
83142
83539
  action: "login",
83143
83540
  card: cardForTypedData("login", typedData),
@@ -83163,7 +83560,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers49.ether
83163
83560
  const card = cardForTx(approved);
83164
83561
  const gas = tx2.gasLimit != null ? import_ethers49.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
83165
83562
  const outcome = await this.deps.bridge.requestSignature({
83166
- id: (0, import_node_crypto7.randomUUID)(),
83563
+ id: (0, import_node_crypto8.randomUUID)(),
83167
83564
  kind: "transaction",
83168
83565
  action: describeFn(approved.data),
83169
83566
  card,
@@ -83639,7 +84036,7 @@ var RealUpstreamPlugin = class {
83639
84036
  }
83640
84037
  if (mode === "external") {
83641
84038
  const borrower = await rt.manager.resolveBorrowerForWrite();
83642
- if (!borrower) {
84039
+ if (!borrower || this.pinnedWalletUnreachable(borrower, { allowCachedLogin: false })) {
83643
84040
  return {
83644
84041
  ok: false,
83645
84042
  failure: {
@@ -83689,6 +84086,20 @@ var RealUpstreamPlugin = class {
83689
84086
  }
83690
84087
  };
83691
84088
  }
84089
+ /** Hosted tier: the SIWE borrower is bound from boot, so "bound" no longer implies a
84090
+ * wallet can sign. Refuse as "no wallet is connected" instead of starting a ceremony
84091
+ * nobody can answer.
84092
+ *
84093
+ * `allowCachedLogin` is for `connectExternal` ONLY: a still-valid lit-ops login lets it
84094
+ * succeed without a wallet (it signs nothing). A WRITE always needs a fresh wallet
84095
+ * signature (ExternalEoaDHSigner), so a cached JWT must not admit it — that would queue
84096
+ * an approval with no wallet attached to sign it. */
84097
+ pinnedWalletUnreachable(borrower, opts) {
84098
+ if (!this.runtime?.manager.identityPinned()) return false;
84099
+ if (this.runtime.bridge.walletState() !== null) return false;
84100
+ if (!opts.allowCachedLogin) return true;
84101
+ return !this.sessionCache.get(`external:${borrower.toLowerCase()}`)?.hasValidToken();
84102
+ }
83692
84103
  /** The EXPLICIT login action (plan 10 OV-10 / A0.7): the ONLY path that may summon the
83693
84104
  * wallet for a lit-ops login outside a write ceremony. Binds the borrower on success —
83694
84105
  * the first verified ceremony fixes the identity. */
@@ -83699,7 +84110,7 @@ var RealUpstreamPlugin = class {
83699
84110
  return { ok: false, reason: `the active mode is '${manager.mode()}' \u2014 run signer_setup action 'use' mode 'external' first` };
83700
84111
  }
83701
84112
  const borrower = manager.borrowerForWrite();
83702
- if (!borrower) {
84113
+ if (!borrower || this.pinnedWalletUnreachable(borrower, { allowCachedLogin: true })) {
83703
84114
  return { ok: false, reason: "no wallet is connected \u2014 open the approval page (signer_setup action 'status') and connect your wallet first" };
83704
84115
  }
83705
84116
  const key = `external:${borrower.toLowerCase()}`;
@@ -84235,7 +84646,8 @@ var RealUpstreamPlugin = class {
84235
84646
  // src/boundary/upstream/shared/external-bridge/bridge.ts
84236
84647
  var fs4 = __toESM(require("fs"));
84237
84648
  var http3 = __toESM(require("http"));
84238
- var import_node_crypto8 = require("crypto");
84649
+ var import_node_crypto9 = require("crypto");
84650
+ var import_ethers51 = require("ethers");
84239
84651
 
84240
84652
  // src/boundary/upstream/shared/external-bridge/approval-page.ts
84241
84653
  function renderApprovalPage(sessionId, nonce) {
@@ -84245,46 +84657,47 @@ function renderApprovalPage(sessionId, nonce) {
84245
84657
  <meta charset="utf-8">
84246
84658
  <meta name="viewport" content="width=device-width, initial-scale=1">
84247
84659
  <title>Diamond Hands \u2014 signature approval</title>
84660
+ ${HOUSE_HEAD_LINKS}
84248
84661
  <style>
84249
- :root { --bg:#0d1117; --panel:#161b22; --line:#30363d; --text:#e6edf3; --dim:#8b949e;
84250
- --accent:#58a6ff; --approve:#238636; --reject:#da3633; }
84251
- * { box-sizing:border-box; }
84252
- body { margin:0; font:15px/1.5 system-ui,sans-serif; background:var(--bg); color:var(--text);
84253
- display:flex; min-height:100vh; align-items:center; justify-content:center; }
84254
- main { width:min(560px,94vw); }
84255
- h1 { font-size:18px; font-weight:600; letter-spacing:.02em; }
84256
- h1 span { color:var(--accent); }
84257
- .panel { background:var(--panel); border:1px solid var(--line); border-radius:10px; padding:20px; margin-top:12px; }
84258
- .status { color:var(--dim); font-size:13px; }
84259
- .card { white-space:pre-wrap; font-family:ui-monospace,monospace; font-size:14px;
84260
- background:var(--bg); border:1px solid var(--line); border-radius:8px; padding:14px; margin:14px 0; }
84261
- .action { text-transform:uppercase; letter-spacing:.08em; font-size:12px; color:var(--accent); }
84262
- button { border:0; border-radius:8px; padding:10px 22px; font-size:15px; color:#fff; cursor:pointer; }
84263
- #approve { background:var(--approve); margin-right:10px; }
84264
- #reject { background:var(--reject); }
84265
- #wallet { font-family:ui-monospace,monospace; font-size:12px; color:var(--dim); margin-top:10px; }
84662
+ ${HOUSE_BASE_CSS}
84663
+ /* \u2500\u2500 approval page only \u2500\u2500 */
84664
+ main { max-width: 36rem; }
84665
+ .status { color:#a1a1a1; font-size:0.875rem; }
84666
+ .action { text-transform:uppercase; letter-spacing:.08em; font-size:0.75rem; font-weight:600; color:#dbff91; margin-top:0.25rem; }
84667
+ /* The decoded card IS the operation (decode-equivalence): kept monospace and pre-wrapped
84668
+ exactly as the server rendered it, on an inset well darker than the panel. */
84669
+ .card { white-space:pre-wrap; font-family:ui-monospace,SFMono-Regular,Menlo,monospace; font-size:0.875rem; color:#fafafa;
84670
+ background:#0a0a0a; border:1px solid rgba(255,255,255,0.1); border-radius:10px; padding:14px; margin:0.75rem 0 1rem; }
84671
+ .actions { display:flex; flex-wrap:wrap; gap:0.75rem; }
84672
+ #deadline { margin-bottom:1rem; }
84673
+ #wallet { font-family:ui-monospace,SFMono-Regular,Menlo,monospace; font-size:0.75rem; color:#a1a1a1; margin-top:1rem; }
84674
+ #wallet:empty { display:none; }
84675
+ #wc { margin-top:1.25rem; border-top:1px solid rgba(255,255,255,0.06); padding-top:1rem; }
84676
+ #wc-uri { user-select:all; word-break:break-all; font-size:0.75rem; }
84677
+ #wc-hint { margin-top:0.75rem; }
84266
84678
  .hidden { display:none; }
84267
84679
  </style>
84268
84680
  </head>
84269
84681
  <body>
84682
+ ${houseHeader("Diamond Hands \xB7 signature approval")}
84270
84683
  <main>
84271
- <h1><span>\u25C6</span> Diamond Hands \u2014 signature approval</h1>
84684
+ <h1>Signature approval</h1>
84272
84685
  <div class="panel">
84273
84686
  <div id="status" class="status">Connecting to your wallet\u2026</div>
84274
84687
  <div id="request" class="hidden">
84275
84688
  <div id="action" class="action"></div>
84276
84689
  <div id="card" class="card"></div>
84277
84690
  <div id="deadline" class="status hidden"></div>
84278
- <button id="approve">Approve in wallet</button>
84279
- <button id="reject">Reject</button>
84691
+ <div class="actions">
84692
+ <button id="approve" class="btn-primary">Approve in wallet</button>
84693
+ <button id="reject" class="btn-danger">Reject</button>
84694
+ </div>
84280
84695
  </div>
84281
84696
  <div id="wallet"></div>
84282
- <div id="wc" style="margin-top:14px; border-top:1px solid var(--line); padding-top:12px;">
84283
- <button id="wc-connect" style="background:var(--panel); border:1px solid var(--line); color:var(--text);">
84284
- Use a mobile wallet instead (WalletConnect)
84285
- </button>
84286
- <div id="wc-qr" class="hidden" style="background:#fff; border-radius:8px; padding:8px; margin-top:10px; max-width:280px;"></div>
84287
- <div id="wc-uri" class="card hidden" style="user-select:all; word-break:break-all; font-size:12px;"></div>
84697
+ <div id="wc">
84698
+ <button id="wc-connect" class="btn-secondary">Use a mobile wallet instead (WalletConnect)</button>
84699
+ <div id="wc-qr" class="qr-plate hidden"></div>
84700
+ <div id="wc-uri" class="card hidden"></div>
84288
84701
  <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>
84289
84702
  </div>
84290
84703
  </div>
@@ -84359,21 +84772,63 @@ async function healChain() {
84359
84772
  }).catch(() => undefined);
84360
84773
  }
84361
84774
  await readWallet();
84362
- await post(BASE + "hello", { account: account, chainId: chainId });
84775
+ await sayHello();
84363
84776
  showWallet();
84364
84777
  }
84365
84778
 
84779
+ function utf8Hex(text) {
84780
+ return "0x" + Array.from(new TextEncoder().encode(text)).map((b) => b.toString(16).padStart(2, "0")).join("");
84781
+ }
84782
+
84783
+ // Presence proof: the bridge only believes a wallet is at this page once the wallet has
84784
+ // SIGNED a short statement naming this page's origin, the chain and a per-page nonce. Saying
84785
+ // an address proves nothing (it is public); signing proves the key is here. One prompt per
84786
+ // page session: once this account has proven itself the bridge accepts later hellos for it
84787
+ // (a chain switch) without asking the wallet again.
84788
+ let provenFor = null;
84789
+ async function sayHello() {
84790
+ let signature;
84791
+ if (provenFor === null || provenFor.toLowerCase() !== String(account).toLowerCase()) {
84792
+ const ch = await fetch(BASE + "challenge?s=" + SESSION + "&chainId=" + chainId).then((r) => r.json());
84793
+ showIdleStatus("Sign the short statement in your wallet to prove it is yours \u2014 it moves no funds.");
84794
+ signature = await window.ethereum.request({ method: "personal_sign", params: [utf8Hex(ch.statement), account] });
84795
+ }
84796
+ const r = await post(BASE + "hello", { account: account, chainId: chainId, signature: signature });
84797
+ if (!r.ok) {
84798
+ const b = await r.json().catch(() => ({}));
84799
+ showStatus("This wallet was not accepted: " + (b.error || "HTTP " + r.status));
84800
+ return false;
84801
+ }
84802
+ provenFor = account;
84803
+ return true;
84804
+ }
84805
+
84806
+ // The stream opens at load, so a card can be on screen BEFORE connect() finishes. The status
84807
+ // line then belongs to that card (its review / mobile-wallet guidance), and connection
84808
+ // progress must not overwrite it. Connection progress lines (idle / "sign the statement", whose
84809
+ // wallet popup is self-explanatory) go through here; failures (a refused hello, a lost
84810
+ // stream, a wrong network) still show unconditionally.
84811
+ function showIdleStatus(text) {
84812
+ if (current !== null) return;
84813
+ showStatus(text);
84814
+ }
84815
+
84366
84816
  async function connect() {
84367
- if (!window.ethereum) { showStatus("No wallet detected \u2014 install MetaMask (or open this page in a wallet browser)."); return; }
84817
+ if (!window.ethereum) {
84818
+ // The event stream is already open (see the bottom of this script) \u2014 a phone paired
84819
+ // below still mirrors its cards here.
84820
+ showIdleStatus("No browser wallet detected \u2014 use the mobile wallet option below, or install MetaMask (or open this page in a wallet browser).");
84821
+ return;
84822
+ }
84368
84823
  await window.ethereum.request({ method: "eth_requestAccounts" });
84369
84824
  await readWallet();
84370
- await post(BASE + "hello", { account: account, chainId: chainId });
84825
+ const accepted = await sayHello();
84371
84826
  showWallet();
84372
84827
  window.ethereum.on("accountsChanged", onAccountsChanged);
84373
84828
  window.ethereum.on("chainChanged", onChainChanged);
84829
+ if (!accepted) return;
84374
84830
  await healChain();
84375
- showStatus("Connected. Waiting for a signature request\u2026");
84376
- listen();
84831
+ showIdleStatus("Connected. Waiting for a signature request\u2026");
84377
84832
  }
84378
84833
 
84379
84834
  // Handlers trust the EVENT payloads \u2014 re-reading eth_accounts/eth_chainId here races the
@@ -84383,6 +84838,8 @@ async function onAccountsChanged(accounts) {
84383
84838
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
84384
84839
  showWallet();
84385
84840
  invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
84841
+ // The bridge adopts no account from an event alone \u2014 a different account proves itself.
84842
+ if (account) await sayHello();
84386
84843
  }
84387
84844
 
84388
84845
  async function onChainChanged(cid) {
@@ -84392,8 +84849,14 @@ async function onChainChanged(cid) {
84392
84849
  invalidatePageRequests("Network changed \u2014 pending request invalidated.");
84393
84850
  }
84394
84851
 
84852
+ // ONE stream per page, opened at load whatever wallet this browser has: a phone paired
84853
+ // through WalletConnect needs no injected wallet, and its read-only mirror arrives on this
84854
+ // stream. Opening it proves nothing \u2014 the bridge sends this page NOTHING until a person is
84855
+ // proven (a signed hello, or a pairing a phone answered).
84856
+ let es = null;
84395
84857
  function listen() {
84396
- const es = new EventSource(BASE + "events?s=" + SESSION);
84858
+ if (es !== null) return;
84859
+ es = new EventSource(BASE + "events?s=" + SESSION);
84397
84860
  es.onmessage = (ev) => {
84398
84861
  const next = JSON.parse(ev.data);
84399
84862
  // A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
@@ -84585,6 +85048,7 @@ document.getElementById("wc-connect").onclick = async () => {
84585
85048
  showStatus("Scan the QR (or paste the code) in your mobile wallet \u2014 it becomes the signing wallet.");
84586
85049
  };
84587
85050
 
85051
+ listen();
84588
85052
  connect();
84589
85053
  </script>
84590
85054
  </body>
@@ -84665,6 +85129,16 @@ document.getElementById("generate").onclick = () => submit(true);
84665
85129
 
84666
85130
  // src/boundary/upstream/shared/external-bridge/bridge.ts
84667
85131
  var MAX_SESSIONS = 16;
85132
+ var MAX_PENDING_PAIRINGS = 64;
85133
+ function presenceStatement(origin2, chainId, nonce) {
85134
+ return [
85135
+ "Diamond Hands approval page",
85136
+ "Sign to prove this wallet is yours. This moves no funds and approves no operation.",
85137
+ `Origin: ${origin2}`,
85138
+ `Chain ID: ${chainId}`,
85139
+ `Session nonce: ${nonce}`
85140
+ ].join("\n");
85141
+ }
84668
85142
  var DEFAULT_EXPIRY_MS = 5 * 60 * 1e3;
84669
85143
  var DEFAULT_ATTACH_GRACE_MS = 60 * 1e3;
84670
85144
  var DEFAULT_HOSTED_ATTACH_GRACE_MS = 180 * 1e3;
@@ -84678,6 +85152,7 @@ function wcDeclineOrFault(e) {
84678
85152
  }
84679
85153
  var SignatureBridge = class {
84680
85154
  clock;
85155
+ sweepIntervalMs;
84681
85156
  /** Lowercased at construction so every comparison is case-flat — EIP-55 checksum casing
84682
85157
  * differs between what SIWE signs and what a wallet reports for the SAME address. */
84683
85158
  boundAccount;
@@ -84690,7 +85165,7 @@ var SignatureBridge = class {
84690
85165
  /** Started state independent of the transport binding (mounted bridges own no server). */
84691
85166
  started = false;
84692
85167
  mount;
84693
- token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
85168
+ token = (0, import_node_crypto9.randomBytes)(24).toString("hex");
84694
85169
  /** Hosted mounts: when the current page token was minted (rotation basis). */
84695
85170
  tokenMintedAt = 0;
84696
85171
  /** Ceremony-scoped link (plan 06 §1.5): the SAME URL is multi-visit and multi-owner —
@@ -84708,13 +85183,20 @@ var SignatureBridge = class {
84708
85183
  wcTransport = null;
84709
85184
  /** True while a WalletConnect session is THE wallet — ceremonies route over WC. */
84710
85185
  wcActive = false;
84711
- /** Page session that most recently asked for a pairing QR — see `serveWcPairing`. */
84712
- pairingSessionId = null;
85186
+ /** Which page session asked for which pairing (pairing id → session id). The transport's
85187
+ * `onSession` says WHICH PAIRING a phone answered; this says whose it was. The previous
85188
+ * "most recent asker" guess let a second session claim the credit for a QR the user's
85189
+ * phone scanned (Sentinel 2 PoC-B). */
85190
+ pairingOwners = /* @__PURE__ */ new Map();
84713
85191
  keystoreUnlock;
84714
85192
  unlockToken = null;
84715
85193
  unlockSession = null;
84716
85194
  constructor(opts) {
84717
85195
  this.clock = opts?.clock ?? Date.now;
85196
+ this.sweepIntervalMs = opts?.sweepIntervalMs ?? 1e3;
85197
+ if (!Number.isInteger(this.sweepIntervalMs) || this.sweepIntervalMs < 0) {
85198
+ throw new Error(`bridge sweepIntervalMs must be a non-negative integer (got ${String(opts?.sweepIntervalMs)})`);
85199
+ }
84718
85200
  this.boundAccount = opts?.boundAccount?.toLowerCase();
84719
85201
  this.expiryMs = opts?.expiryMs ?? DEFAULT_EXPIRY_MS;
84720
85202
  this.maxPending = opts?.maxPending ?? null;
@@ -84730,7 +85212,7 @@ var SignatureBridge = class {
84730
85212
  unlockUrl() {
84731
85213
  if (!this.started) throw new Error("bridge is not started");
84732
85214
  if (!this.keystoreUnlock) throw new Error("keystore unlock is not wired on this bridge");
84733
- this.unlockToken = (0, import_node_crypto8.randomBytes)(24).toString("hex");
85215
+ this.unlockToken = (0, import_node_crypto9.randomBytes)(24).toString("hex");
84734
85216
  return this.mount ? `${this.mount.baseUrl}/unlock?t=${this.unlockToken}` : `http://127.0.0.1:${this.port}/unlock?t=${this.unlockToken}`;
84735
85217
  }
84736
85218
  /** Idempotent — the bridge spawns on the first write that needs it (plan 04 §2).
@@ -84750,8 +85232,10 @@ var SignatureBridge = class {
84750
85232
  this.server = server;
84751
85233
  }
84752
85234
  this.started = true;
84753
- this.sweepTimer = setInterval(() => this.sweep(), 1e3);
84754
- this.sweepTimer.unref();
85235
+ if (this.sweepIntervalMs > 0) {
85236
+ this.sweepTimer = setInterval(() => this.sweep(), this.sweepIntervalMs);
85237
+ this.sweepTimer.unref();
85238
+ }
84755
85239
  if (this.urlFile) fs4.writeFileSync(this.urlFile, this.url());
84756
85240
  }
84757
85241
  /** Plan 12 C1: the outer server's dispatch entry for a MOUNTED bridge — `req.url`
@@ -84771,7 +85255,7 @@ var SignatureBridge = class {
84771
85255
  if (this.mount) {
84772
85256
  const now = this.clock();
84773
85257
  if (this.tokenMintedAt === 0 || now - this.tokenMintedAt > HOSTED_PAGE_TOKEN_TTL_MS) {
84774
- this.token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
85258
+ this.token = (0, import_node_crypto9.randomBytes)(24).toString("hex");
84775
85259
  this.tokenMintedAt = now;
84776
85260
  }
84777
85261
  return `${this.mount.baseUrl}/?t=${this.token}`;
@@ -84811,6 +85295,16 @@ var SignatureBridge = class {
84811
85295
  pendingCount() {
84812
85296
  return this.pending.size;
84813
85297
  }
85298
+ /** A request lives for the bridge's expiry OR until its payload dies, whichever is first.
85299
+ * The BTC-withdraw execute leg's payload dies inside a sub-minute quantum window; holding
85300
+ * the ceremony open for the full five minutes kept a dead card on screen and let the phone
85301
+ * be asked to sign something the protocol would refuse. */
85302
+ deadlineFor(request, nowMs) {
85303
+ const bridgeDeadline = nowMs + this.expiryMs;
85304
+ if (request.expiresAtSec === void 0) return bridgeDeadline;
85305
+ if (!Number.isFinite(request.expiresAtSec)) throw new Error(`request ${request.id} carries a non-finite expiresAtSec`);
85306
+ return Math.min(bridgeDeadline, request.expiresAtSec * 1e3);
85307
+ }
84814
85308
  /**
84815
85309
  * Enqueue a request and resolve on the human's decision (or expiry/invalidation).
84816
85310
  * Chain-id mismatch with an already-connected wallet refuses BEFORE the wallet is asked.
@@ -84833,7 +85327,7 @@ var SignatureBridge = class {
84833
85327
  const now = this.clock();
84834
85328
  const entry = {
84835
85329
  request,
84836
- deadlineMs: now + this.expiryMs,
85330
+ deadlineMs: this.deadlineFor(request, now),
84837
85331
  enqueuedMs: now,
84838
85332
  resolve,
84839
85333
  settled: false,
@@ -84864,7 +85358,7 @@ var SignatureBridge = class {
84864
85358
  const now = this.clock();
84865
85359
  const entry = {
84866
85360
  request,
84867
- deadlineMs: now + this.expiryMs,
85361
+ deadlineMs: this.deadlineFor(request, now),
84868
85362
  enqueuedMs: now,
84869
85363
  resolve,
84870
85364
  settled: false,
@@ -84916,6 +85410,7 @@ var SignatureBridge = class {
84916
85410
  return;
84917
85411
  }
84918
85412
  try {
85413
+ if (this.expireIfOverdue(entry)) return;
84919
85414
  if (req.kind === "transaction") {
84920
85415
  this.pushEntry(entry);
84921
85416
  const tx2 = req.tx;
@@ -84927,15 +85422,23 @@ var SignatureBridge = class {
84927
85422
  } else if (req.kind === "personal-sign") {
84928
85423
  if (entry.finalize) {
84929
85424
  const fresh = await entry.finalize();
85425
+ if (entry.settled) return;
85426
+ if (entry.owner !== "wc") return;
85427
+ const live = transport.active();
85428
+ if (!this.wcActive || !live || live.account.toLowerCase() !== account.toLowerCase()) {
85429
+ this.settle(entry, {
85430
+ status: "invalidated",
85431
+ reason: "the WalletConnect wallet changed while this payload was being prepared \u2014 the phone was not asked. Reconnect your wallet and retry the operation."
85432
+ });
85433
+ return;
85434
+ }
84930
85435
  req.personalSign = fresh.personalSign;
84931
85436
  req.card = fresh.card;
84932
85437
  }
85438
+ if (this.expireIfOverdue(entry)) return;
84933
85439
  const ps = req.personalSign;
84934
- if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
84935
- this.settle(entry, {
84936
- status: "invalidated",
84937
- 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)`
84938
- });
85440
+ if (!this.pageAttached()) {
85441
+ this.settle(entry, { status: "invalidated", reason: this.noPageReason(ps.layout === RAW_HASH_LAYOUT) });
84939
85442
  return;
84940
85443
  }
84941
85444
  this.pushEntry(entry);
@@ -84960,6 +85463,16 @@ var SignatureBridge = class {
84960
85463
  }
84961
85464
  }
84962
85465
  }
85466
+ /** Refusal for a WalletConnect personal_sign with no proven approval page attached.
85467
+ *
85468
+ * The remedy names BOTH halves, because opening the link alone does not fix it: a freshly
85469
+ * opened page is a stranger until a phone answers a pairing it showed (or its wallet signs
85470
+ * the presence statement), so it receives no card. Following "just reopen the URL" looped
85471
+ * (Sentinel 2 PoC-C). */
85472
+ noPageReason(blindHash) {
85473
+ 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";
85474
+ 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)`;
85475
+ }
84963
85476
  /** A live attachment that could still decide a request: an open approval-page SSE
84964
85477
  * stream (real page or headless driver) or an active WalletConnect session. PUBLIC
84965
85478
  * (plan 17 E1): the connector's idle-eviction predicate reads it — a tenant world
@@ -85037,12 +85550,13 @@ var SignatureBridge = class {
85037
85550
  this.server = null;
85038
85551
  this.started = false;
85039
85552
  this.wallet = null;
85040
- this.token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
85553
+ this.token = (0, import_node_crypto9.randomBytes)(24).toString("hex");
85041
85554
  this.tokenMintedAt = 0;
85042
85555
  if (this.urlFile) fs4.rmSync(this.urlFile, { force: true });
85043
85556
  void this.wcTransport?.close().catch(() => void 0);
85044
85557
  this.wcTransport = null;
85045
85558
  this.wcActive = false;
85559
+ this.pairingOwners.clear();
85046
85560
  }
85047
85561
  // ---- HTTP plumbing ----
85048
85562
  route(req, res) {
@@ -85050,6 +85564,7 @@ var SignatureBridge = class {
85050
85564
  const url2 = new URL(req.url ?? "/", this.mount ? this.mount.origin : `http://127.0.0.1:${this.port}`);
85051
85565
  if (req.method === "GET" && url2.pathname === "/") return this.servePage(url2, res);
85052
85566
  if (req.method === "GET" && url2.pathname === "/config") return this.serveConfig(url2, res);
85567
+ if (req.method === "GET" && url2.pathname === "/challenge") return this.serveChallenge(url2, res);
85053
85568
  if (req.method === "GET" && url2.pathname === "/wc-pairing") return void this.serveWcPairing(url2, res);
85054
85569
  if (req.method === "GET" && url2.pathname === "/unlock") return this.serveUnlockPage(url2, res);
85055
85570
  if (req.method === "POST" && url2.pathname === "/unlock-submit")
@@ -85108,9 +85623,17 @@ var SignatureBridge = class {
85108
85623
  this.deny(res, 429, `too many open approval pages (${MAX_SESSIONS}) \u2014 close one and retry`);
85109
85624
  return;
85110
85625
  }
85111
- const sessionId = (0, import_node_crypto8.randomBytes)(24).toString("hex");
85112
- this.sessions.set(sessionId, { wallet: null, sse: null, refused: null, lastSeenMs: this.clock(), wcPaired: false });
85113
- const page = htmlPageSecurityHeaders();
85626
+ const sessionId = (0, import_node_crypto9.randomBytes)(24).toString("hex");
85627
+ this.sessions.set(sessionId, {
85628
+ wallet: null,
85629
+ sse: null,
85630
+ refused: null,
85631
+ lastSeenMs: this.clock(),
85632
+ wcPaired: false,
85633
+ presenceNonce: (0, import_node_crypto9.randomBytes)(16).toString("hex"),
85634
+ provenAccount: null
85635
+ });
85636
+ const page = htmlPageSecurityHeaders(HOUSE_CSP_EXTRA);
85114
85637
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
85115
85638
  res.end(renderApprovalPage(sessionId, page.nonce));
85116
85639
  }
@@ -85120,11 +85643,29 @@ var SignatureBridge = class {
85120
85643
  res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
85121
85644
  res.end(JSON.stringify({ network: this.network ?? null }));
85122
85645
  }
85646
+ /** The origin this bridge is served from — what a presence statement names. */
85647
+ publicOrigin() {
85648
+ return this.mount ? this.mount.origin : `http://127.0.0.1:${this.port}`;
85649
+ }
85650
+ /** The presence statement for this session + chain (session-gated). The page signs exactly
85651
+ * this text in its wallet; the bridge rebuilds it on `hello` rather than trusting any text
85652
+ * the client sends back. */
85653
+ serveChallenge(url2, res) {
85654
+ const session = this.sessionOf(url2.searchParams.get("s"), res);
85655
+ if (!session) return;
85656
+ const chainId = Number(url2.searchParams.get("chainId"));
85657
+ if (!Number.isInteger(chainId)) {
85658
+ this.deny(res, 400, "challenge requires an integer chainId");
85659
+ return;
85660
+ }
85661
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
85662
+ res.end(JSON.stringify({ statement: presenceStatement(this.publicOrigin(), chainId, session.presenceNonce) }));
85663
+ }
85123
85664
  /** WalletConnect pairing (D2, session-gated): lazily boots the WC transport and serves a
85124
85665
  * fresh pairing URI. A wallet approving the pairing becomes THE wallet. */
85125
85666
  async serveWcPairing(url2, res) {
85126
85667
  if (!this.checkSession(url2.searchParams.get("s"), res)) return;
85127
- this.pairingSessionId = url2.searchParams.get("s");
85668
+ const askingSession = url2.searchParams.get("s");
85128
85669
  if (!this.wcConfig) {
85129
85670
  this.deny(res, 404, "WalletConnect is not configured (set DH_WC_PROJECT_ID)");
85130
85671
  return;
@@ -85139,17 +85680,20 @@ var SignatureBridge = class {
85139
85680
  this.wcTransport.onSession((info) => {
85140
85681
  const refusal = info ? this.accountRefusal(info.account) : null;
85141
85682
  if (info && refusal) {
85142
- this.wcActive = false;
85143
- this.rebuildSharedWallet();
85144
- this.demoteWcEntries();
85683
+ if (!this.wcActive) {
85684
+ this.rebuildSharedWallet();
85685
+ this.demoteWcEntries();
85686
+ }
85145
85687
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
85146
85688
  `);
85147
- return;
85689
+ return false;
85148
85690
  }
85149
85691
  this.wcActive = info !== null;
85150
85692
  this.wallet = info ? { account: info.account, chainId: info.chainId } : null;
85151
- if (info && this.pairingSessionId) {
85152
- const paired = this.sessions.get(this.pairingSessionId);
85693
+ if (info?.pairingId) {
85694
+ const owner = this.pairingOwners.get(info.pairingId);
85695
+ this.pairingOwners.delete(info.pairingId);
85696
+ const paired = owner ? this.sessions.get(owner) : void 0;
85153
85697
  if (paired) paired.wcPaired = true;
85154
85698
  }
85155
85699
  if (info === null) {
@@ -85164,7 +85708,15 @@ var SignatureBridge = class {
85164
85708
  }
85165
85709
  });
85166
85710
  }
85167
- const { uri } = await this.wcTransport.createPairing();
85711
+ const { uri, pairingId } = await this.wcTransport.createPairing();
85712
+ if (pairingId) {
85713
+ this.pairingOwners.set(pairingId, askingSession);
85714
+ while (this.pairingOwners.size > MAX_PENDING_PAIRINGS) {
85715
+ const oldest = this.pairingOwners.keys().next();
85716
+ if (oldest.done) break;
85717
+ this.pairingOwners.delete(oldest.value);
85718
+ }
85719
+ }
85168
85720
  const { default: qrcode } = await import("qrcode-generator");
85169
85721
  const qr = qrcode(0, "M");
85170
85722
  qr.addData(uri);
@@ -85189,7 +85741,7 @@ var SignatureBridge = class {
85189
85741
  return;
85190
85742
  }
85191
85743
  this.unlockToken = null;
85192
- this.unlockSession = (0, import_node_crypto8.randomBytes)(24).toString("hex");
85744
+ this.unlockSession = (0, import_node_crypto9.randomBytes)(24).toString("hex");
85193
85745
  const page = htmlPageSecurityHeaders();
85194
85746
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
85195
85747
  res.end(renderUnlockPage(this.unlockSession, page.nonce));
@@ -85252,6 +85804,34 @@ var SignatureBridge = class {
85252
85804
  this.deny(res, 403, refusal);
85253
85805
  return;
85254
85806
  }
85807
+ const alreadyProven = session.provenAccount !== null && session.provenAccount.toLowerCase() === account.toLowerCase();
85808
+ if (!alreadyProven) {
85809
+ const signature = body["signature"];
85810
+ if (typeof signature !== "string" || signature === "") {
85811
+ this.deny(
85812
+ res,
85813
+ 403,
85814
+ `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.`
85815
+ );
85816
+ return;
85817
+ }
85818
+ const statement = presenceStatement(this.publicOrigin(), chainId, session.presenceNonce);
85819
+ let recovered = null;
85820
+ try {
85821
+ recovered = import_ethers51.ethers.verifyMessage(statement, signature);
85822
+ } catch {
85823
+ recovered = null;
85824
+ }
85825
+ if (recovered === null || recovered.toLowerCase() !== account.toLowerCase()) {
85826
+ this.deny(
85827
+ res,
85828
+ 403,
85829
+ `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).`
85830
+ );
85831
+ return;
85832
+ }
85833
+ session.provenAccount = account;
85834
+ }
85255
85835
  session.wallet = { account, chainId };
85256
85836
  this.wallet = { account, chainId };
85257
85837
  this.replayPending(session);
@@ -85293,17 +85873,21 @@ var SignatureBridge = class {
85293
85873
  if (refusedSwitch) {
85294
85874
  this.quarantine(session, switchRefusal);
85295
85875
  } else {
85296
- session.wallet = offered;
85876
+ const sameProven = offered !== null && session.provenAccount !== null && offered.account.toLowerCase() === session.provenAccount.toLowerCase();
85877
+ session.wallet = sameProven ? offered : null;
85297
85878
  if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
85298
85879
  this.wallet = session.wallet;
85880
+ } else if (this.wallet === null && prev === null && session.wallet !== null) {
85881
+ this.wallet = session.wallet;
85299
85882
  }
85300
85883
  }
85301
- const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
85302
- if (unchanged) {
85884
+ const reported = refusedSwitch ? null : offered;
85885
+ const unchanged = prev !== null && reported !== null && prev.account.toLowerCase() === reported.account.toLowerCase() && prev.chainId === reported.chainId;
85886
+ if (unchanged || prev === null) {
85303
85887
  this.ok(res);
85304
85888
  return;
85305
85889
  }
85306
- 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";
85890
+ 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";
85307
85891
  for (const entry of this.pending.values()) {
85308
85892
  if (entry.settled || entry.collect) continue;
85309
85893
  if (this.ownedByWc(entry)) continue;
@@ -85346,6 +85930,10 @@ var SignatureBridge = class {
85346
85930
  this.deny(res, 404, "unknown or already-settled requestId");
85347
85931
  return;
85348
85932
  }
85933
+ if (this.expireIfOverdue(entry)) {
85934
+ this.deny(res, 410, "this request has expired \u2014 retry the operation");
85935
+ return;
85936
+ }
85349
85937
  if (entry.request.kind !== "personal-sign") {
85350
85938
  this.deny(res, 400, "finalize applies only to personal-sign requests");
85351
85939
  return;
@@ -85372,6 +85960,10 @@ var SignatureBridge = class {
85372
85960
  this.deny(res, 404, "request settled while finalizing");
85373
85961
  return;
85374
85962
  }
85963
+ if (this.expireIfOverdue(entry)) {
85964
+ this.deny(res, 410, "this request expired while its payload was being prepared \u2014 retry the operation");
85965
+ return;
85966
+ }
85375
85967
  entry.request.personalSign = fresh.personalSign;
85376
85968
  entry.request.card = fresh.card;
85377
85969
  }
@@ -85385,6 +85977,10 @@ var SignatureBridge = class {
85385
85977
  this.deny(res, 404, "unknown or already-settled requestId");
85386
85978
  return;
85387
85979
  }
85980
+ if (this.expireIfOverdue(entry)) {
85981
+ this.deny(res, 410, "this request has expired \u2014 retry the operation");
85982
+ return;
85983
+ }
85388
85984
  if (body["approved"] !== true) {
85389
85985
  if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
85390
85986
  this.settle(entry, {
@@ -85433,6 +86029,16 @@ var SignatureBridge = class {
85433
86029
  this.ok(res);
85434
86030
  }
85435
86031
  // ---- helpers ----
86032
+ /** Accept-time deadline check. The 1 s sweep is only the backstop: between the deadline and
86033
+ * the next tick a late click on /finalize or /result — or a WalletConnect dispatch — would
86034
+ * otherwise still ask for or accept a signature over a payload the protocol will refuse.
86035
+ * Settles the entry `expired` (the same outcome the sweep gives) and reports it. */
86036
+ expireIfOverdue(entry) {
86037
+ if (entry.settled) return true;
86038
+ if (this.clock() < entry.deadlineMs) return false;
86039
+ this.settle(entry, { status: "expired" });
86040
+ return true;
86041
+ }
85436
86042
  settle(entry, outcome) {
85437
86043
  entry.settled = true;
85438
86044
  this.pending.delete(entry.request.id);
@@ -85651,7 +86257,7 @@ function createBoundary(config, opts) {
85651
86257
  "createBoundary(real) is async \u2014 use createRealBoundary() so the write SDK can be built."
85652
86258
  );
85653
86259
  }
85654
- const configFingerprint = (0, import_node_crypto9.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
86260
+ const configFingerprint = (0, import_node_crypto10.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
85655
86261
  if (opts?.ceremony) {
85656
86262
  const plugin2 = new MockUpstreamPlugin(config, { ceremony: opts.ceremony });
85657
86263
  const boundary2 = new BoundaryCore({
@@ -85814,6 +86420,7 @@ async function createRealBoundary(config, wallet, overrides) {
85814
86420
  const manager = new SignerManager({
85815
86421
  persistence: overrides?.signerPersistence?.(config.network) ?? fileSignerPersistence(stateFile),
85816
86422
  initialMode,
86423
+ ...overrides?.boundBorrower ? { authenticatedBorrower: import_ethers52.ethers.getAddress(overrides.boundBorrower) } : {},
85817
86424
  candidate: () => bridge.walletState()?.account ?? null,
85818
86425
  pendingCeremonies: () => bridge.pendingCount(),
85819
86426
  keystore
@@ -85825,7 +86432,7 @@ async function createRealBoundary(config, wallet, overrides) {
85825
86432
  }
85826
86433
  const plugin = new RealUpstreamPlugin(config, wallet, { manager, bridge, keystore });
85827
86434
  await plugin.initWriteSdk();
85828
- const configFingerprint = (0, import_node_crypto9.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
86435
+ const configFingerprint = (0, import_node_crypto10.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
85829
86436
  const capabilities = () => ({
85830
86437
  reads: {
85831
86438
  public: true,
@@ -85909,8 +86516,8 @@ async function buildBoundary(configResult, overrides) {
85909
86516
  );
85910
86517
  }
85911
86518
  try {
85912
- const decrypted = await import_ethers51.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
85913
- if (!(decrypted instanceof import_ethers51.ethers.Wallet)) {
86519
+ const decrypted = await import_ethers53.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
86520
+ if (!(decrypted instanceof import_ethers53.ethers.Wallet)) {
85914
86521
  return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
85915
86522
  }
85916
86523
  wallet = decrypted;
@@ -86390,7 +86997,7 @@ on the real adapter and the mock.
86390
86997
  **The walkthrough:**
86391
86998
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
86392
86999
  desktop browser; ${approvalPageLocation(d)}
86393
- 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. KEEP THE APPROVAL PAGE OPEN: while a\n phone wallet is connected the page becomes the READ-ONLY reader for every ceremony \u2014\n it shows the full card, the phone shows only what a wallet can render, and you approve\n or decline in the phone. (Cancel still works from the page.)" : ". " + phoneWalletOffer(d) + "."}
87000
+ 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. KEEP THAT APPROVAL PAGE OPEN \u2014 the one\n whose QR you scanned: while a phone wallet is connected it is the READ-ONLY reader for\n every ceremony \u2014 it shows the full card, the phone shows only what a wallet can render,\n and you approve or decline in the phone. (Cancel still works from the page.) With no\n such page open, the phone is NOT asked to sign the opaque 32-byte hashes (loan and withdrawal\n envelopes) \u2014 those refuse, because a wallet shows them as a bare hash. Plain transactions and\n typed-data are not gated: the wallet decodes those itself." : ". " + phoneWalletOffer(d) + "."}
86394
87001
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
86395
87002
  login ceremony explicitly (one typed-data signature in the wallet).
86396
87003
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -86778,7 +87385,9 @@ plus one lit-ops login signature (read access). After that, every operation that
86778
87385
  funds asks for its OWN approval in the user's wallet, every time \u2014 and reads never pop
86779
87386
  the wallet. The login session lives ONLY in the server's memory: a server restart, or
86780
87387
  an idle spell long enough that the tenant's world is evicted, means signing in again.
86781
- That is the flip side of "nothing stored at rest" \u2014 a re-login is normal, not a fault.
87388
+ That is the flip side of never storing a login session at rest \u2014 a re-login is normal,
87389
+ not a fault. (The connector's own sign-in is a separate grant; /auth.md states whether
87390
+ this deployment keeps it across restarts.)
86782
87391
 
86783
87392
  **What the hosted server IS trusted with** (the six residual trusts \u2014 state them
86784
87393
  honestly when asked "is this safe"):
@@ -87047,7 +87656,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
87047
87656
 
87048
87657
  // src/tools/loan.ts
87049
87658
  var import_zod = require("zod");
87050
- var import_ethers52 = require("ethers");
87659
+ var import_ethers54 = require("ethers");
87051
87660
 
87052
87661
  // src/util/format.ts
87053
87662
  function bigintReplacer(_key, value) {
@@ -87235,7 +87844,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
87235
87844
  const b = getB();
87236
87845
  if (!b.ok) return renderError(b.error);
87237
87846
  return renderEnvelope(
87238
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers52.parseEther)(amountUcd.toString()).toString() })
87847
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers54.parseEther)(amountUcd.toString()).toString() })
87239
87848
  );
87240
87849
  })
87241
87850
  );
@@ -87273,7 +87882,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
87273
87882
  if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
87274
87883
  amountUcdWei = detail.data.debtUcdWei;
87275
87884
  } else {
87276
- amountUcdWei = (0, import_ethers52.parseEther)(amountUcd.toString()).toString();
87885
+ amountUcdWei = (0, import_ethers54.parseEther)(amountUcd.toString()).toString();
87277
87886
  }
87278
87887
  return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
87279
87888
  })
@@ -87876,7 +88485,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
87876
88485
 
87877
88486
  // src/tools/signer.ts
87878
88487
  var import_zod6 = require("zod");
87879
- var import_ethers53 = require("ethers");
88488
+ var import_ethers55 = require("ethers");
87880
88489
  var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
87881
88490
  var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
87882
88491
  var EXTERNAL_ONLY_MODES = ["external"];
@@ -87918,7 +88527,7 @@ function registerSignerTool(server, getRuntime, opts) {
87918
88527
  if (mode !== void 0 && !offeredModes.includes(mode)) {
87919
88528
  return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
87920
88529
  }
87921
- if (safeAddress !== void 0 && !import_ethers53.ethers.isAddress(safeAddress)) {
88530
+ if (safeAddress !== void 0 && !import_ethers55.ethers.isAddress(safeAddress)) {
87922
88531
  return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
87923
88532
  }
87924
88533
  if (action === "status") {
@@ -87929,9 +88538,9 @@ function registerSignerTool(server, getRuntime, opts) {
87929
88538
  // Plan 16 A3 — provenance honesty: the assistant must never guess HOW an
87930
88539
  // identity is known. borrower = a persisted binding; candidate = a live
87931
88540
  // wallet connection in THIS process only.
87932
- identityProvenance: s.borrower !== null ? `borrower ${s.borrower} is a PERSISTED binding (survives restarts until 'disconnect' or 'reset-borrower')` + (s.candidate !== null ? `; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only)` : "") : s.candidate !== null ? `no borrower is bound; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only) \u2014 the first verified signature binds it` : "no borrower is bound and no wallet is connected",
88541
+ identityProvenance: manager.identityPinned() ? `borrower ${s.borrower} is the wallet that signed this connector's login \u2014 it is your borrowing identity for this session and cannot be swapped, and only this wallet can approve writes` + (s.candidate !== null ? `; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only)` : "") : s.borrower !== null ? `borrower ${s.borrower} is a PERSISTED binding (survives restarts until 'disconnect' or 'reset-borrower')` + (s.candidate !== null ? `; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only)` : "") : s.candidate !== null ? `no borrower is bound; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only) \u2014 the first verified signature binds it` : "no borrower is bound and no wallet is connected",
87933
88542
  approvalPageUrl: bridge.url(),
87934
- hint: s.mode === "none" ? manager.invitation() + (s.keystoreConfigured ? " Note: keystore material IS already configured \u2014 choosing 'keystore' (or 'safe') unlocks it automatically; the unlock page is only for NEW material." : "") : s.mode === "external" && !s.borrower && !s.candidate ? "External mode: open the approval page URL above and connect your wallet \u2014 it becomes your borrowing identity." : !s.keystoreUnlocked && s.keystoreConfigured ? `Active mode: ${s.mode}. Keystore material is configured \u2014 'use keystore' unlocks it automatically; the unlock page is only for NEW material.` : `Active mode: ${s.mode}. Writes still require confirmed:true, always.`
88543
+ hint: s.mode === "none" ? manager.invitation() + (s.keystoreConfigured ? " Note: keystore material IS already configured \u2014 choosing 'keystore' (or 'safe') unlocks it automatically; the unlock page is only for NEW material." : "") : s.mode === "external" && !s.borrower && !s.candidate ? "External mode: open the approval page URL above and connect your wallet \u2014 it becomes your borrowing identity." : s.mode === "external" && manager.identityPinned() && !s.candidate ? `Signed in as ${s.borrower}. Chain reads work now (position_status by id, protocol_status, btc_price). Listing positions (position_list borrower=${s.borrower}) goes through the authenticated indexer proxy and needs a lit-ops login: open the approval page URL above, connect THIS wallet (any other is refused), then run signer_setup 'connect' \u2014 one login signature that moves nothing. The same connected wallet approves writes.` : !s.keystoreUnlocked && s.keystoreConfigured ? `Active mode: ${s.mode}. Keystore material is configured \u2014 'use keystore' unlocks it automatically; the unlock page is only for NEW material.` : `Active mode: ${s.mode}. Writes still require confirmed:true, always.`
87935
88544
  });
87936
88545
  }
87937
88546
  if (action === "use") {
@@ -88008,6 +88617,11 @@ function registerSignerTool(server, getRuntime, opts) {
88008
88617
  });
88009
88618
  }
88010
88619
  if (action === "reset-borrower") {
88620
+ if (manager.identityPinned()) {
88621
+ return validationFailed(
88622
+ `the borrowing identity is ${manager.boundBorrower()} \u2014 the wallet that signed this connector's login \u2014 and cannot be swapped here. To act as a different wallet, sign in to the connector again with that wallet.`
88623
+ );
88624
+ }
88011
88625
  manager.resetBorrower();
88012
88626
  return ok({
88013
88627
  reset: true,
@@ -88403,8 +89017,16 @@ function requireSafeCount(value, fallback, name, min) {
88403
89017
  return value;
88404
89018
  }
88405
89019
  var RATE_WINDOW_MS = 60 * 1e3;
89020
+ function assertWcLegComposable(opts) {
89021
+ assertWcMinSafeVersion(
89022
+ opts.serverVersion ?? SERVER_VERSION,
89023
+ opts.siweWc !== void 0 || resolvedWcProjectId(opts.env) !== void 0
89024
+ );
89025
+ resolveWcLimits(opts.siweWcLimits);
89026
+ }
88406
89027
  function composeConnector(opts, rawPublicOrigin) {
88407
89028
  const publicOrigin = normalizePublicOrigin(rawPublicOrigin);
89029
+ assertWcLegComposable(opts);
88408
89030
  const allowedNetworks = opts.allowedNetworks ?? ["sepolia"];
88409
89031
  if (allowedNetworks.length === 0) throw new Error("connector service: allowedNetworks must name at least one network");
88410
89032
  const launchNetwork = allowedNetworks[0];
@@ -88446,7 +89068,7 @@ function composeConnector(opts, rawPublicOrigin) {
88446
89068
  }
88447
89069
  async function buildWorld(tenantKey) {
88448
89070
  const stores = /* @__PURE__ */ new Map();
88449
- const mountId = (0, import_node_crypto10.randomUUID)().replaceAll("-", "");
89071
+ const mountId = (0, import_node_crypto11.randomUUID)().replaceAll("-", "");
88450
89072
  const overrides = {
88451
89073
  externalOnly: true,
88452
89074
  allowedNetworks,
@@ -88725,7 +89347,7 @@ function composeConnector(opts, rawPublicOrigin) {
88725
89347
  }
88726
89348
  const mcp = createServer2(world.deps, CONNECTOR_INSTRUCTIONS);
88727
89349
  const transport = new import_streamableHttp.StreamableHTTPServerTransport({
88728
- sessionIdGenerator: () => (0, import_node_crypto10.randomUUID)(),
89350
+ sessionIdGenerator: () => (0, import_node_crypto11.randomUUID)(),
88729
89351
  onsessioninitialized: (sessionId) => {
88730
89352
  evictExcessSessions(tenantKey);
88731
89353
  sessions.set(sessionId, { transport, tenant: tenantKey, lastSeen: clock() });
@@ -88769,7 +89391,7 @@ function composeConnector(opts, rawPublicOrigin) {
88769
89391
  return;
88770
89392
  }
88771
89393
  const p = (req.originalUrl ?? req.url).split("?")[0].toLowerCase();
88772
- const sensitive = ["/mcp", "/token", "/register", "/revoke", "/authorize"].some(
89394
+ const sensitive = ["/mcp", "/token", "/register", "/revoke", "/authorize", "/account"].some(
88773
89395
  (r) => p === r || p.startsWith(`${r}/`)
88774
89396
  );
88775
89397
  if (!sensitive) {
@@ -88805,9 +89427,12 @@ function composeConnector(opts, rawPublicOrigin) {
88805
89427
  origin: () => publicOrigin,
88806
89428
  chainId: launchNetwork === "mainnet" ? 1 : 11155111,
88807
89429
  ...wcLeg ? { wc: wcLeg } : {},
89430
+ ...opts.siweWcLimits ? { wcLimits: opts.siweWcLimits } : {},
89431
+ ...opts.oauthStore ? { store: opts.oauthStore } : {},
88808
89432
  ...opts.clock ? { clock: opts.clock } : {}
88809
89433
  });
88810
89434
  siweRef = siwe;
89435
+ mountAccountApi(app, siwe, opts.account);
88811
89436
  app.post("/authorize/siwe-message", import_express.default.json(), (req, res) => {
88812
89437
  const b = req.body;
88813
89438
  const r = siwe.siweMessage(String(b.flowId ?? ""), String(b.address ?? ""));
@@ -88828,7 +89453,12 @@ function composeConnector(opts, rawPublicOrigin) {
88828
89453
  });
88829
89454
  app.post("/authorize/wc-pairing", import_express.default.json(), (req, res) => {
88830
89455
  const b = req.body;
88831
- void siwe.wcPairing(String(b.flowId ?? "")).then((r) => {
89456
+ const ip = req.ip;
89457
+ if (ip === void 0) {
89458
+ res.status(400).json({ reason: "cannot determine the requesting network address - mobile wallet sign-in refused" });
89459
+ return;
89460
+ }
89461
+ void siwe.wcPairing(String(b.flowId ?? ""), ip).then((r) => {
88832
89462
  if (!r.ok) res.status(r.status).json({ reason: r.reason });
88833
89463
  else res.json({ uri: r.uri, qrSvg: r.qrSvg });
88834
89464
  }).catch((e) => {
@@ -88842,7 +89472,8 @@ function composeConnector(opts, rawPublicOrigin) {
88842
89472
  const authMd = renderAuthMd({
88843
89473
  publicOrigin,
88844
89474
  networks: allowedNetworks,
88845
- walletConnectEnabled: wcLeg !== void 0
89475
+ walletConnectEnabled: wcLeg !== void 0,
89476
+ grants: { durable: opts.oauthStore !== void 0, accountApi: opts.account !== void 0 }
88846
89477
  });
88847
89478
  app.get("/auth.md", (_req, res) => {
88848
89479
  res.setHeader("X-Content-Type-Options", "nosniff");
@@ -88872,10 +89503,10 @@ function composeConnector(opts, rawPublicOrigin) {
88872
89503
  })
88873
89504
  );
88874
89505
  authImpl = {
88875
- tenant(req) {
89506
+ async tenant(req) {
88876
89507
  const header = req.headers.authorization;
88877
89508
  if (typeof header !== "string" || !header.startsWith("Bearer ")) return null;
88878
- const info = siwe.lookupAccessToken(header.slice("Bearer ".length));
89509
+ const info = await siwe.lookupAccessToken(header.slice("Bearer ".length));
88879
89510
  const address = info?.extra?.["address"];
88880
89511
  return typeof address === "string" ? { address } : null;
88881
89512
  }
@@ -88916,6 +89547,64 @@ function composeConnector(opts, rawPublicOrigin) {
88916
89547
  }
88917
89548
  };
88918
89549
  }
89550
+ function mountAccountApi(app, siwe, account) {
89551
+ const allowed = new Set(account?.appOrigins ?? []);
89552
+ app.use("/account", (req, res, next) => {
89553
+ const origin2 = req.headers.origin;
89554
+ if (typeof origin2 === "string" && allowed.has(origin2)) {
89555
+ res.setHeader("Access-Control-Allow-Origin", origin2);
89556
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
89557
+ res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
89558
+ res.setHeader("Access-Control-Max-Age", "600");
89559
+ }
89560
+ res.setHeader("Vary", "Origin");
89561
+ res.setHeader("Cache-Control", "no-store");
89562
+ if (req.method === "OPTIONS") {
89563
+ res.status(204).end();
89564
+ return;
89565
+ }
89566
+ next();
89567
+ });
89568
+ const fail = (res, status, error, reason) => {
89569
+ res.status(status).json({ error, reason });
89570
+ };
89571
+ const identify = async (req, res) => {
89572
+ if (!account) {
89573
+ fail(res, 501, "not_configured", "the account API is not configured on this deployment (no app identity verifier)");
89574
+ return null;
89575
+ }
89576
+ const header = req.headers.authorization;
89577
+ if (typeof header !== "string" || !header.startsWith("Bearer ") || header.length === "Bearer ".length) {
89578
+ fail(res, 401, "unauthorized", "missing app session \u2014 send the app's Firebase ID token as 'Authorization: Bearer <token>'");
89579
+ return null;
89580
+ }
89581
+ const who = await account.verifier.verify(header.slice("Bearer ".length));
89582
+ if (!who.ok) {
89583
+ fail(res, 401, "unauthorized", who.reason);
89584
+ return null;
89585
+ }
89586
+ return who.address;
89587
+ };
89588
+ app.get("/account/grants", (req, res) => {
89589
+ void (async () => {
89590
+ const address = await identify(req, res);
89591
+ if (address === null) return;
89592
+ res.json({ address, grants: await siwe.listGrants(address) });
89593
+ })().catch((e) => fail(res, 503, "store_error", `the connection store failed: ${e instanceof Error ? e.message : String(e)}`));
89594
+ });
89595
+ app.post("/account/grants/:id/revoke", (req, res) => {
89596
+ void (async () => {
89597
+ const address = await identify(req, res);
89598
+ if (address === null) return;
89599
+ const id = String(req.params["id"]);
89600
+ if (!await siwe.revokeGrantForAddress(address, id)) {
89601
+ fail(res, 404, "not_found", `no live connection '${id}' belongs to ${address}`);
89602
+ return;
89603
+ }
89604
+ res.json({ revoked: true, id });
89605
+ })().catch((e) => fail(res, 503, "store_error", `the connection store failed: ${e instanceof Error ? e.message : String(e)}`));
89606
+ });
89607
+ }
88919
89608
  var CONNECTOR_PATH_PREFIXES = [
88920
89609
  "/mcp",
88921
89610
  "/approval/",