nansen-cli 1.46.0 → 2.0.1

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 (78) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +157 -14
  3. package/docs/browser-login.md +123 -0
  4. package/package.json +11 -2
  5. package/scripts/postinstall.js +35 -30
  6. package/skills/nansen-agent-guide/SKILL.md +13 -2
  7. package/skills/nansen-alerts-webhook-listener/SKILL.md +5 -2
  8. package/skills/nansen-dca-tracker/SKILL.md +10 -2
  9. package/skills/nansen-defi-positions/SKILL.md +5 -2
  10. package/skills/nansen-exit-signals/SKILL.md +10 -2
  11. package/skills/nansen-fund-tracker/SKILL.md +10 -2
  12. package/skills/nansen-general-search/SKILL.md +10 -2
  13. package/skills/nansen-holder-analysis/SKILL.md +10 -2
  14. package/skills/nansen-limit-orders/SKILL.md +6 -3
  15. package/skills/nansen-perp-screener/SKILL.md +10 -2
  16. package/skills/nansen-perp-trader-profile/SKILL.md +10 -2
  17. package/skills/nansen-polymarket-deep-dive/SKILL.md +10 -2
  18. package/skills/nansen-polymarket-insider-scan/SKILL.md +10 -2
  19. package/skills/nansen-polymarket-trader-profile/SKILL.md +10 -2
  20. package/skills/nansen-portfolio-tracker/SKILL.md +10 -2
  21. package/skills/nansen-prediction-markets/SKILL.md +10 -2
  22. package/skills/nansen-sm-cross-chain-flows/SKILL.md +10 -2
  23. package/skills/nansen-smart-alerts/SKILL.md +9 -4
  24. package/skills/nansen-smart-money-alpha/SKILL.md +10 -2
  25. package/skills/nansen-smart-money-tracker/SKILL.md +10 -2
  26. package/skills/nansen-smart-money-trend/SKILL.md +10 -2
  27. package/skills/nansen-token-research/SKILL.md +10 -2
  28. package/skills/nansen-token-screener/SKILL.md +14 -4
  29. package/skills/nansen-token-transfer-analysis/SKILL.md +10 -2
  30. package/skills/nansen-trading/SKILL.md +8 -2
  31. package/skills/nansen-wallet-batch/SKILL.md +10 -2
  32. package/skills/nansen-wallet-clustering/SKILL.md +10 -2
  33. package/skills/nansen-wallet-deep-dive/SKILL.md +10 -2
  34. package/skills/nansen-wallet-keychain-migration/SKILL.md +5 -2
  35. package/skills/nansen-wallet-manager/SKILL.md +11 -9
  36. package/skills/nansen-wallet-profiler/SKILL.md +10 -2
  37. package/skills/nansen-web-fetcher/SKILL.md +5 -2
  38. package/skills/nansen-web-searcher/SKILL.md +5 -2
  39. package/src/api.js +202 -104
  40. package/src/auth-browser.js +16 -0
  41. package/src/auth-credentials.js +73 -0
  42. package/src/auth-device.js +242 -0
  43. package/src/auth-key-input.js +46 -0
  44. package/src/auth-login.js +89 -0
  45. package/src/auth-state.js +487 -0
  46. package/src/auth-store-native.js +20 -0
  47. package/src/auth-store-worker.js +64 -0
  48. package/src/auth-store.js +140 -0
  49. package/src/auto-paginate.js +288 -0
  50. package/src/bridge.js +126 -21
  51. package/src/cache-inspect.js +345 -0
  52. package/src/cli.js +473 -199
  53. package/src/commands/agent.js +15 -7
  54. package/src/commands/completion.js +2 -15
  55. package/src/commands/mcp.js +20 -18
  56. package/src/cost-cache.js +16 -2
  57. package/src/debug.js +348 -0
  58. package/src/doctor.js +22 -45
  59. package/src/hl-action.js +41 -13
  60. package/src/limit-order.js +1 -1
  61. package/src/mcp-client-config.js +169 -0
  62. package/src/mcp-client-config.json +17 -0
  63. package/src/mcp-verify.js +6 -5
  64. package/src/perp.js +41 -0
  65. package/src/privy.js +12 -12
  66. package/src/response-meta.js +56 -1
  67. package/src/rpc-urls.js +9 -11
  68. package/src/schema.json +185 -8
  69. package/src/semver.js +23 -4
  70. package/src/swap-simulation.js +35 -30
  71. package/src/telemetry.js +20 -0
  72. package/src/trading.js +266 -29
  73. package/src/transfer.js +53 -6
  74. package/src/update-check.js +9 -1
  75. package/src/wallet.js +107 -17
  76. package/src/walletconnect-trading.js +24 -5
  77. package/src/x402-svm.js +123 -64
  78. package/src/x402.js +46 -14
