nansen-cli 2.3.0 → 2.5.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 (80) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/README.md +61 -38
  3. package/docs/auth.md +56 -0
  4. package/docs/browser-login.md +101 -7
  5. package/docs/error-codes.md +251 -0
  6. package/package.json +10 -4
  7. package/skills/nansen-agent-guide/SKILL.md +20 -4
  8. package/skills/nansen-alerts-webhook-listener/SKILL.md +17 -14
  9. package/skills/nansen-dca-tracker/SKILL.md +1 -1
  10. package/skills/nansen-defi-positions/SKILL.md +1 -1
  11. package/skills/nansen-exit-signals/SKILL.md +2 -2
  12. package/skills/nansen-fund-tracker/SKILL.md +1 -1
  13. package/skills/nansen-general-search/SKILL.md +1 -1
  14. package/skills/nansen-holder-analysis/SKILL.md +2 -2
  15. package/skills/nansen-limit-orders/SKILL.md +9 -1
  16. package/skills/nansen-mpp-payment/SKILL.md +2 -2
  17. package/skills/nansen-perp-screener/SKILL.md +1 -1
  18. package/skills/nansen-perp-trader-profile/SKILL.md +1 -1
  19. package/skills/nansen-polymarket-deep-dive/SKILL.md +1 -1
  20. package/skills/nansen-polymarket-insider-scan/SKILL.md +1 -1
  21. package/skills/nansen-polymarket-trader-profile/SKILL.md +1 -1
  22. package/skills/nansen-portfolio-tracker/SKILL.md +1 -1
  23. package/skills/nansen-prediction-markets/SKILL.md +1 -1
  24. package/skills/nansen-sm-cross-chain-flows/SKILL.md +1 -1
  25. package/skills/nansen-smart-alerts/SKILL.md +5 -2
  26. package/skills/nansen-smart-money-alpha/SKILL.md +1 -1
  27. package/skills/nansen-smart-money-tracker/SKILL.md +8 -7
  28. package/skills/nansen-smart-money-trend/SKILL.md +1 -1
  29. package/skills/nansen-token-research/SKILL.md +1 -1
  30. package/skills/nansen-token-screener/SKILL.md +1 -1
  31. package/skills/nansen-token-transfer-analysis/SKILL.md +1 -1
  32. package/skills/nansen-trading/SKILL.md +23 -2
  33. package/skills/nansen-wallet-batch/SKILL.md +1 -1
  34. package/skills/nansen-wallet-clustering/SKILL.md +1 -1
  35. package/skills/nansen-wallet-deep-dive/SKILL.md +1 -1
  36. package/skills/nansen-wallet-keychain-migration/SKILL.md +1 -1
  37. package/skills/nansen-wallet-manager/SKILL.md +11 -5
  38. package/skills/nansen-wallet-profiler/SKILL.md +1 -1
  39. package/skills/nansen-web-fetcher/SKILL.md +1 -1
  40. package/skills/nansen-web-searcher/SKILL.md +1 -1
  41. package/src/api-endpoints.json +1605 -0
  42. package/src/api.js +282 -124
  43. package/src/auth-credentials.js +1 -0
  44. package/src/auth-key-input.js +57 -9
  45. package/src/auth-state.js +2 -2
  46. package/src/auth-store-native.js +6 -1
  47. package/src/auth-store-worker.js +1 -1
  48. package/src/auth-store.js +9 -4
  49. package/src/auto-paginate.js +25 -7
  50. package/src/bridge.js +19 -10
  51. package/src/cache-inspect.js +16 -6
  52. package/src/cli.js +272 -114
  53. package/src/commands/agent.js +2 -3
  54. package/src/commands/alerts.js +365 -18
  55. package/src/commands/completion.js +4 -1
  56. package/src/commands/feedback.js +98 -37
  57. package/src/commands/mcp.js +1 -1
  58. package/src/commands/research.js +14 -37
  59. package/src/cost-cache.js +33 -7
  60. package/src/doctor.js +14 -5
  61. package/src/ens.js +14 -5
  62. package/src/error-codes.js +228 -0
  63. package/src/execute-guard.js +8 -3
  64. package/src/input-validation.js +555 -0
  65. package/src/limit-order.js +127 -54
  66. package/src/perp.js +358 -35
  67. package/src/privy.js +90 -15
  68. package/src/query-options.js +47 -8
  69. package/src/response-cache-files.js +65 -0
  70. package/src/response-meta.js +8 -2
  71. package/src/rpc-urls.js +3 -1
  72. package/src/schema.json +1254 -156
  73. package/src/solana-tx.js +4 -0
  74. package/src/telemetry-flags.js +75 -0
  75. package/src/trade-validation.js +167 -8
  76. package/src/trading.js +243 -20
  77. package/src/transfer.js +79 -12
  78. package/src/update-check.js +32 -5
  79. package/src/wallet.js +246 -69
  80. package/src/walletconnect-x402.js +27 -9
