-
-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy pathnpm-client.ts
More file actions
457 lines (404 loc) · 13.6 KB
/
npm-client.ts
File metadata and controls
457 lines (404 loc) · 13.6 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
import crypto from 'node:crypto'
import process from 'node:process'
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { mkdtemp, writeFile, rm } 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 } from './logger.ts'
const execFileAsync = promisify(execFile)
/**
* 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
}
function detectOtpRequired(stderr: string): boolean {
const otpPatterns = [
'EOTP',
'one-time password',
'This operation requires a one-time password',
'--otp=<code>',
]
const lowerStderr = stderr.toLowerCase()
return otpPatterns.some(pattern => lowerStderr.includes(pattern.toLowerCase()))
}
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()
return authPatterns.some(pattern => lowerStderr.includes(pattern.toLowerCase()))
}
function filterNpmWarnings(stderr: string): string {
return stderr
.split('\n')
.filter(line => !line.startsWith('npm warn'))
.join('\n')
.trim()
}
async function execNpm(
args: string[],
options: { otp?: string; silent?: boolean } = {},
): Promise<NpmExecResult> {
// 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 {
// Use execFile instead of exec to avoid shell injection vulnerabilities
// execFile does not spawn a shell, so metacharacters are passed literally
const { stdout, stderr } = await execFileAsync('npm', npmArgs, {
timeout: 60000,
env: { ...process.env, FORCE_COLOR: '0' },
})
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)
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',
otp?: string,
): Promise<NpmExecResult> {
validateOrgName(org)
validateUsername(user)
return execNpm(['org', 'set', org, user, role], { otp })
}
export async function orgRemoveUser(
org: string,
user: string,
otp?: string,
): Promise<NpmExecResult> {
validateOrgName(org)
validateUsername(user)
return execNpm(['org', 'rm', org, user], { otp })
}
export async function teamCreate(scopeTeam: string, otp?: string): Promise<NpmExecResult> {
validateScopeTeam(scopeTeam)
return execNpm(['team', 'create', scopeTeam], { otp })
}
export async function teamDestroy(scopeTeam: string, otp?: string): Promise<NpmExecResult> {
validateScopeTeam(scopeTeam)
return execNpm(['team', 'destroy', scopeTeam], { otp })
}
export async function teamAddUser(
scopeTeam: string,
user: string,
otp?: string,
): Promise<NpmExecResult> {
validateScopeTeam(scopeTeam)
validateUsername(user)
return execNpm(['team', 'add', scopeTeam, user], { otp })
}
export async function teamRemoveUser(
scopeTeam: string,
user: string,
otp?: string,
): Promise<NpmExecResult> {
validateScopeTeam(scopeTeam)
validateUsername(user)
return execNpm(['team', 'rm', scopeTeam, user], { otp })
}
export async function accessGrant(
permission: 'read-only' | 'read-write',
scopeTeam: string,
pkg: string,
otp?: string,
): Promise<NpmExecResult> {
validateScopeTeam(scopeTeam)
validatePackageName(pkg)
return execNpm(['access', 'grant', permission, scopeTeam, pkg], { otp })
}
export async function accessRevoke(
scopeTeam: string,
pkg: string,
otp?: string,
): Promise<NpmExecResult> {
validateScopeTeam(scopeTeam)
validatePackageName(pkg)
return execNpm(['access', 'revoke', scopeTeam, pkg], { otp })
}
export async function ownerAdd(user: string, pkg: string, otp?: string): Promise<NpmExecResult> {
validateUsername(user)
validatePackageName(pkg)
return execNpm(['owner', 'add', user, pkg], { otp })
}
export async function ownerRemove(user: string, pkg: string, otp?: string): Promise<NpmExecResult> {
validateUsername(user)
validatePackageName(pkg)
return execNpm(['owner', 'rm', user, pkg], { otp })
}
// 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 otp Optional OTP for 2FA
*/
export async function packageInit(
name: string,
author?: string,
otp?: string,
): Promise<NpmExecResult> {
validatePackageName(name)
// Create a temporary directory
const tempDir = await mkdtemp(join(tmpdir(), 'npmx-init-'))
try {
// 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, 'package.json'), JSON.stringify(packageJson, null, 2))
// Create empty index.js
await writeFile(join(tempDir, 'index.js'), '// Placeholder\n')
// Build npm publish args
const args = ['publish']
if (access) {
args.push('--access', access)
}
// Run npm publish from the temp directory
const npmArgs = otp ? [...args, '--otp', otp] : args
// Log the command being run (hide OTP value for security)
const displayCmd = otp ? `npm ${args.join(' ')} --otp ******` : `npm ${args.join(' ')}`
logCommand(`${displayCmd} (in temp dir for ${name})`)
try {
const { stdout, stderr } = await execFileAsync('npm', npmArgs, {
timeout: 60000,
cwd: tempDir,
env: { ...process.env, FORCE_COLOR: '0' },
})
logSuccess(`Published ${name}@0.0.0`)
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)
const requiresOtp = detectOtpRequired(stderr)
const authFailure = detectAuthFailure(stderr)
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,
}
}
} finally {
// Clean up temp directory
await rm(tempDir, { recursive: true, force: true }).catch(() => {
// Ignore cleanup errors
})
}
}
/**
* Deprecate a package or a specific version with a custom message.
* @param pkg Package name (e.g. "vue" or "@nuxt/kit")
* @param reason Deprecation message shown to users
* @param version Optional version to deprecate (e.g. "1.0.0"); if omitted, deprecates the whole package
* @param options.dryRun If true, passes --dry-run to npm (report what would be done without making changes)
* @param options.registry Registry URL (e.g. "https://registry.npmjs.org"); if set, passes --registry
*/
export async function packageDeprecate(
pkg: string,
reason: string,
version?: string,
otp?: string,
options?: { dryRun?: boolean; registry?: string },
): Promise<NpmExecResult> {
validatePackageName(pkg)
const target = version ? `${pkg}@${version}` : pkg
const args = ['deprecate', target, reason]
if (options?.dryRun) {
args.push('--dry-run')
}
if (options?.registry?.trim()) {
args.push('--registry', options.registry.trim())
}
return execNpm(args, { otp })
}