nansen-cli 2.0.0 → 2.1.0

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 (55) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +37 -9
  3. package/docs/browser-login.md +13 -7
  4. package/package.json +2 -2
  5. package/scripts/postinstall.js +1 -1
  6. package/skills/nansen-agent-guide/SKILL.md +3 -3
  7. package/skills/nansen-alerts-webhook-listener/SKILL.md +1 -1
  8. package/skills/nansen-dca-tracker/SKILL.md +1 -1
  9. package/skills/nansen-defi-positions/SKILL.md +1 -1
  10. package/skills/nansen-exit-signals/SKILL.md +1 -1
  11. package/skills/nansen-fund-tracker/SKILL.md +1 -1
  12. package/skills/nansen-general-search/SKILL.md +1 -1
  13. package/skills/nansen-holder-analysis/SKILL.md +1 -1
  14. package/skills/nansen-limit-orders/SKILL.md +1 -1
  15. package/skills/nansen-perp-screener/SKILL.md +1 -1
  16. package/skills/nansen-perp-trader-profile/SKILL.md +1 -1
  17. package/skills/nansen-polymarket-deep-dive/SKILL.md +1 -1
  18. package/skills/nansen-polymarket-insider-scan/SKILL.md +1 -1
  19. package/skills/nansen-polymarket-trader-profile/SKILL.md +1 -1
  20. package/skills/nansen-portfolio-tracker/SKILL.md +1 -1
  21. package/skills/nansen-prediction-markets/SKILL.md +1 -1
  22. package/skills/nansen-sm-cross-chain-flows/SKILL.md +1 -1
  23. package/skills/nansen-smart-alerts/SKILL.md +1 -1
  24. package/skills/nansen-smart-money-alpha/SKILL.md +1 -1
  25. package/skills/nansen-smart-money-tracker/SKILL.md +1 -1
  26. package/skills/nansen-smart-money-trend/SKILL.md +1 -1
  27. package/skills/nansen-token-research/SKILL.md +1 -1
  28. package/skills/nansen-token-screener/SKILL.md +1 -1
  29. package/skills/nansen-token-transfer-analysis/SKILL.md +1 -1
  30. package/skills/nansen-trading/SKILL.md +1 -1
  31. package/skills/nansen-wallet-batch/SKILL.md +1 -1
  32. package/skills/nansen-wallet-clustering/SKILL.md +1 -1
  33. package/skills/nansen-wallet-deep-dive/SKILL.md +1 -1
  34. package/skills/nansen-wallet-keychain-migration/SKILL.md +1 -1
  35. package/skills/nansen-wallet-manager/SKILL.md +1 -1
  36. package/skills/nansen-wallet-profiler/SKILL.md +1 -1
  37. package/skills/nansen-web-fetcher/SKILL.md +1 -1
  38. package/skills/nansen-web-searcher/SKILL.md +1 -1
  39. package/src/auth-credentials.js +16 -4
  40. package/src/auth-device.js +1 -1
  41. package/src/auth-login.js +4 -5
  42. package/src/auth-state.js +10 -8
  43. package/src/auth-store-worker.js +4 -3
  44. package/src/auto-paginate.js +31 -15
  45. package/src/bridge.js +105 -77
  46. package/src/cache-inspect.js +3 -7
  47. package/src/cli.js +13 -12
  48. package/src/doctor.js +1 -1
  49. package/src/limit-order.js +1 -1
  50. package/src/local-file.js +75 -0
  51. package/src/schema.json +28 -3
  52. package/src/solana-tx.js +74 -0
  53. package/src/trading.js +76 -40
  54. package/src/wallet.js +16 -35
  55. package/src/x402-svm.js +165 -7
@@ -19,7 +19,7 @@ Browser login requests `nansen:api` for API-key-equivalent account API permissio
19
19
 
20
20
  Before any research command or loop, require an explicitly selected API key or saved browser session. Run `nansen auth status` first. Its cached/unverified metadata does not prove credential validity or unlocked storage. Cached access-token expiry alone does not mean the session is unusable: the CLI normally renews a selected session automatically during an already-authorized research task, without another consent request or a separate account check. Stop on anonymous selection, invalid authentication state, blocked or uncertain renewal/cleanup, or an actual authentication failure, including rejected or expired refresh authority. Follow the CLI error guidance; use the free `nansen account` check when troubleshooting calls for it. Do not unset a failed key, erase a session or switch to anonymous access to retry.
21
21
 
22
- Use `nansen login` for fresh browser approval when server admission and the supported platform cohort are enabled, or configure a conventional API key. `NANSEN_API_KEY` overrides the saved session. OpenClaw's optional `primaryEnv` mapping preserves configured API-key injection; it is not a required-key gate or proof of authentication. Normal credits and entitlements apply. Login does not purchase credits. Browser rollout acceptance is still pending.
22
+ Use `nansen login` for fresh browser approval within the documented platform scope, or configure a conventional API key. `NANSEN_API_KEY` overrides the saved session. OpenClaw's optional `primaryEnv` mapping preserves configured API-key injection; it is not a required-key gate or proof of authentication. Normal credits and entitlements apply. Login does not purchase credits. Browser login is available in CLI 2.0.0 within the [macOS arm64 preview scope](https://github.com/nansen-ai/nansen-cli/blob/main/docs/browser-login.md#preview-platform-scope).
23
23
 
