-
-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy pathserver.ts
More file actions
755 lines (651 loc) · 20.9 KB
/
server.ts
File metadata and controls
755 lines (651 loc) · 20.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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
import crypto from 'node:crypto'
import { H3, HTTPError, handleCors, type H3Event } from 'h3-next'
import type { CorsOptions } from 'h3-next'
import * as v from 'valibot'
import type { ConnectorState, PendingOperation, ApiResponse } from './types.ts'
import { logDebug, logError } from './logger.ts'
import {
getNpmUser,
getNpmAvatar,
orgAddUser,
orgRemoveUser,
orgListUsers,
teamCreate,
teamDestroy,
teamAddUser,
teamRemoveUser,
teamListTeams,
teamListUsers,
accessGrant,
accessRevoke,
accessListCollaborators,
ownerAdd,
ownerRemove,
packageInit,
packageDeprecate,
listUserPackages,
type NpmExecResult,
} from './npm-client.ts'
import {
ConnectBodySchema,
ExecuteBodySchema,
CreateOperationBodySchema,
BatchOperationsBodySchema,
OrgNameSchema,
ScopeTeamSchema,
PackageNameSchema,
OperationIdSchema,
safeParse,
validateOperationParams,
} from './schemas.ts'
// Read version from package.json
import pkg from '../package.json' with { type: 'json' }
export const CONNECTOR_VERSION = pkg.version
function generateToken(): string {
return crypto.randomBytes(16).toString('hex')
}
function generateOperationId(): string {
return crypto.randomBytes(8).toString('hex')
}
const corsOptions: CorsOptions = {
origin: ['https://npmx.dev', /^http:\/\/localhost:\d+$/, /^http:\/\/127.0.0.1:\d+$/],
methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
}
export function createConnectorApp(expectedToken: string) {
const state: ConnectorState = {
session: {
token: expectedToken,
connectedAt: 0,
npmUser: null,
avatar: null,
},
operations: [],
}
const app = new H3()
// Handle CORS for all requests (including preflight)
app.use((event: H3Event) => {
const corsResult = handleCors(event, corsOptions)
if (corsResult !== false) {
return corsResult
}
})
function validateToken(authHeader: string | null): boolean {
if (!authHeader) return false
const token = authHeader.replace('Bearer ', '')
return token === expectedToken
}
app.post('/connect', async (event: H3Event) => {
const rawBody = await event.req.json()
const parsed = safeParse(ConnectBodySchema, rawBody)
if (!parsed.success) {
throw new HTTPError({ statusCode: 400, message: parsed.error })
}
if (parsed.data.token !== expectedToken) {
throw new HTTPError({ statusCode: 401, message: 'Invalid token' })
}
const [npmUser, avatar] = await Promise.all([getNpmUser(), getNpmAvatar()])
state.session.connectedAt = Date.now()
state.session.npmUser = npmUser
state.session.avatar = avatar
return {
success: true,
data: {
npmUser,
avatar,
connectedAt: state.session.connectedAt,
},
} as ApiResponse
})
app.get('/state', event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
return {
success: true,
data: {
npmUser: state.session.npmUser,
avatar: state.session.avatar,
operations: state.operations,
},
} as ApiResponse
})
app.post('/operations', async event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
const rawBody = await event.req.json()
const parsed = safeParse(CreateOperationBodySchema, rawBody)
if (!parsed.success) {
throw new HTTPError({ statusCode: 400, message: parsed.error })
}
const { type, params, description, command } = parsed.data
// Validate params based on operation type
try {
validateOperationParams(type, params)
} catch (err) {
const message = err instanceof v.ValiError ? err.issues[0]?.message : String(err)
throw new HTTPError({ statusCode: 400, message: `Invalid params: ${message}` })
}
const operation: PendingOperation = {
id: generateOperationId(),
type,
params,
description,
command,
status: 'pending',
createdAt: Date.now(),
}
state.operations.push(operation)
return {
success: true,
data: operation,
} as ApiResponse
})
app.post('/operations/batch', async event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
const rawBody = await event.req.json()
const parsed = safeParse(BatchOperationsBodySchema, rawBody)
if (!parsed.success) {
throw new HTTPError({ statusCode: 400, message: parsed.error })
}
// Validate each operation's params
for (let i = 0; i < parsed.data.length; i++) {
const op = parsed.data[i]
if (!op) continue
try {
validateOperationParams(op.type, op.params)
} catch (err) {
const message = err instanceof v.ValiError ? err.issues[0]?.message : String(err)
throw new HTTPError({
statusCode: 400,
message: `Operation ${i}: Invalid params: ${message}`,
})
}
}
const created: PendingOperation[] = []
for (const op of parsed.data) {
const operation: PendingOperation = {
id: generateOperationId(),
type: op.type,
params: op.params,
description: op.description,
command: op.command,
status: 'pending',
createdAt: Date.now(),
}
state.operations.push(operation)
created.push(operation)
}
return {
success: true,
data: created,
} as ApiResponse
})
app.post('/approve', event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
const url = new URL(event.req.url)
const id = url.searchParams.get('id')
const idValidation = safeParse(OperationIdSchema, id)
if (!idValidation.success) {
throw new HTTPError({ statusCode: 400, message: idValidation.error })
}
const operation = state.operations.find(op => op.id === idValidation.data)
if (!operation) {
throw new HTTPError({ statusCode: 404, message: 'Operation not found' })
}
if (operation.status !== 'pending') {
throw new HTTPError({
statusCode: 400,
message: 'Operation is not pending',
})
}
operation.status = 'approved'
return {
success: true,
data: operation,
} as ApiResponse
})
app.post('/approve-all', event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
const pendingOps = state.operations.filter(op => op.status === 'pending')
for (const op of pendingOps) {
op.status = 'approved'
}
return {
success: true,
data: { approved: pendingOps.length },
} as ApiResponse
})
app.post('/retry', event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
const url = new URL(event.req.url)
const id = url.searchParams.get('id')
const idValidation = safeParse(OperationIdSchema, id)
if (!idValidation.success) {
throw new HTTPError({ statusCode: 400, message: idValidation.error })
}
const operation = state.operations.find(op => op.id === idValidation.data)
if (!operation) {
throw new HTTPError({ statusCode: 404, message: 'Operation not found' })
}
if (operation.status !== 'failed') {
throw new HTTPError({
statusCode: 400,
message: 'Only failed operations can be retried',
})
}
// Reset the operation for retry
operation.status = 'approved'
operation.result = undefined
return {
success: true,
data: operation,
} as ApiResponse
})
app.post('/execute', async event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
// OTP can be passed directly in the request body for this execution
let otp: string | undefined
try {
const rawBody = await event.req.json()
if (rawBody) {
const parsed = safeParse(ExecuteBodySchema, rawBody)
if (!parsed.success) {
throw new HTTPError({ statusCode: 400, message: parsed.error })
}
otp = parsed.data.otp
}
} catch (err) {
// Re-throw HTTPError, ignore JSON parse errors (empty body is fine)
if (err instanceof HTTPError) throw err
}
const approvedOps = state.operations.filter(op => op.status === 'approved')
const results: Array<{ id: string; result: NpmExecResult }> = []
let otpRequired = false
const completedIds = new Set<string>()
const failedIds = new Set<string>()
// Execute operations in waves, respecting dependencies
// Each wave contains operations whose dependencies are satisfied
while (true) {
// Find operations ready to run (no pending dependencies)
const readyOps = approvedOps.filter(op => {
// Already processed
if (completedIds.has(op.id) || failedIds.has(op.id)) return false
// No dependency - ready
if (!op.dependsOn) return true
// Dependency completed successfully - ready
if (completedIds.has(op.dependsOn)) return true
// Dependency failed - skip this one too
if (failedIds.has(op.dependsOn)) {
op.status = 'failed'
op.result = {
stdout: '',
stderr: 'Skipped: dependency failed',
exitCode: 1,
}
failedIds.add(op.id)
results.push({ id: op.id, result: op.result })
return false
}
// Dependency still pending - not ready
return false
})
// No more operations to run
if (readyOps.length === 0) break
// If we've hit an OTP error and no OTP was provided, stop
if (otpRequired && !otp) break
// Execute ready operations in parallel
const runningOps = readyOps.map(async op => {
op.status = 'running'
const result = await executeOperation(op, otp)
op.result = result
op.status = result.exitCode === 0 ? 'completed' : 'failed'
if (result.exitCode === 0) {
completedIds.add(op.id)
} else {
failedIds.add(op.id)
}
// Track if OTP is needed
if (result.requiresOtp) {
otpRequired = true
}
results.push({ id: op.id, result })
})
await Promise.all(runningOps)
}
// Check if any operation had an auth failure
const authFailure = results.some(r => r.result.authFailure)
return {
success: true,
data: {
results,
otpRequired,
authFailure,
},
} as ApiResponse
})
app.delete('/operations', event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
const url = new URL(event.req.url)
const id = url.searchParams.get('id')
const idValidation = safeParse(OperationIdSchema, id)
if (!idValidation.success) {
throw new HTTPError({ statusCode: 400, message: idValidation.error })
}
const index = state.operations.findIndex(op => op.id === idValidation.data)
if (index === -1) {
throw new HTTPError({ statusCode: 404, message: 'Operation not found' })
}
const operation = state.operations[index]
if (!operation || operation.status === 'running') {
throw new HTTPError({
statusCode: 400,
message: 'Cannot cancel running operation',
})
}
state.operations.splice(index, 1)
return { success: true } as ApiResponse
})
app.delete('/operations/all', event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
const removed = state.operations.filter(op => op.status !== 'running').length
state.operations = state.operations.filter(op => op.status === 'running')
return {
success: true,
data: { removed },
} as ApiResponse
})
// List endpoints (read-only data fetching)
app.get('/org/:org/users', async event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
const orgRaw = event.context.params?.org
const orgValidation = safeParse(OrgNameSchema, orgRaw)
if (!orgValidation.success) {
throw new HTTPError({ statusCode: 400, message: orgValidation.error })
}
const result = await orgListUsers(orgValidation.data)
if (result.exitCode !== 0) {
return {
success: false,
error: result.stderr || 'Failed to list org users',
} as ApiResponse
}
try {
const users = JSON.parse(result.stdout) as Record<string, 'developer' | 'admin' | 'owner'>
return {
success: true,
data: users,
} as ApiResponse
} catch {
return {
success: false,
error: 'Failed to parse org users',
} as ApiResponse
}
})
app.get('/org/:org/teams', async event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
const orgRaw = event.context.params?.org
const orgValidation = safeParse(OrgNameSchema, orgRaw)
if (!orgValidation.success) {
throw new HTTPError({ statusCode: 400, message: orgValidation.error })
}
const result = await teamListTeams(orgValidation.data)
if (result.exitCode !== 0) {
return {
success: false,
error: result.stderr || 'Failed to list teams',
} as ApiResponse
}
try {
const teams = JSON.parse(result.stdout) as string[]
return {
success: true,
data: teams,
} as ApiResponse
} catch {
return {
success: false,
error: 'Failed to parse teams',
} as ApiResponse
}
})
app.get('/team/:scopeTeam/users', async event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
const scopeTeamRaw = event.context.params?.scopeTeam
if (!scopeTeamRaw) {
throw new HTTPError({ statusCode: 400, message: 'Team name required' })
}
// Decode the team name (handles encoded colons like nuxt%3Adevelopers)
const scopeTeam = decodeURIComponent(scopeTeamRaw)
const validationResult = safeParse(ScopeTeamSchema, scopeTeam)
if (!validationResult.success) {
logError('scope:team validation failed')
logDebug(validationResult.error, { scopeTeamRaw, scopeTeam })
throw new HTTPError({
statusCode: 400,
message: `Invalid scope:team format: ${scopeTeam}. Expected @scope:team`,
})
}
const result = await teamListUsers(scopeTeam)
if (result.exitCode !== 0) {
return {
success: false,
error: result.stderr || 'Failed to list team users',
} as ApiResponse
}
try {
const users = JSON.parse(result.stdout) as string[]
return {
success: true,
data: users,
} as ApiResponse
} catch {
return {
success: false,
error: 'Failed to parse team users',
} as ApiResponse
}
})
app.get('/package/:pkg/collaborators', async event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
const pkgRaw = event.context.params?.pkg
if (!pkgRaw) {
throw new HTTPError({ statusCode: 400, message: 'Package name required' })
}
// Decode the package name (handles scoped packages like @nuxt%2Fkit)
const decodedPkg = decodeURIComponent(pkgRaw)
const pkgValidation = safeParse(PackageNameSchema, decodedPkg)
if (!pkgValidation.success) {
throw new HTTPError({ statusCode: 400, message: pkgValidation.error })
}
const result = await accessListCollaborators(pkgValidation.data)
if (result.exitCode !== 0) {
return {
success: false,
error: result.stderr || 'Failed to list collaborators',
} as ApiResponse
}
try {
const collaborators = JSON.parse(result.stdout) as Record<string, 'read-only' | 'read-write'>
return {
success: true,
data: collaborators,
} as ApiResponse
} catch {
return {
success: false,
error: 'Failed to parse collaborators',
} as ApiResponse
}
})
// User-specific endpoints
app.get('/user/packages', async event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
const npmUser = state.session.npmUser
if (!npmUser) {
return {
success: false,
error: 'Not logged in to npm',
} as ApiResponse
}
const result = await listUserPackages(npmUser)
if (result.exitCode !== 0) {
return {
success: false,
error: result.stderr || 'Failed to list user packages',
} as ApiResponse
}
try {
// npm access list packages returns { "packageName": "read-write" | "read-only" }
const packages = JSON.parse(result.stdout) as Record<string, 'read-write' | 'read-only'>
return {
success: true,
data: packages,
} as ApiResponse
} catch {
return {
success: false,
error: 'Failed to parse user packages',
} as ApiResponse
}
})
app.get('/user/orgs', async event => {
const auth = event.req.headers.get('authorization')
if (!validateToken(auth)) {
throw new HTTPError({ statusCode: 401, message: 'Unauthorized' })
}
const npmUser = state.session.npmUser
if (!npmUser) {
return {
success: false,
error: 'Not logged in to npm',
} as ApiResponse
}
// Get user's packages and extract org names from scoped packages
const result = await listUserPackages(npmUser)
if (result.exitCode !== 0) {
return {
success: false,
error: result.stderr || 'Failed to list user packages',
} as ApiResponse
}
try {
const packages = JSON.parse(result.stdout) as Record<string, string>
const orgs = new Set<string>()
// Extract org names from scoped packages (e.g., @myorg/mypackage -> myorg)
for (const pkgName of Object.keys(packages)) {
if (pkgName.startsWith('@')) {
const match = pkgName.match(/^@([^/]+)\//)
if (match && match[1]) {
// Exclude the user's own scope (personal packages)
if (match[1].toLowerCase() !== npmUser.toLowerCase()) {
orgs.add(match[1])
}
}
}
}
return {
success: true,
data: Array.from(orgs).sort(),
} as ApiResponse
} catch {
return {
success: false,
error: 'Failed to parse user orgs',
} as ApiResponse
}
})
return app
}
async function executeOperation(op: PendingOperation, otp?: string): Promise<NpmExecResult> {
const { type, params } = op
switch (type) {
case 'org:add-user':
return orgAddUser(
params.org,
params.user,
params.role as 'developer' | 'admin' | 'owner',
otp,
)
case 'org:rm-user':
return orgRemoveUser(params.org, params.user, otp)
case 'team:create':
return teamCreate(params.scopeTeam, otp)
case 'team:destroy':
return teamDestroy(params.scopeTeam, otp)
case 'team:add-user':
return teamAddUser(params.scopeTeam, params.user, otp)
case 'team:rm-user':
return teamRemoveUser(params.scopeTeam, params.user, otp)
case 'access:grant':
return accessGrant(
params.permission as 'read-only' | 'read-write',
params.scopeTeam,
params.pkg,
otp,
)
case 'access:revoke':
return accessRevoke(params.scopeTeam, params.pkg, otp)
case 'owner:add':
return ownerAdd(params.user, params.pkg, otp)
case 'owner:rm':
return ownerRemove(params.user, params.pkg, otp)
case 'package:init':
return packageInit(params.name, params.author, otp)
case 'package:deprecate': {
const dryRun = params.dryRun === 'true'
const registry = params.registry?.trim() ?? undefined
return packageDeprecate(params.pkg, params.message, params.version, otp, {
dryRun: dryRun ?? undefined,
registry,
})
}
default:
return {
stdout: '',
stderr: `Unknown operation type: ${type}`,
exitCode: 1,
}
}
}
export { generateToken }