@swarm-tips/client 0.4.2 → 0.4.4

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.
Files changed (40) hide show
  1. package/README.md +3 -2
  2. package/SBOM.spdx.json +5 -5
  3. package/dist/agent.d.ts +17 -1
  4. package/dist/agent.js +71 -54
  5. package/dist/cli/swarm.d.ts +5 -0
  6. package/dist/cli/swarm.js +48 -21
  7. package/dist/contracts/generated/coordination_game.d.ts +179 -1
  8. package/dist/contracts/generated/shillbot.d.ts +119 -12
  9. package/dist/contracts/idl/coordination_game.json +180 -2
  10. package/dist/contracts/idl/shillbot.json +119 -12
  11. package/dist/generated/openapi.d.ts +17 -2
  12. package/dist/generated/openapi.js +1 -1
  13. package/dist/http.js +1 -1
  14. package/dist/inbox/client.d.ts +2 -4
  15. package/dist/inbox/client.js +11 -6
  16. package/dist/inbox/index.d.ts +1 -1
  17. package/dist/inbox/index.js +1 -1
  18. package/dist/inbox/types.d.ts +9 -0
  19. package/dist/inbox/types.js +10 -0
  20. package/dist/index.d.ts +5 -3
  21. package/dist/index.js +4 -2
  22. package/dist/shillbot/api.d.ts +8 -1
  23. package/dist/shillbot/api.js +53 -133
  24. package/dist/shillbot/index.d.ts +1 -0
  25. package/dist/shillbot/index.js +3 -0
  26. package/dist/shillbot/verify-tx.d.ts +62 -0
  27. package/dist/shillbot/verify-tx.js +643 -0
  28. package/dist/signer/evm.d.ts +1 -1
  29. package/dist/signer/evm.js +72 -2
  30. package/dist/signer/index.d.ts +1 -1
  31. package/dist/signer/solana.d.ts +3 -2
  32. package/dist/signer/solana.js +36 -9
  33. package/dist/signer/types.d.ts +4 -1
  34. package/dist/version.d.ts +1 -1
  35. package/dist/version.js +1 -1
  36. package/dist/vow/index.d.ts +1 -1
  37. package/dist/vow/index.js +1 -1
  38. package/dist/vow/verify.d.ts +36 -0
  39. package/dist/vow/verify.js +458 -1
  40. package/package.json +1 -1
@@ -1,7 +1,464 @@
1
- import { PublicKey } from "@solana/web3.js";
1
+ import { Connection, PublicKey } from "@solana/web3.js";
2
+ import { SwarmClientError } from "../errors.js";
3
+ import { shillbotProtocol } from "./decoders/shillbot.js";
2
4
  import { anchorDiscriminator, bytesEqual } from "./discriminator.js";
3
5
  import { asV1, checkSchema } from "./schema.js";
4
6
  export const DEFAULT_SCORE_MAX = 1000000n;
