-
-
Notifications
You must be signed in to change notification settings - Fork 427
Expand file tree
/
Copy pathnpm-client.ts
More file actions
625 lines (543 loc) · 18.9 KB
/
npm-client.ts
File metadata and controls
625 lines (543 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
import crypto from 'node:crypto'
import process from 'node:process'
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { mkdtempDisposable, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import * as v from 'valibot'
import { PackageNameSchema, UsernameSchema, OrgNameSchema, ScopeTeamSchema } from './schemas.ts'
import { logCommand, logSuccess, logError, logDebug } from './logger.ts'
import { resolveNpmProcessCommand } from './npm-process.ts'
const execFileAsync = promisify(execFile)
export const NPM_REGISTRY_URL = 'https://registry.npmjs.org/'
function createNpmEnv(overrides: Record<string, string> = {}): Record<string, string> {
return {
...process.env,
...overrides,
FORCE_COLOR: '0',
npm_config_registry: NPM_REGISTRY_URL,
}
}
/**
* Validates an npm package name using the official npm validation package
* @throws Error if the name is invalid
* @internal
*/
export function validatePackageName(name: string): void {
const result = v.safeParse(PackageNameSchema, name)
if (!result.success) {
const message = result.issues[0]?.message || 'Invalid package name'
throw new Error(`Invalid package name "${name}": ${message}`)
}
}
/**
* Validates an npm username
* @throws Error if the username is invalid
* @internal
*/
export function validateUsername(name: string): void {
const result = v.safeParse(UsernameSchema, name)
if (!result.success) {
throw new Error(`Invalid username: ${name}`)
}
}
/**
* Validates an npm org name (without the @ prefix)
* @throws Error if the org name is invalid
* @internal
*/
export function validateOrgName(name: string): void {
const result = v.safeParse(OrgNameSchema, name)
if (!result.success) {
throw new Error(`Invalid org name: ${name}`)
}
}
/**
* Validates a scope:team format (e.g., @myorg:developers)
* @throws Error if the scope:team is invalid
* @internal
*/
export function validateScopeTeam(scopeTeam: string): void {
const result = v.safeParse(ScopeTeamSchema, scopeTeam)
if (!result.success) {
throw new Error(`Invalid scope:team format: ${scopeTeam}. Expected @scope:team`)
}
}
export interface NpmExecResult {
stdout: string
stderr: string
exitCode: number
/** True if the operation failed due to missing/invalid OTP */
requiresOtp?: boolean
/** True if the operation failed due to authentication failure (not logged in or token expired) */
authFailure?: boolean
/** URLs detected in the command output (stdout + stderr) */
urls?: string[]
}
function detectOtpRequired(stderr: string): boolean {
const otpPatterns = [
'EOTP',
'one-time password',
'This operation requires a one-time password',
'OTP required for authentication',
'--otp=<code>',
]
const lowerStderr = stderr.toLowerCase()
logDebug('Checking for OTP requirement in stderr:', stderr)
logDebug('OTP patterns:', otpPatterns)
const result = otpPatterns.some(pattern => lowerStderr.includes(pattern.toLowerCase()))
logDebug('OTP required:', result)
return result
}
function detectAuthFailure(stderr: string): boolean {
const authPatterns = [
'ENEEDAUTH',
'You must be logged in',
'authentication error',
'Unable to authenticate',
'code E401',
'code E403',
'401 Unauthorized',
'403 Forbidden',
'not logged in',
'npm login',
'npm adduser',
]
const lowerStderr = stderr.toLowerCase()
logDebug('Checking for auth failure in stderr:', stderr)
logDebug('Auth patterns:', authPatterns)
const result = authPatterns.some(pattern => lowerStderr.includes(pattern.toLowerCase()))
logDebug('Auth failure:', result)
return result
}
function filterNpmWarnings(stderr: string): string {
return stderr
.split('\n')
.filter(line => !line.startsWith('npm warn'))
.join('\n')
.trim()
}
const URL_RE = /https?:\/\/[^\s<>"{}|\\^`[\]]+/g
export function extractUrls(text: string): string[] {
const matches = text.match(URL_RE)
if (!matches) return []
const cleaned = matches.map(url => url.replace(/[.,;:!?)]+$/, ''))
return [...new Set(cleaned)]
}
// Patterns to detect npm's OTP prompt in pty output
const OTP_PROMPT_RE = /Enter OTP:/i
// Patterns to detect npm's web auth URL prompt in pty output
const AUTH_URL_PROMPT_RE = /Press ENTER to open in the browser/i
// npm prints "Authenticate your account at:\n<url>" — capture the URL on the next line
const AUTH_URL_TITLE_RE = /Authenticate your account at:\s*(https?:\/\/\S+)/
function stripAnsi(text: string): string {
// eslint disabled because we need escape characters in regex
// eslint-disable-next-line no-control-regex, regexp/no-obscure-range
return text.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, '')
}
const AUTH_URL_TIMEOUT_MS = 90_000
export interface ExecNpmOptions {
otp?: string
silent?: boolean
/** Working directory for the npm command. */
cwd?: string
/** When true, use PTY-based interactive execution instead of execFile. */
interactive?: boolean
/** When true, npm opens auth URLs in the user's browser.
* When false, browser opening is suppressed via npm_config_browser=false.
* Only relevant when `interactive` is true. */
openUrls?: boolean
/** Called when an auth URL is detected in the pty output, while npm is still running (polling doneUrl). Lets the caller expose the URL to the frontend via /state before the execute response comes back.
* Only relevant when `interactive` is true. */
onAuthUrl?: (url: string) => void
}
/**
* PTY-based npm execution for interactive commands (uses node-pty).
*
* - Web OTP - either open URL in browser if openUrls is true or passes the URL to frontend. If no auth happend within AUTH_URL_TIMEOUT_MS kills the process to unlock the connector.
*
* - CLI OTP - if we get a classic OTP prompt will either return OTP request to the frontend or will pass sent OTP if its provided
*/
async function execNpmInteractive(
args: string[],
options: ExecNpmOptions = {},
): Promise<NpmExecResult> {
const openUrls = options.openUrls === true
const { promise, resolve } = Promise.withResolvers<NpmExecResult>()
// Lazy-load node-pty so the native addon is only required when interactive mode is actually used.
const pty = await import('@lydell/node-pty')
const npmArgs = options.otp ? [...args, '--otp', options.otp] : args
if (!options.silent) {
const displayCmd = options.otp
? ['npm', ...args, '--otp', '******'].join(' ')
: ['npm', ...args].join(' ')
logCommand(`${displayCmd} (interactive/pty)`)
}
let output = ''
let resolved = false
let otpPromptSeen = false
let authUrlSeen = false
let enterSent = false
let authUrlTimeout: ReturnType<typeof setTimeout> | null = null
let authUrlTimedOut = false
const env = createNpmEnv()
// When openUrls is false, tell npm not to open the browser.
// npm still prints the auth URL and polls doneUrl
if (!openUrls) {
env.npm_config_browser = 'false'
}
const child = pty.spawn('npm', npmArgs, {
name: 'xterm-256color',
cols: 120,
rows: 30,
cwd: options.cwd,
env,
})
// General timeout: 5 minutes (covers non-auth interactive commands)
const timeout = setTimeout(() => {
if (resolved) return
logDebug('Interactive command timed out', { output })
child.kill()
}, 300000)
child.onData((data: string) => {
output += data
const clean = stripAnsi(data)
logDebug('pty data:', { text: clean.trim() })
const cleanAll = stripAnsi(output)
// Detect auth URL in output and notify the caller.
if (!authUrlSeen) {
const urlMatch = cleanAll.match(AUTH_URL_TITLE_RE)
if (urlMatch && urlMatch[1]) {
authUrlSeen = true
const authUrl = urlMatch[1].replace(/[.,;:!?)]+$/, '')
logDebug('Auth URL detected:', { authUrl, openUrls })
options.onAuthUrl?.(authUrl)
authUrlTimeout = setTimeout(() => {
if (resolved) return
authUrlTimedOut = true
logDebug('Auth URL timeout (90s) — killing process')
logError('Authentication timed out after 90 seconds')
child.kill()
}, AUTH_URL_TIMEOUT_MS)
}
}
if (authUrlSeen && openUrls && !enterSent && AUTH_URL_PROMPT_RE.test(cleanAll)) {
enterSent = true
logDebug('Web auth prompt detected, pressing ENTER')
child.write('\r')
}
if (!otpPromptSeen && OTP_PROMPT_RE.test(cleanAll)) {
otpPromptSeen = true
if (options.otp) {
logDebug('OTP prompt detected, writing OTP')
child.write(options.otp + '\r')
} else {
logDebug('OTP prompt detected but no OTP provided, killing process')
child.kill()
}
}
})
child.onExit(({ exitCode }) => {
if (resolved) return
resolved = true
clearTimeout(timeout)
if (authUrlTimeout) clearTimeout(authUrlTimeout)
const cleanOutput = stripAnsi(output)
logDebug('Interactive command exited:', { exitCode, output: cleanOutput })
const requiresOtp =
authUrlTimedOut || (otpPromptSeen && !options.otp) || detectOtpRequired(cleanOutput)
const authFailure = detectAuthFailure(cleanOutput)
const urls = extractUrls(cleanOutput)
if (!options.silent) {
if (exitCode === 0) {
logSuccess('Done')
} else if (requiresOtp) {
logError('OTP required')
} else if (authFailure) {
logError('Authentication required - please run "npm login" and restart the connector')
} else {
const firstLine = filterNpmWarnings(cleanOutput).split('\n')[0] || 'Command failed'
logError(firstLine)
}
}
// If auth URL timed out, force a non-zero exit code so it's marked as failed
const finalExitCode = authUrlTimedOut ? 1 : exitCode
resolve({
stdout: cleanOutput.trim(),
stderr: requiresOtp
? 'This operation requires a one-time password (OTP).'
: authFailure
? 'Authentication failed. Please run "npm login" and restart the connector.'
: filterNpmWarnings(cleanOutput),
exitCode: finalExitCode,
requiresOtp,
authFailure,
urls: urls.length > 0 ? urls : undefined,
})
})
return promise
}
async function execNpm(args: string[], options: ExecNpmOptions = {}): Promise<NpmExecResult> {
if (options.interactive) {
return execNpmInteractive(args, options)
}
// Build the full args array including OTP if provided
const npmArgs = options.otp ? [...args, '--otp', options.otp] : args
// Log the command being run (hide OTP value for security)
if (!options.silent) {
const displayCmd = options.otp
? ['npm', ...args, '--otp', '******'].join(' ')
: ['npm', ...args].join(' ')
logCommand(displayCmd)
}
try {
logDebug('Executing npm command:', { command: 'npm', args: npmArgs })
const { command, args: processArgs } = resolveNpmProcessCommand(npmArgs)
const { stdout, stderr } = await execFileAsync(command, processArgs, {
timeout: 60000,
cwd: options.cwd,
env: createNpmEnv(),
})
logDebug('Command succeeded:', { stdout, stderr })
if (!options.silent) {
logSuccess('Done')
}
return {
stdout: stdout.trim(),
stderr: filterNpmWarnings(stderr),
exitCode: 0,
}
} catch (error) {
const err = error as { stdout?: string; stderr?: string; code?: number }
const stderr = err.stderr?.trim() ?? String(error)
logDebug('Command failed:', { error, stdout: err.stdout, stderr: err.stderr, code: err.code })
const requiresOtp = detectOtpRequired(stderr)
const authFailure = detectAuthFailure(stderr)
if (!options.silent) {
if (requiresOtp) {
logError('OTP required')
} else if (authFailure) {
logError('Authentication required - please run "npm login" and restart the connector')
} else {
logError(filterNpmWarnings(stderr).split('\n')[0] || 'Command failed')
}
}
return {
stdout: err.stdout?.trim() ?? '',
stderr: requiresOtp
? 'This operation requires a one-time password (OTP).'
: authFailure
? 'Authentication failed. Please run "npm login" and restart the connector.'
: filterNpmWarnings(stderr),
exitCode: err.code ?? 1,
requiresOtp,
authFailure,
}
}
}
export async function getNpmUser(): Promise<string | null> {
const result = await execNpm(['whoami'], { silent: true })
if (result.exitCode === 0 && result.stdout) {
return result.stdout
}
return null
}
/**
* Gets the user's avatar as a base64 data URL from Gravatar.
* Returns null if the user's email cannot be retrieved or avatar fetch fails.
*/
export async function getNpmAvatar(): Promise<string | null> {
const result = await execNpm(['profile', 'get', 'email', '--json'], { silent: true })
if (result.exitCode !== 0 || !result.stdout) {
return null
}
try {
const parsed = JSON.parse(result.stdout) as { email?: string }
if (!parsed.email) {
return null
}
const email = parsed.email.trim().toLowerCase()
const hash = crypto.createHash('md5').update(email).digest('hex')
const gravatarUrl = `https://www.gravatar.com/avatar/${hash}?s=64&d=retro`
const response = await fetch(gravatarUrl)
if (!response.ok) {
return null
}
const contentType = response.headers.get('content-type') || 'image/png'
const buffer = await response.arrayBuffer()
const base64 = Buffer.from(buffer).toString('base64')
return `data:${contentType};base64,${base64}`
} catch {
return null
}
}
export async function orgAddUser(
org: string,
user: string,
role: 'developer' | 'admin' | 'owner',
options?: ExecNpmOptions,
): Promise<NpmExecResult> {
validateOrgName(org)
validateUsername(user)
return execNpm(['org', 'set', org, user, role], options)
}
export async function orgRemoveUser(
org: string,
user: string,
options?: ExecNpmOptions,
): Promise<NpmExecResult> {
validateOrgName(org)
validateUsername(user)
return execNpm(['org', 'rm', org, user], options)
}
export async function teamCreate(
scopeTeam: string,
options?: ExecNpmOptions,
): Promise<NpmExecResult> {
validateScopeTeam(scopeTeam)
return execNpm(['team', 'create', scopeTeam], options)
}
export async function teamDestroy(
scopeTeam: string,
options?: ExecNpmOptions,
): Promise<NpmExecResult> {
validateScopeTeam(scopeTeam)
return execNpm(['team', 'destroy', scopeTeam], options)
}
export async function teamAddUser(
scopeTeam: string,
user: string,
options?: ExecNpmOptions,
): Promise<NpmExecResult> {
validateScopeTeam(scopeTeam)
validateUsername(user)
return execNpm(['team', 'add', scopeTeam, user], options)
}
export async function teamRemoveUser(
scopeTeam: string,
user: string,
options?: ExecNpmOptions,
): Promise<NpmExecResult> {
validateScopeTeam(scopeTeam)
validateUsername(user)
return execNpm(['team', 'rm', scopeTeam, user], options)
}
export async function accessGrant(
permission: 'read-only' | 'read-write',
scopeTeam: string,
pkg: string,
options?: ExecNpmOptions,
): Promise<NpmExecResult> {
validateScopeTeam(scopeTeam)
validatePackageName(pkg)
return execNpm(['access', 'grant', permission, scopeTeam, pkg], options)
}
export async function accessRevoke(
scopeTeam: string,
pkg: string,
options?: ExecNpmOptions,
): Promise<NpmExecResult> {
validateScopeTeam(scopeTeam)
validatePackageName(pkg)
return execNpm(['access', 'revoke', scopeTeam, pkg], options)
}
export async function ownerAdd(
user: string,
pkg: string,
options?: ExecNpmOptions,
): Promise<NpmExecResult> {
validateUsername(user)
validatePackageName(pkg)
return execNpm(['owner', 'add', user, pkg], options)
}
export async function ownerRemove(
user: string,
pkg: string,
options?: ExecNpmOptions,
): Promise<NpmExecResult> {
validateUsername(user)
validatePackageName(pkg)
return execNpm(['owner', 'rm', user, pkg], options)
}
// List functions (for reading data) - silent since they're not user-triggered operations
export async function orgListUsers(org: string): Promise<NpmExecResult> {
validateOrgName(org)
return execNpm(['org', 'ls', org, '--json'], { silent: true })
}
export async function teamListTeams(org: string): Promise<NpmExecResult> {
validateOrgName(org)
return execNpm(['team', 'ls', org, '--json'], { silent: true })
}
export async function teamListUsers(scopeTeam: string): Promise<NpmExecResult> {
validateScopeTeam(scopeTeam)
return execNpm(['team', 'ls', scopeTeam, '--json'], { silent: true })
}
export async function accessListCollaborators(pkg: string): Promise<NpmExecResult> {
validatePackageName(pkg)
return execNpm(['access', 'list', 'collaborators', pkg, '--json'], { silent: true })
}
/**
* Lists all packages that a user has access to publish.
* Uses `npm access list packages @{user} --json`
* Returns a map of package name to permission level
*/
export async function listUserPackages(user: string): Promise<NpmExecResult> {
validateUsername(user)
return execNpm(['access', 'list', 'packages', `@${user}`, '--json'], { silent: true })
}
/**
* Initialize and publish a new package to claim the name.
* Creates a minimal package.json in a temp directory and publishes it.
* @param name Package name to claim
* @param author npm username of the publisher (for author field)
* @param options Execution options (otp, interactive, etc.)
*/
export async function packageInit(
name: string,
author?: string,
options?: ExecNpmOptions,
): Promise<NpmExecResult> {
validatePackageName(name)
// Let Node clean up the temp directory automatically when this scope exits.
await using tempDir = await mkdtempDisposable(join(tmpdir(), 'npmx-init-'))
// Determine access type based on whether it's a scoped package
const isScoped = name.startsWith('@')
const access = isScoped ? 'public' : undefined
// Create minimal package.json
const packageJson = {
name,
version: '0.0.0',
description: `Placeholder for ${name}`,
main: 'index.js',
scripts: {},
keywords: [],
author: author ? `${author} (https://www.npmjs.com/~${author})` : '',
license: 'UNLICENSED',
private: false,
...(access && { publishConfig: { access } }),
}
await writeFile(join(tempDir.path, 'package.json'), JSON.stringify(packageJson, null, 2))
// Create empty index.js
await writeFile(join(tempDir.path, 'index.js'), '// Placeholder\n')
// Build npm publish args
const args = ['publish']
if (access) {
args.push('--access', access)
}
const displayCmd = options?.otp
? ['npm', ...args, '--otp', '******'].join(' ')
: ['npm', ...args].join(' ')
logCommand(`${displayCmd} (in temp dir for ${name})`)
const result = await execNpm(args, { ...options, cwd: tempDir.path, silent: true })
if (result.exitCode === 0) {
logSuccess(`Published ${name}@0.0.0`)
} else if (result.requiresOtp) {
logError('OTP required')
} else if (result.authFailure) {
logError('Authentication required - please run "npm login" and restart the connector')
} else {
logError(result.stderr.split('\n')[0] || 'Command failed')
}
return result
}