@orion-belt/sdk 0.0.0-stage → 1.0.0

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.
package/dist/client.js ADDED
@@ -0,0 +1,646 @@
1
+ // Client for the Orion Belt HTTP API. The Go SDK in pkg/sdk is the reference
2
+ // for auth and request behaviour; this client sends the same requests over the
3
+ // platform fetch, so it runs in Node 20+, Deno, Bun and browsers.
4
+ const DEFAULT_TIMEOUT_MS = 30_000;
5
+ /** A non-2xx response. `message` is the server's `error` field when it sent one. */
6
+ export class ApiError extends Error {
7
+ statusCode;
8
+ body;
9
+ serverMessage;
10
+ constructor(statusCode, serverMessage, body) {
11
+ const detail = serverMessage || body;
12
+ super(detail ? `api error (${statusCode}): ${detail}` : `api error (${statusCode})`);
13
+ this.name = 'ApiError';
14
+ this.statusCode = statusCode;
15
+ this.serverMessage = serverMessage;
16
+ this.body = body;
17
+ }
18
+ }
19
+ /** Escapes one path segment so an ID can never add or climb path levels. */
20
+ function seg(value) {
21
+ return encodeURIComponent(value);
22
+ }
23
+ /** Encodes the set parameters; empty, zero and false mean "use the server default". */
24
+ function query(params) {
25
+ const search = new URLSearchParams();
26
+ for (const [key, value] of Object.entries(params)) {
27
+ if (value === undefined || value === null || value === '' || value === false) {
28
+ continue;
29
+ }
30
+ if (typeof value === 'number' && !(value > 0)) {
31
+ continue;
32
+ }
33
+ search.set(key, String(value));
34
+ }
35
+ const encoded = search.toString();
36
+ return encoded ? `?${encoded}` : '';
37
+ }
38
+ function trimToUndefined(value) {
39
+ const trimmed = value?.trim();
40
+ return trimmed ? trimmed : undefined;
41
+ }
42
+ function trimTrailingSlashes(value) {
43
+ // A loop rather than /\/+$/: that regex backtracks quadratically on a long
44
+ // run of slashes that is not at the end.
45
+ let end = value.length;
46
+ while (end > 0 && value[end - 1] === '/') {
47
+ end--;
48
+ }
49
+ return value.slice(0, end);
50
+ }
51
+ function errorMessage(body) {
52
+ try {
53
+ const parsed = JSON.parse(body);
54
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
55
+ for (const key of ['error', 'message']) {
56
+ const value = parsed[key];
57
+ if (typeof value === 'string' && value) {
58
+ return value;
59
+ }
60
+ }
61
+ }
62
+ }
63
+ catch {
64
+ // Not JSON: the raw text is the message.
65
+ }
66
+ return body.trim();
67
+ }
68
+ function base64(bytes) {
69
+ let binary = '';
70
+ for (const byte of bytes) {
71
+ binary += String.fromCharCode(byte);
72
+ }
73
+ return btoa(binary);
74
+ }
75
+ /**
76
+ * Client for one Orion Belt server. Auth precedence matches the server:
77
+ * X-API-Key wins over X-Session-Token; a bearer token is sent alongside
78
+ * either. The login helpers store the credential they obtain on the client.
79
+ */
80
+ export class OrionBeltClient {
81
+ baseUrl;
82
+ timeoutMs;
83
+ headers;
84
+ fetchImpl;
85
+ apiKey;
86
+ sessionToken;
87
+ bearerToken;
88
+ constructor(options) {
89
+ const baseUrl = trimTrailingSlashes(options.baseUrl.trim());
90
+ if (!baseUrl) {
91
+ throw new Error('baseUrl is required');
92
+ }
93
+ this.baseUrl = baseUrl;
94
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
95
+ this.headers = { ...options.headers };
96
+ const userAgent = trimToUndefined(options.userAgent);
97
+ if (userAgent) {
98
+ this.headers['User-Agent'] = userAgent;
99
+ }
100
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
101
+ this.apiKey = trimToUndefined(options.apiKey);
102
+ this.sessionToken = trimToUndefined(options.sessionToken);
103
+ this.bearerToken = trimToUndefined(options.bearerToken);
104
+ }
105
+ setApiKey(apiKey) {
106
+ this.apiKey = trimToUndefined(apiKey);
107
+ }
108
+ setSessionToken(sessionToken) {
109
+ this.sessionToken = trimToUndefined(sessionToken);
110
+ }
111
+ setBearerToken(bearerToken) {
112
+ this.bearerToken = trimToUndefined(bearerToken);
113
+ }
114
+ /** Current credentials, e.g. to persist a session obtained by a login helper. */
115
+ get credentials() {
116
+ const out = {};
117
+ if (this.apiKey)
118
+ out.apiKey = this.apiKey;
119
+ if (this.sessionToken)
120
+ out.sessionToken = this.sessionToken;
121
+ if (this.bearerToken)
122
+ out.bearerToken = this.bearerToken;
123
+ return out;
124
+ }
125
+ // Transport
126
+ /** Absolute URL for an API path; paths without /api/ are taken as /api/v1-relative. */
127
+ url(path) {
128
+ if (/^https?:\/\//i.test(path)) {
129
+ return path;
130
+ }
131
+ const normalized = path.startsWith('/') ? path : `/${path}`;
132
+ return `${this.baseUrl}${normalized.startsWith('/api/') ? '' : '/api/v1'}${normalized}`;
133
+ }
134
+ /** The credential headers this client sends, e.g. for opening the WebSocket endpoints. */
135
+ authHeaders() {
136
+ const headers = {};
137
+ if (this.apiKey) {
138
+ headers['X-API-Key'] = this.apiKey;
139
+ }
140
+ else if (this.sessionToken) {
141
+ headers['X-Session-Token'] = this.sessionToken;
142
+ }
143
+ if (this.bearerToken) {
144
+ headers['Authorization'] = `Bearer ${this.bearerToken}`;
145
+ }
146
+ return headers;
147
+ }
148
+ async send(method, path, body, contentType, auth) {
149
+ const headers = { ...this.headers };
150
+ if (contentType) {
151
+ headers['Content-Type'] = contentType;
152
+ }
153
+ if (auth) {
154
+ Object.assign(headers, this.authHeaders());
155
+ }
156
+ const init = { method, headers };
157
+ if (body !== undefined) {
158
+ init.body = body;
159
+ }
160
+ if (this.timeoutMs > 0) {
161
+ init.signal = AbortSignal.timeout(this.timeoutMs);
162
+ }
163
+ const response = await this.fetchImpl(this.url(path), init);
164
+ if (!response.ok) {
165
+ const text = await response.text();
166
+ throw new ApiError(response.status, errorMessage(text), text.trim());
167
+ }
168
+ return response;
169
+ }
170
+ /**
171
+ * Sends a JSON request and returns the decoded response (undefined for an
172
+ * empty body). Use it for endpoints this client has no method for yet.
173
+ */
174
+ async request(method, path, body, options = {}) {
175
+ const payload = body === undefined ? undefined : JSON.stringify(body);
176
+ const response = await this.send(method, path, payload, payload === undefined ? undefined : 'application/json', options.auth ?? true);
177
+ const text = await response.text();
178
+ return (text ? JSON.parse(text) : undefined);
179
+ }
180
+ /** Sends a request without a body and returns the raw response bytes. */
181
+ async requestBytes(method, path, options = {}) {
182
+ const response = await this.send(method, path, undefined, undefined, options.auth ?? true);
183
+ return new Uint8Array(await response.arrayBuffer());
184
+ }
185
+ async list(path, key) {
186
+ let result = await this.request('GET', path);
187
+ if (key !== undefined) {
188
+ result = result && typeof result === 'object' && !Array.isArray(result) ? result[key] : undefined;
189
+ }
190
+ return Array.isArray(result) ? result : [];
191
+ }
192
+ storeSession(result) {
193
+ if (result?.session_token) {
194
+ this.sessionToken = result.session_token;
195
+ }
196
+ if (result?.access_token) {
197
+ this.bearerToken = result.access_token;
198
+ }
199
+ }
200
+ // Public: registration and login
201
+ /** Addresses the gateway advertises to clients and agents. Needs no credentials. */
202
+ getGatewayInfo() {
203
+ return this.request('GET', '/gateway-info', undefined, { auth: false });
204
+ }
205
+ /** The server's build version. Needs no credentials. */
206
+ getVersion() {
207
+ return this.request('GET', '/version', undefined, { auth: false });
208
+ }
209
+ /** The server's OpenAPI 3 document, as YAML text. */
210
+ async getOpenApiSpec() {
211
+ return new TextDecoder().decode(await this.requestBytes('GET', '/openapi.yaml', { auth: false }));
212
+ }
213
+ /** Where to find the OpenAPI document (/openapi.json answers with pointers, not the spec). */
214
+ getOpenApiIndex() {
215
+ return this.request('GET', '/openapi.json', undefined, { auth: false });
216
+ }
217
+ /** Registers an agent. The server requires an admin or operator, so credentials are sent. */
218
+ registerAgent(req) {
219
+ return this.request('POST', '/public/register/agent', req);
220
+ }
221
+ /** Registers a user. `is_admin` is honoured only for an admin caller or the first account. */
222
+ registerClient(req) {
223
+ return this.request('POST', '/public/register/client', req);
224
+ }
225
+ /** A one-time challenge for the SSH-key logins. */
226
+ async issueChallenge(username) {
227
+ const result = await this.request('POST', '/public/auth/challenge', { username }, { auth: false });
228
+ if (!result?.challenge) {
229
+ throw new Error('no challenge returned');
230
+ }
231
+ return result.challenge;
232
+ }
233
+ async signedLogin(path, username, signer, totpCode) {
234
+ const challenge = await this.issueChallenge(username);
235
+ const { format, signature } = await signer.sign(new TextEncoder().encode(challenge));
236
+ const body = {
237
+ username,
238
+ public_key: signer.publicKey,
239
+ challenge,
240
+ signature_format: format,
241
+ signature: base64(signature),
242
+ };
243
+ const totp = totpCode?.trim();
244
+ if (totp) {
245
+ body['totp_code'] = totp;
246
+ }
247
+ return (await this.request('POST', path, body, { auth: false })) ?? {};
248
+ }
249
+ /** SSH challenge login that returns a session token (POST /public/login). */
250
+ async loginWithSshSession(username, signer, totpCode) {
251
+ const result = await this.signedLogin('/public/login', username, signer, totpCode);
252
+ if (!result.session_token) {
253
+ throw new Error('no session token returned');
254
+ }
255
+ this.storeSession(result);
256
+ return result;
257
+ }
258
+ /** SSH challenge login that returns an API key (POST /public/login/key). */
259
+ async loginWithSshKey(username, signer, totpCode) {
260
+ const result = await this.signedLogin('/public/login/key', username, signer, totpCode);
261
+ if (!result.api_key) {
262
+ throw new Error('no API key returned');
263
+ }
264
+ this.apiKey = result.api_key;
265
+ return result;
266
+ }
267
+ /** SSH challenge login that returns a JWT bearer token (POST /public/login/token). */
268
+ async loginWithSshJwt(username, signer, totpCode) {
269
+ const result = await this.signedLogin('/public/login/token', username, signer, totpCode);
270
+ if (!result.access_token) {
271
+ throw new Error('no access token returned');
272
+ }
273
+ this.bearerToken = result.access_token;
274
+ return result;
275
+ }
276
+ async loginWithPassword(username, password, totpCode = '') {
277
+ const result = (await this.request('POST', '/public/login/password', { username, password, totp_code: totpCode }, { auth: false })) ?? {};
278
+ if (!result.session_token) {
279
+ throw new Error('no session token returned');
280
+ }
281
+ this.storeSession(result);
282
+ return result;
283
+ }
284
+ async redeemBrowserBootstrap(code) {
285
+ const result = (await this.request('POST', '/public/auth/browser-bootstrap/redeem', { code }, { auth: false })) ?? {};
286
+ this.storeSession(result);
287
+ return result;
288
+ }
289
+ webauthnLoginBegin(username) {
290
+ return this.request('POST', '/public/webauthn/login/begin', { username }, { auth: false });
291
+ }
292
+ async webauthnLoginFinish(username, response) {
293
+ const result = (await this.request('POST', '/public/webauthn/login/finish', { username, response }, { auth: false })) ?? {};
294
+ this.storeSession(result);
295
+ return result;
296
+ }
297
+ /** Calls a plugin's inbound webhook. The plugin authenticates the caller itself. */
298
+ pluginWebhook(plugin, path, method = 'POST', body) {
299
+ const sub = path.replace(/^\/+/, '').split('/').map(seg).join('/');
300
+ return this.request(method, `/public/plugins/${seg(plugin)}/${sub}`, body, { auth: false });
301
+ }
302
+ // Current user
303
+ /**
304
+ * Ends the HTTP session and drops the session and bearer tokens from this
305
+ * client. The server does not revoke a JWT at logout: one issued alongside
306
+ * the session stays valid until it expires.
307
+ */
308
+ async logout() {
309
+ await this.request('POST', '/logout');
310
+ this.sessionToken = undefined;
311
+ this.bearerToken = undefined;
312
+ }
313
+ getCurrentUser() {
314
+ return this.request('GET', '/auth/me');
315
+ }
316
+ /** A one-time code that opens a browser session as this user. */
317
+ requestBrowserBootstrap() {
318
+ return this.request('POST', '/auth/browser-bootstrap');
319
+ }
320
+ async setPassword(password, totpCode) {
321
+ await this.request('POST', '/auth/password', { password, totp_code: totpCode });
322
+ }
323
+ async clearPassword(totpCode) {
324
+ await this.request('DELETE', '/auth/password', { totp_code: totpCode });
325
+ }
326
+ mfaEnroll() {
327
+ return this.request('POST', '/mfa/enroll', {});
328
+ }
329
+ async mfaConfirm(code) {
330
+ await this.request('POST', '/mfa/confirm', { code });
331
+ }
332
+ async mfaDisable(code) {
333
+ await this.request('POST', '/mfa/disable', { code });
334
+ }
335
+ mfaStatus() {
336
+ return this.request('GET', '/mfa/status');
337
+ }
338
+ webauthnRegisterBegin() {
339
+ return this.request('POST', '/webauthn/register/begin', {});
340
+ }
341
+ /** Completes registration and returns the new credential's ID. */
342
+ async webauthnRegisterFinish(response) {
343
+ const result = await this.request('POST', '/webauthn/register/finish', response);
344
+ return result?.id ?? '';
345
+ }
346
+ webauthnCredentials() {
347
+ return this.list('/webauthn/credentials');
348
+ }
349
+ async webauthnDeleteCredential(credentialId) {
350
+ await this.request('DELETE', `/webauthn/credentials/${seg(credentialId)}`);
351
+ }
352
+ listSshKeys() {
353
+ return this.list('/ssh-keys');
354
+ }
355
+ addSshKey(name, publicKey) {
356
+ return this.request('POST', '/ssh-keys', { name, public_key: publicKey });
357
+ }
358
+ async deleteSshKey(keyId) {
359
+ await this.request('DELETE', `/ssh-keys/${seg(keyId)}`);
360
+ }
361
+ /** Creates a key; the raw key is in `api_key` and is returned only this once. */
362
+ createApiKey(req) {
363
+ return this.request('POST', '/api-keys', req);
364
+ }
365
+ listApiKeys() {
366
+ return this.list('/api-keys', 'api_keys');
367
+ }
368
+ async revokeApiKey(keyId) {
369
+ await this.request('POST', `/api-keys/${seg(keyId)}/revoke`);
370
+ }
371
+ async deleteApiKey(keyId) {
372
+ await this.request('DELETE', `/api-keys/${seg(keyId)}`);
373
+ }
374
+ // Notifications
375
+ listNotifications(limit = 0) {
376
+ return this.list(`/notifications${query({ limit })}`);
377
+ }
378
+ async unreadNotificationCount() {
379
+ const result = await this.request('GET', '/notifications/unread-count');
380
+ return result?.unread ?? 0;
381
+ }
382
+ async markNotificationRead(notificationId) {
383
+ await this.request('POST', `/notifications/${seg(notificationId)}/read`);
384
+ }
385
+ async markAllNotificationsRead() {
386
+ await this.request('POST', '/notifications/read-all');
387
+ }
388
+ /** The caller's preferences and the admin bounds they were resolved within. */
389
+ getNotificationPrefs() {
390
+ return this.request('GET', '/notifications/prefs');
391
+ }
392
+ /** Stores preferences. Values outside the admin policy are clamped; `adjusted` says so. */
393
+ putNotificationPrefs(prefs) {
394
+ return this.request('PUT', '/notifications/prefs', prefs);
395
+ }
396
+ // Users, machines, permissions
397
+ listUsers() {
398
+ return this.list('/users');
399
+ }
400
+ getUser(userId) {
401
+ return this.request('GET', `/users/${seg(userId)}`);
402
+ }
403
+ createUser(req) {
404
+ return this.request('POST', '/admin/users', req);
405
+ }
406
+ updateUser(userId, req) {
407
+ return this.request('PUT', `/admin/users/${seg(userId)}`, req);
408
+ }
409
+ async deleteUser(userId) {
410
+ await this.request('DELETE', `/admin/users/${seg(userId)}`);
411
+ }
412
+ listMachines() {
413
+ return this.list('/machines');
414
+ }
415
+ getMachine(machineId) {
416
+ return this.request('GET', `/machines/${seg(machineId)}`);
417
+ }
418
+ /** Resolves a machine by name from listMachines; throws when absent. */
419
+ async getMachineByName(name) {
420
+ const machine = (await this.listMachines()).find((m) => m.name === name);
421
+ if (!machine) {
422
+ throw new Error(`machine ${JSON.stringify(name)} not found`);
423
+ }
424
+ return machine;
425
+ }
426
+ createMachine(req) {
427
+ return this.request('POST', '/admin/machines', req);
428
+ }
429
+ updateMachine(machineId, req) {
430
+ return this.request('PUT', `/admin/machines/${seg(machineId)}`, req);
431
+ }
432
+ /** Deletes a machine, or with `archive` deactivates it and keeps its history. */
433
+ async deleteMachine(machineId, archive = false) {
434
+ await this.request('DELETE', `/admin/machines/${seg(machineId)}${query({ archive })}`);
435
+ }
436
+ /** Reconciles a cluster's RoleBindings with its grants; `dryRun` only reports drift. */
437
+ kubeReconcile(machineId, dryRun = false) {
438
+ return this.request(dryRun ? 'GET' : 'POST', `/admin/machines/${seg(machineId)}/kubernetes/reconcile`);
439
+ }
440
+ getUserPermissions(userId) {
441
+ return this.list(`/permissions/user/${seg(userId)}`);
442
+ }
443
+ getMachinePermissions(machineId) {
444
+ return this.list(`/permissions/machine/${seg(machineId)}`);
445
+ }
446
+ listAllPermissions(limit = 0) {
447
+ return this.list(`/admin/permissions${query({ limit })}`);
448
+ }
449
+ grantPermission(req) {
450
+ return this.request('POST', '/admin/permissions', req);
451
+ }
452
+ updatePermission(permissionId, req) {
453
+ return this.request('PATCH', `/admin/permissions/${seg(permissionId)}`, req);
454
+ }
455
+ async revokePermission(permissionId) {
456
+ await this.request('DELETE', `/admin/permissions/${seg(permissionId)}`);
457
+ }
458
+ /** Grants one access type on every user x machine pair. */
459
+ bulkGrantPermissions(req) {
460
+ return this.request('POST', '/admin/permissions/bulk', req);
461
+ }
462
+ bulkRevokePermissions(ids) {
463
+ return this.request('POST', '/admin/permissions/bulk-revoke', { ids });
464
+ }
465
+ /** Resolved access for one user or one machine; set exactly one. */
466
+ effectivePermissions(filter) {
467
+ return this.list(`/admin/permissions/effective${query({ user_id: filter.userId, machine_id: filter.machineId })}`);
468
+ }
469
+ /** What the caller holds or could request. `scope` is "related" (default) or "all". */
470
+ listCapabilities(scope = '', userId = '') {
471
+ return this.request('GET', `/capabilities${query({ scope, user_id: userId })}`);
472
+ }
473
+ /** Whether a user (default: the caller) may reach a machine as `remoteUser`, and why. */
474
+ explainAccess(machine, remoteUser, accessType = '', user = '') {
475
+ return this.request('GET', `/access/explain${query({ machine, remote_user: remoteUser, access_type: accessType, user })}`);
476
+ }
477
+ // Access requests
478
+ listAccessRequests(status = '') {
479
+ return this.list(`/access-requests${query({ status })}`);
480
+ }
481
+ createAccessRequest(req) {
482
+ return this.request('POST', '/access-requests', req);
483
+ }
484
+ getAccessRequest(requestId) {
485
+ return this.request('GET', `/access-requests/${seg(requestId)}`);
486
+ }
487
+ listPendingAccessRequests() {
488
+ return this.list('/admin/access-requests/pending');
489
+ }
490
+ async approveAccessRequest(requestId, reviewerId = '') {
491
+ await this.request('POST', `/admin/access-requests/${seg(requestId)}/approve`, { reviewer_id: reviewerId });
492
+ }
493
+ async rejectAccessRequest(requestId, reviewerId = '') {
494
+ await this.request('POST', `/admin/access-requests/${seg(requestId)}/reject`, { reviewer_id: reviewerId });
495
+ }
496
+ getRiskPolicy() {
497
+ return this.request('GET', '/admin/risk-policy');
498
+ }
499
+ /** Replaces the risk policy outright; send the whole document. */
500
+ putRiskPolicy(policy) {
501
+ return this.request('PUT', '/admin/risk-policy', policy);
502
+ }
503
+ // Sessions, audit, reporting
504
+ listSessions(status = '') {
505
+ return this.list(`/sessions${query({ status })}`);
506
+ }
507
+ listActiveSessions() {
508
+ return this.list('/sessions/active');
509
+ }
510
+ getSession(sessionId) {
511
+ return this.request('GET', `/sessions/${seg(sessionId)}`);
512
+ }
513
+ /** The raw session recording. */
514
+ getSessionContent(sessionId) {
515
+ return this.requestBytes('GET', `/sessions/${seg(sessionId)}/content`);
516
+ }
517
+ listAuditLogs(limit = 0) {
518
+ return this.list(`/audit-logs${query({ limit })}`);
519
+ }
520
+ /** Report bytes. `params` carries report options such as from/to or as_of. */
521
+ exportReport(reportName, format = '', params = {}) {
522
+ return this.requestBytes('GET', `/reports/${seg(reportName)}/export${query({ ...params, format })}`);
523
+ }
524
+ getUsageDashboard(windowHours = 0, top = 0) {
525
+ return this.request('GET', `/dashboard/usage${query({ window_hours: windowHours, top })}`);
526
+ }
527
+ listAnomalies(limit = 0, userId = '') {
528
+ return this.list(`/anomalies${query({ limit, user_id: userId })}`);
529
+ }
530
+ getSetupStatus() {
531
+ return this.request('GET', '/setup/status');
532
+ }
533
+ // Notification policy and templates (admin)
534
+ getNotificationPolicy() {
535
+ return this.request('GET', '/admin/notifications/policy');
536
+ }
537
+ /** Replaces the policy outright; send the whole document. */
538
+ putNotificationPolicy(policy) {
539
+ return this.request('PUT', '/admin/notifications/policy', policy);
540
+ }
541
+ listNotificationTemplates() {
542
+ return this.list('/admin/notifications/templates', 'templates');
543
+ }
544
+ putNotificationTemplate(event, template) {
545
+ // The server rejects a body naming a different event than the path.
546
+ return this.request('PUT', `/admin/notifications/templates/${seg(event)}`, { ...template, event_type: event });
547
+ }
548
+ /** Drops the override, returning the event to its built-in copy. */
549
+ async deleteNotificationTemplate(event) {
550
+ await this.request('DELETE', `/admin/notifications/templates/${seg(event)}`);
551
+ }
552
+ // Plugins and agents (admin)
553
+ listPlugins() {
554
+ return this.list('/admin/plugins', 'plugins');
555
+ }
556
+ /** Stores config. `configure_error` reports a config the plugin rejected after saving. */
557
+ updatePluginConfig(name, enabled, config) {
558
+ return this.request('PUT', `/admin/plugins/${seg(name)}/config`, { enabled, config });
559
+ }
560
+ async enablePlugin(name) {
561
+ const result = await this.request('POST', `/admin/plugins/${seg(name)}/enable`);
562
+ return result?.plugin ?? {};
563
+ }
564
+ async disablePlugin(name) {
565
+ const result = await this.request('POST', `/admin/plugins/${seg(name)}/disable`);
566
+ return result?.plugin ?? {};
567
+ }
568
+ /** Machine IDs with a live agent connection. */
569
+ listConnectedAgents() {
570
+ return this.list('/admin/agents/connected', 'agents');
571
+ }
572
+ /** Sends a control command (reload, drain, undrain, update) and returns its output. */
573
+ async sendAgentCommand(machineId, command) {
574
+ const result = await this.request('POST', `/admin/agents/${seg(machineId)}/command`, { command });
575
+ return result?.output ?? '';
576
+ }
577
+ async disconnectAgent(machineId) {
578
+ await this.request('POST', `/admin/agents/${seg(machineId)}/disconnect`);
579
+ }
580
+ generateAgentInstallScript(req) {
581
+ return this.request('POST', '/admin/agents/install-script', req);
582
+ }
583
+ // SSH certificate authority
584
+ getTrustedCa() {
585
+ return this.request('GET', '/ssh-cert/ca');
586
+ }
587
+ issueUserCert(publicKey, ttlHours = 0) {
588
+ return this.request('POST', '/ssh-cert', { public_key: publicKey, ttl_hours: ttlHours });
589
+ }
590
+ exportCa() {
591
+ return this.request('GET', '/admin/ca/export');
592
+ }
593
+ listSshCertificates(certType = '') {
594
+ return this.list(`/admin/ssh-certificates${query({ cert_type: certType })}`, 'certificates');
595
+ }
596
+ async revokeSshCertificate(serial, reason = '') {
597
+ await this.request('POST', `/admin/ssh-certificates/${seg(serial)}/revoke`, { reason });
598
+ }
599
+ // Remote files
600
+ /** Lists a directory; the server defaults to "/" as root. */
601
+ async listFiles(machine, path = '', remoteUser = '') {
602
+ const result = (await this.request('GET', `/files/list${query({ machine, path, user: remoteUser })}`)) ?? {};
603
+ result.entries ??= [];
604
+ return result;
605
+ }
606
+ downloadFile(machine, path, remoteUser = '') {
607
+ return this.requestBytes('GET', `/files/download${query({ machine, path, user: remoteUser })}`);
608
+ }
609
+ async uploadFile(machine, path, fileName, content, remoteUser = '') {
610
+ const form = new FormData();
611
+ form.set('machine', machine);
612
+ form.set('path', path);
613
+ if (remoteUser) {
614
+ form.set('user', remoteUser);
615
+ }
616
+ const blob = content instanceof Blob ? content : new Blob([content]);
617
+ form.set('file', blob, fileName);
618
+ // fetch sets the multipart Content-Type with its boundary.
619
+ const response = await this.send('POST', '/files/upload', form, undefined, true);
620
+ const text = await response.text();
621
+ return (text ? JSON.parse(text) : {});
622
+ }
623
+ async makeDir(machine, path, remoteUser = '') {
624
+ const body = { machine, path };
625
+ if (remoteUser) {
626
+ body['user'] = remoteUser;
627
+ }
628
+ await this.request('POST', '/files/mkdir', body);
629
+ }
630
+ async deleteFile(machine, path, remoteUser = '') {
631
+ await this.request('DELETE', `/files${query({ machine, path, user: remoteUser })}`);
632
+ }
633
+ // WebSocket endpoints. These return the ws:// or wss:// URL; open it with a
634
+ // WebSocket client that can send authHeaders() on the upgrade request.
635
+ wsUrl(path) {
636
+ return this.url(path).replace(/^http/i, 'ws');
637
+ }
638
+ /** URL of an interactive web terminal on `machine`. */
639
+ terminalWsUrl(machine, remoteUser = '') {
640
+ return this.wsUrl(`/terminal/ws${query({ machine, user: remoteUser })}`);
641
+ }
642
+ /** URL that streams a live session's output to a watcher. */
643
+ sessionWatchWsUrl(sessionId) {
644
+ return this.wsUrl(`/sessions/${seg(sessionId)}/watch`);
645
+ }
646
+ }
@@ -0,0 +1,3 @@
1
+ export { ApiError, OrionBeltClient } from './client.js';
2
+ export type { ClientOptions, Signer } from './client.js';
3
+ export type * from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { ApiError, OrionBeltClient } from './client.js';