@karoy/dsh-gitlab-workbench 0.0.0-stage → 0.2.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.
@@ -0,0 +1,567 @@
1
+ import { GitLabError, pageOf } from './gitlab.js';
2
+ /** The prefix of every route this plugin serves. */
3
+ export const ROUTE_PREFIX = '/gitlab-workbench/api/';
4
+ /** The largest request body accepted. */
5
+ const MAX_BODY = 1024 * 1024;
6
+ /** How much of a job trace is returned. */
7
+ const TRACE_TAIL = 200000;
8
+ /** The actions that need an instance id. */
9
+ const PROJECT_ACTIONS = new Set([
10
+ 'projects',
11
+ 'project',
12
+ 'branches',
13
+ 'tags',
14
+ 'commits',
15
+ 'tree',
16
+ 'file',
17
+ 'pipelines',
18
+ 'pipeline',
19
+ 'job-trace',
20
+ 'pipeline/retry',
21
+ 'pipeline/cancel',
22
+ 'job/retry',
23
+ 'job/cancel',
24
+ 'job/play',
25
+ 'merge-requests',
26
+ 'merge-request',
27
+ 'issues',
28
+ 'issue',
29
+ ]);
30
+ /** File extensions the viewer treats as binary. */
31
+ const BINARY_EXTENSIONS = new Set([
32
+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'ico', 'bmp', 'tif', 'tiff', 'avif',
33
+ 'pdf', 'zip', 'gz', 'tgz', 'bz2', 'xz', '7z', 'rar', 'jar', 'war',
34
+ 'woff', 'woff2', 'ttf', 'otf', 'eot', 'mp3', 'mp4', 'webm', 'mov', 'avi',
35
+ 'so', 'dll', 'exe', 'bin', 'class', 'pyc', 'wasm', 'db', 'sqlite',
36
+ ]);
37
+ function json(res, status, body) {
38
+ res.writeHead(status, {
39
+ 'Content-Type': 'application/json; charset=utf-8',
40
+ 'Cache-Control': 'no-store',
41
+ });
42
+ res.end(JSON.stringify(body));
43
+ }
44
+ function ok(res, data) {
45
+ json(res, 200, { ok: true, data });
46
+ }
47
+ function fail(res, error) {
48
+ const status = Number.isInteger(error?.status) ? error.status : 500;
49
+ json(res, status, {
50
+ ok: false,
51
+ error: {
52
+ code: error?.code ?? 'internal_error',
53
+ message: String(error?.message ?? error),
54
+ ...(error?.detail ? { detail: String(error.detail) } : {}),
55
+ },
56
+ });
57
+ }
58
+ function readJson(req) {
59
+ return new Promise((resolve, reject) => {
60
+ let size = 0;
61
+ const chunks = [];
62
+ req.on('data', (chunk) => {
63
+ size += chunk.length;
64
+ if (size > MAX_BODY) {
65
+ reject(Object.assign(new Error('The request body is too large.'), { status: 413, code: 'body_too_large' }));
66
+ req.destroy();
67
+ return;
68
+ }
69
+ chunks.push(chunk);
70
+ });
71
+ req.on('end', () => {
72
+ if (chunks.length === 0) {
73
+ resolve({});
74
+ return;
75
+ }
76
+ try {
77
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
78
+ resolve(parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {});
79
+ }
80
+ catch {
81
+ reject(Object.assign(new Error('The request body is not valid JSON.'), { status: 400, code: 'bad_json' }));
82
+ }
83
+ });
84
+ req.on('error', (error) => reject(error));
85
+ });
86
+ }
87
+ /** Strip ANSI escape sequences so a trace renders as plain text. */
88
+ function plainTrace(text) {
89
+ return String(text)
90
+ .replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, '')
91
+ .replace(/\r\n/g, '\n');
92
+ }
93
+ /** Report whether a file should be opened in the binary branch. */
94
+ function looksBinary(filePath, text) {
95
+ const extension = filePath.includes('.') ? filePath.split('.').pop().toLowerCase() : '';
96
+ if (BINARY_EXTENSIONS.has(extension))
97
+ return true;
98
+ return text.includes('\u0000');
99
+ }
100
+ /** Build the route handler. */
101
+ export function createRoutes({ ctx, store, gitlab, version }) {
102
+ /** Apply the host's own admission check to one request. */
103
+ function admit(req, res) {
104
+ // The connection service is optional and is not part of this plugin's
105
+ // `inject`; read it through the registry so a profile without it falls
106
+ // back to the loopback check instead of throwing.
107
+ let connection;
108
+ try {
109
+ connection = ctx.get?.('connection');
110
+ }
111
+ catch {
112
+ connection = undefined;
113
+ }
114
+ if (connection && typeof connection.requestRejection === 'function') {
115
+ let rejected;
116
+ try {
117
+ rejected = connection.requestRejection(req);
118
+ }
119
+ catch {
120
+ rejected = 403;
121
+ }
122
+ if (rejected) {
123
+ json(res, rejected, { ok: false, error: { code: 'forbidden', message: 'forbidden' } });
124
+ return false;
125
+ }
126
+ return true;
127
+ }
128
+ const remote = String(req.socket?.remoteAddress ?? '');
129
+ if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(remote)) {
130
+ json(res, 403, { ok: false, error: { code: 'forbidden', message: 'forbidden' } });
131
+ return false;
132
+ }
133
+ return true;
134
+ }
135
+ /** Describe one instance for the browser, without its token. */
136
+ async function describeInstance(instance) {
137
+ const token = await store.readToken(instance.id);
138
+ const status = store.getStatus(instance.id) ?? { ok: null };
139
+ return {
140
+ id: instance.id,
141
+ label: instance.label,
142
+ endpoint: instance.endpoint,
143
+ verifyTls: instance.verifyTls !== false,
144
+ hasCaPem: typeof instance.caPem === 'string' && instance.caPem !== '',
145
+ hasToken: Boolean(token?.token),
146
+ tokenUsername: token?.username ?? '',
147
+ status,
148
+ createdAt: instance.createdAt,
149
+ updatedAt: instance.updatedAt,
150
+ };
151
+ }
152
+ /** Check one instance against GitLab and remember the result. */
153
+ async function testInstance(instanceId) {
154
+ const instance = store.get(instanceId);
155
+ if (!instance)
156
+ throw Object.assign(new Error('Unknown instance.'), { code: 'unknown_instance', status: 404 });
157
+ try {
158
+ const user = await gitlab.currentUser(instanceId);
159
+ const gitlabVersion = await gitlab.version(instanceId);
160
+ const status = {
161
+ ok: true,
162
+ user: {
163
+ username: String(user.username ?? ''),
164
+ name: String(user.name ?? ''),
165
+ avatarUrl: String(user.avatar_url ?? ''),
166
+ webUrl: String(user.web_url ?? ''),
167
+ },
168
+ version: gitlabVersion,
169
+ };
170
+ store.setStatus(instanceId, status);
171
+ return { ...status, checkedAt: new Date().toISOString() };
172
+ }
173
+ catch (error) {
174
+ const failure = error;
175
+ const status = {
176
+ ok: false,
177
+ error: {
178
+ code: failure?.code ?? 'connection_failed',
179
+ message: String(failure?.message ?? error),
180
+ status: failure?.status ?? 502,
181
+ },
182
+ };
183
+ store.setStatus(instanceId, status);
184
+ return { ...status, checkedAt: new Date().toISOString() };
185
+ }
186
+ }
187
+ function required(body, name) {
188
+ const value = body?.[name];
189
+ const text = typeof value === 'number' && Number.isFinite(value)
190
+ ? String(value)
191
+ : typeof value === 'string'
192
+ ? value.trim()
193
+ : '';
194
+ if (text === '') {
195
+ throw Object.assign(new Error(`The "${name}" field is required.`), { status: 400, code: 'bad_request' });
196
+ }
197
+ return text;
198
+ }
199
+ function requiredQuery(query, name) {
200
+ const value = query.get(name);
201
+ if (!value || value.trim() === '') {
202
+ throw Object.assign(new Error(`The "${name}" parameter is required.`), { status: 400, code: 'bad_request' });
203
+ }
204
+ return value;
205
+ }
206
+ function projectSegment(project) {
207
+ return encodeURIComponent(project);
208
+ }
209
+ async function dispatch(action, req, res, url) {
210
+ const query = url.searchParams;
211
+ const method = req.method ?? 'GET';
212
+ if (action === 'ping') {
213
+ ok(res, { version });
214
+ return;
215
+ }
216
+ if (action === 'instances' && method === 'GET') {
217
+ const items = await Promise.all(store.list().map((instance) => describeInstance(instance)));
218
+ ok(res, { items });
219
+ return;
220
+ }
221
+ if (action === 'instances/add' && method === 'POST') {
222
+ const body = await readJson(req);
223
+ const instance = store.add({
224
+ label: typeof body.label === 'string' ? body.label : '',
225
+ endpoint: required(body, 'endpoint'),
226
+ verifyTls: body.verifyTls !== false,
227
+ caPem: typeof body.caPem === 'string' ? body.caPem : '',
228
+ });
229
+ ok(res, await describeInstance(instance));
230
+ return;
231
+ }
232
+ if (action === 'instances/update' && method === 'POST') {
233
+ const body = await readJson(req);
234
+ const id = required(body, 'id');
235
+ const patch = {};
236
+ if (typeof body.label === 'string')
237
+ patch.label = body.label;
238
+ if (typeof body.endpoint === 'string')
239
+ patch.endpoint = body.endpoint;
240
+ if (typeof body.verifyTls === 'boolean')
241
+ patch.verifyTls = body.verifyTls;
242
+ if (body.caPem === null || typeof body.caPem === 'string')
243
+ patch.caPem = body.caPem;
244
+ const instance = await store.update(id, patch);
245
+ ok(res, await describeInstance(instance));
246
+ return;
247
+ }
248
+ if (action === 'instances/remove' && method === 'POST') {
249
+ const body = await readJson(req);
250
+ const id = required(body, 'id');
251
+ ok(res, { removed: await store.remove(id) });
252
+ return;
253
+ }
254
+ if (action === 'instances/token' && method === 'POST') {
255
+ const body = await readJson(req);
256
+ const id = required(body, 'id');
257
+ const token = required(body, 'token');
258
+ const instance = store.get(id);
259
+ if (!instance)
260
+ throw Object.assign(new Error('Unknown instance.'), { code: 'unknown_instance', status: 404 });
261
+ let user;
262
+ try {
263
+ user = await gitlab.currentUser(id, token);
264
+ }
265
+ catch (error) {
266
+ const failure = error;
267
+ if (failure?.code === 'unauthorized') {
268
+ throw Object.assign(new Error('GitLab rejected this token. Check its scopes (read_api, or api) and expiry.'), {
269
+ code: 'invalid_token',
270
+ status: 401,
271
+ });
272
+ }
273
+ throw error;
274
+ }
275
+ await store.writeToken(id, {
276
+ token,
277
+ username: String(user.username ?? ''),
278
+ name: String(user.name ?? ''),
279
+ avatarUrl: String(user.avatar_url ?? ''),
280
+ webUrl: String(user.web_url ?? ''),
281
+ updatedAt: new Date().toISOString(),
282
+ });
283
+ ok(res, { status: await testInstance(id) });
284
+ return;
285
+ }
286
+ if (action === 'instances/test' && method === 'POST') {
287
+ const body = await readJson(req);
288
+ ok(res, await testInstance(required(body, 'id')));
289
+ return;
290
+ }
291
+ if (!PROJECT_ACTIONS.has(action)) {
292
+ throw Object.assign(new Error(`Unknown action "${action}".`), { status: 404, code: 'unknown_action' });
293
+ }
294
+ const instanceId = requiredQuery(query, 'id');
295
+ if (!store.get(instanceId)) {
296
+ throw Object.assign(new Error('Unknown instance.'), { code: 'unknown_instance', status: 404 });
297
+ }
298
+ if (action === 'projects' && method === 'GET') {
299
+ const result = await gitlab.request(instanceId, {
300
+ path: '/projects',
301
+ query: {
302
+ membership: true,
303
+ simple: false,
304
+ per_page: 40,
305
+ order_by: 'last_activity_at',
306
+ sort: 'desc',
307
+ page: query.get('page') ?? '1',
308
+ search: query.get('search') ?? '',
309
+ },
310
+ });
311
+ ok(res, pageOf(result));
312
+ return;
313
+ }
314
+ if (action === 'project' && method === 'GET') {
315
+ const project = requiredQuery(query, 'path');
316
+ const result = await gitlab.request(instanceId, { path: `/projects/${projectSegment(project)}` });
317
+ const data = result.data ?? {};
318
+ let openMergeRequests = null;
319
+ try {
320
+ const count = await gitlab.request(instanceId, {
321
+ path: `/projects/${projectSegment(project)}/merge_requests`,
322
+ query: { state: 'opened', per_page: 1 },
323
+ });
324
+ const parsed = Number.parseInt(String(count.headers?.['x-total'] ?? ''), 10);
325
+ openMergeRequests = Number.isFinite(parsed) ? parsed : null;
326
+ }
327
+ catch {
328
+ openMergeRequests = null;
329
+ }
330
+ ok(res, { project: data, openMergeRequests });
331
+ return;
332
+ }
333
+ if (action === 'branches' && method === 'GET') {
334
+ const project = requiredQuery(query, 'path');
335
+ const result = await gitlab.request(instanceId, {
336
+ path: `/projects/${projectSegment(project)}/repository/branches`,
337
+ query: { per_page: 100, page: query.get('page') ?? '1' },
338
+ });
339
+ ok(res, pageOf(result));
340
+ return;
341
+ }
342
+ if (action === 'tags' && method === 'GET') {
343
+ const project = requiredQuery(query, 'path');
344
+ const result = await gitlab.request(instanceId, {
345
+ path: `/projects/${projectSegment(project)}/repository/tags`,
346
+ query: { per_page: 100, page: query.get('page') ?? '1' },
347
+ });
348
+ ok(res, pageOf(result));
349
+ return;
350
+ }
351
+ if (action === 'commits' && method === 'GET') {
352
+ const project = requiredQuery(query, 'path');
353
+ const result = await gitlab.request(instanceId, {
354
+ path: `/projects/${projectSegment(project)}/repository/commits`,
355
+ query: { per_page: 30, page: query.get('page') ?? '1', ref_name: query.get('ref') ?? '' },
356
+ });
357
+ ok(res, pageOf(result));
358
+ return;
359
+ }
360
+ if (action === 'tree' && method === 'GET') {
361
+ const project = requiredQuery(query, 'path');
362
+ const result = await gitlab.request(instanceId, {
363
+ path: `/projects/${projectSegment(project)}/repository/tree`,
364
+ query: {
365
+ per_page: 100,
366
+ page: query.get('page') ?? '1',
367
+ path: query.get('dir') ?? '',
368
+ ref: query.get('ref') ?? '',
369
+ },
370
+ });
371
+ ok(res, pageOf(result));
372
+ return;
373
+ }
374
+ if (action === 'file' && method === 'GET') {
375
+ const project = requiredQuery(query, 'path');
376
+ const filePath = requiredQuery(query, 'filePath');
377
+ const ref = query.get('ref') ?? '';
378
+ const result = await gitlab.request(instanceId, {
379
+ path: `/projects/${projectSegment(project)}/repository/files/${encodeURIComponent(filePath)}/raw`,
380
+ query: { ref },
381
+ text: true,
382
+ });
383
+ const text = String(result.text ?? '');
384
+ const binary = looksBinary(filePath, text);
385
+ const limit = 300000;
386
+ ok(res, {
387
+ filePath,
388
+ ref,
389
+ binary,
390
+ size: Buffer.byteLength(text, 'utf8'),
391
+ truncated: text.length > limit,
392
+ content: binary ? '' : text.slice(0, limit),
393
+ });
394
+ return;
395
+ }
396
+ if (action === 'pipelines' && method === 'GET') {
397
+ const project = requiredQuery(query, 'path');
398
+ const result = await gitlab.request(instanceId, {
399
+ path: `/projects/${projectSegment(project)}/pipelines`,
400
+ query: {
401
+ per_page: 30,
402
+ page: query.get('page') ?? '1',
403
+ status: query.get('status') ?? '',
404
+ ref: query.get('ref') ?? '',
405
+ order_by: 'id',
406
+ sort: 'desc',
407
+ },
408
+ });
409
+ ok(res, pageOf(result));
410
+ return;
411
+ }
412
+ if (action === 'pipeline' && method === 'GET') {
413
+ const project = requiredQuery(query, 'path');
414
+ const pipelineId = requiredQuery(query, 'pipelineId');
415
+ const pipeline = await gitlab.request(instanceId, {
416
+ path: `/projects/${projectSegment(project)}/pipelines/${encodeURIComponent(pipelineId)}`,
417
+ });
418
+ const jobs = await gitlab.request(instanceId, {
419
+ path: `/projects/${projectSegment(project)}/pipelines/${encodeURIComponent(pipelineId)}/jobs`,
420
+ query: { per_page: 100 },
421
+ });
422
+ ok(res, { pipeline: pipeline.data ?? {}, jobs: pageOf(jobs).items });
423
+ return;
424
+ }
425
+ if (action === 'job-trace' && method === 'GET') {
426
+ const project = requiredQuery(query, 'path');
427
+ const jobId = requiredQuery(query, 'jobId');
428
+ const result = await gitlab.request(instanceId, {
429
+ path: `/projects/${projectSegment(project)}/jobs/${encodeURIComponent(jobId)}/trace`,
430
+ text: true,
431
+ timeoutMs: 30000,
432
+ });
433
+ const text = plainTrace(result.text ?? '');
434
+ ok(res, {
435
+ jobId,
436
+ content: text.length > TRACE_TAIL ? text.slice(text.length - TRACE_TAIL) : text,
437
+ truncated: text.length > TRACE_TAIL,
438
+ size: Buffer.byteLength(text, 'utf8'),
439
+ });
440
+ return;
441
+ }
442
+ if (action === 'pipeline/retry' && method === 'POST') {
443
+ const body = await readJson(req);
444
+ const result = await gitlab.request(instanceId, {
445
+ method: 'POST',
446
+ path: `/projects/${projectSegment(required(body, 'path'))}/pipelines/${encodeURIComponent(required(body, 'pipelineId'))}/retry`,
447
+ });
448
+ ok(res, result.data ?? {});
449
+ return;
450
+ }
451
+ if (action === 'pipeline/cancel' && method === 'POST') {
452
+ const body = await readJson(req);
453
+ const result = await gitlab.request(instanceId, {
454
+ method: 'POST',
455
+ path: `/projects/${projectSegment(required(body, 'path'))}/pipelines/${encodeURIComponent(required(body, 'pipelineId'))}/cancel`,
456
+ });
457
+ ok(res, result.data ?? {});
458
+ return;
459
+ }
460
+ if (action === 'job/retry' && method === 'POST') {
461
+ const body = await readJson(req);
462
+ const result = await gitlab.request(instanceId, {
463
+ method: 'POST',
464
+ path: `/projects/${projectSegment(required(body, 'path'))}/jobs/${encodeURIComponent(required(body, 'jobId'))}/retry`,
465
+ });
466
+ ok(res, result.data ?? {});
467
+ return;
468
+ }
469
+ if (action === 'job/cancel' && method === 'POST') {
470
+ const body = await readJson(req);
471
+ const result = await gitlab.request(instanceId, {
472
+ method: 'POST',
473
+ path: `/projects/${projectSegment(required(body, 'path'))}/jobs/${encodeURIComponent(required(body, 'jobId'))}/cancel`,
474
+ });
475
+ ok(res, result.data ?? {});
476
+ return;
477
+ }
478
+ if (action === 'job/play' && method === 'POST') {
479
+ const body = await readJson(req);
480
+ const result = await gitlab.request(instanceId, {
481
+ method: 'POST',
482
+ path: `/projects/${projectSegment(required(body, 'path'))}/jobs/${encodeURIComponent(required(body, 'jobId'))}/play`,
483
+ });
484
+ ok(res, result.data ?? {});
485
+ return;
486
+ }
487
+ if (action === 'merge-requests' && method === 'GET') {
488
+ const project = requiredQuery(query, 'path');
489
+ const result = await gitlab.request(instanceId, {
490
+ path: `/projects/${projectSegment(project)}/merge_requests`,
491
+ query: {
492
+ state: query.get('state') ?? 'opened',
493
+ per_page: 30,
494
+ page: query.get('page') ?? '1',
495
+ order_by: 'updated_at',
496
+ sort: 'desc',
497
+ },
498
+ });
499
+ ok(res, pageOf(result));
500
+ return;
501
+ }
502
+ if (action === 'merge-request' && method === 'GET') {
503
+ const project = requiredQuery(query, 'path');
504
+ const iid = requiredQuery(query, 'iid');
505
+ const result = await gitlab.request(instanceId, {
506
+ path: `/projects/${projectSegment(project)}/merge_requests/${encodeURIComponent(iid)}`,
507
+ });
508
+ ok(res, result.data ?? {});
509
+ return;
510
+ }
511
+ if (action === 'issues' && method === 'GET') {
512
+ const project = requiredQuery(query, 'path');
513
+ const result = await gitlab.request(instanceId, {
514
+ path: `/projects/${projectSegment(project)}/issues`,
515
+ query: {
516
+ state: query.get('state') ?? 'opened',
517
+ per_page: 30,
518
+ page: query.get('page') ?? '1',
519
+ order_by: 'updated_at',
520
+ sort: 'desc',
521
+ },
522
+ });
523
+ ok(res, pageOf(result));
524
+ return;
525
+ }
526
+ if (action === 'issue' && method === 'GET') {
527
+ const project = requiredQuery(query, 'path');
528
+ const iid = requiredQuery(query, 'iid');
529
+ const result = await gitlab.request(instanceId, {
530
+ path: `/projects/${projectSegment(project)}/issues/${encodeURIComponent(iid)}`,
531
+ });
532
+ ok(res, result.data ?? {});
533
+ return;
534
+ }
535
+ throw Object.assign(new Error(`Unknown action "${action}".`), { status: 404, code: 'unknown_action' });
536
+ }
537
+ return async function handle(req, res) {
538
+ try {
539
+ if (!admit(req, res))
540
+ return;
541
+ const url = new URL(req.url ?? '/', 'http://dsh.internal');
542
+ const root = ROUTE_PREFIX.replace(/\/$/, '');
543
+ if (!url.pathname.startsWith(root)) {
544
+ json(res, 404, { ok: false, error: { code: 'not_found', message: 'not found' } });
545
+ return;
546
+ }
547
+ const action = url.pathname.slice(root.length).replace(/^\/+/, '').replace(/\/+$/, '');
548
+ if (action === '') {
549
+ json(res, 404, { ok: false, error: { code: 'unknown_action', message: 'unknown action' } });
550
+ return;
551
+ }
552
+ await dispatch(action, req, res, url);
553
+ }
554
+ catch (error) {
555
+ const failure = error;
556
+ if (failure instanceof GitLabError || failure?.code) {
557
+ fail(res, failure);
558
+ return;
559
+ }
560
+ fail(res, Object.assign(new Error('The request failed.'), {
561
+ status: 500,
562
+ code: 'internal_error',
563
+ detail: String(error?.message ?? error),
564
+ }));
565
+ }
566
+ };
567
+ }