24
24
  API keys and browser sessions use the same automatic x402 payment behavior: a supported HTTP 402 challenge can spend funds from the configured wallet under existing wallet authorization, payment policy and spending limits. Each call, including calls in loops, can incur a payment. Authentication, authorization and session-renewal failures never trigger payment; login verification and `nansen account` never pay automatically. Anonymous x402 remains available as a separate paid workflow requiring explicit user intent and payment setup. Do not run this research workflow anonymously or switch to anonymous access after authentication fails.
25
25
 
@@ -17,7 +17,7 @@ allowed-tools: Bash(nansen:*)
17
17
  ---
18
18
  ## Authentication
19
19
 
20
- Nansen account API calls accept a selected `nansen:api` browser session or conventional API key with the same permissions. `NANSEN_API_KEY` takes precedence; optional `primaryEnv` preserves configured-key injection. Run `nansen auth status` for offline selection. Cached access expiry alone permits automatic renewal during an authorized task. Stop on anonymous selection, invalid state, blocked/uncertain renewal or actual auth failure; never drop a credential or fall back to anonymous x402 payment. Browser login does not grant wallet signing, privileged service identity or a persistent MCP integration key. Preserve all confirmation, signing, sanctions and geographic checks below. Browser rollout acceptance is still pending.
20
+ Nansen account API calls accept a selected `nansen:api` browser session or conventional API key with the same permissions. `NANSEN_API_KEY` takes precedence; optional `primaryEnv` preserves configured-key injection. Run `nansen auth status` for offline selection. Cached access expiry alone permits automatic renewal during an authorized task. Stop on anonymous selection, invalid state, blocked/uncertain renewal or actual auth failure; never drop a credential or fall back to anonymous x402 payment. Browser login does not grant wallet signing, privileged service identity or a persistent MCP integration key. Preserve all confirmation, signing, sanctions and geographic checks below. Browser login is available in CLI 2.0.0 within the [macOS arm64 preview scope](https://github.com/nansen-ai/nansen-cli/blob/main/docs/browser-login.md#preview-platform-scope).
21
21
 
22
22
 
23
23
 
@@ -19,7 +19,7 @@ Browser login requests `nansen:api` for API-key-equivalent account API permissio
19
19
 
20
20
  Before any research command or loop, require an explicitly selected API key or saved browser session. Run `nansen auth status` first. Its cached/unverified metadata does not prove credential validity or unlocked storage. Cached access-token expiry alone does not mean the session is unusable: the CLI normally renews a selected session automatically during an already-authorized research task, without another consent request or a separate account check. Stop on anonymous selection, invalid authentication state, blocked or uncertain renewal/cleanup, or an actual authentication failure, including rejected or expired refresh authority. Follow the CLI error guidance; use the free `nansen account` check when troubleshooting calls for it. Do not unset a failed key, erase a session or switch to anonymous access to retry.
21
21
 
22
- Use `nansen login` for fresh browser approval when server admission and the supported platform cohort are enabled, or configure a conventional API key. `NANSEN_API_KEY` overrides the saved session. OpenClaw's optional `primaryEnv` mapping preserves configured API-key injection; it is not a required-key gate or proof of authentication. Normal credits and entitlements apply. Login does not purchase credits. Browser rollout acceptance is still pending.
22
+ Use `nansen login` for fresh browser approval within the documented platform scope, or configure a conventional API key. `NANSEN_API_KEY` overrides the saved session. OpenClaw's optional `primaryEnv` mapping preserves configured API-key injection; it is not a required-key gate or proof of authentication. Normal credits and entitlements apply. Login does not purchase credits. Browser login is available in CLI 2.0.0 within the [macOS arm64 preview scope](https://github.com/nansen-ai/nansen-cli/blob/main/docs/browser-login.md#preview-platform-scope).
23
23
 
24
24
  API keys and browser sessions use the same automatic x402 payment behavior: a supported HTTP 402 challenge can spend funds from the configured wallet under existing wallet authorization, payment policy and spending limits. Each call, including calls in loops, can incur a payment. Authentication, authorization and session-renewal failures never trigger payment; login verification and `nansen account` never pay automatically. Anonymous x402 remains available as a separate paid workflow requiring explicit user intent and payment setup. Do not run this research workflow anonymously or switch to anonymous access after authentication fails.
25
25
 
@@ -19,7 +19,7 @@ Browser login requests `nansen:api` for API-key-equivalent account API permissio
19
19
 
20
20
  Before any research command or loop, require an explicitly selected API key or saved browser session. Run `nansen auth status` first. Its cached/unverified metadata does not prove credential validity or unlocked storage. Cached access-token expiry alone does not mean the session is unusable: the CLI normally renews a selected session automatically during an already-authorized research task, without another consent request or a separate account check. Stop on anonymous selection, invalid authentication state, blocked or uncertain renewal/cleanup, or an actual authentication failure, including rejected or expired refresh authority. Follow the CLI error guidance; use the free `nansen account` check when troubleshooting calls for it. Do not unset a failed key, erase a session or switch to anonymous access to retry.
21
21
 
22
- Use `nansen login` for fresh browser approval when server admission and the supported platform cohort are enabled, or configure a conventional API key. `NANSEN_API_KEY` overrides the saved session. OpenClaw's optional `primaryEnv` mapping preserves configured API-key injection; it is not a required-key gate or proof of authentication. Normal credits and entitlements apply. Login does not purchase credits. Browser rollout acceptance is still pending.
22
+ Use `nansen login` for fresh browser approval within the documented platform scope, or configure a conventional API key. `NANSEN_API_KEY` overrides the saved session. OpenClaw's optional `primaryEnv` mapping preserves configured API-key injection; it is not a required-key gate or proof of authentication. Normal credits and entitlements apply. Login does not purchase credits. Browser login is available in CLI 2.0.0 within the [macOS arm64 preview scope](https://github.com/nansen-ai/nansen-cli/blob/main/docs/browser-login.md#preview-platform-scope).
23
23
 
24
24
  API keys and browser sessions use the same automatic x402 payment behavior: a supported HTTP 402 challenge can spend funds from the configured wallet under existing wallet authorization, payment policy and spending limits. Each call, including calls in loops, can incur a payment. Authentication, authorization and session-renewal failures never trigger payment; login verification and `nansen account` never pay automatically. Anonymous x402 remains available as a separate paid workflow requiring explicit user intent and payment setup. Do not run this research workflow anonymously or switch to anonymous access after authentication fails.
25
25
 
@@ -19,7 +19,7 @@ Browser login requests `nansen:api` for API-key-equivalent account API permissio
19
19
 
20
20
  Before any research command or loop, require an explicitly selected API key or saved browser session. Run `nansen auth status` first. Its cached/unverified metadata does not prove credential validity or unlocked storage. Cached access-token expiry alone does not mean the session is unusable: the CLI normally renews a selected session automatically during an already-authorized research task, without another consent request or a separate account check. Stop on anonymous selection, invalid authentication state, blocked or uncertain renewal/cleanup, or an actual authentication failure, including rejected or expired refresh authority. Follow the CLI error guidance; use the free `nansen account` check when troubleshooting calls for it. Do not unset a failed key, erase a session or switch to anonymous access to retry.
21
21
 
22
- Use `nansen login` for fresh browser approval when server admission and the supported platform cohort are enabled, or configure a conventional API key. `NANSEN_API_KEY` overrides the saved session. OpenClaw's optional `primaryEnv` mapping preserves configured API-key injection; it is not a required-key gate or proof of authentication. Normal credits and entitlements apply. Login does not purchase credits. Browser rollout acceptance is still pending.
22
+ Use `nansen login` for fresh browser approval within the documented platform scope, or configure a conventional API key. `NANSEN_API_KEY` overrides the saved session. OpenClaw's optional `primaryEnv` mapping preserves configured API-key injection; it is not a required-key gate or proof of authentication. Normal credits and entitlements apply. Login does not purchase credits. Browser login is available in CLI 2.0.0 within the [macOS arm64 preview scope](https://github.com/nansen-ai/nansen-cli/blob/main/docs/browser-login.md#preview-platform-scope).
23
23
 
24
24
  API keys and browser sessions use the same automatic x402 payment behavior: a supported HTTP 402 challenge can spend funds from the configured wallet under existing wallet authorization, payment policy and spending limits. Each call, including calls in loops, can incur a payment. Authentication, authorization and session-renewal failures never trigger payment; login verification and `nansen account` never pay automatically. Anonymous x402 remains available as a separate paid workflow requiring explicit user intent and payment setup. Do not run this research workflow anonymously or switch to anonymous access after authentication fails.
25
25
 
@@ -15,7 +15,7 @@ allowed-tools: Bash(nansen:*)
15
15
  ---
16
16
  ## Authentication
17
17
 
18
- Nansen account API calls accept a selected `nansen:api` browser session or conventional API key with the same permissions. `NANSEN_API_KEY` takes precedence; optional `primaryEnv` preserves configured-key injection. Run `nansen auth status` for offline selection. Cached access expiry alone permits automatic renewal during an authorized task. Stop on anonymous selection, invalid state, blocked/uncertain renewal or actual auth failure; never drop a credential or fall back to anonymous x402 payment. Browser login does not grant wallet signing, privileged service identity or a persistent MCP integration key. Preserve all confirmation, signing, sanctions and geographic checks below. Browser rollout acceptance is still pending.
18
+ Nansen account API calls accept a selected `nansen:api` browser session or conventional API key with the same permissions. `NANSEN_API_KEY` takes precedence; optional `primaryEnv` preserves configured-key injection. Run `nansen auth status` for offline selection. Cached access expiry alone permits automatic renewal during an authorized task. Stop on anonymous selection, invalid state, blocked/uncertain renewal or actual auth failure; never drop a credential or fall back to anonymous x402 payment. Browser login does not grant wallet signing, privileged service identity or a persistent MCP integration key. Preserve all confirmation, signing, sanctions and geographic checks below. Browser login is available in CLI 2.0.0 within the [macOS arm64 preview scope](https://github.com/nansen-ai/nansen-cli/blob/main/docs/browser-login.md#preview-platform-scope).
19
19
 
20
20
 
21
21
 
@@ -15,7 +15,7 @@ allowed-tools: Bash(nansen:*)
15
15
  ---
16
16
  ## Authentication
17
17
 
18
- Nansen account API calls accept a selected `nansen:api` browser session or conventional API key with the same permissions. `NANSEN_API_KEY` takes precedence; optional `primaryEnv` preserves configured-key injection. Run `nansen auth status` for offline selection. Cached access expiry alone permits automatic renewal during an authorized task. Stop on anonymous selection, invalid state, blocked/uncertain renewal or actual auth failure; never drop a credential or fall back to anonymous x402 payment. Browser login does not grant wallet signing, privileged service identity or a persistent MCP integration key. Preserve all confirmation, signing, sanctions and geographic checks below. Browser rollout acceptance is still pending.
18
+ Nansen account API calls accept a selected `nansen:api` browser session or conventional API key with the same permissions. `NANSEN_API_KEY` takes precedence; optional `primaryEnv` preserves configured-key injection. Run `nansen auth status` for offline selection. Cached access expiry alone permits automatic renewal during an authorized task. Stop on anonymous selection, invalid state, blocked/uncertain renewal or actual auth failure; never drop a credential or fall back to anonymous x402 payment. Browser login does not grant wallet signing, privileged service identity or a persistent MCP integration key. Preserve all confirmation, signing, sanctions and geographic checks below. Browser login is available in CLI 2.0.0 within the [macOS arm64 preview scope](https://github.com/nansen-ai/nansen-cli/blob/main/docs/browser-login.md#preview-platform-scope).
19
19
 
20
20
 
21
21
 
@@ -19,7 +19,7 @@ Browser login requests `nansen:api` for API-key-equivalent account API permissio
19
19
 
20
20
  Before any research command or loop, require an explicitly selected API key or saved browser session. Run `nansen auth status` first. Its cached/unverified metadata does not prove credential validity or unlocked storage. Cached access-token expiry alone does not mean the session is unusable: the CLI normally renews a selected session automatically during an already-authorized research task, without another consent request or a separate account check. Stop on anonymous selection, invalid authentication state, blocked or uncertain renewal/cleanup, or an actual authentication failure, including rejected or expired refresh authority. Follow the CLI error guidance; use the free `nansen account` check when troubleshooting calls for it. Do not unset a failed key, erase a session or switch to anonymous access to retry.
21
21
 
22
- Use `nansen login` for fresh browser approval when server admission and the supported platform cohort are enabled, or configure a conventional API key. `NANSEN_API_KEY` overrides the saved session. OpenClaw's optional `primaryEnv` mapping preserves configured API-key injection; it is not a required-key gate or proof of authentication. Normal credits and entitlements apply. Login does not purchase credits. Browser rollout acceptance is still pending.
22
+ Use `nansen login` for fresh browser approval within the documented platform scope, or configure a conventional API key. `NANSEN_API_KEY` overrides the saved session. OpenClaw's optional `primaryEnv` mapping preserves configured API-key injection; it is not a required-key gate or proof of authentication. Normal credits and entitlements apply. Login does not purchase credits. Browser login is available in CLI 2.0.0 within the [macOS arm64 preview scope](https://github.com/nansen-ai/nansen-cli/blob/main/docs/browser-login.md#preview-platform-scope).
23
23
 
24
24
  API keys and browser sessions use the same automatic x402 payment behavior: a supported HTTP 402 challenge can spend funds from the configured wallet under existing wallet authorization, payment policy and spending limits. Each call, including calls in loops, can incur a payment. Authentication, authorization and session-renewal failures never trigger payment; login verification and `nansen account` never pay automatically. Anonymous x402 remains available as a separate paid workflow requiring explicit user intent and payment setup. Do not run this research workflow anonymously or switch to anonymous access after authentication fails.
25
25
 
@@ -15,7 +15,7 @@ allowed-tools: Bash(nansen:*)
15
15
  ---
16
16
  ## Authentication
17
17
 
18
- Nansen account API calls accept a selected `nansen:api` browser session or conventional API key with the same permissions. `NANSEN_API_KEY` takes precedence; optional `primaryEnv` preserves configured-key injection. Run `nansen auth status` for offline selection. Cached access expiry alone permits automatic renewal during an authorized task. Stop on anonymous selection, invalid state, blocked/uncertain renewal or actual auth failure; never drop a credential or fall back to anonymous x402 payment. Browser login does not grant wallet signing, privileged service identity or a persistent MCP integration key. Preserve all confirmation, signing, sanctions and geographic checks below. Browser rollout acceptance is still pending.
18
+ Nansen account API calls accept a selected `nansen:api` browser session or conventional API key with the same permissions. `NANSEN_API_KEY` takes precedence; optional `primaryEnv` preserves configured-key injection. Run `nansen auth status` for offline selection. Cached access expiry alone permits automatic renewal during an authorized task. Stop on anonymous selection, invalid state, blocked/uncertain renewal or actual auth failure; never drop a credential or fall back to anonymous x402 payment. Browser login does not grant wallet signing, privileged service identity or a persistent MCP integration key. Preserve all confirmation, signing, sanctions and geographic checks below. Browser login is available in CLI 2.0.0 within the [macOS arm64 preview scope](https://github.com/nansen-ai/nansen-cli/blob/main/docs/browser-login.md#preview-platform-scope).
19
19
 
20
20
 
21
21
 
@@ -15,7 +15,7 @@ allowed-tools: Bash(nansen:*)
15
15
  ---
16
16
  ## Authentication
17
17
 
18
- Nansen account API calls accept a selected `nansen:api` browser session or conventional API key with the same permissions. `NANSEN_API_KEY` takes precedence; optional `primaryEnv` preserves configured-key injection. Run `nansen auth status` for offline selection. Cached access expiry alone permits automatic renewal during an authorized task. Stop on anonymous selection, invalid state, blocked/uncertain renewal or actual auth failure; never drop a credential or fall back to anonymous x402 payment. Browser login does not grant wallet signing, privileged service identity or a persistent MCP integration key. Preserve all confirmation, signing, sanctions and geographic checks below. Browser rollout acceptance is still pending.
18
+ Nansen account API calls accept a selected `nansen:api` browser session or conventional API key with the same permissions. `NANSEN_API_KEY` takes precedence; optional `primaryEnv` preserves configured-key injection. Run `nansen auth status` for offline selection. Cached access expiry alone permits automatic renewal during an authorized task. Stop on anonymous selection, invalid state, blocked/uncertain renewal or actual auth failure; never drop a credential or fall back to anonymous x402 payment. Browser login does not grant wallet signing, privileged service identity or a persistent MCP integration key. Preserve all confirmation, signing, sanctions and geographic checks below. Browser login is available in CLI 2.0.0 within the [macOS arm64 preview scope](https://github.com/nansen-ai/nansen-cli/blob/main/docs/browser-login.md#preview-platform-scope).
19
19
 
20
20
 
21
21
 
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import os from 'node:os';
4
4
  import { fileURLToPath } from 'node:url';
5
+ import { readLocalFile } from './local-file.js';
5
6
 
6
7
  export const DEFAULT_API_ORIGIN = 'https://api.nansen.ai';
7
8
  const DEV_CONFIG = fileURLToPath(new URL('../config.json', import.meta.url));
@@ -32,21 +33,32 @@ export function validAuthPointer(auth) {
32
33
  }
33
34
  export function readAuthConfig(env = process.env, devConfigPath = DEV_CONFIG) {
34
35
  const userPath = path.join(authDirectory(env), 'config.json');
35
- const configPath = fs.existsSync(userPath) ? userPath : fs.existsSync(devConfigPath) ? devConfigPath : null;
36
+ let configFileExists;
37
+ try { configFileExists = Boolean(fs.lstatSync(userPath, { throwIfNoEntry: false })); }
38
+ catch { return { config: {}, configPath: userPath, configError: 'unreadable', configFileExists: true, devConfigPath }; }
39
+ const configPath = configFileExists ? userPath : fs.existsSync(devConfigPath) ? devConfigPath : null;
36
40
  let config = {};
37
41
  let configError = null;
38
42
  if (configPath) {
39
43
  try {
40
- config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
44
+ const options = { root: path.dirname(configPath), privateFile: configPath === userPath };
45
+ let contents;
46
+ try { contents = readLocalFile(configPath, options); }
47
+ catch (error) {
48
+ // Login and renewal replace config atomically. Revalidate once from scratch.
49
+ if (!error.localFileRace) throw error;
50
+ contents = readLocalFile(configPath, options);
51
+ }
52
+ config = JSON.parse(contents);
41
53
  if (!config || typeof config !== 'object' || Array.isArray(config)) throw new Error();
42
54
  } catch (err) { config = {}; configError = err instanceof SyntaxError ? 'parse' : 'unreadable'; }
43
55
  }
44
56
  if (config.auth && !validAuthPointer(config.auth)) configError = 'format';
45
- return { config, configPath, configError, configFileExists: fs.existsSync(userPath), devConfigPath };
57
+ return { config, configPath, configError, configFileExists, devConfigPath };
46
58
  }
47
59
  export function resolveCredential({ env = process.env, explicitKey, snapshot = readAuthConfig(env) } = {}) {
48
60
  if (explicitKey !== undefined) return explicitKey === null ? { kind: 'anonymous', source: null } : { kind: 'api-key', source: 'explicit', apiKey: explicitKey };
49
- if (env.NANSEN_API_KEY !== undefined) return { kind: 'api-key', source: 'env', apiKey: env.NANSEN_API_KEY };
61
+ if (typeof env.NANSEN_API_KEY === 'string' && env.NANSEN_API_KEY.trim()) return { kind: 'api-key', source: 'env', apiKey: env.NANSEN_API_KEY };
50
62
  if (snapshot.configError) return { kind: 'invalid', source: 'config', error: snapshot.configError };
51
63
  const { config } = snapshot;
52
64
  if (config.auth?.active?.kind === 'session') return { kind: 'session', source: 'session', ...config.auth.active, selectionEpoch: config.auth.selectionEpoch };
@@ -119,7 +119,7 @@ export function validateSession(bundle, now = Date.now(), { allowExpired = false
119
119
  const publicJwk = createPublicKey(createPrivateKey({ key: bundle.privateJwk, format: 'jwk' })).export({ format: 'jwk' });
120
120
  const jkt = createHash('sha256').update(JSON.stringify({ crv: publicJwk.crv, kty: publicJwk.kty, x: publicJwk.x, y: publicJwk.y })).digest('base64url');
121
121
  if (extra || !signature || h.alg !== 'ES256' || publicJwk.crv !== 'P-256' || claims.iss !== bundle.issuer || claims.aud !== bundle.audience || claims.scope !== 'nansen:api' || claims.cnf?.jkt !== jkt || !Number.isFinite(claims.exp) || !Number.isFinite(bundle.expiresAt) || bundle.expiresAt > claims.exp * 1000) throw new Error();
122
- if (claims.session_access_revocation_version !== 1) throw new AuthError('BROWSER_SESSION_SETUP_REQUIRED', 'The session lacks supported revocation coverage. Browser login may not be enabled for this cohort. Ask the operator to verify issuer SESSION_ACCESS_REVOCATION_ENABLED and API BROWSER_SESSION_ACCOUNT_ENABLED before retrying; repeated pairing will not repair server setup.');
122
+ if (claims.session_access_revocation_version !== 1) throw new AuthError('BROWSER_SESSION_SETUP_REQUIRED', "The session lacks supported revocation coverage. Run nansen login again. If this persists, ask support to check the session issuer's API audience and revocation claim.");
123
123
  if (!Number.isFinite(claims.iat) || !Number.isFinite(claims.nbf) || claims.exp <= claims.iat || typeof claims.sub !== 'string' || !claims.sub || (bundle.accountId !== undefined && claims.sub !== bundle.accountId)) throw new Error();
124
124
  if (claims.exp - claims.iat > 3600) throw lifetimeError();
125
125
  if (claims.nbf > now / 1000 + 60) throw new AuthError('SESSION_CLOCK_SKEW', 'Session time is ahead of the local clock. Synchronize system time and check issuer clock configuration before retrying login.');
package/src/auth-login.js CHANGED
@@ -54,11 +54,10 @@ export async function browserLogin({ flags = {}, env = process.env, isTTY = proc
54
54
  cleanup.push(...result.cleanup);
55
55
  try { cleanup.push(...await state.finish(attempt)); } catch { cleanup.push({ local: 'incomplete', remote: 'unconfirmed' }); }
56
56
  attempt = null;
57
- const override = env.NANSEN_API_KEY !== undefined;
58
- const overrideMessage = override && !env.NANSEN_API_KEY.trim()
59
- ? 'NANSEN_API_KEY is blank. Commands will fail until you unset it or supply a valid environment key.'
60
- : 'Commands still use NANSEN_API_KEY. Unset it to use this session.';
61
- progress(override ? `Browser session saved for ${bundle.accountId}. ${overrideMessage}` : `Browser session saved for ${bundle.accountId}.`);
57
+ const override = Boolean(env.NANSEN_API_KEY?.trim());
58
+ progress(override
59
+ ? `Browser session saved for ${bundle.accountId}. Commands still use NANSEN_API_KEY. Unset it to use this session.`
60
+ : `Browser session saved for ${bundle.accountId}.`);
62
61
  for (const message of cleanupMessage(cleanup)) progress(message);
63
62
  emit('saved', { account_id: bundle.accountId, effective_source: override ? 'env' : 'session', cleanup });
64
63
  } catch (error) {
package/src/auth-state.js CHANGED
@@ -5,6 +5,7 @@ import { setTimeout as delay } from 'node:timers/promises';
5
5
  import { AuthError, authDirectory, validAuthPointer } from './auth-credentials.js';
6
6
  import { createAuthStore } from './auth-store.js';
7
7
  import { refreshSession, retireSession, validateSession } from './auth-device.js';
8
+ import { openLocalFile, readLocalFile } from './local-file.js';
8
9
 
9
10
  const queues = new Map();
10
11
  const MAX_RETRYABLE_RENEWALS = 5;
@@ -16,8 +17,8 @@ const journalExists = file => {
16
17
  };
17
18
  const stateError = () => new AuthError('AUTH_STATE_INVALID', 'Saved authentication cannot be read safely. Repair config.json permissions or restore the file; no other credential was selected.');
18
19
  function safePath(file, directory = false) {
19
- if (!fs.existsSync(file)) return;
20
- const stat = fs.lstatSync(file);
20
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
21
+ if (!stat) return;
21
22
  if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()) ||
22
23
  (process.platform !== 'win32' && ((stat.mode & 0o022) || stat.uid !== process.getuid()))) throw stateError();
23
24
  }
@@ -25,8 +26,7 @@ const uuid = value => typeof value === 'string' && /^[a-f0-9-]{36}$/.test(value)
25
26
  function readJournal(file, id) {
26
27
  try {
27
28
  safePath(file);
28
- if (fs.statSync(file).size > 4096) throw journalError();
29
- const value = JSON.parse(fs.readFileSync(file, 'utf8'));
29
+ const value = JSON.parse(readLocalFile(file, { root: path.dirname(path.dirname(file)), privateFile: true, maxBytes: 4096 }));
30
30
  if (value?.id !== id) throw journalError();
31
31
  if (value.kind === 'rotation') {
32
32
  if (value.version !== 2 || value.id !== value.selectionEpoch || !uuid(value.selectionEpoch) ||
@@ -78,7 +78,7 @@ async function waitTurn(previous, signal) {
78
78
  }
79
79
  async function loadLocks() {
80
80
  try { return (await import('fs-native-extensions')).default; }
81
- catch { throw new AuthError('AUTH_LOCK_UNAVAILABLE', 'Native authentication locking is unavailable. Reinstall nansen-cli with optional dependencies to save or remove authentication. Legacy key setup and logout also require this binding. Environment API keys still work. For offline saved-key removal, stop every CLI/auth process, then follow docs/browser-login.md#offline-recovery-without-native-locking. Do not delete auth journals or wallet files.'); }
81
+ catch { throw new AuthError('AUTH_LOCK_UNAVAILABLE', 'Native authentication locking is unavailable. Reinstall nansen-cli with optional dependencies; if they are installed, this platform may lack a compatible fs-native-extensions prebuild. Legacy key setup and logout require this binding. Environment API keys still work. For offline saved-key removal, stop every CLI/auth process, then follow docs/browser-login.md#offline-recovery-without-native-locking. Do not delete auth journals or wallet files.'); }
82
82
  }
83
83
  export function createAuthState({ directory = authDirectory(), store = createAuthStore({ directory }), retire = retireSession, refresh = refreshSession, now = Date.now, barrier = async () => {}, locks = loadLocks, waitMs = 15000, operationMs = 60000 } = {}) {
84
84
  let operationSignal;
@@ -96,7 +96,7 @@ export function createAuthState({ directory = authDirectory(), store = createAut
96
96
  safePath(configFile);
97
97
  if (!fs.existsSync(configFile)) return {};
98
98
  try {
99
- const value = JSON.parse(fs.readFileSync(configFile, 'utf8'));
99
+ const value = JSON.parse(readLocalFile(configFile, { root: directory, privateFile: true }));
100
100
  if (!value || typeof value !== 'object' || Array.isArray(value) || (value.auth && !validAuthPointer(value.auth))) throw new Error();
101
101
  return value;
102
102
  } catch { throw stateError(); }
@@ -129,7 +129,9 @@ export function createAuthState({ directory = authDirectory(), store = createAut
129
129
  const native = await locks();
130
130
  signal?.throwIfAborted();
131
131
  safePath(file);
132
- const fd = fs.openSync(file, 'a+', 0o600);
132
+ let fd;
133
+ try { fd = openLocalFile(file, { root: directory, flags: fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_APPEND, privateFile: true }); }
134
+ catch { throw stateError(); }
133
135
 
134
136
  try {
135
137
  while (!native.tryLock(fd)) {
@@ -250,7 +252,7 @@ export function createAuthState({ directory = authDirectory(), store = createAut
250
252
  }
251
253
  const blockedReason = error => ({ SESSION_REFRESH_REJECTED: 'rejected', BROWSER_SESSION_SETUP_REQUIRED: 'setup', SESSION_CLOCK_SKEW: 'clock', SESSION_EXPIRED: 'expired', SESSION_REFRESH_PROTOCOL_ERROR: 'protocol' }[error.code] || 'uncertain');
252
254
  function renewalError(reason) {
253
- if (reason === 'setup') return new AuthError('BROWSER_SESSION_SETUP_REQUIRED', 'The renewed session has incompatible issuer setup. Ask the operator to verify the supported 3600-second lifetime, SESSION_ACCESS_REVOCATION_ENABLED and BROWSER_SESSION_ACCOUNT_ENABLED. Renewal may have consumed the credential; do not retry it. Pair again only after server setup is repaired.');
255
+ if (reason === 'setup') return new AuthError('BROWSER_SESSION_SETUP_REQUIRED', 'The renewed session has incompatible issuer setup. Ask support to check the supported 3600-second lifetime and revocation coverage. Renewal may have consumed the credential; do not retry it. Run nansen login after the issuer is fixed.');
254
256
  if (reason === 'clock') return new AuthError('SESSION_CLOCK_SKEW', 'The renewed session is ahead of the local clock. Synchronize system time, then run nansen login. The possibly consumed refresh credential will not be retried.');
255
257
  if (reason === 'expired') return new AuthError('SESSION_EXPIRED', 'The renewed access token was already expired. Check system time and issuer configuration, then run nansen login. The possibly consumed refresh credential will not be retried.');
256
258
  if (reason === 'retry_exhausted') return new AuthError('SESSION_REFRESH_RETRY_EXHAUSTED', 'Session renewal repeatedly failed before rotation. Check connectivity, system time and issuer availability, then run nansen login. Automatic renewal is stopped for this session.');
@@ -4,6 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { Worker } from 'node:worker_threads';
6
6
  import locks from 'fs-native-extensions';
7
+ import { openLocalFile } from './local-file.js';
7
8
 
8
9
  const stop = () => process.kill(process.pid, 'SIGKILL');
9
10
  const timer = setTimeout(stop, 10000);
@@ -13,8 +14,8 @@ process.stdout.on('error', stop);
13
14
  let input = '', phase = 'guard';
14
15
  let fd;
15
16
  function safe(file, directory = false) {
16
- if (!fs.existsSync(file)) return;
17
- const stat = fs.lstatSync(file);
17
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
18
+ if (!stat) return;
18
19
  if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()) ||
19
20
  (process.platform !== 'win32' && ((stat.mode & 0o022) || stat.uid !== process.getuid()))) throw new Error();
20
21
  }
@@ -27,7 +28,7 @@ function receive(line) {
27
28
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
28
29
  const file = path.join(directory, 'auth-store.lock');
29
30
  safe(file);
30
- fd = fs.openSync(file, 'a+', 0o600);
31
+ fd = openLocalFile(file, { root: directory, flags: fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_APPEND, privateFile: true });
31
32
  // Independent acquisition: no cross-platform inherited-lock assumptions.
32
33
  // This stable inode is never unlinked, including by recovery.
33
34
  if (!locks.tryLock(fd)) throw new Error();
@@ -16,14 +16,23 @@ export const DEFAULT_MAX_PAGES = 10;
16
16
  // unbounded memory and billed API work from a long-running agent.
17
17
  export const MAX_PAGES_LIMIT = 1000;
18
18
 
19
+ function hasObjectRows(rows) {
20
+ return rows.every(row => row !== null && typeof row === 'object' && !Array.isArray(row));
21
+ }
22
+
19
23
  // Shared by collectPages and cli.js's formatTable/formatCsv/formatStream so
20
24
  // pagination and output formatting recognise the same row shapes.
21
- export function locateRows(page, { descriptive = false } = {}) {
25
+ export function locateRows(page, { descriptive = false, descriptiveKey, allowEmptyDescriptive = false } = {}) {
22
26
  if (page?.success === false) return null;
23
- if (Array.isArray(page)) return { rows: page, rebuild: rows => ({ data: rows }) };
24
- if (Array.isArray(page?.data)) return { rows: page.data, rebuild: rows => ({ ...page, data: rows }) };
25
- if (Array.isArray(page?.results)) return { rows: page.results, rebuild: rows => ({ ...page, results: rows }) };
26
- if (Array.isArray(page?.data?.data)) {
27
+ if (descriptiveKey) {
28
+ const rows = page?.[descriptiveKey];
29
+ if (!Array.isArray(rows) || !hasObjectRows(rows)) return null;
30
+ return { rows, key: descriptiveKey, rebuild: mergedRows => ({ ...page, [descriptiveKey]: mergedRows }) };
31
+ }
32
+ if (Array.isArray(page) && hasObjectRows(page)) return { rows: page, rebuild: rows => ({ data: rows }) };
33
+ if (Array.isArray(page?.data) && hasObjectRows(page.data)) return { rows: page.data, rebuild: rows => ({ ...page, data: rows }) };
34
+ if (Array.isArray(page?.results) && hasObjectRows(page.results)) return { rows: page.results, rebuild: rows => ({ ...page, results: rows }) };
35
+ if (Array.isArray(page?.data?.data) && hasObjectRows(page.data.data)) {
27
36
  return {
28
37
  rows: page.data.data,
29
38
  rebuild: rows => {
@@ -35,7 +44,7 @@ export function locateRows(page, { descriptive = false } = {}) {
35
44
  },
36
45
  };
37
46
  }
38
- if (Array.isArray(page?.data?.results)) {
47
+ if (Array.isArray(page?.data?.results) && hasObjectRows(page.data.results)) {
39
48
  return {
40
49
  rows: page.data.results,
41
50
  rebuild: rows => {
@@ -47,15 +56,18 @@ export function locateRows(page, { descriptive = false } = {}) {
47
56
  }
48
57
 
49
58
  // Older endpoints use a descriptive top-level key (`trades`, `holdings`,
50
- // `balances`, etc.) rather than `data`. A single array is unambiguous; do
51
- // not count pagination metadata as rows or guess when an envelope contains
52
- // several independent data arrays.
59
+ // `balances`, etc.) rather than `data`. Only a populated array of objects
60
+ // can identify rows here. Empty or primitive arrays may be envelope fields.
53
61
  if (descriptive && page && typeof page === 'object') {
54
- const arrays = Object.entries(page)
55
- .filter(([key, value]) => key !== 'pagination' && Array.isArray(value));
56
- if (arrays.length === 1) {
57
- const [key, rows] = arrays[0];
58
- return { rows, rebuild: mergedRows => ({ ...page, [key]: mergedRows }) };
62
+ const fields = Object.entries(page).filter(([key]) => key !== 'pagination' && key !== 'success');
63
+ const arrays = fields.filter(([, value]) => Array.isArray(value) && value.length > 0 && hasObjectRows(value));
64
+ // Pagination can recognize an empty first page only when the array is
65
+ // the entire payload apart from status and pagination metadata.
66
+ const emptyOnly = allowEmptyDescriptive && fields.length === 1
67
+ && Array.isArray(fields[0][1]) && fields[0][1].length === 0;
68
+ if (arrays.length === 1 || (arrays.length === 0 && emptyOnly)) {
69
+ const [key, rows] = arrays[0] || fields[0];
70
+ return { rows, key, rebuild: mergedRows => ({ ...page, [key]: mergedRows }) };
59
71
  }
60
72
  }
61
73
  return null;
@@ -139,7 +151,11 @@ export async function collectPages(fetchPage, pagination, { maxPages = DEFAULT_M
139
151
  const res = await fetchPage({ ...pagination, page });
140
152
  pagesFetched++;
141
153
  if (res?.success === false) throw failedPageError(res, page);
142
- const located = locateRows(res, { descriptive: true });
154
+ const located = locateRows(res, {
155
+ descriptive: true,
156
+ descriptiveKey: first?.key,
157
+ allowEmptyDescriptive: first === undefined,
158
+ });
143
159
  if (first === undefined) {
144
160
  if (!located) return res;
145
161
  first = located;