@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,268 @@
1
+ /**
2
+ * A small GitLab REST v4 client over node http/https.
3
+ *
4
+ * Why not the built-in fetch: a self-managed instance is regularly served with
5
+ * a corporate or self-signed certificate, and node's fetch offers no per-call
6
+ * way to pass `ca` or to disable verification. The https module does, and it
7
+ * also lets this plugin keep the token on one origin while following only
8
+ * same-origin redirects.
9
+ */
10
+ import http from 'node:http';
11
+ import https from 'node:https';
12
+ /** The largest JSON response this client accepts. */
13
+ const MAX_BODY = 8 * 1024 * 1024;
14
+ /** The largest plain-text response (a job trace) this client accepts. */
15
+ const MAX_TEXT = 6 * 1024 * 1024;
16
+ /** How many same-origin redirects are followed. */
17
+ const MAX_REDIRECTS = 3;
18
+ /** A failure the routes report as-is. */
19
+ export class GitLabError extends Error {
20
+ code;
21
+ status;
22
+ detail;
23
+ constructor(message, options = {}) {
24
+ super(message);
25
+ this.name = 'GitLabError';
26
+ this.code = options.code ?? 'gitlab_error';
27
+ this.status = options.status ?? 502;
28
+ this.detail = options.detail;
29
+ }
30
+ }
31
+ /** Turn a transport failure into a message that names the likely cause. */
32
+ function transportError(error, instance) {
33
+ const code = String(error?.code ?? '');
34
+ const host = new URL(instance.endpoint).host;
35
+ if (code === 'ECONNREFUSED') {
36
+ return new GitLabError(`Cannot connect to ${host}: the connection was refused.`, {
37
+ code: 'connection_refused',
38
+ status: 502,
39
+ detail: String(error?.message ?? ''),
40
+ });
41
+ }
42
+ if (code === 'ENOTFOUND' || code === 'EAI_AGAIN') {
43
+ return new GitLabError(`Cannot resolve ${host}. Check the instance URL and DNS.`, {
44
+ code: 'dns_error',
45
+ status: 502,
46
+ detail: String(error?.message ?? ''),
47
+ });
48
+ }
49
+ if (code === 'DEPTH_ZERO_SELF_SIGNED_CERT'
50
+ || code === 'SELF_SIGNED_CERT_IN_CHAIN'
51
+ || code === 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'
52
+ || code === 'CERT_HAS_EXPIRED') {
53
+ return new GitLabError(`${host} presented a certificate node does not trust. Add the corporate CA or disable verification for this instance in Settings.`, { code: 'tls_error', status: 502, detail: String(error?.message ?? '') });
54
+ }
55
+ if (code === 'ETIMEDOUT' || /timeout/i.test(String(error?.message ?? ''))) {
56
+ return new GitLabError(`The request to ${host} timed out.`, {
57
+ code: 'timeout',
58
+ status: 504,
59
+ detail: String(error?.message ?? ''),
60
+ });
61
+ }
62
+ return new GitLabError(`Cannot reach ${host}: ${String(error?.message ?? error)}`, {
63
+ code: 'network_error',
64
+ status: 502,
65
+ detail: String(error?.message ?? ''),
66
+ });
67
+ }
68
+ /** Read a GitLab error body into one line. */
69
+ function errorMessage(body, text) {
70
+ if (body && typeof body === 'object') {
71
+ const source = body;
72
+ const message = source.message ?? source.error_description ?? source.error;
73
+ if (typeof message === 'string' && message.trim() !== '')
74
+ return message.trim();
75
+ if (Array.isArray(message))
76
+ return message.map(String).join('; ');
77
+ if (message && typeof message === 'object') {
78
+ return Object.entries(message)
79
+ .map(([key, value]) => `${key}: ${Array.isArray(value) ? value.join(', ') : String(value)}`)
80
+ .join('; ');
81
+ }
82
+ }
83
+ const compact = String(text ?? '').replace(/\s+/g, ' ').trim();
84
+ return compact.length > 0 ? compact.slice(0, 300) : 'GitLab rejected the request.';
85
+ }
86
+ /** Map an HTTP status to a stable error code. */
87
+ function codeForStatus(status) {
88
+ if (status === 401)
89
+ return 'unauthorized';
90
+ if (status === 403)
91
+ return 'forbidden';
92
+ if (status === 404)
93
+ return 'not_found';
94
+ if (status === 409)
95
+ return 'conflict';
96
+ if (status === 429)
97
+ return 'rate_limited';
98
+ if (status >= 500)
99
+ return 'gitlab_server_error';
100
+ return 'request_failed';
101
+ }
102
+ /** Create the GitLab client. */
103
+ export function createGitLab({ store, logger: _logger }) {
104
+ async function request(instanceId, options) {
105
+ const instance = store.get(instanceId);
106
+ if (!instance)
107
+ throw new GitLabError('Unknown instance.', { code: 'unknown_instance', status: 404 });
108
+ const token = options.token ? { token: options.token } : await store.readToken(instanceId);
109
+ if (!token?.token) {
110
+ throw new GitLabError('No personal access token is stored for this instance.', {
111
+ code: 'no_token',
112
+ status: 401,
113
+ });
114
+ }
115
+ const url = new URL(`${instance.endpoint}/api/v4${options.path}`);
116
+ for (const [key, value] of Object.entries(options.query ?? {})) {
117
+ if (value === undefined || value === null || value === '')
118
+ continue;
119
+ url.searchParams.set(key, String(value));
120
+ }
121
+ const headers = {
122
+ 'PRIVATE-TOKEN': token.token,
123
+ Accept: options.text ? 'text/plain, */*' : 'application/json',
124
+ 'User-Agent': 'dsh-gitlab-workbench/0.2',
125
+ };
126
+ let payload;
127
+ if (options.body !== undefined) {
128
+ payload = Buffer.from(JSON.stringify(options.body), 'utf8');
129
+ headers['Content-Type'] = 'application/json';
130
+ headers['Content-Length'] = String(payload.length);
131
+ }
132
+ const timeoutMs = options.timeoutMs ?? 25000;
133
+ const maxBody = options.maxBody ?? (options.text ? MAX_TEXT : MAX_BODY);
134
+ const send = (target, redirects) => new Promise((resolve, reject) => {
135
+ const transport = target.protocol === 'https:' ? https : http;
136
+ const requestOptions = {
137
+ method: options.method ?? 'GET',
138
+ headers,
139
+ timeout: timeoutMs,
140
+ };
141
+ if (target.protocol === 'https:') {
142
+ requestOptions.rejectUnauthorized = instance.verifyTls !== false;
143
+ if (instance.caPem)
144
+ requestOptions.ca = instance.caPem;
145
+ }
146
+ const req = transport.request(target, requestOptions, (res) => {
147
+ const status = res.statusCode ?? 0;
148
+ const location = res.headers.location;
149
+ if (status >= 300 && status < 400 && location && redirects < MAX_REDIRECTS) {
150
+ res.resume();
151
+ let next;
152
+ try {
153
+ next = new URL(location, target);
154
+ }
155
+ catch {
156
+ reject(new GitLabError('GitLab returned an invalid redirect.', { code: 'bad_redirect', status: 502 }));
157
+ return;
158
+ }
159
+ if (next.origin !== new URL(instance.endpoint).origin) {
160
+ reject(new GitLabError(`GitLab redirected to another origin (${next.origin}); refusing to forward the token.`, { code: 'cross_origin_redirect', status: 502 }));
161
+ return;
162
+ }
163
+ resolve(send(next, redirects + 1));
164
+ return;
165
+ }
166
+ const chunks = [];
167
+ let size = 0;
168
+ res.on('data', (chunk) => {
169
+ size += chunk.length;
170
+ if (size > maxBody) {
171
+ res.destroy();
172
+ reject(new GitLabError('The response is too large to display.', { code: 'response_too_large', status: 502 }));
173
+ return;
174
+ }
175
+ chunks.push(chunk);
176
+ });
177
+ res.on('end', () => {
178
+ const buffer = Buffer.concat(chunks);
179
+ const text = buffer.toString('utf8');
180
+ const contentType = String(res.headers['content-type'] ?? '');
181
+ const looksJson = contentType.includes('json') || /^\s*[[{]/.test(text);
182
+ let data;
183
+ if (looksJson && (!options.text || status >= 400)) {
184
+ try {
185
+ data = text.trim() === '' ? null : JSON.parse(text);
186
+ }
187
+ catch {
188
+ data = undefined;
189
+ }
190
+ }
191
+ if (status >= 200 && status < 300) {
192
+ resolve({ status, headers: res.headers, data, text });
193
+ return;
194
+ }
195
+ resolve({
196
+ status,
197
+ headers: res.headers,
198
+ data,
199
+ text,
200
+ error: new GitLabError(errorMessage(data, text), {
201
+ code: codeForStatus(status),
202
+ status,
203
+ detail: typeof res.headers['retry-after'] === 'string' ? `Retry after ${res.headers['retry-after']}s` : undefined,
204
+ }),
205
+ });
206
+ });
207
+ res.on('error', (error) => reject(transportError(error, instance)));
208
+ });
209
+ req.on('timeout', () => {
210
+ req.destroy(Object.assign(new Error('timeout'), { code: 'ETIMEDOUT' }));
211
+ });
212
+ req.on('error', (error) => reject(transportError(error, instance)));
213
+ if (payload)
214
+ req.write(payload);
215
+ req.end();
216
+ });
217
+ let result;
218
+ try {
219
+ result = await send(url, 0);
220
+ }
221
+ catch (error) {
222
+ if (error instanceof GitLabError)
223
+ throw error;
224
+ throw transportError(error, instance);
225
+ }
226
+ if (result.error)
227
+ throw result.error;
228
+ return result;
229
+ }
230
+ async function currentUser(instanceId, token) {
231
+ const result = await request(instanceId, { path: '/user', ...(token ? { token } : {}) });
232
+ return result.data ?? {};
233
+ }
234
+ async function version(instanceId) {
235
+ try {
236
+ const result = await request(instanceId, { path: '/version', timeoutMs: 10000 });
237
+ if (result.data && typeof result.data === 'object') {
238
+ const value = result.data.version ?? result.data;
239
+ return typeof value === 'string' ? value : '';
240
+ }
241
+ }
242
+ catch {
243
+ // A version the proxy does not expose does not fail the connection.
244
+ }
245
+ return '';
246
+ }
247
+ return { request, currentUser, version };
248
+ }
249
+ /** Turn a paginated response into one object the client understands. */
250
+ export function pageOf(result) {
251
+ const header = (name) => {
252
+ const value = result.headers?.[name];
253
+ if (Array.isArray(value))
254
+ return value[0];
255
+ return typeof value === 'string' ? value : undefined;
256
+ };
257
+ const number = (name) => {
258
+ const raw = header(name);
259
+ const parsed = raw === undefined ? NaN : Number.parseInt(raw, 10);
260
+ return Number.isFinite(parsed) ? parsed : null;
261
+ };
262
+ return {
263
+ items: Array.isArray(result.data) ? result.data : [],
264
+ total: number('x-total'),
265
+ page: number('x-page') ?? 1,
266
+ nextPage: number('x-next-page'),
267
+ };
268
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * dsh-gitlab-workbench — the host half.
3
+ *
4
+ * It owns the instance list, the personal access tokens (through the host
5
+ * credential service) and every GitLab request. The browser half is a left
6
+ * sidebar entry and the global panel it opens; it reaches this half through the
7
+ * same-origin routes registered below and never sees a token.
8
+ *
9
+ * Build: `npm run build` (tsc for this half, esbuild for the client).
10
+ */
11
+ import { createGitLab } from './gitlab.js';
12
+ import { createRoutes, ROUTE_PREFIX } from './routes.js';
13
+ import { createInstanceStore } from './store.js';
14
+ /** The plugin version reported by the routes and the log line. */
15
+ export const VERSION = '0.2.1';
16
+ /** The route table needs the web server. */
17
+ export const inject = ['webServer'];
18
+ /**
19
+ * Install the host half.
20
+ *
21
+ * @param ctx The plugin context.
22
+ * @param config The row configuration (unused; instances live in the panel).
23
+ */
24
+ export function apply(ctx, config = {}) {
25
+ const logger = ctx.logger;
26
+ const store = createInstanceStore({ ctx, logger });
27
+ const gitlab = createGitLab({ store, logger });
28
+ const handle = createRoutes({ ctx, store, gitlab, version: VERSION });
29
+ const register = () => ctx.webServer.register({
30
+ kind: 'prefix',
31
+ path: ROUTE_PREFIX.replace(/\/$/, ''),
32
+ handler: (req, res) => {
33
+ Promise.resolve(handle(req, res)).catch((error) => {
34
+ logger?.warn?.('gitlab-workbench: a route failed', { error: String(error?.message ?? error) });
35
+ if (!res.headersSent) {
36
+ res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
37
+ res.end(JSON.stringify({ ok: false, error: { code: 'internal_error', message: 'The request failed.' } }));
38
+ }
39
+ });
40
+ },
41
+ });
42
+ if (typeof ctx.effect === 'function') {
43
+ ctx.effect(register, 'gitlab-workbench: api routes');
44
+ }
45
+ else {
46
+ register();
47
+ }
48
+ logger?.info?.('gitlab-workbench: ready', {
49
+ version: VERSION,
50
+ instances: store.list().length,
51
+ credentials: store.hasCredentials() ? 'ready' : 'missing',
52
+ config: Object.keys(config ?? {}).length,
53
+ });
54
+ }