7
+ /** Default maximum VOW attestation HTTP response size (`2 MiB`). */
8
+ export const DEFAULT_MAX_VOW_BYTES = 2 * 1024 * 1024;
9
+ const DEFAULT_VOW_SOLANA_RPC = {
10
+ mainnet: "https://api.mainnet-beta.solana.com",
11
+ devnet: "https://api.devnet.solana.com",
12
+ };
13
+ const MAX_VOW_URL_LENGTH = 2048;
14
+ const FORBIDDEN_EXACT_HOSTS = new Set([
15
+ "localhost",
16
+ "metadata.google.internal",
17
+ "metadata",
18
+ "instance-data",
19
+ ]);
20
+ const FORBIDDEN_HOST_SUFFIXES = [
21
+ ".internal",
22
+ ".local",
23
+ ".localhost",
24
+ ".run.app",
25
+ ".nip.io",
26
+ ".sslip.io",
27
+ ".xip.io",
28
+ ];
29
+ function isNonGlobalIpv4(o0, o1, o2, _o3) {
30
+ if (o0 === 0)
31
+ return true; // 0.0.0.0/8
32
+ if (o0 === 10)
33
+ return true; // 10.0.0.0/8 RFC 1918
34
+ if (o0 === 100 && (o1 & 0xc0) === 64)
35
+ return true; // 100.64.0.0/10 CGNAT
36
+ if (o0 === 127)
37
+ return true; // 127.0.0.0/8 loopback
38
+ if (o0 === 169 && o1 === 254)
39
+ return true; // 169.254.0.0/16 link-local / cloud metadata
40
+ if (o0 === 172 && o1 >= 16 && o1 <= 31)
41
+ return true; // 172.16.0.0/12 RFC 1918
42
+ if (o0 === 192 && o1 === 0 && (o2 === 0 || o2 === 2))
43
+ return true; // 192.0.0.0/24 & 192.0.2.0/24
44
+ if (o0 === 192 && o1 === 88 && o2 === 99)
45
+ return true; // 192.88.99.0/24 6to4 relay
46
+ if (o0 === 192 && o1 === 168)
47
+ return true; // 192.168.0.0/16 RFC 1918
48
+ if (o0 === 198 && (o1 === 18 || o1 === 19))
49
+ return true; // 198.18.0.0/15 benchmarking
50
+ if (o0 === 198 && o1 === 51 && o2 === 100)
51
+ return true; // 198.51.100.0/24 TEST-NET-2
52
+ if (o0 === 203 && o1 === 0 && o2 === 113)
53
+ return true; // 203.0.113.0/24 TEST-NET-3
54
+ if (o0 >= 224)
55
+ return true; // 224.0.0.0/4 multicast + 240.0.0.0/4 reserved/broadcast
56
+ return false;
57
+ }
58
+ function parseIpv4Octets(host) {
59
+ const parts = host.split(".");
60
+ if (parts.length !== 4)
61
+ return null;
62
+ const octets = [];
63
+ for (const part of parts) {
64
+ if (!/^\d{1,3}$/.test(part))
65
+ return null;
66
+ if (part.length > 1 && part.startsWith("0"))
67
+ return null;
68
+ const n = Number(part);
69
+ if (!Number.isInteger(n) || n < 0 || n > 255)
70
+ return null;
71
+ octets.push(n);
72
+ }
73
+ return [octets[0], octets[1], octets[2], octets[3]];
74
+ }
75
+ function parseIpv6Segments(bracketedHost) {
76
+ if (!bracketedHost.startsWith("[") || !bracketedHost.endsWith("]"))
77
+ return null;
78
+ const inner = bracketedHost.slice(1, -1);
79
+ if (!inner || inner.includes("%"))
80
+ return null;
81
+ const doubleColonParts = inner.split("::");
82
+ if (doubleColonParts.length > 2)
83
+ return null;
84
+ const expandTokens = (chunk) => {
85
+ if (!chunk)
86
+ return [];
87
+ const rawTokens = chunk.split(":");
88
+ const out = [];
89
+ for (let i = 0; i < rawTokens.length; i++) {
90
+ const tok = rawTokens[i];
91
+ if (tok.includes(".")) {
92
+ if (i !== rawTokens.length - 1)
93
+ return null;
94
+ const v4 = parseIpv4Octets(tok);
95
+ if (!v4)
96
+ return null;
97
+ out.push((v4[0] << 8) | v4[1], (v4[2] << 8) | v4[3]);
98
+ }
99
+ else {
100
+ if (!/^[0-9a-fA-F]{1,4}$/.test(tok))
101
+ return null;
102
+ out.push(parseInt(tok, 16));
103
+ }
104
+ }
105
+ return out;
106
+ };
107
+ if (doubleColonParts.length === 1) {
108
+ const segs = expandTokens(doubleColonParts[0]);
109
+ if (!segs || segs.length !== 8)
110
+ return null;
111
+ return Uint16Array.from(segs);
112
+ }
113
+ const left = expandTokens(doubleColonParts[0]);
114
+ const right = expandTokens(doubleColonParts[1]);
115
+ if (!left || !right || left.length + right.length >= 8)
116
+ return null;
117
+ const zeroFill = new Array(8 - left.length - right.length).fill(0);
118
+ return Uint16Array.from([...left, ...zeroFill, ...right]);
119
+ }
120
+ function isNonGlobalIpv6(seg) {
121
+ const allZeroPrefix6 = seg[0] === 0 && seg[1] === 0 && seg[2] === 0 && seg[3] === 0 && seg[4] === 0 && seg[5] === 0;
122
+ // :: (unspecified), ::1 (loopback), and ::a.b.c.d (IPv4-compatible)
123
+ if (allZeroPrefix6)
124
+ return true;
125
+ // ::ffff:0:0/96 (IPv4-mapped IPv6 literals — rejected outright)
126
+ if (seg[0] === 0 && seg[1] === 0 && seg[2] === 0 && seg[3] === 0 && seg[4] === 0 && seg[5] === 0xffff) {
127
+ return true;
128
+ }
129
+ // ::ffff:0:0:0/96 (IPv4-translated)
130
+ if (seg[0] === 0 && seg[1] === 0 && seg[2] === 0 && seg[3] === 0 && seg[4] === 0xffff && seg[5] === 0) {
131
+ return true;
132
+ }
133
+ // 64:ff9b::/96 & 64:ff9b:1::/48 (NAT64)
134
+ if (seg[0] === 0x0064 && seg[1] === 0xff9b)
135
+ return true;
136
+ // 2002::/16 (6to4)
137
+ if (seg[0] === 0x2002)
138
+ return true;
139
+ // 2001:0000::/23 (Teredo / IETF protocol) & 2001:db8::/32 (documentation)
140
+ if (seg[0] === 0x2001 && (seg[1] < 0x0200 || seg[1] === 0x0db8))
141
+ return true;
142
+ // fc00::/7 (Unique Local)
143
+ if ((seg[0] & 0xfe00) === 0xfc00)
144
+ return true;
145
+ // fe80::/10 (Link-Local) & fec0::/10 (Site-Local)
146
+ if ((seg[0] & 0xffc0) === 0xfe80 || (seg[0] & 0xffc0) === 0xfec0)
147
+ return true;
148
+ // ff00::/8 (Multicast)
149
+ if ((seg[0] & 0xff00) === 0xff00)
150
+ return true;
151
+ return false;
152
+ }
153
+ /**
154
+ * Validate a VOW attestation URL against SSRF, scheme downgrade, trailing-dot FQDN
155
+ * bypasses, internal/metadata suffixes, and private/loopback/link-local IP literals.
156
+ */
157
+ export function validateVowUrl(rawUrl, opts) {
158
+ const operation = opts?.operation ?? "tasks.verifyVow";
159
+ const trimmed = rawUrl.trim();
160
+ if (!trimmed || trimmed.length > MAX_VOW_URL_LENGTH) {
161
+ throw new SwarmClientError({
162
+ code: "INVALID_ARGUMENT",
163
+ operation,
164
+ message: "VOW URL is empty or exceeds maximum length (2048 chars)",
165
+ });
166
+ }
167
+ let parsed;
168
+ try {
169
+ parsed = new URL(trimmed);
170
+ }
171
+ catch (cause) {
172
+ throw new SwarmClientError({
173
+ code: "INVALID_ARGUMENT",
174
+ operation,
175
+ message: `Invalid VOW URL: ${trimmed}`,
176
+ cause,
177
+ });
178
+ }
179
+ if (parsed.username || parsed.password) {
180
+ throw new SwarmClientError({
181
+ code: "INVALID_ARGUMENT",
182
+ operation,
183
+ message: "VOW URL must not include embedded credentials",
184
+ });
185
+ }
186
+ const host = parsed.hostname.toLowerCase();
187
+ if (!host || host.endsWith(".")) {
188
+ throw new SwarmClientError({
189
+ code: "INVALID_ARGUMENT",
190
+ operation,
191
+ message: `VOW URL hostname "${parsed.hostname}" is forbidden (trailing-dot FQDNs are rejected)`,
192
+ });
193
+ }
194
+ const isLoopbackHost = host === "127.0.0.1" || host === "localhost" || host === "[::1]";
195
+ if (parsed.protocol === "http:") {
196
+ if (opts?.allowLocalhostHttp === true && isLoopbackHost) {
197
+ return parsed;
198
+ }
199
+ throw new SwarmClientError({
200
+ code: "INVALID_ARGUMENT",
201
+ operation,
202
+ message: "VOW URL must use https: (http: is only allowed on loopback with allowLocalhostHttp: true)",
203
+ });
204
+ }
205
+ if (parsed.protocol !== "https:") {
206
+ throw new SwarmClientError({
207
+ code: "INVALID_ARGUMENT",
208
+ operation,
209
+ message: `Unsupported VOW URL scheme "${parsed.protocol}" (expected https:)`,
210
+ });
211
+ }
212
+ if (parsed.port !== "" && parsed.port !== "443") {
213
+ throw new SwarmClientError({
214
+ code: "INVALID_ARGUMENT",
215
+ operation,
216
+ message: `Non-standard HTTPS port "${parsed.port}" is forbidden for VOW URLs`,
217
+ });
218
+ }
219
+ if (FORBIDDEN_EXACT_HOSTS.has(host) ||
220
+ FORBIDDEN_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix))) {
221
+ throw new SwarmClientError({
222
+ code: "INVALID_ARGUMENT",
223
+ operation,
224
+ message: `Forbidden internal or metadata hostname "${host}" in VOW URL`,
225
+ });
226
+ }
227
+ if (host.startsWith("[")) {
228
+ const ipv6 = parseIpv6Segments(host);
229
+ if (!ipv6 || isNonGlobalIpv6(ipv6)) {
230
+ throw new SwarmClientError({
231
+ code: "INVALID_ARGUMENT",
232
+ operation,
233
+ message: `Forbidden non-global or malformed IPv6 literal "${host}" in VOW URL`,
234
+ });
235
+ }
236
+ return parsed;
237
+ }
238
+ const ipv4 = parseIpv4Octets(host);
239
+ if (ipv4) {
240
+ if (isNonGlobalIpv4(ipv4[0], ipv4[1], ipv4[2], ipv4[3])) {
241
+ throw new SwarmClientError({
242
+ code: "INVALID_ARGUMENT",
243
+ operation,
244
+ message: `Forbidden private, loopback, or link-local IPv4 literal "${host}" in VOW URL`,
245
+ });
246
+ }
247
+ return parsed;
248
+ }
249
+ if (/^[\d.]+$/.test(host) || !host.includes(".")) {
250
+ throw new SwarmClientError({
251
+ code: "INVALID_ARGUMENT",
252
+ operation,
253
+ message: `Invalid or single-label hostname "${host}" in VOW URL`,
254
+ });
255
+ }
256
+ return parsed;
257
+ }
258
+ /**
259
+ * Safely fetch and JSON-decode a VOW v1 attestation document with `redirect: "error"`
260
+ * and a strict streaming byte cap (`DEFAULT_MAX_VOW_BYTES` = 2 MiB).
261
+ */
262
+ export async function fetchVowAttestationJson(rawUrl, opts) {
263
+ const operation = opts?.operation ?? "tasks.verifyVow";
264
+ const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_VOW_BYTES;
265
+ if (!Number.isInteger(maxBytes) || maxBytes <= 0) {
266
+ throw new SwarmClientError({
267
+ code: "INVALID_ARGUMENT",
268
+ operation,
269
+ message: `maxBytes must be a positive integer, got ${String(maxBytes)}`,
270
+ });
271
+ }
272
+ const validatedUrl = validateVowUrl(rawUrl, {
273
+ allowLocalhostHttp: opts?.allowLocalhostHttp,
274
+ operation,
275
+ });
276
+ const rawFetch = opts?.fetch ?? globalThis.fetch;
277
+ if (!rawFetch) {
278
+ throw new SwarmClientError({
279
+ code: "INVALID_ARGUMENT",
280
+ operation,
281
+ message: "A fetch implementation is required to retrieve VOW URLs",
282
+ });
283
+ }
284
+ const fetchImpl = opts?.fetch
285
+ ? (input, init) => opts.fetch(input, init)
286
+ : rawFetch.bind(globalThis);
287
+ let resp;
288
+ try {
289
+ resp = await fetchImpl(validatedUrl.toString(), {
290
+ method: "GET",
291
+ redirect: "error",
292
+ headers: { Accept: "application/json" },
293
+ });
294
+ }
295
+ catch (cause) {
296
+ if (cause instanceof SwarmClientError)
297
+ throw cause;
298
+ throw new SwarmClientError({
299
+ code: "NETWORK_ERROR",
300
+ operation,
301
+ message: `Failed to fetch VOW attestation (redirects are forbidden): ${cause instanceof Error ? cause.message : String(cause)}`,
302
+ cause,
303
+ });
304
+ }
305
+ if ((resp.status >= 300 && resp.status < 400) ||
306
+ resp.type === "opaqueredirect" ||
307
+ resp.redirected === true) {
308
+ await resp.body?.cancel?.().catch(() => undefined);
309
+ throw new SwarmClientError({
310
+ code: "INVALID_RESPONSE",
311
+ operation,
312
+ status: resp.status,
313
+ message: "HTTP redirects are forbidden when fetching VOW attestations",
314
+ });
315
+ }
316
+ if (!resp.ok) {
317
+ await resp.body?.cancel?.().catch(() => undefined);
318
+ throw new SwarmClientError({
319
+ code: "HTTP_ERROR",
320
+ operation,
321
+ status: resp.status,
322
+ message: `Failed to fetch VOW attestation: HTTP ${resp.status}`,
323
+ });
324
+ }
325
+ const contentLengthHeader = resp.headers?.get?.("content-length") ?? null;
326
+ if (contentLengthHeader !== null && contentLengthHeader.trim() !== "") {
327
+ const declaredLength = Number(contentLengthHeader.trim());
328
+ if (!Number.isFinite(declaredLength) || declaredLength < 0) {
329
+ await resp.body?.cancel?.().catch(() => undefined);
330
+ throw new SwarmClientError({
331
+ code: "INVALID_RESPONSE",
332
+ operation,
333
+ message: `Malformed Content-Length header on VOW response: ${contentLengthHeader}`,
334
+ });
335
+ }
336
+ if (declaredLength > maxBytes) {
337
+ await resp.body?.cancel?.().catch(() => undefined);
338
+ throw new SwarmClientError({
339
+ code: "INVALID_RESPONSE",
340
+ operation,
341
+ message: `VOW attestation Content-Length (${declaredLength} bytes) exceeds maxBytes (${maxBytes})`,
342
+ });
343
+ }
344
+ }
345
+ let utf8Text;
346
+ if (resp.body && typeof resp.body.getReader === "function") {
347
+ const reader = resp.body.getReader();
348
+ const chunks = [];
349
+ let totalBytes = 0;
350
+ try {
351
+ while (true) {
352
+ const { done, value } = await reader.read();
353
+ if (done)
354
+ break;
355
+ if (value) {
356
+ totalBytes += value.byteLength;
357
+ if (totalBytes > maxBytes) {
358
+ await reader.cancel().catch(() => undefined);
359
+ throw new SwarmClientError({
360
+ code: "INVALID_RESPONSE",
361
+ operation,
362
+ message: `VOW attestation response body exceeded maxBytes (${maxBytes} bytes)`,
363
+ });
364
+ }
365
+ chunks.push(value);
366
+ }
367
+ }
368
+ }
369
+ finally {
370
+ reader.releaseLock?.();
371
+ }
372
+ const combined = new Uint8Array(totalBytes);
373
+ let offset = 0;
374
+ for (const chunk of chunks) {
375
+ combined.set(chunk, offset);
376
+ offset += chunk.byteLength;
377
+ }
378
+ try {
379
+ utf8Text = new TextDecoder("utf-8", { fatal: true }).decode(combined);
380
+ }
381
+ catch (cause) {
382
+ throw new SwarmClientError({
383
+ code: "INVALID_RESPONSE",
384
+ operation,
385
+ message: "VOW attestation response is not valid UTF-8",
386
+ cause,
387
+ });
388
+ }
389
+ }
390
+ else {
391
+ utf8Text = await resp.text();
392
+ const encodedLen = new TextEncoder().encode(utf8Text).byteLength;
393
+ if (encodedLen > maxBytes) {
394
+ throw new SwarmClientError({
395
+ code: "INVALID_RESPONSE",
396
+ operation,
397
+ message: `VOW attestation response body exceeded maxBytes (${maxBytes} bytes)`,
398
+ });
399
+ }
400
+ }
401
+ try {
402
+ return JSON.parse(utf8Text);
403
+ }
404
+ catch (cause) {
405
+ throw new SwarmClientError({
406
+ code: "INVALID_RESPONSE",
407
+ operation,
408
+ message: "VOW attestation response is not valid JSON",
409
+ cause,
410
+ });
411
+ }
412
+ }
413
+ /**
414
+ * High-level VOW v1 verifier accepting an HTTPS URL, JSON string, or parsed object.
415
+ * Enforces SSRF host/IP validation, `redirect: "error"`, and a 2 MiB streaming body cap.
416
+ */
417
+ export async function verifyVow(urlOrJson, opts) {
418
+ const operation = opts?.operation ?? "tasks.verifyVow";
419
+ let attestation = urlOrJson;
420
+ if (typeof urlOrJson === "string") {
421
+ const trimmed = urlOrJson.trim();
422
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
423
+ try {
424
+ attestation = JSON.parse(trimmed);
425
+ }
426
+ catch (cause) {
427
+ throw new SwarmClientError({
428
+ code: "INVALID_ARGUMENT",
429
+ operation,
430
+ message: "Expected valid VOW URL, JSON string, or object",
431
+ cause,
432
+ });
433
+ }
434
+ }
435
+ else if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
436
+ attestation = await fetchVowAttestationJson(trimmed, opts);
437
+ }
438
+ else {
439
+ try {
440
+ attestation = JSON.parse(trimmed);
441
+ }
442
+ catch (cause) {
443
+ throw new SwarmClientError({
444
+ code: "INVALID_ARGUMENT",
445
+ operation,
446
+ message: "Expected VOW URL, JSON string, or object",
447
+ cause,
448
+ });
449
+ }
450
+ }
451
+ }
452
+ const defaultNet = opts?.network ?? "mainnet";
453
+ const net = attestation &&
454
+ typeof attestation === "object" &&
455
+ attestation.network === "devnet"
456
+ ? "devnet"
457
+ : defaultNet;
458
+ const conn = opts?.connection ??
459
+ new Connection(opts?.rpcUrl ?? DEFAULT_VOW_SOLANA_RPC[net], "confirmed");
460
+ return verifyV1(attestation, opts?.protocol ?? shillbotProtocol, conn, opts?.expectedScoreMax);
461
+ }
5
462
  /**
6
463
  * Step-by-step verifier per `docs/specs/vow-v1.md` §4.
7
464
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swarm-tips/client",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
4
4
  "description": "Typed browser and Node.js clients for Swarm Tips, Shillbot, and Coordination Game",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",