autho 0.0.12 → 0.0.13

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 (2) hide show
  1. package/build/bin.js +2277 -2190
  2. package/package.json +14 -14
package/build/bin.js CHANGED
@@ -23161,7 +23161,7 @@ var require_bl = __commonJS({
23161
23161
  var require_ora = __commonJS({
23162
23162
  "node_modules/.pnpm/ora@5.4.1/node_modules/ora/index.js"(exports2, module2) {
23163
23163
  "use strict";
23164
- var readline3 = require("readline");
23164
+ var readline2 = require("readline");
23165
23165
  var chalk2 = require_source();
23166
23166
  var cliCursor3 = require_cli_cursor();
23167
23167
  var cliSpinners = require_cli_spinners();
@@ -23214,7 +23214,7 @@ var require_ora = __commonJS({
23214
23214
  if (process.platform === "win32") {
23215
23215
  return;
23216
23216
  }
23217
- this.rl = readline3.createInterface({
23217
+ this.rl = readline2.createInterface({
23218
23218
  input: process.stdin,
23219
23219
  output: this.mutedStream
23220
23220
  });
@@ -57229,2371 +57229,2412 @@ var inquirer = {
57229
57229
  };
57230
57230
  var inquirer_default = inquirer;
57231
57231
 
57232
- // packages/cli/utils.js
57233
- var prompt2 = inquirer_default.prompt;
57234
- var ask = async ({ name = "", message = "", type = "input" }) => {
57235
- const answers = await inquirer_default.prompt([
57236
- {
57237
- name,
57238
- message,
57239
- type
57232
+ // node_modules/.pnpm/otpauth@9.2.3/node_modules/otpauth/dist/otpauth.node.mjs
57233
+ var crypto = __toESM(require("node:crypto"), 1);
57234
+ var uintToBuf = (num) => {
57235
+ const buf = new ArrayBuffer(8);
57236
+ const arr = new Uint8Array(buf);
57237
+ let acc = num;
57238
+ for (let i = 7; i >= 0; i--) {
57239
+ if (acc === 0)
57240
+ break;
57241
+ arr[i] = acc & 255;
57242
+ acc -= arr[i];
57243
+ acc /= 256;
57244
+ }
57245
+ return buf;
57246
+ };
57247
+ var jsSHA = void 0;
57248
+ var globalScope = (() => {
57249
+ if (typeof globalThis === "object")
57250
+ return globalThis;
57251
+ else {
57252
+ Object.defineProperty(Object.prototype, "__GLOBALTHIS__", {
57253
+ get() {
57254
+ return this;
57255
+ },
57256
+ configurable: true
57257
+ });
57258
+ try {
57259
+ if (typeof __GLOBALTHIS__ !== "undefined")
57260
+ return __GLOBALTHIS__;
57261
+ } finally {
57262
+ delete Object.prototype.__GLOBALTHIS__;
57240
57263
  }
57241
- ]);
57242
- return answers[name];
57264
+ }
57265
+ if (typeof self !== "undefined")
57266
+ return self;
57267
+ else if (typeof window !== "undefined")
57268
+ return window;
57269
+ else if (typeof global !== "undefined")
57270
+ return global;
57271
+ return void 0;
57272
+ })();
57273
+ var OPENSSL_JSSHA_ALGO_MAP = {
57274
+ SHA1: "SHA-1",
57275
+ SHA224: "SHA-224",
57276
+ SHA256: "SHA-256",
57277
+ SHA384: "SHA-384",
57278
+ SHA512: "SHA-512",
57279
+ "SHA3-224": "SHA3-224",
57280
+ "SHA3-256": "SHA3-256",
57281
+ "SHA3-384": "SHA3-384",
57282
+ "SHA3-512": "SHA3-512"
57243
57283
  };
57244
-
57245
- // packages/models/Secret.js
57246
- var import_joi = __toESM(require_lib6(), 1);
57247
- var import_node_crypto = require("node:crypto");
57248
- var createSecretSchema = import_joi.default.object({
57249
- id: import_joi.default.string().default((0, import_node_crypto.randomUUID)()),
57250
- protected: import_joi.default.boolean().default(false),
57251
- name: import_joi.default.string().required(),
57252
- type: import_joi.default.string().required().valid("otp", "password", "note"),
57253
- value: import_joi.default.string().required(),
57254
- typeOptions: import_joi.default.object().default({}),
57255
- createdAt: import_joi.default.date().default(/* @__PURE__ */ new Date())
57256
- });
57257
-
57258
- // packages/sdk/cipher.js
57259
- var import_crypto = __toESM(require("crypto"), 1);
57260
- var import_fs = __toESM(require("fs"), 1);
57261
- var import_path = __toESM(require("path"), 1);
57262
- var import_zlib = __toESM(require("zlib"), 1);
57263
-
57264
- // packages/shared/config.js
57265
- var import_dotenv = __toESM(require_main2(), 1);
57266
- import_dotenv.default.config();
57267
- var config_default = {
57268
- masterPasswordHash: process.env.AUTHO_MASTER_PASSWORD_HASH,
57269
- masterPassword: process.env.AUTHO_MASTER_PASSWORD,
57270
- randomSize: process.env.AUTHO_RANDOM_SIZE || 16,
57271
- encryptionALgo: process.env.AUTHO_ENCRYPTION_ALGO || "aes-256-gcm",
57272
- hashAlgo: process.env.AUTHO_HASH_ALGO || "sha256",
57273
- dataFolder: process.env.AUTHO_DATA_FOLDER,
57274
- name: process.env.AUTHO_COLLECTION_NAME || "default"
57284
+ var hmacDigest = (algorithm, key, message) => {
57285
+ if (crypto?.createHmac) {
57286
+ const hmac = crypto.createHmac(algorithm, globalScope.Buffer.from(key));
57287
+ hmac.update(globalScope.Buffer.from(message));
57288
+ return hmac.digest().buffer;
57289
+ } else {
57290
+ const variant = OPENSSL_JSSHA_ALGO_MAP[algorithm.toUpperCase()];
57291
+ if (typeof variant === "undefined") {
57292
+ throw new TypeError("Unknown hash function");
57293
+ }
57294
+ const hmac = new jsSHA(variant, "ARRAYBUFFER");
57295
+ hmac.setHMACKey(key, "ARRAYBUFFER");
57296
+ hmac.update(message);
57297
+ return hmac.getHMAC("ARRAYBUFFER");
57298
+ }
57275
57299
  };
57276
-
57277
- // packages/sdk/cipher.js
57278
- var Cipher = class _Cipher {
57279
- static hash(text, algorithm = config_default.hashAlgo, encoding = "hex") {
57280
- const hash = import_crypto.default.createHash(algorithm);
57281
- hash.update(text);
57282
- return hash.digest(encoding);
57300
+ var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
57301
+ var base32ToBuf = (str) => {
57302
+ let end = str.length;
57303
+ while (str[end - 1] === "=")
57304
+ --end;
57305
+ const cstr = (end < str.length ? str.substring(0, end) : str).toUpperCase();
57306
+ const buf = new ArrayBuffer(cstr.length * 5 / 8 | 0);
57307
+ const arr = new Uint8Array(buf);
57308
+ let bits = 0;
57309
+ let value = 0;
57310
+ let index = 0;
57311
+ for (let i = 0; i < cstr.length; i++) {
57312
+ const idx = ALPHABET.indexOf(cstr[i]);
57313
+ if (idx === -1)
57314
+ throw new TypeError(`Invalid character found: ${cstr[i]}`);
57315
+ value = value << 5 | idx;
57316
+ bits += 5;
57317
+ if (bits >= 8) {
57318
+ bits -= 8;
57319
+ arr[index++] = value >>> bits;
57320
+ }
57283
57321
  }
57284
- static random(size = config_default.randomSize) {
57285
- const rnd = import_crypto.default.randomBytes(size);
57286
- return rnd;
57322
+ return buf;
57323
+ };
57324
+ var base32FromBuf = (buf) => {
57325
+ const arr = new Uint8Array(buf);
57326
+ let bits = 0;
57327
+ let value = 0;
57328
+ let str = "";
57329
+ for (let i = 0; i < arr.length; i++) {
57330
+ value = value << 8 | arr[i];
57331
+ bits += 8;
57332
+ while (bits >= 5) {
57333
+ str += ALPHABET[value >>> bits - 5 & 31];
57334
+ bits -= 5;
57335
+ }
57287
57336
  }
57288
- static randomString(encoding = "hex") {
57289
- const rnd = _Cipher.random().toString(encoding);
57290
- return rnd;
57337
+ if (bits > 0) {
57338
+ str += ALPHABET[value << 5 - bits & 31];
57291
57339
  }
57292
- static sign(text) {
57293
- const hash = _Cipher.hash(text);
57294
- const signature = `${hash.substring(0, 10)}:${hash.substring(hash.length - 10)}`;
57295
- return signature;
57340
+ return str;
57341
+ };
57342
+ var hexToBuf = (str) => {
57343
+ const buf = new ArrayBuffer(str.length / 2);
57344
+ const arr = new Uint8Array(buf);
57345
+ for (let i = 0; i < str.length; i += 2) {
57346
+ arr[i / 2] = parseInt(str.substring(i, i + 2), 16);
57296
57347
  }
57297
- static verify(text, signature) {
57298
- const expectedSignature = _Cipher.sign(text);
57299
- return expectedSignature === signature;
57348
+ return buf;
57349
+ };
57350
+ var hexFromBuf = (buf) => {
57351
+ const arr = new Uint8Array(buf);
57352
+ let str = "";
57353
+ for (let i = 0; i < arr.length; i++) {
57354
+ const hex = arr[i].toString(16);
57355
+ if (hex.length === 1)
57356
+ str += "0";
57357
+ str += hex;
57300
57358
  }
57301
- static encrypt({
57302
- value,
57303
- encryptionKey,
57304
- algorithm = config_default.encryptionALgo,
57305
- encoding = "hex"
57306
- }) {
57307
- const publicKey = _Cipher.randomString();
57308
- let cipher = import_crypto.default.createCipheriv(
57309
- algorithm,
57310
- Buffer.from(encryptionKey, encoding),
57311
- Buffer.from(publicKey, encoding),
57312
- { authTagLength: 16 }
57313
- );
57314
- let encrypted = cipher.update(value);
57315
- encrypted = Buffer.concat([encrypted, cipher.final()]);
57316
- encrypted = encrypted.toString(encoding);
57317
- const authTag = cipher.getAuthTag().toString(encoding);
57318
- return {
57319
- publicKey,
57320
- encrypted,
57321
- algorithm,
57322
- signature: _Cipher.sign(value),
57323
- encoding,
57324
- authTag,
57325
- provider: "crypto",
57326
- platform: "autho"
57327
- };
57359
+ return str.toUpperCase();
57360
+ };
57361
+ var latin1ToBuf = (str) => {
57362
+ const buf = new ArrayBuffer(str.length);
57363
+ const arr = new Uint8Array(buf);
57364
+ for (let i = 0; i < str.length; i++) {
57365
+ arr[i] = str.charCodeAt(i) & 255;
57328
57366
  }
57329
- static decrypt({
57330
- value,
57331
- publicKey,
57332
- encryptionKey,
57333
- signature = false,
57334
- algorithm = config_default.encryptionALgo,
57335
- authTag,
57336
- encoding = "hex"
57337
- }) {
57338
- value = Buffer.from(value, encoding);
57339
- let decipher = import_crypto.default.createDecipheriv(
57340
- algorithm,
57341
- Buffer.from(encryptionKey, encoding),
57342
- Buffer.from(publicKey, encoding),
57343
- { authTagLength: 16 }
57344
- );
57345
- if (authTag) {
57346
- decipher.setAuthTag(Buffer.from(authTag, encoding));
57347
- }
57348
- let decrypted = decipher.update(value);
57349
- decrypted = Buffer.concat([decrypted, decipher.final()]);
57350
- decrypted = decrypted.toString();
57351
- if (signature && !_Cipher.verify(decrypted, signature)) {
57352
- throw new Error("Invalid signature");
57353
- }
57354
- return decrypted;
57367
+ return buf;
57368
+ };
57369
+ var latin1FromBuf = (buf) => {
57370
+ const arr = new Uint8Array(buf);
57371
+ let str = "";
57372
+ for (let i = 0; i < arr.length; i++) {
57373
+ str += String.fromCharCode(arr[i]);
57355
57374
  }
57356
- static canDecrypt(options) {
57357
- return options.platform === "autho";
57375
+ return str;
57376
+ };
57377
+ var ENCODER = globalScope.TextEncoder ? new globalScope.TextEncoder("utf-8") : null;
57378
+ var DECODER = globalScope.TextDecoder ? new globalScope.TextDecoder("utf-8") : null;
57379
+ var utf8ToBuf = (str) => {
57380
+ if (!ENCODER) {
57381
+ throw new Error("Encoding API not available");
57358
57382
  }
57359
- static encryptFile(inputFilePath, outputFilePath, encryptionKey) {
57360
- const inputBuffer = import_fs.default.readFileSync(inputFilePath);
57361
- const params = {
57362
- value: inputBuffer,
57363
- encryptionKey
57364
- };
57365
- const encryptedData = _Cipher.encrypt(params);
57366
- import_fs.default.writeFileSync(
57367
- outputFilePath,
57368
- Buffer.from(JSON.stringify(encryptedData)).toString("base64")
57369
- );
57383
+ return ENCODER.encode(str).buffer;
57384
+ };
57385
+ var utf8FromBuf = (buf) => {
57386
+ if (!DECODER) {
57387
+ throw new Error("Encoding API not available");
57370
57388
  }
57371
- static decryptFile(inputFilePath, outputFilePath, encryptionKey) {
57372
- const inputFileContent = import_fs.default.readFileSync(inputFilePath);
57373
- const decoded = Buffer.from(
57374
- inputFileContent.toString("utf-8"),
57375
- "base64"
57376
- ).toString("utf-8");
57377
- const encryptedData = JSON.parse(decoded);
57378
- if (!_Cipher.canDecrypt(encryptedData)) {
57379
- throw new Error("Invalid file");
57389
+ return DECODER.decode(buf);
57390
+ };
57391
+ var randomBytes2 = (size) => {
57392
+ if (crypto?.randomBytes) {
57393
+ return crypto.randomBytes(size).buffer;
57394
+ } else {
57395
+ if (!globalScope.crypto?.getRandomValues) {
57396
+ throw new Error("Cryptography API not available");
57380
57397
  }
57381
- const params = {
57382
- ...encryptedData,
57383
- value: encryptedData.encrypted,
57384
- encryptionKey
57385
- };
57386
- const decryptedData = _Cipher.decrypt(params);
57387
- import_fs.default.writeFileSync(outputFilePath, decryptedData);
57398
+ return globalScope.crypto.getRandomValues(new Uint8Array(size)).buffer;
57388
57399
  }
57389
- static encryptFolder({ inputFolderPath, outputFilePath, encryptionKey, algorithm = config_default.encryptionALgo, encoding = "hex" }) {
57390
- const outputStream = import_fs.default.createWriteStream(outputFilePath);
57391
- const gzip = import_zlib.default.createGzip();
57392
- gzip.pipe(outputStream);
57393
- const baseFolder = import_path.default.basename(inputFolderPath);
57394
- function traverseFolder(folderPath) {
57395
- const items = import_fs.default.readdirSync(folderPath);
57396
- for (const item of items) {
57397
- const itemPath = import_path.default.join(baseFolder, import_path.default.relative(inputFolderPath, import_path.default.join(folderPath, item)));
57398
- if (import_fs.default.statSync(itemPath).isDirectory()) {
57399
- traverseFolder(itemPath);
57400
- } else {
57401
- const fileContent = import_fs.default.readFileSync(itemPath);
57402
- const params = {
57403
- value: fileContent,
57404
- encryptionKey,
57405
- algorithm,
57406
- encoding
57407
- };
57408
- const encryptedData = _Cipher.encrypt(params);
57409
- const encrypted = encryptedData.encrypted;
57410
- delete encryptedData.encrypted;
57411
- const encryptionMeta = Buffer.from(JSON.stringify(encryptedData)).toString("base64");
57412
- gzip.write(`${itemPath}
57413
- ---
57414
- ${encrypted}
57415
- ---
57416
- ${encryptionMeta}
57417
- :::
57418
- `);
57419
- }
57420
- }
57421
- }
57422
- traverseFolder(inputFolderPath);
57423
- gzip.end();
57424
- return new Promise((resolve, reject) => {
57425
- outputStream.on("finish", resolve);
57426
- outputStream.on("error", reject);
57427
- });
57400
+ };
57401
+ var Secret = class _Secret {
57402
+ /**
57403
+ * Creates a secret key object.
57404
+ * @param {Object} [config] Configuration options.
57405
+ * @param {ArrayBuffer} [config.buffer=randomBytes] Secret key.
57406
+ * @param {number} [config.size=20] Number of random bytes to generate, ignored if 'buffer' is provided.
57407
+ */
57408
+ constructor({
57409
+ buffer,
57410
+ size = 20
57411
+ } = {}) {
57412
+ this.buffer = typeof buffer === "undefined" ? randomBytes2(size) : buffer;
57428
57413
  }
57429
- static decryptFolder({ inputFilePath, outputFolderPath, encryptionKey }) {
57430
- const inputStream = import_fs.default.createReadStream(inputFilePath);
57431
- const gunzip = import_zlib.default.createGunzip();
57432
- inputStream.pipe(gunzip);
57433
- let buff = "";
57434
- const compileFile = (data) => {
57435
- buff += data;
57436
- if (buff.includes(":::")) {
57437
- const [file, next] = buff.split("\n:::\n");
57438
- let [filePath, encrypted, encryptionMeta] = file.split("\n---\n");
57439
- filePath = import_path.default.join(outputFolderPath, filePath);
57440
- try {
57441
- import_fs.default.mkdirSync(import_path.default.dirname(filePath), { recursive: true });
57442
- } catch (error) {
57443
- }
57444
- const decoded = Buffer.from(
57445
- encryptionMeta,
57446
- "base64"
57447
- ).toString("utf-8");
57448
- const metaData = JSON.parse(decoded);
57449
- const params = {
57450
- ...metaData,
57451
- value: encrypted,
57452
- encryptionKey
57453
- };
57454
- const decryptedData = _Cipher.decrypt(params);
57455
- import_fs.default.writeFileSync(filePath, decryptedData);
57456
- buff = next;
57457
- }
57458
- };
57459
- gunzip.on("data", (data) => {
57460
- compileFile(data.toString("utf8"));
57461
- });
57462
- return new Promise((resolve, reject) => {
57463
- gunzip.on("end", resolve);
57464
- gunzip.on("error", reject);
57414
+ /**
57415
+ * Converts a Latin-1 string to a Secret object.
57416
+ * @param {string} str Latin-1 string.
57417
+ * @returns {Secret} Secret object.
57418
+ */
57419
+ static fromLatin1(str) {
57420
+ return new _Secret({
57421
+ buffer: latin1ToBuf(str)
57465
57422
  });
57466
57423
  }
57467
- };
57468
-
57469
- // packages/sdk/secrets.js
57470
- var Secrets = class {
57471
- constructor(db) {
57472
- this.db = db;
57424
+ /**
57425
+ * Converts an UTF-8 string to a Secret object.
57426
+ * @param {string} str UTF-8 string.
57427
+ * @returns {Secret} Secret object.
57428
+ */
57429
+ static fromUTF8(str) {
57430
+ return new _Secret({
57431
+ buffer: utf8ToBuf(str)
57432
+ });
57473
57433
  }
57474
- get secrets() {
57475
- return this.db.get("secrets", []);
57434
+ /**
57435
+ * Converts a base32 string to a Secret object.
57436
+ * @param {string} str Base32 string.
57437
+ * @returns {Secret} Secret object.
57438
+ */
57439
+ static fromBase32(str) {
57440
+ return new _Secret({
57441
+ buffer: base32ToBuf(str)
57442
+ });
57476
57443
  }
57477
- set secrets(value) {
57478
- this.db.set("secrets", value);
57444
+ /**
57445
+ * Converts a hexadecimal string to a Secret object.
57446
+ * @param {string} str Hexadecimal string.
57447
+ * @returns {Secret} Secret object.
57448
+ */
57449
+ static fromHex(str) {
57450
+ return new _Secret({
57451
+ buffer: hexToBuf(str)
57452
+ });
57479
57453
  }
57480
- async get(id) {
57481
- return this.secrets.find((secret) => secret.id == id);
57454
+ /**
57455
+ * Latin-1 string representation of secret key.
57456
+ * @type {string}
57457
+ */
57458
+ get latin1() {
57459
+ Object.defineProperty(this, "latin1", {
57460
+ enumerable: true,
57461
+ value: latin1FromBuf(this.buffer)
57462
+ });
57463
+ return this.latin1;
57482
57464
  }
57483
- async add(secret, encryptionKey) {
57484
- const { value, error } = createSecretSchema.validate(secret);
57485
- if (error) {
57486
- throw new Error(error);
57487
- }
57488
- const { encrypted, ...encryption } = Cipher.encrypt({
57489
- ...value,
57490
- encryptionKey
57465
+ /**
57466
+ * UTF-8 string representation of secret key.
57467
+ * @type {string}
57468
+ */
57469
+ get utf8() {
57470
+ Object.defineProperty(this, "utf8", {
57471
+ enumerable: true,
57472
+ value: utf8FromBuf(this.buffer)
57491
57473
  });
57492
- this.secrets = [
57493
- ...this.secrets,
57494
- { ...value, ...encryption, value: encrypted }
57495
- ];
57474
+ return this.utf8;
57496
57475
  }
57497
- async remove(id) {
57498
- this.secrets = this.secrets.filter((secret) => secret.id != id);
57476
+ /**
57477
+ * Base32 string representation of secret key.
57478
+ * @type {string}
57479
+ */
57480
+ get base32() {
57481
+ Object.defineProperty(this, "base32", {
57482
+ enumerable: true,
57483
+ value: base32FromBuf(this.buffer)
57484
+ });
57485
+ return this.base32;
57499
57486
  }
57500
- async clear() {
57501
- this.secrets = [];
57487
+ /**
57488
+ * Hexadecimal string representation of secret key.
57489
+ * @type {string}
57490
+ */
57491
+ get hex() {
57492
+ Object.defineProperty(this, "hex", {
57493
+ enumerable: true,
57494
+ value: hexFromBuf(this.buffer)
57495
+ });
57496
+ return this.hex;
57502
57497
  }
57503
57498
  };
57504
-
57505
- // node_modules/.pnpm/conf@12.0.0/node_modules/conf/dist/source/index.js
57506
- var import_node_util2 = require("node:util");
57507
- var import_node_process7 = __toESM(require("node:process"), 1);
57508
- var import_node_fs2 = __toESM(require("node:fs"), 1);
57509
- var import_node_path4 = __toESM(require("node:path"), 1);
57510
- var import_node_crypto2 = __toESM(require("node:crypto"), 1);
57511
- var import_node_assert2 = __toESM(require("node:assert"), 1);
57512
-
57513
- // node_modules/.pnpm/dot-prop@8.0.2/node_modules/dot-prop/index.js
57514
- var isObject = (value) => {
57515
- const type = typeof value;
57516
- return value !== null && (type === "object" || type === "function");
57499
+ var timingSafeEqual2 = (a, b) => {
57500
+ if (crypto?.timingSafeEqual) {
57501
+ return crypto.timingSafeEqual(globalScope.Buffer.from(a), globalScope.Buffer.from(b));
57502
+ } else {
57503
+ if (a.length !== b.length) {
57504
+ throw new TypeError("Input strings must have the same length");
57505
+ }
57506
+ let i = -1;
57507
+ let out = 0;
57508
+ while (++i < a.length) {
57509
+ out |= a.charCodeAt(i) ^ b.charCodeAt(i);
57510
+ }
57511
+ return out === 0;
57512
+ }
57517
57513
  };
57518
- var disallowedKeys = /* @__PURE__ */ new Set([
57519
- "__proto__",
57520
- "prototype",
57521
- "constructor"
57522
- ]);
57523
- var digits = new Set("0123456789");
57524
- function getPathSegments(path5) {
57525
- const parts = [];
57526
- let currentSegment = "";
57527
- let currentPart = "start";
57528
- let isIgnoring = false;
57529
- for (const character of path5) {
57530
- switch (character) {
57531
- case "\\": {
57532
- if (currentPart === "index") {
57533
- throw new Error("Invalid character in an index");
57534
- }
57535
- if (currentPart === "indexEnd") {
57536
- throw new Error("Invalid character after an index");
57537
- }
57538
- if (isIgnoring) {
57539
- currentSegment += character;
57540
- }
57541
- currentPart = "property";
57542
- isIgnoring = !isIgnoring;
57543
- break;
57544
- }
57545
- case ".": {
57546
- if (currentPart === "index") {
57547
- throw new Error("Invalid character in an index");
57548
- }
57549
- if (currentPart === "indexEnd") {
57550
- currentPart = "property";
57551
- break;
57552
- }
57553
- if (isIgnoring) {
57554
- isIgnoring = false;
57555
- currentSegment += character;
57556
- break;
57557
- }
57558
- if (disallowedKeys.has(currentSegment)) {
57559
- return [];
57560
- }
57561
- parts.push(currentSegment);
57562
- currentSegment = "";
57563
- currentPart = "property";
57564
- break;
57565
- }
57566
- case "[": {
57567
- if (currentPart === "index") {
57568
- throw new Error("Invalid character in an index");
57569
- }
57570
- if (currentPart === "indexEnd") {
57571
- currentPart = "index";
57572
- break;
57573
- }
57574
- if (isIgnoring) {
57575
- isIgnoring = false;
57576
- currentSegment += character;
57577
- break;
57578
- }
57579
- if (currentPart === "property") {
57580
- if (disallowedKeys.has(currentSegment)) {
57581
- return [];
57582
- }
57583
- parts.push(currentSegment);
57584
- currentSegment = "";
57585
- }
57586
- currentPart = "index";
57587
- break;
57588
- }
57589
- case "]": {
57590
- if (currentPart === "index") {
57591
- parts.push(Number.parseInt(currentSegment, 10));
57592
- currentSegment = "";
57593
- currentPart = "indexEnd";
57594
- break;
57595
- }
57596
- if (currentPart === "indexEnd") {
57597
- throw new Error("Invalid character after an index");
57598
- }
57599
- }
57600
- default: {
57601
- if (currentPart === "index" && !digits.has(character)) {
57602
- throw new Error("Invalid character in an index");
57603
- }
57604
- if (currentPart === "indexEnd") {
57605
- throw new Error("Invalid character after an index");
57606
- }
57607
- if (currentPart === "start") {
57608
- currentPart = "property";
57609
- }
57610
- if (isIgnoring) {
57611
- isIgnoring = false;
57612
- currentSegment += "\\";
57613
- }
57614
- currentSegment += character;
57615
- }
57616
- }
57617
- }
57618
- if (isIgnoring) {
57619
- currentSegment += "\\";
57620
- }
57621
- switch (currentPart) {
57622
- case "property": {
57623
- if (disallowedKeys.has(currentSegment)) {
57624
- return [];
57625
- }
57626
- parts.push(currentSegment);
57627
- break;
57628
- }
57629
- case "index": {
57630
- throw new Error("Index was not closed");
57631
- }
57632
- case "start": {
57633
- parts.push("");
57634
- break;
57635
- }
57636
- }
57637
- return parts;
57638
- }
57639
- function isStringIndex(object, key) {
57640
- if (typeof key !== "number" && Array.isArray(object)) {
57641
- const index = Number.parseInt(key, 10);
57642
- return Number.isInteger(index) && object[index] === object[key];
57514
+ var HOTP = class _HOTP {
57515
+ /**
57516
+ * Default configuration.
57517
+ * @type {{
57518
+ * issuer: string,
57519
+ * label: string,
57520
+ * issuerInLabel: boolean,
57521
+ * algorithm: string,
57522
+ * digits: number,
57523
+ * counter: number
57524
+ * window: number
57525
+ * }}
57526
+ */
57527
+ static get defaults() {
57528
+ return {
57529
+ issuer: "",
57530
+ label: "OTPAuth",
57531
+ issuerInLabel: true,
57532
+ algorithm: "SHA1",
57533
+ digits: 6,
57534
+ counter: 0,
57535
+ window: 1
57536
+ };
57643
57537
  }
57644
- return false;
57645
- }
57646
- function assertNotStringIndex(object, key) {
57647
- if (isStringIndex(object, key)) {
57648
- throw new Error("Cannot use string index");
57538
+ /**
57539
+ * Creates an HOTP object.
57540
+ * @param {Object} [config] Configuration options.
57541
+ * @param {string} [config.issuer=''] Account provider.
57542
+ * @param {string} [config.label='OTPAuth'] Account label.
57543
+ * @param {boolean} [config.issuerInLabel=true] Include issuer prefix in label.
57544
+ * @param {Secret|string} [config.secret=Secret] Secret key.
57545
+ * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
57546
+ * @param {number} [config.digits=6] Token length.
57547
+ * @param {number} [config.counter=0] Initial counter value.
57548
+ */
57549
+ constructor({
57550
+ issuer = _HOTP.defaults.issuer,
57551
+ label = _HOTP.defaults.label,
57552
+ issuerInLabel = _HOTP.defaults.issuerInLabel,
57553
+ secret = new Secret(),
57554
+ algorithm = _HOTP.defaults.algorithm,
57555
+ digits: digits2 = _HOTP.defaults.digits,
57556
+ counter = _HOTP.defaults.counter
57557
+ } = {}) {
57558
+ this.issuer = issuer;
57559
+ this.label = label;
57560
+ this.issuerInLabel = issuerInLabel;
57561
+ this.secret = typeof secret === "string" ? Secret.fromBase32(secret) : secret;
57562
+ this.algorithm = algorithm.toUpperCase();
57563
+ this.digits = digits2;
57564
+ this.counter = counter;
57649
57565
  }
57650
- }
57651
- function getProperty(object, path5, value) {
57652
- if (!isObject(object) || typeof path5 !== "string") {
57653
- return value === void 0 ? object : value;
57566
+ /**
57567
+ * Generates an HOTP token.
57568
+ * @param {Object} config Configuration options.
57569
+ * @param {Secret} config.secret Secret key.
57570
+ * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
57571
+ * @param {number} [config.digits=6] Token length.
57572
+ * @param {number} [config.counter=0] Counter value.
57573
+ * @returns {string} Token.
57574
+ */
57575
+ static generate({
57576
+ secret,
57577
+ algorithm = _HOTP.defaults.algorithm,
57578
+ digits: digits2 = _HOTP.defaults.digits,
57579
+ counter = _HOTP.defaults.counter
57580
+ }) {
57581
+ const digest = new Uint8Array(hmacDigest(algorithm, secret.buffer, uintToBuf(counter)));
57582
+ const offset = digest[digest.byteLength - 1] & 15;
57583
+ const otp = ((digest[offset] & 127) << 24 | (digest[offset + 1] & 255) << 16 | (digest[offset + 2] & 255) << 8 | digest[offset + 3] & 255) % 10 ** digits2;
57584
+ return otp.toString().padStart(digits2, "0");
57654
57585
  }
57655
- const pathArray = getPathSegments(path5);
57656
- if (pathArray.length === 0) {
57657
- return value;
57586
+ /**
57587
+ * Generates an HOTP token.
57588
+ * @param {Object} [config] Configuration options.
57589
+ * @param {number} [config.counter=this.counter++] Counter value.
57590
+ * @returns {string} Token.
57591
+ */
57592
+ generate({
57593
+ counter = this.counter++
57594
+ } = {}) {
57595
+ return _HOTP.generate({
57596
+ secret: this.secret,
57597
+ algorithm: this.algorithm,
57598
+ digits: this.digits,
57599
+ counter
57600
+ });
57658
57601
  }
57659
- for (let index = 0; index < pathArray.length; index++) {
57660
- const key = pathArray[index];
57661
- if (isStringIndex(object, key)) {
57662
- object = index === pathArray.length - 1 ? void 0 : null;
57663
- } else {
57664
- object = object[key];
57665
- }
57666
- if (object === void 0 || object === null) {
57667
- if (index !== pathArray.length - 1) {
57668
- return value;
57602
+ /**
57603
+ * Validates an HOTP token.
57604
+ * @param {Object} config Configuration options.
57605
+ * @param {string} config.token Token value.
57606
+ * @param {Secret} config.secret Secret key.
57607
+ * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
57608
+ * @param {number} config.digits Token length.
57609
+ * @param {number} [config.counter=0] Counter value.
57610
+ * @param {number} [config.window=1] Window of counter values to test.
57611
+ * @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
57612
+ */
57613
+ static validate({
57614
+ token,
57615
+ secret,
57616
+ algorithm,
57617
+ digits: digits2,
57618
+ counter = _HOTP.defaults.counter,
57619
+ window: window2 = _HOTP.defaults.window
57620
+ }) {
57621
+ if (token.length !== digits2)
57622
+ return null;
57623
+ let delta = null;
57624
+ for (let i = counter - window2; i <= counter + window2; ++i) {
57625
+ const generatedToken = _HOTP.generate({
57626
+ secret,
57627
+ algorithm,
57628
+ digits: digits2,
57629
+ counter: i
57630
+ });
57631
+ if (timingSafeEqual2(token, generatedToken)) {
57632
+ delta = i - counter;
57669
57633
  }
57670
- break;
57671
- }
57672
- }
57673
- return object === void 0 ? value : object;
57674
- }
57675
- function setProperty(object, path5, value) {
57676
- if (!isObject(object) || typeof path5 !== "string") {
57677
- return object;
57678
- }
57679
- const root = object;
57680
- const pathArray = getPathSegments(path5);
57681
- for (let index = 0; index < pathArray.length; index++) {
57682
- const key = pathArray[index];
57683
- assertNotStringIndex(object, key);
57684
- if (index === pathArray.length - 1) {
57685
- object[key] = value;
57686
- } else if (!isObject(object[key])) {
57687
- object[key] = typeof pathArray[index + 1] === "number" ? [] : {};
57688
- }
57689
- object = object[key];
57690
- }
57691
- return root;
57692
- }
57693
- function deleteProperty(object, path5) {
57694
- if (!isObject(object) || typeof path5 !== "string") {
57695
- return false;
57696
- }
57697
- const pathArray = getPathSegments(path5);
57698
- for (let index = 0; index < pathArray.length; index++) {
57699
- const key = pathArray[index];
57700
- assertNotStringIndex(object, key);
57701
- if (index === pathArray.length - 1) {
57702
- delete object[key];
57703
- return true;
57704
- }
57705
- object = object[key];
57706
- if (!isObject(object)) {
57707
- return false;
57708
57634
  }
57635
+ return delta;
57709
57636
  }
57710
- }
57711
- function hasProperty(object, path5) {
57712
- if (!isObject(object) || typeof path5 !== "string") {
57713
- return false;
57714
- }
57715
- const pathArray = getPathSegments(path5);
57716
- if (pathArray.length === 0) {
57717
- return false;
57637
+ /**
57638
+ * Validates an HOTP token.
57639
+ * @param {Object} config Configuration options.
57640
+ * @param {string} config.token Token value.
57641
+ * @param {number} [config.counter=this.counter] Counter value.
57642
+ * @param {number} [config.window=1] Window of counter values to test.
57643
+ * @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
57644
+ */
57645
+ validate({
57646
+ token,
57647
+ counter = this.counter,
57648
+ window: window2
57649
+ }) {
57650
+ return _HOTP.validate({
57651
+ token,
57652
+ secret: this.secret,
57653
+ algorithm: this.algorithm,
57654
+ digits: this.digits,
57655
+ counter,
57656
+ window: window2
57657
+ });
57718
57658
  }
57719
- for (const key of pathArray) {
57720
- if (!isObject(object) || !(key in object) || isStringIndex(object, key)) {
57721
- return false;
57722
- }
57723
- object = object[key];
57659
+ /**
57660
+ * Returns a Google Authenticator key URI.
57661
+ * @returns {string} URI.
57662
+ */
57663
+ toString() {
57664
+ const e = encodeURIComponent;
57665
+ return `otpauth://hotp/${this.issuer.length > 0 ? this.issuerInLabel ? `${e(this.issuer)}:${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?`}secret=${e(this.secret.base32)}&algorithm=${e(this.algorithm)}&digits=${e(this.digits)}&counter=${e(this.counter)}`;
57724
57666
  }
57725
- return true;
57726
- }
57727
-
57728
- // node_modules/.pnpm/env-paths@3.0.0/node_modules/env-paths/index.js
57729
- var import_node_path = __toESM(require("node:path"), 1);
57730
- var import_node_os2 = __toESM(require("node:os"), 1);
57731
- var import_node_process2 = __toESM(require("node:process"), 1);
57732
- var homedir = import_node_os2.default.homedir();
57733
- var tmpdir = import_node_os2.default.tmpdir();
57734
- var { env: env2 } = import_node_process2.default;
57735
- var macos = (name) => {
57736
- const library = import_node_path.default.join(homedir, "Library");
57737
- return {
57738
- data: import_node_path.default.join(library, "Application Support", name),
57739
- config: import_node_path.default.join(library, "Preferences", name),
57740
- cache: import_node_path.default.join(library, "Caches", name),
57741
- log: import_node_path.default.join(library, "Logs", name),
57742
- temp: import_node_path.default.join(tmpdir, name)
57743
- };
57744
- };
57745
- var windows = (name) => {
57746
- const appData = env2.APPDATA || import_node_path.default.join(homedir, "AppData", "Roaming");
57747
- const localAppData = env2.LOCALAPPDATA || import_node_path.default.join(homedir, "AppData", "Local");
57748
- return {
57749
- // Data/config/cache/log are invented by me as Windows isn't opinionated about this
57750
- data: import_node_path.default.join(localAppData, name, "Data"),
57751
- config: import_node_path.default.join(appData, name, "Config"),
57752
- cache: import_node_path.default.join(localAppData, name, "Cache"),
57753
- log: import_node_path.default.join(localAppData, name, "Log"),
57754
- temp: import_node_path.default.join(tmpdir, name)
57755
- };
57756
- };
57757
- var linux = (name) => {
57758
- const username = import_node_path.default.basename(homedir);
57759
- return {
57760
- data: import_node_path.default.join(env2.XDG_DATA_HOME || import_node_path.default.join(homedir, ".local", "share"), name),
57761
- config: import_node_path.default.join(env2.XDG_CONFIG_HOME || import_node_path.default.join(homedir, ".config"), name),
57762
- cache: import_node_path.default.join(env2.XDG_CACHE_HOME || import_node_path.default.join(homedir, ".cache"), name),
57763
- // https://wiki.debian.org/XDGBaseDirectorySpecification#state
57764
- log: import_node_path.default.join(env2.XDG_STATE_HOME || import_node_path.default.join(homedir, ".local", "state"), name),
57765
- temp: import_node_path.default.join(tmpdir, username, name)
57766
- };
57767
57667
  };
57768
- function envPaths(name, { suffix = "nodejs" } = {}) {
57769
- if (typeof name !== "string") {
57770
- throw new TypeError(`Expected a string, got ${typeof name}`);
57771
- }
57772
- if (suffix) {
57773
- name += `-${suffix}`;
57774
- }
57775
- if (import_node_process2.default.platform === "darwin") {
57776
- return macos(name);
57668
+ var TOTP = class _TOTP {
57669
+ /**
57670
+ * Default configuration.
57671
+ * @type {{
57672
+ * issuer: string,
57673
+ * label: string,
57674
+ * issuerInLabel: boolean,
57675
+ * algorithm: string,
57676
+ * digits: number,
57677
+ * period: number
57678
+ * window: number
57679
+ * }}
57680
+ */
57681
+ static get defaults() {
57682
+ return {
57683
+ issuer: "",
57684
+ label: "OTPAuth",
57685
+ issuerInLabel: true,
57686
+ algorithm: "SHA1",
57687
+ digits: 6,
57688
+ period: 30,
57689
+ window: 1
57690
+ };
57777
57691
  }
57778
- if (import_node_process2.default.platform === "win32") {
57779
- return windows(name);
57692
+ /**
57693
+ * Creates a TOTP object.
57694
+ * @param {Object} [config] Configuration options.
57695
+ * @param {string} [config.issuer=''] Account provider.
57696
+ * @param {string} [config.label='OTPAuth'] Account label.
57697
+ * @param {boolean} [config.issuerInLabel=true] Include issuer prefix in label.
57698
+ * @param {Secret|string} [config.secret=Secret] Secret key.
57699
+ * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
57700
+ * @param {number} [config.digits=6] Token length.
57701
+ * @param {number} [config.period=30] Token time-step duration.
57702
+ */
57703
+ constructor({
57704
+ issuer = _TOTP.defaults.issuer,
57705
+ label = _TOTP.defaults.label,
57706
+ issuerInLabel = _TOTP.defaults.issuerInLabel,
57707
+ secret = new Secret(),
57708
+ algorithm = _TOTP.defaults.algorithm,
57709
+ digits: digits2 = _TOTP.defaults.digits,
57710
+ period = _TOTP.defaults.period
57711
+ } = {}) {
57712
+ this.issuer = issuer;
57713
+ this.label = label;
57714
+ this.issuerInLabel = issuerInLabel;
57715
+ this.secret = typeof secret === "string" ? Secret.fromBase32(secret) : secret;
57716
+ this.algorithm = algorithm.toUpperCase();
57717
+ this.digits = digits2;
57718
+ this.period = period;
57780
57719
  }
57781
- return linux(name);
57782
- }
57783
-
57784
- // node_modules/.pnpm/atomically@2.0.3/node_modules/atomically/dist/index.js
57785
- var import_node_path3 = __toESM(require("node:path"), 1);
57786
-
57787
- // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/index.js
57788
- var import_node_fs = __toESM(require("node:fs"), 1);
57789
- var import_node_util = require("node:util");
57790
-
57791
- // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/attemptify.js
57792
- var attemptifyAsync = (fn, onError) => {
57793
- return function attemptified(...args) {
57794
- return fn.apply(void 0, args).catch(onError);
57795
- };
57796
- };
57797
- var attemptifySync = (fn, onError) => {
57798
- return function attemptified(...args) {
57799
- try {
57800
- return fn.apply(void 0, args);
57801
- } catch (error) {
57802
- return onError(error);
57803
- }
57804
- };
57805
- };
57806
-
57807
- // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/constants.js
57808
- var import_node_process3 = __toESM(require("node:process"), 1);
57809
- var IS_USER_ROOT = import_node_process3.default.getuid ? !import_node_process3.default.getuid() : false;
57810
- var LIMIT_FILES_DESCRIPTORS = 1e4;
57811
- var NOOP = () => void 0;
57812
-
57813
- // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/handlers.js
57814
- var Handlers = {
57815
- /* API */
57816
- isChangeErrorOk: (error) => {
57817
- if (!Handlers.isNodeError(error))
57818
- return false;
57819
- const { code } = error;
57820
- if (code === "ENOSYS")
57821
- return true;
57822
- if (!IS_USER_ROOT && (code === "EINVAL" || code === "EPERM"))
57823
- return true;
57824
- return false;
57825
- },
57826
- isNodeError: (error) => {
57827
- return error instanceof Error;
57828
- },
57829
- isRetriableError: (error) => {
57830
- if (!Handlers.isNodeError(error))
57831
- return false;
57832
- const { code } = error;
57833
- if (code === "EMFILE" || code === "ENFILE" || code === "EAGAIN" || code === "EBUSY" || code === "EACCESS" || code === "EACCES" || code === "EACCS" || code === "EPERM")
57834
- return true;
57835
- return false;
57836
- },
57837
- onChangeError: (error) => {
57838
- if (!Handlers.isNodeError(error))
57839
- throw error;
57840
- if (Handlers.isChangeErrorOk(error))
57841
- return;
57842
- throw error;
57720
+ /**
57721
+ * Generates a TOTP token.
57722
+ * @param {Object} config Configuration options.
57723
+ * @param {Secret} config.secret Secret key.
57724
+ * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
57725
+ * @param {number} [config.digits=6] Token length.
57726
+ * @param {number} [config.period=30] Token time-step duration.
57727
+ * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
57728
+ * @returns {string} Token.
57729
+ */
57730
+ static generate({
57731
+ secret,
57732
+ algorithm,
57733
+ digits: digits2,
57734
+ period = _TOTP.defaults.period,
57735
+ timestamp = Date.now()
57736
+ }) {
57737
+ return HOTP.generate({
57738
+ secret,
57739
+ algorithm,
57740
+ digits: digits2,
57741
+ counter: Math.floor(timestamp / 1e3 / period)
57742
+ });
57843
57743
  }
57844
- };
57845
- var handlers_default = Handlers;
57846
-
57847
- // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/retryify_queue.js
57848
- var RetryfyQueue = class {
57849
- constructor() {
57850
- this.interval = 25;
57851
- this.intervalId = void 0;
57852
- this.limit = LIMIT_FILES_DESCRIPTORS;
57853
- this.queueActive = /* @__PURE__ */ new Set();
57854
- this.queueWaiting = /* @__PURE__ */ new Set();
57855
- this.init = () => {
57856
- if (this.intervalId)
57857
- return;
57858
- this.intervalId = setInterval(this.tick, this.interval);
57859
- };
57860
- this.reset = () => {
57861
- if (!this.intervalId)
57862
- return;
57863
- clearInterval(this.intervalId);
57864
- delete this.intervalId;
57865
- };
57866
- this.add = (fn) => {
57867
- this.queueWaiting.add(fn);
57868
- if (this.queueActive.size < this.limit / 2) {
57869
- this.tick();
57870
- } else {
57871
- this.init();
57872
- }
57873
- };
57874
- this.remove = (fn) => {
57875
- this.queueWaiting.delete(fn);
57876
- this.queueActive.delete(fn);
57877
- };
57878
- this.schedule = () => {
57879
- return new Promise((resolve) => {
57880
- const cleanup = () => this.remove(resolver);
57881
- const resolver = () => resolve(cleanup);
57882
- this.add(resolver);
57883
- });
57884
- };
57885
- this.tick = () => {
57886
- if (this.queueActive.size >= this.limit)
57887
- return;
57888
- if (!this.queueWaiting.size)
57889
- return this.reset();
57890
- for (const fn of this.queueWaiting) {
57891
- if (this.queueActive.size >= this.limit)
57892
- break;
57893
- this.queueWaiting.delete(fn);
57894
- this.queueActive.add(fn);
57895
- fn();
57896
- }
57897
- };
57744
+ /**
57745
+ * Generates a TOTP token.
57746
+ * @param {Object} [config] Configuration options.
57747
+ * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
57748
+ * @returns {string} Token.
57749
+ */
57750
+ generate({
57751
+ timestamp = Date.now()
57752
+ } = {}) {
57753
+ return _TOTP.generate({
57754
+ secret: this.secret,
57755
+ algorithm: this.algorithm,
57756
+ digits: this.digits,
57757
+ period: this.period,
57758
+ timestamp
57759
+ });
57898
57760
  }
57899
- };
57900
- var retryify_queue_default = new RetryfyQueue();
57901
-
57902
- // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/retryify.js
57903
- var retryifyAsync = (fn, isRetriableError) => {
57904
- return function retrified(timestamp) {
57905
- return function attempt(...args) {
57906
- return retryify_queue_default.schedule().then((cleanup) => {
57907
- const onResolve = (result) => {
57908
- cleanup();
57909
- return result;
57910
- };
57911
- const onReject = (error) => {
57912
- cleanup();
57913
- if (Date.now() >= timestamp)
57914
- throw error;
57915
- if (isRetriableError(error)) {
57916
- const delay = Math.round(100 * Math.random());
57917
- const delayPromise = new Promise((resolve) => setTimeout(resolve, delay));
57918
- return delayPromise.then(() => attempt.apply(void 0, args));
57919
- }
57920
- throw error;
57921
- };
57922
- return fn.apply(void 0, args).then(onResolve, onReject);
57923
- });
57924
- };
57925
- };
57926
- };
57927
- var retryifySync = (fn, isRetriableError) => {
57928
- return function retrified(timestamp) {
57929
- return function attempt(...args) {
57930
- try {
57931
- return fn.apply(void 0, args);
57932
- } catch (error) {
57933
- if (Date.now() > timestamp)
57934
- throw error;
57935
- if (isRetriableError(error))
57936
- return attempt.apply(void 0, args);
57937
- throw error;
57938
- }
57939
- };
57940
- };
57941
- };
57942
-
57943
- // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/index.js
57944
- var FS = {
57945
- attempt: {
57946
- /* ASYNC */
57947
- chmod: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.chmod), handlers_default.onChangeError),
57948
- chown: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.chown), handlers_default.onChangeError),
57949
- close: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.close), NOOP),
57950
- fsync: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.fsync), NOOP),
57951
- mkdir: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.mkdir), NOOP),
57952
- realpath: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.realpath), NOOP),
57953
- stat: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.stat), NOOP),
57954
- unlink: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.unlink), NOOP),
57955
- /* SYNC */
57956
- chmodSync: attemptifySync(import_node_fs.default.chmodSync, handlers_default.onChangeError),
57957
- chownSync: attemptifySync(import_node_fs.default.chownSync, handlers_default.onChangeError),
57958
- closeSync: attemptifySync(import_node_fs.default.closeSync, NOOP),
57959
- existsSync: attemptifySync(import_node_fs.default.existsSync, NOOP),
57960
- fsyncSync: attemptifySync(import_node_fs.default.fsync, NOOP),
57961
- mkdirSync: attemptifySync(import_node_fs.default.mkdirSync, NOOP),
57962
- realpathSync: attemptifySync(import_node_fs.default.realpathSync, NOOP),
57963
- statSync: attemptifySync(import_node_fs.default.statSync, NOOP),
57964
- unlinkSync: attemptifySync(import_node_fs.default.unlinkSync, NOOP)
57965
- },
57966
- retry: {
57967
- /* ASYNC */
57968
- close: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.close), handlers_default.isRetriableError),
57969
- fsync: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.fsync), handlers_default.isRetriableError),
57970
- open: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.open), handlers_default.isRetriableError),
57971
- readFile: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.readFile), handlers_default.isRetriableError),
57972
- rename: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.rename), handlers_default.isRetriableError),
57973
- stat: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.stat), handlers_default.isRetriableError),
57974
- write: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.write), handlers_default.isRetriableError),
57975
- writeFile: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.writeFile), handlers_default.isRetriableError),
57976
- /* SYNC */
57977
- closeSync: retryifySync(import_node_fs.default.closeSync, handlers_default.isRetriableError),
57978
- fsyncSync: retryifySync(import_node_fs.default.fsyncSync, handlers_default.isRetriableError),
57979
- openSync: retryifySync(import_node_fs.default.openSync, handlers_default.isRetriableError),
57980
- readFileSync: retryifySync(import_node_fs.default.readFileSync, handlers_default.isRetriableError),
57981
- renameSync: retryifySync(import_node_fs.default.renameSync, handlers_default.isRetriableError),
57982
- statSync: retryifySync(import_node_fs.default.statSync, handlers_default.isRetriableError),
57983
- writeSync: retryifySync(import_node_fs.default.writeSync, handlers_default.isRetriableError),
57984
- writeFileSync: retryifySync(import_node_fs.default.writeFileSync, handlers_default.isRetriableError)
57761
+ /**
57762
+ * Validates a TOTP token.
57763
+ * @param {Object} config Configuration options.
57764
+ * @param {string} config.token Token value.
57765
+ * @param {Secret} config.secret Secret key.
57766
+ * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
57767
+ * @param {number} config.digits Token length.
57768
+ * @param {number} [config.period=30] Token time-step duration.
57769
+ * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
57770
+ * @param {number} [config.window=1] Window of counter values to test.
57771
+ * @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
57772
+ */
57773
+ static validate({
57774
+ token,
57775
+ secret,
57776
+ algorithm,
57777
+ digits: digits2,
57778
+ period = _TOTP.defaults.period,
57779
+ timestamp = Date.now(),
57780
+ window: window2
57781
+ }) {
57782
+ return HOTP.validate({
57783
+ token,
57784
+ secret,
57785
+ algorithm,
57786
+ digits: digits2,
57787
+ counter: Math.floor(timestamp / 1e3 / period),
57788
+ window: window2
57789
+ });
57985
57790
  }
57986
- };
57987
- var dist_default = FS;
57988
-
57989
- // node_modules/.pnpm/atomically@2.0.3/node_modules/atomically/dist/constants.js
57990
- var import_node_os3 = __toESM(require("node:os"), 1);
57991
- var import_node_process4 = __toESM(require("node:process"), 1);
57992
- var DEFAULT_ENCODING = "utf8";
57993
- var DEFAULT_FILE_MODE = 438;
57994
- var DEFAULT_FOLDER_MODE = 511;
57995
- var DEFAULT_WRITE_OPTIONS = {};
57996
- var DEFAULT_USER_UID = import_node_os3.default.userInfo().uid;
57997
- var DEFAULT_USER_GID = import_node_os3.default.userInfo().gid;
57998
- var DEFAULT_TIMEOUT_SYNC = 1e3;
57999
- var IS_POSIX = !!import_node_process4.default.getuid;
58000
- var IS_USER_ROOT2 = import_node_process4.default.getuid ? !import_node_process4.default.getuid() : false;
58001
- var LIMIT_BASENAME_LENGTH = 128;
58002
-
58003
- // node_modules/.pnpm/atomically@2.0.3/node_modules/atomically/dist/utils/lang.js
58004
- var isException = (value) => {
58005
- return value instanceof Error && "code" in value;
58006
- };
58007
- var isString = (value) => {
58008
- return typeof value === "string";
58009
- };
58010
- var isUndefined = (value) => {
58011
- return value === void 0;
58012
- };
58013
-
58014
- // node_modules/.pnpm/atomically@2.0.3/node_modules/atomically/dist/utils/temp.js
58015
- var import_node_path2 = __toESM(require("node:path"), 1);
58016
-
58017
- // node_modules/.pnpm/when-exit@2.1.2/node_modules/when-exit/dist/node/interceptor.js
58018
- var import_node_process6 = __toESM(require("node:process"), 1);
58019
-
58020
- // node_modules/.pnpm/when-exit@2.1.2/node_modules/when-exit/dist/node/constants.js
58021
- var import_node_process5 = __toESM(require("node:process"), 1);
58022
- var IS_LINUX = import_node_process5.default.platform === "linux";
58023
- var IS_WINDOWS = import_node_process5.default.platform === "win32";
58024
-
58025
- // node_modules/.pnpm/when-exit@2.1.2/node_modules/when-exit/dist/node/signals.js
58026
- var Signals = ["SIGABRT", "SIGALRM", "SIGHUP", "SIGINT", "SIGTERM"];
58027
- if (!IS_WINDOWS) {
58028
- Signals.push("SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT");
58029
- }
58030
- if (IS_LINUX) {
58031
- Signals.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT", "SIGUNUSED");
58032
- }
58033
- var signals_default = Signals;
57791
+ /**
57792
+ * Validates a TOTP token.
57793
+ * @param {Object} config Configuration options.
57794
+ * @param {string} config.token Token value.
57795
+ * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
57796
+ * @param {number} [config.window=1] Window of counter values to test.
57797
+ * @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
57798
+ */
57799
+ validate({
57800
+ token,
57801
+ timestamp,
57802
+ window: window2
57803
+ }) {
57804
+ return _TOTP.validate({
57805
+ token,
57806
+ secret: this.secret,
57807
+ algorithm: this.algorithm,
57808
+ digits: this.digits,
57809
+ period: this.period,
57810
+ timestamp,
57811
+ window: window2
57812
+ });
57813
+ }
57814
+ /**
57815
+ * Returns a Google Authenticator key URI.
57816
+ * @returns {string} URI.
57817
+ */
57818
+ toString() {
57819
+ const e = encodeURIComponent;
57820
+ return `otpauth://totp/${this.issuer.length > 0 ? this.issuerInLabel ? `${e(this.issuer)}:${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?`}secret=${e(this.secret.base32)}&algorithm=${e(this.algorithm)}&digits=${e(this.digits)}&period=${e(this.period)}`;
57821
+ }
57822
+ };
58034
57823
 
58035
- // node_modules/.pnpm/when-exit@2.1.2/node_modules/when-exit/dist/node/interceptor.js
58036
- var Interceptor = class {
58037
- /* CONSTRUCTOR */
58038
- constructor() {
58039
- this.callbacks = /* @__PURE__ */ new Set();
58040
- this.exited = false;
58041
- this.exit = (signal) => {
58042
- if (this.exited)
58043
- return;
58044
- this.exited = true;
58045
- for (const callback of this.callbacks) {
58046
- callback();
58047
- }
58048
- if (signal) {
58049
- if (IS_WINDOWS && (signal !== "SIGINT" && signal !== "SIGTERM" && signal !== "SIGKILL")) {
58050
- import_node_process6.default.kill(import_node_process6.default.pid, "SIGTERM");
58051
- } else {
58052
- import_node_process6.default.kill(import_node_process6.default.pid, signal);
58053
- }
58054
- }
58055
- };
58056
- this.hook = () => {
58057
- import_node_process6.default.once("exit", () => this.exit());
58058
- for (const signal of signals_default) {
58059
- import_node_process6.default.once(signal, () => this.exit(signal));
58060
- }
58061
- };
58062
- this.register = (callback) => {
58063
- this.callbacks.add(callback);
58064
- return () => {
58065
- this.callbacks.delete(callback);
58066
- };
57824
+ // packages/sdk/otp.js
57825
+ var OTP = class {
57826
+ constructor(secret) {
57827
+ const options = {
57828
+ issuer: "Autho",
57829
+ label: secret.name,
57830
+ algorithm: "SHA1",
57831
+ digits: 6,
57832
+ period: 30,
57833
+ secret: secret.value
58067
57834
  };
58068
- this.hook();
57835
+ this.totp = new TOTP(options);
57836
+ }
57837
+ generate() {
57838
+ return this.totp.generate();
57839
+ }
57840
+ validate(token, window2 = 1) {
57841
+ return this.totp.validate({ token, window: window2 });
58069
57842
  }
58070
57843
  };
58071
- var interceptor_default = new Interceptor();
58072
-
58073
- // node_modules/.pnpm/when-exit@2.1.2/node_modules/when-exit/dist/node/index.js
58074
- var whenExit = interceptor_default.register;
58075
- var node_default = whenExit;
58076
57844
 
58077
- // node_modules/.pnpm/atomically@2.0.3/node_modules/atomically/dist/utils/temp.js
58078
- var Temp = {
58079
- /* VARIABLES */
58080
- store: {},
58081
- /* API */
58082
- create: (filePath) => {
58083
- const randomness = `000000${Math.floor(Math.random() * 16777215).toString(16)}`.slice(-6);
58084
- const timestamp = Date.now().toString().slice(-10);
58085
- const prefix = "tmp-";
58086
- const suffix = `.${prefix}${timestamp}${randomness}`;
58087
- const tempPath = `${filePath}${suffix}`;
58088
- return tempPath;
58089
- },
58090
- get: (filePath, creator, purge = true) => {
58091
- const tempPath = Temp.truncate(creator(filePath));
58092
- if (tempPath in Temp.store)
58093
- return Temp.get(filePath, creator, purge);
58094
- Temp.store[tempPath] = purge;
58095
- const disposer = () => delete Temp.store[tempPath];
58096
- return [tempPath, disposer];
58097
- },
58098
- purge: (filePath) => {
58099
- if (!Temp.store[filePath])
58100
- return;
58101
- delete Temp.store[filePath];
58102
- dist_default.attempt.unlink(filePath);
58103
- },
58104
- purgeSync: (filePath) => {
58105
- if (!Temp.store[filePath])
58106
- return;
58107
- delete Temp.store[filePath];
58108
- dist_default.attempt.unlinkSync(filePath);
58109
- },
58110
- purgeSyncAll: () => {
58111
- for (const filePath in Temp.store) {
58112
- Temp.purgeSync(filePath);
57845
+ // packages/cli/utils.js
57846
+ var prompt2 = inquirer_default.prompt;
57847
+ var ask = async ({ name = "", message = "", type = "input" }) => {
57848
+ const answers = await inquirer_default.prompt([
57849
+ {
57850
+ name,
57851
+ message,
57852
+ type
58113
57853
  }
58114
- },
58115
- truncate: (filePath) => {
58116
- const basename2 = import_node_path2.default.basename(filePath);
58117
- if (basename2.length <= LIMIT_BASENAME_LENGTH)
58118
- return filePath;
58119
- const truncable = /^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(basename2);
58120
- if (!truncable)
58121
- return filePath;
58122
- const truncationLength = basename2.length - LIMIT_BASENAME_LENGTH;
58123
- return `${filePath.slice(0, -basename2.length)}${truncable[1]}${truncable[2].slice(0, -truncationLength)}${truncable[3]}`;
58124
- }
57854
+ ]);
57855
+ return answers[name];
57856
+ };
57857
+ var generateOTP = (secret) => {
57858
+ const otp = new OTP(secret);
57859
+ console.log("OTP code:", otp.generate());
58125
57860
  };
58126
- node_default(Temp.purgeSyncAll);
58127
- var temp_default = Temp;
58128
57861
 
58129
- // node_modules/.pnpm/atomically@2.0.3/node_modules/atomically/dist/index.js
58130
- function writeFileSync(filePath, data, options = DEFAULT_WRITE_OPTIONS) {
58131
- if (isString(options))
58132
- return writeFileSync(filePath, data, { encoding: options });
58133
- const timeout = Date.now() + ((options.timeout ?? DEFAULT_TIMEOUT_SYNC) || -1);
58134
- let tempDisposer = null;
58135
- let tempPath = null;
58136
- let fd = null;
58137
- try {
58138
- const filePathReal = dist_default.attempt.realpathSync(filePath);
58139
- const filePathExists = !!filePathReal;
58140
- filePath = filePathReal || filePath;
58141
- [tempPath, tempDisposer] = temp_default.get(filePath, options.tmpCreate || temp_default.create, !(options.tmpPurge === false));
58142
- const useStatChown = IS_POSIX && isUndefined(options.chown);
58143
- const useStatMode = isUndefined(options.mode);
58144
- if (filePathExists && (useStatChown || useStatMode)) {
58145
- const stats = dist_default.attempt.statSync(filePath);
58146
- if (stats) {
58147
- options = { ...options };
58148
- if (useStatChown) {
58149
- options.chown = { uid: stats.uid, gid: stats.gid };
58150
- }
58151
- if (useStatMode) {
58152
- options.mode = stats.mode;
58153
- }
58154
- }
58155
- }
58156
- if (!filePathExists) {
58157
- const parentPath = import_node_path3.default.dirname(filePath);
58158
- dist_default.attempt.mkdirSync(parentPath, {
58159
- mode: DEFAULT_FOLDER_MODE,
58160
- recursive: true
58161
- });
58162
- }
58163
- fd = dist_default.retry.openSync(timeout)(tempPath, "w", options.mode || DEFAULT_FILE_MODE);
58164
- if (options.tmpCreated) {
58165
- options.tmpCreated(tempPath);
58166
- }
58167
- if (isString(data)) {
58168
- dist_default.retry.writeSync(timeout)(fd, data, 0, options.encoding || DEFAULT_ENCODING);
58169
- } else if (!isUndefined(data)) {
58170
- dist_default.retry.writeSync(timeout)(fd, data, 0, data.length, 0);
58171
- }
58172
- if (options.fsync !== false) {
58173
- if (options.fsyncWait !== false) {
58174
- dist_default.retry.fsyncSync(timeout)(fd);
58175
- } else {
58176
- dist_default.attempt.fsync(fd);
58177
- }
58178
- }
58179
- dist_default.retry.closeSync(timeout)(fd);
58180
- fd = null;
58181
- if (options.chown && (options.chown.uid !== DEFAULT_USER_UID || options.chown.gid !== DEFAULT_USER_GID)) {
58182
- dist_default.attempt.chownSync(tempPath, options.chown.uid, options.chown.gid);
58183
- }
58184
- if (options.mode && options.mode !== DEFAULT_FILE_MODE) {
58185
- dist_default.attempt.chmodSync(tempPath, options.mode);
58186
- }
58187
- try {
58188
- dist_default.retry.renameSync(timeout)(tempPath, filePath);
58189
- } catch (error) {
58190
- if (!isException(error))
58191
- throw error;
58192
- if (error.code !== "ENAMETOOLONG")
58193
- throw error;
58194
- dist_default.retry.renameSync(timeout)(tempPath, temp_default.truncate(filePath));
58195
- }
58196
- tempDisposer();
58197
- tempPath = null;
58198
- } finally {
58199
- if (fd)
58200
- dist_default.attempt.closeSync(fd);
58201
- if (tempPath)
58202
- temp_default.purge(tempPath);
58203
- }
58204
- }
57862
+ // packages/models/Secret.js
57863
+ var import_joi = __toESM(require_lib6(), 1);
57864
+ var import_node_crypto = require("node:crypto");
57865
+ var createSecretSchema = import_joi.default.object({
57866
+ id: import_joi.default.string().default((0, import_node_crypto.randomUUID)()),
57867
+ protected: import_joi.default.boolean().default(false),
57868
+ name: import_joi.default.string().required(),
57869
+ type: import_joi.default.string().required().valid("otp", "password", "note"),
57870
+ value: import_joi.default.string().required(),
57871
+ typeOptions: import_joi.default.object().default({}),
57872
+ createdAt: import_joi.default.date().default(/* @__PURE__ */ new Date())
57873
+ });
58205
57874
 
58206
- // node_modules/.pnpm/conf@12.0.0/node_modules/conf/dist/source/index.js
58207
- var import_ajv = __toESM(require_ajv(), 1);
58208
- var import_ajv_formats = __toESM(require_dist(), 1);
57875
+ // packages/sdk/cipher.js
57876
+ var import_crypto = __toESM(require("crypto"), 1);
57877
+ var import_fs = __toESM(require("fs"), 1);
57878
+ var import_path = __toESM(require("path"), 1);
57879
+ var import_zlib = __toESM(require("zlib"), 1);
58209
57880
 
58210
- // node_modules/.pnpm/mimic-fn@4.0.0/node_modules/mimic-fn/index.js
58211
- var copyProperty = (to, from3, property, ignoreNonConfigurable) => {
58212
- if (property === "length" || property === "prototype") {
58213
- return;
57881
+ // packages/shared/config.js
57882
+ var import_dotenv = __toESM(require_main2(), 1);
57883
+ import_dotenv.default.config();
57884
+ var config_default = {
57885
+ masterPasswordHash: process.env.AUTHO_MASTER_PASSWORD_HASH,
57886
+ masterPassword: process.env.AUTHO_MASTER_PASSWORD,
57887
+ randomSize: process.env.AUTHO_RANDOM_SIZE || 16,
57888
+ encryptionALgo: process.env.AUTHO_ENCRYPTION_ALGO || "aes-256-gcm",
57889
+ hashAlgo: process.env.AUTHO_HASH_ALGO || "sha256",
57890
+ dataFolder: process.env.AUTHO_DATA_FOLDER,
57891
+ name: process.env.AUTHO_COLLECTION_NAME || "default"
57892
+ };
57893
+
57894
+ // packages/sdk/cipher.js
57895
+ var Cipher = class _Cipher {
57896
+ static hash(text, algorithm = config_default.hashAlgo, encoding = "hex") {
57897
+ const hash = import_crypto.default.createHash(algorithm);
57898
+ hash.update(text);
57899
+ return hash.digest(encoding);
58214
57900
  }
58215
- if (property === "arguments" || property === "caller") {
58216
- return;
57901
+ static random(size = config_default.randomSize) {
57902
+ const rnd = import_crypto.default.randomBytes(size);
57903
+ return rnd;
58217
57904
  }
58218
- const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
58219
- const fromDescriptor = Object.getOwnPropertyDescriptor(from3, property);
58220
- if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
58221
- return;
57905
+ static randomString(encoding = "hex") {
57906
+ const rnd = _Cipher.random().toString(encoding);
57907
+ return rnd;
58222
57908
  }
58223
- Object.defineProperty(to, property, fromDescriptor);
58224
- };
58225
- var canCopyProperty = function(toDescriptor, fromDescriptor) {
58226
- return toDescriptor === void 0 || toDescriptor.configurable || toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value);
58227
- };
58228
- var changePrototype = (to, from3) => {
58229
- const fromPrototype = Object.getPrototypeOf(from3);
58230
- if (fromPrototype === Object.getPrototypeOf(to)) {
58231
- return;
57909
+ static sign(text) {
57910
+ const hash = _Cipher.hash(text);
57911
+ const signature = `${hash.substring(0, 10)}:${hash.substring(hash.length - 10)}`;
57912
+ return signature;
58232
57913
  }
58233
- Object.setPrototypeOf(to, fromPrototype);
58234
- };
58235
- var wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/
58236
- ${fromBody}`;
58237
- var toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, "toString");
58238
- var toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, "name");
58239
- var changeToString = (to, from3, name) => {
58240
- const withName = name === "" ? "" : `with ${name.trim()}() `;
58241
- const newToString = wrappedToString.bind(null, withName, from3.toString());
58242
- Object.defineProperty(newToString, "name", toStringName);
58243
- Object.defineProperty(to, "toString", { ...toStringDescriptor, value: newToString });
58244
- };
58245
- function mimicFunction(to, from3, { ignoreNonConfigurable = false } = {}) {
58246
- const { name } = to;
58247
- for (const property of Reflect.ownKeys(from3)) {
58248
- copyProperty(to, from3, property, ignoreNonConfigurable);
57914
+ static verify(text, signature) {
57915
+ const expectedSignature = _Cipher.sign(text);
57916
+ return expectedSignature === signature;
58249
57917
  }
58250
- changePrototype(to, from3);
58251
- changeToString(to, from3, name);
58252
- return to;
58253
- }
58254
-
58255
- // node_modules/.pnpm/debounce-fn@5.1.2/node_modules/debounce-fn/index.js
58256
- var debounceFn = (inputFunction, options = {}) => {
58257
- if (typeof inputFunction !== "function") {
58258
- throw new TypeError(`Expected the first argument to be a function, got \`${typeof inputFunction}\``);
57918
+ static encrypt({
57919
+ value,
57920
+ encryptionKey,
57921
+ algorithm = config_default.encryptionALgo,
57922
+ encoding = "hex"
57923
+ }) {
57924
+ const publicKey = _Cipher.randomString();
57925
+ let cipher = import_crypto.default.createCipheriv(
57926
+ algorithm,
57927
+ Buffer.from(encryptionKey, encoding),
57928
+ Buffer.from(publicKey, encoding),
57929
+ { authTagLength: 16 }
57930
+ );
57931
+ let encrypted = cipher.update(value);
57932
+ encrypted = Buffer.concat([encrypted, cipher.final()]);
57933
+ encrypted = encrypted.toString(encoding);
57934
+ const authTag = cipher.getAuthTag().toString(encoding);
57935
+ return {
57936
+ publicKey,
57937
+ encrypted,
57938
+ algorithm,
57939
+ signature: _Cipher.sign(value),
57940
+ encoding,
57941
+ authTag,
57942
+ provider: "crypto",
57943
+ platform: "autho"
57944
+ };
58259
57945
  }
58260
- const {
58261
- wait = 0,
58262
- maxWait = Number.POSITIVE_INFINITY,
58263
- before = false,
58264
- after = true
58265
- } = options;
58266
- if (!before && !after) {
58267
- throw new Error("Both `before` and `after` are false, function wouldn't be called.");
57946
+ static decrypt({
57947
+ value,
57948
+ publicKey,
57949
+ encryptionKey,
57950
+ signature = false,
57951
+ algorithm = config_default.encryptionALgo,
57952
+ authTag,
57953
+ encoding = "hex"
57954
+ }) {
57955
+ value = Buffer.from(value, encoding);
57956
+ let decipher = import_crypto.default.createDecipheriv(
57957
+ algorithm,
57958
+ Buffer.from(encryptionKey, encoding),
57959
+ Buffer.from(publicKey, encoding),
57960
+ { authTagLength: 16 }
57961
+ );
57962
+ if (authTag) {
57963
+ decipher.setAuthTag(Buffer.from(authTag, encoding));
57964
+ }
57965
+ let decrypted = decipher.update(value);
57966
+ decrypted = Buffer.concat([decrypted, decipher.final()]);
57967
+ decrypted = decrypted.toString();
57968
+ if (signature && !_Cipher.verify(decrypted, signature)) {
57969
+ throw new Error("Invalid signature");
57970
+ }
57971
+ return decrypted;
58268
57972
  }
58269
- let timeout;
58270
- let maxTimeout;
58271
- let result;
58272
- const debouncedFunction = function(...arguments_) {
58273
- const context = this;
58274
- const later = () => {
58275
- timeout = void 0;
58276
- if (maxTimeout) {
58277
- clearTimeout(maxTimeout);
58278
- maxTimeout = void 0;
58279
- }
58280
- if (after) {
58281
- result = inputFunction.apply(context, arguments_);
58282
- }
57973
+ static canDecrypt(options) {
57974
+ return options.platform === "autho";
57975
+ }
57976
+ static encryptFile(inputFilePath, outputFilePath, encryptionKey) {
57977
+ const inputBuffer = import_fs.default.readFileSync(inputFilePath);
57978
+ const params = {
57979
+ value: inputBuffer,
57980
+ encryptionKey
58283
57981
  };
58284
- const maxLater = () => {
58285
- maxTimeout = void 0;
58286
- if (timeout) {
58287
- clearTimeout(timeout);
58288
- timeout = void 0;
57982
+ const encryptedData = _Cipher.encrypt(params);
57983
+ import_fs.default.writeFileSync(
57984
+ outputFilePath,
57985
+ Buffer.from(JSON.stringify(encryptedData)).toString("base64")
57986
+ );
57987
+ }
57988
+ static decryptFile(inputFilePath, outputFilePath, encryptionKey) {
57989
+ const inputFileContent = import_fs.default.readFileSync(inputFilePath);
57990
+ const decoded = Buffer.from(
57991
+ inputFileContent.toString("utf-8"),
57992
+ "base64"
57993
+ ).toString("utf-8");
57994
+ const encryptedData = JSON.parse(decoded);
57995
+ if (!_Cipher.canDecrypt(encryptedData)) {
57996
+ throw new Error("Invalid file");
57997
+ }
57998
+ const params = {
57999
+ ...encryptedData,
58000
+ value: encryptedData.encrypted,
58001
+ encryptionKey
58002
+ };
58003
+ const decryptedData = _Cipher.decrypt(params);
58004
+ import_fs.default.writeFileSync(outputFilePath, decryptedData);
58005
+ }
58006
+ static encryptFolder({ inputFolderPath, outputFilePath, encryptionKey, algorithm = config_default.encryptionALgo, encoding = "hex" }) {
58007
+ const outputStream = import_fs.default.createWriteStream(outputFilePath);
58008
+ const gzip = import_zlib.default.createGzip();
58009
+ gzip.pipe(outputStream);
58010
+ const baseFolder = import_path.default.basename(inputFolderPath);
58011
+ function traverseFolder(folderPath) {
58012
+ const items = import_fs.default.readdirSync(folderPath);
58013
+ for (const item of items) {
58014
+ const itemPath = import_path.default.join(baseFolder, import_path.default.relative(inputFolderPath, import_path.default.join(folderPath, item)));
58015
+ if (import_fs.default.statSync(itemPath).isDirectory()) {
58016
+ traverseFolder(itemPath);
58017
+ } else {
58018
+ const fileContent = import_fs.default.readFileSync(itemPath);
58019
+ const params = {
58020
+ value: fileContent,
58021
+ encryptionKey,
58022
+ algorithm,
58023
+ encoding
58024
+ };
58025
+ const encryptedData = _Cipher.encrypt(params);
58026
+ const encrypted = encryptedData.encrypted;
58027
+ delete encryptedData.encrypted;
58028
+ const encryptionMeta = Buffer.from(JSON.stringify(encryptedData)).toString("base64");
58029
+ gzip.write(`${itemPath}
58030
+ ---
58031
+ ${encrypted}
58032
+ ---
58033
+ ${encryptionMeta}
58034
+ :::
58035
+ `);
58036
+ }
58289
58037
  }
58290
- if (after) {
58291
- result = inputFunction.apply(context, arguments_);
58038
+ }
58039
+ traverseFolder(inputFolderPath);
58040
+ gzip.end();
58041
+ return new Promise((resolve, reject) => {
58042
+ outputStream.on("finish", resolve);
58043
+ outputStream.on("error", reject);
58044
+ });
58045
+ }
58046
+ static decryptFolder({ inputFilePath, outputFolderPath, encryptionKey }) {
58047
+ const inputStream = import_fs.default.createReadStream(inputFilePath);
58048
+ const gunzip = import_zlib.default.createGunzip();
58049
+ inputStream.pipe(gunzip);
58050
+ let buff = "";
58051
+ const compileFile = (data) => {
58052
+ buff += data;
58053
+ if (buff.includes(":::")) {
58054
+ const [file, next] = buff.split("\n:::\n");
58055
+ let [filePath, encrypted, encryptionMeta] = file.split("\n---\n");
58056
+ filePath = import_path.default.join(outputFolderPath, filePath);
58057
+ try {
58058
+ import_fs.default.mkdirSync(import_path.default.dirname(filePath), { recursive: true });
58059
+ } catch (error) {
58060
+ }
58061
+ const decoded = Buffer.from(
58062
+ encryptionMeta,
58063
+ "base64"
58064
+ ).toString("utf-8");
58065
+ const metaData = JSON.parse(decoded);
58066
+ const params = {
58067
+ ...metaData,
58068
+ value: encrypted,
58069
+ encryptionKey
58070
+ };
58071
+ const decryptedData = _Cipher.decrypt(params);
58072
+ import_fs.default.writeFileSync(filePath, decryptedData);
58073
+ buff = next;
58292
58074
  }
58293
58075
  };
58294
- const shouldCallNow = before && !timeout;
58295
- clearTimeout(timeout);
58296
- timeout = setTimeout(later, wait);
58297
- if (maxWait > 0 && maxWait !== Number.POSITIVE_INFINITY && !maxTimeout) {
58298
- maxTimeout = setTimeout(maxLater, maxWait);
58299
- }
58300
- if (shouldCallNow) {
58301
- result = inputFunction.apply(context, arguments_);
58302
- }
58303
- return result;
58304
- };
58305
- mimicFunction(debouncedFunction, inputFunction);
58306
- debouncedFunction.cancel = () => {
58307
- if (timeout) {
58308
- clearTimeout(timeout);
58309
- timeout = void 0;
58310
- }
58311
- if (maxTimeout) {
58312
- clearTimeout(maxTimeout);
58313
- maxTimeout = void 0;
58314
- }
58315
- };
58316
- return debouncedFunction;
58076
+ gunzip.on("data", (data) => {
58077
+ compileFile(data.toString("utf8"));
58078
+ });
58079
+ return new Promise((resolve, reject) => {
58080
+ gunzip.on("end", resolve);
58081
+ gunzip.on("error", reject);
58082
+ });
58083
+ }
58317
58084
  };
58318
- var debounce_fn_default = debounceFn;
58319
-
58320
- // node_modules/.pnpm/conf@12.0.0/node_modules/conf/dist/source/index.js
58321
- var import_semver = __toESM(require_semver2(), 1);
58322
58085
 
58323
- // node_modules/.pnpm/uint8array-extras@0.3.0/node_modules/uint8array-extras/index.js
58324
- var objectToString = Object.prototype.toString;
58325
- function isUint8Array(value) {
58326
- return value && objectToString.call(value) === "[object Uint8Array]";
58327
- }
58328
- function assertUint8Array(value) {
58329
- if (!isUint8Array(value)) {
58330
- throw new TypeError(`Expected \`Uint8Array\`, got \`${typeof value}\``);
58086
+ // packages/sdk/secrets.js
58087
+ var Secrets = class {
58088
+ constructor(db) {
58089
+ this.db = db;
58331
58090
  }
58332
- }
58333
- function concatUint8Arrays(arrays, totalLength) {
58334
- if (arrays.length === 0) {
58335
- return new Uint8Array(0);
58091
+ get secrets() {
58092
+ return this.db.get("secrets", []);
58336
58093
  }
58337
- totalLength ??= arrays.reduce((accumulator, currentValue) => accumulator + currentValue.length, 0);
58338
- const returnValue = new Uint8Array(totalLength);
58339
- let offset = 0;
58340
- for (const array of arrays) {
58341
- assertUint8Array(array);
58342
- returnValue.set(array, offset);
58343
- offset += array.length;
58094
+ set secrets(value) {
58095
+ this.db.set("secrets", value);
58344
58096
  }
58345
- return returnValue;
58346
- }
58347
- function uint8ArrayToString(array) {
58348
- assertUint8Array(array);
58349
- return new globalThis.TextDecoder().decode(array);
58350
- }
58351
- function assertString(value) {
58352
- if (typeof value !== "string") {
58353
- throw new TypeError(`Expected \`string\`, got \`${typeof value}\``);
58097
+ async get(id) {
58098
+ return this.secrets.find((secret) => secret.id == id);
58354
58099
  }
58355
- }
58356
- function stringToUint8Array(string) {
58357
- assertString(string);
58358
- return new globalThis.TextEncoder().encode(string);
58359
- }
58360
- var byteToHexLookupTable = Array.from({ length: 256 }, (_3, index) => index.toString(16).padStart(2, "0"));
58100
+ async add(secret, encryptionKey) {
58101
+ const { value, error } = createSecretSchema.validate(secret);
58102
+ if (error) {
58103
+ throw new Error(error);
58104
+ }
58105
+ const { encrypted, ...encryption } = Cipher.encrypt({
58106
+ ...value,
58107
+ encryptionKey
58108
+ });
58109
+ const newSecret = { ...value, ...encryption, value: encrypted };
58110
+ this.secrets = [
58111
+ ...this.secrets,
58112
+ newSecret
58113
+ ];
58114
+ return newSecret;
58115
+ }
58116
+ async remove(id) {
58117
+ this.secrets = this.secrets.filter((secret) => secret.id != id);
58118
+ }
58119
+ async clear() {
58120
+ this.secrets = [];
58121
+ }
58122
+ };
58361
58123
 
58362
58124
  // node_modules/.pnpm/conf@12.0.0/node_modules/conf/dist/source/index.js
58363
- var Ajv = import_ajv.default.default;
58364
- var ajvFormats = import_ajv_formats.default.default;
58365
- var encryptionAlgorithm = "aes-256-cbc";
58366
- var createPlainObject = () => /* @__PURE__ */ Object.create(null);
58367
- var isExist = (data) => data !== void 0 && data !== null;
58368
- var checkValueType = (key, value) => {
58369
- const nonJsonTypes = /* @__PURE__ */ new Set([
58370
- "undefined",
58371
- "symbol",
58372
- "function"
58373
- ]);
58125
+ var import_node_util2 = require("node:util");
58126
+ var import_node_process7 = __toESM(require("node:process"), 1);
58127
+ var import_node_fs2 = __toESM(require("node:fs"), 1);
58128
+ var import_node_path4 = __toESM(require("node:path"), 1);
58129
+ var import_node_crypto2 = __toESM(require("node:crypto"), 1);
58130
+ var import_node_assert2 = __toESM(require("node:assert"), 1);
58131
+
58132
+ // node_modules/.pnpm/dot-prop@8.0.2/node_modules/dot-prop/index.js
58133
+ var isObject = (value) => {
58374
58134
  const type = typeof value;
58375
- if (nonJsonTypes.has(type)) {
58376
- throw new TypeError(`Setting a value of type \`${type}\` for key \`${key}\` is not allowed as it's not supported by JSON`);
58377
- }
58135
+ return value !== null && (type === "object" || type === "function");
58378
58136
  };
58379
- var INTERNAL_KEY = "__internal__";
58380
- var MIGRATION_KEY = `${INTERNAL_KEY}.migrations.version`;
58381
- var Conf = class {
58382
- path;
58383
- events;
58384
- #validator;
58385
- #encryptionKey;
58386
- #options;
58387
- #defaultValues = {};
58388
- constructor(partialOptions = {}) {
58389
- const options = {
58390
- configName: "config",
58391
- fileExtension: "json",
58392
- projectSuffix: "nodejs",
58393
- clearInvalidConfig: false,
58394
- accessPropertiesByDotNotation: true,
58395
- configFileMode: 438,
58396
- ...partialOptions
58397
- };
58398
- if (!options.cwd) {
58399
- if (!options.projectName) {
58400
- throw new Error("Please specify the `projectName` option.");
58137
+ var disallowedKeys = /* @__PURE__ */ new Set([
58138
+ "__proto__",
58139
+ "prototype",
58140
+ "constructor"
58141
+ ]);
58142
+ var digits = new Set("0123456789");
58143
+ function getPathSegments(path5) {
58144
+ const parts = [];
58145
+ let currentSegment = "";
58146
+ let currentPart = "start";
58147
+ let isIgnoring = false;
58148
+ for (const character of path5) {
58149
+ switch (character) {
58150
+ case "\\": {
58151
+ if (currentPart === "index") {
58152
+ throw new Error("Invalid character in an index");
58153
+ }
58154
+ if (currentPart === "indexEnd") {
58155
+ throw new Error("Invalid character after an index");
58156
+ }
58157
+ if (isIgnoring) {
58158
+ currentSegment += character;
58159
+ }
58160
+ currentPart = "property";
58161
+ isIgnoring = !isIgnoring;
58162
+ break;
58401
58163
  }
58402
- options.cwd = envPaths(options.projectName, { suffix: options.projectSuffix }).config;
58403
- }
58404
- this.#options = options;
58405
- if (options.schema) {
58406
- if (typeof options.schema !== "object") {
58407
- throw new TypeError("The `schema` option must be an object.");
58164
+ case ".": {
58165
+ if (currentPart === "index") {
58166
+ throw new Error("Invalid character in an index");
58167
+ }
58168
+ if (currentPart === "indexEnd") {
58169
+ currentPart = "property";
58170
+ break;
58171
+ }
58172
+ if (isIgnoring) {
58173
+ isIgnoring = false;
58174
+ currentSegment += character;
58175
+ break;
58176
+ }
58177
+ if (disallowedKeys.has(currentSegment)) {
58178
+ return [];
58179
+ }
58180
+ parts.push(currentSegment);
58181
+ currentSegment = "";
58182
+ currentPart = "property";
58183
+ break;
58408
58184
  }
58409
- const ajv = new Ajv({
58410
- allErrors: true,
58411
- useDefaults: true
58412
- });
58413
- ajvFormats(ajv);
58414
- const schema = {
58415
- type: "object",
58416
- properties: options.schema
58417
- };
58418
- this.#validator = ajv.compile(schema);
58419
- for (const [key, value] of Object.entries(options.schema)) {
58420
- if (value?.default) {
58421
- this.#defaultValues[key] = value.default;
58185
+ case "[": {
58186
+ if (currentPart === "index") {
58187
+ throw new Error("Invalid character in an index");
58188
+ }
58189
+ if (currentPart === "indexEnd") {
58190
+ currentPart = "index";
58191
+ break;
58422
58192
  }
58193
+ if (isIgnoring) {
58194
+ isIgnoring = false;
58195
+ currentSegment += character;
58196
+ break;
58197
+ }
58198
+ if (currentPart === "property") {
58199
+ if (disallowedKeys.has(currentSegment)) {
58200
+ return [];
58201
+ }
58202
+ parts.push(currentSegment);
58203
+ currentSegment = "";
58204
+ }
58205
+ currentPart = "index";
58206
+ break;
58423
58207
  }
58424
- }
58425
- if (options.defaults) {
58426
- this.#defaultValues = {
58427
- ...this.#defaultValues,
58428
- ...options.defaults
58429
- };
58430
- }
58431
- if (options.serialize) {
58432
- this._serialize = options.serialize;
58433
- }
58434
- if (options.deserialize) {
58435
- this._deserialize = options.deserialize;
58436
- }
58437
- this.events = new EventTarget();
58438
- this.#encryptionKey = options.encryptionKey;
58439
- const fileExtension = options.fileExtension ? `.${options.fileExtension}` : "";
58440
- this.path = import_node_path4.default.resolve(options.cwd, `${options.configName ?? "config"}${fileExtension}`);
58441
- const fileStore = this.store;
58442
- const store = Object.assign(createPlainObject(), options.defaults, fileStore);
58443
- this._validate(store);
58444
- try {
58445
- import_node_assert2.default.deepEqual(fileStore, store);
58446
- } catch {
58447
- this.store = store;
58448
- }
58449
- if (options.watch) {
58450
- this._watch();
58451
- }
58452
- if (options.migrations) {
58453
- if (!options.projectVersion) {
58454
- throw new Error("Please specify the `projectVersion` option.");
58208
+ case "]": {
58209
+ if (currentPart === "index") {
58210
+ parts.push(Number.parseInt(currentSegment, 10));
58211
+ currentSegment = "";
58212
+ currentPart = "indexEnd";
58213
+ break;
58214
+ }
58215
+ if (currentPart === "indexEnd") {
58216
+ throw new Error("Invalid character after an index");
58217
+ }
58218
+ }
58219
+ default: {
58220
+ if (currentPart === "index" && !digits.has(character)) {
58221
+ throw new Error("Invalid character in an index");
58222
+ }
58223
+ if (currentPart === "indexEnd") {
58224
+ throw new Error("Invalid character after an index");
58225
+ }
58226
+ if (currentPart === "start") {
58227
+ currentPart = "property";
58228
+ }
58229
+ if (isIgnoring) {
58230
+ isIgnoring = false;
58231
+ currentSegment += "\\";
58232
+ }
58233
+ currentSegment += character;
58455
58234
  }
58456
- this._migrate(options.migrations, options.projectVersion, options.beforeEachMigration);
58457
58235
  }
58458
58236
  }
58459
- get(key, defaultValue) {
58460
- if (this.#options.accessPropertiesByDotNotation) {
58461
- return this._get(key, defaultValue);
58462
- }
58463
- const { store } = this;
58464
- return key in store ? store[key] : defaultValue;
58237
+ if (isIgnoring) {
58238
+ currentSegment += "\\";
58465
58239
  }
58466
- set(key, value) {
58467
- if (typeof key !== "string" && typeof key !== "object") {
58468
- throw new TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof key}`);
58469
- }
58470
- if (typeof key !== "object" && value === void 0) {
58471
- throw new TypeError("Use `delete()` to clear values");
58240
+ switch (currentPart) {
58241
+ case "property": {
58242
+ if (disallowedKeys.has(currentSegment)) {
58243
+ return [];
58244
+ }
58245
+ parts.push(currentSegment);
58246
+ break;
58472
58247
  }
58473
- if (this._containsReservedKey(key)) {
58474
- throw new TypeError(`Please don't use the ${INTERNAL_KEY} key, as it's used to manage this module internal operations.`);
58248
+ case "index": {
58249
+ throw new Error("Index was not closed");
58475
58250
  }
58476
- const { store } = this;
58477
- const set2 = (key2, value2) => {
58478
- checkValueType(key2, value2);
58479
- if (this.#options.accessPropertiesByDotNotation) {
58480
- setProperty(store, key2, value2);
58481
- } else {
58482
- store[key2] = value2;
58483
- }
58484
- };
58485
- if (typeof key === "object") {
58486
- const object = key;
58487
- for (const [key2, value2] of Object.entries(object)) {
58488
- set2(key2, value2);
58489
- }
58490
- } else {
58491
- set2(key, value);
58251
+ case "start": {
58252
+ parts.push("");
58253
+ break;
58492
58254
  }
58493
- this.store = store;
58494
58255
  }
58495
- /**
58496
- Check if an item exists.
58497
-
58498
- @param key - The key of the item to check.
58499
- */
58500
- has(key) {
58501
- if (this.#options.accessPropertiesByDotNotation) {
58502
- return hasProperty(this.store, key);
58503
- }
58504
- return key in this.store;
58256
+ return parts;
58257
+ }
58258
+ function isStringIndex(object, key) {
58259
+ if (typeof key !== "number" && Array.isArray(object)) {
58260
+ const index = Number.parseInt(key, 10);
58261
+ return Number.isInteger(index) && object[index] === object[key];
58505
58262
  }
58506
- /**
58507
- Reset items to their default values, as defined by the `defaults` or `schema` option.
58508
-
58509
- @see `clear()` to reset all items.
58510
-
58511
- @param keys - The keys of the items to reset.
58512
- */
58513
- reset(...keys) {
58514
- for (const key of keys) {
58515
- if (isExist(this.#defaultValues[key])) {
58516
- this.set(key, this.#defaultValues[key]);
58517
- }
58518
- }
58263
+ return false;
58264
+ }
58265
+ function assertNotStringIndex(object, key) {
58266
+ if (isStringIndex(object, key)) {
58267
+ throw new Error("Cannot use string index");
58519
58268
  }
58520
- delete(key) {
58521
- const { store } = this;
58522
- if (this.#options.accessPropertiesByDotNotation) {
58523
- deleteProperty(store, key);
58269
+ }
58270
+ function getProperty(object, path5, value) {
58271
+ if (!isObject(object) || typeof path5 !== "string") {
58272
+ return value === void 0 ? object : value;
58273
+ }
58274
+ const pathArray = getPathSegments(path5);
58275
+ if (pathArray.length === 0) {
58276
+ return value;
58277
+ }
58278
+ for (let index = 0; index < pathArray.length; index++) {
58279
+ const key = pathArray[index];
58280
+ if (isStringIndex(object, key)) {
58281
+ object = index === pathArray.length - 1 ? void 0 : null;
58524
58282
  } else {
58525
- delete store[key];
58283
+ object = object[key];
58284
+ }
58285
+ if (object === void 0 || object === null) {
58286
+ if (index !== pathArray.length - 1) {
58287
+ return value;
58288
+ }
58289
+ break;
58526
58290
  }
58527
- this.store = store;
58528
58291
  }
58529
- /**
58530
- Delete all items.
58531
-
58532
- This resets known items to their default values, if defined by the `defaults` or `schema` option.
58533
- */
58534
- clear() {
58535
- this.store = createPlainObject();
58536
- for (const key of Object.keys(this.#defaultValues)) {
58537
- this.reset(key);
58292
+ return object === void 0 ? value : object;
58293
+ }
58294
+ function setProperty(object, path5, value) {
58295
+ if (!isObject(object) || typeof path5 !== "string") {
58296
+ return object;
58297
+ }
58298
+ const root = object;
58299
+ const pathArray = getPathSegments(path5);
58300
+ for (let index = 0; index < pathArray.length; index++) {
58301
+ const key = pathArray[index];
58302
+ assertNotStringIndex(object, key);
58303
+ if (index === pathArray.length - 1) {
58304
+ object[key] = value;
58305
+ } else if (!isObject(object[key])) {
58306
+ object[key] = typeof pathArray[index + 1] === "number" ? [] : {};
58538
58307
  }
58308
+ object = object[key];
58539
58309
  }
58540
- /**
58541
- Watches the given `key`, calling `callback` on any changes.
58542
-
58543
- @param key - The key wo watch.
58544
- @param callback - A callback function that is called on any changes. When a `key` is first set `oldValue` will be `undefined`, and when a key is deleted `newValue` will be `undefined`.
58545
- @returns A function, that when called, will unsubscribe.
58546
- */
58547
- onDidChange(key, callback) {
58548
- if (typeof key !== "string") {
58549
- throw new TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof key}`);
58310
+ return root;
58311
+ }
58312
+ function deleteProperty(object, path5) {
58313
+ if (!isObject(object) || typeof path5 !== "string") {
58314
+ return false;
58315
+ }
58316
+ const pathArray = getPathSegments(path5);
58317
+ for (let index = 0; index < pathArray.length; index++) {
58318
+ const key = pathArray[index];
58319
+ assertNotStringIndex(object, key);
58320
+ if (index === pathArray.length - 1) {
58321
+ delete object[key];
58322
+ return true;
58550
58323
  }
58551
- if (typeof callback !== "function") {
58552
- throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof callback}`);
58324
+ object = object[key];
58325
+ if (!isObject(object)) {
58326
+ return false;
58553
58327
  }
58554
- return this._handleChange(() => this.get(key), callback);
58555
58328
  }
58556
- /**
58557
- Watches the whole config object, calling `callback` on any changes.
58558
-
58559
- @param callback - A callback function that is called on any changes. When a `key` is first set `oldValue` will be `undefined`, and when a key is deleted `newValue` will be `undefined`.
58560
- @returns A function, that when called, will unsubscribe.
58561
- */
58562
- onDidAnyChange(callback) {
58563
- if (typeof callback !== "function") {
58564
- throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof callback}`);
58565
- }
58566
- return this._handleChange(() => this.store, callback);
58329
+ }
58330
+ function hasProperty(object, path5) {
58331
+ if (!isObject(object) || typeof path5 !== "string") {
58332
+ return false;
58567
58333
  }
58568
- get size() {
58569
- return Object.keys(this.store).length;
58334
+ const pathArray = getPathSegments(path5);
58335
+ if (pathArray.length === 0) {
58336
+ return false;
58570
58337
  }
58571
- get store() {
58572
- try {
58573
- const data = import_node_fs2.default.readFileSync(this.path, this.#encryptionKey ? null : "utf8");
58574
- const dataString = this._encryptData(data);
58575
- const deserializedData = this._deserialize(dataString);
58576
- this._validate(deserializedData);
58577
- return Object.assign(createPlainObject(), deserializedData);
58578
- } catch (error) {
58579
- if (error?.code === "ENOENT") {
58580
- this._ensureDirectory();
58581
- return createPlainObject();
58582
- }
58583
- if (this.#options.clearInvalidConfig && error.name === "SyntaxError") {
58584
- return createPlainObject();
58585
- }
58586
- throw error;
58338
+ for (const key of pathArray) {
58339
+ if (!isObject(object) || !(key in object) || isStringIndex(object, key)) {
58340
+ return false;
58587
58341
  }
58342
+ object = object[key];
58343
+ }
58344
+ return true;
58345
+ }
58346
+
58347
+ // node_modules/.pnpm/env-paths@3.0.0/node_modules/env-paths/index.js
58348
+ var import_node_path = __toESM(require("node:path"), 1);
58349
+ var import_node_os2 = __toESM(require("node:os"), 1);
58350
+ var import_node_process2 = __toESM(require("node:process"), 1);
58351
+ var homedir = import_node_os2.default.homedir();
58352
+ var tmpdir = import_node_os2.default.tmpdir();
58353
+ var { env: env2 } = import_node_process2.default;
58354
+ var macos = (name) => {
58355
+ const library = import_node_path.default.join(homedir, "Library");
58356
+ return {
58357
+ data: import_node_path.default.join(library, "Application Support", name),
58358
+ config: import_node_path.default.join(library, "Preferences", name),
58359
+ cache: import_node_path.default.join(library, "Caches", name),
58360
+ log: import_node_path.default.join(library, "Logs", name),
58361
+ temp: import_node_path.default.join(tmpdir, name)
58362
+ };
58363
+ };
58364
+ var windows = (name) => {
58365
+ const appData = env2.APPDATA || import_node_path.default.join(homedir, "AppData", "Roaming");
58366
+ const localAppData = env2.LOCALAPPDATA || import_node_path.default.join(homedir, "AppData", "Local");
58367
+ return {
58368
+ // Data/config/cache/log are invented by me as Windows isn't opinionated about this
58369
+ data: import_node_path.default.join(localAppData, name, "Data"),
58370
+ config: import_node_path.default.join(appData, name, "Config"),
58371
+ cache: import_node_path.default.join(localAppData, name, "Cache"),
58372
+ log: import_node_path.default.join(localAppData, name, "Log"),
58373
+ temp: import_node_path.default.join(tmpdir, name)
58374
+ };
58375
+ };
58376
+ var linux = (name) => {
58377
+ const username = import_node_path.default.basename(homedir);
58378
+ return {
58379
+ data: import_node_path.default.join(env2.XDG_DATA_HOME || import_node_path.default.join(homedir, ".local", "share"), name),
58380
+ config: import_node_path.default.join(env2.XDG_CONFIG_HOME || import_node_path.default.join(homedir, ".config"), name),
58381
+ cache: import_node_path.default.join(env2.XDG_CACHE_HOME || import_node_path.default.join(homedir, ".cache"), name),
58382
+ // https://wiki.debian.org/XDGBaseDirectorySpecification#state
58383
+ log: import_node_path.default.join(env2.XDG_STATE_HOME || import_node_path.default.join(homedir, ".local", "state"), name),
58384
+ temp: import_node_path.default.join(tmpdir, username, name)
58385
+ };
58386
+ };
58387
+ function envPaths(name, { suffix = "nodejs" } = {}) {
58388
+ if (typeof name !== "string") {
58389
+ throw new TypeError(`Expected a string, got ${typeof name}`);
58390
+ }
58391
+ if (suffix) {
58392
+ name += `-${suffix}`;
58588
58393
  }
58589
- set store(value) {
58590
- this._ensureDirectory();
58591
- this._validate(value);
58592
- this._write(value);
58593
- this.events.dispatchEvent(new Event("change"));
58394
+ if (import_node_process2.default.platform === "darwin") {
58395
+ return macos(name);
58594
58396
  }
58595
- *[Symbol.iterator]() {
58596
- for (const [key, value] of Object.entries(this.store)) {
58597
- yield [key, value];
58598
- }
58397
+ if (import_node_process2.default.platform === "win32") {
58398
+ return windows(name);
58599
58399
  }
58600
- _encryptData(data) {
58601
- if (!this.#encryptionKey) {
58602
- return typeof data === "string" ? data : uint8ArrayToString(data);
58603
- }
58400
+ return linux(name);
58401
+ }
58402
+
58403
+ // node_modules/.pnpm/atomically@2.0.3/node_modules/atomically/dist/index.js
58404
+ var import_node_path3 = __toESM(require("node:path"), 1);
58405
+
58406
+ // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/index.js
58407
+ var import_node_fs = __toESM(require("node:fs"), 1);
58408
+ var import_node_util = require("node:util");
58409
+
58410
+ // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/attemptify.js
58411
+ var attemptifyAsync = (fn, onError) => {
58412
+ return function attemptified(...args) {
58413
+ return fn.apply(void 0, args).catch(onError);
58414
+ };
58415
+ };
58416
+ var attemptifySync = (fn, onError) => {
58417
+ return function attemptified(...args) {
58604
58418
  try {
58605
- const initializationVector = data.slice(0, 16);
58606
- const password = import_node_crypto2.default.pbkdf2Sync(this.#encryptionKey, initializationVector.toString(), 1e4, 32, "sha512");
58607
- const decipher = import_node_crypto2.default.createDecipheriv(encryptionAlgorithm, password, initializationVector);
58608
- const slice = data.slice(17);
58609
- const dataUpdate = typeof slice === "string" ? stringToUint8Array(slice) : slice;
58610
- return uint8ArrayToString(concatUint8Arrays([decipher.update(dataUpdate), decipher.final()]));
58611
- } catch {
58419
+ return fn.apply(void 0, args);
58420
+ } catch (error) {
58421
+ return onError(error);
58612
58422
  }
58613
- return data.toString();
58423
+ };
58424
+ };
58425
+
58426
+ // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/constants.js
58427
+ var import_node_process3 = __toESM(require("node:process"), 1);
58428
+ var IS_USER_ROOT = import_node_process3.default.getuid ? !import_node_process3.default.getuid() : false;
58429
+ var LIMIT_FILES_DESCRIPTORS = 1e4;
58430
+ var NOOP = () => void 0;
58431
+
58432
+ // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/handlers.js
58433
+ var Handlers = {
58434
+ /* API */
58435
+ isChangeErrorOk: (error) => {
58436
+ if (!Handlers.isNodeError(error))
58437
+ return false;
58438
+ const { code } = error;
58439
+ if (code === "ENOSYS")
58440
+ return true;
58441
+ if (!IS_USER_ROOT && (code === "EINVAL" || code === "EPERM"))
58442
+ return true;
58443
+ return false;
58444
+ },
58445
+ isNodeError: (error) => {
58446
+ return error instanceof Error;
58447
+ },
58448
+ isRetriableError: (error) => {
58449
+ if (!Handlers.isNodeError(error))
58450
+ return false;
58451
+ const { code } = error;
58452
+ if (code === "EMFILE" || code === "ENFILE" || code === "EAGAIN" || code === "EBUSY" || code === "EACCESS" || code === "EACCES" || code === "EACCS" || code === "EPERM")
58453
+ return true;
58454
+ return false;
58455
+ },
58456
+ onChangeError: (error) => {
58457
+ if (!Handlers.isNodeError(error))
58458
+ throw error;
58459
+ if (Handlers.isChangeErrorOk(error))
58460
+ return;
58461
+ throw error;
58614
58462
  }
58615
- _handleChange(getter, callback) {
58616
- let currentValue = getter();
58617
- const onChange = () => {
58618
- const oldValue = currentValue;
58619
- const newValue = getter();
58620
- if ((0, import_node_util2.isDeepStrictEqual)(newValue, oldValue)) {
58463
+ };
58464
+ var handlers_default = Handlers;
58465
+
58466
+ // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/retryify_queue.js
58467
+ var RetryfyQueue = class {
58468
+ constructor() {
58469
+ this.interval = 25;
58470
+ this.intervalId = void 0;
58471
+ this.limit = LIMIT_FILES_DESCRIPTORS;
58472
+ this.queueActive = /* @__PURE__ */ new Set();
58473
+ this.queueWaiting = /* @__PURE__ */ new Set();
58474
+ this.init = () => {
58475
+ if (this.intervalId)
58476
+ return;
58477
+ this.intervalId = setInterval(this.tick, this.interval);
58478
+ };
58479
+ this.reset = () => {
58480
+ if (!this.intervalId)
58621
58481
  return;
58482
+ clearInterval(this.intervalId);
58483
+ delete this.intervalId;
58484
+ };
58485
+ this.add = (fn) => {
58486
+ this.queueWaiting.add(fn);
58487
+ if (this.queueActive.size < this.limit / 2) {
58488
+ this.tick();
58489
+ } else {
58490
+ this.init();
58622
58491
  }
58623
- currentValue = newValue;
58624
- callback.call(this, newValue, oldValue);
58625
58492
  };
58626
- this.events.addEventListener("change", onChange);
58627
- return () => {
58628
- this.events.removeEventListener("change", onChange);
58493
+ this.remove = (fn) => {
58494
+ this.queueWaiting.delete(fn);
58495
+ this.queueActive.delete(fn);
58496
+ };
58497
+ this.schedule = () => {
58498
+ return new Promise((resolve) => {
58499
+ const cleanup = () => this.remove(resolver);
58500
+ const resolver = () => resolve(cleanup);
58501
+ this.add(resolver);
58502
+ });
58503
+ };
58504
+ this.tick = () => {
58505
+ if (this.queueActive.size >= this.limit)
58506
+ return;
58507
+ if (!this.queueWaiting.size)
58508
+ return this.reset();
58509
+ for (const fn of this.queueWaiting) {
58510
+ if (this.queueActive.size >= this.limit)
58511
+ break;
58512
+ this.queueWaiting.delete(fn);
58513
+ this.queueActive.add(fn);
58514
+ fn();
58515
+ }
58629
58516
  };
58630
58517
  }
58631
- _deserialize = (value) => JSON.parse(value);
58632
- _serialize = (value) => JSON.stringify(value, void 0, " ");
58633
- _validate(data) {
58634
- if (!this.#validator) {
58635
- return;
58636
- }
58637
- const valid = this.#validator(data);
58638
- if (valid || !this.#validator.errors) {
58639
- return;
58640
- }
58641
- const errors = this.#validator.errors.map(({ instancePath, message = "" }) => `\`${instancePath.slice(1)}\` ${message}`);
58642
- throw new Error("Config schema violation: " + errors.join("; "));
58643
- }
58644
- _ensureDirectory() {
58645
- import_node_fs2.default.mkdirSync(import_node_path4.default.dirname(this.path), { recursive: true });
58646
- }
58647
- _write(value) {
58648
- let data = this._serialize(value);
58649
- if (this.#encryptionKey) {
58650
- const initializationVector = import_node_crypto2.default.randomBytes(16);
58651
- const password = import_node_crypto2.default.pbkdf2Sync(this.#encryptionKey, initializationVector.toString(), 1e4, 32, "sha512");
58652
- const cipher = import_node_crypto2.default.createCipheriv(encryptionAlgorithm, password, initializationVector);
58653
- data = concatUint8Arrays([initializationVector, stringToUint8Array(":"), cipher.update(stringToUint8Array(data)), cipher.final()]);
58654
- }
58655
- if (import_node_process7.default.env.SNAP) {
58656
- import_node_fs2.default.writeFileSync(this.path, data, { mode: this.#options.configFileMode });
58657
- } else {
58518
+ };
58519
+ var retryify_queue_default = new RetryfyQueue();
58520
+
58521
+ // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/retryify.js
58522
+ var retryifyAsync = (fn, isRetriableError) => {
58523
+ return function retrified(timestamp) {
58524
+ return function attempt(...args) {
58525
+ return retryify_queue_default.schedule().then((cleanup) => {
58526
+ const onResolve = (result) => {
58527
+ cleanup();
58528
+ return result;
58529
+ };
58530
+ const onReject = (error) => {
58531
+ cleanup();
58532
+ if (Date.now() >= timestamp)
58533
+ throw error;
58534
+ if (isRetriableError(error)) {
58535
+ const delay = Math.round(100 * Math.random());
58536
+ const delayPromise = new Promise((resolve) => setTimeout(resolve, delay));
58537
+ return delayPromise.then(() => attempt.apply(void 0, args));
58538
+ }
58539
+ throw error;
58540
+ };
58541
+ return fn.apply(void 0, args).then(onResolve, onReject);
58542
+ });
58543
+ };
58544
+ };
58545
+ };
58546
+ var retryifySync = (fn, isRetriableError) => {
58547
+ return function retrified(timestamp) {
58548
+ return function attempt(...args) {
58658
58549
  try {
58659
- writeFileSync(this.path, data, { mode: this.#options.configFileMode });
58550
+ return fn.apply(void 0, args);
58660
58551
  } catch (error) {
58661
- if (error?.code === "EXDEV") {
58662
- import_node_fs2.default.writeFileSync(this.path, data, { mode: this.#options.configFileMode });
58663
- return;
58664
- }
58552
+ if (Date.now() > timestamp)
58553
+ throw error;
58554
+ if (isRetriableError(error))
58555
+ return attempt.apply(void 0, args);
58665
58556
  throw error;
58666
58557
  }
58667
- }
58668
- }
58669
- _watch() {
58670
- this._ensureDirectory();
58671
- if (!import_node_fs2.default.existsSync(this.path)) {
58672
- this._write(createPlainObject());
58673
- }
58674
- if (import_node_process7.default.platform === "win32") {
58675
- import_node_fs2.default.watch(this.path, { persistent: false }, debounce_fn_default(() => {
58676
- this.events.dispatchEvent(new Event("change"));
58677
- }, { wait: 100 }));
58678
- } else {
58679
- import_node_fs2.default.watchFile(this.path, { persistent: false }, debounce_fn_default(() => {
58680
- this.events.dispatchEvent(new Event("change"));
58681
- }, { wait: 5e3 }));
58682
- }
58558
+ };
58559
+ };
58560
+ };
58561
+
58562
+ // node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/index.js
58563
+ var FS = {
58564
+ attempt: {
58565
+ /* ASYNC */
58566
+ chmod: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.chmod), handlers_default.onChangeError),
58567
+ chown: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.chown), handlers_default.onChangeError),
58568
+ close: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.close), NOOP),
58569
+ fsync: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.fsync), NOOP),
58570
+ mkdir: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.mkdir), NOOP),
58571
+ realpath: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.realpath), NOOP),
58572
+ stat: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.stat), NOOP),
58573
+ unlink: attemptifyAsync((0, import_node_util.promisify)(import_node_fs.default.unlink), NOOP),
58574
+ /* SYNC */
58575
+ chmodSync: attemptifySync(import_node_fs.default.chmodSync, handlers_default.onChangeError),
58576
+ chownSync: attemptifySync(import_node_fs.default.chownSync, handlers_default.onChangeError),
58577
+ closeSync: attemptifySync(import_node_fs.default.closeSync, NOOP),
58578
+ existsSync: attemptifySync(import_node_fs.default.existsSync, NOOP),
58579
+ fsyncSync: attemptifySync(import_node_fs.default.fsync, NOOP),
58580
+ mkdirSync: attemptifySync(import_node_fs.default.mkdirSync, NOOP),
58581
+ realpathSync: attemptifySync(import_node_fs.default.realpathSync, NOOP),
58582
+ statSync: attemptifySync(import_node_fs.default.statSync, NOOP),
58583
+ unlinkSync: attemptifySync(import_node_fs.default.unlinkSync, NOOP)
58584
+ },
58585
+ retry: {
58586
+ /* ASYNC */
58587
+ close: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.close), handlers_default.isRetriableError),
58588
+ fsync: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.fsync), handlers_default.isRetriableError),
58589
+ open: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.open), handlers_default.isRetriableError),
58590
+ readFile: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.readFile), handlers_default.isRetriableError),
58591
+ rename: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.rename), handlers_default.isRetriableError),
58592
+ stat: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.stat), handlers_default.isRetriableError),
58593
+ write: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.write), handlers_default.isRetriableError),
58594
+ writeFile: retryifyAsync((0, import_node_util.promisify)(import_node_fs.default.writeFile), handlers_default.isRetriableError),
58595
+ /* SYNC */
58596
+ closeSync: retryifySync(import_node_fs.default.closeSync, handlers_default.isRetriableError),
58597
+ fsyncSync: retryifySync(import_node_fs.default.fsyncSync, handlers_default.isRetriableError),
58598
+ openSync: retryifySync(import_node_fs.default.openSync, handlers_default.isRetriableError),
58599
+ readFileSync: retryifySync(import_node_fs.default.readFileSync, handlers_default.isRetriableError),
58600
+ renameSync: retryifySync(import_node_fs.default.renameSync, handlers_default.isRetriableError),
58601
+ statSync: retryifySync(import_node_fs.default.statSync, handlers_default.isRetriableError),
58602
+ writeSync: retryifySync(import_node_fs.default.writeSync, handlers_default.isRetriableError),
58603
+ writeFileSync: retryifySync(import_node_fs.default.writeFileSync, handlers_default.isRetriableError)
58683
58604
  }
58684
- _migrate(migrations, versionToMigrate, beforeEachMigration) {
58685
- let previousMigratedVersion = this._get(MIGRATION_KEY, "0.0.0");
58686
- const newerVersions = Object.keys(migrations).filter((candidateVersion) => this._shouldPerformMigration(candidateVersion, previousMigratedVersion, versionToMigrate));
58687
- let storeBackup = { ...this.store };
58688
- for (const version of newerVersions) {
58689
- try {
58690
- if (beforeEachMigration) {
58691
- beforeEachMigration(this, {
58692
- fromVersion: previousMigratedVersion,
58693
- toVersion: version,
58694
- finalVersion: versionToMigrate,
58695
- versions: newerVersions
58696
- });
58605
+ };
58606
+ var dist_default = FS;
58607
+
58608
+ // node_modules/.pnpm/atomically@2.0.3/node_modules/atomically/dist/constants.js
58609
+ var import_node_os3 = __toESM(require("node:os"), 1);
58610
+ var import_node_process4 = __toESM(require("node:process"), 1);
58611
+ var DEFAULT_ENCODING = "utf8";
58612
+ var DEFAULT_FILE_MODE = 438;
58613
+ var DEFAULT_FOLDER_MODE = 511;
58614
+ var DEFAULT_WRITE_OPTIONS = {};
58615
+ var DEFAULT_USER_UID = import_node_os3.default.userInfo().uid;
58616
+ var DEFAULT_USER_GID = import_node_os3.default.userInfo().gid;
58617
+ var DEFAULT_TIMEOUT_SYNC = 1e3;
58618
+ var IS_POSIX = !!import_node_process4.default.getuid;
58619
+ var IS_USER_ROOT2 = import_node_process4.default.getuid ? !import_node_process4.default.getuid() : false;
58620
+ var LIMIT_BASENAME_LENGTH = 128;
58621
+
58622
+ // node_modules/.pnpm/atomically@2.0.3/node_modules/atomically/dist/utils/lang.js
58623
+ var isException = (value) => {
58624
+ return value instanceof Error && "code" in value;
58625
+ };
58626
+ var isString = (value) => {
58627
+ return typeof value === "string";
58628
+ };
58629
+ var isUndefined = (value) => {
58630
+ return value === void 0;
58631
+ };
58632
+
58633
+ // node_modules/.pnpm/atomically@2.0.3/node_modules/atomically/dist/utils/temp.js
58634
+ var import_node_path2 = __toESM(require("node:path"), 1);
58635
+
58636
+ // node_modules/.pnpm/when-exit@2.1.2/node_modules/when-exit/dist/node/interceptor.js
58637
+ var import_node_process6 = __toESM(require("node:process"), 1);
58638
+
58639
+ // node_modules/.pnpm/when-exit@2.1.2/node_modules/when-exit/dist/node/constants.js
58640
+ var import_node_process5 = __toESM(require("node:process"), 1);
58641
+ var IS_LINUX = import_node_process5.default.platform === "linux";
58642
+ var IS_WINDOWS = import_node_process5.default.platform === "win32";
58643
+
58644
+ // node_modules/.pnpm/when-exit@2.1.2/node_modules/when-exit/dist/node/signals.js
58645
+ var Signals = ["SIGABRT", "SIGALRM", "SIGHUP", "SIGINT", "SIGTERM"];
58646
+ if (!IS_WINDOWS) {
58647
+ Signals.push("SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT");
58648
+ }
58649
+ if (IS_LINUX) {
58650
+ Signals.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT", "SIGUNUSED");
58651
+ }
58652
+ var signals_default = Signals;
58653
+
58654
+ // node_modules/.pnpm/when-exit@2.1.2/node_modules/when-exit/dist/node/interceptor.js
58655
+ var Interceptor = class {
58656
+ /* CONSTRUCTOR */
58657
+ constructor() {
58658
+ this.callbacks = /* @__PURE__ */ new Set();
58659
+ this.exited = false;
58660
+ this.exit = (signal) => {
58661
+ if (this.exited)
58662
+ return;
58663
+ this.exited = true;
58664
+ for (const callback of this.callbacks) {
58665
+ callback();
58666
+ }
58667
+ if (signal) {
58668
+ if (IS_WINDOWS && (signal !== "SIGINT" && signal !== "SIGTERM" && signal !== "SIGKILL")) {
58669
+ import_node_process6.default.kill(import_node_process6.default.pid, "SIGTERM");
58670
+ } else {
58671
+ import_node_process6.default.kill(import_node_process6.default.pid, signal);
58697
58672
  }
58698
- const migration = migrations[version];
58699
- migration?.(this);
58700
- this._set(MIGRATION_KEY, version);
58701
- previousMigratedVersion = version;
58702
- storeBackup = { ...this.store };
58703
- } catch (error) {
58704
- this.store = storeBackup;
58705
- throw new Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${error}`);
58706
58673
  }
58674
+ };
58675
+ this.hook = () => {
58676
+ import_node_process6.default.once("exit", () => this.exit());
58677
+ for (const signal of signals_default) {
58678
+ import_node_process6.default.once(signal, () => this.exit(signal));
58679
+ }
58680
+ };
58681
+ this.register = (callback) => {
58682
+ this.callbacks.add(callback);
58683
+ return () => {
58684
+ this.callbacks.delete(callback);
58685
+ };
58686
+ };
58687
+ this.hook();
58688
+ }
58689
+ };
58690
+ var interceptor_default = new Interceptor();
58691
+
58692
+ // node_modules/.pnpm/when-exit@2.1.2/node_modules/when-exit/dist/node/index.js
58693
+ var whenExit = interceptor_default.register;
58694
+ var node_default = whenExit;
58695
+
58696
+ // node_modules/.pnpm/atomically@2.0.3/node_modules/atomically/dist/utils/temp.js
58697
+ var Temp = {
58698
+ /* VARIABLES */
58699
+ store: {},
58700
+ /* API */
58701
+ create: (filePath) => {
58702
+ const randomness = `000000${Math.floor(Math.random() * 16777215).toString(16)}`.slice(-6);
58703
+ const timestamp = Date.now().toString().slice(-10);
58704
+ const prefix = "tmp-";
58705
+ const suffix = `.${prefix}${timestamp}${randomness}`;
58706
+ const tempPath = `${filePath}${suffix}`;
58707
+ return tempPath;
58708
+ },
58709
+ get: (filePath, creator, purge = true) => {
58710
+ const tempPath = Temp.truncate(creator(filePath));
58711
+ if (tempPath in Temp.store)
58712
+ return Temp.get(filePath, creator, purge);
58713
+ Temp.store[tempPath] = purge;
58714
+ const disposer = () => delete Temp.store[tempPath];
58715
+ return [tempPath, disposer];
58716
+ },
58717
+ purge: (filePath) => {
58718
+ if (!Temp.store[filePath])
58719
+ return;
58720
+ delete Temp.store[filePath];
58721
+ dist_default.attempt.unlink(filePath);
58722
+ },
58723
+ purgeSync: (filePath) => {
58724
+ if (!Temp.store[filePath])
58725
+ return;
58726
+ delete Temp.store[filePath];
58727
+ dist_default.attempt.unlinkSync(filePath);
58728
+ },
58729
+ purgeSyncAll: () => {
58730
+ for (const filePath in Temp.store) {
58731
+ Temp.purgeSync(filePath);
58707
58732
  }
58708
- if (this._isVersionInRangeFormat(previousMigratedVersion) || !import_semver.default.eq(previousMigratedVersion, versionToMigrate)) {
58709
- this._set(MIGRATION_KEY, versionToMigrate);
58710
- }
58733
+ },
58734
+ truncate: (filePath) => {
58735
+ const basename2 = import_node_path2.default.basename(filePath);
58736
+ if (basename2.length <= LIMIT_BASENAME_LENGTH)
58737
+ return filePath;
58738
+ const truncable = /^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(basename2);
58739
+ if (!truncable)
58740
+ return filePath;
58741
+ const truncationLength = basename2.length - LIMIT_BASENAME_LENGTH;
58742
+ return `${filePath.slice(0, -basename2.length)}${truncable[1]}${truncable[2].slice(0, -truncationLength)}${truncable[3]}`;
58711
58743
  }
58712
- _containsReservedKey(key) {
58713
- if (typeof key === "object") {
58714
- const firsKey = Object.keys(key)[0];
58715
- if (firsKey === INTERNAL_KEY) {
58716
- return true;
58744
+ };
58745
+ node_default(Temp.purgeSyncAll);
58746
+ var temp_default = Temp;
58747
+
58748
+ // node_modules/.pnpm/atomically@2.0.3/node_modules/atomically/dist/index.js
58749
+ function writeFileSync(filePath, data, options = DEFAULT_WRITE_OPTIONS) {
58750
+ if (isString(options))
58751
+ return writeFileSync(filePath, data, { encoding: options });
58752
+ const timeout = Date.now() + ((options.timeout ?? DEFAULT_TIMEOUT_SYNC) || -1);
58753
+ let tempDisposer = null;
58754
+ let tempPath = null;
58755
+ let fd = null;
58756
+ try {
58757
+ const filePathReal = dist_default.attempt.realpathSync(filePath);
58758
+ const filePathExists = !!filePathReal;
58759
+ filePath = filePathReal || filePath;
58760
+ [tempPath, tempDisposer] = temp_default.get(filePath, options.tmpCreate || temp_default.create, !(options.tmpPurge === false));
58761
+ const useStatChown = IS_POSIX && isUndefined(options.chown);
58762
+ const useStatMode = isUndefined(options.mode);
58763
+ if (filePathExists && (useStatChown || useStatMode)) {
58764
+ const stats = dist_default.attempt.statSync(filePath);
58765
+ if (stats) {
58766
+ options = { ...options };
58767
+ if (useStatChown) {
58768
+ options.chown = { uid: stats.uid, gid: stats.gid };
58769
+ }
58770
+ if (useStatMode) {
58771
+ options.mode = stats.mode;
58772
+ }
58717
58773
  }
58718
58774
  }
58719
- if (typeof key !== "string") {
58720
- return false;
58775
+ if (!filePathExists) {
58776
+ const parentPath = import_node_path3.default.dirname(filePath);
58777
+ dist_default.attempt.mkdirSync(parentPath, {
58778
+ mode: DEFAULT_FOLDER_MODE,
58779
+ recursive: true
58780
+ });
58721
58781
  }
58722
- if (this.#options.accessPropertiesByDotNotation) {
58723
- if (key.startsWith(`${INTERNAL_KEY}.`)) {
58724
- return true;
58725
- }
58726
- return false;
58782
+ fd = dist_default.retry.openSync(timeout)(tempPath, "w", options.mode || DEFAULT_FILE_MODE);
58783
+ if (options.tmpCreated) {
58784
+ options.tmpCreated(tempPath);
58727
58785
  }
58728
- return false;
58729
- }
58730
- _isVersionInRangeFormat(version) {
58731
- return import_semver.default.clean(version) === null;
58732
- }
58733
- _shouldPerformMigration(candidateVersion, previousMigratedVersion, versionToMigrate) {
58734
- if (this._isVersionInRangeFormat(candidateVersion)) {
58735
- if (previousMigratedVersion !== "0.0.0" && import_semver.default.satisfies(previousMigratedVersion, candidateVersion)) {
58736
- return false;
58786
+ if (isString(data)) {
58787
+ dist_default.retry.writeSync(timeout)(fd, data, 0, options.encoding || DEFAULT_ENCODING);
58788
+ } else if (!isUndefined(data)) {
58789
+ dist_default.retry.writeSync(timeout)(fd, data, 0, data.length, 0);
58790
+ }
58791
+ if (options.fsync !== false) {
58792
+ if (options.fsyncWait !== false) {
58793
+ dist_default.retry.fsyncSync(timeout)(fd);
58794
+ } else {
58795
+ dist_default.attempt.fsync(fd);
58737
58796
  }
58738
- return import_semver.default.satisfies(versionToMigrate, candidateVersion);
58739
58797
  }
58740
- if (import_semver.default.lte(candidateVersion, previousMigratedVersion)) {
58741
- return false;
58798
+ dist_default.retry.closeSync(timeout)(fd);
58799
+ fd = null;
58800
+ if (options.chown && (options.chown.uid !== DEFAULT_USER_UID || options.chown.gid !== DEFAULT_USER_GID)) {
58801
+ dist_default.attempt.chownSync(tempPath, options.chown.uid, options.chown.gid);
58742
58802
  }
58743
- if (import_semver.default.gt(candidateVersion, versionToMigrate)) {
58744
- return false;
58803
+ if (options.mode && options.mode !== DEFAULT_FILE_MODE) {
58804
+ dist_default.attempt.chmodSync(tempPath, options.mode);
58745
58805
  }
58746
- return true;
58747
- }
58748
- _get(key, defaultValue) {
58749
- return getProperty(this.store, key, defaultValue);
58750
- }
58751
- _set(key, value) {
58752
- const { store } = this;
58753
- setProperty(store, key, value);
58754
- this.store = store;
58806
+ try {
58807
+ dist_default.retry.renameSync(timeout)(tempPath, filePath);
58808
+ } catch (error) {
58809
+ if (!isException(error))
58810
+ throw error;
58811
+ if (error.code !== "ENAMETOOLONG")
58812
+ throw error;
58813
+ dist_default.retry.renameSync(timeout)(tempPath, temp_default.truncate(filePath));
58814
+ }
58815
+ tempDisposer();
58816
+ tempPath = null;
58817
+ } finally {
58818
+ if (fd)
58819
+ dist_default.attempt.closeSync(fd);
58820
+ if (tempPath)
58821
+ temp_default.purge(tempPath);
58755
58822
  }
58756
- };
58823
+ }
58757
58824
 
58758
- // packages/sdk/db.js
58759
- var projectName = "autho";
58760
- var DB = class {
58761
- constructor({ encryptionKey, name = "default", dataFolder }) {
58762
- this.encryptionKey = encryptionKey;
58763
- this.client = new Conf({
58764
- projectName,
58765
- encryptionKey,
58766
- configName: name,
58767
- cwd: dataFolder,
58768
- projectSuffix: ""
58769
- });
58770
- }
58771
- get(key, defaultValue) {
58772
- return this.client.get(key, defaultValue);
58773
- }
58774
- set(key, value) {
58775
- this.client.set(key, value);
58776
- }
58777
- clear() {
58778
- this.client.clear();
58825
+ // node_modules/.pnpm/conf@12.0.0/node_modules/conf/dist/source/index.js
58826
+ var import_ajv = __toESM(require_ajv(), 1);
58827
+ var import_ajv_formats = __toESM(require_dist(), 1);
58828
+
58829
+ // node_modules/.pnpm/mimic-fn@4.0.0/node_modules/mimic-fn/index.js
58830
+ var copyProperty = (to, from3, property, ignoreNonConfigurable) => {
58831
+ if (property === "length" || property === "prototype") {
58832
+ return;
58779
58833
  }
58780
- store() {
58781
- return this.client.store;
58834
+ if (property === "arguments" || property === "caller") {
58835
+ return;
58782
58836
  }
58783
- path() {
58784
- return this.client.path;
58837
+ const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
58838
+ const fromDescriptor = Object.getOwnPropertyDescriptor(from3, property);
58839
+ if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
58840
+ return;
58785
58841
  }
58842
+ Object.defineProperty(to, property, fromDescriptor);
58786
58843
  };
58787
-
58788
- // packages/cli/app.js
58789
- var App = class {
58790
- constructor(options = {}) {
58791
- this.encryptionKey = options.encryptionKey || config_default.masterPasswordHash;
58792
- this.dataFolder = options.dataFolder || config_default.dataFolder;
58793
- this.name = options.name || config_default.name;
58794
- this.db = new DB({
58795
- encryptionKey: this.encryptionKey,
58796
- dataFolder: this.dataFolder,
58797
- name: this.name
58798
- });
58799
- this.secrets = new Secrets(this.db);
58800
- }
58801
- static async masterKey(masterPassword, masterPasswordHash) {
58802
- masterPassword = masterPassword || config_default.masterPassword;
58803
- masterPasswordHash = masterPasswordHash || config_default.masterPasswordHash;
58804
- if (masterPasswordHash) {
58805
- return masterPasswordHash;
58806
- } else if (!masterPassword) {
58807
- masterPassword = await ask({
58808
- name: "masterPassword",
58809
- message: "Password:",
58810
- type: "password",
58811
- required: true
58812
- });
58813
- }
58814
- masterPasswordHash = Cipher.hash(masterPassword);
58815
- return masterPasswordHash;
58816
- }
58844
+ var canCopyProperty = function(toDescriptor, fromDescriptor) {
58845
+ return toDescriptor === void 0 || toDescriptor.configurable || toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value);
58817
58846
  };
58818
-
58819
- // packages/cli/wizards/getEncryptionKey.js
58820
- var wizard = async (confirm = false) => {
58821
- const questions = [
58822
- {
58823
- name: "password",
58824
- message: "password:",
58825
- type: "password",
58826
- required: true
58827
- }
58828
- ];
58829
- if (confirm) {
58830
- questions.push({
58831
- name: "confirmPassword",
58832
- message: "confirm password:",
58833
- type: "password",
58834
- required: true
58835
- });
58836
- }
58837
- const input = await prompt2(questions);
58838
- if (input.confirmPassword && input.password !== input.confirmPassword) {
58839
- throw new Error("Passwords do not match");
58847
+ var changePrototype = (to, from3) => {
58848
+ const fromPrototype = Object.getPrototypeOf(from3);
58849
+ if (fromPrototype === Object.getPrototypeOf(to)) {
58850
+ return;
58840
58851
  }
58841
- return Cipher.hash(input.password);
58852
+ Object.setPrototypeOf(to, fromPrototype);
58842
58853
  };
58843
- var getEncryptionKey_default = wizard;
58854
+ var wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/
58855
+ ${fromBody}`;
58856
+ var toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, "toString");
58857
+ var toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, "name");
58858
+ var changeToString = (to, from3, name) => {
58859
+ const withName = name === "" ? "" : `with ${name.trim()}() `;
58860
+ const newToString = wrappedToString.bind(null, withName, from3.toString());
58861
+ Object.defineProperty(newToString, "name", toStringName);
58862
+ Object.defineProperty(to, "toString", { ...toStringDescriptor, value: newToString });
58863
+ };
58864
+ function mimicFunction(to, from3, { ignoreNonConfigurable = false } = {}) {
58865
+ const { name } = to;
58866
+ for (const property of Reflect.ownKeys(from3)) {
58867
+ copyProperty(to, from3, property, ignoreNonConfigurable);
58868
+ }
58869
+ changePrototype(to, from3);
58870
+ changeToString(to, from3, name);
58871
+ return to;
58872
+ }
58844
58873
 
58845
- // packages/cli/wizards/createSecret.js
58846
- var wizard2 = async (app) => {
58847
- const secrets = app.secrets;
58848
- const info = await prompt2([
58849
- {
58850
- name: "name",
58851
- message: "name:",
58852
- type: "input",
58853
- required: true
58854
- },
58855
- {
58856
- name: "type",
58857
- message: "type:",
58858
- type: "list",
58859
- default: "password",
58860
- choices: [
58861
- { name: "Password", value: "password" },
58862
- { name: "OTP", value: "otp" },
58863
- { name: "Note", value: "note" }
58864
- ],
58865
- required: true
58866
- },
58867
- {
58868
- name: "protected",
58869
- message: "protected:",
58870
- type: "confirm",
58871
- default: false,
58872
- required: true
58873
- }
58874
- ]);
58875
- let newSecret = { typeOptions: {} };
58876
- let encryptionKey = app.db.encryptionKey;
58877
- if (info.protected) {
58878
- encryptionKey = await getEncryptionKey_default(true);
58874
+ // node_modules/.pnpm/debounce-fn@5.1.2/node_modules/debounce-fn/index.js
58875
+ var debounceFn = (inputFunction, options = {}) => {
58876
+ if (typeof inputFunction !== "function") {
58877
+ throw new TypeError(`Expected the first argument to be a function, got \`${typeof inputFunction}\``);
58879
58878
  }
58880
- switch (info.type) {
58881
- case "password":
58882
- {
58883
- const password = await prompt2([
58884
- {
58885
- name: "url",
58886
- message: "url:",
58887
- type: "input",
58888
- required: false
58889
- },
58890
- {
58891
- name: "username",
58892
- message: "username:",
58893
- type: "input",
58894
- required: true
58895
- },
58896
- {
58897
- name: "value",
58898
- message: "password:",
58899
- type: "password",
58900
- required: true
58901
- }
58902
- ]);
58903
- newSecret = {
58904
- ...info,
58905
- value: password.value,
58906
- typeOptions: {
58907
- username: password.username,
58908
- url: password.url
58909
- }
58910
- };
58879
+ const {
58880
+ wait = 0,
58881
+ maxWait = Number.POSITIVE_INFINITY,
58882
+ before = false,
58883
+ after = true
58884
+ } = options;
58885
+ if (!before && !after) {
58886
+ throw new Error("Both `before` and `after` are false, function wouldn't be called.");
58887
+ }
58888
+ let timeout;
58889
+ let maxTimeout;
58890
+ let result;
58891
+ const debouncedFunction = function(...arguments_) {
58892
+ const context = this;
58893
+ const later = () => {
58894
+ timeout = void 0;
58895
+ if (maxTimeout) {
58896
+ clearTimeout(maxTimeout);
58897
+ maxTimeout = void 0;
58911
58898
  }
58912
- break;
58913
- case "note":
58914
- {
58915
- const note = await prompt2([
58916
- {
58917
- name: "value",
58918
- message: "note:",
58919
- type: "password",
58920
- required: true
58921
- }
58922
- ]);
58923
- newSecret = {
58924
- ...info,
58925
- value: note.value,
58926
- typeOptions: {}
58927
- };
58899
+ if (after) {
58900
+ result = inputFunction.apply(context, arguments_);
58928
58901
  }
58929
- break;
58930
- case "otp":
58931
- {
58932
- const otp = await prompt2([
58933
- {
58934
- name: "username",
58935
- message: "username:",
58936
- type: "input",
58937
- required: true
58938
- },
58939
- {
58940
- name: "value",
58941
- message: "value:",
58942
- type: "password",
58943
- required: true
58944
- }
58945
- ]);
58946
- newSecret = {
58947
- ...info,
58948
- value: otp.value,
58949
- typeOptions: {
58950
- username: otp.username
58951
- }
58952
- };
58902
+ };
58903
+ const maxLater = () => {
58904
+ maxTimeout = void 0;
58905
+ if (timeout) {
58906
+ clearTimeout(timeout);
58907
+ timeout = void 0;
58953
58908
  }
58954
- break;
58955
- }
58956
- await secrets.add(newSecret, encryptionKey);
58909
+ if (after) {
58910
+ result = inputFunction.apply(context, arguments_);
58911
+ }
58912
+ };
58913
+ const shouldCallNow = before && !timeout;
58914
+ clearTimeout(timeout);
58915
+ timeout = setTimeout(later, wait);
58916
+ if (maxWait > 0 && maxWait !== Number.POSITIVE_INFINITY && !maxTimeout) {
58917
+ maxTimeout = setTimeout(maxLater, maxWait);
58918
+ }
58919
+ if (shouldCallNow) {
58920
+ result = inputFunction.apply(context, arguments_);
58921
+ }
58922
+ return result;
58923
+ };
58924
+ mimicFunction(debouncedFunction, inputFunction);
58925
+ debouncedFunction.cancel = () => {
58926
+ if (timeout) {
58927
+ clearTimeout(timeout);
58928
+ timeout = void 0;
58929
+ }
58930
+ if (maxTimeout) {
58931
+ clearTimeout(maxTimeout);
58932
+ maxTimeout = void 0;
58933
+ }
58934
+ };
58935
+ return debouncedFunction;
58957
58936
  };
58958
- var createSecret_default = wizard2;
58937
+ var debounce_fn_default = debounceFn;
58959
58938
 
58960
- // packages/cli/wizards/getSecret.js
58961
- var wizard3 = async (app) => {
58962
- const existingSecrets = app.db.get("secrets", []);
58963
- if (existingSecrets.length === 0) {
58964
- throw new Error("No secrets found");
58939
+ // node_modules/.pnpm/conf@12.0.0/node_modules/conf/dist/source/index.js
58940
+ var import_semver = __toESM(require_semver2(), 1);
58941
+
58942
+ // node_modules/.pnpm/uint8array-extras@0.3.0/node_modules/uint8array-extras/index.js
58943
+ var objectToString = Object.prototype.toString;
58944
+ function isUint8Array(value) {
58945
+ return value && objectToString.call(value) === "[object Uint8Array]";
58946
+ }
58947
+ function assertUint8Array(value) {
58948
+ if (!isUint8Array(value)) {
58949
+ throw new TypeError(`Expected \`Uint8Array\`, got \`${typeof value}\``);
58965
58950
  }
58966
- const choices = existingSecrets.map((secret2) => ({
58967
- value: secret2.id,
58968
- name: `${secret2.name} (${secret2.typeOptions.username || secret2.id})`
58969
- }));
58970
- const { id: secretId } = await prompt2({
58971
- name: "id",
58972
- message: "Secrets:",
58973
- type: "list",
58974
- choices,
58975
- required: true
58976
- });
58977
- const secret = await app.secrets.get(secretId);
58978
- if (!secret) {
58979
- throw new Error("Secret not found");
58951
+ }
58952
+ function concatUint8Arrays(arrays, totalLength) {
58953
+ if (arrays.length === 0) {
58954
+ return new Uint8Array(0);
58980
58955
  }
58981
- return secret;
58982
- };
58983
- var getSecret_default = wizard3;
58956
+ totalLength ??= arrays.reduce((accumulator, currentValue) => accumulator + currentValue.length, 0);
58957
+ const returnValue = new Uint8Array(totalLength);
58958
+ let offset = 0;
58959
+ for (const array of arrays) {
58960
+ assertUint8Array(array);
58961
+ returnValue.set(array, offset);
58962
+ offset += array.length;
58963
+ }
58964
+ return returnValue;
58965
+ }
58966
+ function uint8ArrayToString(array) {
58967
+ assertUint8Array(array);
58968
+ return new globalThis.TextDecoder().decode(array);
58969
+ }
58970
+ function assertString(value) {
58971
+ if (typeof value !== "string") {
58972
+ throw new TypeError(`Expected \`string\`, got \`${typeof value}\``);
58973
+ }
58974
+ }
58975
+ function stringToUint8Array(string) {
58976
+ assertString(string);
58977
+ return new globalThis.TextEncoder().encode(string);
58978
+ }
58979
+ var byteToHexLookupTable = Array.from({ length: 256 }, (_3, index) => index.toString(16).padStart(2, "0"));
58984
58980
 
58985
- // node_modules/.pnpm/otpauth@9.2.3/node_modules/otpauth/dist/otpauth.node.mjs
58986
- var crypto3 = __toESM(require("node:crypto"), 1);
58987
- var uintToBuf = (num) => {
58988
- const buf = new ArrayBuffer(8);
58989
- const arr = new Uint8Array(buf);
58990
- let acc = num;
58991
- for (let i = 7; i >= 0; i--) {
58992
- if (acc === 0)
58993
- break;
58994
- arr[i] = acc & 255;
58995
- acc -= arr[i];
58996
- acc /= 256;
58981
+ // node_modules/.pnpm/conf@12.0.0/node_modules/conf/dist/source/index.js
58982
+ var Ajv = import_ajv.default.default;
58983
+ var ajvFormats = import_ajv_formats.default.default;
58984
+ var encryptionAlgorithm = "aes-256-cbc";
58985
+ var createPlainObject = () => /* @__PURE__ */ Object.create(null);
58986
+ var isExist = (data) => data !== void 0 && data !== null;
58987
+ var checkValueType = (key, value) => {
58988
+ const nonJsonTypes = /* @__PURE__ */ new Set([
58989
+ "undefined",
58990
+ "symbol",
58991
+ "function"
58992
+ ]);
58993
+ const type = typeof value;
58994
+ if (nonJsonTypes.has(type)) {
58995
+ throw new TypeError(`Setting a value of type \`${type}\` for key \`${key}\` is not allowed as it's not supported by JSON`);
58997
58996
  }
58998
- return buf;
58999
58997
  };
59000
- var jsSHA = void 0;
59001
- var globalScope = (() => {
59002
- if (typeof globalThis === "object")
59003
- return globalThis;
59004
- else {
59005
- Object.defineProperty(Object.prototype, "__GLOBALTHIS__", {
59006
- get() {
59007
- return this;
59008
- },
59009
- configurable: true
59010
- });
59011
- try {
59012
- if (typeof __GLOBALTHIS__ !== "undefined")
59013
- return __GLOBALTHIS__;
59014
- } finally {
59015
- delete Object.prototype.__GLOBALTHIS__;
58998
+ var INTERNAL_KEY = "__internal__";
58999
+ var MIGRATION_KEY = `${INTERNAL_KEY}.migrations.version`;
59000
+ var Conf = class {
59001
+ path;
59002
+ events;
59003
+ #validator;
59004
+ #encryptionKey;
59005
+ #options;
59006
+ #defaultValues = {};
59007
+ constructor(partialOptions = {}) {
59008
+ const options = {
59009
+ configName: "config",
59010
+ fileExtension: "json",
59011
+ projectSuffix: "nodejs",
59012
+ clearInvalidConfig: false,
59013
+ accessPropertiesByDotNotation: true,
59014
+ configFileMode: 438,
59015
+ ...partialOptions
59016
+ };
59017
+ if (!options.cwd) {
59018
+ if (!options.projectName) {
59019
+ throw new Error("Please specify the `projectName` option.");
59020
+ }
59021
+ options.cwd = envPaths(options.projectName, { suffix: options.projectSuffix }).config;
59016
59022
  }
59017
- }
59018
- if (typeof self !== "undefined")
59019
- return self;
59020
- else if (typeof window !== "undefined")
59021
- return window;
59022
- else if (typeof global !== "undefined")
59023
- return global;
59024
- return void 0;
59025
- })();
59026
- var OPENSSL_JSSHA_ALGO_MAP = {
59027
- SHA1: "SHA-1",
59028
- SHA224: "SHA-224",
59029
- SHA256: "SHA-256",
59030
- SHA384: "SHA-384",
59031
- SHA512: "SHA-512",
59032
- "SHA3-224": "SHA3-224",
59033
- "SHA3-256": "SHA3-256",
59034
- "SHA3-384": "SHA3-384",
59035
- "SHA3-512": "SHA3-512"
59036
- };
59037
- var hmacDigest = (algorithm, key, message) => {
59038
- if (crypto3?.createHmac) {
59039
- const hmac = crypto3.createHmac(algorithm, globalScope.Buffer.from(key));
59040
- hmac.update(globalScope.Buffer.from(message));
59041
- return hmac.digest().buffer;
59042
- } else {
59043
- const variant = OPENSSL_JSSHA_ALGO_MAP[algorithm.toUpperCase()];
59044
- if (typeof variant === "undefined") {
59045
- throw new TypeError("Unknown hash function");
59023
+ this.#options = options;
59024
+ if (options.schema) {
59025
+ if (typeof options.schema !== "object") {
59026
+ throw new TypeError("The `schema` option must be an object.");
59027
+ }
59028
+ const ajv = new Ajv({
59029
+ allErrors: true,
59030
+ useDefaults: true
59031
+ });
59032
+ ajvFormats(ajv);
59033
+ const schema = {
59034
+ type: "object",
59035
+ properties: options.schema
59036
+ };
59037
+ this.#validator = ajv.compile(schema);
59038
+ for (const [key, value] of Object.entries(options.schema)) {
59039
+ if (value?.default) {
59040
+ this.#defaultValues[key] = value.default;
59041
+ }
59042
+ }
59043
+ }
59044
+ if (options.defaults) {
59045
+ this.#defaultValues = {
59046
+ ...this.#defaultValues,
59047
+ ...options.defaults
59048
+ };
59049
+ }
59050
+ if (options.serialize) {
59051
+ this._serialize = options.serialize;
59052
+ }
59053
+ if (options.deserialize) {
59054
+ this._deserialize = options.deserialize;
59055
+ }
59056
+ this.events = new EventTarget();
59057
+ this.#encryptionKey = options.encryptionKey;
59058
+ const fileExtension = options.fileExtension ? `.${options.fileExtension}` : "";
59059
+ this.path = import_node_path4.default.resolve(options.cwd, `${options.configName ?? "config"}${fileExtension}`);
59060
+ const fileStore = this.store;
59061
+ const store = Object.assign(createPlainObject(), options.defaults, fileStore);
59062
+ this._validate(store);
59063
+ try {
59064
+ import_node_assert2.default.deepEqual(fileStore, store);
59065
+ } catch {
59066
+ this.store = store;
59046
59067
  }
59047
- const hmac = new jsSHA(variant, "ARRAYBUFFER");
59048
- hmac.setHMACKey(key, "ARRAYBUFFER");
59049
- hmac.update(message);
59050
- return hmac.getHMAC("ARRAYBUFFER");
59051
- }
59052
- };
59053
- var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
59054
- var base32ToBuf = (str) => {
59055
- let end = str.length;
59056
- while (str[end - 1] === "=")
59057
- --end;
59058
- const cstr = (end < str.length ? str.substring(0, end) : str).toUpperCase();
59059
- const buf = new ArrayBuffer(cstr.length * 5 / 8 | 0);
59060
- const arr = new Uint8Array(buf);
59061
- let bits = 0;
59062
- let value = 0;
59063
- let index = 0;
59064
- for (let i = 0; i < cstr.length; i++) {
59065
- const idx = ALPHABET.indexOf(cstr[i]);
59066
- if (idx === -1)
59067
- throw new TypeError(`Invalid character found: ${cstr[i]}`);
59068
- value = value << 5 | idx;
59069
- bits += 5;
59070
- if (bits >= 8) {
59071
- bits -= 8;
59072
- arr[index++] = value >>> bits;
59068
+ if (options.watch) {
59069
+ this._watch();
59073
59070
  }
59074
- }
59075
- return buf;
59076
- };
59077
- var base32FromBuf = (buf) => {
59078
- const arr = new Uint8Array(buf);
59079
- let bits = 0;
59080
- let value = 0;
59081
- let str = "";
59082
- for (let i = 0; i < arr.length; i++) {
59083
- value = value << 8 | arr[i];
59084
- bits += 8;
59085
- while (bits >= 5) {
59086
- str += ALPHABET[value >>> bits - 5 & 31];
59087
- bits -= 5;
59071
+ if (options.migrations) {
59072
+ if (!options.projectVersion) {
59073
+ throw new Error("Please specify the `projectVersion` option.");
59074
+ }
59075
+ this._migrate(options.migrations, options.projectVersion, options.beforeEachMigration);
59088
59076
  }
59089
59077
  }
59090
- if (bits > 0) {
59091
- str += ALPHABET[value << 5 - bits & 31];
59092
- }
59093
- return str;
59094
- };
59095
- var hexToBuf = (str) => {
59096
- const buf = new ArrayBuffer(str.length / 2);
59097
- const arr = new Uint8Array(buf);
59098
- for (let i = 0; i < str.length; i += 2) {
59099
- arr[i / 2] = parseInt(str.substring(i, i + 2), 16);
59100
- }
59101
- return buf;
59102
- };
59103
- var hexFromBuf = (buf) => {
59104
- const arr = new Uint8Array(buf);
59105
- let str = "";
59106
- for (let i = 0; i < arr.length; i++) {
59107
- const hex = arr[i].toString(16);
59108
- if (hex.length === 1)
59109
- str += "0";
59110
- str += hex;
59111
- }
59112
- return str.toUpperCase();
59113
- };
59114
- var latin1ToBuf = (str) => {
59115
- const buf = new ArrayBuffer(str.length);
59116
- const arr = new Uint8Array(buf);
59117
- for (let i = 0; i < str.length; i++) {
59118
- arr[i] = str.charCodeAt(i) & 255;
59119
- }
59120
- return buf;
59121
- };
59122
- var latin1FromBuf = (buf) => {
59123
- const arr = new Uint8Array(buf);
59124
- let str = "";
59125
- for (let i = 0; i < arr.length; i++) {
59126
- str += String.fromCharCode(arr[i]);
59127
- }
59128
- return str;
59129
- };
59130
- var ENCODER = globalScope.TextEncoder ? new globalScope.TextEncoder("utf-8") : null;
59131
- var DECODER = globalScope.TextDecoder ? new globalScope.TextDecoder("utf-8") : null;
59132
- var utf8ToBuf = (str) => {
59133
- if (!ENCODER) {
59134
- throw new Error("Encoding API not available");
59135
- }
59136
- return ENCODER.encode(str).buffer;
59137
- };
59138
- var utf8FromBuf = (buf) => {
59139
- if (!DECODER) {
59140
- throw new Error("Encoding API not available");
59078
+ get(key, defaultValue) {
59079
+ if (this.#options.accessPropertiesByDotNotation) {
59080
+ return this._get(key, defaultValue);
59081
+ }
59082
+ const { store } = this;
59083
+ return key in store ? store[key] : defaultValue;
59141
59084
  }
59142
- return DECODER.decode(buf);
59143
- };
59144
- var randomBytes2 = (size) => {
59145
- if (crypto3?.randomBytes) {
59146
- return crypto3.randomBytes(size).buffer;
59147
- } else {
59148
- if (!globalScope.crypto?.getRandomValues) {
59149
- throw new Error("Cryptography API not available");
59085
+ set(key, value) {
59086
+ if (typeof key !== "string" && typeof key !== "object") {
59087
+ throw new TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof key}`);
59150
59088
  }
59151
- return globalScope.crypto.getRandomValues(new Uint8Array(size)).buffer;
59089
+ if (typeof key !== "object" && value === void 0) {
59090
+ throw new TypeError("Use `delete()` to clear values");
59091
+ }
59092
+ if (this._containsReservedKey(key)) {
59093
+ throw new TypeError(`Please don't use the ${INTERNAL_KEY} key, as it's used to manage this module internal operations.`);
59094
+ }
59095
+ const { store } = this;
59096
+ const set2 = (key2, value2) => {
59097
+ checkValueType(key2, value2);
59098
+ if (this.#options.accessPropertiesByDotNotation) {
59099
+ setProperty(store, key2, value2);
59100
+ } else {
59101
+ store[key2] = value2;
59102
+ }
59103
+ };
59104
+ if (typeof key === "object") {
59105
+ const object = key;
59106
+ for (const [key2, value2] of Object.entries(object)) {
59107
+ set2(key2, value2);
59108
+ }
59109
+ } else {
59110
+ set2(key, value);
59111
+ }
59112
+ this.store = store;
59152
59113
  }
59153
- };
59154
- var Secret = class _Secret {
59155
59114
  /**
59156
- * Creates a secret key object.
59157
- * @param {Object} [config] Configuration options.
59158
- * @param {ArrayBuffer} [config.buffer=randomBytes] Secret key.
59159
- * @param {number} [config.size=20] Number of random bytes to generate, ignored if 'buffer' is provided.
59160
- */
59161
- constructor({
59162
- buffer,
59163
- size = 20
59164
- } = {}) {
59165
- this.buffer = typeof buffer === "undefined" ? randomBytes2(size) : buffer;
59115
+ Check if an item exists.
59116
+
59117
+ @param key - The key of the item to check.
59118
+ */
59119
+ has(key) {
59120
+ if (this.#options.accessPropertiesByDotNotation) {
59121
+ return hasProperty(this.store, key);
59122
+ }
59123
+ return key in this.store;
59166
59124
  }
59167
59125
  /**
59168
- * Converts a Latin-1 string to a Secret object.
59169
- * @param {string} str Latin-1 string.
59170
- * @returns {Secret} Secret object.
59171
- */
59172
- static fromLatin1(str) {
59173
- return new _Secret({
59174
- buffer: latin1ToBuf(str)
59175
- });
59126
+ Reset items to their default values, as defined by the `defaults` or `schema` option.
59127
+
59128
+ @see `clear()` to reset all items.
59129
+
59130
+ @param keys - The keys of the items to reset.
59131
+ */
59132
+ reset(...keys) {
59133
+ for (const key of keys) {
59134
+ if (isExist(this.#defaultValues[key])) {
59135
+ this.set(key, this.#defaultValues[key]);
59136
+ }
59137
+ }
59176
59138
  }
59177
- /**
59178
- * Converts an UTF-8 string to a Secret object.
59179
- * @param {string} str UTF-8 string.
59180
- * @returns {Secret} Secret object.
59181
- */
59182
- static fromUTF8(str) {
59183
- return new _Secret({
59184
- buffer: utf8ToBuf(str)
59185
- });
59139
+ delete(key) {
59140
+ const { store } = this;
59141
+ if (this.#options.accessPropertiesByDotNotation) {
59142
+ deleteProperty(store, key);
59143
+ } else {
59144
+ delete store[key];
59145
+ }
59146
+ this.store = store;
59186
59147
  }
59187
59148
  /**
59188
- * Converts a base32 string to a Secret object.
59189
- * @param {string} str Base32 string.
59190
- * @returns {Secret} Secret object.
59191
- */
59192
- static fromBase32(str) {
59193
- return new _Secret({
59194
- buffer: base32ToBuf(str)
59195
- });
59149
+ Delete all items.
59150
+
59151
+ This resets known items to their default values, if defined by the `defaults` or `schema` option.
59152
+ */
59153
+ clear() {
59154
+ this.store = createPlainObject();
59155
+ for (const key of Object.keys(this.#defaultValues)) {
59156
+ this.reset(key);
59157
+ }
59196
59158
  }
59197
59159
  /**
59198
- * Converts a hexadecimal string to a Secret object.
59199
- * @param {string} str Hexadecimal string.
59200
- * @returns {Secret} Secret object.
59201
- */
59202
- static fromHex(str) {
59203
- return new _Secret({
59204
- buffer: hexToBuf(str)
59205
- });
59160
+ Watches the given `key`, calling `callback` on any changes.
59161
+
59162
+ @param key - The key wo watch.
59163
+ @param callback - A callback function that is called on any changes. When a `key` is first set `oldValue` will be `undefined`, and when a key is deleted `newValue` will be `undefined`.
59164
+ @returns A function, that when called, will unsubscribe.
59165
+ */
59166
+ onDidChange(key, callback) {
59167
+ if (typeof key !== "string") {
59168
+ throw new TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof key}`);
59169
+ }
59170
+ if (typeof callback !== "function") {
59171
+ throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof callback}`);
59172
+ }
59173
+ return this._handleChange(() => this.get(key), callback);
59206
59174
  }
59207
59175
  /**
59208
- * Latin-1 string representation of secret key.
59209
- * @type {string}
59210
- */
59211
- get latin1() {
59212
- Object.defineProperty(this, "latin1", {
59213
- enumerable: true,
59214
- value: latin1FromBuf(this.buffer)
59215
- });
59216
- return this.latin1;
59176
+ Watches the whole config object, calling `callback` on any changes.
59177
+
59178
+ @param callback - A callback function that is called on any changes. When a `key` is first set `oldValue` will be `undefined`, and when a key is deleted `newValue` will be `undefined`.
59179
+ @returns A function, that when called, will unsubscribe.
59180
+ */
59181
+ onDidAnyChange(callback) {
59182
+ if (typeof callback !== "function") {
59183
+ throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof callback}`);
59184
+ }
59185
+ return this._handleChange(() => this.store, callback);
59217
59186
  }
59218
- /**
59219
- * UTF-8 string representation of secret key.
59220
- * @type {string}
59221
- */
59222
- get utf8() {
59223
- Object.defineProperty(this, "utf8", {
59224
- enumerable: true,
59225
- value: utf8FromBuf(this.buffer)
59226
- });
59227
- return this.utf8;
59187
+ get size() {
59188
+ return Object.keys(this.store).length;
59228
59189
  }
59229
- /**
59230
- * Base32 string representation of secret key.
59231
- * @type {string}
59232
- */
59233
- get base32() {
59234
- Object.defineProperty(this, "base32", {
59235
- enumerable: true,
59236
- value: base32FromBuf(this.buffer)
59237
- });
59238
- return this.base32;
59190
+ get store() {
59191
+ try {
59192
+ const data = import_node_fs2.default.readFileSync(this.path, this.#encryptionKey ? null : "utf8");
59193
+ const dataString = this._encryptData(data);
59194
+ const deserializedData = this._deserialize(dataString);
59195
+ this._validate(deserializedData);
59196
+ return Object.assign(createPlainObject(), deserializedData);
59197
+ } catch (error) {
59198
+ if (error?.code === "ENOENT") {
59199
+ this._ensureDirectory();
59200
+ return createPlainObject();
59201
+ }
59202
+ if (this.#options.clearInvalidConfig && error.name === "SyntaxError") {
59203
+ return createPlainObject();
59204
+ }
59205
+ throw error;
59206
+ }
59239
59207
  }
59240
- /**
59241
- * Hexadecimal string representation of secret key.
59242
- * @type {string}
59243
- */
59244
- get hex() {
59245
- Object.defineProperty(this, "hex", {
59246
- enumerable: true,
59247
- value: hexFromBuf(this.buffer)
59248
- });
59249
- return this.hex;
59208
+ set store(value) {
59209
+ this._ensureDirectory();
59210
+ this._validate(value);
59211
+ this._write(value);
59212
+ this.events.dispatchEvent(new Event("change"));
59250
59213
  }
59251
- };
59252
- var timingSafeEqual2 = (a, b) => {
59253
- if (crypto3?.timingSafeEqual) {
59254
- return crypto3.timingSafeEqual(globalScope.Buffer.from(a), globalScope.Buffer.from(b));
59255
- } else {
59256
- if (a.length !== b.length) {
59257
- throw new TypeError("Input strings must have the same length");
59214
+ *[Symbol.iterator]() {
59215
+ for (const [key, value] of Object.entries(this.store)) {
59216
+ yield [key, value];
59258
59217
  }
59259
- let i = -1;
59260
- let out = 0;
59261
- while (++i < a.length) {
59262
- out |= a.charCodeAt(i) ^ b.charCodeAt(i);
59218
+ }
59219
+ _encryptData(data) {
59220
+ if (!this.#encryptionKey) {
59221
+ return typeof data === "string" ? data : uint8ArrayToString(data);
59263
59222
  }
59264
- return out === 0;
59223
+ try {
59224
+ const initializationVector = data.slice(0, 16);
59225
+ const password = import_node_crypto2.default.pbkdf2Sync(this.#encryptionKey, initializationVector.toString(), 1e4, 32, "sha512");
59226
+ const decipher = import_node_crypto2.default.createDecipheriv(encryptionAlgorithm, password, initializationVector);
59227
+ const slice = data.slice(17);
59228
+ const dataUpdate = typeof slice === "string" ? stringToUint8Array(slice) : slice;
59229
+ return uint8ArrayToString(concatUint8Arrays([decipher.update(dataUpdate), decipher.final()]));
59230
+ } catch {
59231
+ }
59232
+ return data.toString();
59265
59233
  }
59266
- };
59267
- var HOTP = class _HOTP {
59268
- /**
59269
- * Default configuration.
59270
- * @type {{
59271
- * issuer: string,
59272
- * label: string,
59273
- * issuerInLabel: boolean,
59274
- * algorithm: string,
59275
- * digits: number,
59276
- * counter: number
59277
- * window: number
59278
- * }}
59279
- */
59280
- static get defaults() {
59281
- return {
59282
- issuer: "",
59283
- label: "OTPAuth",
59284
- issuerInLabel: true,
59285
- algorithm: "SHA1",
59286
- digits: 6,
59287
- counter: 0,
59288
- window: 1
59234
+ _handleChange(getter, callback) {
59235
+ let currentValue = getter();
59236
+ const onChange = () => {
59237
+ const oldValue = currentValue;
59238
+ const newValue = getter();
59239
+ if ((0, import_node_util2.isDeepStrictEqual)(newValue, oldValue)) {
59240
+ return;
59241
+ }
59242
+ currentValue = newValue;
59243
+ callback.call(this, newValue, oldValue);
59244
+ };
59245
+ this.events.addEventListener("change", onChange);
59246
+ return () => {
59247
+ this.events.removeEventListener("change", onChange);
59289
59248
  };
59290
59249
  }
59291
- /**
59292
- * Creates an HOTP object.
59293
- * @param {Object} [config] Configuration options.
59294
- * @param {string} [config.issuer=''] Account provider.
59295
- * @param {string} [config.label='OTPAuth'] Account label.
59296
- * @param {boolean} [config.issuerInLabel=true] Include issuer prefix in label.
59297
- * @param {Secret|string} [config.secret=Secret] Secret key.
59298
- * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
59299
- * @param {number} [config.digits=6] Token length.
59300
- * @param {number} [config.counter=0] Initial counter value.
59301
- */
59302
- constructor({
59303
- issuer = _HOTP.defaults.issuer,
59304
- label = _HOTP.defaults.label,
59305
- issuerInLabel = _HOTP.defaults.issuerInLabel,
59306
- secret = new Secret(),
59307
- algorithm = _HOTP.defaults.algorithm,
59308
- digits: digits2 = _HOTP.defaults.digits,
59309
- counter = _HOTP.defaults.counter
59310
- } = {}) {
59311
- this.issuer = issuer;
59312
- this.label = label;
59313
- this.issuerInLabel = issuerInLabel;
59314
- this.secret = typeof secret === "string" ? Secret.fromBase32(secret) : secret;
59315
- this.algorithm = algorithm.toUpperCase();
59316
- this.digits = digits2;
59317
- this.counter = counter;
59250
+ _deserialize = (value) => JSON.parse(value);
59251
+ _serialize = (value) => JSON.stringify(value, void 0, " ");
59252
+ _validate(data) {
59253
+ if (!this.#validator) {
59254
+ return;
59255
+ }
59256
+ const valid = this.#validator(data);
59257
+ if (valid || !this.#validator.errors) {
59258
+ return;
59259
+ }
59260
+ const errors = this.#validator.errors.map(({ instancePath, message = "" }) => `\`${instancePath.slice(1)}\` ${message}`);
59261
+ throw new Error("Config schema violation: " + errors.join("; "));
59318
59262
  }
59319
- /**
59320
- * Generates an HOTP token.
59321
- * @param {Object} config Configuration options.
59322
- * @param {Secret} config.secret Secret key.
59323
- * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
59324
- * @param {number} [config.digits=6] Token length.
59325
- * @param {number} [config.counter=0] Counter value.
59326
- * @returns {string} Token.
59327
- */
59328
- static generate({
59329
- secret,
59330
- algorithm = _HOTP.defaults.algorithm,
59331
- digits: digits2 = _HOTP.defaults.digits,
59332
- counter = _HOTP.defaults.counter
59333
- }) {
59334
- const digest = new Uint8Array(hmacDigest(algorithm, secret.buffer, uintToBuf(counter)));
59335
- const offset = digest[digest.byteLength - 1] & 15;
59336
- const otp = ((digest[offset] & 127) << 24 | (digest[offset + 1] & 255) << 16 | (digest[offset + 2] & 255) << 8 | digest[offset + 3] & 255) % 10 ** digits2;
59337
- return otp.toString().padStart(digits2, "0");
59263
+ _ensureDirectory() {
59264
+ import_node_fs2.default.mkdirSync(import_node_path4.default.dirname(this.path), { recursive: true });
59265
+ }
59266
+ _write(value) {
59267
+ let data = this._serialize(value);
59268
+ if (this.#encryptionKey) {
59269
+ const initializationVector = import_node_crypto2.default.randomBytes(16);
59270
+ const password = import_node_crypto2.default.pbkdf2Sync(this.#encryptionKey, initializationVector.toString(), 1e4, 32, "sha512");
59271
+ const cipher = import_node_crypto2.default.createCipheriv(encryptionAlgorithm, password, initializationVector);
59272
+ data = concatUint8Arrays([initializationVector, stringToUint8Array(":"), cipher.update(stringToUint8Array(data)), cipher.final()]);
59273
+ }
59274
+ if (import_node_process7.default.env.SNAP) {
59275
+ import_node_fs2.default.writeFileSync(this.path, data, { mode: this.#options.configFileMode });
59276
+ } else {
59277
+ try {
59278
+ writeFileSync(this.path, data, { mode: this.#options.configFileMode });
59279
+ } catch (error) {
59280
+ if (error?.code === "EXDEV") {
59281
+ import_node_fs2.default.writeFileSync(this.path, data, { mode: this.#options.configFileMode });
59282
+ return;
59283
+ }
59284
+ throw error;
59285
+ }
59286
+ }
59287
+ }
59288
+ _watch() {
59289
+ this._ensureDirectory();
59290
+ if (!import_node_fs2.default.existsSync(this.path)) {
59291
+ this._write(createPlainObject());
59292
+ }
59293
+ if (import_node_process7.default.platform === "win32") {
59294
+ import_node_fs2.default.watch(this.path, { persistent: false }, debounce_fn_default(() => {
59295
+ this.events.dispatchEvent(new Event("change"));
59296
+ }, { wait: 100 }));
59297
+ } else {
59298
+ import_node_fs2.default.watchFile(this.path, { persistent: false }, debounce_fn_default(() => {
59299
+ this.events.dispatchEvent(new Event("change"));
59300
+ }, { wait: 5e3 }));
59301
+ }
59302
+ }
59303
+ _migrate(migrations, versionToMigrate, beforeEachMigration) {
59304
+ let previousMigratedVersion = this._get(MIGRATION_KEY, "0.0.0");
59305
+ const newerVersions = Object.keys(migrations).filter((candidateVersion) => this._shouldPerformMigration(candidateVersion, previousMigratedVersion, versionToMigrate));
59306
+ let storeBackup = { ...this.store };
59307
+ for (const version of newerVersions) {
59308
+ try {
59309
+ if (beforeEachMigration) {
59310
+ beforeEachMigration(this, {
59311
+ fromVersion: previousMigratedVersion,
59312
+ toVersion: version,
59313
+ finalVersion: versionToMigrate,
59314
+ versions: newerVersions
59315
+ });
59316
+ }
59317
+ const migration = migrations[version];
59318
+ migration?.(this);
59319
+ this._set(MIGRATION_KEY, version);
59320
+ previousMigratedVersion = version;
59321
+ storeBackup = { ...this.store };
59322
+ } catch (error) {
59323
+ this.store = storeBackup;
59324
+ throw new Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${error}`);
59325
+ }
59326
+ }
59327
+ if (this._isVersionInRangeFormat(previousMigratedVersion) || !import_semver.default.eq(previousMigratedVersion, versionToMigrate)) {
59328
+ this._set(MIGRATION_KEY, versionToMigrate);
59329
+ }
59330
+ }
59331
+ _containsReservedKey(key) {
59332
+ if (typeof key === "object") {
59333
+ const firsKey = Object.keys(key)[0];
59334
+ if (firsKey === INTERNAL_KEY) {
59335
+ return true;
59336
+ }
59337
+ }
59338
+ if (typeof key !== "string") {
59339
+ return false;
59340
+ }
59341
+ if (this.#options.accessPropertiesByDotNotation) {
59342
+ if (key.startsWith(`${INTERNAL_KEY}.`)) {
59343
+ return true;
59344
+ }
59345
+ return false;
59346
+ }
59347
+ return false;
59338
59348
  }
59339
- /**
59340
- * Generates an HOTP token.
59341
- * @param {Object} [config] Configuration options.
59342
- * @param {number} [config.counter=this.counter++] Counter value.
59343
- * @returns {string} Token.
59344
- */
59345
- generate({
59346
- counter = this.counter++
59347
- } = {}) {
59348
- return _HOTP.generate({
59349
- secret: this.secret,
59350
- algorithm: this.algorithm,
59351
- digits: this.digits,
59352
- counter
59353
- });
59349
+ _isVersionInRangeFormat(version) {
59350
+ return import_semver.default.clean(version) === null;
59354
59351
  }
59355
- /**
59356
- * Validates an HOTP token.
59357
- * @param {Object} config Configuration options.
59358
- * @param {string} config.token Token value.
59359
- * @param {Secret} config.secret Secret key.
59360
- * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
59361
- * @param {number} config.digits Token length.
59362
- * @param {number} [config.counter=0] Counter value.
59363
- * @param {number} [config.window=1] Window of counter values to test.
59364
- * @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
59365
- */
59366
- static validate({
59367
- token,
59368
- secret,
59369
- algorithm,
59370
- digits: digits2,
59371
- counter = _HOTP.defaults.counter,
59372
- window: window2 = _HOTP.defaults.window
59373
- }) {
59374
- if (token.length !== digits2)
59375
- return null;
59376
- let delta = null;
59377
- for (let i = counter - window2; i <= counter + window2; ++i) {
59378
- const generatedToken = _HOTP.generate({
59379
- secret,
59380
- algorithm,
59381
- digits: digits2,
59382
- counter: i
59383
- });
59384
- if (timingSafeEqual2(token, generatedToken)) {
59385
- delta = i - counter;
59352
+ _shouldPerformMigration(candidateVersion, previousMigratedVersion, versionToMigrate) {
59353
+ if (this._isVersionInRangeFormat(candidateVersion)) {
59354
+ if (previousMigratedVersion !== "0.0.0" && import_semver.default.satisfies(previousMigratedVersion, candidateVersion)) {
59355
+ return false;
59386
59356
  }
59357
+ return import_semver.default.satisfies(versionToMigrate, candidateVersion);
59387
59358
  }
59388
- return delta;
59359
+ if (import_semver.default.lte(candidateVersion, previousMigratedVersion)) {
59360
+ return false;
59361
+ }
59362
+ if (import_semver.default.gt(candidateVersion, versionToMigrate)) {
59363
+ return false;
59364
+ }
59365
+ return true;
59389
59366
  }
59390
- /**
59391
- * Validates an HOTP token.
59392
- * @param {Object} config Configuration options.
59393
- * @param {string} config.token Token value.
59394
- * @param {number} [config.counter=this.counter] Counter value.
59395
- * @param {number} [config.window=1] Window of counter values to test.
59396
- * @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
59397
- */
59398
- validate({
59399
- token,
59400
- counter = this.counter,
59401
- window: window2
59402
- }) {
59403
- return _HOTP.validate({
59404
- token,
59405
- secret: this.secret,
59406
- algorithm: this.algorithm,
59407
- digits: this.digits,
59408
- counter,
59409
- window: window2
59410
- });
59367
+ _get(key, defaultValue) {
59368
+ return getProperty(this.store, key, defaultValue);
59411
59369
  }
59412
- /**
59413
- * Returns a Google Authenticator key URI.
59414
- * @returns {string} URI.
59415
- */
59416
- toString() {
59417
- const e = encodeURIComponent;
59418
- return `otpauth://hotp/${this.issuer.length > 0 ? this.issuerInLabel ? `${e(this.issuer)}:${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?`}secret=${e(this.secret.base32)}&algorithm=${e(this.algorithm)}&digits=${e(this.digits)}&counter=${e(this.counter)}`;
59370
+ _set(key, value) {
59371
+ const { store } = this;
59372
+ setProperty(store, key, value);
59373
+ this.store = store;
59419
59374
  }
59420
59375
  };
59421
- var TOTP = class _TOTP {
59422
- /**
59423
- * Default configuration.
59424
- * @type {{
59425
- * issuer: string,
59426
- * label: string,
59427
- * issuerInLabel: boolean,
59428
- * algorithm: string,
59429
- * digits: number,
59430
- * period: number
59431
- * window: number
59432
- * }}
59433
- */
59434
- static get defaults() {
59435
- return {
59436
- issuer: "",
59437
- label: "OTPAuth",
59438
- issuerInLabel: true,
59439
- algorithm: "SHA1",
59440
- digits: 6,
59441
- period: 30,
59442
- window: 1
59443
- };
59376
+
59377
+ // packages/sdk/db.js
59378
+ var projectName = "autho";
59379
+ var DB = class {
59380
+ constructor({ encryptionKey, name = "default", dataFolder }) {
59381
+ this.encryptionKey = encryptionKey;
59382
+ this.client = new Conf({
59383
+ projectName,
59384
+ encryptionKey,
59385
+ configName: name,
59386
+ cwd: dataFolder,
59387
+ projectSuffix: ""
59388
+ });
59444
59389
  }
59445
- /**
59446
- * Creates a TOTP object.
59447
- * @param {Object} [config] Configuration options.
59448
- * @param {string} [config.issuer=''] Account provider.
59449
- * @param {string} [config.label='OTPAuth'] Account label.
59450
- * @param {boolean} [config.issuerInLabel=true] Include issuer prefix in label.
59451
- * @param {Secret|string} [config.secret=Secret] Secret key.
59452
- * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
59453
- * @param {number} [config.digits=6] Token length.
59454
- * @param {number} [config.period=30] Token time-step duration.
59455
- */
59456
- constructor({
59457
- issuer = _TOTP.defaults.issuer,
59458
- label = _TOTP.defaults.label,
59459
- issuerInLabel = _TOTP.defaults.issuerInLabel,
59460
- secret = new Secret(),
59461
- algorithm = _TOTP.defaults.algorithm,
59462
- digits: digits2 = _TOTP.defaults.digits,
59463
- period = _TOTP.defaults.period
59464
- } = {}) {
59465
- this.issuer = issuer;
59466
- this.label = label;
59467
- this.issuerInLabel = issuerInLabel;
59468
- this.secret = typeof secret === "string" ? Secret.fromBase32(secret) : secret;
59469
- this.algorithm = algorithm.toUpperCase();
59470
- this.digits = digits2;
59471
- this.period = period;
59390
+ get(key, defaultValue) {
59391
+ return this.client.get(key, defaultValue);
59472
59392
  }
59473
- /**
59474
- * Generates a TOTP token.
59475
- * @param {Object} config Configuration options.
59476
- * @param {Secret} config.secret Secret key.
59477
- * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
59478
- * @param {number} [config.digits=6] Token length.
59479
- * @param {number} [config.period=30] Token time-step duration.
59480
- * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
59481
- * @returns {string} Token.
59482
- */
59483
- static generate({
59484
- secret,
59485
- algorithm,
59486
- digits: digits2,
59487
- period = _TOTP.defaults.period,
59488
- timestamp = Date.now()
59489
- }) {
59490
- return HOTP.generate({
59491
- secret,
59492
- algorithm,
59493
- digits: digits2,
59494
- counter: Math.floor(timestamp / 1e3 / period)
59495
- });
59393
+ set(key, value) {
59394
+ this.client.set(key, value);
59496
59395
  }
59497
- /**
59498
- * Generates a TOTP token.
59499
- * @param {Object} [config] Configuration options.
59500
- * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
59501
- * @returns {string} Token.
59502
- */
59503
- generate({
59504
- timestamp = Date.now()
59505
- } = {}) {
59506
- return _TOTP.generate({
59507
- secret: this.secret,
59508
- algorithm: this.algorithm,
59509
- digits: this.digits,
59510
- period: this.period,
59511
- timestamp
59512
- });
59396
+ clear() {
59397
+ this.client.clear();
59513
59398
  }
59514
- /**
59515
- * Validates a TOTP token.
59516
- * @param {Object} config Configuration options.
59517
- * @param {string} config.token Token value.
59518
- * @param {Secret} config.secret Secret key.
59519
- * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
59520
- * @param {number} config.digits Token length.
59521
- * @param {number} [config.period=30] Token time-step duration.
59522
- * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
59523
- * @param {number} [config.window=1] Window of counter values to test.
59524
- * @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
59525
- */
59526
- static validate({
59527
- token,
59528
- secret,
59529
- algorithm,
59530
- digits: digits2,
59531
- period = _TOTP.defaults.period,
59532
- timestamp = Date.now(),
59533
- window: window2
59534
- }) {
59535
- return HOTP.validate({
59536
- token,
59537
- secret,
59538
- algorithm,
59539
- digits: digits2,
59540
- counter: Math.floor(timestamp / 1e3 / period),
59541
- window: window2
59399
+ store() {
59400
+ return this.client.store;
59401
+ }
59402
+ path() {
59403
+ return this.client.path;
59404
+ }
59405
+ };
59406
+
59407
+ // packages/cli/app.js
59408
+ var App = class {
59409
+ constructor(options = {}) {
59410
+ this.encryptionKey = options.encryptionKey || config_default.masterPasswordHash;
59411
+ this.dataFolder = options.dataFolder || config_default.dataFolder;
59412
+ this.name = options.name || config_default.name;
59413
+ this.db = new DB({
59414
+ encryptionKey: this.encryptionKey,
59415
+ dataFolder: this.dataFolder,
59416
+ name: this.name
59542
59417
  });
59418
+ this.secrets = new Secrets(this.db);
59543
59419
  }
59544
- /**
59545
- * Validates a TOTP token.
59546
- * @param {Object} config Configuration options.
59547
- * @param {string} config.token Token value.
59548
- * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
59549
- * @param {number} [config.window=1] Window of counter values to test.
59550
- * @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
59551
- */
59552
- validate({
59553
- token,
59554
- timestamp,
59555
- window: window2
59556
- }) {
59557
- return _TOTP.validate({
59558
- token,
59559
- secret: this.secret,
59560
- algorithm: this.algorithm,
59561
- digits: this.digits,
59562
- period: this.period,
59563
- timestamp,
59564
- window: window2
59420
+ static async masterKey(masterPassword, masterPasswordHash) {
59421
+ masterPassword = masterPassword || config_default.masterPassword;
59422
+ masterPasswordHash = masterPasswordHash || config_default.masterPasswordHash;
59423
+ if (masterPasswordHash) {
59424
+ return masterPasswordHash;
59425
+ } else if (!masterPassword) {
59426
+ masterPassword = await ask({
59427
+ name: "masterPassword",
59428
+ message: "Password:",
59429
+ type: "password",
59430
+ required: true
59431
+ });
59432
+ }
59433
+ masterPasswordHash = Cipher.hash(masterPassword);
59434
+ return masterPasswordHash;
59435
+ }
59436
+ };
59437
+
59438
+ // packages/cli/wizards/getEncryptionKey.js
59439
+ var wizard = async (confirm = false) => {
59440
+ const questions = [
59441
+ {
59442
+ name: "password",
59443
+ message: "password:",
59444
+ type: "password",
59445
+ required: true
59446
+ }
59447
+ ];
59448
+ if (confirm) {
59449
+ questions.push({
59450
+ name: "confirmPassword",
59451
+ message: "confirm password:",
59452
+ type: "password",
59453
+ required: true
59565
59454
  });
59566
59455
  }
59567
- /**
59568
- * Returns a Google Authenticator key URI.
59569
- * @returns {string} URI.
59570
- */
59571
- toString() {
59572
- const e = encodeURIComponent;
59573
- return `otpauth://totp/${this.issuer.length > 0 ? this.issuerInLabel ? `${e(this.issuer)}:${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?`}secret=${e(this.secret.base32)}&algorithm=${e(this.algorithm)}&digits=${e(this.digits)}&period=${e(this.period)}`;
59456
+ const input = await prompt2(questions);
59457
+ if (input.confirmPassword && input.password !== input.confirmPassword) {
59458
+ throw new Error("Passwords do not match");
59574
59459
  }
59460
+ return Cipher.hash(input.password);
59575
59461
  };
59462
+ var getEncryptionKey_default = wizard;
59576
59463
 
59577
- // packages/sdk/otp.js
59578
- var OTP = class {
59579
- constructor(secret) {
59580
- const options = {
59581
- issuer: "Autho",
59582
- label: secret.name,
59583
- algorithm: "SHA1",
59584
- digits: 6,
59585
- period: 30,
59586
- secret: secret.value
59587
- };
59588
- this.totp = new TOTP(options);
59464
+ // packages/cli/wizards/createSecret.js
59465
+ var wizard2 = async (app) => {
59466
+ const secrets = app.secrets;
59467
+ const info = await prompt2([
59468
+ {
59469
+ name: "name",
59470
+ message: "name:",
59471
+ type: "input",
59472
+ required: true
59473
+ },
59474
+ {
59475
+ name: "type",
59476
+ message: "type:",
59477
+ type: "list",
59478
+ default: "password",
59479
+ choices: [
59480
+ { name: "Password", value: "password" },
59481
+ { name: "OTP", value: "otp" },
59482
+ { name: "Note", value: "note" }
59483
+ ],
59484
+ required: true
59485
+ },
59486
+ {
59487
+ name: "protected",
59488
+ message: "protected:",
59489
+ type: "confirm",
59490
+ default: false,
59491
+ required: true
59492
+ }
59493
+ ]);
59494
+ let newSecret = { typeOptions: {} };
59495
+ let encryptionKey = app.db.encryptionKey;
59496
+ if (info.protected) {
59497
+ encryptionKey = await getEncryptionKey_default(true);
59589
59498
  }
59590
- generate() {
59591
- return this.totp.generate();
59499
+ switch (info.type) {
59500
+ case "password":
59501
+ {
59502
+ const password = await prompt2([
59503
+ {
59504
+ name: "url",
59505
+ message: "url:",
59506
+ type: "input",
59507
+ required: false
59508
+ },
59509
+ {
59510
+ name: "username",
59511
+ message: "username:",
59512
+ type: "input",
59513
+ required: true
59514
+ },
59515
+ {
59516
+ name: "value",
59517
+ message: "password:",
59518
+ type: "password",
59519
+ required: true
59520
+ }
59521
+ ]);
59522
+ newSecret = {
59523
+ ...info,
59524
+ value: password.value,
59525
+ typeOptions: {
59526
+ username: password.username,
59527
+ url: password.url
59528
+ }
59529
+ };
59530
+ }
59531
+ break;
59532
+ case "note":
59533
+ {
59534
+ const note = await prompt2([
59535
+ {
59536
+ name: "value",
59537
+ message: "note:",
59538
+ type: "password",
59539
+ required: true
59540
+ }
59541
+ ]);
59542
+ newSecret = {
59543
+ ...info,
59544
+ value: note.value,
59545
+ typeOptions: {}
59546
+ };
59547
+ }
59548
+ break;
59549
+ case "otp":
59550
+ {
59551
+ const otp = await prompt2([
59552
+ {
59553
+ name: "username",
59554
+ message: "username:",
59555
+ type: "input",
59556
+ required: true
59557
+ },
59558
+ {
59559
+ name: "value",
59560
+ message: "value:",
59561
+ type: "password",
59562
+ required: true
59563
+ }
59564
+ ]);
59565
+ const test = await prompt2([
59566
+ {
59567
+ name: "validate",
59568
+ message: "validate:",
59569
+ type: "confirm",
59570
+ default: false,
59571
+ required: true
59572
+ }
59573
+ ]);
59574
+ if (test.validate) {
59575
+ generateOTP({
59576
+ name: info.name,
59577
+ value: otp.value
59578
+ });
59579
+ while (1) {
59580
+ const valid = await prompt2([
59581
+ {
59582
+ name: "try",
59583
+ message: "try again?",
59584
+ type: "confirm",
59585
+ default: false,
59586
+ required: true
59587
+ }
59588
+ ]);
59589
+ if (!valid.try) {
59590
+ break;
59591
+ } else {
59592
+ generateOTP({
59593
+ name: info.name,
59594
+ value: otp.value
59595
+ });
59596
+ }
59597
+ }
59598
+ }
59599
+ newSecret = {
59600
+ ...info,
59601
+ value: otp.value,
59602
+ typeOptions: {
59603
+ username: otp.username
59604
+ }
59605
+ };
59606
+ }
59607
+ break;
59592
59608
  }
59593
- validate(token, window2 = 1) {
59594
- return this.totp.validate({ token, window: window2 });
59609
+ const created = await secrets.add(newSecret, encryptionKey);
59610
+ console.log("Secret created:", created.id);
59611
+ };
59612
+ var createSecret_default = wizard2;
59613
+
59614
+ // packages/cli/wizards/getSecret.js
59615
+ var wizard3 = async (app) => {
59616
+ const existingSecrets = app.db.get("secrets", []);
59617
+ if (existingSecrets.length === 0) {
59618
+ throw new Error("No secrets found");
59619
+ }
59620
+ const choices = existingSecrets.map((secret2) => ({
59621
+ value: secret2.id,
59622
+ name: `${secret2.name} ${secret2.typeOptions.username ? `(${secret2.typeOptions.username}) ` : ""}(${secret2.id})`
59623
+ }));
59624
+ const { id: secretId } = await prompt2({
59625
+ name: "id",
59626
+ message: "Secrets:",
59627
+ type: "list",
59628
+ choices,
59629
+ required: true
59630
+ });
59631
+ const secret = await app.secrets.get(secretId);
59632
+ if (!secret) {
59633
+ throw new Error("Secret not found");
59595
59634
  }
59635
+ return secret;
59596
59636
  };
59637
+ var getSecret_default = wizard3;
59597
59638
 
59598
59639
  // packages/shared/logger.js
59599
59640
  var import_baloga = __toESM(require_baloga(), 1);
@@ -59601,7 +59642,6 @@ var logger = new import_baloga.Logger();
59601
59642
  var Logger = import_baloga.Logger;
59602
59643
 
59603
59644
  // packages/cli/bin.js
59604
- var import_readline = __toESM(require("readline"), 1);
59605
59645
  var logger2 = new Logger();
59606
59646
  var program2 = new Command();
59607
59647
  var getAuthoAbsolutePath = (path5) => {
@@ -59622,10 +59662,9 @@ var basename = (filePath) => {
59622
59662
  const folderName = import_path2.default.basename(normalizedPath);
59623
59663
  return folderName;
59624
59664
  };
59625
- function printLine(text, cursorTo = 0, moveCursor = 0) {
59626
- import_readline.default.cursorTo(process.stdout, cursorTo);
59627
- process.stdout.write(text + " ");
59628
- import_readline.default.moveCursor(process.stdout, cursorTo, moveCursor);
59665
+ function printLine(text) {
59666
+ process.stdout.write("\x1B[2K\x1B[1G");
59667
+ process.stdout.write(text);
59629
59668
  }
59630
59669
  var countDown = async (textStart, textEnd, seconds) => {
59631
59670
  return new Promise((resolve) => {
@@ -59634,24 +59673,30 @@ var countDown = async (textStart, textEnd, seconds) => {
59634
59673
  seconds--;
59635
59674
  if (seconds < 0) {
59636
59675
  printLine(textEnd);
59676
+ process.stdout.write("\n");
59637
59677
  clearInterval(interval);
59638
59678
  resolve();
59639
59679
  }
59640
59680
  }, 1e3);
59641
59681
  });
59642
59682
  };
59643
- program2.name("autho").description("Secrets manager").version("0.0.10").option("-p, --password <password>", "Master password").option("-ph, --passwordHash <passwordHash>", "Master password hash").option("-n, --name <name>", "Collection name").option(
59644
- "-data, --dataFolder <folderPath>",
59683
+ var initApp = async (args, opts) => {
59684
+ const { password, passwordHash } = { ...opts, ...args };
59685
+ args.encryptionKey = await App.masterKey(
59686
+ password,
59687
+ passwordHash
59688
+ );
59689
+ const app = new App(args);
59690
+ return app;
59691
+ };
59692
+ program2.name("autho").description("Secrets manager").version("0.0.11").option("-p, --password <password>", "Master password").option("-ph, --passwordHash <passwordHash>", "Master password hash").option("-n, --name <name>", "Collection name").option(
59693
+ "--dataFolder <folderPath>",
59645
59694
  "Folder path to store secrets db",
59646
59695
  getAuthoAbsolutePath
59647
59696
  ).action(async (args) => {
59648
59697
  try {
59649
- logger2.debug("args:", args);
59650
- args.encryptionKey = await App.masterKey(
59651
- args.password,
59652
- args.passwordHash
59653
- );
59654
- const app = new App(args);
59698
+ logger2.debug("input:", args);
59699
+ const app = await initApp(args, program2.opts());
59655
59700
  logger2.debug(`Reading data from:`, app.db.path());
59656
59701
  let choices = [
59657
59702
  { value: "create", name: "Create new secret" },
@@ -59686,10 +59731,12 @@ program2.name("autho").description("Secrets manager").version("0.0.10").option("
59686
59731
  break;
59687
59732
  case "otp":
59688
59733
  {
59689
- const otp = new OTP(readSecret);
59690
- console.log("OTP code:", otp.generate());
59691
- await countDown("Expired at: ", "The code is not longer valid, please generate new code.", 30);
59692
- process.exit(0);
59734
+ generateOTP(readSecret);
59735
+ await countDown(
59736
+ "Expired in: ",
59737
+ "The code is not longer valid, please generate new code.",
59738
+ 30
59739
+ );
59693
59740
  }
59694
59741
  break;
59695
59742
  }
@@ -59700,7 +59747,6 @@ program2.name("autho").description("Secrets manager").version("0.0.10").option("
59700
59747
  const deleteSecret = await getSecret_default(app);
59701
59748
  await app.secrets.remove(deleteSecret.id);
59702
59749
  console.log("Removed");
59703
- process.exit(0);
59704
59750
  }
59705
59751
  break;
59706
59752
  default:
@@ -59712,9 +59758,50 @@ program2.name("autho").description("Secrets manager").version("0.0.10").option("
59712
59758
  console.log(error.stack);
59713
59759
  process.exit(1);
59714
59760
  }
59761
+ process.exit(0);
59762
+ });
59763
+ program2.command("secret").description("Secret operations").option("--action <action>", "Secret action (create/list/read/delete)", "create").option("--id <id>", "Secret id").option("--decrypt", "Decrypt secret", false).action(async (args) => {
59764
+ try {
59765
+ logger2.debug(`input:`, args);
59766
+ const { id, decrypt, action } = args;
59767
+ const app = await initApp(args, program2.opts());
59768
+ logger2.debug(`Reading data from:`, app.db.path());
59769
+ switch (action) {
59770
+ case "read": {
59771
+ const selected = await app.secrets.get(id);
59772
+ if (!selected) {
59773
+ throw new Error("No secret found");
59774
+ }
59775
+ if (decrypt) {
59776
+ selected.value = Cipher.decrypt({
59777
+ ...selected,
59778
+ encryptionKey: app.encryptionKey
59779
+ });
59780
+ }
59781
+ console.log(selected);
59782
+ break;
59783
+ }
59784
+ case "delete":
59785
+ await app.secrets.remove(id);
59786
+ break;
59787
+ case "create":
59788
+ await createSecret_default(app);
59789
+ break;
59790
+ case "list":
59791
+ console.dir(app.secrets.secrets);
59792
+ break;
59793
+ default:
59794
+ throw new Error("Unknown action:", action);
59795
+ }
59796
+ } catch (error) {
59797
+ logger2.error("Something went wrong, Error: ", error.message);
59798
+ console.log(error.stack);
59799
+ process.exit(1);
59800
+ }
59801
+ process.exit(0);
59715
59802
  });
59716
59803
  program2.command("file").description("Encrypt/Decrypt file").option("-f, --filePath <filePath>", "File path").option("-en, --encrypt", "Encrypt file", false).option("-de, --decrypt", "Decrypt file", false).option("--override", "Override original file", false).action(async (args) => {
59717
- logger2.debug(`file:`, args);
59804
+ logger2.debug(`input:`, args);
59718
59805
  const { encrypt, decrypt, override } = args;
59719
59806
  let { filePath } = args;
59720
59807
  filePath = toAbsolutePath(filePath);
@@ -59739,7 +59826,7 @@ program2.command("file").description("Encrypt/Decrypt file").option("-f, --fileP
59739
59826
  });
59740
59827
  program2.command("files").description("Encrypt/Decrypt file").option("--input <inputPath>", "Folder path").option("--output <outputPath>", "Folder path", process.cwd()).option("-en, --encrypt", "Encrypt folder", false).option("-de, --decrypt", "Decrypt folder", false).action(async (args) => {
59741
59828
  try {
59742
- logger2.debug(`files:`, args);
59829
+ logger2.debug(`input:`, args);
59743
59830
  const { encrypt, decrypt } = args;
59744
59831
  let { input, output } = args;
59745
59832
  input = toAbsolutePath(input);
@@ -59773,7 +59860,7 @@ program2.command("files").description("Encrypt/Decrypt file").option("--input <i
59773
59860
  }
59774
59861
  process.exit(0);
59775
59862
  });
59776
- program2.parse();
59863
+ program2.parse(process.argv);
59777
59864
  /*! Bundled license information:
59778
59865
 
59779
59866
  safe-buffer/index.js: