@inversealtruism/csd-client 0.1.5 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -22,17 +22,22 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  CsdClient: () => CsdClient,
24
24
  rpcHeaderToHeader: () => rpcHeaderToHeader,
25
- rpcTxToTx: () => rpcTxToTx
25
+ rpcTxToTx: () => rpcTxToTx,
26
+ verifyInputValues: () => verifyInputValues
26
27
  });
27
28
  module.exports = __toCommonJS(index_exports);
29
+ var import_csd_codec = require("@inversealtruism/csd-codec");
28
30
  var CsdClient = class {
29
31
  base;
30
32
  f;
31
33
  timeoutMs;
32
34
  retries;
35
+ maxBytes;
33
36
  constructor(opts) {
34
37
  this.base = opts.baseUrl.replace(/\/+$/, "");
35
- this.f = opts.fetch ?? globalThis.fetch;
38
+ this.maxBytes = Math.max(1, opts.maxResponseBytes ?? 16 * 1024 * 1024);
39
+ const gf = globalThis.fetch;
40
+ this.f = opts.fetch ?? (gf ? gf.bind(globalThis) : gf);
36
41
  this.timeoutMs = opts.timeoutMs ?? 1e4;
37
42
  this.retries = Math.max(0, opts.retries ?? 0);
38
43
  if (!this.f) throw new Error("no fetch available \u2014 pass opts.fetch");
@@ -45,7 +50,7 @@ var CsdClient = class {
45
50
  if (r.status >= 500 && attempt < this.retries) {
46
51
  lastErr = new Error(`HTTP ${r.status}`);
47
52
  } else if (!r.ok) throw new Error(`${init?.method ?? "GET"} ${path} \u2192 HTTP ${r.status}`);
48
- else return await r.json();
53
+ else return await this.readCapped(r, path);
49
54
  } catch (e) {
50
55
  if (attempt >= this.retries) throw e;
51
56
  lastErr = e;
@@ -55,6 +60,49 @@ var CsdClient = class {
55
60
  void lastErr;
56
61
  }
57
62
  }
63
+ /**
64
+ * Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
65
+ * oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
66
+ * it exceeds the cap — so a malicious node cannot make us buffer a giant body and OOM before
67
+ * we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
68
+ * streaming body (older MV3/Node), preserving the cap as a best effort.
69
+ */
70
+ async readCapped(r, path) {
71
+ const max = this.maxBytes;
72
+ const cl = r.headers.get("content-length");
73
+ if (cl && Number(cl) > max) throw new Error(`GET ${path} \u2192 response too large (${cl} > ${max} bytes)`);
74
+ const body = r.body;
75
+ if (!body || typeof body.getReader !== "function") {
76
+ const t = await r.text();
77
+ if (t.length > max) throw new Error(`GET ${path} \u2192 response too large (${t.length} > ${max} bytes)`);
78
+ return JSON.parse(t);
79
+ }
80
+ const reader = body.getReader();
81
+ const chunks = [];
82
+ let total = 0;
83
+ for (; ; ) {
84
+ const { value, done } = await reader.read();
85
+ if (done) break;
86
+ if (value) {
87
+ total += value.length;
88
+ if (total > max) {
89
+ try {
90
+ await reader.cancel();
91
+ } catch {
92
+ }
93
+ throw new Error(`GET ${path} \u2192 response exceeded ${max} bytes`);
94
+ }
95
+ chunks.push(value);
96
+ }
97
+ }
98
+ const buf = new Uint8Array(total);
99
+ let off = 0;
100
+ for (const c of chunks) {
101
+ buf.set(c, off);
102
+ off += c.length;
103
+ }
104
+ return JSON.parse(new TextDecoder().decode(buf));
105
+ }
58
106
  get(path) {
59
107
  return this.req(path);
60
108
  }
@@ -160,6 +208,34 @@ function rpcTxToTx(j) {
160
208
  outputs: j.outputs.map((o) => ({ value: o.value, scriptPubkey: o.script_pubkey }))
161
209
  };
162
210
  }
211
+ async function verifyInputValues(client, inputs) {
212
+ const norm = (s) => String(s).toLowerCase().replace(/^0x/, "");
213
+ let total = 0;
214
+ for (const i of inputs) {
215
+ let info;
216
+ try {
217
+ info = await client.tx(i.txid);
218
+ } catch {
219
+ return { ok: false, total: 0 };
220
+ }
221
+ const body = info?.tx ?? info;
222
+ if (!body || !Array.isArray(body.outputs) || !Array.isArray(body.inputs)) return { ok: false, total: 0 };
223
+ let tx;
224
+ try {
225
+ tx = rpcTxToTx(body);
226
+ } catch {
227
+ return { ok: false, total: 0 };
228
+ }
229
+ if (norm((0, import_csd_codec.txid)(tx)) !== norm(i.txid)) return { ok: false, total: 0 };
230
+ const out = tx.outputs[i.vout];
231
+ if (!out) return { ok: false, total: 0 };
232
+ const v = Number(out.value);
233
+ if (!Number.isSafeInteger(v) || v <= 0) return { ok: false, total: 0 };
234
+ total += v;
235
+ if (!Number.isSafeInteger(total)) return { ok: false, total: 0 };
236
+ }
237
+ return { ok: true, total };
238
+ }
163
239
  function rpcHeaderToHeader(h) {
164
240
  return { version: h.version, prev: h.prev, merkle: h.merkle, time: h.time, bits: h.bits, nonce: h.nonce };
165
241
  }
@@ -167,5 +243,6 @@ function rpcHeaderToHeader(h) {
167
243
  0 && (module.exports = {
168
244
  CsdClient,
169
245
  rpcHeaderToHeader,
170
- rpcTxToTx
246
+ rpcTxToTx,
247
+ verifyInputValues
171
248
  });
package/dist/index.d.cts CHANGED
@@ -111,14 +111,30 @@ interface ClientOptions {
111
111
  /** retry NETWORK failures (timeouts, refused, 5xx) this many times with jittered backoff.
112
112
  * NEVER retries an application result (`ok:false`) or 4xx — those are answers, not outages. */
113
113
  retries?: number;
114
+ /**
115
+ * Hard ceiling (bytes) on a response body before it is parsed. A lying/malicious node can
116
+ * otherwise stream a multi-hundred-MB body that the verifier buffers (`await r.json()`) and
117
+ * OOM-crashes BEFORE any PoW/merkle/LWMA check runs — a remote DoS of the trusted light-client
118
+ * path (audit M2). Default 16 MiB ≫ any real block; raise it for an unusually large block source.
119
+ */
120
+ maxResponseBytes?: number;
114
121
  }
115
122
  declare class CsdClient {
116
123
  private readonly base;
117
124
  private readonly f;
118
125
  private readonly timeoutMs;
119
126
  private readonly retries;
127
+ private readonly maxBytes;
120
128
  constructor(opts: ClientOptions);
121
129
  private req;
130
+ /**
131
+ * Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
132
+ * oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
133
+ * it exceeds the cap — so a malicious node cannot make us buffer a giant body and OOM before
134
+ * we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
135
+ * streaming body (older MV3/Node), preserving the cap as a best effort.
136
+ */
137
+ private readCapped;
122
138
  private get;
123
139
  private post;
124
140
  private getOk;
@@ -159,7 +175,25 @@ declare class CsdClient {
159
175
  }
160
176
  /** Convert a node /tx or /block tx JSON back into the codec's Tx struct (for re-verification). */
161
177
  declare function rpcTxToTx(j: RpcTxJson): Tx;
178
+ /** UTXO-VALUE-1 cure (audit). A CSD fee is implicit (Σin − Σout) and uncapped by consensus, so a
179
+ * builder that trusts a hostile RPC's /utxos `value` can compute too-small a change and silently
180
+ * BURN the difference as fee. This confirms each selected input's REAL value by fetching its source
181
+ * tx and RECOMPUTING its txid with the consensus codec — the txid commits to the output values, so
182
+ * a forged body whose recomputed txid still matches the prevout is impossible. Fail-CLOSED: any
183
+ * unreachable/forged/missing source aborts. Returns the verified input total (use it to compute
184
+ * change from REAL values, not the reported ones). RPC-facing builders (wallet, cairn-sdk) should
185
+ * call this before assembling a spend; csd-tx itself is pure and cannot fetch.
186
+ * (Mirrors the proven cairn-wallet `node.ts` implementation; the wallet's TXB-1 cure made canonical.) */
187
+ declare function verifyInputValues(client: {
188
+ tx(id: string): Promise<any>;
189
+ }, inputs: {
190
+ txid: string;
191
+ vout: number;
192
+ }[]): Promise<{
193
+ ok: boolean;
194
+ total: number;
195
+ }>;
162
196
  /** Convert a node /block header JSON into the codec's BlockHeader. */
163
197
  declare function rpcHeaderToHeader(h: RpcHeaderJson): BlockHeader;
164
198
 
165
- export { type ClientOptions, CsdClient, type RpcBlock, type RpcHeaderJson, type RpcHealth, type RpcProposal, type RpcSubmit, type RpcTip, type RpcTxInfo, type RpcTxJson, type RpcUtxo, type RpcUtxos, type WaitForTxResult, rpcHeaderToHeader, rpcTxToTx };
199
+ export { type ClientOptions, CsdClient, type RpcBlock, type RpcHeaderJson, type RpcHealth, type RpcProposal, type RpcSubmit, type RpcTip, type RpcTxInfo, type RpcTxJson, type RpcUtxo, type RpcUtxos, type WaitForTxResult, rpcHeaderToHeader, rpcTxToTx, verifyInputValues };
package/dist/index.d.ts CHANGED
@@ -111,14 +111,30 @@ interface ClientOptions {
111
111
  /** retry NETWORK failures (timeouts, refused, 5xx) this many times with jittered backoff.
112
112
  * NEVER retries an application result (`ok:false`) or 4xx — those are answers, not outages. */
113
113
  retries?: number;
114
+ /**
115
+ * Hard ceiling (bytes) on a response body before it is parsed. A lying/malicious node can
116
+ * otherwise stream a multi-hundred-MB body that the verifier buffers (`await r.json()`) and
117
+ * OOM-crashes BEFORE any PoW/merkle/LWMA check runs — a remote DoS of the trusted light-client
118
+ * path (audit M2). Default 16 MiB ≫ any real block; raise it for an unusually large block source.
119
+ */
120
+ maxResponseBytes?: number;
114
121
  }
115
122
  declare class CsdClient {
116
123
  private readonly base;
117
124
  private readonly f;
118
125
  private readonly timeoutMs;
119
126
  private readonly retries;
127
+ private readonly maxBytes;
120
128
  constructor(opts: ClientOptions);
121
129
  private req;
130
+ /**
131
+ * Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
132
+ * oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
133
+ * it exceeds the cap — so a malicious node cannot make us buffer a giant body and OOM before
134
+ * we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
135
+ * streaming body (older MV3/Node), preserving the cap as a best effort.
136
+ */
137
+ private readCapped;
122
138
  private get;
123
139
  private post;
124
140
  private getOk;
@@ -159,7 +175,25 @@ declare class CsdClient {
159
175
  }
160
176
  /** Convert a node /tx or /block tx JSON back into the codec's Tx struct (for re-verification). */
161
177
  declare function rpcTxToTx(j: RpcTxJson): Tx;
178
+ /** UTXO-VALUE-1 cure (audit). A CSD fee is implicit (Σin − Σout) and uncapped by consensus, so a
179
+ * builder that trusts a hostile RPC's /utxos `value` can compute too-small a change and silently
180
+ * BURN the difference as fee. This confirms each selected input's REAL value by fetching its source
181
+ * tx and RECOMPUTING its txid with the consensus codec — the txid commits to the output values, so
182
+ * a forged body whose recomputed txid still matches the prevout is impossible. Fail-CLOSED: any
183
+ * unreachable/forged/missing source aborts. Returns the verified input total (use it to compute
184
+ * change from REAL values, not the reported ones). RPC-facing builders (wallet, cairn-sdk) should
185
+ * call this before assembling a spend; csd-tx itself is pure and cannot fetch.
186
+ * (Mirrors the proven cairn-wallet `node.ts` implementation; the wallet's TXB-1 cure made canonical.) */
187
+ declare function verifyInputValues(client: {
188
+ tx(id: string): Promise<any>;
189
+ }, inputs: {
190
+ txid: string;
191
+ vout: number;
192
+ }[]): Promise<{
193
+ ok: boolean;
194
+ total: number;
195
+ }>;
162
196
  /** Convert a node /block header JSON into the codec's BlockHeader. */
163
197
  declare function rpcHeaderToHeader(h: RpcHeaderJson): BlockHeader;
164
198
 
165
- export { type ClientOptions, CsdClient, type RpcBlock, type RpcHeaderJson, type RpcHealth, type RpcProposal, type RpcSubmit, type RpcTip, type RpcTxInfo, type RpcTxJson, type RpcUtxo, type RpcUtxos, type WaitForTxResult, rpcHeaderToHeader, rpcTxToTx };
199
+ export { type ClientOptions, CsdClient, type RpcBlock, type RpcHeaderJson, type RpcHealth, type RpcProposal, type RpcSubmit, type RpcTip, type RpcTxInfo, type RpcTxJson, type RpcUtxo, type RpcUtxos, type WaitForTxResult, rpcHeaderToHeader, rpcTxToTx, verifyInputValues };
package/dist/index.js CHANGED
@@ -1,12 +1,16 @@
1
1
  // src/index.ts
2
+ import { txid as codecTxid } from "@inversealtruism/csd-codec";
2
3
  var CsdClient = class {
3
4
  base;
4
5
  f;
5
6
  timeoutMs;
6
7
  retries;
8
+ maxBytes;
7
9
  constructor(opts) {
8
10
  this.base = opts.baseUrl.replace(/\/+$/, "");
9
- this.f = opts.fetch ?? globalThis.fetch;
11
+ this.maxBytes = Math.max(1, opts.maxResponseBytes ?? 16 * 1024 * 1024);
12
+ const gf = globalThis.fetch;
13
+ this.f = opts.fetch ?? (gf ? gf.bind(globalThis) : gf);
10
14
  this.timeoutMs = opts.timeoutMs ?? 1e4;
11
15
  this.retries = Math.max(0, opts.retries ?? 0);
12
16
  if (!this.f) throw new Error("no fetch available \u2014 pass opts.fetch");
@@ -19,7 +23,7 @@ var CsdClient = class {
19
23
  if (r.status >= 500 && attempt < this.retries) {
20
24
  lastErr = new Error(`HTTP ${r.status}`);
21
25
  } else if (!r.ok) throw new Error(`${init?.method ?? "GET"} ${path} \u2192 HTTP ${r.status}`);
22
- else return await r.json();
26
+ else return await this.readCapped(r, path);
23
27
  } catch (e) {
24
28
  if (attempt >= this.retries) throw e;
25
29
  lastErr = e;
@@ -29,6 +33,49 @@ var CsdClient = class {
29
33
  void lastErr;
30
34
  }
31
35
  }
36
+ /**
37
+ * Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
38
+ * oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
39
+ * it exceeds the cap — so a malicious node cannot make us buffer a giant body and OOM before
40
+ * we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
41
+ * streaming body (older MV3/Node), preserving the cap as a best effort.
42
+ */
43
+ async readCapped(r, path) {
44
+ const max = this.maxBytes;
45
+ const cl = r.headers.get("content-length");
46
+ if (cl && Number(cl) > max) throw new Error(`GET ${path} \u2192 response too large (${cl} > ${max} bytes)`);
47
+ const body = r.body;
48
+ if (!body || typeof body.getReader !== "function") {
49
+ const t = await r.text();
50
+ if (t.length > max) throw new Error(`GET ${path} \u2192 response too large (${t.length} > ${max} bytes)`);
51
+ return JSON.parse(t);
52
+ }
53
+ const reader = body.getReader();
54
+ const chunks = [];
55
+ let total = 0;
56
+ for (; ; ) {
57
+ const { value, done } = await reader.read();
58
+ if (done) break;
59
+ if (value) {
60
+ total += value.length;
61
+ if (total > max) {
62
+ try {
63
+ await reader.cancel();
64
+ } catch {
65
+ }
66
+ throw new Error(`GET ${path} \u2192 response exceeded ${max} bytes`);
67
+ }
68
+ chunks.push(value);
69
+ }
70
+ }
71
+ const buf = new Uint8Array(total);
72
+ let off = 0;
73
+ for (const c of chunks) {
74
+ buf.set(c, off);
75
+ off += c.length;
76
+ }
77
+ return JSON.parse(new TextDecoder().decode(buf));
78
+ }
32
79
  get(path) {
33
80
  return this.req(path);
34
81
  }
@@ -134,11 +181,40 @@ function rpcTxToTx(j) {
134
181
  outputs: j.outputs.map((o) => ({ value: o.value, scriptPubkey: o.script_pubkey }))
135
182
  };
136
183
  }
184
+ async function verifyInputValues(client, inputs) {
185
+ const norm = (s) => String(s).toLowerCase().replace(/^0x/, "");
186
+ let total = 0;
187
+ for (const i of inputs) {
188
+ let info;
189
+ try {
190
+ info = await client.tx(i.txid);
191
+ } catch {
192
+ return { ok: false, total: 0 };
193
+ }
194
+ const body = info?.tx ?? info;
195
+ if (!body || !Array.isArray(body.outputs) || !Array.isArray(body.inputs)) return { ok: false, total: 0 };
196
+ let tx;
197
+ try {
198
+ tx = rpcTxToTx(body);
199
+ } catch {
200
+ return { ok: false, total: 0 };
201
+ }
202
+ if (norm(codecTxid(tx)) !== norm(i.txid)) return { ok: false, total: 0 };
203
+ const out = tx.outputs[i.vout];
204
+ if (!out) return { ok: false, total: 0 };
205
+ const v = Number(out.value);
206
+ if (!Number.isSafeInteger(v) || v <= 0) return { ok: false, total: 0 };
207
+ total += v;
208
+ if (!Number.isSafeInteger(total)) return { ok: false, total: 0 };
209
+ }
210
+ return { ok: true, total };
211
+ }
137
212
  function rpcHeaderToHeader(h) {
138
213
  return { version: h.version, prev: h.prev, merkle: h.merkle, time: h.time, bits: h.bits, nonce: h.nonce };
139
214
  }
140
215
  export {
141
216
  CsdClient,
142
217
  rpcHeaderToHeader,
143
- rpcTxToTx
218
+ rpcTxToTx,
219
+ verifyInputValues
144
220
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inversealtruism/csd-client",
3
- "version": "0.1.5",
3
+ "version": "0.1.8",
4
4
  "description": "Typed HTTP RPC client for a Compute Substrate node (or the Cairn proxy / a discovered gateway) — tip/block/tx/utxos/proposals/top/domains/mempool/submit/templates.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -19,12 +19,12 @@
19
19
  "README.md"
20
20
  ],
21
21
  "dependencies": {
22
- "@inversealtruism/csd-codec": "0.1.5"
22
+ "@inversealtruism/csd-codec": "0.1.8"
23
23
  },
24
24
  "license": "MIT",
25
25
  "sideEffects": false,
26
26
  "devDependencies": {
27
- "@inversealtruism/csd-vectors": "0.1.5"
27
+ "@inversealtruism/csd-vectors": "0.1.8"
28
28
  },
29
29
  "publishConfig": {
30
30
  "access": "public"