@@ -0,0 +1,487 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { setTimeout as delay } from 'node:timers/promises';
5
+ import { AuthError, authDirectory, validAuthPointer } from './auth-credentials.js';
6
+ import { createAuthStore } from './auth-store.js';
7
+ import { refreshSession, retireSession, validateSession } from './auth-device.js';
8
+
9
+ const queues = new Map();
10
+ const MAX_RETRYABLE_RENEWALS = 5;
11
+ const recognizedJournal = name => /^[a-f0-9-]{36}\.json$/.test(name);
12
+ const journalError = () => new AuthError('AUTH_JOURNAL_INVALID', 'Authentication recovery cannot safely read auth-operations. Preserve its files and secure-store entries. Stop all CLI authentication processes, restore only a known-valid journal backup for this state, or contact support using docs/browser-login.md#damaged-or-unrecognized-journals.');
13
+ const journalExists = file => {
14
+ try { return Boolean(fs.lstatSync(file, { throwIfNoEntry: false })); }
15
+ catch { throw journalError(); }
16
+ };
17
+ 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
+ function safePath(file, directory = false) {
19
+ if (!fs.existsSync(file)) return;
20
+ const stat = fs.lstatSync(file);
21
+ if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()) ||
22
+ (process.platform !== 'win32' && ((stat.mode & 0o022) || stat.uid !== process.getuid()))) throw stateError();
23
+ }
24
+ const uuid = value => typeof value === 'string' && /^[a-f0-9-]{36}$/.test(value);
25
+ function readJournal(file, id) {
26
+ try {
27
+ safePath(file);
28
+ if (fs.statSync(file).size > 4096) throw journalError();
29
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
30
+ if (value?.id !== id) throw journalError();
31
+ if (value.kind === 'rotation') {
32
+ if (value.version !== 2 || value.id !== value.selectionEpoch || !uuid(value.selectionEpoch) ||
33
+ !uuid(value.sourceGeneration) || !uuid(value.targetGeneration) || value.sourceGeneration === value.targetGeneration ||
34
+ !['in_flight', 'ready', 'blocked', 'retryable', 'retired'].includes(value.phase) ||
35
+ (value.phase === 'blocked' ? !['uncertain', 'rejected', 'setup', 'clock', 'expired', 'protocol', 'retry_exhausted'].includes(value.reason) : value.reason !== undefined) ||
36
+ (value.phase === 'retryable' ? !Number.isFinite(value.retryNotBefore) || value.retryNotBefore < 0 : value.retryNotBefore !== undefined) ||
37
+ (value.retryFailures !== undefined && (!Number.isInteger(value.retryFailures) || value.retryFailures < 0 || value.retryFailures > MAX_RETRYABLE_RENEWALS)) ||
38
+ (value.phase === 'retryable' && value.retryFailures >= MAX_RETRYABLE_RENEWALS) ||
39
+ (value.reason === 'retry_exhausted' && value.retryFailures !== MAX_RETRYABLE_RENEWALS) ||
40
+ (value.phase === 'retired' ? !['unconfirmed', 'recorded_pending', 'refresh_only'].includes(value.remote) : value.remote !== undefined) ||
41
+ Object.keys(value).some(k => !['version', 'id', 'kind', 'selectionEpoch', 'sourceGeneration', 'targetGeneration', 'phase', 'reason', 'retryNotBefore', 'retryFailures', 'remote'].includes(k))) throw journalError();
42
+ } else if (value.kind !== undefined || value.version !== undefined || !Array.isArray(value.generations) || value.generations.length > 2 || value.generations.some(g => !uuid(g)) ||
43
+ (value.blockedBy !== undefined && (!uuid(value.blockedBy) || value.blockedBy === value.id)) ||
44
+ (value.unissued !== undefined && typeof value.unissued !== 'boolean') || (value.candidateRemote !== undefined && !['unconfirmed', 'recorded_pending', 'refresh_only'].includes(value.candidateRemote))) throw journalError();
45
+ return value;
46
+ } catch { throw journalError(); }
47
+ }
48
+ // Metadata-only: never locks, opens secure storage, recovers, or contacts the issuer.
49
+ export function renewalStatus(directory, selection) {
50
+ try {
51
+ if (!uuid(selection.selectionEpoch)) return 'metadata_unreadable';
52
+ const file = path.join(directory, 'auth-operations', `${selection.selectionEpoch}.json`);
53
+ safePath(directory, true); safePath(path.dirname(file), true);
54
+ if (!journalExists(file)) return 'not_recorded';
55
+ const journal = readJournal(file, selection.selectionEpoch);
56
+ if (journal.kind !== 'rotation') return 'metadata_unreadable';
57
+ return { in_flight: 'pending_or_uncertain', ready: 'ready_local_recovery', blocked: 'login_required', retryable: 'retryable' }[journal.phase] || 'metadata_unreadable';
58
+ } catch { return 'metadata_unreadable'; }
59
+ }
60
+ function timedSignal(parent, ms, code) {
61
+ const controller = new AbortController();
62
+ const cancel = () => controller.abort(new AuthError('AUTH_CANCELLED', 'Authentication operation cancelled. Retry the command.'));
63
+ parent?.addEventListener('abort', cancel, { once: true });
64
+ if (parent?.aborted) cancel();
65
+ const timer = setTimeout(() => controller.abort(new AuthError(code, code === 'AUTH_BUSY' ? 'Another authentication operation is running. Retry after it finishes.' : 'Authentication operation timed out. Retry the command; an uncertain renewal requires login.')), ms);
66
+ return { signal: controller.signal, close() { clearTimeout(timer); parent?.removeEventListener('abort', cancel); } };
67
+ }
68
+ async function waitTurn(previous, signal) {
69
+ signal.throwIfAborted();
70
+ let cancel;
71
+ try {
72
+ await Promise.race([previous, new Promise((_, reject) => {
73
+ cancel = () => reject(signal.reason);
74
+ signal.addEventListener('abort', cancel, { once: true });
75
+ })]);
76
+ signal.throwIfAborted();
77
+ } finally { signal.removeEventListener('abort', cancel); }
78
+ }
79
+ async function loadLocks() {
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; 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
+ }
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
+ let operationSignal;
85
+ const options = () => ({ signal: operationSignal });
86
+ const check = () => operationSignal?.throwIfAborted();
87
+ const configFile = path.join(directory, 'config.json');
88
+ const journalDir = path.join(directory, 'auth-operations');
89
+ function prepare() {
90
+ safePath(directory, true);
91
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
92
+ safePath(journalDir, true);
93
+ fs.mkdirSync(journalDir, { mode: 0o700, recursive: true });
94
+ }
95
+ function read() {
96
+ safePath(configFile);
97
+ if (!fs.existsSync(configFile)) return {};
98
+ try {
99
+ const value = JSON.parse(fs.readFileSync(configFile, 'utf8'));
100
+ if (!value || typeof value !== 'object' || Array.isArray(value) || (value.auth && !validAuthPointer(value.auth))) throw new Error();
101
+ return value;
102
+ } catch { throw stateError(); }
103
+ }
104
+ async function atomic(file, value) {
105
+ check();
106
+ safePath(file);
107
+ const temp = `${file}.${randomUUID()}.tmp`;
108
+ let fd;
109
+ try {
110
+ fd = fs.openSync(temp, 'wx', 0o600);
111
+ fs.writeFileSync(fd, JSON.stringify(value, null, 2));
112
+ await barrier('before-flush', path.basename(file)); check();
113
+ fs.fsyncSync(fd);
114
+ fs.closeSync(fd); fd = undefined;
115
+ await barrier('before-rename', path.basename(file)); check();
116
+ fs.renameSync(temp, file);
117
+ await barrier('after-rename', path.basename(file));
118
+ if (process.platform !== 'win32') {
119
+ const dirFd = fs.openSync(path.dirname(file), 'r');
120
+ try { fs.fsyncSync(dirFd); } finally { fs.closeSync(dirFd); }
121
+ }
122
+ } finally {
123
+ if (fd !== undefined) fs.closeSync(fd);
124
+ try { fs.unlinkSync(temp); } catch { /* rename may already have committed */ }
125
+ }
126
+ }
127
+ async function acquire(file, signal, wait = true) {
128
+ signal?.throwIfAborted();
129
+ const native = await locks();
130
+ signal?.throwIfAborted();
131
+ safePath(file);
132
+ const fd = fs.openSync(file, 'a+', 0o600);
133
+
134
+ try {
135
+ while (!native.tryLock(fd)) {
136
+ if (!wait) { fs.closeSync(fd); return null; }
137
+ signal?.throwIfAborted();
138
+ await delay(50, undefined, { signal });
139
+ }
140
+ return () => { try { native.unlock(fd); } finally { fs.closeSync(fd); } };
141
+ } catch (error) { fs.closeSync(fd); throw error; }
142
+ }
143
+ async function locked(fn, signal) {
144
+ const previous = queues.get(directory) || Promise.resolve();
145
+ let finish;
146
+ const done = new Promise(resolve => { finish = resolve; });
147
+ // A cancelled waiter must not allow a later waiter to overtake the owner.
148
+ const tail = previous.then(() => done);
149
+ queues.set(directory, tail);
150
+ const waiting = timedSignal(signal, waitMs, 'AUTH_BUSY');
151
+ let release, budget;
152
+ try {
153
+ await waitTurn(previous, waiting.signal);
154
+ prepare();
155
+ release = await acquire(path.join(directory, 'auth.lock'), waiting.signal);
156
+ waiting.close();
157
+ budget = timedSignal(signal, operationMs, 'AUTH_TIMEOUT');
158
+ operationSignal = budget.signal;
159
+ check();
160
+ return await fn();
161
+ } catch (error) {
162
+ if (budget?.signal.aborted) throw budget.signal.reason;
163
+ if (waiting.signal.aborted) throw waiting.signal.reason;
164
+ throw error;
165
+ } finally {
166
+ if (budget) { budget.close(); operationSignal = undefined; }
167
+ waiting.close(); release?.(); finish();
168
+ tail.then(() => { if (queues.get(directory) === tail) queues.delete(directory); });
169
+ }
170
+ }
171
+ const journalPath = id => path.join(journalDir, `${id}.json`);
172
+ async function cleanupGeneration(generation, knownRemote) {
173
+ let remote = knownRemote || 'unconfirmed';
174
+ if (!knownRemote) {
175
+ try { remote = (await retire(await store.read(generation, options()), options())).remote; } catch { /* absence alone never proves no issuance */ }
176
+ }
177
+ try { await store.remove(generation, options()); return { remote, local: 'removed' }; }
178
+ catch { return { remote, local: 'incomplete' }; }
179
+ }
180
+ async function cleanJournal(journal, config) {
181
+ if (journal.kind === 'rotation') return cleanRotation(journal, config);
182
+ // Deselection retained this known source while damaged metadata may hide
183
+ // another generation. Never discharge it ahead of that journal.
184
+ if (journal.blockedBy && journalExists(journalPath(journal.blockedBy))) return [{ local: 'incomplete', remote: 'unconfirmed', code: 'AUTH_JOURNAL_INVALID' }];
185
+ const activeRotation = config.auth?.active?.kind === 'session' ? rotationFor(config) : null;
186
+ const outcomes = [];
187
+ const pending = [];
188
+ for (const generation of journal.generations) {
189
+ check();
190
+ if (config.auth?.active?.generation === generation || (activeRotation && [activeRotation.sourceGeneration, activeRotation.targetGeneration].includes(generation))) continue;
191
+ const knownRemote = generation === journal.id ? (journal.unissued === true ? 'not_needed' : journal.candidateRemote) : undefined;
192
+ const result = await cleanupGeneration(generation, knownRemote);
193
+ outcomes.push(result);
194
+ if (result.local !== 'removed') pending.push(generation);
195
+ }
196
+ if (pending.length) await atomic(journalPath(journal.id), { ...journal, generations: pending });
197
+ else fs.unlinkSync(journalPath(journal.id));
198
+ // A delayed finish() must not resurrect already discharged references.
199
+ journal.generations = pending;
200
+ return outcomes;
201
+ }
202
+ async function recover() {
203
+ read(); // Reject unsupported pointers before any recovery mutation.
204
+ const results = [];
205
+ // The global lock proves no writer is using these same-directory staging
206
+ // files. Remove crash leftovers, including explicit legacy-key saves.
207
+ for (const [dir, pattern] of [
208
+ [directory, /^config\.json\.[a-f0-9-]{36}\.tmp$/],
209
+ [journalDir, /^[a-f0-9-]{36}\.json\.[a-f0-9-]{36}\.tmp$/],
210
+ ]) {
211
+ for (const file of fs.readdirSync(dir).filter(name => pattern.test(name))) {
212
+ const target = path.join(dir, file); safePath(target); fs.unlinkSync(target);
213
+ }
214
+ }
215
+ const files = fs.readdirSync(journalDir).filter(recognizedJournal);
216
+ // Drain a bounded batch even from pre-existing over-limit directories.
217
+ // Admission is capped separately; logout must always be able to recover.
218
+ for (const file of files.slice(0, 8)) {
219
+ check();
220
+ const id = file.slice(0, -5);
221
+ const release = await acquire(path.join(journalDir, `${id}.lock`), operationSignal, false);
222
+ if (!release) continue;
223
+ try {
224
+ const journal = readJournal(path.join(journalDir, file), id);
225
+ results.push(...await cleanJournal(journal, read()));
226
+ } finally { release(); }
227
+ }
228
+ // Only the global lock owner can discover/remove attempt-lock paths. Never
229
+ // unlink a live inode: a paused process still owns it regardless of age.
230
+ for (const file of fs.readdirSync(journalDir).filter(f => /^[a-f0-9-]{36}\.lock$/.test(f))) {
231
+ if (fs.existsSync(journalPath(file.slice(0, -5)))) continue;
232
+ const lockFile = path.join(journalDir, file);
233
+ const release = await acquire(lockFile, operationSignal, false);
234
+ if (release) { release(); fs.unlinkSync(lockFile); }
235
+ }
236
+ if (fs.readdirSync(journalDir).some(recognizedJournal)) results.push({ local: 'pending', remote: 'not_attempted' });
237
+ if (fs.readdirSync(journalDir).some(f => f.endsWith('.json') && !recognizedJournal(f))) results.push({ local: 'unrecognized', remote: 'not_attempted' });
238
+ return results;
239
+ }
240
+ function rotationFor(config) {
241
+ const epoch = config.auth?.selectionEpoch;
242
+ if (!uuid(epoch) || !journalExists(journalPath(epoch))) return null;
243
+ const journal = readJournal(journalPath(epoch), epoch);
244
+ if (journal.kind !== 'rotation' || config.auth.version !== 2 || config.auth.active.kind !== 'session' || ![journal.sourceGeneration, journal.targetGeneration].includes(config.auth.active.generation)) throw stateError();
245
+ return journal;
246
+ }
247
+ function assertSelection(config, selection) {
248
+ const active = config.auth?.active;
249
+ if (active?.kind !== 'session' || config.auth.selectionEpoch !== selection.selectionEpoch || ['accountId', 'issuer', 'audience'].some(k => active[k] !== selection[k])) throw new AuthError('AUTH_SELECTION_CHANGED', 'Saved authentication changed. Run the command again.');
250
+ }
251
+ 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
+ function renewalError(reason) {
253
+ 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
+ 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
+ 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
+ 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.');
257
+ if (reason === 'protocol') return new AuthError('SESSION_REFRESH_PROTOCOL_ERROR', 'The issuer rejected the refresh request format. Check CLI/issuer compatibility with the operator before running nansen login. The request will not be retried.');
258
+ return reason === 'rejected' ? new AuthError('SESSION_REFRESH_REJECTED', 'The saved session cannot be renewed. Run: nansen login.') : new AuthError('SESSION_RENEWAL_UNCERTAIN', 'Session renewal outcome is unknown. Run: nansen login. The saved refresh credential was not retried.');
259
+ }
260
+ async function readBundle(generation, active) {
261
+ const bundle = await store.read(generation, options());
262
+ validateSession(bundle, now(), { allowExpired: true });
263
+ if (['issuer', 'audience', 'accountId'].some(k => bundle[k] !== active[k])) throw stateError();
264
+ return bundle;
265
+ }
266
+ async function publishRotation(journal, bundle, config) {
267
+ check();
268
+ if (config.auth.selectionEpoch !== journal.selectionEpoch || config.auth.active.generation !== journal.sourceGeneration) throw stateError();
269
+ const next = { ...config, auth: { ...config.auth, version: 2, active: { ...config.auth.active, generation: journal.targetGeneration, expiresAt: bundle.expiresAt } } };
270
+ try { await atomic(configFile, next); }
271
+ catch (error) {
272
+ const observed = read();
273
+ if (observed.auth?.selectionEpoch !== journal.selectionEpoch || observed.auth?.active?.generation !== journal.targetGeneration) throw error;
274
+ }
275
+ await barrier('rotation-committed');
276
+ }
277
+ async function recoverSelectedRotation(journal, config) {
278
+ if (config.auth.active.generation === journal.targetGeneration) { await cleanRotation(journal, config); return; }
279
+ if (journal.phase === 'blocked' || journal.phase === 'retryable') return;
280
+ let target;
281
+ try { target = await readBundle(journal.targetGeneration, config.auth.active); }
282
+ catch (error) {
283
+ // An inaccessible store is not evidence that the response was lost.
284
+ if (!error.missing && error.code === 'AUTH_STORE_UNAVAILABLE') throw error;
285
+ if (operationSignal.aborted) throw operationSignal.reason;
286
+ await atomic(journalPath(journal.id), { ...journal, phase: 'blocked', reason: blockedReason(error) });
287
+ return;
288
+ }
289
+ const source = await readBundle(journal.sourceGeneration, config.auth.active);
290
+ if (JSON.stringify(target.privateJwk) !== JSON.stringify(source.privateJwk) || target.refreshToken === source.refreshToken || target.accessToken === source.accessToken) throw stateError();
291
+ await publishRotation(journal, target, config);
292
+ await cleanRotation(journal, read());
293
+ }
294
+ async function cleanRotation(journal, config) {
295
+ const sameChoice = config.auth?.selectionEpoch === journal.selectionEpoch;
296
+ if (sameChoice && config.auth?.active?.generation === journal.sourceGeneration) return [];
297
+ if (sameChoice && config.auth?.active?.generation !== journal.targetGeneration) throw stateError();
298
+ let remote = 'not_needed';
299
+ if (sameChoice && journal.phase === 'retired') throw stateError();
300
+ if (!sameChoice && journal.phase === 'retired') remote = journal.remote;
301
+ if (!sameChoice && journal.phase !== 'retired') {
302
+ // Actual logout/replacement: retain both blobs until a readable authority
303
+ // has had its retirement attempt. A consumed parent is supported by IdP.
304
+ remote = 'unconfirmed';
305
+ let authority;
306
+ for (const generation of [journal.targetGeneration, journal.sourceGeneration]) {
307
+ check();
308
+ try { authority = await store.read(generation, options()); break; } catch { /* try retained parent */ }
309
+ }
310
+ if (!authority) return [{ remote, local: 'incomplete' }];
311
+ try { remote = (await retire(authority, options())).remote; } catch { /* remote remains unconfirmed */ }
312
+ const retired = { ...journal, phase: 'retired', remote };
313
+ delete retired.reason; delete retired.retryNotBefore;
314
+ await atomic(journalPath(journal.id), retired);
315
+ }
316
+ const generations = sameChoice ? [journal.sourceGeneration] : [journal.sourceGeneration, journal.targetGeneration];
317
+ try {
318
+ for (const generation of generations) { check(); await store.remove(generation, options()); }
319
+ fs.unlinkSync(journalPath(journal.id));
320
+ return [{ remote, local: 'removed' }];
321
+ } catch { return [{ remote, local: 'incomplete' }]; }
322
+ }
323
+ return {
324
+ async begin({ preflight = true, signal } = {}) {
325
+ return locked(async () => {
326
+ const cleanup = await recover();
327
+ if (fs.readdirSync(journalDir).filter(recognizedJournal).length >= 8) throw new AuthError('AUTH_CLEANUP_REQUIRED', 'Unlock the credential store and run nansen logout to finish cleanup.');
328
+ const id = randomUUID();
329
+ const epoch = read().auth?.selectionEpoch ?? null;
330
+ const release = await acquire(path.join(journalDir, `${id}.lock`), operationSignal);
331
+ const journal = { id, generations: preflight ? [id] : [], unissued: true };
332
+ const attempt = { id, epoch, release, journal, cleanup };
333
+ try {
334
+ await atomic(journalPath(id), journal);
335
+ await barrier('journal');
336
+ if (preflight) await store.preflight(id, options());
337
+ return attempt;
338
+ } catch (err) {
339
+ try { await cleanJournal(journal, read()); } catch { /* preserve original failure and any remaining journal */ } finally { release(); }
340
+ throw err;
341
+ }
342
+ }, signal);
343
+ },
344
+ async markIssuancePossible(attempt, signal) {
345
+ signal?.throwIfAborted();
346
+ if (attempt.journal.unissued === false) return;
347
+ return locked(async () => {
348
+ if (attempt.journal.unissued === false) return;
349
+ const journal = { ...attempt.journal, unissued: false };
350
+ await atomic(journalPath(attempt.id), journal);
351
+ attempt.journal = journal;
352
+ }, signal);
353
+ },
354
+ async install(attempt, { bundle, apiKey, baseUrl }, signal) {
355
+ return locked(async () => {
356
+ const config = read();
357
+ if ((config.auth?.selectionEpoch ?? null) !== attempt.epoch) throw new AuthError('AUTH_SELECTION_CHANGED', 'Another login or logout changed the saved credential. This attempt was not installed.');
358
+ signal?.throwIfAborted();
359
+ if (bundle) {
360
+ attempt.journal.unissued = false;
361
+ await atomic(journalPath(attempt.id), attempt.journal);
362
+ await store.write(attempt.id, bundle, options()); await barrier('stored');
363
+ }
364
+ const old = config.auth?.active;
365
+ attempt.journal.generations = [...(bundle ? [attempt.id] : []), ...(old?.kind === 'session' && !rotationFor(config) ? [old.generation] : [])];
366
+ await atomic(journalPath(attempt.id), attempt.journal);
367
+ const active = bundle ? { kind: 'session', generation: attempt.id, issuer: bundle.issuer, audience: bundle.audience, accountId: bundle.accountId, expiresAt: bundle.expiresAt } : { kind: 'api-key' };
368
+ const epoch = randomUUID();
369
+ const next = { ...config, baseUrl, auth: { version: config.auth?.version || 1, selectionEpoch: epoch, active } };
370
+ delete next.apiKey;
371
+ if (!bundle) next.apiKey = apiKey;
372
+ signal?.throwIfAborted();
373
+ try { await atomic(configFile, next); }
374
+ catch (error) {
375
+ // rename may have succeeded even though fsync/acknowledgement failed.
376
+ let observed;
377
+ try { observed = read().auth?.selectionEpoch; } catch { attempt.uncertain = true; throw stateError(); }
378
+ if (observed !== epoch) throw error;
379
+ }
380
+ attempt.committed = true;
381
+ await barrier('committed');
382
+ const cleanup = await cleanJournal(attempt.journal, read());
383
+ cleanup.push(...await recover());
384
+ return { cleanup, active };
385
+ }, signal);
386
+ },
387
+ async finish(attempt) {
388
+ try { if (attempt.uncertain) return [{ local: 'incomplete', remote: 'unconfirmed' }]; return await locked(async () => fs.existsSync(journalPath(attempt.id)) ? cleanJournal(attempt.journal, read()) : []); }
389
+ finally { attempt.release(); }
390
+ },
391
+ async logout() {
392
+ return locked(async () => {
393
+ const config = read();
394
+ const old = config.auth?.active;
395
+ const id = randomUUID();
396
+ let damagedRotation;
397
+ if (old?.kind === 'session') {
398
+ let rotation;
399
+ try { rotation = rotationFor(config); }
400
+ catch (error) {
401
+ if (!['AUTH_JOURNAL_INVALID', 'AUTH_STATE_INVALID'].includes(error.code)) throw error;
402
+ damagedRotation = error.code;
403
+ }
404
+ if (!rotation) await atomic(journalPath(id), { id, generations: [old.generation], ...(damagedRotation && { blockedBy: config.auth.selectionEpoch }) });
405
+ }
406
+ const next = { ...config, auth: { version: config.auth?.version || 1, selectionEpoch: randomUUID(), active: { kind: 'none' } } };
407
+ delete next.apiKey;
408
+ try { await atomic(configFile, next); }
409
+ catch (error) { if (read().auth?.selectionEpoch !== next.auth.selectionEpoch) throw error; }
410
+ let cleanup;
411
+ try { await barrier('logout-committed'); cleanup = damagedRotation ? [{ local: 'incomplete', remote: 'unconfirmed', code: damagedRotation }] : await recover(); }
412
+ catch (error) { cleanup = [{ local: 'incomplete', remote: 'unconfirmed', ...(error.code === 'AUTH_JOURNAL_INVALID' && { code: error.code }) }]; }
413
+ return { removed: Boolean(config.apiKey || old?.kind === 'session'), cleanup };
414
+ });
415
+ },
416
+ async acquireSession(selection, { audience, signal } = {}) {
417
+ if (selection.audience !== audience) throw new AuthError('AUTH_ORIGIN_MISMATCH', 'The saved session does not match the selected API origin. Check NANSEN_BASE_URL or run nansen login.');
418
+ return locked(async () => {
419
+ let config = read();
420
+ assertSelection(config, selection);
421
+ // Validate the prospective format before any typed path or mutation.
422
+ if (!validAuthPointer({ ...config.auth, version: 2 })) throw stateError();
423
+ let journal = rotationFor(config);
424
+ if (journal) await recoverSelectedRotation(journal, config);
425
+ config = read();
426
+ assertSelection(config, selection);
427
+ let bundle = await readBundle(config.auth.active.generation, config.auth.active);
428
+ journal = rotationFor(config);
429
+ if (journal?.phase === 'blocked') throw renewalError(journal.reason);
430
+ if (journal?.phase === 'retryable' && journal.retryNotBefore > now()) {
431
+ if (bundle.expiresAt <= now()) throw new AuthError('SESSION_REFRESH_RETRYABLE', 'Session renewal is rate limited or temporarily refused. Retry later, or run nansen login to start a new approval.');
432
+ validateSession(bundle, now());
433
+ return bundle;
434
+ }
435
+ if (bundle.expiresAt - now() > 60000) return bundle;
436
+ // An obsolete generation must be removed before creating another one.
437
+ if (journal && config.auth.active.generation === journal.targetGeneration) throw new AuthError('AUTH_CLEANUP_REQUIRED', 'Renewal cleanup is incomplete. Unlock secure storage and retry.');
438
+ if (!journal) {
439
+ // Discharge pre-renewal pairing journals while this generation is
440
+ // still active. An old journal must never later retire it as obsolete.
441
+ await recover();
442
+ const files = fs.readdirSync(journalDir).filter(recognizedJournal);
443
+ if (files.length <= 8 && files.some(file => readJournal(path.join(journalDir, file), file.slice(0, -5)).generations?.includes(config.auth.active.generation))) throw new AuthError('AUTH_BUSY', 'Login cleanup is still running. Retry after it finishes.');
444
+ if (files.length >= 8) throw new AuthError('AUTH_CLEANUP_REQUIRED', 'Authentication cleanup is pending. Run nansen logout after unlocking secure storage.');
445
+ if (config.auth.version !== 2) {
446
+ config = { ...config, auth: { ...config.auth, version: 2 } };
447
+ await atomic(configFile, config);
448
+ }
449
+ journal = { version: 2, kind: 'rotation', id: config.auth.selectionEpoch, selectionEpoch: config.auth.selectionEpoch, sourceGeneration: config.auth.active.generation, targetGeneration: randomUUID(), phase: 'in_flight' };
450
+ } else {
451
+ journal = { ...journal, phase: 'in_flight' }; delete journal.retryNotBefore;
452
+ }
453
+ // No consumptive call until the marker and v2 pointer barrier are durable.
454
+ await atomic(journalPath(journal.id), journal);
455
+ await barrier('rotation-marked'); check();
456
+ let replacement;
457
+ try { replacement = await refresh(bundle, { ...options(), now }); }
458
+ catch (error) {
459
+ // Legacy v2 journals lack the counter. Preserve them, then persist the
460
+ // count on the next proved non-consuming refusal; restarts cannot reset it.
461
+ const retryable = error.code === 'SESSION_REFRESH_RETRYABLE' && Number.isFinite(error.retryNotBefore) && error.retryNotBefore >= 0;
462
+ const retryFailures = (journal.retryFailures || 0) + (retryable ? 1 : 0);
463
+ const canRetry = retryable && retryFailures < MAX_RETRYABLE_RENEWALS;
464
+ const next = { ...journal, retryFailures, phase: canRetry ? 'retryable' : 'blocked', ...(canRetry
465
+ ? { retryNotBefore: Math.max(error.retryNotBefore, now() + 1000 * 2 ** (retryFailures - 1)) }
466
+ : { reason: retryable ? 'retry_exhausted' : blockedReason(error) }) };
467
+ await atomic(journalPath(journal.id), next);
468
+ if (canRetry) throw new AuthError('SESSION_REFRESH_RETRYABLE', 'Session renewal was refused before rotation. Check connectivity and system time, then retry later, or run nansen login to start a new approval.');
469
+ throw renewalError(next.reason);
470
+ }
471
+ check();
472
+ await barrier('rotation-received');
473
+ // The transport validated the response. Readback/restart validates again.
474
+ try { await store.write(journal.targetGeneration, replacement, options()); }
475
+ catch { throw new AuthError('SESSION_RENEWAL_STORAGE_ERROR', 'Could not store the renewed session. Retry the command to recover a complete replacement, or run nansen login. The old refresh credential will not be retried.'); }
476
+ await barrier('rotation-stored'); check();
477
+ journal.phase = 'ready';
478
+ await atomic(journalPath(journal.id), journal);
479
+ await publishRotation(journal, replacement, config);
480
+ await cleanRotation(journal, read());
481
+ bundle = { ...replacement, version: 1, generation: journal.targetGeneration };
482
+ check(); validateSession(bundle, now());
483
+ return bundle;
484
+ }, signal);
485
+ },
486
+ };
487
+ }
@@ -0,0 +1,20 @@
1
+ // Runs only inside the guarded helper process, never in the CLI event loop.
2
+ import { parentPort, workerData } from 'node:worker_threads';
3
+ let Entry;
4
+ try {
5
+ ({ Entry } = await import('@napi-rs/keyring'));
6
+ if (typeof Entry !== 'function') throw new Error();
7
+ }
8
+ catch { Entry = undefined; parentPort.postMessage({ error: 'BINDING_MISSING' }); }
9
+ if (Entry) {
10
+ try {
11
+ const { operation, account, data } = workerData;
12
+ const entry = new Entry('nansen-cli-api-auth-v1', account, { linux: { store: 'secret-service' } });
13
+ let value;
14
+ if (operation === 'set') { entry.setSecret(Buffer.from(data, 'base64')); value = true; }
15
+ else if (operation === 'get') { const bytes = entry.getSecret(); value = bytes == null ? null : Buffer.from(bytes).toString('base64'); }
16
+ else if (operation === 'delete') value = entry.deleteCredential();
17
+ else throw new Error();
18
+ parentPort.postMessage({ value });
19
+ } catch { parentPort.postMessage({ error: 'STORE_UNAVAILABLE' }); }
20
+ }
@@ -0,0 +1,64 @@
1
+ // The process owns execution exclusion; only its worker thread enters keyring.
2
+ // A blocked native call cannot block this process's parent-loss/timeout watchdog.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { Worker } from 'node:worker_threads';
6
+ import locks from 'fs-native-extensions';
7
+
8
+ const stop = () => process.kill(process.pid, 'SIGKILL');
9
+ const timer = setTimeout(stop, 10000);
10
+ process.stdin.on('end', stop);
11
+ process.stdin.on('error', stop);
12
+ process.stdout.on('error', stop);
13
+ let input = '', phase = 'guard';
14
+ let fd;
15
+ function safe(file, directory = false) {
16
+ if (!fs.existsSync(file)) return;
17
+ const stat = fs.lstatSync(file);
18
+ if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()) ||
19
+ (process.platform !== 'win32' && ((stat.mode & 0o022) || stat.uid !== process.getuid()))) throw new Error();
20
+ }
21
+ function receive(line) {
22
+ const message = JSON.parse(line);
23
+ if (phase === 'guard') {
24
+ const directory = message.directory;
25
+ if (typeof directory !== 'string' || !path.isAbsolute(directory)) throw new Error();
26
+ safe(directory, true);
27
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
28
+ const file = path.join(directory, 'auth-store.lock');
29
+ safe(file);
30
+ fd = fs.openSync(file, 'a+', 0o600);
31
+ // Independent acquisition: no cross-platform inherited-lock assumptions.
32
+ // This stable inode is never unlinked, including by recovery.
33
+ if (!locks.tryLock(fd)) throw new Error();
34
+ phase = 'operation';
35
+ process.stdout.write('{"ready":true}\n');
36
+ return;
37
+ }
38
+ if (phase !== 'operation' || !['set', 'get', 'delete'].includes(message.operation) || !/^[a-f0-9-]{36}\.(probe|manifest|[0-7])$/.test(message.account)) throw new Error();
39
+ phase = 'running';
40
+ const worker = new Worker(new URL('./auth-store-native.js', import.meta.url), { workerData: message, stdout: true, stderr: true });
41
+ worker.stdout.resume(); worker.stderr.resume();
42
+ let result;
43
+ worker.on('message', value => { result = value; });
44
+ worker.on('error', stop);
45
+ worker.on('exit', code => {
46
+ // No response or lock release until the executor can no longer write.
47
+ if (code !== 0 || !result || (result.error && result.error !== 'BINDING_MISSING')) return stop();
48
+ process.stdout.write(JSON.stringify(result) + '\n', () => {
49
+ clearTimeout(timer);
50
+ fs.closeSync(fd);
51
+ process.exit(0);
52
+ });
53
+ });
54
+ }
55
+ process.stdin.setEncoding('utf8');
56
+ process.stdin.on('data', chunk => {
57
+ input += chunk;
58
+ if (input.length > 40000) return stop();
59
+ let end;
60
+ while ((end = input.indexOf('\n')) !== -1) {
61
+ const line = input.slice(0, end); input = input.slice(end + 1);
62
+ try { receive(line); } catch { return stop(); }
63
+ }
64
+ });