@@ -5,7 +5,7 @@
5
5
 
6
6
  import crypto from 'crypto';
7
7
  import { NansenError, ErrorCode, statusToErrorCode, browserSessionError, browserSessionResponseMeta, telemetryHeaders, packageVersion } from '../api.js';
8
- import { getCostForEndpoint } from '../cost-cache.js';
8
+ import { getCostForEndpoint, formatCost } from '../cost-cache.js';
9
9
  import { readResponseMeta } from '../response-meta.js';
10
10
 
11
11
  /**
@@ -167,11 +167,10 @@ export function buildAgentCommands(deps = {}) {
167
167
  'agent': async (args, apiInstance, flags, options) => {
168
168
  // ── Help ──
169
169
  if (flags.help || flags.h || args[0] === 'help' || args.length === 0) {
170
- const fmtCost = (c) => `${c.free} credit${c.free === 1 ? '' : 's'} (Free tier) / ${c.pro} credit${c.pro === 1 ? '' : 's'} (Pro tier)`;
171
170
  const fastCost = getCostForEndpoint('/api/v1/agent/fast');
172
171
  const expertCost = getCostForEndpoint('/api/v1/agent/expert');
173
172
  const costSection = (fastCost || expertCost)
174
- ? `\nCOST:\n${fastCost ? ` fast: ${fmtCost(fastCost)}\n` : ''}${expertCost ? ` expert: ${fmtCost(expertCost)}\n` : ''}`
173
+ ? `\nCOST:\n${fastCost ? ` fast: ${formatCost(fastCost)}\n` : ''}${expertCost ? ` expert: ${formatCost(expertCost)}\n` : ''}`
175
174
  : '';
176
175
  log(`nansen agent — Nansen Research Agent
177
176
 
@@ -5,6 +5,290 @@
5
5
 
6
6
  import { NansenError, ErrorCode } from '../api.js';
7
7
  import { parseCsvOption } from '../query-options.js';
8
+ import { unknownCommandError } from '../input-validation.js';
9
+ import { hasControlChars, readWebhookSecretInput } from '../auth-key-input.js';
10
+
11
+ // ============= Webhook signing secret input =============
12
+
13
+ /** Environment variable read for the webhook signing secret. */
14
+ export const WEBHOOK_SECRET_ENV = 'NANSEN_WEBHOOK_SECRET';
15
+
16
+ /**
17
+ * Resolve the webhook signing secret for create/update, or undefined.
18
+ *
19
+ * Sources, in order: --webhook-secret <secret> or --webhook-secret-stdin
20
+ * (passing both is an error), then NANSEN_WEBHOOK_SECRET. An explicit option
21
+ * overrides the environment, as --api-key overrides NANSEN_API_KEY. The
22
+ * environment is read only together with --webhook, so a variable exported for
23
+ * other commands never adds a secret to an alert that has no webhook channel.
24
+ * Errors never quote the secret.
25
+ */
26
+ export async function resolveWebhookSecret(options, flags, { env = process.env, stdin = process.stdin, stdinTTY } = {}) {
27
+ // A bare `--webhook-secret` (no value) lands in flags, possibly as
28
+ // `[true, true]` when repeated; any presence counts as the flag being given.
29
+ const bareFlag = flags['webhook-secret'] !== undefined;
30
+ const fromFlag = Object.hasOwn(options, 'webhook-secret') || bareFlag;
31
+ const fromStdin = flags['webhook-secret-stdin'] !== undefined;
32
+ if (fromFlag && fromStdin) {
33
+ throw new NansenError('Use either --webhook-secret or --webhook-secret-stdin, not both.', ErrorCode.INVALID_PARAMS);
34
+ }
35
+ if (fromFlag) {
36
+ if (bareFlag && Object.hasOwn(options, 'webhook-secret')) {
37
+ throw new NansenError('--webhook-secret can only be passed once', ErrorCode.INVALID_PARAMS);
38
+ }
39
+ if (bareFlag) {
40
+ throw new NansenError('--webhook-secret requires a value. To keep the secret out of shell history, use --webhook-secret-stdin or NANSEN_WEBHOOK_SECRET instead.', ErrorCode.MISSING_PARAM);
41
+ }
42
+ if (!options.webhook) throw new NansenError('--webhook-secret requires --webhook', ErrorCode.INVALID_PARAMS);
43
+ return { value: options['webhook-secret'], source: '--webhook-secret' };
44
+ }
45
+ if (fromStdin) {
46
+ if (!options.webhook) throw new NansenError('--webhook-secret-stdin requires --webhook', ErrorCode.INVALID_PARAMS);
47
+ const value = await readWebhookSecretInput(stdin, stdinTTY ?? stdin?.isTTY);
48
+ return { value, source: '--webhook-secret-stdin' };
49
+ }
50
+ const value = typeof env?.[WEBHOOK_SECRET_ENV] === 'string' ? env[WEBHOOK_SECRET_ENV].trim() : '';
51
+ if (!value || !options.webhook) return undefined;
52
+ // Same rule as stdin: a line break means more than one value.
53
+ if (hasControlChars(value)) {
54
+ throw new NansenError(`${WEBHOOK_SECRET_ENV} must be a single line without control characters.`, ErrorCode.INVALID_PARAMS);
55
+ }
56
+ return { value, source: WEBHOOK_SECRET_ENV };
57
+ }
58
+
59
+ // ============= Channel secret redaction =============
60
+
61
+ export const REDACTED = '****';
62
+
63
+ // Webhook hosts with a known URL shape, and how many leading path segments
64
+ // identify the channel without granting access: Slack keeps /services/<team>,
65
+ // Discord keeps /api/webhooks/<id>. Any other URL keeps only its scheme and
66
+ // port, since a custom endpoint can carry a token in any part of its hostname,
67
+ // the path or the query.
68
+ const KNOWN_WEBHOOK_HOSTS = [
69
+ { host: /^hooks\.slack\.com$/i, keepSegments: 2 },
70
+ { host: /^(?:ptb\.|canary\.)?discord(?:app)?\.com$/i, keepSegments: 3 },
71
+ ];
72
+
73
+ const SECRET_KEY_PATTERN = /url|secret|token|key|password|auth/i;
74
+
75
+ /**
76
+ * Mask a webhook URL. Userinfo, query, hash and at least the last path segment
77
+ * are always dropped. A value that does not parse as an http(s) URL is masked
78
+ * entirely.
79
+ */
80
+ export function redactUrl(url) {
81
+ let parsed;
82
+ try {
83
+ parsed = new URL(String(url).replace(/\\\//g, '/'));
84
+ } catch {
85
+ return REDACTED;
86
+ }
87
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return REDACTED;
88
+ const known = KNOWN_WEBHOOK_HOSTS.find(h => h.host.test(parsed.hostname));
89
+ const host = known ? parsed.hostname : REDACTED;
90
+ const origin = `${parsed.protocol}//${host}${parsed.port ? `:${parsed.port}` : ''}`;
91
+ const segments = parsed.pathname.split('/').filter(Boolean);
92
+ const keep = known ? Math.min(known.keepSegments, Math.max(0, segments.length - 1)) : 0;
93
+ return [origin, ...segments.slice(0, keep), REDACTED].join('/');
94
+ }
95
+
96
+ // Everything under a credential key is a credential, whatever its type: a
97
+ // number, a boolean, or an object whose own keys look harmless (`{ value }`).
98
+ // Only URLs get the partial, identifying mask; null stays null.
99
+ function maskSecretValue(key, value) {
100
+ if (value == null) return value;
101
+ if (typeof value === 'string') return /url/i.test(key) ? redactUrl(value) : REDACTED;
102
+ if (Array.isArray(value)) return value.map(v => maskSecretValue(key, v));
103
+ if (typeof value === 'object') {
104
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, maskSecretValue(/url/i.test(k) ? k : key, v)]));
105
+ }
106
+ return REDACTED;
107
+ }
108
+
109
+ function redactChannelData(value) {
110
+ if (Array.isArray(value)) return value.map(redactChannelData);
111
+ if (!value || typeof value !== 'object') return value;
112
+ const out = {};
113
+ for (const [key, v] of Object.entries(value)) {
114
+ out[key] = SECRET_KEY_PATTERN.test(key) ? maskSecretValue(key, v) : redactChannelData(v);
115
+ }
116
+ return out;
117
+ }
118
+
119
+ /**
120
+ * Return a copy of an alerts API response with channel credentials masked:
121
+ * Slack/Discord/webhook URLs and webhook signing secrets. Anyone holding a
122
+ * webhook URL can post to the channel, and CLI output is routinely pasted into
123
+ * chats, logs and tickets, so these are hidden unless --reveal is passed.
124
+ * Works on any response shape by masking every `channels` array it finds.
125
+ * Telegram chat IDs are not credentials and stay visible.
126
+ */
127
+ export function redactAlertSecrets(value) {
128
+ if (Array.isArray(value)) return value.map(redactAlertSecrets);
129
+ if (!value || typeof value !== 'object') return value;
130
+ const out = {};
131
+ for (const [key, v] of Object.entries(value)) {
132
+ if (key === 'channels' && Array.isArray(v)) {
133
+ // The whole channel, not just `data`, in case credentials sit at its top level.
134
+ out[key] = v.map(redactChannelData);
135
+ } else {
136
+ out[key] = redactAlertSecrets(v);
137
+ }
138
+ }
139
+ return out;
140
+ }
141
+
142
+ // Any http(s) URL in error text, including the JSON-escaped `https:\/\/` form.
143
+ // Alert errors have no reason to quote URLs other than channels and the
144
+ // Nansen links the CLI's own errors point to, so everything else is masked
145
+ // rather than guessing which are webhooks.
146
+ const URL_IN_TEXT = /https?:(?:\\?\/){2}[^\s"'<>]+/gi;
147
+ // Exact URLs, not hosts: a generic webhook can point at any host and path,
148
+ // including a nansen.ai one. A URL differing in any part (path, query, hash,
149
+ // port, userinfo) is masked. Trailing sentence punctuation is ignored.
150
+ const NANSEN_LINKS = new Set([
151
+ 'https://docs.nansen.ai/',
152
+ 'https://docs.nansen.ai/getting-started/error-handling',
153
+ 'https://app.nansen.ai/api?tab=api',
154
+ 'https://app.nansen.ai/auth/agent-setup',
155
+ ]);
156
+
157
+ function isNansenLink(url) {
158
+ try {
159
+ return NANSEN_LINKS.has(new URL(url.replace(/\\\//g, '/').replace(/[.,;:!?)\]]+$/, '')).href);
160
+ } catch {
161
+ return false;
162
+ }
163
+ }
164
+
165
+ // Keys in a request payload whose values are credentials. Narrower than
166
+ // SECRET_KEY_PATTERN so alert filters such as `tokens` or `tokenSectors`
167
+ // are not mistaken for secrets and masked out of error messages: `token` and
168
+ // `key` count only at the end of a key (`accessToken`, `apiKey`).
169
+ const CREDENTIAL_KEY_PATTERN = /url|secret|password|passphrase|credential|token$|key$|^auth/i;
170
+
171
+ const maskCredential = v => (/^https?:/i.test(v) ? redactUrl(v) : REDACTED);
172
+
173
+ // Mask credential-keyed fields anywhere in an error body, not only inside
174
+ // `channels`: an error can echo a stored secret on its own (`{ detail: { secret } }`),
175
+ // including on `list`, where there is no request payload to match it against.
176
+ // Nansen URLs (e.g. links to docs) stay readable.
177
+ function maskCredentialKeys(value) {
178
+ if (Array.isArray(value)) return value.map(maskCredentialKeys);
179
+ if (!value || typeof value !== 'object') return value;
180
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => {
181
+ if (!CREDENTIAL_KEY_PATTERN.test(k)) return [k, maskCredentialKeys(v)];
182
+ return [k, typeof v === 'string' && isNansenLink(v) ? v : maskSecretValue(k, v)];
183
+ }));
184
+ }
185
+
186
+ // Credential values in a request payload (channel flags, --data, or existing
187
+ // alert data merged into an update) or in an error body. Every string or
188
+ // number under a credential key counts, at any depth, as they would be echoed
189
+ // as text. Objects already visited are skipped, so circular details are safe.
190
+ function payloadCredentials(value, underCredentialKey = false, out = [], seen = new WeakSet()) {
191
+ if (typeof value === 'string' || typeof value === 'number') {
192
+ if (underCredentialKey) out.push(String(value));
193
+ } else if (value && typeof value === 'object' && !seen.has(value)) {
194
+ seen.add(value);
195
+ const entries = Array.isArray(value) ? value.map(v => [null, v]) : Object.entries(value);
196
+ for (const [k, v] of entries) {
197
+ payloadCredentials(v, underCredentialKey || (k !== null && CREDENTIAL_KEY_PATTERN.test(k)), out, seen);
198
+ }
199
+ }
200
+ return out;
201
+ }
202
+
203
+ // Credentials sent or passed on this invocation, mapped to their masked form.
204
+ // They are matched by value, which covers a secret that is not a URL.
205
+ function suppliedChannelSecrets(options, payload, errorBody) {
206
+ const secrets = [];
207
+ // Flag values shorter than the minimum are left alone: URLs that short are
208
+ // not valid and buildChannels rejects short --webhook-secret values. --data
209
+ // has no minimum, so a payload credential of any length is matched; values
210
+ // shorter than 8 characters only as a whole token, so a short secret such
211
+ // as `abc1` does not garble unrelated words that contain it.
212
+ const add = (value, masked, minLength) => {
213
+ for (const v of [value].flat()) {
214
+ if (typeof v !== 'string' || v.length < Math.max(1, minLength)) continue;
215
+ const wholeToken = v.length < 8;
216
+ secrets.push([v, masked(v), wholeToken]);
217
+ const escaped = JSON.stringify(v).slice(1, -1).replace(/\//g, '\\/');
218
+ if (escaped !== v) secrets.push([escaped, masked(v), wholeToken]);
219
+ }
220
+ };
221
+ for (const flag of ['slack', 'discord', 'webhook']) add(options[flag], redactUrl, 8);
222
+ add(options['webhook-secret'], () => REDACTED, 16);
223
+ add(payloadCredentials(payload), maskCredential, 1);
224
+ // A credential field in the error body names the value, so the same secret
225
+ // is also scrubbed wherever the message quotes it (e.g. a stored secret on
226
+ // `list`, where there is no payload to match against).
227
+ add(payloadCredentials(errorBody).filter(v => !isNansenLink(v)), maskCredential, 1);
228
+ // Longest first, so a value that contains another is replaced whole.
229
+ return secrets.sort((a, b) => b[0].length - a[0].length);
230
+ }
231
+
232
+ function scrubString(text, secrets) {
233
+ let out = text;
234
+ for (const [value, masked, wholeToken] of secrets) {
235
+ if (!wholeToken) {
236
+ out = out.split(value).join(masked);
237
+ continue;
238
+ }
239
+ const escaped = value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
240
+ out = out.replace(new RegExp(`(?<![A-Za-z0-9])${escaped}(?![A-Za-z0-9])`, 'g'), () => masked);
241
+ }
242
+ // Sentence punctuation the URL pattern swallows (`(https://x/y).`) is kept
243
+ // outside the mask, so the text around a masked URL stays intact.
244
+ return out.replace(URL_IN_TEXT, match => {
245
+ const [, url, tail] = match.match(/^(.*?)([.,;:!?)\]]*)$/);
246
+ return isNansenLink(url) ? match : redactUrl(url) + tail;
247
+ });
248
+ }
249
+
250
+ function scrubDeep(value, secrets) {
251
+ if (typeof value === 'string') return scrubString(value, secrets);
252
+ if (Array.isArray(value)) return value.map(v => scrubDeep(v, secrets));
253
+ if (!value || typeof value !== 'object') return value;
254
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, scrubDeep(v, secrets)]));
255
+ }
256
+
257
+ /**
258
+ * Return an error safe to print: the message and details have channel
259
+ * credentials masked. API error bodies are copied into NansenError.details and
260
+ * printed, and a validation error can echo the channels it rejected. If the
261
+ * details cannot be walked (e.g. a circular structure), they are dropped.
262
+ * `payload` is the request body that was sent, if any.
263
+ */
264
+ export function redactAlertError(error, options = {}, payload = undefined) {
265
+ const secrets = suppliedChannelSecrets(options, payload, [error?.details, error?.data]);
266
+ const scrub = value => {
267
+ if (value == null) return value;
268
+ try {
269
+ return scrubDeep(maskCredentialKeys(redactAlertSecrets(value)), secrets);
270
+ } catch {
271
+ return null;
272
+ }
273
+ };
274
+ const message = typeof error?.message === 'string' ? scrubString(error.message, secrets) : error?.message;
275
+ if (error instanceof NansenError) {
276
+ return new NansenError(message, error.code, error.status, scrub(error.details));
277
+ }
278
+ if (error instanceof Error) {
279
+ // formatError() reads message, code, status and details/data.
280
+ const scrubbed = new Error(message);
281
+ scrubbed.name = error.name;
282
+ for (const key of ['code', 'status']) {
283
+ if (error[key] !== undefined) scrubbed[key] = error[key];
284
+ }
285
+ for (const key of ['details', 'data']) {
286
+ if (error[key] !== undefined) scrubbed[key] = scrub(error[key]);
287
+ }
288
+ return scrubbed;
289
+ }
290
+ return error;
291
+ }
8
292
 
