@sourceregistry/openbao-js 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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1828 @@
1
+ 'use strict';
2
+
3
+ // src/utils.ts
4
+ function trimSlashes(value) {
5
+ return value.replace(/^\/+|\/+$/g, "");
6
+ }
7
+ function joinPath(...segments) {
8
+ return segments.filter((s) => s !== void 0 && s !== "").map(
9
+ (s) => trimSlashes(String(s)).split("/").filter(Boolean).map((part) => encodeURIComponent(part)).join("/")
10
+ ).filter(Boolean).join("/");
11
+ }
12
+ function joinFolder(...segments) {
13
+ const p = joinPath(...segments);
14
+ return p.endsWith("/") ? p : `${p}/`;
15
+ }
16
+ function buildQuery(query) {
17
+ if (!query) return "";
18
+ const params = new URLSearchParams();
19
+ for (const [key, value] of Object.entries(query)) {
20
+ if (value === void 0 || value === null) continue;
21
+ if (Array.isArray(value)) {
22
+ for (const v of value) params.append(key, String(v));
23
+ } else {
24
+ params.append(key, String(value));
25
+ }
26
+ }
27
+ const s = params.toString();
28
+ return s ? `?${s}` : "";
29
+ }
30
+ function compact(obj) {
31
+ const out = {};
32
+ for (const [k, v] of Object.entries(obj)) if (v !== void 0) out[k] = v;
33
+ return out;
34
+ }
35
+ var encoder = new TextEncoder();
36
+ var decoder = new TextDecoder();
37
+ function toBase64(input) {
38
+ const bytes = typeof input === "string" ? encoder.encode(input) : input;
39
+ let binary = "";
40
+ const chunk = 32768;
41
+ for (let i = 0; i < bytes.length; i += chunk) {
42
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
43
+ }
44
+ return btoa(binary);
45
+ }
46
+ function fromBase64(b642) {
47
+ const binary = atob(b642);
48
+ const bytes = new Uint8Array(binary.length);
49
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
50
+ return bytes;
51
+ }
52
+ function fromBase64String(b642) {
53
+ return decoder.decode(fromBase64(b642));
54
+ }
55
+ function readEnv(...names) {
56
+ const env = globalThis.process?.env;
57
+ if (!env) return void 0;
58
+ for (const n of names) {
59
+ const v = env[n];
60
+ if (v) return v;
61
+ }
62
+ return void 0;
63
+ }
64
+ function sleep(ms, signal) {
65
+ return new Promise((resolve, reject) => {
66
+ if (signal?.aborted) return reject(signal.reason);
67
+ const t = setTimeout(() => {
68
+ signal?.removeEventListener("abort", onAbort);
69
+ resolve();
70
+ }, ms);
71
+ const onAbort = () => {
72
+ clearTimeout(t);
73
+ reject(signal?.reason);
74
+ };
75
+ signal?.addEventListener("abort", onAbort, { once: true });
76
+ });
77
+ }
78
+
79
+ // src/errors.ts
80
+ var OpenBaoError = class extends Error {
81
+ name = "OpenBaoError";
82
+ /** HTTP status code returned by the server. */
83
+ status;
84
+ /** Error messages from the response body's `errors` array. */
85
+ errors;
86
+ /** Warnings returned alongside the error, if any. */
87
+ warnings;
88
+ /** HTTP method of the failed request. */
89
+ method;
90
+ /** API path of the failed request (relative to `/v1/`). */
91
+ path;
92
+ /** Parsed response body (or raw text when it was not JSON). */
93
+ body;
94
+ constructor(init) {
95
+ const detail = init.errors?.length ? init.errors.join("; ") : `HTTP ${init.status}`;
96
+ super(`${init.method} /v1/${init.path} failed (${init.status}): ${detail}`);
97
+ this.status = init.status;
98
+ this.method = init.method;
99
+ this.path = init.path;
100
+ this.errors = init.errors ?? [];
101
+ this.warnings = init.warnings ?? [];
102
+ this.body = init.body;
103
+ }
104
+ /** `true` for 404 Not Found — e.g. reading a secret that does not exist. */
105
+ get isNotFound() {
106
+ return this.status === 404;
107
+ }
108
+ /** `true` for 403 Forbidden — missing/invalid token or insufficient policy. */
109
+ get isForbidden() {
110
+ return this.status === 403;
111
+ }
112
+ /** `true` when the server reports it is sealed (503 + "sealed" message). */
113
+ get isSealed() {
114
+ return this.status === 503 && this.errors.some((e) => /sealed/i.test(e));
115
+ }
116
+ };
117
+ var OpenBaoConnectionError = class extends Error {
118
+ name = "OpenBaoConnectionError";
119
+ method;
120
+ path;
121
+ /** `true` when the request was aborted because the configured timeout elapsed. */
122
+ timedOut;
123
+ constructor(init) {
124
+ const reason = init.timedOut ? "request timed out" : init.cause instanceof Error ? init.cause.message : String(init.cause);
125
+ super(`${init.method} /v1/${init.path} failed: ${reason}`, { cause: init.cause });
126
+ this.method = init.method;
127
+ this.path = init.path;
128
+ this.timedOut = init.timedOut ?? false;
129
+ }
130
+ };
131
+ function isOpenBaoError(err) {
132
+ return err instanceof OpenBaoError;
133
+ }
134
+ function isNotFound(err) {
135
+ return err instanceof OpenBaoError && err.status === 404;
136
+ }
137
+
138
+ // src/api/base.ts
139
+ function unwrapData(res) {
140
+ if (res && typeof res === "object" && "data" in res && res.data != null) {
141
+ return res.data;
142
+ }
143
+ return res;
144
+ }
145
+ var MountedApi = class {
146
+ constructor(client, mount) {
147
+ this.client = client;
148
+ this.mount = trimSlashes(mount);
149
+ }
150
+ client;
151
+ /** Mount path without surrounding slashes, e.g. `secret` or `auth/approle`. */
152
+ mount;
153
+ /** Builds `<mount>/<...segments>` with each segment URL-encoded. */
154
+ path(...segments) {
155
+ return joinPath(this.mount, ...segments);
156
+ }
157
+ };
158
+ var AuthMethodApi = class extends MountedApi {
159
+ constructor(client, mount) {
160
+ super(client, `auth/${trimSlashes(mount).replace(/^auth\//, "")}`);
161
+ }
162
+ /** @internal */
163
+ async doLogin(path, body, opts = {}) {
164
+ const { setToken = true, ...call } = opts;
165
+ const res = await this.client.request({
166
+ ...call,
167
+ method: "POST",
168
+ path,
169
+ body,
170
+ token: null
171
+ });
172
+ if (!res?.auth) {
173
+ throw new Error(`Login at ${path} returned no auth block${res?.warnings?.length ? `: ${res.warnings.join("; ")}` : ""}`);
174
+ }
175
+ if (setToken) this.client.token = res.auth.client_token;
176
+ return res.auth;
177
+ }
178
+ };
179
+ var Resource = class {
180
+ constructor(client, basePath) {
181
+ this.client = client;
182
+ this.basePath = basePath;
183
+ }
184
+ client;
185
+ basePath;
186
+ /** Lists item names. Returns `[]` when the collection is empty. */
187
+ async list(opts) {
188
+ return (await this.client.list(`${trimSlashes(this.basePath)}/`, opts)).keys;
189
+ }
190
+ /** Reads an item. Throws `OpenBaoError` (404) when it does not exist. */
191
+ async read(name, opts) {
192
+ return unwrapData(await this.client.read(joinPath(this.basePath, name), opts));
193
+ }
194
+ /** Creates or updates an item. */
195
+ async write(name, data, opts) {
196
+ await this.client.write(joinPath(this.basePath, name), compact(data), opts);
197
+ }
198
+ async delete(name, opts) {
199
+ await this.client.delete(joinPath(this.basePath, name), opts);
200
+ }
201
+ /** `true` when the item exists. */
202
+ async exists(name, opts) {
203
+ try {
204
+ await this.read(name, opts);
205
+ return true;
206
+ } catch (err) {
207
+ if (err instanceof OpenBaoError && err.status === 404) return false;
208
+ throw err;
209
+ }
210
+ }
211
+ };
212
+ async function postData(client, path, body, opts) {
213
+ const res = await client.write(path, body, opts);
214
+ if (res === void 0) throw new Error(`POST /v1/${path} returned no content`);
215
+ return unwrapData(res);
216
+ }
217
+ async function getData(client, path, opts) {
218
+ return unwrapData(await client.read(path, opts));
219
+ }
220
+
221
+ // src/api/auth.ts
222
+ var TokenAuth = class extends MountedApi {
223
+ /** Token roles (`auth/token/roles/:name`). */
224
+ roles;
225
+ constructor(client) {
226
+ super(client, "auth/token");
227
+ this.roles = new Resource(client, this.path("roles"));
228
+ }
229
+ /**
230
+ * Creates a token. Does **not** change the client's token — use
231
+ * `bao.withToken(auth.client_token)` to act as it.
232
+ */
233
+ async create(options = {}, opts) {
234
+ const { role_name, ...body } = options;
235
+ return this.authOf(await this.client.write(this.path("create", role_name), compact(body), opts));
236
+ }
237
+ /** Creates an orphan token (no parent). */
238
+ async createOrphan(options = {}, opts) {
239
+ return this.authOf(await this.client.write(this.path("create-orphan"), compact(options), opts));
240
+ }
241
+ /** Looks up the client's own token. */
242
+ lookupSelf(opts) {
243
+ return getData(this.client, this.path("lookup-self"), opts);
244
+ }
245
+ lookup(token, opts) {
246
+ return postData(this.client, this.path("lookup"), { token }, opts);
247
+ }
248
+ lookupAccessor(accessor, opts) {
249
+ return postData(this.client, this.path("lookup-accessor"), { accessor }, opts);
250
+ }
251
+ /** Renews the client's own token. */
252
+ async renewSelf(increment, opts) {
253
+ return this.authOf(await this.client.write(this.path("renew-self"), compact({ increment }), opts));
254
+ }
255
+ async renew(token, increment, opts) {
256
+ return this.authOf(await this.client.write(this.path("renew"), compact({ token, increment }), opts));
257
+ }
258
+ async renewAccessor(accessor, increment, opts) {
259
+ return this.authOf(await this.client.write(this.path("renew-accessor"), compact({ accessor, increment }), opts));
260
+ }
261
+ /** Revokes the client's own token and clears it from the client. */
262
+ async revokeSelf(opts) {
263
+ await this.client.write(this.path("revoke-self"), {}, opts);
264
+ if (opts?.token === void 0) this.client.token = void 0;
265
+ }
266
+ async revoke(token, opts) {
267
+ await this.client.write(this.path("revoke"), { token }, opts);
268
+ }
269
+ async revokeAccessor(accessor, opts) {
270
+ await this.client.write(this.path("revoke-accessor"), { accessor }, opts);
271
+ }
272
+ /** Revokes a token but leaves its children as orphans. Requires `sudo`. */
273
+ async revokeOrphan(token, opts) {
274
+ await this.client.write(this.path("revoke-orphan"), { token }, opts);
275
+ }
276
+ /** Lists token accessors. Requires `sudo`. */
277
+ async listAccessors(opts) {
278
+ return (await this.client.list(`${this.path("accessors")}/`, opts)).keys;
279
+ }
280
+ async tidy(opts) {
281
+ await this.client.write(this.path("tidy"), {}, opts);
282
+ }
283
+ /**
284
+ * Keeps the client's token alive by renewing it at ~2/3 of its TTL.
285
+ * Returns a handle with `stop()`. Timers are `unref`'d so they never keep a
286
+ * Node.js process alive. Stops automatically when the token is not renewable
287
+ * or reaches its max TTL.
288
+ */
289
+ keepAlive(options = {}) {
290
+ let timer;
291
+ let stopped = false;
292
+ const schedule = (ttlSeconds) => {
293
+ if (stopped || ttlSeconds <= 0) return;
294
+ timer = setTimeout(tick, Math.max(1, ttlSeconds * (2 / 3)) * 1e3);
295
+ timer.unref?.();
296
+ };
297
+ const tick = async () => {
298
+ try {
299
+ const auth = await this.renewSelf(options.increment);
300
+ options.onRenew?.(auth);
301
+ if (auth.renewable) schedule(auth.lease_duration);
302
+ } catch (err) {
303
+ options.onError?.(err);
304
+ }
305
+ };
306
+ this.lookupSelf().then((info) => {
307
+ if (info.renewable) schedule(info.ttl);
308
+ }).catch((err) => options.onError?.(err));
309
+ return {
310
+ stop: () => {
311
+ stopped = true;
312
+ if (timer) clearTimeout(timer);
313
+ }
314
+ };
315
+ }
316
+ authOf(res) {
317
+ if (!res?.auth) throw new Error("Token endpoint returned no auth block");
318
+ return res.auth;
319
+ }
320
+ };
321
+ var AppRoleAuth = class extends AuthMethodApi {
322
+ /** Role definitions (`auth/<mount>/role/:name`). */
323
+ roles;
324
+ constructor(client, mount = "approle") {
325
+ super(client, mount);
326
+ this.roles = new Resource(client, this.path("role"));
327
+ }
328
+ /** Logs in. The returned token is stored on the client unless `setToken: false`. */
329
+ login(roleId, secretId, opts) {
330
+ return this.doLogin(this.path("login"), compact({ role_id: roleId, secret_id: secretId }), opts);
331
+ }
332
+ async readRoleId(role, opts) {
333
+ return (await getData(this.client, this.path("role", role, "role-id"), opts)).role_id;
334
+ }
335
+ async setRoleId(role, roleId, opts) {
336
+ await this.client.write(this.path("role", role, "role-id"), { role_id: roleId }, opts);
337
+ }
338
+ /** Generates a new secret-id. */
339
+ generateSecretId(role, options = {}, opts) {
340
+ return postData(this.client, this.path("role", role, "secret-id"), this.secretIdBody(options), opts);
341
+ }
342
+ /**
343
+ * Generates a secret-id wrapped in a single-use response-wrapping token —
344
+ * the recommended way to hand secret-ids to workloads.
345
+ */
346
+ async generateWrappedSecretId(role, wrapTTL = "5m", options = {}, opts) {
347
+ const res = await this.client.write(this.path("role", role, "secret-id"), this.secretIdBody(options), { ...opts, wrapTTL });
348
+ if (!res?.wrap_info) throw new Error("Expected a wrapped response");
349
+ return res.wrap_info;
350
+ }
351
+ /** Lists secret-id accessors for a role. */
352
+ async listSecretIdAccessors(role, opts) {
353
+ return (await this.client.list(`${this.path("role", role, "secret-id")}/`, opts)).keys;
354
+ }
355
+ async lookupSecretId(role, secretId, opts) {
356
+ return (await this.client.write(this.path("role", role, "secret-id", "lookup"), { secret_id: secretId }, opts))?.data;
357
+ }
358
+ async destroySecretId(role, secretId, opts) {
359
+ await this.client.write(this.path("role", role, "secret-id", "destroy"), { secret_id: secretId }, opts);
360
+ }
361
+ async lookupSecretIdAccessor(role, accessor, opts) {
362
+ return (await this.client.write(this.path("role", role, "secret-id-accessor", "lookup"), { secret_id_accessor: accessor }, opts))?.data;
363
+ }
364
+ async destroySecretIdAccessor(role, accessor, opts) {
365
+ await this.client.write(this.path("role", role, "secret-id-accessor", "destroy"), { secret_id_accessor: accessor }, opts);
366
+ }
367
+ async tidySecretIds(opts) {
368
+ await this.client.write(this.path("tidy", "secret-id"), {}, opts);
369
+ }
370
+ secretIdBody(o) {
371
+ return compact({ ...o, metadata: o.metadata ? JSON.stringify(o.metadata) : void 0 });
372
+ }
373
+ };
374
+ var UserpassAuth = class extends AuthMethodApi {
375
+ users;
376
+ constructor(client, mount = "userpass") {
377
+ super(client, mount);
378
+ this.users = new Resource(client, this.path("users"));
379
+ }
380
+ login(username, password, opts) {
381
+ return this.doLogin(this.path("login", username), { password }, opts);
382
+ }
383
+ async setPassword(username, password, opts) {
384
+ await this.client.write(this.path("users", username, "password"), { password }, opts);
385
+ }
386
+ async setPolicies(username, policies, opts) {
387
+ await this.client.write(this.path("users", username, "policies"), { token_policies: policies }, opts);
388
+ }
389
+ };
390
+ var LdapAuth = class extends AuthMethodApi {
391
+ users;
392
+ groups;
393
+ constructor(client, mount = "ldap") {
394
+ super(client, mount);
395
+ this.users = new Resource(client, this.path("users"));
396
+ this.groups = new Resource(client, this.path("groups"));
397
+ }
398
+ login(username, password, opts) {
399
+ return this.doLogin(this.path("login", username), { password }, opts);
400
+ }
401
+ readConfig(opts) {
402
+ return getData(this.client, this.path("config"), opts);
403
+ }
404
+ async writeConfig(config, opts) {
405
+ await this.client.write(this.path("config"), compact(config), opts);
406
+ }
407
+ };
408
+ var JwtAuth = class extends AuthMethodApi {
409
+ roles;
410
+ constructor(client, mount = "jwt") {
411
+ super(client, mount);
412
+ this.roles = new Resource(client, this.path("role"));
413
+ }
414
+ /** Logs in with a signed JWT (e.g. a GitHub Actions / Kubernetes / CI token). */
415
+ login(jwt, role, opts) {
416
+ return this.doLogin(this.path("login"), compact({ jwt, role }), opts);
417
+ }
418
+ readConfig(opts) {
419
+ return getData(this.client, this.path("config"), opts);
420
+ }
421
+ async writeConfig(config, opts) {
422
+ await this.client.write(this.path("config"), compact(config), opts);
423
+ }
424
+ /** Step 1 of the OIDC browser flow: obtain the provider authorization URL. */
425
+ async oidcAuthUrl(redirectUri, options = {}) {
426
+ const { role, client_nonce, ...opts } = options;
427
+ const res = await postData(this.client, this.path("oidc", "auth_url"), compact({ role, redirect_uri: redirectUri, client_nonce }), { token: null, ...opts });
428
+ return res.auth_url;
429
+ }
430
+ /** Step 2 of the OIDC browser flow: exchange the callback parameters for a token. */
431
+ async oidcCallback(params, opts = {}) {
432
+ const { setToken = true, ...call } = opts;
433
+ const res = await this.client.request({ ...call, method: "GET", path: this.path("oidc", "callback"), query: params, token: null });
434
+ if (!res?.auth) throw new Error("OIDC callback returned no auth block");
435
+ if (setToken) this.client.token = res.auth.client_token;
436
+ return res.auth;
437
+ }
438
+ };
439
+ var KubernetesAuth = class extends AuthMethodApi {
440
+ roles;
441
+ constructor(client, mount = "kubernetes") {
442
+ super(client, mount);
443
+ this.roles = new Resource(client, this.path("role"));
444
+ }
445
+ login(role, jwt, opts) {
446
+ return this.doLogin(this.path("login"), { role, jwt }, opts);
447
+ }
448
+ /**
449
+ * Logs in with the pod's projected service-account token (Node.js only).
450
+ * @param tokenPath defaults to `/var/run/secrets/kubernetes.io/serviceaccount/token`
451
+ */
452
+ async loginWithServiceAccount(role, tokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token", opts) {
453
+ const { readFile } = await import('fs/promises');
454
+ const jwt = (await readFile(tokenPath, "utf8")).trim();
455
+ return this.login(role, jwt, opts);
456
+ }
457
+ readConfig(opts) {
458
+ return getData(this.client, this.path("config"), opts);
459
+ }
460
+ async writeConfig(config, opts) {
461
+ await this.client.write(this.path("config"), compact(config), opts);
462
+ }
463
+ };
464
+ var CertAuth = class extends AuthMethodApi {
465
+ certs;
466
+ constructor(client, mount = "cert") {
467
+ super(client, mount);
468
+ this.certs = new Resource(client, this.path("certs"));
469
+ }
470
+ login(name, opts) {
471
+ return this.doLogin(this.path("login"), compact({ name }), opts);
472
+ }
473
+ };
474
+ var RadiusAuth = class extends AuthMethodApi {
475
+ users;
476
+ constructor(client, mount = "radius") {
477
+ super(client, mount);
478
+ this.users = new Resource(client, this.path("users"));
479
+ }
480
+ login(username, password, opts) {
481
+ return this.doLogin(this.path("login", username), { password }, opts);
482
+ }
483
+ async writeConfig(config, opts) {
484
+ await this.client.write(this.path("config"), compact(config), opts);
485
+ }
486
+ };
487
+ var KerberosAuth = class extends AuthMethodApi {
488
+ constructor(client, mount = "kerberos") {
489
+ super(client, mount);
490
+ }
491
+ /** Logs in with a base64 SPNEGO token (sent as `Authorization: Negotiate <token>`). */
492
+ login(spnegoToken, opts = {}) {
493
+ return this.doLogin(this.path("login"), {}, { ...opts, headers: { ...opts.headers, Authorization: `Negotiate ${spnegoToken}` } });
494
+ }
495
+ };
496
+ var GenericAuth = class extends AuthMethodApi {
497
+ login(body, options = {}) {
498
+ const { path = "login", ...opts } = options;
499
+ return this.doLogin(this.path(path), body, opts);
500
+ }
501
+ };
502
+ var Auth = class {
503
+ constructor(client) {
504
+ this.client = client;
505
+ this.token = new TokenAuth(client);
506
+ }
507
+ client;
508
+ token;
509
+ approle(mount = "approle") {
510
+ return new AppRoleAuth(this.client, mount);
511
+ }
512
+ userpass(mount = "userpass") {
513
+ return new UserpassAuth(this.client, mount);
514
+ }
515
+ ldap(mount = "ldap") {
516
+ return new LdapAuth(this.client, mount);
517
+ }
518
+ jwt(mount = "jwt") {
519
+ return new JwtAuth(this.client, mount);
520
+ }
521
+ oidc(mount = "oidc") {
522
+ return new JwtAuth(this.client, mount);
523
+ }
524
+ kubernetes(mount = "kubernetes") {
525
+ return new KubernetesAuth(this.client, mount);
526
+ }
527
+ cert(mount = "cert") {
528
+ return new CertAuth(this.client, mount);
529
+ }
530
+ radius(mount = "radius") {
531
+ return new RadiusAuth(this.client, mount);
532
+ }
533
+ kerberos(mount = "kerberos") {
534
+ return new KerberosAuth(this.client, mount);
535
+ }
536
+ /** Generic accessor for any mounted auth method. */
537
+ method(mount) {
538
+ return new GenericAuth(this.client, mount);
539
+ }
540
+ };
541
+
542
+ // src/api/secrets/database.ts
543
+ var Database = class extends MountedApi {
544
+ /** Connection configurations (`<mount>/config/:name`). */
545
+ connections;
546
+ /** Dynamic roles (`<mount>/roles/:name`). */
547
+ roles;
548
+ /** Static roles (`<mount>/static-roles/:name`). */
549
+ staticRoles;
550
+ constructor(client, mount = "database") {
551
+ super(client, mount);
552
+ this.connections = new Resource(client, this.path("config"));
553
+ this.roles = new Resource(client, this.path("roles"));
554
+ this.staticRoles = new Resource(client, this.path("static-roles"));
555
+ }
556
+ /**
557
+ * Generates dynamic credentials. Returns the full envelope so you can manage
558
+ * the lease (`lease_id`, `lease_duration`) via `sys.leases`.
559
+ */
560
+ creds(role, opts) {
561
+ return this.client.read(this.path("creds", role), opts);
562
+ }
563
+ /** Reads the current password of a static role. */
564
+ staticCreds(role, opts) {
565
+ return getData(this.client, this.path("static-creds", role), opts);
566
+ }
567
+ async rotateRoot(connection, opts) {
568
+ await this.client.write(this.path("rotate-root", connection), {}, opts);
569
+ }
570
+ async rotateStaticRole(role, opts) {
571
+ await this.client.write(this.path("rotate-role", role), {}, opts);
572
+ }
573
+ /** Closes and reloads a connection (`<mount>/reset/:name`). */
574
+ async resetConnection(connection, opts) {
575
+ await this.client.write(joinPath(this.mount, "reset", connection), {}, opts);
576
+ }
577
+ };
578
+
579
+ // src/api/secrets/kv.ts
580
+ var KvV1 = class extends MountedApi {
581
+ constructor(client, mount = "kv") {
582
+ super(client, mount);
583
+ }
584
+ /** Reads a secret. Throws `OpenBaoError` (404) if it does not exist. */
585
+ async get(path, opts) {
586
+ return (await this.client.read(this.path(path), opts)).data;
587
+ }
588
+ /** Creates or replaces a secret. */
589
+ async set(path, data, opts) {
590
+ await this.client.write(this.path(path), data, opts);
591
+ }
592
+ async delete(path, opts) {
593
+ await this.client.delete(this.path(path), opts);
594
+ }
595
+ /** Lists keys under a folder. Folders end with `/`. */
596
+ async list(path = "", opts) {
597
+ return (await this.client.list(`${this.path(path)}/`, opts)).keys;
598
+ }
599
+ };
600
+ var KvV2 = class extends MountedApi {
601
+ constructor(client, mount = "secret") {
602
+ super(client, mount);
603
+ }
604
+ /** Reads the latest (or a specific) version of a secret with its metadata. */
605
+ async read(path, options = {}) {
606
+ const { version, ...opts } = options;
607
+ const res = await this.client.read(this.path("data", path), { ...opts, query: { version } });
608
+ return res.data;
609
+ }
610
+ /** Reads just the secret payload. Throws `OpenBaoError` (404) when missing or deleted. */
611
+ async get(path, options = {}) {
612
+ const secret = await this.read(path, options);
613
+ if (secret.data == null) {
614
+ throw new OpenBaoError({ status: 404, method: "GET", path: this.path("data", path), errors: ["secret version is deleted or destroyed"] });
615
+ }
616
+ return secret.data;
617
+ }
618
+ /**
619
+ * Writes a new version. Pass `cas` for check-and-set (`0` = only create if absent).
620
+ * Returns metadata for the new version.
621
+ */
622
+ async write(path, data, options = {}) {
623
+ const { cas, ...opts } = options;
624
+ const body = cas === void 0 ? { data } : { options: { cas }, data };
625
+ return unwrapData(await this.client.write(this.path("data", path), body, opts));
626
+ }
627
+ /** Alias of {@link write}. */
628
+ set(path, data, options = {}) {
629
+ return this.write(path, data, options);
630
+ }
631
+ /**
632
+ * JSON merge-patches the latest version (keys set to `null` are removed).
633
+ * Requires the `patch` capability.
634
+ */
635
+ async patch(path, data, options = {}) {
636
+ const { cas, ...opts } = options;
637
+ const body = cas === void 0 ? { data } : { options: { cas }, data };
638
+ return unwrapData(await this.client.patch(this.path("data", path), body, opts));
639
+ }
640
+ /** Returns the key structure of a secret (values replaced by `null`). */
641
+ async subkeys(path, options = {}) {
642
+ const { version, depth, ...opts } = options;
643
+ return (await this.client.read(this.path("subkeys", path), { ...opts, query: { version, depth } })).data;
644
+ }
645
+ /** Soft-deletes the latest version (recoverable with {@link undelete}). */
646
+ async delete(path, opts) {
647
+ await this.client.delete(this.path("data", path), opts);
648
+ }
649
+ /** Soft-deletes specific versions. */
650
+ async deleteVersions(path, versions, opts) {
651
+ await this.client.write(this.path("delete", path), { versions }, opts);
652
+ }
653
+ async undelete(path, versions, opts) {
654
+ await this.client.write(this.path("undelete", path), { versions }, opts);
655
+ }
656
+ /** Permanently destroys versions' data. */
657
+ async destroy(path, versions, opts) {
658
+ await this.client.request({ ...opts, method: "PUT", path: this.path("destroy", path), body: { versions } });
659
+ }
660
+ /** Lists keys under a folder (folders end with `/`). Returns `[]` for empty/missing folders. */
661
+ async list(path = "", opts) {
662
+ return (await this.client.list(`${this.path("metadata", path)}/`, opts)).keys;
663
+ }
664
+ /** Recursively lists every key under a folder (OpenBao `SCAN`). */
665
+ async scan(path = "", opts) {
666
+ return (await this.client.scan(`${this.path("metadata", path)}/`, opts)).keys;
667
+ }
668
+ /** Lists keys together with their full metadata (OpenBao `detailed-metadata`). */
669
+ async listDetailed(path = "", opts) {
670
+ return this.client.list(`${this.path("detailed-metadata", path)}/`, opts);
671
+ }
672
+ async readMetadata(path, opts) {
673
+ return (await this.client.read(this.path("metadata", path), opts)).data;
674
+ }
675
+ async writeMetadata(path, metadata, opts) {
676
+ await this.client.write(this.path("metadata", path), compact(metadata), opts);
677
+ }
678
+ async patchMetadata(path, metadata, opts) {
679
+ await this.client.patch(this.path("metadata", path), compact(metadata), opts);
680
+ }
681
+ /** Permanently deletes the key, all versions and metadata. */
682
+ async deleteMetadata(path, opts) {
683
+ await this.client.delete(this.path("metadata", path), opts);
684
+ }
685
+ async readConfig(opts) {
686
+ return (await this.client.read(this.path("config"), opts)).data;
687
+ }
688
+ async writeConfig(config, opts) {
689
+ await this.client.write(this.path("config"), compact(config), opts);
690
+ }
691
+ };
692
+ var Cubbyhole = class extends KvV1 {
693
+ constructor(client) {
694
+ super(client, "cubbyhole");
695
+ }
696
+ };
697
+
698
+ // src/api/secrets/misc.ts
699
+ var Totp = class extends MountedApi {
700
+ constructor(client, mount = "totp") {
701
+ super(client, mount);
702
+ }
703
+ /** Creates a key. When `generate` and `exported` are set, returns the provisioning `url` and base64 PNG `barcode`. */
704
+ async createKey(name, options, opts) {
705
+ const res = await this.client.write(this.path("keys", name), compact(options), opts);
706
+ return res?.data ?? {};
707
+ }
708
+ readKey(name, opts) {
709
+ return getData(this.client, this.path("keys", name), opts);
710
+ }
711
+ async listKeys(opts) {
712
+ return (await this.client.list(`${this.path("keys")}/`, opts)).keys;
713
+ }
714
+ async deleteKey(name, opts) {
715
+ await this.client.delete(this.path("keys", name), opts);
716
+ }
717
+ /** Generates the current code (only for keys created with `generate: true`). */
718
+ async code(name, opts) {
719
+ return (await getData(this.client, this.path("code", name), opts)).code;
720
+ }
721
+ async validate(name, code, opts) {
722
+ return (await postData(this.client, this.path("code", name), { code }, opts)).valid;
723
+ }
724
+ };
725
+ var Ssh = class extends MountedApi {
726
+ roles;
727
+ constructor(client, mount = "ssh") {
728
+ super(client, mount);
729
+ this.roles = new Resource(client, this.path("roles"));
730
+ }
731
+ /** Configures the signing CA. With no keys given, one is generated. Returns the CA public key. */
732
+ async configureCa(options = { generate_signing_key: true }, opts) {
733
+ const res = await this.client.write(this.path("config", "ca"), compact(options), opts);
734
+ return res?.data?.public_key;
735
+ }
736
+ async readCaPublicKey(opts) {
737
+ return (await getData(this.client, this.path("config", "ca"), opts)).public_key;
738
+ }
739
+ async deleteCa(opts) {
740
+ await this.client.delete(this.path("config", "ca"), opts);
741
+ }
742
+ /** Signs an SSH public key. */
743
+ sign(role, publicKey, options = {}, opts) {
744
+ const valid_principals = Array.isArray(options.valid_principals) ? options.valid_principals.join(",") : options.valid_principals;
745
+ return postData(this.client, this.path("sign", role), compact({ ...options, valid_principals, public_key: publicKey }), opts);
746
+ }
747
+ /** Generates a key pair and signs it. */
748
+ issue(role, options = {}, opts) {
749
+ const valid_principals = Array.isArray(options.valid_principals) ? options.valid_principals.join(",") : options.valid_principals;
750
+ return postData(this.client, this.path("issue", role), compact({ ...options, valid_principals }), opts);
751
+ }
752
+ /** Creates an OTP credential for an OTP role. */
753
+ otp(role, ip, username, opts) {
754
+ return postData(this.client, this.path("creds", role), compact({ ip, username }), opts);
755
+ }
756
+ verifyOtp(otp, opts) {
757
+ return postData(this.client, this.path("verify"), { otp }, opts);
758
+ }
759
+ };
760
+ var IdentityCollection = class {
761
+ constructor(client, kind) {
762
+ this.client = client;
763
+ this.kind = kind;
764
+ this.byName = new Resource(client, `identity/${kind}/name`);
765
+ this.byId = new Resource(client, `identity/${kind}/id`);
766
+ }
767
+ client;
768
+ kind;
769
+ /** Access by name (`identity/<kind>/name/:name`). */
770
+ byName;
771
+ /** Access by id (`identity/<kind>/id/:id`). */
772
+ byId;
773
+ /** Creates (or updates, when `id` is given) and returns `{ id, name }`. */
774
+ async create(input, opts) {
775
+ const res = await this.client.write(`identity/${this.kind}`, compact(input), opts);
776
+ return res?.data;
777
+ }
778
+ };
779
+ var Identity = class {
780
+ constructor(client) {
781
+ this.client = client;
782
+ this.entities = new IdentityCollection(client, "entity");
783
+ this.groups = new IdentityCollection(client, "group");
784
+ this.entityAliases = new Resource(client, "identity/entity-alias/id");
785
+ this.groupAliases = new Resource(client, "identity/group-alias/id");
786
+ }
787
+ client;
788
+ entities;
789
+ groups;
790
+ /** Entity aliases (`identity/entity-alias/id/:id`). */
791
+ entityAliases;
792
+ /** Group aliases (`identity/group-alias/id/:id`). */
793
+ groupAliases;
794
+ /** Creates an entity alias linking an auth-method identity to an entity. */
795
+ async createEntityAlias(input, opts) {
796
+ return (await this.client.write("identity/entity-alias", compact(input), opts))?.data;
797
+ }
798
+ async createGroupAlias(input, opts) {
799
+ return (await this.client.write("identity/group-alias", compact(input), opts))?.data;
800
+ }
801
+ /** Merges entities into `toEntityId`. */
802
+ async mergeEntities(fromEntityIds, toEntityId, options = {}, opts) {
803
+ await this.client.write("identity/entity/merge", compact({ from_entity_ids: fromEntityIds, to_entity_id: toEntityId, force: options.force }), opts);
804
+ }
805
+ /** Looks up an entity by `name`, `id`, `alias_id`, or `alias_name` + `alias_mount_accessor`. Returns `undefined` when not found. */
806
+ async lookupEntity(criteria, opts) {
807
+ return (await this.client.write("identity/lookup/entity", compact(criteria), opts))?.data;
808
+ }
809
+ async lookupGroup(criteria, opts) {
810
+ return (await this.client.write("identity/lookup/group", compact(criteria), opts))?.data;
811
+ }
812
+ /** Generates a signed OIDC identity token for the calling entity. */
813
+ oidcToken(role, opts) {
814
+ return getData(this.client, `identity/oidc/token/${encodeURIComponent(role)}`, opts);
815
+ }
816
+ async introspectOidcToken(token, clientId, opts) {
817
+ const res = await this.client.request({
818
+ ...opts,
819
+ method: "POST",
820
+ path: "identity/oidc/introspect",
821
+ body: compact({ token, client_id: clientId })
822
+ });
823
+ return res;
824
+ }
825
+ };
826
+
827
+ // src/api/secrets/pki.ts
828
+ var toList = (v) => Array.isArray(v) ? v.join(",") : v;
829
+ function normalizeSans(req) {
830
+ return compact({
831
+ ...req,
832
+ alt_names: toList(req.alt_names),
833
+ ip_sans: toList(req.ip_sans),
834
+ uri_sans: toList(req.uri_sans),
835
+ other_sans: toList(req.other_sans)
836
+ });
837
+ }
838
+ var Pki = class extends MountedApi {
839
+ /** Role definitions (`<mount>/roles/:name`). */
840
+ roles;
841
+ constructor(client, mount = "pki") {
842
+ super(client, mount);
843
+ this.roles = new Resource(client, this.path("roles"));
844
+ }
845
+ /** Issues a certificate (and private key) against a role. */
846
+ issue(role, request, opts) {
847
+ return postData(this.client, this.path("issue", role), normalizeSans(request), opts);
848
+ }
849
+ /** Signs a CSR against a role. */
850
+ sign(role, csr, request = {}, opts) {
851
+ return postData(this.client, this.path("sign", role), normalizeSans({ ...request, csr }), opts);
852
+ }
853
+ /** Signs a CSR verbatim (bypasses role restrictions; requires sudo-like policy). */
854
+ signVerbatim(csr, request = {}, opts) {
855
+ const { role, ...rest } = request;
856
+ return postData(this.client, this.path("sign-verbatim", role), normalizeSans({ ...rest, csr }), opts);
857
+ }
858
+ async revoke(serialNumber, opts) {
859
+ return postData(this.client, this.path("revoke"), { serial_number: serialNumber }, opts);
860
+ }
861
+ /** Reads a certificate by serial (`ca`, `crl`, `ca_chain` are also accepted). */
862
+ async readCert(serial, opts) {
863
+ return getData(this.client, this.path("cert", serial), opts);
864
+ }
865
+ async listCerts(opts) {
866
+ return (await this.client.list(`${this.path("certs")}/`, opts)).keys;
867
+ }
868
+ async listRevokedCerts(opts) {
869
+ return (await this.client.list(`${this.path("certs", "revoked")}/`, opts)).keys;
870
+ }
871
+ /** Default issuer's CA certificate as PEM. Unauthenticated. */
872
+ caPem(opts) {
873
+ return this.client.request({ ...opts, method: "GET", path: this.path("ca", "pem"), responseType: "text", token: null });
874
+ }
875
+ /** Default issuer's CA chain as PEM. Unauthenticated. */
876
+ caChainPem(opts) {
877
+ return this.client.request({ ...opts, method: "GET", path: this.path("ca_chain"), responseType: "text", token: null });
878
+ }
879
+ /** Current CRL as PEM. Unauthenticated. */
880
+ crlPem(opts) {
881
+ return this.client.request({ ...opts, method: "GET", path: this.path("crl", "pem"), responseType: "text", token: null });
882
+ }
883
+ // ------------------------------------------------------------ CA lifecycle
884
+ /** Generates a self-signed root. `type: 'exported'` returns the private key. */
885
+ generateRoot(options, opts) {
886
+ const { type = "internal", ...body } = options;
887
+ return postData(this.client, this.path("root", "generate", type), compact(body), opts);
888
+ }
889
+ /** Generates an intermediate CSR. */
890
+ generateIntermediate(options, opts) {
891
+ const { type = "internal", ...body } = options;
892
+ return postData(this.client, this.path("intermediate", "generate", type), compact(body), opts);
893
+ }
894
+ /** Signs an intermediate CSR with this mount's root. */
895
+ signIntermediate(csr, options = {}, opts) {
896
+ return postData(this.client, this.path("root", "sign-intermediate"), compact({ ...options, csr }), opts);
897
+ }
898
+ /** Imports the signed intermediate certificate. */
899
+ async setSignedIntermediate(certificate, opts) {
900
+ await this.client.write(this.path("intermediate", "set-signed"), { certificate }, opts);
901
+ }
902
+ /** Imports a PEM bundle (certificate and/or key). */
903
+ async importBundle(pemBundle, opts) {
904
+ const res = await this.client.write(this.path("config", "ca"), { pem_bundle: pemBundle }, opts);
905
+ return res?.data;
906
+ }
907
+ async deleteRoot(opts) {
908
+ await this.client.delete(this.path("root"), opts);
909
+ }
910
+ // ------------------------------------------------------------ issuers & config
911
+ async listIssuers(opts) {
912
+ return this.client.list(`${this.path("issuers")}/`, opts);
913
+ }
914
+ readIssuer(ref = "default", opts) {
915
+ return getData(this.client, this.path("issuer", ref), opts);
916
+ }
917
+ async updateIssuer(ref, config, opts) {
918
+ await this.client.write(this.path("issuer", ref), compact(config), opts);
919
+ }
920
+ async setUrls(urls, opts) {
921
+ await this.client.write(this.path("config", "urls"), compact(urls), opts);
922
+ }
923
+ readUrls(opts) {
924
+ return getData(this.client, this.path("config", "urls"), opts);
925
+ }
926
+ async rotateCrl(opts) {
927
+ await this.client.read(this.path("crl", "rotate"), opts);
928
+ }
929
+ async tidy(options = { tidy_cert_store: true, tidy_revoked_certs: true }, opts) {
930
+ await this.client.write(this.path("tidy"), compact(options), opts);
931
+ }
932
+ };
933
+
934
+ // src/api/secrets/transit.ts
935
+ var b64 = (v) => v === void 0 ? void 0 : toBase64(v);
936
+ var Transit = class extends MountedApi {
937
+ constructor(client, mount = "transit") {
938
+ super(client, mount);
939
+ }
940
+ // ------------------------------------------------------------ keys
941
+ async createKey(name, options = {}, opts) {
942
+ await this.client.write(this.path("keys", name), compact(options), opts);
943
+ }
944
+ async readKey(name, opts) {
945
+ return (await this.client.read(this.path("keys", name), opts)).data;
946
+ }
947
+ async listKeys(opts) {
948
+ return (await this.client.list(`${this.path("keys")}/`, opts)).keys;
949
+ }
950
+ /** Deletes a key. The key must have `deletion_allowed: true` (see {@link configureKey}). */
951
+ async deleteKey(name, opts) {
952
+ await this.client.delete(this.path("keys", name), opts);
953
+ }
954
+ async configureKey(name, config, opts) {
955
+ await this.client.write(this.path("keys", name, "config"), compact(config), opts);
956
+ }
957
+ async rotateKey(name, opts) {
958
+ await this.client.write(this.path("keys", name, "rotate"), {}, opts);
959
+ }
960
+ async trimKey(name, minAvailableVersion, opts) {
961
+ await this.client.write(this.path("keys", name, "trim"), { min_available_version: minAvailableVersion }, opts);
962
+ }
963
+ async exportKey(name, type, version, opts) {
964
+ return (await this.client.read(this.path("export", type, name, version), opts)).data;
965
+ }
966
+ async backupKey(name, opts) {
967
+ return (await this.client.read(this.path("backup", name), opts)).data.backup;
968
+ }
969
+ async restoreKey(backup, options = {}) {
970
+ const { name, force, ...opts } = options;
971
+ await this.client.write(this.path("restore", name), compact({ backup, force }), opts);
972
+ }
973
+ // ------------------------------------------------------------ encryption
974
+ /** Encrypts `plaintext` and returns the `bao:v1:...` ciphertext. */
975
+ async encrypt(key, plaintext, options = {}) {
976
+ const { context, keyVersion, nonce, associatedData, ...opts } = options;
977
+ const res = await postData(
978
+ this.client,
979
+ this.path("encrypt", key),
980
+ compact({ plaintext: toBase64(plaintext), context: b64(context), key_version: keyVersion, nonce, associated_data: b64(associatedData) }),
981
+ opts
982
+ );
983
+ return res.ciphertext;
984
+ }
985
+ /** Decrypts to a UTF-8 string. Use {@link decryptBytes} for binary data. */
986
+ async decrypt(key, ciphertext, options = {}) {
987
+ return fromBase64String(await this.decryptRaw(key, ciphertext, options));
988
+ }
989
+ /** Decrypts to raw bytes. */
990
+ async decryptBytes(key, ciphertext, options = {}) {
991
+ return fromBase64(await this.decryptRaw(key, ciphertext, options));
992
+ }
993
+ /** Re-encrypts ciphertext with the latest (or given) key version without exposing plaintext. */
994
+ async rewrap(key, ciphertext, options = {}) {
995
+ const { context, keyVersion, nonce, ...opts } = options;
996
+ const res = await postData(
997
+ this.client,
998
+ this.path("rewrap", key),
999
+ compact({ ciphertext, context: b64(context), key_version: keyVersion, nonce }),
1000
+ opts
1001
+ );
1002
+ return res.ciphertext;
1003
+ }
1004
+ /** Encrypts many items in one request. Per-item failures are reported in `error`. */
1005
+ async encryptBatch(key, items, options = {}) {
1006
+ const { keyVersion, ...opts } = options;
1007
+ const batch_input = items.map((i) => compact({ plaintext: toBase64(i.plaintext), context: b64(i.context), reference: i.reference }));
1008
+ const res = await postData(this.client, this.path("encrypt", key), compact({ batch_input, key_version: keyVersion }), opts);
1009
+ return res.batch_results;
1010
+ }
1011
+ /** Decrypts many items in one request. `plaintext` in results is decoded to UTF-8. */
1012
+ async decryptBatch(key, items, opts) {
1013
+ const batch_input = items.map((i) => compact({ ciphertext: i.ciphertext, context: b64(i.context), reference: i.reference }));
1014
+ const res = await postData(this.client, this.path("decrypt", key), { batch_input }, opts);
1015
+ return res.batch_results.map(
1016
+ (r) => r.plaintext !== void 0 ? { ...r, plaintext: fromBase64String(r.plaintext) } : r
1017
+ );
1018
+ }
1019
+ /**
1020
+ * Generates a data key for envelope encryption. `plaintext` (base64) is only
1021
+ * returned for `type: 'plaintext'`.
1022
+ */
1023
+ async generateDataKey(key, options = {}) {
1024
+ const { type = "plaintext", bits, context, nonce, ...opts } = options;
1025
+ const res = await postData(
1026
+ this.client,
1027
+ this.path("datakey", type, key),
1028
+ compact({ bits, context: b64(context), nonce }),
1029
+ opts
1030
+ );
1031
+ return res;
1032
+ }
1033
+ // ------------------------------------------------------------ signing / hmac
1034
+ async sign(key, input, options = {}) {
1035
+ const { hashAlgorithm, keyVersion, context, prehashed, signatureAlgorithm, marshalingAlgorithm, saltLength, ...opts } = options;
1036
+ const res = await postData(
1037
+ this.client,
1038
+ this.path("sign", key),
1039
+ compact({
1040
+ input: toBase64(input),
1041
+ hash_algorithm: hashAlgorithm,
1042
+ key_version: keyVersion,
1043
+ context: b64(context),
1044
+ prehashed,
1045
+ signature_algorithm: signatureAlgorithm,
1046
+ marshaling_algorithm: marshalingAlgorithm,
1047
+ salt_length: saltLength
1048
+ }),
1049
+ opts
1050
+ );
1051
+ return res.signature;
1052
+ }
1053
+ async verify(key, input, signature, options = {}) {
1054
+ const { hashAlgorithm, context, prehashed, signatureAlgorithm, marshalingAlgorithm, saltLength, ...opts } = options;
1055
+ const res = await postData(
1056
+ this.client,
1057
+ this.path("verify", key),
1058
+ compact({
1059
+ input: toBase64(input),
1060
+ signature,
1061
+ hash_algorithm: hashAlgorithm,
1062
+ context: b64(context),
1063
+ prehashed,
1064
+ signature_algorithm: signatureAlgorithm,
1065
+ marshaling_algorithm: marshalingAlgorithm,
1066
+ salt_length: saltLength
1067
+ }),
1068
+ opts
1069
+ );
1070
+ return res.valid;
1071
+ }
1072
+ async hmac(key, input, options = {}) {
1073
+ const { algorithm, keyVersion, ...opts } = options;
1074
+ const res = await postData(
1075
+ this.client,
1076
+ this.path("hmac", key),
1077
+ compact({ input: toBase64(input), algorithm, key_version: keyVersion }),
1078
+ opts
1079
+ );
1080
+ return res.hmac;
1081
+ }
1082
+ async verifyHmac(key, input, hmac, options = {}) {
1083
+ const { algorithm, ...opts } = options;
1084
+ const res = await postData(this.client, this.path("verify", key), compact({ input: toBase64(input), hmac, algorithm }), opts);
1085
+ return res.valid;
1086
+ }
1087
+ // ------------------------------------------------------------ utilities
1088
+ async random(bytes = 32, options = {}) {
1089
+ const { format, source, ...opts } = options;
1090
+ const res = await postData(this.client, this.path("random", source, bytes), compact({ format }), opts);
1091
+ return res.random_bytes;
1092
+ }
1093
+ async hash(input, options = {}) {
1094
+ const { algorithm, format, ...opts } = options;
1095
+ const res = await postData(this.client, this.path("hash", algorithm), compact({ input: toBase64(input), format }), opts);
1096
+ return res.sum;
1097
+ }
1098
+ async decryptRaw(key, ciphertext, options) {
1099
+ const { context, nonce, associatedData, ...opts } = options;
1100
+ const res = await postData(
1101
+ this.client,
1102
+ this.path("decrypt", key),
1103
+ compact({ ciphertext, context: b64(context), nonce, associated_data: b64(associatedData) }),
1104
+ opts
1105
+ );
1106
+ return res.plaintext;
1107
+ }
1108
+ };
1109
+
1110
+ // src/api/sys.ts
1111
+ var SysMounts = class {
1112
+ constructor(client) {
1113
+ this.client = client;
1114
+ }
1115
+ client;
1116
+ /** Lists all mounted secrets engines keyed by path (`secret/`, `transit/`, ...). */
1117
+ async list(opts) {
1118
+ const res = await this.client.read("sys/mounts", opts);
1119
+ return unwrapData(res);
1120
+ }
1121
+ /** Reads one mount's configuration. */
1122
+ async read(path, opts) {
1123
+ return unwrapData(await this.client.read(joinPath("sys/mounts", path), opts));
1124
+ }
1125
+ /** Mounts a secrets engine at `path`. */
1126
+ async enable(path, options, opts) {
1127
+ await this.client.write(joinPath("sys/mounts", path), compact(options), opts);
1128
+ }
1129
+ /** Unmounts a secrets engine (destroys all its data). */
1130
+ async disable(path, opts) {
1131
+ await this.client.delete(joinPath("sys/mounts", path), opts);
1132
+ }
1133
+ async readTune(path, opts) {
1134
+ return unwrapData(await this.client.read(joinPath("sys/mounts", path, "tune"), opts));
1135
+ }
1136
+ async tune(path, config, opts) {
1137
+ await this.client.write(joinPath("sys/mounts", path, "tune"), compact(config), opts);
1138
+ }
1139
+ /** Moves a mount (`sys/remount`). Returns the migration id. */
1140
+ async remount(from, to, opts) {
1141
+ const res = await this.client.write("sys/remount", { from, to }, opts);
1142
+ return res ? unwrapData(res) : void 0;
1143
+ }
1144
+ };
1145
+ var SysAuth = class {
1146
+ constructor(client) {
1147
+ this.client = client;
1148
+ }
1149
+ client;
1150
+ async list(opts) {
1151
+ return unwrapData(await this.client.read("sys/auth", opts));
1152
+ }
1153
+ async read(path, opts) {
1154
+ return unwrapData(await this.client.read(joinPath("sys/auth", path), opts));
1155
+ }
1156
+ async enable(path, options, opts) {
1157
+ await this.client.write(joinPath("sys/auth", path), compact(options), opts);
1158
+ }
1159
+ async disable(path, opts) {
1160
+ await this.client.delete(joinPath("sys/auth", path), opts);
1161
+ }
1162
+ async readTune(path, opts) {
1163
+ return unwrapData(await this.client.read(joinPath("sys/auth", path, "tune"), opts));
1164
+ }
1165
+ async tune(path, config, opts) {
1166
+ await this.client.write(joinPath("sys/auth", path, "tune"), compact(config), opts);
1167
+ }
1168
+ };
1169
+ var SysAclPolicies = class {
1170
+ constructor(client) {
1171
+ this.client = client;
1172
+ }
1173
+ client;
1174
+ async list(opts) {
1175
+ return (await this.client.list(joinFolder("sys/policies/acl"), opts)).keys;
1176
+ }
1177
+ /** Returns the policy HCL text. */
1178
+ async read(name, opts) {
1179
+ const res = unwrapData(await this.client.read(joinPath("sys/policies/acl", name), opts));
1180
+ return res.policy;
1181
+ }
1182
+ /** Creates or replaces a policy from HCL/JSON text. */
1183
+ async write(name, policy, opts) {
1184
+ await this.client.request({ ...opts, method: "PUT", path: joinPath("sys/policies/acl", name), body: { policy } });
1185
+ }
1186
+ async delete(name, opts) {
1187
+ await this.client.delete(joinPath("sys/policies/acl", name), opts);
1188
+ }
1189
+ };
1190
+ var SysPasswordPolicies = class {
1191
+ constructor(client) {
1192
+ this.client = client;
1193
+ }
1194
+ client;
1195
+ async list(opts) {
1196
+ return (await this.client.list(joinFolder("sys/policies/password"), opts)).keys;
1197
+ }
1198
+ async read(name, opts) {
1199
+ return unwrapData(await this.client.read(joinPath("sys/policies/password", name), opts)).policy;
1200
+ }
1201
+ async write(name, policy, opts) {
1202
+ await this.client.request({ ...opts, method: "PUT", path: joinPath("sys/policies/password", name), body: { policy } });
1203
+ }
1204
+ async delete(name, opts) {
1205
+ await this.client.delete(joinPath("sys/policies/password", name), opts);
1206
+ }
1207
+ /** Generates a password from the named policy. */
1208
+ async generate(name, opts) {
1209
+ return unwrapData(await this.client.read(joinPath("sys/policies/password", name, "generate"), opts)).password;
1210
+ }
1211
+ };
1212
+ var SysLeases = class {
1213
+ constructor(client) {
1214
+ this.client = client;
1215
+ }
1216
+ client;
1217
+ async lookup(leaseId, opts) {
1218
+ const res = await this.client.request({ ...opts, method: "PUT", path: "sys/leases/lookup", body: { lease_id: leaseId } });
1219
+ return unwrapData(res);
1220
+ }
1221
+ /** Lists lease ids under a prefix, e.g. `database/creds/readonly/`. */
1222
+ async list(prefix, opts) {
1223
+ return (await this.client.list(joinFolder("sys/leases/lookup", prefix), opts)).keys;
1224
+ }
1225
+ /** Renews a lease. Returns the new response envelope (with updated `lease_duration`). */
1226
+ renew(leaseId, increment, opts) {
1227
+ return this.client.request({
1228
+ ...opts,
1229
+ method: "PUT",
1230
+ path: "sys/leases/renew",
1231
+ body: compact({ lease_id: leaseId, increment })
1232
+ });
1233
+ }
1234
+ async revoke(leaseId, options = {}) {
1235
+ const { sync, ...opts } = options;
1236
+ await this.client.request({ ...opts, method: "PUT", path: "sys/leases/revoke", body: compact({ lease_id: leaseId, sync }) });
1237
+ }
1238
+ async revokePrefix(prefix, options = {}) {
1239
+ const { sync, ...opts } = options;
1240
+ await this.client.request({ ...opts, method: "PUT", path: joinPath("sys/leases/revoke-prefix", prefix), body: compact({ sync }) });
1241
+ }
1242
+ /** Revokes all leases under prefix ignoring backend errors. Requires `sudo`. */
1243
+ async revokeForce(prefix, opts) {
1244
+ await this.client.request({ ...opts, method: "PUT", path: joinPath("sys/leases/revoke-force", prefix) });
1245
+ }
1246
+ async tidy(opts) {
1247
+ await this.client.write("sys/leases/tidy", {}, opts);
1248
+ }
1249
+ };
1250
+ var SysWrapping = class {
1251
+ constructor(client) {
1252
+ this.client = client;
1253
+ }
1254
+ client;
1255
+ /** Wraps arbitrary data in a single-use token. Returns the wrap info (use `.token`). */
1256
+ async wrap(data, ttl = "5m", opts) {
1257
+ const res = await this.client.request({ ...opts, method: "POST", path: "sys/wrapping/wrap", body: data, wrapTTL: ttl });
1258
+ if (!res?.wrap_info) throw new Error("sys/wrapping/wrap returned no wrap_info");
1259
+ return res.wrap_info;
1260
+ }
1261
+ /**
1262
+ * Unwraps a wrapping token. Returns the original response envelope, so both
1263
+ * wrapped secrets (`.data`) and wrapped logins (`.auth`) are available.
1264
+ */
1265
+ unwrap(wrappingToken, opts) {
1266
+ return this.client.request({
1267
+ ...opts,
1268
+ method: "POST",
1269
+ path: "sys/wrapping/unwrap",
1270
+ body: wrappingToken ? { token: wrappingToken } : {}
1271
+ });
1272
+ }
1273
+ async lookup(wrappingToken, opts) {
1274
+ return unwrapData(
1275
+ await this.client.request({
1276
+ ...opts,
1277
+ method: "POST",
1278
+ path: "sys/wrapping/lookup",
1279
+ body: { token: wrappingToken },
1280
+ token: opts?.token ?? null
1281
+ })
1282
+ );
1283
+ }
1284
+ async rewrap(wrappingToken, opts) {
1285
+ const res = await this.client.request({ ...opts, method: "POST", path: "sys/wrapping/rewrap", body: { token: wrappingToken } });
1286
+ if (!res?.wrap_info) throw new Error("sys/wrapping/rewrap returned no wrap_info");
1287
+ return res.wrap_info;
1288
+ }
1289
+ };
1290
+ var SysTools = class {
1291
+ constructor(client) {
1292
+ this.client = client;
1293
+ }
1294
+ client;
1295
+ async random(bytes = 32, options = {}) {
1296
+ const { format, source, ...opts } = options;
1297
+ const res = await this.client.write(joinPath("sys/tools/random", source, bytes), compact({ format }), opts);
1298
+ return unwrapData(res).random_bytes;
1299
+ }
1300
+ /** Hashes input (string or bytes; base64-encoded automatically). */
1301
+ async hash(input, options = {}) {
1302
+ const { algorithm, format, ...opts } = options;
1303
+ const res = await this.client.write(joinPath("sys/tools/hash", algorithm), compact({ input: toBase64(input), format }), opts);
1304
+ return unwrapData(res).sum;
1305
+ }
1306
+ };
1307
+ var SysAudit = class {
1308
+ constructor(client) {
1309
+ this.client = client;
1310
+ }
1311
+ client;
1312
+ async list(opts) {
1313
+ return unwrapData(await this.client.read("sys/audit", opts));
1314
+ }
1315
+ /**
1316
+ * Enables an audit device. Note: recent OpenBao releases may require audit
1317
+ * devices to be declared in server configuration instead of via the API.
1318
+ */
1319
+ async enable(path, options, opts) {
1320
+ await this.client.request({ ...opts, method: "PUT", path: joinPath("sys/audit", path), body: compact(options) });
1321
+ }
1322
+ async disable(path, opts) {
1323
+ await this.client.delete(joinPath("sys/audit", path), opts);
1324
+ }
1325
+ /** Hashes `input` with the audit device's HMAC key (`sys/audit-hash`). */
1326
+ async hash(path, input, opts) {
1327
+ return unwrapData(await this.client.write(joinPath("sys/audit-hash", path), { input }, opts)).hash;
1328
+ }
1329
+ };
1330
+ var SysNamespaces = class {
1331
+ constructor(client) {
1332
+ this.client = client;
1333
+ }
1334
+ client;
1335
+ /** Lists child namespaces of the current namespace. */
1336
+ async list(opts) {
1337
+ const res = await this.client.list("sys/namespaces", opts);
1338
+ return { keys: res.keys, key_info: res.key_info ?? {} };
1339
+ }
1340
+ async read(path, opts) {
1341
+ return unwrapData(await this.client.read(joinPath("sys/namespaces", path), opts));
1342
+ }
1343
+ async create(path, options = {}) {
1344
+ const { custom_metadata, seal, ...opts } = options;
1345
+ const res = await this.client.write(joinPath("sys/namespaces", path), compact({ custom_metadata, seal }), opts);
1346
+ return unwrapData(res);
1347
+ }
1348
+ /** Merge-patches a namespace's custom metadata. */
1349
+ async patch(path, custom_metadata, opts) {
1350
+ return unwrapData(await this.client.patch(joinPath("sys/namespaces", path), { custom_metadata }, opts));
1351
+ }
1352
+ async delete(path, opts) {
1353
+ await this.client.delete(joinPath("sys/namespaces", path), opts);
1354
+ }
1355
+ async sealStatus(path, opts) {
1356
+ return unwrapData(await this.client.read(joinPath("sys/namespaces", path, "seal-status"), opts));
1357
+ }
1358
+ async seal(path, opts) {
1359
+ await this.client.request({ ...opts, method: "PUT", path: joinPath("sys/namespaces", path, "seal") });
1360
+ }
1361
+ async unseal(path, key, options = {}) {
1362
+ const { reset, ...opts } = options;
1363
+ return unwrapData(
1364
+ await this.client.request({ ...opts, method: "PUT", path: joinPath("sys/namespaces", path, "unseal"), body: compact({ key, reset }) })
1365
+ );
1366
+ }
1367
+ };
1368
+ var Sys = class {
1369
+ constructor(client) {
1370
+ this.client = client;
1371
+ this.mounts = new SysMounts(client);
1372
+ this.auth = new SysAuth(client);
1373
+ this.policies = { acl: new SysAclPolicies(client), password: new SysPasswordPolicies(client) };
1374
+ this.leases = new SysLeases(client);
1375
+ this.wrapping = new SysWrapping(client);
1376
+ this.tools = new SysTools(client);
1377
+ this.audit = new SysAudit(client);
1378
+ this.namespaces = new SysNamespaces(client);
1379
+ }
1380
+ client;
1381
+ mounts;
1382
+ auth;
1383
+ policies;
1384
+ leases;
1385
+ wrapping;
1386
+ tools;
1387
+ audit;
1388
+ namespaces;
1389
+ /**
1390
+ * Node health. Never throws for sealed / standby / uninitialized states —
1391
+ * inspect the returned flags instead. Unauthenticated.
1392
+ */
1393
+ health(options = {}) {
1394
+ const { signal, ...query } = options;
1395
+ return this.client.request({
1396
+ method: "GET",
1397
+ path: "sys/health",
1398
+ query,
1399
+ signal,
1400
+ token: null,
1401
+ acceptStatus: [429, 472, 473, 501, 503]
1402
+ });
1403
+ }
1404
+ sealStatus(opts) {
1405
+ return this.client.request({ ...opts, method: "GET", path: "sys/seal-status" });
1406
+ }
1407
+ async seal(opts) {
1408
+ await this.client.request({ ...opts, method: "PUT", path: "sys/seal" });
1409
+ }
1410
+ /** Submits one unseal key share. */
1411
+ unseal(key, options = {}) {
1412
+ const { reset, migrate, ...opts } = options;
1413
+ return this.client.request({ ...opts, method: "PUT", path: "sys/unseal", body: compact({ key, reset, migrate }) });
1414
+ }
1415
+ /** Resets unseal progress. */
1416
+ unsealReset(opts) {
1417
+ return this.client.request({ ...opts, method: "PUT", path: "sys/unseal", body: { reset: true } });
1418
+ }
1419
+ async initStatus(opts) {
1420
+ return (await this.client.request({ ...opts, method: "GET", path: "sys/init" })).initialized;
1421
+ }
1422
+ /** Initializes a new server. Returns unseal keys and the initial root token. */
1423
+ init(options = { secret_shares: 5, secret_threshold: 3 }, opts) {
1424
+ return this.client.request({ ...opts, method: "PUT", path: "sys/init", body: compact(options), token: null });
1425
+ }
1426
+ leader(opts) {
1427
+ return this.client.request({ ...opts, method: "GET", path: "sys/leader" });
1428
+ }
1429
+ haStatus(opts) {
1430
+ return this.client.request({ ...opts, method: "GET", path: "sys/ha-status" });
1431
+ }
1432
+ async stepDown(opts) {
1433
+ await this.client.request({ ...opts, method: "PUT", path: "sys/step-down" });
1434
+ }
1435
+ async keyStatus(opts) {
1436
+ return unwrapData(await this.client.read("sys/key-status", opts));
1437
+ }
1438
+ /** Rotates the backend encryption key. */
1439
+ async rotate(opts) {
1440
+ await this.client.request({ ...opts, method: "PUT", path: "sys/rotate" });
1441
+ }
1442
+ async hostInfo(opts) {
1443
+ return unwrapData(await this.client.read("sys/host-info", opts));
1444
+ }
1445
+ /** Versions this cluster has run, keyed by version string. */
1446
+ async versionHistory(opts) {
1447
+ const res = await this.client.list("sys/version-history", opts);
1448
+ return { keys: res.keys, key_info: res.key_info ?? {} };
1449
+ }
1450
+ /** Returns `{ [path]: capabilities[] }` for the given token (or the client token via `capabilitiesSelf`). */
1451
+ async capabilities(token, paths, opts) {
1452
+ const res = await this.client.write("sys/capabilities", { token, paths }, opts);
1453
+ return pickCapabilities(unwrapData(res), paths);
1454
+ }
1455
+ async capabilitiesSelf(paths, opts) {
1456
+ const res = await this.client.write("sys/capabilities-self", { paths }, opts);
1457
+ return pickCapabilities(unwrapData(res), paths);
1458
+ }
1459
+ async capabilitiesAccessor(accessor, paths, opts) {
1460
+ const res = await this.client.write("sys/capabilities-accessor", { accessor, paths }, opts);
1461
+ return pickCapabilities(unwrapData(res), paths);
1462
+ }
1463
+ /** Prometheus-format metrics (text) or JSON metrics. */
1464
+ metrics(format = "prometheus", opts) {
1465
+ return this.client.request({ ...opts, method: "GET", path: "sys/metrics", query: { format: format === "prometheus" ? "prometheus" : void 0 }, responseType: format === "prometheus" ? "text" : "json" });
1466
+ }
1467
+ };
1468
+ function pickCapabilities(data, paths) {
1469
+ const out = {};
1470
+ for (const p of paths) {
1471
+ const v = data[p];
1472
+ out[p] = Array.isArray(v) ? v : paths.length === 1 && Array.isArray(data["capabilities"]) ? data["capabilities"] : [];
1473
+ }
1474
+ return out;
1475
+ }
1476
+
1477
+ // src/core.ts
1478
+ var DEFAULT_RETRY = {
1479
+ retries: 2,
1480
+ minDelay: 250,
1481
+ maxDelay: 5e3,
1482
+ statusCodes: [412, 429, 503]
1483
+ };
1484
+ var IDEMPOTENT = /* @__PURE__ */ new Set(["GET", "HEAD", "LIST", "SCAN", "PUT", "DELETE"]);
1485
+ var OpenBaoCore = class {
1486
+ /** @internal */
1487
+ config;
1488
+ constructor(options = {}) {
1489
+ const useEnv = options.useEnv ?? true;
1490
+ const env = (...names) => useEnv ? readEnv(...names) : void 0;
1491
+ const fetchImpl = options.fetch ?? globalThis.fetch;
1492
+ if (!fetchImpl) {
1493
+ throw new Error("No fetch implementation available; pass `fetch` in OpenBao options (Node >= 18 has one built in).");
1494
+ }
1495
+ this.config = {
1496
+ address: (options.address ?? env("BAO_ADDR", "VAULT_ADDR") ?? "http://127.0.0.1:8200").replace(/\/+$/, ""),
1497
+ token: options.token ?? env("BAO_TOKEN", "VAULT_TOKEN"),
1498
+ namespace: options.namespace ?? env("BAO_NAMESPACE", "VAULT_NAMESPACE"),
1499
+ headers: { ...options.headers },
1500
+ timeout: options.timeout ?? 6e4,
1501
+ retry: options.retry === false ? false : { ...DEFAULT_RETRY, ...options.retry },
1502
+ fetch: fetchImpl,
1503
+ requestInit: options.requestInit,
1504
+ requestHeader: options.requestHeader ?? true
1505
+ };
1506
+ }
1507
+ /** Base server address (without `/v1`). */
1508
+ get address() {
1509
+ return this.config.address;
1510
+ }
1511
+ /** Current client token. Login helpers update this automatically. */
1512
+ get token() {
1513
+ return this.config.token;
1514
+ }
1515
+ set token(value) {
1516
+ this.config.token = value;
1517
+ }
1518
+ /** Current namespace. */
1519
+ get namespace() {
1520
+ return this.config.namespace;
1521
+ }
1522
+ set namespace(value) {
1523
+ this.config.namespace = value;
1524
+ }
1525
+ /** Sends a request and returns the decoded body (`undefined` for 204 No Content). */
1526
+ async request(opts) {
1527
+ const path = opts.path.replace(/^\/+/, "");
1528
+ const url = `${this.config.address}/v1/${path}${buildQuery(opts.query)}`;
1529
+ const headers = this.buildHeaders(opts);
1530
+ const hasBody = opts.body !== void 0;
1531
+ if (hasBody) headers["Content-Type"] = opts.contentType ?? "application/json";
1532
+ const body = hasBody ? typeof opts.body === "string" && opts.contentType && opts.contentType !== "application/json" ? opts.body : JSON.stringify(opts.body) : void 0;
1533
+ const retry = this.config.retry;
1534
+ const maxAttempts = retry ? retry.retries + 1 : 1;
1535
+ for (let attempt = 1; ; attempt++) {
1536
+ let res;
1537
+ const { signal, cleanup, timedOut } = this.createSignal(opts.signal);
1538
+ try {
1539
+ res = await this.config.fetch(url, {
1540
+ ...this.config.requestInit,
1541
+ method: opts.method,
1542
+ headers,
1543
+ body,
1544
+ signal
1545
+ });
1546
+ } catch (cause) {
1547
+ cleanup();
1548
+ const canRetry = retry && attempt < maxAttempts && IDEMPOTENT.has(opts.method) && !opts.signal?.aborted;
1549
+ if (canRetry) {
1550
+ await sleep(this.backoff(attempt), opts.signal);
1551
+ continue;
1552
+ }
1553
+ throw new OpenBaoConnectionError({ method: opts.method, path, cause, timedOut: timedOut() });
1554
+ }
1555
+ try {
1556
+ const ok = res.ok || opts.acceptStatus?.includes(res.status);
1557
+ if (!ok && retry && attempt < maxAttempts && retry.statusCodes.includes(res.status)) {
1558
+ await res.body?.cancel().catch(() => void 0);
1559
+ await sleep(this.backoff(attempt, res.headers.get("retry-after")), opts.signal);
1560
+ continue;
1561
+ }
1562
+ const parsed = await this.parseBody(res, opts.responseType ?? "json");
1563
+ if (!ok) {
1564
+ const obj = parsed && typeof parsed === "object" ? parsed : {};
1565
+ throw new OpenBaoError({
1566
+ status: res.status,
1567
+ method: opts.method,
1568
+ path,
1569
+ errors: Array.isArray(obj.errors) ? obj.errors.map(String) : typeof parsed === "string" && parsed ? [parsed] : [],
1570
+ warnings: Array.isArray(obj.warnings) ? obj.warnings.map(String) : [],
1571
+ body: parsed
1572
+ });
1573
+ }
1574
+ return parsed;
1575
+ } catch (err) {
1576
+ if (err instanceof OpenBaoError) throw err;
1577
+ throw new OpenBaoConnectionError({ method: opts.method, path, cause: err, timedOut: timedOut() });
1578
+ } finally {
1579
+ cleanup();
1580
+ }
1581
+ }
1582
+ }
1583
+ // ---------------------------------------------------------------- generic logical ops
1584
+ /** `GET` a path and return the full response envelope. Throws {@link OpenBaoError} (404) when missing. */
1585
+ read(path, opts = {}) {
1586
+ return this.request({ ...opts, method: "GET", path });
1587
+ }
1588
+ /** `POST` data to a path. Resolves to `undefined` when the server answers 204. */
1589
+ write(path, data, opts = {}) {
1590
+ return this.request({ ...opts, method: "POST", path, body: data ?? {} });
1591
+ }
1592
+ /** JSON merge-patch a path (`PATCH` with `application/merge-patch+json`). */
1593
+ patch(path, data, opts = {}) {
1594
+ return this.request({
1595
+ ...opts,
1596
+ method: "PATCH",
1597
+ path,
1598
+ body: data,
1599
+ contentType: "application/merge-patch+json"
1600
+ });
1601
+ }
1602
+ /** `DELETE` a path. */
1603
+ delete(path, opts = {}) {
1604
+ return this.request({ ...opts, method: "DELETE", path });
1605
+ }
1606
+ /**
1607
+ * `LIST` a path. Returns `{ keys: [] }` when nothing exists (OpenBao answers 404 for empty lists).
1608
+ */
1609
+ async list(path, opts = {}) {
1610
+ const { after, limit, ...call } = opts;
1611
+ return this.listLike("LIST", path, { after, limit }, call);
1612
+ }
1613
+ /** Recursive `SCAN` of a path (OpenBao-specific). Returns `{ keys: [] }` when nothing exists. */
1614
+ async scan(path, opts = {}) {
1615
+ const { after, limit, ...call } = opts;
1616
+ return this.listLike("SCAN", path, { after, limit }, call);
1617
+ }
1618
+ // ---------------------------------------------------------------- internals
1619
+ async listLike(verb, path, page, call) {
1620
+ try {
1621
+ const res = verb === "LIST" ? await this.request({
1622
+ ...call,
1623
+ method: "GET",
1624
+ path,
1625
+ query: { list: true, after: page.after, limit: page.limit }
1626
+ }) : await this.request({
1627
+ ...call,
1628
+ method: "SCAN",
1629
+ path,
1630
+ query: { after: page.after, limit: page.limit }
1631
+ });
1632
+ return { keys: res?.data?.keys ?? [], ...res?.data?.key_info ? { key_info: res.data.key_info } : {} };
1633
+ } catch (err) {
1634
+ if (err instanceof OpenBaoError && err.status === 404) return { keys: [] };
1635
+ throw err;
1636
+ }
1637
+ }
1638
+ buildHeaders(opts) {
1639
+ const headers = { Accept: "application/json", ...this.config.headers };
1640
+ if (this.config.requestHeader) headers["X-Vault-Request"] = "true";
1641
+ const token = opts.token === void 0 ? this.config.token : opts.token;
1642
+ if (token) headers["X-Vault-Token"] = token;
1643
+ const ns = opts.namespace === void 0 ? this.config.namespace : opts.namespace;
1644
+ if (ns) headers["X-Vault-Namespace"] = trimSlashes(ns);
1645
+ if (opts.wrapTTL !== void 0) headers["X-Vault-Wrap-TTL"] = String(opts.wrapTTL);
1646
+ Object.assign(headers, opts.headers);
1647
+ return headers;
1648
+ }
1649
+ async parseBody(res, type) {
1650
+ if (res.status === 204 || res.status === 304) return void 0;
1651
+ const text = await res.text();
1652
+ if (!text) return void 0;
1653
+ const isJson = (res.headers.get("content-type") ?? "").includes("json");
1654
+ if (type === "text" && res.ok) return text;
1655
+ if (isJson || type === "json") {
1656
+ try {
1657
+ return JSON.parse(text);
1658
+ } catch {
1659
+ return text;
1660
+ }
1661
+ }
1662
+ return text;
1663
+ }
1664
+ createSignal(user) {
1665
+ const timeout = this.config.timeout;
1666
+ if (!timeout) return { signal: user, cleanup: () => void 0, timedOut: () => false };
1667
+ const controller = new AbortController();
1668
+ let fired = false;
1669
+ const timer = setTimeout(() => {
1670
+ fired = true;
1671
+ controller.abort(new Error("timeout"));
1672
+ }, timeout);
1673
+ const onAbort = () => controller.abort(user?.reason);
1674
+ if (user) {
1675
+ if (user.aborted) controller.abort(user.reason);
1676
+ else user.addEventListener("abort", onAbort, { once: true });
1677
+ }
1678
+ return {
1679
+ signal: controller.signal,
1680
+ cleanup: () => {
1681
+ clearTimeout(timer);
1682
+ user?.removeEventListener("abort", onAbort);
1683
+ },
1684
+ timedOut: () => fired
1685
+ };
1686
+ }
1687
+ backoff(attempt, retryAfter) {
1688
+ const retry = this.config.retry || DEFAULT_RETRY;
1689
+ const fromHeader = retryAfter ? Number(retryAfter) * 1e3 : NaN;
1690
+ if (Number.isFinite(fromHeader) && fromHeader >= 0) return Math.min(fromHeader, retry.maxDelay);
1691
+ const base = Math.min(retry.maxDelay, retry.minDelay * 2 ** (attempt - 1));
1692
+ return base / 2 + Math.random() * (base / 2);
1693
+ }
1694
+ };
1695
+
1696
+ // src/client.ts
1697
+ var OpenBao = class _OpenBao extends OpenBaoCore {
1698
+ _sys;
1699
+ _auth;
1700
+ _identity;
1701
+ _cubbyhole;
1702
+ constructor(options = {}) {
1703
+ super(options);
1704
+ }
1705
+ /** System backend: health, seal, mounts, policies, leases, wrapping, namespaces, ... */
1706
+ get sys() {
1707
+ return this._sys ??= new Sys(this);
1708
+ }
1709
+ /** Auth methods: `auth.token`, `auth.approle()`, `auth.userpass()`, `auth.jwt()`, ... */
1710
+ get auth() {
1711
+ return this._auth ??= new Auth(this);
1712
+ }
1713
+ /** Identity secrets engine: entities, groups, aliases, OIDC identity tokens. */
1714
+ get identity() {
1715
+ return this._identity ??= new Identity(this);
1716
+ }
1717
+ /** The token's private cubbyhole. */
1718
+ get cubbyhole() {
1719
+ return this._cubbyhole ??= new Cubbyhole(this);
1720
+ }
1721
+ /** KV version 2 engine mounted at `mount` (default `secret`). */
1722
+ kv2(mount = "secret") {
1723
+ return new KvV2(this, mount);
1724
+ }
1725
+ /** Alias of {@link kv2} — KV v2 is the default KV engine. */
1726
+ kv(mount = "secret") {
1727
+ return this.kv2(mount);
1728
+ }
1729
+ /** KV version 1 engine mounted at `mount` (default `kv`). */
1730
+ kv1(mount = "kv") {
1731
+ return new KvV1(this, mount);
1732
+ }
1733
+ /** Transit engine mounted at `mount` (default `transit`). */
1734
+ transit(mount = "transit") {
1735
+ return new Transit(this, mount);
1736
+ }
1737
+ /** PKI engine mounted at `mount` (default `pki`). */
1738
+ pki(mount = "pki") {
1739
+ return new Pki(this, mount);
1740
+ }
1741
+ /** Database engine mounted at `mount` (default `database`). */
1742
+ database(mount = "database") {
1743
+ return new Database(this, mount);
1744
+ }
1745
+ /** TOTP engine mounted at `mount` (default `totp`). */
1746
+ totp(mount = "totp") {
1747
+ return new Totp(this, mount);
1748
+ }
1749
+ /** SSH engine mounted at `mount` (default `ssh`). */
1750
+ ssh(mount = "ssh") {
1751
+ return new Ssh(this, mount);
1752
+ }
1753
+ /**
1754
+ * Returns an independent client bound to another namespace. Token changes on
1755
+ * the returned client do not affect this one.
1756
+ */
1757
+ withNamespace(namespace) {
1758
+ return this.clone({ namespace });
1759
+ }
1760
+ /** Returns an independent client that authenticates with `token`. */
1761
+ withToken(token) {
1762
+ return this.clone({ token });
1763
+ }
1764
+ /** Returns an independent copy of this client with some settings overridden. */
1765
+ clone(overrides = {}) {
1766
+ const c = this.config;
1767
+ const has = (k) => Object.prototype.hasOwnProperty.call(overrides, k);
1768
+ return new _OpenBao({
1769
+ address: c.address,
1770
+ token: has("token") ? overrides.token : c.token,
1771
+ namespace: has("namespace") ? overrides.namespace : c.namespace,
1772
+ headers: { ...c.headers, ...overrides.headers },
1773
+ timeout: overrides.timeout ?? c.timeout,
1774
+ retry: has("retry") ? overrides.retry : c.retry,
1775
+ fetch: c.fetch,
1776
+ requestInit: c.requestInit,
1777
+ requestHeader: c.requestHeader,
1778
+ useEnv: false
1779
+ });
1780
+ }
1781
+ };
1782
+
1783
+ exports.AppRoleAuth = AppRoleAuth;
1784
+ exports.Auth = Auth;
1785
+ exports.AuthMethodApi = AuthMethodApi;
1786
+ exports.CertAuth = CertAuth;
1787
+ exports.Cubbyhole = Cubbyhole;
1788
+ exports.Database = Database;
1789
+ exports.GenericAuth = GenericAuth;
1790
+ exports.Identity = Identity;
1791
+ exports.IdentityCollection = IdentityCollection;
1792
+ exports.JwtAuth = JwtAuth;
1793
+ exports.KerberosAuth = KerberosAuth;
1794
+ exports.KubernetesAuth = KubernetesAuth;
1795
+ exports.KvV1 = KvV1;
1796
+ exports.KvV2 = KvV2;
1797
+ exports.LdapAuth = LdapAuth;
1798
+ exports.MountedApi = MountedApi;
1799
+ exports.OpenBao = OpenBao;
1800
+ exports.OpenBaoConnectionError = OpenBaoConnectionError;
1801
+ exports.OpenBaoCore = OpenBaoCore;
1802
+ exports.OpenBaoError = OpenBaoError;
1803
+ exports.Pki = Pki;
1804
+ exports.RadiusAuth = RadiusAuth;
1805
+ exports.Resource = Resource;
1806
+ exports.Ssh = Ssh;
1807
+ exports.Sys = Sys;
1808
+ exports.SysAclPolicies = SysAclPolicies;
1809
+ exports.SysAudit = SysAudit;
1810
+ exports.SysAuth = SysAuth;
1811
+ exports.SysLeases = SysLeases;
1812
+ exports.SysMounts = SysMounts;
1813
+ exports.SysNamespaces = SysNamespaces;
1814
+ exports.SysPasswordPolicies = SysPasswordPolicies;
1815
+ exports.SysTools = SysTools;
1816
+ exports.SysWrapping = SysWrapping;
1817
+ exports.TokenAuth = TokenAuth;
1818
+ exports.Totp = Totp;
1819
+ exports.Transit = Transit;
1820
+ exports.UserpassAuth = UserpassAuth;
1821
+ exports.fromBase64 = fromBase64;
1822
+ exports.fromBase64String = fromBase64String;
1823
+ exports.isNotFound = isNotFound;
1824
+ exports.isOpenBaoError = isOpenBaoError;
1825
+ exports.toBase64 = toBase64;
1826
+ exports.unwrapData = unwrapData;
1827
+ //# sourceMappingURL=index.cjs.map
1828
+ //# sourceMappingURL=index.cjs.map