nansen-cli 1.44.0 → 1.44.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,58 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.44.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [#604](https://github.com/nansen-ai/nansen-cli/pull/604) [`9d541d7`](https://github.com/nansen-ai/nansen-cli/commit/9d541d7d6aef232b0761846f6e716222f67798c4) Thanks [@kome12](https://github.com/kome12)! - Bind limit-order deposits to the trusted vault destination: reject any deposit whose wallet-sourced transfer (SPL token or native SOL) does not land in a token account this same transaction creates via CreateAccountWithSeed seeded off the user's vault. Covers both the SPL-token and native-SOL deposit paths.
8
+
9
+ - [#600](https://github.com/nansen-ai/nansen-cli/pull/600) [`c86af55`](https://github.com/nansen-ai/nansen-cli/commit/c86af55dff3fa71c61726650ec66060b61d1918e) Thanks [@kome12](https://github.com/kome12)! - Isolate the response cache by credential and request context so cached
10
+ responses can no longer be shared across different API keys or API origins that
11
+ use the same cache directory. Cache keys now include the base URL, HTTP method,
12
+ and a hashed form of the effective credentials, and use SHA-256.
13
+
14
+ - [#612](https://github.com/nansen-ai/nansen-cli/pull/612) [`492b441`](https://github.com/nansen-ai/nansen-cli/commit/492b441d49df6e256b3e63645e16644bdec3a56c) Thanks [@gulshngill](https://github.com/gulshngill)! - Reject hard-linked `.credentials` files in the wallet-password fallback write, so the credential write cannot chmod, truncate, or overwrite an unrelated file
15
+
16
+ - [#611](https://github.com/nansen-ai/nansen-cli/pull/611) [`959225c`](https://github.com/nansen-ai/nansen-cli/commit/959225c1527540359763bb55a90f12fc4ffb14ea) Thanks [@gulshngill](https://github.com/gulshngill)! - Report `from_cache` telemetry from the API instance so it survives command handlers that rebuild their result, and pass it on the `alerts list --table` path, which previously never reported the field at all
17
+
18
+ - [#609](https://github.com/nansen-ai/nansen-cli/pull/609) [`288f566`](https://github.com/nansen-ai/nansen-cli/commit/288f566b674f8b550b19b26b4721e3fe68cc54f6) Thanks [@gulshngill](https://github.com/gulshngill)! - Fix `from_cache` telemetry always reporting `false` on cache hits
19
+
20
+ - [#586](https://github.com/nansen-ai/nansen-cli/pull/586) [`b254240`](https://github.com/nansen-ai/nansen-cli/commit/b25424008fe0202972ac706913721a3433f30d59) Thanks [@Kewe63](https://github.com/Kewe63)! - Tighten POSIX permissions when rewriting the fallback wallet credentials file and refuse non-regular credential paths.
21
+
22
+ - [#615](https://github.com/nansen-ai/nansen-cli/pull/615) [`9166884`](https://github.com/nansen-ai/nansen-cli/commit/916688496c2c83dee17e81a9b6c753a94b8ff0be) Thanks [@teyrebaz33](https://github.com/teyrebaz33)! - Fix `nansen transfer`/`nansen trade execute` with `--wallet walletconnect` using any connected EVM account instead of verifying the WalletConnect session is actually approved for the chain being signed/broadcast on.
23
+
24
+ `getWalletConnectAddress('evm')` matched any account whose CAIP-2 chain tag started with `eip155:`, regardless of which specific chain it was approved for. Because EVM addresses are identical across chains, a session connected only to Ethereum mainnet would be silently used to sign a transaction destined for Base (or vice versa) -- nothing downstream (including the quote/request-intent binding checks) could catch this, since they only compare addresses, not chains.
25
+
26
+ `getWalletConnectAddress` now accepts an optional `chainId`, and when given, only returns an account the session has approved for that exact chain (mirroring the mainnet-only exact match already used for Solana in the same function). Every place that resolves a WalletConnect EVM address before signing or broadcasting a real transaction now passes the target chain ID and fails closed with a clear error instead of proceeding with a wrong-chain session: `nansen transfer`'s `sendTokensViaWalletConnect`, and `nansen trade execute`'s quote-building, pre-execute wallet-match check, and immediate pre-signing check for its EVM WalletConnect swap path.
27
+
28
+ ## 1.44.1
29
+
30
+ ### Patch Changes
31
+
32
+ - [#588](https://github.com/nansen-ai/nansen-cli/pull/588) [`0db1c74`](https://github.com/nansen-ai/nansen-cli/commit/0db1c745b4cdfd05b47bd261159bace7b60f0854) Thanks [@Kewe63](https://github.com/Kewe63)! - Prevent duplicate alert creation after ambiguous network failures and keep Smart Alert mutations out of the response cache.
33
+
34
+ - [#595](https://github.com/nansen-ai/nansen-cli/pull/595) [`1e3fadb`](https://github.com/nansen-ai/nansen-cli/commit/1e3fadb346be2219e8d91ba417806ae7f5b9bcd9) Thanks [@devorun](https://github.com/devorun)! - Fix `--cache` reshaping a cached array response into an object. Endpoints that return a top-level JSON array were object-spread on a cache hit, so `[a, b]` came back as `{ 0: a, 1: b }` and every `Array.isArray()` branch downstream stopped matching — the first call printed rows and the second printed nothing. Cached arrays now stay arrays, and primitive response bodies are returned untouched instead of being exploded into character maps.
35
+
36
+ - [#589](https://github.com/nansen-ai/nansen-cli/pull/589) [`0cc4c18`](https://github.com/nansen-ai/nansen-cli/commit/0cc4c180e5525b6bf8a777d04401ac60b7c926a8) Thanks [@ygd58](https://github.com/ygd58)! - Fix `nansen alerts list --limit`/`--offset` silently misbehaving on invalid or edge-case input. `--limit 0` and `--offset 0` were treated as "not set" (falsy check) and silently ignored instead of honored; a non-numeric value like `--limit abc` silently returned zero results (`Array.prototype.slice` coerces `NaN` to `0`) instead of erroring; and a negative `--offset` was silently accepted by `slice()`, which treats negative indices as "from the end" — returning the wrong records instead of rejecting the input. Both flags are now validated as non-negative integers, matching the strict-validation convention already used elsewhere in the CLI (e.g. `--slippage`), and throw a clear `INVALID_PARAMS` error otherwise.
37
+
38
+ - [#577](https://github.com/nansen-ai/nansen-cli/pull/577) [`3c214a1`](https://github.com/nansen-ai/nansen-cli/commit/3c214a179a3f2c78a8b4b17e2c6b1177828bf2c6) Thanks [@batuhankocyigit](https://github.com/batuhankocyigit)! - Fix `nansen alerts create`/`update` silently dropping numeric range filters (`--usd-min/max`, `--market-cap-min/max`, `--fdv-min/max`, `--token-amount-min/max`, `--token-age-min/max`, and the `--inflow/outflow/netflow-*-min/max` flags) instead of rejecting bad input. These flags were converted with plain `Number(val)`, so a typo or garbage value (e.g. `--usd-min abc`) became `NaN`, which `JSON.stringify` silently turns into `null` in the request body — the alert would get created without the filter the user thought they'd set, with no error at any point. `--*-min`/`--*-max` now reject non-numeric input with a clear `Invalid --<flag> "<value>": must be a number` error; valid negative values (e.g. `--netflow-1h-min -5000` for a net-outflow filter) are unaffected.
39
+
40
+ - [#605](https://github.com/nansen-ai/nansen-cli/pull/605) [`9656d08`](https://github.com/nansen-ai/nansen-cli/commit/9656d08e2df3562ac650d299a5fc6b92bf00d8ad) Thanks [@kome12](https://github.com/kome12)! - Keep non-JSON 4xx responses from trade execute reusable instead of treating them as ambiguous broadcast failures.
41
+
42
+ - [#602](https://github.com/nansen-ai/nansen-cli/pull/602) [`9c72189`](https://github.com/nansen-ai/nansen-cli/commit/9c72189c6760c119784b3534a6777bd1a2e3ce11) Thanks [@kome12](https://github.com/kome12)! - trade limit-order cancel: give distinct, actionable errors when the refund can't be verified — a fully-filled order now says so plainly ("nothing left to refund") instead of sharing the same generic message as unparseable order metadata.
43
+
44
+ - [#598](https://github.com/nansen-ai/nansen-cli/pull/598) [`1450b66`](https://github.com/nansen-ai/nansen-cli/commit/1450b66ffab26d0d9fbe570c90de79916f405ffb) Thanks [@kome12](https://github.com/kome12)! - Close two dust-refund gaps in limit-order cancel verification: a native-SOL refund at or below the fee/rent slack could be "cancelled" by returning a single lamport while the rest of the escrow was rerouted, and a cancel now fails closed when the order is found but its remaining refund amount can't be computed instead of silently downgrading to a bare positive-inflow check.
45
+
46
+ - [#598](https://github.com/nansen-ai/nansen-cli/pull/598) [`b6d5baf`](https://github.com/nansen-ai/nansen-cli/commit/b6d5baf1b14ebd53287744eb23a1f9c4b7ac20a3) Thanks [@kome12](https://github.com/kome12)! - Limit-order create and cancel now verify the API-provided Solana transaction's simulated balance effect against the requested operation before signing, refusing to sign a deposit that would move unexpected funds out of the wallet or a cancel that fails to return the order's own deposited asset to it. The cancel check binds to the full expected remaining refund, not just a positive inflow, so a withdrawal that reroutes most of the escrow and returns only a dust amount of the right asset is refused. Also closes a gap where a cancel could pass on an inflow of any asset (not just the deposited one), and a tiny native-SOL deposit could pass on a fee-only outflow. The pre-cancel order lookup now paginates the active-order list, so an order beyond the first page can still be cancelled.
47
+
48
+ - [#582](https://github.com/nansen-ai/nansen-cli/pull/582) [`8e674c2`](https://github.com/nansen-ai/nansen-cli/commit/8e674c24c6c9340b2c658e511199ac546064fe9b) Thanks [@devorun](https://github.com/devorun)! - Telemetry now creates `~/.nansen` with mode 0700 and writes its id/session files with mode 0600, matching every other module that writes to that directory. Previously these were the only writes there that used default permissions, so when they were the first to create the directory (for example when authenticating with `NANSEN_API_KEY` instead of `nansen login`) it was left group- and world-readable.
49
+
50
+ - [#594](https://github.com/nansen-ai/nansen-cli/pull/594) [`95bdde1`](https://github.com/nansen-ai/nansen-cli/commit/95bdde151057b0bdc6b0bdc5efd67cc3420a9c44) Thanks [@Kewe63](https://github.com/Kewe63)! - Reject invalid cache TTL values before constructing the API client.
51
+
52
+ - [#593](https://github.com/nansen-ai/nansen-cli/pull/593) [`dfc908a`](https://github.com/nansen-ai/nansen-cli/commit/dfc908a74ebc9a6341629c43bea4d98df1219ccc) Thanks [@Kewe63](https://github.com/Kewe63)! - Reject invalid retry counts before constructing the API client.
53
+
54
+ - [#599](https://github.com/nansen-ai/nansen-cli/pull/599) [`bdbdcb2`](https://github.com/nansen-ai/nansen-cli/commit/bdbdcb222ae2f3a4f3b88c8832e7375c46559d79) Thanks [@kome12](https://github.com/kome12)! - x402 auto-pay now signs only for supported schemes and recognized payment networks (exact Solana mainnet CAIP-2 binding), and derives the EIP-712 chain id from the validated network. The EIP-712 domain version is now required across all signing backends (local, WalletConnect, Privy) so a missing version can no longer be silently defaulted to a wrong value, while a null/empty remote chain id is treated as unspecified rather than a conflict.
55
+
3
56
  ## 1.44.0
4
57
 
5
58
  ### Minor Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nansen-cli",
3
- "version": "1.44.0",
3
+ "version": "1.44.2",
4
4
  "description": "AI-agent CLI for Nansen API analytics, DEX swaps, and cross-chain trading",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
package/src/api.js CHANGED
@@ -246,19 +246,53 @@ const DEFAULT_CACHE_TTL = 300; // 5 minutes
246
246
 
247
247
  import crypto from 'crypto';
248
248
 
249
- /**
250
- * Generate cache key from endpoint and request body
251
- */
252
- function getCacheKey(endpoint, body) {
253
- const data = JSON.stringify({ endpoint, body });
254
- return crypto.createHash('md5').update(data).digest('hex');
249
+ const AUTH_HEADER_NAMES = ['apikey', 'authorization', 'payment-signature'];
250
+
251
+ // payment-signature is intentionally included: it is an auth credential and
252
+ // including it isolates caches between users with different static signatures.
253
+ // This is safe because:
254
+ // (a) User-supplied signatures (--x402-payment-signature) live in defaultHeaders
255
+ // and are stable across calls, keeping the identity hash stable.
256
+ // (b) Auto-generated signatures from the x402 retry path are added inside
257
+ // _x402Retry(), which calls fetch() directly and never goes through the
258
+ // cache check — so they never appear in options.headers here.
259
+ // INVARIANT: do not place a freshly-generated per-request Payment-Signature in
260
+ // options.headers before calling request() — it would produce a unique identity
261
+ // hash on every call and silently disable caching for those requests.
262
+ export function computeIdentityDigest(apiKey, ...headerSets) {
263
+ const authHeaders = {};
264
+ for (const headers of headerSets) {
265
+ if (!headers) continue;
266
+ for (const [name, value] of Object.entries(headers)) {
267
+ const lower = name.toLowerCase();
268
+ if (AUTH_HEADER_NAMES.includes(lower)) authHeaders[lower] = value;
269
+ }
270
+ }
271
+ const material = JSON.stringify({
272
+ apiKey: apiKey ?? null,
273
+ authHeaders: Object.fromEntries(
274
+ Object.entries(authHeaders).sort(([a], [b]) => a.localeCompare(b))
275
+ ),
276
+ });
277
+ return crypto.createHash('sha256').update(material).digest('hex');
278
+ }
279
+
280
+ function getCacheKey(endpoint, body, context = {}) {
281
+ const data = JSON.stringify({
282
+ endpoint,
283
+ body,
284
+ baseUrl: context.baseUrl ?? null,
285
+ method: context.method ?? null,
286
+ identity: context.identity ?? null,
287
+ });
288
+ return crypto.createHash('sha256').update(data).digest('hex');
255
289
  }
256
290
 
257
291
  /**
258
292
  * Get cached response if valid
259
293
  */
260
- export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL) {
261
- const cacheKey = getCacheKey(endpoint, body);
294
+ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL, context = {}) {
295
+ const cacheKey = getCacheKey(endpoint, body, context);
262
296
  const cacheFile = path.join(CACHE_DIR, `${cacheKey}.json`);
263
297
 
264
298
  if (!fs.existsSync(cacheFile)) {
@@ -275,7 +309,22 @@ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL
275
309
  return null;
276
310
  }
277
311
 
278
- return { ...cached.data, _meta: { ...cached.data._meta, fromCache: true, cacheAge: Math.round(age) } };
312
+ // Re-attach the cache marker without reshaping the payload. Object-spreading
313
+ // a top-level array turns it into { 0: …, 1: … }, so a cached array came back
314
+ // as an object and every Array.isArray() branch downstream (the table/CSV/
315
+ // markdown formatters in cli.js, alertsGet) stopped recognising it — the first
316
+ // call rendered rows and the second rendered nothing. Arrays therefore get
317
+ // _meta hung off the array itself, exactly as the live request path does when
318
+ // it records retriedAttempts, and primitives are handed back untouched
319
+ // because a non-object cannot carry the marker at all.
320
+ const meta = { ...cached.data?._meta, fromCache: true, cacheAge: Math.round(age) };
321
+ if (Array.isArray(cached.data)) {
322
+ const rows = cached.data.slice();
323
+ rows._meta = meta;
324
+ return rows;
325
+ }
326
+ if (cached.data === null || typeof cached.data !== 'object') return cached.data;
327
+ return { ...cached.data, _meta: meta };
279
328
  } catch (_e) {
280
329
  // Invalid cache file, delete it
281
330
  try { fs.unlinkSync(cacheFile); } catch { /* ignore */ }
@@ -286,12 +335,12 @@ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL
286
335
  /**
287
336
  * Save response to cache
288
337
  */
289
- export function setCachedResponse(endpoint, body, data) {
338
+ export function setCachedResponse(endpoint, body, data, context = {}) {
290
339
  if (!fs.existsSync(CACHE_DIR)) {
291
340
  fs.mkdirSync(CACHE_DIR, { mode: 0o700, recursive: true });
292
341
  }
293
-
294
- const cacheKey = getCacheKey(endpoint, body);
342
+
343
+ const cacheKey = getCacheKey(endpoint, body, context);
295
344
  const cacheFile = path.join(CACHE_DIR, `${cacheKey}.json`);
296
345
 
297
346
  const cached = {
@@ -528,6 +577,17 @@ export class NansenAPI {
528
577
  this.lastResponseMeta = null;
529
578
  /** API path of the most recent request(), for pairing lastResponseMeta with a cost estimate. */
530
579
  this.lastEndpoint = null;
580
+ /**
581
+ * Whether the most recent request() was answered from the local response
582
+ * cache instead of the network.
583
+ *
584
+ * Lives on the instance for the same reason lastResponseMeta does: a cache
585
+ * hit returns early, and a handler that rebuilds its result (alerts list,
586
+ * for one) drops the `_meta.fromCache` marker carried on the body, so the
587
+ * payload alone can't be trusted to still say so by the time telemetry
588
+ * reads it. Last write wins when a handler makes several calls.
589
+ */
590
+ this.servedFromCache = false;
531
591
  }
532
592
 
533
593
  static cleanBody(body) {
@@ -653,20 +713,33 @@ export class NansenAPI {
653
713
  // Check cache first (if enabled and not bypassed)
654
714
  const useCache = options.cache !== false && this.cacheOptions.enabled;
655
715
  const cacheTtl = options.cacheTtl ?? this.cacheOptions.ttl;
656
-
657
- if (useCache) {
658
- const cached = getCachedResponse(endpoint, body, cacheTtl);
716
+ const method = options.method || 'POST';
717
+ // Defer identity hashing to keep the uncached (default) path free of crypto work.
718
+ // cacheContext is therefore null unless caching is on; the `&& cacheContext`
719
+ // guards below ensure that null never reaches getCacheKey, where a missing
720
+ // identity would silently produce a credential-agnostic (shared) cache key.
721
+ const cacheContext = useCache
722
+ ? {
723
+ baseUrl: this.baseUrl,
724
+ method,
725
+ identity: computeIdentityDigest(this.apiKey, this.defaultHeaders, options.headers),
726
+ }
727
+ : null;
728
+
729
+ if (useCache && cacheContext) {
730
+ const cached = getCachedResponse(endpoint, body, cacheTtl, cacheContext);
659
731
  if (cached) {
732
+ this.servedFromCache = true;
660
733
  return cached;
661
734
  }
662
735
  }
736
+ this.servedFromCache = false;
663
737
 
664
738
  let lastError;
665
-
739
+
666
740
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
667
741
  let response;
668
742
  try {
669
- const method = options.method || 'POST';
670
743
  const isGet = method === 'GET';
671
744
  response = await fetch(url, {
672
745
  method,
@@ -885,8 +958,8 @@ export class NansenAPI {
885
958
  }
886
959
 
887
960
  // Cache successful response
888
- if (useCache) {
889
- setCachedResponse(endpoint, body, data);
961
+ if (useCache && cacheContext) {
962
+ setCachedResponse(endpoint, body, data, cacheContext);
890
963
  }
891
964
 
892
965
  // Attach after caching so the cache stores the payload alone — quota
@@ -1802,15 +1875,17 @@ export class NansenAPI {
1802
1875
  }
1803
1876
 
1804
1877
  async alertsCreate(params = {}) {
1805
- return this.request('/api/v1/smart-alert', params);
1878
+ // Creating an alert is non-idempotent: a lost response after a committed
1879
+ // create must not trigger another request through the generic retry loop.
1880
+ return this.request('/api/v1/smart-alert', params, { cache: false, retry: false });
1806
1881
  }
1807
1882
 
1808
1883
  async alertsUpdate(params = {}) {
1809
- return this.request('/api/v1/smart-alert', params, { method: 'PATCH' });
1884
+ return this.request('/api/v1/smart-alert', params, { method: 'PATCH', cache: false });
1810
1885
  }
1811
1886
 
1812
1887
  async alertsToggle(params = {}) {
1813
- return this.request('/api/v1/smart-alert/toggle', params, { method: 'PATCH' });
1888
+ return this.request('/api/v1/smart-alert/toggle', params, { method: 'PATCH', cache: false });
1814
1889
  }
1815
1890
 
1816
1891
  async alertsGet(id) {
@@ -1822,7 +1897,7 @@ export class NansenAPI {
1822
1897
  }
1823
1898
 
1824
1899
  async alertsDelete(alertId) {
1825
- return this.request(`/api/v1/smart-alert/${encodeURIComponent(alertId)}`, {}, { method: 'DELETE' });
1900
+ return this.request(`/api/v1/smart-alert/${encodeURIComponent(alertId)}`, {}, { method: 'DELETE', cache: false });
1826
1901
  }
1827
1902
  }
1828
1903
 
package/src/chain-ids.js CHANGED
@@ -4,6 +4,12 @@
4
4
  * Single source of truth — import from here instead of defining inline.
5
5
  */
6
6
 
7
+ // If you add a chain to EVM_CHAINS below, add its numeric chain ID here too.
8
+ // transfer.js's EVM transfer paths (both local-wallet and WalletConnect) look
9
+ // up the chain ID here and fail closed with "Unsupported chain" when it's
10
+ // missing -- so a chain listed in EVM_CHAINS but absent here can't actually
11
+ // be used to send a transfer yet, even though address-format validation and
12
+ // ENS resolution already accept it.
7
13
  export const EVM_CHAIN_IDS = {
8
14
  ethereum: 1,
9
15
  base: 8453,
package/src/cli.js CHANGED
@@ -220,6 +220,40 @@ export function parseArgs(args) {
220
220
  return result;
221
221
  }
222
222
 
223
+ function parseNonNegativeSafeIntegerOption(name, options, flags, defaultValue) {
224
+ if (flags[name]) {
225
+ throw new NansenError(
226
+ `--${name} requires a non-negative safe integer value`,
227
+ ErrorCode.INVALID_PARAMS,
228
+ );
229
+ }
230
+ if (options[name] === undefined) return defaultValue;
231
+
232
+ const rawValue = options[name];
233
+ if (Array.isArray(rawValue)) {
234
+ throw new NansenError(
235
+ `--${name} may only be specified once`,
236
+ ErrorCode.INVALID_PARAMS,
237
+ );
238
+ }
239
+ if (typeof rawValue === 'string' && rawValue.trim() === '') {
240
+ throw new NansenError(
241
+ `--${name} requires a non-negative safe integer value`,
242
+ ErrorCode.INVALID_PARAMS,
243
+ );
244
+ }
245
+ const value = typeof rawValue === 'string' || typeof rawValue === 'number'
246
+ ? Number(rawValue)
247
+ : NaN;
248
+ if (!Number.isSafeInteger(value) || value < 0) {
249
+ throw new NansenError(
250
+ `--${name} must be a non-negative safe integer; received: ${String(rawValue)}`,
251
+ ErrorCode.INVALID_PARAMS,
252
+ );
253
+ }
254
+ return value;
255
+ }
256
+
223
257
  // Format a single value for table display
224
258
  export function formatValue(val) {
225
259
  if (val === null || val === undefined) return '';
@@ -1180,7 +1214,7 @@ export function buildCommands(deps = {}) {
1180
1214
  log('CACHE OPTIONS (for any command):');
1181
1215
  log(' --cache Enable caching for this session');
1182
1216
  log(' --no-cache Bypass cache for this request');
1183
- log(' --cache-ttl <seconds> Set cache TTL (default: 300)');
1217
+ log(' --cache-ttl <seconds> Set non-negative safe integer cache TTL (default: 300)');
1184
1218
  }
1185
1219
  };
1186
1220
 
@@ -2039,15 +2073,16 @@ export async function runCLI(rawArgs, deps = {}) {
2039
2073
 
2040
2074
  try {
2041
2075
  // Configure retry options
2076
+ const maxRetries = parseNonNegativeSafeIntegerOption('retries', options, flags, 3);
2042
2077
  const retryOptions = flags['no-retry']
2043
2078
  ? { maxRetries: 0 }
2044
- : { maxRetries: options.retries !== undefined ? (Number.isNaN(parseInt(options.retries, 10)) ? 3 : parseInt(options.retries, 10)) : 3 };
2079
+ : { maxRetries };
2045
2080
 
2046
2081
  // Configure cache options
2047
- const cacheTtl = options['cache-ttl'] !== undefined ? parseInt(options['cache-ttl'], 10) : 300;
2082
+ const cacheTtl = parseNonNegativeSafeIntegerOption('cache-ttl', options, flags, 300);
2048
2083
  const cacheOptions = {
2049
2084
  enabled: flags['cache'] && !flags['no-cache'],
2050
- ttl: Number.isNaN(cacheTtl) ? 300 : cacheTtl
2085
+ ttl: cacheTtl
2051
2086
  };
2052
2087
 
2053
2088
  const defaultHeaders = {};
@@ -2066,6 +2101,19 @@ export async function runCLI(rawArgs, deps = {}) {
2066
2101
 
2067
2102
  let result = await commands[command](subArgs, api, flags, options);
2068
2103
 
2104
+ // The cache marker is hung off the payload's `_meta` by getCachedResponse(),
2105
+ // never as a top-level `fromCache`. Capture it here, before `--fields`
2106
+ // filtering below drops `_meta` along with every other unrequested key —
2107
+ // read any later and a cache hit with `--fields` reports as a live call.
2108
+ //
2109
+ // `_meta` alone isn't enough either: handlers are free to rebuild their
2110
+ // result and some do (`alerts list` filters the array into a fresh one),
2111
+ // which drops the marker before we get here. `api.servedFromCache` is set
2112
+ // on the instance next to the cache-hit early return in request(), so it
2113
+ // survives that reshaping. Compared against `true` so a stubbed API whose
2114
+ // every property is a mock function doesn't read as a hit.
2115
+ const fromCache = !!result?._meta?.fromCache || api.servedFromCache === true;
2116
+
2069
2117
  // Credit balance warning, from the headers on the call just made. Goes to
2070
2118
  // stderr so it never contaminates the JSON on stdout that agents parse.
2071
2119
  // Placed before every return path below so it fires for operational
@@ -2106,7 +2154,7 @@ export async function runCLI(rawArgs, deps = {}) {
2106
2154
  // Alerts list with --table uses custom table format
2107
2155
  if (command === 'alerts' && subcommand === 'list' && table) {
2108
2156
  output(formatAlertsTable(result));
2109
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
2157
+ await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2110
2158
  return { type: 'success', data: result };
2111
2159
  }
2112
2160
 
@@ -2117,14 +2165,14 @@ export async function runCLI(rawArgs, deps = {}) {
2117
2165
  if (streamOutput) {
2118
2166
  output(streamOutput);
2119
2167
  }
2120
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: !!result?.fromCache, flags: usedFlags, chain });
2168
+ await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2121
2169
  return { type: 'stream', data: result };
2122
2170
  }
2123
2171
 
2124
2172
  const successData = { success: true, data: result };
2125
2173
  const formatted = formatOutput(successData, { pretty, table, csv });
2126
2174
  output(formatted.text);
2127
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: !!result?.fromCache, flags: usedFlags, chain });
2175
+ await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2128
2176
  return { type: csv ? 'csv' : 'success', data: result };
2129
2177
  } catch (error) {
2130
2178
  // Unified error envelope across all command families (perp/bridge/trade):
@@ -107,15 +107,32 @@ function parseChains(chainsOpt) {
107
107
  return chainsOpt.split(',').map(s => s.trim()).filter(Boolean);
108
108
  }
109
109
 
110
+ /**
111
+ * Parse a CLI option value as a finite number, or throw a clear error.
112
+ *
113
+ * Plain `Number(val)` turns garbage input ("abc") into NaN, and
114
+ * `JSON.stringify` silently turns NaN into `null` — so a typo'd
115
+ * --usd-min/--market-cap-max/etc. would vanish from the request instead of
116
+ * failing loudly, and the alert would ship without the filter the user
117
+ * asked for.
118
+ */
119
+ function parseFiniteNumber(raw, name) {
120
+ const n = Number(raw);
121
+ if (!Number.isFinite(n)) {
122
+ throw new NansenError(`Invalid --${name} "${raw}": must be a number`, ErrorCode.INVALID_PARAMS);
123
+ }
124
+ return n;
125
+ }
126
+
110
127
  /**
111
128
  * Build a { min, max } range object from two option values.
112
129
  * Returns undefined if neither is provided.
113
130
  */
114
- function buildRange(minVal, maxVal) {
131
+ function buildRange(minVal, maxVal, name) {
115
132
  if (minVal === undefined && maxVal === undefined) return undefined;
116
133
  const r = {};
117
- if (minVal !== undefined) r.min = Number(minVal);
118
- if (maxVal !== undefined) r.max = Number(maxVal);
134
+ if (minVal !== undefined) r.min = parseFiniteNumber(minVal, `${name}-min`);
135
+ if (maxVal !== undefined) r.max = parseFiniteNumber(maxVal, `${name}-max`);
119
136
  return r;
120
137
  }
121
138
 
@@ -138,7 +155,7 @@ export function buildSmTokenFlowsData(options) {
138
155
 
139
156
  const flowFields = ['inflow-1h', 'inflow-1d', 'inflow-7d', 'outflow-1h', 'outflow-1d', 'outflow-7d', 'netflow-1h', 'netflow-1d', 'netflow-7d'];
140
157
  for (const field of flowFields) {
141
- const range = buildRange(options[`${field}-min`], options[`${field}-max`]);
158
+ const range = buildRange(options[`${field}-min`], options[`${field}-max`], field);
142
159
  if (range) {
143
160
  // Convert CLI key "inflow-1h" → data key "inflow_1h"
144
161
  data[field.replace(/-/g, '_')] = range;
@@ -156,13 +173,13 @@ export function buildSmTokenFlowsData(options) {
156
173
  if (excludeSectors) data.exclusion = { ...data.exclusion, tokenSectors: excludeSectors };
157
174
 
158
175
  if (options['token-age-max'] !== undefined) {
159
- data.inclusion = { ...data.inclusion, tokenAge: { max: Number(options['token-age-max']) } };
176
+ data.inclusion = { ...data.inclusion, tokenAge: { max: parseFiniteNumber(options['token-age-max'], 'token-age-max') } };
160
177
  }
161
178
 
162
- const marketCapRange = buildRange(options['market-cap-min'], options['market-cap-max']);
179
+ const marketCapRange = buildRange(options['market-cap-min'], options['market-cap-max'], 'market-cap');
163
180
  if (marketCapRange) data.inclusion = { ...data.inclusion, marketCap: marketCapRange };
164
181
 
165
- const fdvRange = buildRange(options['fdv-min'], options['fdv-max']);
182
+ const fdvRange = buildRange(options['fdv-min'], options['fdv-max'], 'fdv');
166
183
  if (fdvRange) data.inclusion = { ...data.inclusion, fdvUsd: fdvRange };
167
184
 
168
185
  return data;
@@ -181,10 +198,10 @@ export function buildCommonTokenTransferData(options) {
181
198
  data.events = typeof options.events === 'string' ? options.events.split(',') : options.events;
182
199
  }
183
200
 
184
- const usdRange = buildRange(options['usd-min'], options['usd-max']);
201
+ const usdRange = buildRange(options['usd-min'], options['usd-max'], 'usd');
185
202
  if (usdRange) data.usdValue = usdRange;
186
203
 
187
- const amountRange = buildRange(options['token-amount-min'], options['token-amount-max']);
204
+ const amountRange = buildRange(options['token-amount-min'], options['token-amount-max'], 'token-amount');
188
205
  if (amountRange) data.tokenAmount = amountRange;
189
206
 
190
207
  const subjects = parseSubjects(options.subject);
@@ -207,12 +224,12 @@ export function buildCommonTokenTransferData(options) {
207
224
  const tokenAgeMax = options['token-age-max'];
208
225
  if (tokenAgeMin !== undefined || tokenAgeMax !== undefined) {
209
226
  const tokenAge = {};
210
- if (tokenAgeMin !== undefined) tokenAge.min = Number(tokenAgeMin);
211
- if (tokenAgeMax !== undefined) tokenAge.max = Number(tokenAgeMax);
227
+ if (tokenAgeMin !== undefined) tokenAge.min = parseFiniteNumber(tokenAgeMin, 'token-age-min');
228
+ if (tokenAgeMax !== undefined) tokenAge.max = parseFiniteNumber(tokenAgeMax, 'token-age-max');
212
229
  data.inclusion = { ...data.inclusion, tokenAge };
213
230
  }
214
231
 
215
- const marketCapRange = buildRange(options['market-cap-min'], options['market-cap-max']);
232
+ const marketCapRange = buildRange(options['market-cap-min'], options['market-cap-max'], 'market-cap');
216
233
  if (marketCapRange) data.inclusion = { ...data.inclusion, marketCap: marketCapRange };
217
234
 
218
235
  const excludeFrom = parseSubjects(options['exclude-from']);
@@ -232,7 +249,7 @@ export function buildSmartContractCallData(options) {
232
249
  const chains = parseChains(options.chains);
233
250
  if (chains) data.chains = chains;
234
251
 
235
- const usdRange = buildRange(options['usd-min'], options['usd-max']);
252
+ const usdRange = buildRange(options['usd-min'], options['usd-max'], 'usd');
236
253
  if (usdRange) data.usdValue = usdRange;
237
254
 
238
255
  if (options['signature-hash']) {
@@ -606,9 +623,32 @@ USAGE:
606
623
  });
607
624
  }
608
625
 
609
- // Pagination (applied after filtering)
610
- if (options.offset) alerts = alerts.slice(Number(options.offset));
611
- if (options.limit) alerts = alerts.slice(0, Number(options.limit));
626
+ // Pagination (applied after filtering). Validate strictly rather than
627
+ // silently misbehaving on bad input:
628
+ // - `if (options.offset)` / `if (options.limit)` treat 0 as "not set"
629
+ // (falsy), so `--offset 0` / `--limit 0` were silently ignored
630
+ // instead of being honored.
631
+ // - `Number("abc")` is NaN, and `Array.prototype.slice` coerces a NaN
632
+ // argument to 0 — so `--offset abc` silently became a no-op and
633
+ // `--limit abc` silently returned zero results, with no error
634
+ // telling the caller their input wasn't a number at all.
635
+ // - Negative values (`--offset -1`) were accepted and fed straight
636
+ // into `slice()`, which treats negative indices as "from the end" —
637
+ // silently returning the wrong slice instead of rejecting the input.
638
+ if (options.offset !== undefined) {
639
+ const offset = Number(options.offset);
640
+ if (!Number.isInteger(offset) || offset < 0) {
641
+ throw new NansenError(`--offset must be a non-negative integer, got "${options.offset}"`, ErrorCode.INVALID_PARAMS);
642
+ }
643
+ alerts = alerts.slice(offset);
644
+ }
645
+ if (options.limit !== undefined) {
646
+ const limit = Number(options.limit);
647
+ if (!Number.isInteger(limit) || limit < 0) {
648
+ throw new NansenError(`--limit must be a non-negative integer, got "${options.limit}"`, ErrorCode.INVALID_PARAMS);
649
+ }
650
+ alerts = alerts.slice(0, limit);
651
+ }
612
652
 
613
653
  return alerts;
614
654
  },
package/src/keychain.js CHANGED
@@ -151,8 +151,38 @@ function credentialsFileWrite(password) {
151
151
  fs.mkdirSync(dir, { mode: 0o700, recursive: true });
152
152
  }
153
153
  const encoded = Buffer.from(password, 'utf8').toString('base64');
154
- fs.writeFileSync(filePath, `NANSEN_WALLET_PASSWORD_B64=${encoded}\n`, { mode: 0o600 });
155
- return true;
154
+ const content = `NANSEN_WALLET_PASSWORD_B64=${encoded}\n`;
155
+
156
+ // Windows does not implement POSIX modes or O_NOFOLLOW consistently.
157
+ if (process.platform === 'win32') {
158
+ fs.writeFileSync(filePath, content, { mode: 0o600 });
159
+ return true;
160
+ }
161
+
162
+ let fd;
163
+ try {
164
+ const flags = fs.constants.O_WRONLY
165
+ | fs.constants.O_CREAT
166
+ | fs.constants.O_NOFOLLOW
167
+ | fs.constants.O_NONBLOCK;
168
+ fd = fs.openSync(filePath, flags, 0o600);
169
+ const stats = fs.fstatSync(fd);
170
+ if (!stats.isFile()) throw new Error('Credentials path is not a regular file');
171
+ // O_NOFOLLOW only rejects symlinks. A hard link at .credentials points at
172
+ // a victim file that is indistinguishable by path or type, so refuse any
173
+ // regular file with extra links before fchmod/ftruncate touch it.
174
+ if (stats.nlink !== 1) throw new Error('Credentials file has unexpected hard links');
175
+
176
+ // Opening an existing file does not apply the requested mode. Tighten it
177
+ // before replacing the secret, then enforce the final mode after writing.
178
+ fs.fchmodSync(fd, 0o600);
179
+ fs.ftruncateSync(fd, 0);
180
+ fs.writeFileSync(fd, content, 'utf8');
181
+ fs.fchmodSync(fd, 0o600);
182
+ return true;
183
+ } finally {
184
+ if (fd !== undefined) fs.closeSync(fd);
185
+ }
156
186
  } catch {
157
187
  return false;
158
188
  }