9
293
  // ============= Formatting =============
10
294
 
@@ -472,7 +756,7 @@ const TIME_WINDOW_BY_TYPE = {
472
756
  };
473
757
 
474
758
  export function buildAlertsCommands(deps = {}) {
475
- const { log = console.log } = deps;
759
+ const { log = console.log, env = process.env, stdin = process.stdin, stdinTTY } = deps;
476
760
 
477
761
  return {
478
762
  'alerts': async (args, apiInstance, flags, options) => {
@@ -488,16 +772,21 @@ SUBCOMMANDS:
488
772
  toggle Enable or disable an alert
489
773
  delete Delete an alert
490
774
 
775
+ Channel credentials (Slack/Discord/webhook URLs, webhook signing secrets) are
776
+ redacted in output and error messages of every subcommand. Pass --reveal to
777
+ show them.
778
+
491
779
  Run: nansen alerts <subcommand> --help`,
492
780
 
493
781
  list: `nansen alerts list — List all alerts
494
782
 
495
783
  USAGE:
496
- nansen alerts list [--table] [--pretty] [--type <type>] [--enabled|--disabled] [--token-address <addr>] [--chain <chain>] [--limit <n>] [--offset <n>]
784
+ nansen alerts list [--table] [--pretty] [--type <type>] [--enabled|--disabled] [--token-address <addr>] [--chain <chain>] [--limit <n>] [--offset <n>] [--reveal]
497
785
 
498
786
  OPTIONS:
499
787
  --table Human-readable table output (columns: ID, NAME, TYPE, ENABLED, CHANNELS)
500
788
  --pretty Indented JSON output
789
+ --reveal Show full channel webhook URLs and secrets (redacted by default)
501
790
  --type <type> Filter by alert type (sm-token-flows, common-token-transfer, smart-contract-call)
502
791
  --enabled / --disabled Filter by enabled state
503
792
  --token-address <addr> Filter by token address
@@ -522,12 +811,15 @@ REQUIRED:
522
811
 
523
812
  OPTIONS (all types):
524
813
  --chains <chains> Comma-separated chains (e.g. ethereum,solana)
525
- --webhook-secret <secret> Signing secret for webhook payload verification (webhook only)
814
+ --webhook-secret-stdin Read the webhook signing secret from a pipe or file (webhook only)
815
+ --webhook-secret <secret> Signing secret on the command line (visible in shell history and
816
+ the process list; prefer --webhook-secret-stdin or NANSEN_WEBHOOK_SECRET)
526
817
  --token <address:chain> Include token (repeatable)
527
818
  --exclude-token <addr:chain> Exclude token (repeatable)
528
819
  --description '<text>' Alert description
529
820
  --disabled Create in disabled state
530
821
  --data '<json>' Raw JSON merged on top of named flags (escape hatch)
822
+ --reveal Show full channel URLs and secrets in the response (redacted by default)
531
823
 
532
824
  OPTIONS (sm-token-flows):
533
825
  At least one flow threshold required (inflow, outflow, or netflow):
@@ -559,14 +851,22 @@ NOTE: Use single quotes for names with $ or special chars: --name 'SM >$1M'
559
851
  EXAMPLES:
560
852
  nansen alerts create --name 'ETH SM Inflow' --type sm-token-flows --chains ethereum --telegram 5238612255 --inflow-1h-min 1000000
561
853
  nansen alerts create --name 'USDC Transfers' --type common-token-transfer --chains ethereum --telegram 5238612255 --events send,receive --usd-min 1000000 --subject label:"Centralized Exchange"
562
- nansen alerts create --name 'Contract Calls' --type smart-contract-call --chains ethereum --telegram 5238612255 --signature-hash 0xa9059cbb --caller address:0xabc`,
854
+ nansen alerts create --name 'Contract Calls' --type smart-contract-call --chains ethereum --telegram 5238612255 --signature-hash 0xa9059cbb --caller address:0xabc
855
+ nansen alerts create --name 'Hook' --type sm-token-flows --chains ethereum --webhook https://example.com/hook --inflow-1h-min 1000000 --webhook-secret-stdin < secret.txt
856
+
857
+ WEBHOOK SIGNING SECRET (minimum 16 characters, webhook only):
858
+ --webhook-secret-stdin Pipe or redirect it: ... --webhook-secret-stdin < secret.txt
859
+ NANSEN_WEBHOOK_SECRET Environment variable, read only when --webhook is given
860
+ --webhook-secret <secret> Still accepted, but it lands in shell history and the process list
861
+ --webhook-secret and --webhook-secret-stdin cannot be combined. Either one overrides
862
+ NANSEN_WEBHOOK_SECRET. The secret is redacted in output and errors unless --reveal is passed.`,
563
863
 
564
864
  update: `nansen alerts update — Update an existing alert
565
865
 
566
866
  USAGE:
567
867
  nansen alerts update <id> [--name <name>] [--chains <chains>] [--enabled|--disabled] [type-specific flags...]
568
868
 
569
- All create options are accepted. Only provided fields are updated.
869
+ All create options are accepted, including --reveal. Only provided fields are updated.
570
870
  See: nansen alerts create --help for type-specific flags.
571
871
 
572
872
  NOTE: --type cannot change an existing alert's type (use delete + create instead).
@@ -575,13 +875,17 @@ NOTE: --type cannot change an existing alert's type (use delete + create instead
575
875
  EXAMPLES:
576
876
  nansen alerts update abc123 --name 'New Name'
577
877
  nansen alerts update abc123 --inflow-1h-min 2000000
578
- nansen alerts update abc123 --chains ethereum,base --inflow-1h-min 2000000`,
878
+ nansen alerts update abc123 --chains ethereum,base --inflow-1h-min 2000000
879
+ nansen alerts update abc123 --webhook https://example.com/hook --webhook-secret-stdin < secret.txt`,
579
880
 
580
881
  toggle: `nansen alerts toggle — Enable or disable an alert
581
882
 
582
883
  USAGE:
583
884
  nansen alerts toggle <id> --enabled
584
- nansen alerts toggle <id> --disabled`,
885
+ nansen alerts toggle <id> --disabled
886
+
887
+ OPTIONS:
888
+ --reveal Show full channel URLs and secrets in the response (redacted by default)`,
585
889
 
586
890
  delete: `nansen alerts delete — Delete an alert
587
891
 
@@ -594,26 +898,56 @@ USAGE:
594
898
  return;
595
899
  }
596
900
 
901
+ // Signing secret resolved once from --webhook-secret, --webhook-secret-stdin
902
+ // or NANSEN_WEBHOOK_SECRET before create/update runs (stdin can only be read once).
903
+ let webhookSecret;
904
+
597
905
  // Build channels array from --telegram/--slack/--discord/--webhook flags
598
906
  function buildChannels() {
599
- if (options["webhook-secret"] && !options.webhook) {
600
- throw new NansenError('--webhook-secret requires --webhook', ErrorCode.INVALID_PARAMS);
907
+ for (const flag of ['slack', 'discord', 'webhook', 'webhook-secret']) {
908
+ if (Array.isArray(options[flag])) {
909
+ throw new NansenError(`--${flag} can only be passed once`, ErrorCode.INVALID_PARAMS);
910
+ }
911
+ if (typeof options[flag] === 'string' && options[flag].includes(REDACTED)) {
912
+ throw new NansenError(
913
+ `--${flag} looks like a redacted value from alerts output. Pass the full value (nansen alerts list --reveal shows it).`,
914
+ ErrorCode.INVALID_PARAMS,
915
+ );
916
+ }
601
917
  }
602
918
  const channels = [];
603
919
  if (options.telegram) channels.push({ type: 'telegram', data: { chatId: String(options.telegram) } });
604
920
  if (options.slack) channels.push({ type: 'slack', data: { webhookUrl: options.slack } });
605
921
  if (options.discord) channels.push({ type: 'discord', data: { webhookUrl: options.discord } });
922
+ // Output masks a secret as a whole (REDACTED), so only an all-asterisk
923
+ // value is a pasted-back redaction; a real secret may contain `****`.
924
+ if (webhookSecret && webhookSecret.source !== '--webhook-secret' && /^\*+$/.test(webhookSecret.value)) {
925
+ throw new NansenError(
926
+ `The webhook secret from ${webhookSecret.source} looks like a redacted value from alerts output. Pass the full value (nansen alerts list --reveal shows it).`,
927
+ ErrorCode.INVALID_PARAMS,
928
+ );
929
+ }
606
930
  if (options.webhook) {
607
931
  const webhookData = { webhookUrl: options.webhook };
608
- if (options["webhook-secret"]) {
609
- if (options["webhook-secret"].length < 16) throw new NansenError('--webhook-secret must be at least 16 characters', ErrorCode.INVALID_PARAMS);
610
- webhookData.secret = options["webhook-secret"];
932
+ if (webhookSecret) {
933
+ const { value, source } = webhookSecret;
934
+ if (typeof value !== 'string' || value.length < 16) {
935
+ throw new NansenError(
936
+ source === '--webhook-secret' ? '--webhook-secret must be at least 16 characters' : `The webhook secret from ${source} must be at least 16 characters`,
937
+ ErrorCode.INVALID_PARAMS,
938
+ );
939
+ }
940
+ webhookData.secret = value;
611
941
  }
612
942
  channels.push({ type: 'webhook', data: webhookData });
613
943
  }
614
944
  return channels.length > 0 ? channels : null;
615
945
  }
616
946
 
947
+ // Request body of create/update, so a failed request's error can be
948
+ // scrubbed of every credential it carried.
949
+ let sentPayload;
950
+
617
951
  const handlers = {
618
952
  'list': async () => {
619
953
  if (flags.enabled && flags.disabled) throw new NansenError('Cannot specify both --enabled and --disabled', ErrorCode.INVALID_PARAMS);
@@ -683,7 +1017,7 @@ USAGE:
683
1017
  const dataOverride = parseDataOverride(options);
684
1018
  if (dataOverride) data = deepMergePlain(data, dataOverride);
685
1019
  validateAlertData(type, data);
686
- return apiInstance.alertsCreate({
1020
+ sentPayload = {
687
1021
  name,
688
1022
  type,
689
1023
  timeWindow,
@@ -691,7 +1025,8 @@ USAGE:
691
1025
  data,
692
1026
  ...(options.description ? { description: options.description } : {}),
693
1027
  isEnabled: !flags.disabled,
694
- });
1028
+ };
1029
+ return apiInstance.alertsCreate(sentPayload);
695
1030
  },
696
1031
  'update': async () => {
697
1032
  const id = args[1];
@@ -730,6 +1065,7 @@ USAGE:
730
1065
  if (flags.disabled) params.isEnabled = false;
731
1066
  // Validate merged data if present, otherwise validate existing data
732
1067
  validateAlertData(type, params.data ?? existing.data);
1068
+ sentPayload = params;
733
1069
  return apiInstance.alertsUpdate(params);
734
1070
  },
735
1071
  'toggle': () => {
@@ -748,7 +1084,7 @@ USAGE:
748
1084
  };
749
1085
 
750
1086
  if (!handlers[sub]) {
751
- throw new NansenError(`Unknown alerts subcommand: ${sub}. Available: list, create, update, toggle, delete`, ErrorCode.UNKNOWN);
1087
+ throw unknownCommandError('alerts subcommand', sub, ['list', 'create', 'update', 'toggle', 'delete']);
752
1088
  }
753
1089
 
754
1090
  // Subcommand-level help: --help flag or "help" as second positional arg
@@ -758,8 +1094,13 @@ USAGE:
758
1094
  }
759
1095
 
760
1096
  try {
761
- return await handlers[sub]();
1097
+ if (sub === 'create' || sub === 'update') {
1098
+ webhookSecret = await resolveWebhookSecret(options, flags, { env, stdin, stdinTTY });
1099
+ }
1100
+ const result = await handlers[sub]();
1101
+ return flags.reveal ? result : redactAlertSecrets(result);
762
1102
  } catch (err) {
1103
+ let error = err;
763
1104
  // Rewrite cryptic channel validation errors from the API into actionable messages.
764
1105
  // e.g. "Failed to send a welcome message to the channel index 0" → tells the user
765
1106
  // which channel type failed and what to check.
@@ -776,9 +1117,15 @@ USAGE:
776
1117
  : ch?.type === 'webhook'
777
1118
  ? `Invalid webhook URL (${ch.data.webhookUrl}). Ensure the endpoint is reachable and returns 2xx.`
778
1119
  : err.message;
779
- throw new NansenError(hint, err.code ?? ErrorCode.INVALID_PARAMS, err.status);
1120
+ // Keep the API's details (and its request ID); they are redacted below
1121
+ // like any other error body unless --reveal is passed.
1122
+ error = new NansenError(hint, err.code ?? ErrorCode.INVALID_PARAMS, err.status, err.details ?? null);
780
1123
  }
781
- throw err;
1124
+ // API error bodies (message and details) can echo the submitted channels,
1125
+ // and the hint above quotes the webhook URL; all are masked here unless
1126
+ // --reveal is passed.
1127
+ const redactOptions = webhookSecret ? { ...options, 'webhook-secret': webhookSecret.value } : options;
1128
+ throw flags.reveal ? error : redactAlertError(error, redactOptions, sentPayload);
782
1129
  }
783
1130
  },
784
1131
  };
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import { CommandError } from '../api.js';
13
+ import { UNAVAILABLE_COMMANDS } from '../input-validation.js';
13
14
  import { createRequire } from 'module';
14
15
 
15
16
  const require = createRequire(import.meta.url);
@@ -41,7 +42,9 @@ export const UNSCHEMA_COMMANDS = {
41
42
  * teaches the spelling we are trying to retire.
42
43
  */
43
44
  export const EXCLUDED_COMMANDS = new Set([
44
- 'smart-money', 'profiler', 'token', 'search', 'portfolio', 'points', 'prediction-market',
45
+ 'smart-money', 'profiler', 'token', 'search', 'portfolio', 'prediction-market',
46
+ // Removed commands that still answer COMMAND_UNAVAILABLE.
47
+ ...UNAVAILABLE_COMMANDS,
45
48
  'quote', 'execute',
46
49
  // Undocumented top-level alias of `trade bridge-status`: reachable because
47
50
  // runCLI spreads buildTradingCommands over the root, absent from HELP.