@virtbase/proxmox-api 3.0.0 → 4.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +10 -53
  2. package/LICENSE +22 -0
  3. package/README.md +81 -82
  4. package/dist/client.d.ts +13 -7
  5. package/dist/client.js +23 -23
  6. package/dist/errors.d.ts +364 -0
  7. package/dist/errors.js +372 -0
  8. package/dist/index.d.ts +5 -3
  9. package/dist/index.js +3 -18
  10. package/dist/model.d.ts +28408 -28157
  11. package/dist/model.js +4 -16
  12. package/dist/proxmox-engine.d.ts +273 -54
  13. package/dist/proxmox-engine.js +772 -248
  14. package/dist/proxy.d.ts +61 -19
  15. package/dist/proxy.js +118 -33
  16. package/dist/qm-monitor.d.ts +225 -25
  17. package/dist/qm-monitor.js +152 -52
  18. package/dist/schema-info.d.ts +12 -0
  19. package/dist/schema-info.js +13 -0
  20. package/dist/tasks.d.ts +129 -0
  21. package/dist/tasks.js +132 -0
  22. package/package.json +33 -34
  23. package/dist/client.d.ts.map +0 -1
  24. package/dist/client.js.map +0 -1
  25. package/dist/index.d.ts.map +0 -1
  26. package/dist/index.js.map +0 -1
  27. package/dist/model.d.ts.map +0 -1
  28. package/dist/model.js.map +0 -1
  29. package/dist/proxmox-engine.d.ts.map +0 -1
  30. package/dist/proxmox-engine.js.map +0 -1
  31. package/dist/proxy.d.ts.map +0 -1
  32. package/dist/proxy.js.map +0 -1
  33. package/dist/qm-monitor.d.ts.map +0 -1
  34. package/dist/qm-monitor.js.map +0 -1
  35. package/src/__tests__/helpers.ts +0 -39
  36. package/src/__tests__/proxmox-engine.test.ts +0 -393
  37. package/src/__tests__/proxy.test.ts +0 -190
  38. package/src/__tests__/qm-monitor.test.ts +0 -215
  39. package/src/client.ts +0 -58
  40. package/src/index.ts +0 -34
  41. package/src/model.ts +0 -32101
  42. package/src/proxmox-engine.ts +0 -452
  43. package/src/proxy.ts +0 -195
  44. package/src/qm-monitor.ts +0 -303
@@ -1,308 +1,832 @@
1
- // Proxmox-API Interactive proxmox API for developpers how do not like reading docs
2
- // Copyright (C) 2020-2022 Chemouni Uriel <uchemouni@gmail.com>
3
- //
4
- // This program is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // This program is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
- const USER_AGENT = "proxmox-api (https://github.com/UrielCh/proxmox-api)";
17
- const BASE_HEADERS = {
18
- Accept: "*/*",
19
- "User-Agent": USER_AGENT,
20
- };
1
+ import { apiErrorFor, ProxmoxAbortError, ProxmoxAuthenticationError, ProxmoxConfigError, ProxmoxConnectionError, ProxmoxError, ProxmoxResponseError, ProxmoxTimeoutError, } from "./errors.js";
21
2
  /**
22
- * Own enumerable entries of `params`, minus the null and undefined ones.
3
+ * Sent as the `User-Agent` of every request, unless a custom header replaces
4
+ * it.
5
+ */
6
+ const USER_AGENT = "@virtbase/proxmox-api (+https://github.com/virtbase/proxmox-api)";
7
+ /**
8
+ * Path a password login is posted to.
9
+ */
10
+ const TICKET_PATH = "/api2/json/access/ticket";
11
+ /**
12
+ * Port used when the `port` option is omitted.
13
+ */
14
+ const DEFAULT_PORT = 8006;
15
+ /**
16
+ * Milliseconds allowed for a login request when `authTimeout` is omitted.
17
+ */
18
+ const DEFAULT_AUTH_TIMEOUT = 10_000;
19
+ /**
20
+ * Milliseconds allowed for any other request when neither `queryTimeout` nor
21
+ * a per-call `timeout` is given.
22
+ */
23
+ const DEFAULT_QUERY_TIMEOUT = 60_000;
24
+ /**
25
+ * Retries of a failed `GET` when `maxRetries` is omitted.
26
+ */
27
+ const DEFAULT_MAX_RETRIES = 2;
28
+ /**
29
+ * Age in milliseconds from which a cached ticket is replaced by a new login.
23
30
  *
24
- * PVE rejects empty values, and callers routinely pass optional fields
25
- * through as undefined, so they are dropped rather than serialised.
31
+ * Proxmox accepts a ticket for two hours. Renewing at half that leaves a wide
32
+ * margin for clock skew and for requests already in flight.
26
33
  */
