-
-
Notifications
You must be signed in to change notification settings - Fork 424
Expand file tree
/
Copy pathserver.ts
More file actions
569 lines (484 loc) · 15.3 KB
/
server.ts
File metadata and controls
569 lines (484 loc) · 15.3 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
import crypto from 'node:crypto'
import { H3, HTTPError, handleCors, type H3Event } from 'h3-next'
import type { CorsOptions } from 'h3-next'
import type { ConnectorState, PendingOperation, OperationType, ApiResponse } from './types.ts'
import { logDebug, logError } from './logger.ts'
import {
getNpmUser,
orgAddUser,
orgRemoveUser,
orgListUsers,
teamCreate,
teamDestroy,
teamAddUser,
teamRemoveUser,
teamListTeams,
teamListUsers,
accessGrant,
accessRevoke,
accessListCollaborators,
ownerAdd,
ownerRemove,
packageInit,
validateScopeTeam,
type NpmExecResult,
} from './npm-client.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+$/],
methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
}
export function createConnectorApp(expectedToken: string) {
const state: ConnectorState = {
session: {
token: expectedToken,
connectedAt: 0,
npmUser: 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 body = (await event.req.json()) as { token?: string }
if (body?.token !== expectedToken) {
throw new HTTPError({ statusCode: 401, message: 'Invalid token' })
}
const npmUser = await getNpmUser()
state.session.connectedAt = Date.now()
state.session.npmUser = npmUser
return {
success: true,
data: {
npmUser,
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,
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 body = (await event.req.json()) as {
type: OperationType
params: Record<string, string>
description: string
command: string
}
const { type, params, description, command } = body
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 operations = (await event.req.json()) as Array<{
type: OperationType
params: Record<string, string>
description: string
command: string
}>
const created: PendingOperation[] = []
for (const op of operations) {
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 operation = state.operations.find(op => op.id === id)
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 operation = state.operations.find(op => op.id === id)
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 body = (await event.req.json()) as { otp?: string } | null
otp = body?.otp
} catch {
// Empty body is fine - no OTP provided
}
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 index = state.operations.findIndex(op => op.id === id)
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 org = event.context.params?.org
if (!org) {
throw new HTTPError({ statusCode: 400, message: 'Org name required' })
}
const result = await orgListUsers(org)
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 org = event.context.params?.org
if (!org) {
throw new HTTPError({ statusCode: 400, message: 'Org name required' })
}
const result = await teamListTeams(org)
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)
try {
validateScopeTeam(scopeTeam)
} catch (err) {
logError('scope:team validation failed')
logDebug(err, { 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 pkg = event.context.params?.pkg
if (!pkg) {
throw new HTTPError({ statusCode: 400, message: 'Package name required' })
}
// Decode the package name (handles scoped packages like @nuxt%2Fkit)
const decodedPkg = decodeURIComponent(pkg)
const result = await accessListCollaborators(decodedPkg)
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
}
})
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)
default:
return {
stdout: '',
stderr: `Unknown operation type: ${type}`,
exitCode: 1,
}
}
}
export { generateToken }