@veertu/anka-controller 0.0.0-stage → 0.1.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.
@@ -0,0 +1,156 @@
1
+ interface TlsOptions {
2
+ ca?: string;
3
+ cert?: string;
4
+ key?: string;
5
+ passphrase?: string;
6
+ rejectUnauthorized?: boolean;
7
+ }
8
+ interface ControllerClientOptions {
9
+ url: string;
10
+ rootToken?: string;
11
+ authorization?: string;
12
+ tls?: TlsOptions;
13
+ }
14
+ interface PortForwardRule {
15
+ name: string;
16
+ guest_port: string | number;
17
+ host_port?: string | number;
18
+ host_ip?: string;
19
+ protocol?: string;
20
+ }
21
+ interface DiskRequest {
22
+ size: string;
23
+ skip_container_resize?: boolean;
24
+ }
25
+ interface StartInstanceRequest {
26
+ vmid: string;
27
+ tag?: string;
28
+ version?: number;
29
+ name?: string;
30
+ external_id?: string;
31
+ count?: number;
32
+ node_id?: string;
33
+ startup_script?: string;
34
+ startup_script_condition?: number;
35
+ script_monitoring?: boolean;
36
+ script_timeout?: number;
37
+ script_fail_handler?: number;
38
+ name_template?: string;
39
+ group?: string;
40
+ group_id?: string;
41
+ priority?: number;
42
+ usb_device?: string;
43
+ vcpu?: number;
44
+ vram?: number;
45
+ metadata?: Record<string, string | number | boolean>;
46
+ mac_address?: string;
47
+ vlan_tag?: string;
48
+ video_controller?: string;
49
+ hvapic?: string;
50
+ csr_active_config?: string;
51
+ network_local?: string;
52
+ hw_serial?: string;
53
+ hw_uuid?: string;
54
+ port_forwarding_override?: PortForwardRule[];
55
+ network_mode?: string;
56
+ disk?: DiskRequest;
57
+ vnc_password?: string;
58
+ [key: string]: unknown;
59
+ }
60
+ interface PortForwardingRule {
61
+ guest_port?: number | string;
62
+ host_port?: number | string;
63
+ protocol?: string;
64
+ name?: string;
65
+ [key: string]: unknown;
66
+ }
67
+ interface VmInfo {
68
+ uuid?: string;
69
+ name?: string;
70
+ status?: string;
71
+ host_ip?: string;
72
+ ip?: string;
73
+ vnc_port?: number;
74
+ port_forwarding?: PortForwardingRule[];
75
+ [key: string]: unknown;
76
+ }
77
+ interface StartupScriptResult {
78
+ return_code?: number;
79
+ did_timeout?: boolean;
80
+ stdout?: string;
81
+ stderr?: string;
82
+ errors?: string[];
83
+ [key: string]: unknown;
84
+ }
85
+ interface Instance {
86
+ instance_id?: string;
87
+ instance_state?: string;
88
+ message?: string;
89
+ vmid?: string;
90
+ tag?: string;
91
+ external_id?: string;
92
+ progress?: number;
93
+ vminfo?: VmInfo;
94
+ startup_script?: StartupScriptResult;
95
+ [key: string]: unknown;
96
+ }
97
+ interface TemplateVersion {
98
+ tag?: string;
99
+ number?: number;
100
+ description?: string;
101
+ [key: string]: unknown;
102
+ }
103
+ interface Template {
104
+ id: string;
105
+ name?: string;
106
+ size?: number;
107
+ arch?: string;
108
+ versions?: TemplateVersion[];
109
+ [key: string]: unknown;
110
+ }
111
+ interface WaitForOptions {
112
+ intervalMs?: number;
113
+ timeoutMs?: number;
114
+ onPoll?: (instance: Instance) => void;
115
+ isReady?: (instance: Instance) => boolean;
116
+ isFailed?: (instance: Instance) => boolean;
117
+ isStop?: (instance: Instance) => boolean;
118
+ }
119
+ interface WaitForResult {
120
+ done: 'ready' | 'stop';
121
+ instance: Instance;
122
+ }
123
+ interface ControllerClient {
124
+ instances: {
125
+ start(body: StartInstanceRequest): Promise<string[]>;
126
+ get(id: string): Promise<Instance>;
127
+ list(): Promise<Instance[]>;
128
+ terminate(id: string): Promise<void>;
129
+ waitFor(id: string, options?: WaitForOptions): Promise<WaitForResult>;
130
+ };
131
+ templates: {
132
+ list(): Promise<Template[]>;
133
+ get(id: string): Promise<Template>;
134
+ };
135
+ }
136
+
137
+ declare function createControllerClient(options: ControllerClientOptions): ControllerClient;
138
+
139
+ declare class ControllerError extends Error {
140
+ readonly method: string;
141
+ readonly path: string;
142
+ readonly statusCode?: number;
143
+ readonly controllerStatus?: string;
144
+ readonly instance?: Instance;
145
+ constructor(details: {
146
+ message: string;
147
+ method: string;
148
+ path: string;
149
+ statusCode?: number;
150
+ controllerStatus?: string;
151
+ instance?: Instance;
152
+ });
153
+ }
154
+
155
+ export { ControllerError, createControllerClient };
156
+ export type { ControllerClient, ControllerClientOptions, DiskRequest, Instance, PortForwardRule, PortForwardingRule, StartInstanceRequest, StartupScriptResult, Template, TemplateVersion, TlsOptions, VmInfo, WaitForOptions, WaitForResult };
@@ -0,0 +1,156 @@
1
+ interface TlsOptions {
2
+ ca?: string;
3
+ cert?: string;
4
+ key?: string;
5
+ passphrase?: string;
6
+ rejectUnauthorized?: boolean;
7
+ }
8
+ interface ControllerClientOptions {
9
+ url: string;
10
+ rootToken?: string;
11
+ authorization?: string;
12
+ tls?: TlsOptions;
13
+ }
14
+ interface PortForwardRule {
15
+ name: string;
16
+ guest_port: string | number;
17
+ host_port?: string | number;
18
+ host_ip?: string;
19
+ protocol?: string;
20
+ }
21
+ interface DiskRequest {
22
+ size: string;
23
+ skip_container_resize?: boolean;
24
+ }
25
+ interface StartInstanceRequest {
26
+ vmid: string;
27
+ tag?: string;
28
+ version?: number;
29
+ name?: string;
30
+ external_id?: string;
31
+ count?: number;
32
+ node_id?: string;
33
+ startup_script?: string;
34
+ startup_script_condition?: number;
35
+ script_monitoring?: boolean;
36
+ script_timeout?: number;
37
+ script_fail_handler?: number;
38
+ name_template?: string;
39
+ group?: string;
40
+ group_id?: string;
41
+ priority?: number;
42
+ usb_device?: string;
43
+ vcpu?: number;
44
+ vram?: number;
45
+ metadata?: Record<string, string | number | boolean>;
46
+ mac_address?: string;
47
+ vlan_tag?: string;
48
+ video_controller?: string;
49
+ hvapic?: string;
50
+ csr_active_config?: string;
51
+ network_local?: string;
52
+ hw_serial?: string;
53
+ hw_uuid?: string;
54
+ port_forwarding_override?: PortForwardRule[];
55
+ network_mode?: string;
56
+ disk?: DiskRequest;
57
+ vnc_password?: string;
58
+ [key: string]: unknown;
59
+ }
60
+ interface PortForwardingRule {
61
+ guest_port?: number | string;
62
+ host_port?: number | string;
63
+ protocol?: string;
64
+ name?: string;
65
+ [key: string]: unknown;
66
+ }
67
+ interface VmInfo {
68
+ uuid?: string;
69
+ name?: string;
70
+ status?: string;
71
+ host_ip?: string;
72
+ ip?: string;
73
+ vnc_port?: number;
74
+ port_forwarding?: PortForwardingRule[];
75
+ [key: string]: unknown;
76
+ }
77
+ interface StartupScriptResult {
78
+ return_code?: number;
79
+ did_timeout?: boolean;
80
+ stdout?: string;
81
+ stderr?: string;
82
+ errors?: string[];
83
+ [key: string]: unknown;
84
+ }
85
+ interface Instance {
86
+ instance_id?: string;
87
+ instance_state?: string;
88
+ message?: string;
89
+ vmid?: string;
90
+ tag?: string;
91
+ external_id?: string;
92
+ progress?: number;
93
+ vminfo?: VmInfo;
94
+ startup_script?: StartupScriptResult;
95
+ [key: string]: unknown;
96
+ }
97
+ interface TemplateVersion {
98
+ tag?: string;
99
+ number?: number;
100
+ description?: string;
101
+ [key: string]: unknown;
102
+ }
103
+ interface Template {
104
+ id: string;
105
+ name?: string;
106
+ size?: number;
107
+ arch?: string;
108
+ versions?: TemplateVersion[];
109
+ [key: string]: unknown;
110
+ }
111
+ interface WaitForOptions {
112
+ intervalMs?: number;
113
+ timeoutMs?: number;
114
+ onPoll?: (instance: Instance) => void;
115
+ isReady?: (instance: Instance) => boolean;
116
+ isFailed?: (instance: Instance) => boolean;
117
+ isStop?: (instance: Instance) => boolean;
118
+ }
119
+ interface WaitForResult {
120
+ done: 'ready' | 'stop';
121
+ instance: Instance;
122
+ }
123
+ interface ControllerClient {
124
+ instances: {
125
+ start(body: StartInstanceRequest): Promise<string[]>;
126
+ get(id: string): Promise<Instance>;
127
+ list(): Promise<Instance[]>;
128
+ terminate(id: string): Promise<void>;
129
+ waitFor(id: string, options?: WaitForOptions): Promise<WaitForResult>;
130
+ };
131
+ templates: {
132
+ list(): Promise<Template[]>;
133
+ get(id: string): Promise<Template>;
134
+ };
135
+ }
136
+
137
+ declare function createControllerClient(options: ControllerClientOptions): ControllerClient;
138
+
139
+ declare class ControllerError extends Error {
140
+ readonly method: string;
141
+ readonly path: string;
142
+ readonly statusCode?: number;
143
+ readonly controllerStatus?: string;
144
+ readonly instance?: Instance;
145
+ constructor(details: {
146
+ message: string;
147
+ method: string;
148
+ path: string;
149
+ statusCode?: number;
150
+ controllerStatus?: string;
151
+ instance?: Instance;
152
+ });
153
+ }
154
+
155
+ export { ControllerError, createControllerClient };
156
+ export type { ControllerClient, ControllerClientOptions, DiskRequest, Instance, PortForwardRule, PortForwardingRule, StartInstanceRequest, StartupScriptResult, Template, TemplateVersion, TlsOptions, VmInfo, WaitForOptions, WaitForResult };
package/dist/index.js ADDED
@@ -0,0 +1,361 @@
1
+ // src/client.ts
2
+ import https2 from "https";
3
+
4
+ // src/errors.ts
5
+ var ControllerError = class extends Error {
6
+ method;
7
+ path;
8
+ statusCode;
9
+ controllerStatus;
10
+ instance;
11
+ constructor(details) {
12
+ super(details.message);
13
+ this.name = "ControllerError";
14
+ this.method = details.method;
15
+ this.path = details.path;
16
+ this.statusCode = details.statusCode;
17
+ this.controllerStatus = details.controllerStatus;
18
+ this.instance = details.instance;
19
+ }
20
+ };
21
+
22
+ // src/normalize.ts
23
+ function normalizeInstance(value) {
24
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
25
+ throw new Error("Instance record is missing");
26
+ }
27
+ const record = value;
28
+ const nested = record.vm;
29
+ if (!nested || typeof nested !== "object" || Array.isArray(nested)) {
30
+ return record;
31
+ }
32
+ const outer = { ...record };
33
+ delete outer.vm;
34
+ return { ...nested, ...outer };
35
+ }
36
+
37
+ // src/request.ts
38
+ import http from "http";
39
+ import https from "https";
40
+
41
+ // src/redact.ts
42
+ var REDACTED = "[REDACTED]";
43
+ var SENSITIVE_FIELD_NAMES = /* @__PURE__ */ new Set([
44
+ "authorization",
45
+ "cookie",
46
+ "set-cookie",
47
+ "proxy-authorization",
48
+ "x-api-key",
49
+ "x-auth-token",
50
+ "token",
51
+ "password",
52
+ "secret",
53
+ "passphrase",
54
+ "startup_script",
55
+ "gh-pat",
56
+ "gh_pat",
57
+ "controller-auth-cert",
58
+ "controller-auth-cert-key",
59
+ "controller-root-token",
60
+ "root_token",
61
+ "roottoken",
62
+ "cert",
63
+ "key",
64
+ "ca"
65
+ ]);
66
+ function redactString(value, secrets) {
67
+ let redacted = value;
68
+ for (const secret of secrets) {
69
+ if (secret.length >= 4) {
70
+ redacted = redacted.split(secret).join(REDACTED);
71
+ }
72
+ }
73
+ return redacted;
74
+ }
75
+ function redactValue(value, secrets) {
76
+ if (typeof value === "string") {
77
+ return redactString(value, secrets);
78
+ }
79
+ if (Array.isArray(value)) {
80
+ return value.map((item) => redactValue(item, secrets));
81
+ }
82
+ if (value && typeof value === "object") {
83
+ return Object.fromEntries(
84
+ Object.entries(value).map(([key, fieldValue]) => [
85
+ key,
86
+ SENSITIVE_FIELD_NAMES.has(key.toLowerCase()) ? REDACTED : redactValue(fieldValue, secrets)
87
+ ])
88
+ );
89
+ }
90
+ return value;
91
+ }
92
+
93
+ // src/request.ts
94
+ function request(controller, method, requestPath, body) {
95
+ const target = new URL(`${controller.baseUrl}${requestPath}`);
96
+ const transport = target.protocol === "https:" ? https : http;
97
+ const bodyText = body === void 0 ? void 0 : JSON.stringify(body);
98
+ const headers = { accept: "application/json" };
99
+ if (bodyText !== void 0) {
100
+ headers["content-type"] = "application/json";
101
+ headers["content-length"] = Buffer.byteLength(bodyText);
102
+ }
103
+ if (controller.authorization) {
104
+ headers.authorization = controller.authorization;
105
+ }
106
+ return new Promise((resolve, reject) => {
107
+ const incoming = transport.request(
108
+ target,
109
+ {
110
+ method,
111
+ headers,
112
+ agent: target.protocol === "https:" ? controller.agent : void 0
113
+ },
114
+ (response) => {
115
+ const chunks = [];
116
+ response.on("data", (chunk) => chunks.push(chunk));
117
+ response.on("end", () => {
118
+ try {
119
+ resolve(
120
+ readEnvelope(
121
+ method,
122
+ requestPath,
123
+ response.statusCode ?? 0,
124
+ Buffer.concat(chunks).toString("utf8"),
125
+ controller.secrets
126
+ )
127
+ );
128
+ } catch (error) {
129
+ reject(error);
130
+ }
131
+ });
132
+ }
133
+ );
134
+ incoming.on("error", (error) => {
135
+ reject(
136
+ new ControllerError({
137
+ message: `Failed to reach controller at ${controller.baseUrl}: ${redactString(error.message, controller.secrets)}`,
138
+ method,
139
+ path: requestPath
140
+ })
141
+ );
142
+ });
143
+ if (bodyText !== void 0) {
144
+ incoming.write(bodyText);
145
+ }
146
+ incoming.end();
147
+ });
148
+ }
149
+ function readEnvelope(method, requestPath, statusCode, text, secrets) {
150
+ let parsed;
151
+ if (text.trim()) {
152
+ try {
153
+ const value = JSON.parse(text);
154
+ if (value && typeof value === "object" && !Array.isArray(value)) {
155
+ parsed = value;
156
+ }
157
+ } catch {
158
+ parsed = void 0;
159
+ }
160
+ }
161
+ const httpFailed = statusCode < 200 || statusCode >= 300;
162
+ const statusFailed = !parsed || parsed.status !== "OK";
163
+ if (httpFailed || statusFailed) {
164
+ const detail = parsed ? redactString(JSON.stringify(redactValue(parsed, secrets)), secrets) : redactString(text, secrets) || `HTTP ${statusCode}`;
165
+ throw new ControllerError({
166
+ message: `Controller request failed (${method} ${requestPath}): ${detail}`,
167
+ method,
168
+ path: requestPath,
169
+ statusCode,
170
+ controllerStatus: parsed?.status
171
+ });
172
+ }
173
+ return parsed?.body;
174
+ }
175
+
176
+ // src/wait.ts
177
+ var DEFAULT_INTERVAL_MS = 3e3;
178
+ var FAILED_STATES = /* @__PURE__ */ new Set(["Error", "Terminating", "Terminated"]);
179
+ async function waitForInstance(getInstance, id, options = {}) {
180
+ const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
181
+ const timeoutMs = options.timeoutMs ?? 0;
182
+ const isReady = options.isReady ?? ((instance) => instance.instance_state === "Started");
183
+ const isFailed = options.isFailed ?? ((instance) => !!instance.instance_state && FAILED_STATES.has(instance.instance_state));
184
+ const isStop = options.isStop ?? (() => false);
185
+ const startedAt = Date.now();
186
+ const requestPath = `/api/v1/vm?id=${encodeURIComponent(id)}`;
187
+ for (; ; ) {
188
+ const instance = await getInstance(id);
189
+ options.onPoll?.(instance);
190
+ if (isFailed(instance)) {
191
+ throw new ControllerError({
192
+ message: formatFailure(instance),
193
+ method: "GET",
194
+ path: requestPath,
195
+ controllerStatus: instance.instance_state,
196
+ instance
197
+ });
198
+ }
199
+ if (isReady(instance)) {
200
+ return { done: "ready", instance };
201
+ }
202
+ if (isStop(instance)) {
203
+ return { done: "stop", instance };
204
+ }
205
+ if (timeoutMs > 0 && Date.now() - startedAt >= timeoutMs) {
206
+ const state = instance.instance_state ?? "unknown";
207
+ throw new ControllerError({
208
+ message: `Timed out after ${timeoutMs}ms waiting for instance ${id} (instance_state: ${state})`,
209
+ method: "GET",
210
+ path: requestPath,
211
+ controllerStatus: state,
212
+ instance
213
+ });
214
+ }
215
+ await delay(intervalMs);
216
+ }
217
+ }
218
+ function formatFailure(instance) {
219
+ const state = instance.instance_state ?? "unknown";
220
+ let text = `Instance entered ${state} state`;
221
+ if (typeof instance.message === "string" && instance.message) {
222
+ text += `: ${instance.message}`;
223
+ }
224
+ const stderr = instance.startup_script?.stderr;
225
+ if (typeof stderr === "string" && stderr) {
226
+ text += `: ${stderr}`;
227
+ }
228
+ return text;
229
+ }
230
+ function delay(ms) {
231
+ return new Promise((resolve) => {
232
+ setTimeout(resolve, ms);
233
+ });
234
+ }
235
+
236
+ // src/client.ts
237
+ function createControllerClient(options) {
238
+ const url = options.url?.trim() ?? "";
239
+ if (!url) {
240
+ throw new Error("url is required");
241
+ }
242
+ const rootToken = options.rootToken?.trim() ?? "";
243
+ const authorizationValue = options.authorization?.trim() ?? "";
244
+ if (rootToken && authorizationValue) {
245
+ throw new Error("Set rootToken or authorization, not both");
246
+ }
247
+ if (options.tls && !url.startsWith("https://")) {
248
+ throw new Error("tls options require an https url");
249
+ }
250
+ const baseUrl = url.replace(/\/+$/, "");
251
+ const authorization = authorizationValue || basicAuthorization(rootToken);
252
+ const secrets = [rootToken, authorizationValue, authorization].filter((secret) => secret.length > 0);
253
+ const controllerRequest = {
254
+ baseUrl,
255
+ authorization,
256
+ agent: options.tls ? createTlsAgent(options.tls) : void 0,
257
+ secrets
258
+ };
259
+ async function getInstance(id) {
260
+ const requestPath = `/api/v1/vm?id=${encodeURIComponent(id)}`;
261
+ const body = await request(controllerRequest, "GET", requestPath);
262
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
263
+ throw new ControllerError({
264
+ message: `Instance ${id} not found`,
265
+ method: "GET",
266
+ path: requestPath
267
+ });
268
+ }
269
+ return normalizeInstance(body);
270
+ }
271
+ return {
272
+ instances: {
273
+ async start(body) {
274
+ if (!body.vmid || !body.vmid.trim()) {
275
+ throw new Error("vmid is required");
276
+ }
277
+ const ids = await request(controllerRequest, "POST", "/api/v1/vm", body);
278
+ const idsAreMissing = !Array.isArray(ids) || ids.length === 0 || ids.some((id) => typeof id !== "string" || !id);
279
+ if (idsAreMissing) {
280
+ throw new ControllerError({
281
+ message: "Controller did not return an instance id (POST /api/v1/vm)",
282
+ method: "POST",
283
+ path: "/api/v1/vm"
284
+ });
285
+ }
286
+ return ids;
287
+ },
288
+ get: getInstance,
289
+ async list() {
290
+ const body = await request(controllerRequest, "GET", "/api/v1/vm");
291
+ if (body == null) {
292
+ return [];
293
+ }
294
+ if (!Array.isArray(body)) {
295
+ throw new ControllerError({
296
+ message: "Controller request failed (GET /api/v1/vm): instance list body must be an array",
297
+ method: "GET",
298
+ path: "/api/v1/vm"
299
+ });
300
+ }
301
+ return body.map((item) => normalizeInstance(item));
302
+ },
303
+ async terminate(id) {
304
+ await request(controllerRequest, "DELETE", "/api/v1/vm", { id });
305
+ },
306
+ waitFor(id, waitOptions) {
307
+ return waitForInstance(getInstance, id, waitOptions);
308
+ }
309
+ },
310
+ templates: {
311
+ async list() {
312
+ const body = await request(controllerRequest, "GET", "/api/v1/registry/vm");
313
+ if (body == null) {
314
+ return [];
315
+ }
316
+ if (!Array.isArray(body)) {
317
+ throw new ControllerError({
318
+ message: "Controller request failed (GET /api/v1/registry/vm): template list body must be an array",
319
+ method: "GET",
320
+ path: "/api/v1/registry/vm"
321
+ });
322
+ }
323
+ return body;
324
+ },
325
+ async get(id) {
326
+ const requestPath = `/api/v1/registry/vm?id=${encodeURIComponent(id)}`;
327
+ const body = await request(controllerRequest, "GET", requestPath);
328
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
329
+ throw new ControllerError({
330
+ message: `Template ${id} not found`,
331
+ method: "GET",
332
+ path: requestPath
333
+ });
334
+ }
335
+ return body;
336
+ }
337
+ }
338
+ };
339
+ }
340
+ function basicAuthorization(rootToken) {
341
+ if (!rootToken) {
342
+ return "";
343
+ }
344
+ return `Basic ${Buffer.from(`:${rootToken}`).toString("base64")}`;
345
+ }
346
+ function createTlsAgent(tls) {
347
+ const agentOptions = {};
348
+ if (tls.ca !== void 0) agentOptions.ca = tls.ca;
349
+ if (tls.cert !== void 0) agentOptions.cert = tls.cert;
350
+ if (tls.key !== void 0) agentOptions.key = tls.key;
351
+ if (tls.passphrase !== void 0) agentOptions.passphrase = tls.passphrase;
352
+ if (tls.rejectUnauthorized !== void 0) {
353
+ agentOptions.rejectUnauthorized = tls.rejectUnauthorized;
354
+ }
355
+ return new https2.Agent(agentOptions);
356
+ }
357
+ export {
358
+ ControllerError,
359
+ createControllerClient
360
+ };
361
+ //# sourceMappingURL=index.js.map