27
- function definedEntries(params) {
28
- if (!params)
29
- return [];
30
- return Object.entries(params).filter(([, value]) => value !== null && value !== undefined);
34
+ const TICKET_RENEW_AFTER = 60 * 60 * 1000;
35
+ /**
36
+ * Statuses worth repeating: a gateway or overload answer, and the 595, 596,
37
+ * 597 and 599 that pveproxy uses when it cannot reach the node a request is
38
+ * proxied to.
39
+ */
40
+ const RETRYABLE_STATUS = new Set([
41
+ 408, 429, 502, 503, 504, 595, 596, 597, 599,
42
+ ]);
43
+ /**
44
+ * Longest delay before the first retry, in milliseconds. It doubles with
45
+ * each further retry.
46
+ */
47
+ const RETRY_BASE_DELAY = 500;
48
+ /**
49
+ * Longest delay before any retry, in milliseconds.
50
+ */
51
+ const RETRY_MAX_DELAY = 8_000;
52
+ /**
53
+ * Reports whether a value is an object other than `null` or an array.
54
+ */
55
+ function isRecord(value) {
56
+ return typeof value === "object" && value !== null && !Array.isArray(value);
31
57
  }
32
58
  /**
33
- * Encode one parameter the way the PVE API expects: booleans as 1/0, arrays as
34
- * the key repeated once per element.
59
+ * Encodes parameters the way the PVE API expects: booleans as 1/0, arrays as
60
+ * the key repeated once per element, null and undefined left out.
61
+ *
62
+ * @param params - The caller's parameters, which are not modified.
63
+ * @returns The encoded pairs, in the order of the parameters. Values other
64
+ * than booleans are converted to strings.
35
65
  */
36
- function appendParam(target, key, value) {
37
- if (value === true) {
38
- target.set(key, "1");
39
- }
40
- else if (value === false) {
41
- target.set(key, "0");
66
+ function encodeParams(params) {
67
+ const encoded = new URLSearchParams();
68
+ for (const [key, value] of Object.entries(params ?? {})) {
69
+ if (value === null || value === undefined)
70
+ continue;
71
+ for (const element of Array.isArray(value) ? value : [value]) {
72
+ encoded.append(key, element === true ? "1" : element === false ? "0" : `${element}`);
73
+ }
42
74
  }
43
- else if (Array.isArray(value)) {
44
- for (const element of value)
45
- target.append(key, `${element}`);
75
+ return encoded;
76
+ }
77
+ /**
78
+ * Waits out the delay before a retry, ending early when the signal aborts.
79
+ *
80
+ * @remarks
81
+ * Never rejects: the caller checks the signal afterwards.
82
+ *
83
+ * @param ms - Milliseconds to wait.
84
+ * @param signal - Ends the wait when it aborts. An abort that happened
85
+ * before the call goes unnoticed and the full time is waited.
86
+ */
87
+ function sleep(ms, signal) {
88
+ return new Promise((resolve) => {
89
+ const done = () => {
90
+ clearTimeout(timer);
91
+ signal?.removeEventListener("abort", done);
92
+ resolve();
93
+ };
94
+ const timer = setTimeout(done, ms);
95
+ signal?.addEventListener("abort", done, { once: true });
96
+ });
97
+ }
98
+ /**
99
+ * Computes the delay before a retry: exponential backoff with jitter.
100
+ *
101
+ * @param attempt - Number of the attempt that just failed, starting at 1.
102
+ * @returns Milliseconds between 75% and 100% of a ceiling that is 500 for
103
+ * the first attempt, doubles with each further one and stops at 8000.
104
+ */
105
+ function retryDelay(attempt) {
106
+ const ceiling = Math.min(RETRY_MAX_DELAY, RETRY_BASE_DELAY * 2 ** (attempt - 1));
107
+ return Math.round(ceiling * (0.75 + Math.random() * 0.25));
108
+ }
109
+ /**
110
+ * Validates the `host` option and makes it fit for a URL.
111
+ *
112
+ * @param host - The option as given.
113
+ * @returns The host unchanged, or wrapped in brackets when it is a bare
114
+ * IPv6 address.
115
+ * @throws A {@link ProxmoxConfigError} if the host is empty, contains white
116
+ * space or one of `/`, `?`, `#`, `@` and `%`, starts with a scheme, or
117
+ * ends in a port.
118
+ */
119
+ function formatHost(host) {
120
+ if (!host || /[/?#@%\s]/.test(host) || /^[a-z]+:\/\//i.test(host)) {
121
+ throw new ProxmoxConfigError(`Invalid host ${JSON.stringify(host)}: pass a bare hostname or IP address, and set the port and scheme through the "port" and "schema" options.`);
46
122
  }
47
- else {
48
- target.set(key, `${value}`);
123
+ const isBareIpv6 = !host.startsWith("[") && host.split(":").length > 2;
124
+ if (!isBareIpv6 && /:\d+$/.test(host)) {
125
+ throw new ProxmoxConfigError(`Invalid host ${JSON.stringify(host)}: it contains a port. Pass it through the "port" option instead.`);
49
126
  }
127
+ return isBareIpv6 ? `[${host}]` : host;
50
128
  }
51
129
  /**
52
- * Default Proxmox doRequest provider, this Class will be used if you provide Proxmox authentification options to the Proxy generator
130
+ * The HTTP transport behind `proxmoxApi()`: authentication, encoding, retries
131
+ * and error mapping. Construct it directly to keep hold of the session.
132
+ *
133
+ * @remarks
134
+ * Credentials and the session are held in private fields, so logging or
135
+ * serialising an engine never prints them.
136
+ *
137
+ * One engine serves any number of concurrent requests. With password
138
+ * authentication it logs in when the first request is made, caches the
139
+ * ticket, replaces it once it is an hour old and lets concurrent requests
140
+ * share a single login.
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * const engine = new ProxmoxEngine({
145
+ * host: "192.0.2.10",
146
+ * username: "root@pam",
147
+ * password: process.env.PVE_PASSWORD!,
148
+ * });
149
+ * const proxmox = proxmoxApi(engine);
150
+ *
151
+ * const { ticket, CSRFPreventionToken } = await engine.getTicket();
152
+ * ```
53
153
  */
54
154
  export class ProxmoxEngine {
55
- CSRFPreventionToken;
56
- ticket;
57
- username;
58
- password;
59
- hostname; // was named host
60
- port;
61
- schema;
62
- authTimeout;
63
- queryTimeout;
64
- debug;
65
- fetch;
155
+ /**
156
+ * The origin every request is sent to, e.g. `https://192.0.2.10:8006`.
157
+ */
158
+ origin;
159
+ /**
160
+ * Value of the `Authorization` header for token authentication. Unset for
161
+ * password authentication, which is how the two are told apart.
162
+ */
163
+ #authorization;
164
+ /**
165
+ * Login name. Empty with token authentication.
166
+ */
167
+ #username;
168
+ /**
169
+ * Login password. Empty with token authentication.
170
+ */
171
+ #password;
172
+ #otp;
173
+ /**
174
+ * A copy of the `headers` option.
175
+ */
176
+ #headers;
177
+ #authTimeout;
178
+ #queryTimeout;
179
+ #maxRetries;
180
+ #fetch;
181
+ #onEvent;
182
+ /**
183
+ * The cached ticket. Unset until the first login, after
184
+ * {@link ProxmoxEngine.logout} and once Proxmox has rejected it.
185
+ */
186
+ #session;
187
+ /**
188
+ * The login in flight, shared by every request that needs a session while
189
+ * it runs.
190
+ */
191
+ #pendingLogin;
192
+ /**
193
+ * Validates the options and prepares the transport, without sending
194
+ * anything.
195
+ *
196
+ * @param options - Connection settings and credentials. A `tokenID`
197
+ * selects token authentication, even next to a `password`.
198
+ * @throws A {@link ProxmoxConfigError} if `schema` is neither `https` nor
199
+ * `http`, `port` is not an integer from 1 to 65535, `host` is not a bare
200
+ * hostname or IP address, `tokenID` does not read
201
+ * `USER@REALM!TOKENNAME`, `tokenSecret` is empty, neither a `tokenID`
202
+ * nor a `password` is given, or `username` has no realm.
203
+ */
66
204
  constructor(options) {
67
- // Bound to globalThis: some runtimes reject the platform `fetch` when it
68
- // is invoked as a method of another object.
69
- this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
70
- if ("tokenID" in options && options.tokenSecret) {
71
- this.username = "";
72
- this.password = "";
73
- if (!options.tokenID.match(/.*@.+!.+/)) {
74
- const msg = "invalid tokenID, format should look be like USER@REALM!TOKENID";
75
- console.error(msg);
76
- throw Error(msg);
205
+ const scheme = options.schema ?? "https";
206
+ if (scheme !== "https" && scheme !== "http") {
207
+ throw new ProxmoxConfigError(`Invalid schema ${JSON.stringify(scheme)}: expected "https" or "http".`);
208
+ }
209
+ const port = options.port ?? DEFAULT_PORT;
210
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
211
+ throw new ProxmoxConfigError(`Invalid port ${JSON.stringify(port)}.`);
212
+ }
213
+ this.origin = `${scheme}://${formatHost(options.host)}:${port}`;
214
+ if ("tokenID" in options && options.tokenID !== undefined) {
215
+ if (!/^[^@!\s]+@[^@!\s]+![^!\s]+$/.test(options.tokenID)) {
216
+ throw new ProxmoxConfigError('Invalid tokenID: expected the form "USER@REALM!TOKENNAME", for example "root@pam!automation".');
77
217
  }
78
- if (!options.tokenSecret.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)) {
79
- const msg = "invalid tokenSecret, format should be an lowercased UUID like 12345678-1234-1234-1234-1234567890ab";
80
- console.error(msg);
81
- throw Error(msg);
218
+ if (!options.tokenSecret) {
219
+ throw new ProxmoxConfigError("tokenSecret is missing.");
82
220
  }
83
- // USER@REALM!TOKENID
84
- this.ticket = `PVEAPIToken=${options.tokenID}=${options.tokenSecret}`;
221
+ this.#authorization = `PVEAPIToken=${options.tokenID}=${options.tokenSecret}`;
222
+ this.#username = "";
223
+ this.#password = "";
85
224
  }
86
225
  else {
87
- const optPass = options;
88
- this.username = optPass.username || "root@pam";
89
- this.password = optPass.password;
90
- if (!this.password) {
91
- const msg = `password is missing for Proxmox connection`;
92
- console.error(msg);
93
- throw Error(msg);
226
+ const { username = "root@pam", password, otp, } = options;
227
+ if (!password) {
228
+ throw new ProxmoxConfigError("No credentials: pass either tokenID and tokenSecret, or password.");
229
+ }
230
+ if (!username.includes("@")) {
231
+ throw new ProxmoxConfigError(`Invalid username ${JSON.stringify(username)}: the realm is required, for example "root@pam".`);
94
232
  }
233
+ this.#username = username;
234
+ this.#password = password;
235
+ this.#otp = otp;
95
236
  }
96
- this.hostname = options.host;
97
- this.port = options.port;
98
- this.schema = options.schema || "https";
99
- this.authTimeout = options.authTimeout || 5000;
100
- this.queryTimeout = options.queryTimeout || 60000;
101
- this.debug = options.debug;
237
+ this.#authTimeout = options.authTimeout ?? DEFAULT_AUTH_TIMEOUT;
238
+ this.#queryTimeout = options.queryTimeout ?? DEFAULT_QUERY_TIMEOUT;
239
+ this.#maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
240
+ this.#headers = { ...options.headers };
241
+ // Bound to globalThis: some runtimes reject the platform `fetch` when it
242
+ // is invoked as a method of another object.
243
+ this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
244
+ this.#onEvent = options.onEvent;
102
245
  }
103
- get host() {
104
- if (!this.port)
105
- return this.hostname;
106
- return `${this.hostname}:${this.port}`;
246
+ /**
247
+ * The cached ticket of the last password login.
248
+ *
249
+ * @remarks
250
+ * `undefined` before the first login, after {@link ProxmoxEngine.logout}
251
+ * and with token authentication. Reading it sends nothing and does not
252
+ * renew a ticket that is due; call {@link ProxmoxEngine.getTicket} to log
253
+ * in or renew as needed.
254
+ */
255
+ get ticket() {
256
+ return this.#session?.ticket;
107
257
  }
108
258
  /**
259
+ * The CSRF token that belongs to {@link ProxmoxEngine.ticket}, which
260
+ * Proxmox demands alongside it for every request that is not a `GET`.
261
+ * `undefined` whenever the ticket is.
262
+ */
263
+ get CSRFPreventionToken() {
264
+ return this.#session?.CSRFPreventionToken;
265
+ }
266
+ /**
267
+ * Drops the cached ticket, so the next request logs in again.
268
+ *
269
+ * @remarks
270
+ * Nothing is sent, so the ticket itself stays valid until Proxmox expires
271
+ * it. A login already in flight is not cancelled, and its ticket is cached
272
+ * when it completes. With token authentication there is nothing to drop.
273
+ */
274
+ logout() {
275
+ this.#session = undefined;
276
+ }
277
+ /**
278
+ * Returns the ticket and CSRF token, logging in first when there is none
279
+ * or the cached one is due for renewal.
280
+ *
281
+ * @remarks
282
+ * A cached ticket is returned as long as it is less than an hour old. A
283
+ * login already in flight is joined rather than doubled. A login is
284
+ * bounded by `authTimeout` per request and is not retried.
285
+ *
286
+ * @returns The ticket and the CSRF token that goes with it. Both are
287
+ * bearer credentials.
288
+ * @throws A {@link ProxmoxConfigError} if the engine authenticates with an
289
+ * API token, which has no ticket.
290
+ * @throws A {@link ProxmoxAuthenticationError} if Proxmox rejects the
291
+ * username or password, or asks for a second factor that the `otp`
292
+ * option does not supply. The latter has `tfaRequired` set.
293
+ * @throws A {@link ProxmoxTimeoutError} if a login request exceeds
294
+ * `authTimeout`.
295
+ * @throws A {@link ProxmoxConnectionError} if a login request gets no
296
+ * response.
297
+ * @throws A {@link ProxmoxResponseError} if the reply to a successful
298
+ * login carries no ticket or cannot be parsed.
299
+ * @throws A {@link ProxmoxApiError} if the login is answered with any
300
+ * other error status.
301
+ */
302
+ async getTicket() {
303
+ if (this.#authorization) {
304
+ throw new ProxmoxConfigError("This client authenticates with an API token and has no ticket.");
305
+ }
306
+ const { ticket, CSRFPreventionToken } = await this.#ensureSession();
307
+ return { ticket, CSRFPreventionToken };
308
+ }
309
+ /**
310
+ * Sends one API request and returns its decoded reply.
311
+ *
312
+ * @remarks
313
+ * This is the primitive the proxy calls. Parameters travel as a
314
+ * form-encoded body for `POST` and `PUT`, and in the query string for
315
+ * every other method.
316
+ *
317
+ * With password authentication the request first waits for a session,
318
+ * which means a login when there is no ticket or the cached one is due
319
+ * for renewal. Concurrent requests share one login. A request answered
320
+ * with `401` is replayed with a fresh ticket - once, and for any method,
321
+ * since a rejected ticket means the request was never run. With an API
322
+ * token there is no login and a `401` is final.
323
+ *
324
+ * Only a `GET` is retried, up to `maxRetries` times: after a connection
325
+ * error, after a timeout - of the request or of the login it waited for -
326
+ * and after the statuses 408, 429, 502, 503, 504, 595, 596, 597 and 599.
327
+ * The delay is at most half a second before the first retry and doubles
328
+ * with each further one, up to eight seconds. An abort ends it at once.
329
+ *
330
+ * Every attempt has `timeout` milliseconds, counted from the moment it is
331
+ * sent, after any login, until the response body has been read. A body
332
+ * returned as a stream is covered only until the response headers arrive;
333
+ * from then on only `signal` can cancel it.
109
334
  *
110
- * @param method http method GET POST PUT of DELETE
111
- * @param path http path
112
- * @param pathTemplate http path without var replacements *
113
- * @param params query params
114
- * @param retries retries id
115
- * @returns data from remote response
335
+ * Requests, responses, retries and the final failure are reported to
336
+ * `onEvent`. An error raised by a login names the login request, not this
337
+ * one, as its `request`. An error thrown by an `otp` callback is passed on
338
+ * unchanged and unreported.
339
+ *
340
+ * @param method - HTTP method, in upper or lower case.
341
+ * @param path - Path to request, appended to {@link ProxmoxEngine.origin}
342
+ * as it is. It has to start with `/` and to be escaped already.
343
+ * @param pathTemplate - The path with `*` in place of each id. Used only to
344
+ * label errors and events.
345
+ * @param params - Parameters to send. Booleans are sent as `1` and `0`, an
346
+ * array as its key repeated once per element; `null` and `undefined`
347
+ * values are left out. The object is not modified.
348
+ * @param options - Per-call overrides of the timeout, the retries and the
349
+ * headers, and a signal to cancel the request with.
350
+ * @returns The `data` field of a JSON reply, or `null` when it has none.
351
+ * A reply of type `application/octet-stream` yields the response body
352
+ * as a `ReadableStream`, and any other type the body as text, or `null`
353
+ * when it is empty.
354
+ * @throws A {@link ProxmoxAbortError} if `options.signal` is aborted
355
+ * before the request is sent, or aborts while it waits for a login, is
356
+ * in flight, or waits for a retry.
357
+ * @throws A {@link ProxmoxTimeoutError} if the request, or the login it
358
+ * waits for, exceeds its timeout and no retry is left.
359
+ * @throws A {@link ProxmoxConnectionError} if no complete response arrives
360
+ * and no retry is left.
361
+ * @throws A {@link ProxmoxParameterError} if Proxmox answers `400`.
362
+ * @throws A {@link ProxmoxAuthenticationError} if Proxmox answers `401`:
363
+ * to an API token, to a ticket for the second time in this call, or to
364
+ * the login. A login that needs a second factor which the `otp` option
365
+ * does not supply fails the same way, with `tfaRequired` set.
366
+ * @throws A {@link ProxmoxPermissionError} if Proxmox answers `403`.
367
+ * @throws A {@link ProxmoxApiError} if Proxmox answers with any other
368
+ * error status. For a status that is retried, this is the answer to the
369
+ * last attempt.
370
+ * @throws A {@link ProxmoxResponseError} if a success declares a JSON body
371
+ * that does not parse, or the reply to a login carries no ticket.
116
372
  */
117
- async doRequest(method, path, pathTemplate, params, retries = 0) {
118
- const { CSRFPreventionToken, ticket } = await this.getTicket();
119
- // ensure that method is uppercased
373
+ async doRequest(method, path, pathTemplate, params, options = {}) {
120
374
  const httpMethod = method.toUpperCase();
121
- const headers = { ...BASE_HEADERS };
122
- // auth
123
- if (!this.username) {
124
- headers.Authorization = ticket; // PVEAPIToken=USER@REALM!TOKENID=UUID
375
+ const maxRetries = httpMethod === "GET" ? (options.maxRetries ?? this.#maxRetries) : 0;
376
+ const timeout = options.timeout ?? this.#queryTimeout;
377
+ const { signal } = options;
378
+ const info = {
379
+ method: httpMethod,
380
+ path,
381
+ pathTemplate,
382
+ origin: this.origin,
383
+ attempt: 0,
384
+ };
385
+ let renewed = false;
386
+ for (;;) {
387
+ info.attempt++;
388
+ const request = { ...info };
389
+ const started = Date.now();
390
+ let error;
391
+ let retryable;
392
+ try {
393
+ if (signal?.aborted)
394
+ throw new ProxmoxAbortError(request, signal.reason);
395
+ const session = this.#authorization
396
+ ? undefined
397
+ : await this.#sessionFor(signal, request);
398
+ this.#emit({ ...request, type: "request" });
399
+ const exchange = this.#begin(request, timeout, signal);
400
+ let response;
401
+ try {
402
+ response = await this.#send(this.#buildRequest(httpMethod, path, params, {
403
+ ...this.#headers,
404
+ ...options.headers,
405
+ ...this.#authHeaders(httpMethod, session),
406
+ }), exchange);
407
+ if (response.ok) {
408
+ const data = await this.#readData(response, exchange);
409
+ this.#emit({
410
+ ...request,
411
+ type: "response",
412
+ status: response.status,
413
+ durationMs: Date.now() - started,
414
+ });
415
+ return data;
416
+ }
417
+ error = await this.#readError(response, exchange);
418
+ }
419
+ finally {
420
+ // Also releases a streamed body from the deadline: once the headers
421
+ // are in, a download is bounded only by the caller's own signal.
422
+ clearTimeout(exchange.timer);
423
+ }
424
+ // A rejected ticket means the request was never run, so replaying it
425
+ // with a fresh one is safe for every method. Once. Only the request
426
+ // that still holds the current ticket discards it: others in flight
427
+ // may get their 401 after a new login has already replaced it.
428
+ if (response.status === 401 && session && !renewed) {
429
+ renewed = true;
430
+ if (this.#session === session)
431
+ this.#session = undefined;
432
+ info.attempt--;
433
+ continue;
434
+ }
435
+ retryable = RETRYABLE_STATUS.has(response.status);
436
+ }
437
+ catch (caught) {
438
+ if (!ProxmoxError.isInstance(caught))
439
+ throw caught;
440
+ error = caught;
441
+ retryable = caught.code === "connection" || caught.code === "timeout";
442
+ }
443
+ if (retryable && info.attempt <= maxRetries && !signal?.aborted) {
444
+ const delayMs = retryDelay(info.attempt);
445
+ this.#emit({ ...request, type: "retry", delayMs, error });
446
+ await sleep(delayMs, signal);
447
+ continue;
448
+ }
449
+ this.#emit({
450
+ ...request,
451
+ type: "error",
452
+ durationMs: Date.now() - started,
453
+ error,
454
+ });
455
+ throw error;
125
456
  }
126
- else {
127
- headers.cookie = `PVEAuthCookie=${ticket}`;
128
- headers.CSRFPreventionToken = CSRFPreventionToken;
457
+ }
458
+ /**
459
+ * Reports an event to `onEvent`, when there is one. An observer that
460
+ * throws must not fail the request.
461
+ */
462
+ #emit(event) {
463
+ try {
464
+ this.#onEvent?.(event);
129
465
  }
130
- // proxmox base url
131
- const requestUrl = new URL(`${this.schema}://${this.host}${path}`);
132
- let body;
133
- const entries = definedEntries(params);
134
- if (entries.length > 0) {
135
- const sendsBody = httpMethod === "PUT" || httpMethod === "POST";
136
- const searchParams = sendsBody
137
- ? new URLSearchParams()
138
- : requestUrl.searchParams;
139
- for (const [key, value] of entries)
140
- appendParam(searchParams, key, value);
141
- if (sendsBody) {
142
- body = searchParams.toString();
143
- headers["Content-Type"] = "application/x-www-form-urlencoded";
144
- // `Content-Length` is deliberately left to fetch, which derives it
145
- // from the body. Upstream set it by hand from `body.length`; that
146
- // happens to agree here - `URLSearchParams.toString()` percent-encodes
147
- // to ASCII - but it is a second source of truth for the same fact, and
148
- // one that silently disagrees the moment the body is transformed.
149
- }
466
+ catch {
467
+ // Deliberately ignored: by now the request may already have run.
150
468
  }
151
- const fetchInit = {
152
- method: httpMethod,
153
- body,
154
- headers,
155
- // Self-clearing, unlike a setTimeout/clearTimeout pair - which leaked a
156
- // pending timer on every request that threw.
157
- signal: AbortSignal.timeout(this.queryTimeout),
469
+ }
470
+ /**
471
+ * Starts the clock for one attempt. The caller clears `timer` when done.
472
+ *
473
+ * @param request - The request being attempted.
474
+ * @param timeout - Milliseconds after which the attempt is aborted and
475
+ * marked as timed out.
476
+ * @param signal - The caller's own signal, recorded so that a later
477
+ * failure can be attributed to it.
478
+ * @returns The state of the attempt, with its timer already running.
479
+ */
480
+ #begin(request, timeout, signal) {
481
+ const exchange = {
482
+ request,
483
+ timeout,
484
+ signal,
485
+ controller: new AbortController(),
486
+ timedOut: false,
487
+ timer: setTimeout(() => {
488
+ exchange.timedOut = true;
489
+ exchange.controller.abort();
490
+ }, timeout),
158
491
  };
159
- let res;
160
- try {
161
- res = await this.fetch(requestUrl, fetchInit);
492
+ return exchange;
493
+ }
494
+ /**
495
+ * Builds the URL and `fetch` options of a request, without sending it.
496
+ *
497
+ * @param method - HTTP method in upper case.
498
+ * @param path - Path below the origin.
499
+ * @param params - Parameters, which go into a form-encoded body for `POST`
500
+ * and `PUT` and into the query string otherwise. Without any, neither a
501
+ * body nor a `Content-Type` is set.
502
+ * @param headers - Headers to send on top of the default `Accept` and
503
+ * `User-Agent`, which they can replace.
504
+ * @returns What to call `fetch` with, bar the abort signal.
505
+ */
506
+ #buildRequest(method, path, params, headers) {
507
+ const url = new URL(`${this.origin}${path}`);
508
+ const encoded = encodeParams(params);
509
+ const init = {
510
+ method,
511
+ headers: {
512
+ Accept: "application/json",
513
+ "User-Agent": USER_AGENT,
514
+ ...headers,
515
+ },
516
+ };
517
+ if (encoded.size > 0) {
518
+ if (method === "POST" || method === "PUT") {
519
+ init.body = encoded.toString();
520
+ init.headers["Content-Type"] =
521
+ "application/x-www-form-urlencoded";
522
+ }
523
+ else {
524
+ url.search = encoded.toString();
525
+ }
162
526
  }
163
- catch (e) {
164
- this.logRequest(httpMethod, requestUrl, fetchInit, headers, {
165
- ticket,
166
- CSRFPreventionToken,
527
+ return { url, init };
528
+ }
529
+ /**
530
+ * Sends one request, turning every way it can fail without a response into
531
+ * a {@link ProxmoxError}.
532
+ *
533
+ * @remarks
534
+ * The fetch is aborted by the exchange's timer or by the caller's signal,
535
+ * whichever comes first.
536
+ *
537
+ * @returns The response as soon as its headers are in, whatever its
538
+ * status. The body has not been read yet.
539
+ * @throws A {@link ProxmoxError} for an abort, a timeout or a failed
540
+ * connection if `fetch` rejects.
541
+ */
542
+ async #send({ url, init }, exchange) {
543
+ const { signal, controller } = exchange;
544
+ try {
545
+ return await this.#fetch(url, {
546
+ ...init,
547
+ signal: signal
548
+ ? AbortSignal.any([signal, controller.signal])
549
+ : controller.signal,
167
550
  });
168
- const attempt = retries + 1;
169
- if (attempt < 2) {
170
- return this.doRequest(httpMethod, path, pathTemplate, params, attempt);
171
- }
172
- // throw Error
173
- let errMsg = `FaILED to call ${httpMethod} ${requestUrl}`;
174
- const err = e;
175
- if (err.cause?.message)
176
- errMsg += ` cause by:${err.cause.message}`;
177
- throw new Error(errMsg, { cause: e });
178
551
  }
179
- const data = await this.readBody(res, httpMethod, requestUrl);
180
- switch (res.status) {
181
- case 400:
182
- throw Error(`${httpMethod} ${requestUrl} return Error ${res.status} ${res.statusText}: ${JSON.stringify(data)}`);
183
- case 500:
184
- throw Error(`${httpMethod} ${requestUrl} return Error ${res.status} ${res.statusText}: ${JSON.stringify(data)}`);
185
- case 401:
186
- if (res.statusText === "invalid PVE ticket" ||
187
- res.statusText === "permission denied - invalid PVE ticket") {
188
- this.ticket = undefined;
189
- // A token is not renewable, so do not spend the retry on it.
190
- let attempt = this.username ? retries : 10;
191
- attempt++;
192
- if (attempt < 2)
193
- return this.doRequest(httpMethod, path, pathTemplate, params, attempt);
194
- }
195
- throw Error(`${httpMethod} ${requestUrl} return Error ${res.status} ${res.statusText}: ${JSON.stringify(data)}`);
196
- case 200:
197
- return data.data;
198
- default:
199
- throw Error(`${httpMethod} ${requestUrl} connection failed with ${res.status} ${res.statusText} return: ${JSON.stringify(data)}`);
552
+ catch (cause) {
553
+ throw this.#transportError(cause, exchange);
200
554
  }
201
555
  }
202
556
  /**
203
- * Decode a response into the PVE `{ data, errors }` envelope.
557
+ * Classifies a failure of the connection itself: abort, timeout or other.
558
+ *
559
+ * @param cause - What `fetch` or the body stream failed with.
560
+ * @param exchange - The attempt that failed.
561
+ * @returns A {@link ProxmoxAbortError} when the caller's signal has
562
+ * aborted, else a {@link ProxmoxTimeoutError} when the timer has fired,
563
+ * else a {@link ProxmoxConnectionError}. The last one quotes the most
564
+ * specific message it finds: that of the failure's own `cause`, or else
565
+ * that of the failure.
204
566
  */
205
- async readBody(res, method, requestUrl) {
206
- const contentType = res.headers.get("content-type");
207
- const data = { data: null };
208
- // PVE answers `application/json;charset=UTF-8`, but match on the media
209
- // type alone so a proxy that respaces the parameter is still understood.
210
- if (contentType?.startsWith("application/json")) {
211
- try {
212
- return (await res.json());
213
- }
214
- catch {
215
- data.errors = "Failed to parse response json";
216
- }
567
+ #transportError(cause, exchange) {
568
+ const { request, signal, timeout } = exchange;
569
+ if (signal?.aborted)
570
+ return new ProxmoxAbortError(request, cause);
571
+ if (exchange.timedOut)
572
+ return new ProxmoxTimeoutError(timeout, request);
573
+ const detail = cause?.cause?.message ??
574
+ cause?.message;
575
+ return new ProxmoxConnectionError(`${request.method} ${request.path} could not reach ${this.origin}` +
576
+ (detail ? `: ${detail}` : ""), { cause, request });
577
+ }
578
+ /**
579
+ * Reads the body as text, which can still fail or time out after the
580
+ * headers.
581
+ *
582
+ * @throws A {@link ProxmoxError} for an abort, a timeout or a failed
583
+ * connection if the body cannot be read to its end.
584
+ */
585
+ async #readText(response, exchange) {
586
+ try {
587
+ return await response.text();
588
+ }
589
+ catch (cause) {
590
+ throw this.#transportError(cause, exchange);
217
591
  }
218
- else if (contentType === "application/octet-stream") {
219
- data.data = res.body;
592
+ }
593
+ /**
594
+ * Decodes the body of a success response by its content type.
595
+ *
596
+ * @returns The body stream, unread, for `application/octet-stream`; the
597
+ * `data` field of the envelope for `application/json`, or `null` when
598
+ * it has none; the text for any other type, or `null` when it is empty.
599
+ * @throws A {@link ProxmoxResponseError} if a JSON body does not parse.
600
+ * @throws A {@link ProxmoxError} for an abort, a timeout or a failed
601
+ * connection if the body cannot be read to its end.
602
+ */
603
+ async #readData(response, exchange) {
604
+ const { request } = exchange;
605
+ const type = response.headers.get("content-type") ?? "";
606
+ if (type.startsWith("application/octet-stream"))
607
+ return response.body;
608
+ const text = await this.#readText(response, exchange);
609
+ if (!type.startsWith("application/json"))
610
+ return text === "" ? null : text;
611
+ try {
612
+ return JSON.parse(text).data ?? null;
613
+ }
614
+ catch (cause) {
615
+ throw new ProxmoxResponseError(`${request.method} ${request.path} answered ${response.status} with a body that is not valid JSON`, response.status, { cause, request });
220
616
  }
221
- else if (!contentType) {
222
- data.errors = "";
617
+ }
618
+ /**
619
+ * Builds the error for a non-2xx response.
620
+ *
621
+ * @remarks
622
+ * Proxmox reports the reason in the body's `message` since PVE 8.4, and
623
+ * only in the status line before that - which HTTP/2 and most reverse
624
+ * proxies drop - so both are consulted, body first. A body that is not a
625
+ * JSON object serves as the reason when it is at most 500 characters
626
+ * long. With neither a body nor a status text, the reason is
627
+ * `HTTP <status>`.
628
+ *
629
+ * @returns The {@link ProxmoxApiError} subclass matching the status. Its
630
+ * `body` is the parsed JSON object, or the raw text when the body is
631
+ * not one, or `undefined` when the body is empty.
632
+ * @throws A {@link ProxmoxError} for an abort, a timeout or a failed
633
+ * connection if the body cannot be read to its end.
634
+ */
635
+ async #readError(response, exchange) {
636
+ const { request } = exchange;
637
+ const text = await this.#readText(response, exchange);
638
+ let body = text === "" ? undefined : text;
639
+ let message;
640
+ let errors;
641
+ if (text.startsWith("{")) {
223
642
  try {
224
- data.errors = await res.text();
643
+ const envelope = JSON.parse(text);
644
+ body = envelope;
645
+ if (typeof envelope.message === "string") {
646
+ message = envelope.message.trim();
647
+ }
648
+ if (isRecord(envelope.errors)) {
649
+ errors = Object.fromEntries(Object.entries(envelope.errors).map(([key, value]) => [
650
+ key,
651
+ String(value).trim(),
652
+ ]));
653
+ }
225
654
  }
226
655
  catch {
227
- // ignore reading error;
656
+ // Not JSON after all: `body` keeps the raw text, and the reason falls
657
+ // back to the status line.
228
658
  }
229
659
  }
230
- else {
231
- // should never append
232
- throw Error(`${method} ${requestUrl} unexpected contentType "${contentType}" status Line:${res.status} ${res.statusText}`);
660
+ else if (text.length > 0 && text.length <= 500) {
661
+ message = text.trim();
233
662
  }
234
- return data;
663
+ const details = {
664
+ status: response.status,
665
+ statusText: response.statusText,
666
+ reason: message || response.statusText || `HTTP ${response.status}`,
667
+ errors,
668
+ body,
669
+ request,
670
+ };
671
+ return apiErrorFor(details);
235
672
  }
236
673
  /**
237
- * Echo the request that just failed, as a runnable `curl` line or as the
238
- * `fetch` call that produced it. Only fires when `debug` is set.
674
+ * Builds the headers that authenticate a request.
675
+ *
676
+ * @param method - HTTP method in upper case.
677
+ * @param session - The session to present, for password authentication.
678
+ * @returns The `Authorization` header for token authentication. Otherwise
679
+ * the ticket as a cookie, joined by the CSRF token for every method but
680
+ * `GET`, or nothing without a session.
239
681
  */
240
- logRequest(method, requestUrl, fetchInit, headers, auth) {
241
- if (!this.debug)
242
- return;
243
- if (this.debug === "fetch") {
244
- console.log(`fetch("${requestUrl}", ${JSON.stringify(fetchInit)})`);
245
- return;
246
- }
247
- const credentials = headers.cookie
248
- ? `-H "CSRFPreventionToken: ${auth.CSRFPreventionToken}" --cookie ${JSON.stringify(headers.cookie)}`
249
- : `-H "Authorization: ${auth.ticket}"`;
250
- const data = fetchInit.body
251
- ? `--data ${JSON.stringify(fetchInit.body)}`
252
- : "";
253
- if (method === "POST") {
254
- console.log(`curl -v --insecure ${credentials} ${data} ${requestUrl}`);
255
- }
256
- else if (method === "GET") {
257
- console.log(`curl -v --insecure ${credentials} ${requestUrl}`);
682
+ #authHeaders(method, session) {
683
+ if (this.#authorization)
684
+ return { Authorization: this.#authorization };
685
+ if (!session)
686
+ return {};
687
+ const headers = {
688
+ Cookie: `PVEAuthCookie=${session.ticket}`,
689
+ };
690
+ if (method !== "GET") {
691
+ headers.CSRFPreventionToken = session.CSRFPreventionToken;
258
692
  }
259
- else {
260
- console.log(`curl -v -X ${method} ${credentials} ${data} ${requestUrl}`);
693
+ return headers;
694
+ }
695
+ /**
696
+ * Obtains the session for one request. Stops waiting when the caller
697
+ * aborts, while the login itself carries on for whoever else is waiting on
698
+ * it.
699
+ *
700
+ * @param signal - The caller's signal, if any. An abort that happened
701
+ * before the call goes unnoticed.
702
+ * @param request - The request the session is for, named in the abort
703
+ * error.
704
+ * @returns The cached session, or the one a login produces.
705
+ * @throws A {@link ProxmoxAbortError} if the signal aborts first.
706
+ */
707
+ #sessionFor(signal, request) {
708
+ const session = this.#ensureSession();
709
+ if (!signal)
710
+ return session;
711
+ return new Promise((resolve, reject) => {
712
+ const onAbort = () => reject(new ProxmoxAbortError(request, signal.reason));
713
+ signal.addEventListener("abort", onAbort, { once: true });
714
+ session
715
+ .then(resolve, reject)
716
+ .finally(() => signal.removeEventListener("abort", onAbort));
717
+ });
718
+ }
719
+ /**
720
+ * Returns the cached session while it is less than an hour old, and the
721
+ * outcome of a login otherwise.
722
+ *
723
+ * @remarks
724
+ * One login at a time: concurrent callers share the request in flight,
725
+ * which is why it is bounded by `authTimeout` alone and not by any one
726
+ * caller's signal.
727
+ */
728
+ #ensureSession() {
729
+ const session = this.#session;
730
+ if (session && Date.now() - session.obtainedAt < TICKET_RENEW_AFTER) {
731
+ return Promise.resolve(session);
261
732
  }
733
+ this.#pendingLogin ??= this.#login().finally(() => {
734
+ this.#pendingLogin = undefined;
735
+ });
736
+ return this.#pendingLogin;
262
737
  }
263
738
  /**
264
- * return the current ticket/token, or create new ones, is previous one had been discared, or missing.
265
- * @returns Proxmox API ticket and CSRFPreventionToken
739
+ * Logs in with the username and password, answers a second-factor
740
+ * challenge if Proxmox issues one, and caches the resulting session.
741
+ *
742
+ * @remarks
743
+ * The challenge is answered with a second ticket request that sends the
744
+ * code from the `otp` option as a TOTP response, together with the
745
+ * provisional ticket of the first.
746
+ *
747
+ * @returns The new session, which is also stored on the engine.
748
+ * @throws A {@link ProxmoxAuthenticationError} with `tfaRequired` set if a
749
+ * challenge is issued and the `otp` option yields no code. The errors of
750
+ * the ticket requests and of an `otp` callback pass through.
266
751
  */
267
- async getTicket() {
268
- if (this.ticket) {
269
- if (!this.username)
270
- return { ticket: this.ticket, CSRFPreventionToken: "" };
271
- if (this.CSRFPreventionToken)
272
- return {
273
- ticket: this.ticket,
274
- CSRFPreventionToken: this.CSRFPreventionToken,
275
- };
752
+ async #login() {
753
+ let reply = await this.#requestTicket({
754
+ username: this.#username,
755
+ password: this.#password,
756
+ });
757
+ if (reply.NeedTFA) {
758
+ const otp = typeof this.#otp === "function" ? await this.#otp() : this.#otp;
759
+ if (!otp) {
760
+ throw new ProxmoxAuthenticationError({
761
+ status: 401,
762
+ statusText: "two-factor authentication required",
763
+ reason: `${this.#username} requires a second factor: pass the "otp" option, or use an API token`,
764
+ request: this.#loginRequest(),
765
+ }, true);
766
+ }
767
+ reply = await this.#requestTicket({
768
+ username: this.#username,
769
+ password: `totp:${otp}`,
770
+ "tfa-challenge": reply.ticket,
771
+ });
276
772
  }
277
- // update ticket endpoint
278
- const requestUrl = `${this.schema}://${this.host}/api2/json/access/ticket`;
773
+ this.#session = {
774
+ ticket: reply.ticket,
775
+ CSRFPreventionToken: reply.CSRFPreventionToken,
776
+ obtainedAt: Date.now(),
777
+ };
778
+ return this.#session;
779
+ }
780
+ /**
781
+ * Describes a login request, for the errors it may end in. A login is
782
+ * never retried, so its attempt is always the first.
783
+ */
784
+ #loginRequest() {
785
+ return {
786
+ method: "POST",
787
+ path: TICKET_PATH,
788
+ pathTemplate: TICKET_PATH,
789
+ origin: this.origin,
790
+ attempt: 1,
791
+ };
792
+ }
793
+ /**
794
+ * Posts one set of login parameters to the ticket endpoint.
795
+ *
796
+ * @remarks
797
+ * The request is bounded by `authTimeout`, carries the client's `headers`
798
+ * and no authentication, cannot be aborted by a caller and is not reported
799
+ * to `onEvent`.
800
+ *
801
+ * @param params - Form fields of the login.
802
+ * @returns The reply's ticket and CSRF token. `NeedTFA` is set when the
803
+ * ticket is only a challenge for a second factor.
804
+ * @throws A {@link ProxmoxApiError}, or the subclass matching the status,
805
+ * if Proxmox answers with an error status.
806
+ * @throws A {@link ProxmoxResponseError} if a success carries no ticket
807
+ * and CSRF token, or a JSON body that does not parse.
808
+ * @throws A {@link ProxmoxTimeoutError} if `authTimeout` runs out before
809
+ * the response is complete.
810
+ * @throws A {@link ProxmoxConnectionError} if the connection fails before
811
+ * the response is complete.
812
+ */
813
+ async #requestTicket(params) {
814
+ const request = this.#loginRequest();
815
+ const exchange = this.#begin(request, this.#authTimeout, undefined);
279
816
  try {
280
- const { password, username } = this;
281
- const body = new URLSearchParams({ username, password }).toString();
282
- const headers = {
283
- ...BASE_HEADERS,
284
- "Content-Type": "application/x-www-form-urlencoded",
285
- };
286
- const r = await this.fetch(requestUrl, {
287
- method: "POST",
288
- headers,
289
- signal: AbortSignal.timeout(this.authTimeout),
290
- body,
291
- });
292
- const text = await r.text();
293
- if (r.status !== 200) {
294
- throw Error(`login failed with ${r.status}: ${r.statusText} ${text}`);
817
+ const response = await this.#send(this.#buildRequest("POST", TICKET_PATH, params, this.#headers), exchange);
818
+ if (!response.ok)
819
+ throw await this.#readError(response, exchange);
820
+ const data = await this.#readData(response, exchange);
821
+ if (!isRecord(data) ||
822
+ typeof data.ticket !== "string" ||
823
+ typeof data.CSRFPreventionToken !== "string") {
824
+ throw new ProxmoxResponseError("The login succeeded but the reply carries no ticket", response.status, { request });
295
825
  }
296
- const respObj = JSON.parse(text);
297
- const { CSRFPreventionToken, ticket } = respObj.data;
298
- this.CSRFPreventionToken = CSRFPreventionToken;
299
- this.ticket = ticket;
300
- return { ticket, CSRFPreventionToken };
826
+ return data;
301
827
  }
302
- catch (e) {
303
- throw new Error(`Auth ${requestUrl} Failed!`, { cause: e });
828
+ finally {
829
+ clearTimeout(exchange.timer);
304
830
  }
305
831
  }
306
832
  }
307
- export default ProxmoxEngine;
308
- //# sourceMappingURL=proxmox-engine.js.map