@kaynooo/cli-dev 0.7.1 → 0.7.3

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 (3) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +79 -27
  3. package/package.json +3 -3
package/README.md CHANGED
@@ -26,7 +26,7 @@ Fish completes it through the bin itself: `dev __complete`, installed for every
26
26
 
27
27
  The password is read from `crypto.getRandomValues` and written as `openssl rand -hex|-base64` does, `base64url` being that base64 with `+/` swapped for `-_` and the padding dropped. `--copy` also puts the password on the clipboard through `wl-copy` (or xclip, xsel, pbcopy) and says `copied to clipboard` on stderr; without it the clipboard is left alone.
28
28
 
29
- `--bcrypt -` asks for the password masked on a terminal, or reads it from stdin, which keeps it out of the shell history. `--bcrypt` hashes at cost 10. Bun writes bcrypt hashes with the `$2b$` prefix where `htpasswd -B` writes `$2y$`: the algorithm is identical, so `dev` rewrites the prefix to `$2y$`, the one Apache, nginx and traefik basic auth all accept (`$2b$` is accepted by fewer of them). With a generated password the hash prints on stdout, the password on stderr, and it is the password that `--copy` copies, as the password it replaces did.
29
+ `--bcrypt -` asks for the password masked on a terminal, or reads it from stdin, which keeps it out of the shell history. `--bcrypt` hashes at cost 10. Bun writes bcrypt hashes with the `$2b$` prefix where `htpasswd -B` writes `$2y$`: the algorithm is identical, so `dev` rewrites the prefix to `$2y$`, the one Apache, nginx and traefik basic auth all accept (`$2b$` is accepted by fewer of them). With a generated password the hash prints on stdout, the password on stderr, and it is the password that `--copy` copies, as the password it replaces did. bcrypt reads only the first 72 bytes of a password, so `--bcrypt` refuses a longer one rather than hash a prefix of it.
30
30
 
31
31
  ## Notes
32
32
 
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
- #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
- // @bun
1
+ #!/bin/sh
2
+ // @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
3
3
  var __esm = (fn, res, err) => () => {
4
4
  if (fn)
5
5
  try {
@@ -131,6 +131,10 @@ var init_config = __esm(() => {
131
131
  });
132
132
 
133
133
  // ../kit/src/user-config.ts
134
+ import { isAbsolute, join } from "path";
135
+ function xdgFolder(value, fallback) {
136
+ return value !== undefined && isAbsolute(value) ? value : fallback;
137
+ }
134
138
  var init_user_config = () => {};
135
139
 
136
140
  // ../kit/src/theme.ts
@@ -578,10 +582,10 @@ var init_args = __esm(() => {
578
582
 
579
583
  // ../kit/src/folders.ts
580
584
  import { homedir as homedir2 } from "os";
581
- import { join as join3 } from "path";
585
+ import { join as join4 } from "path";
582
586
  import process12 from "process";
583
587
  function cacheFolder({ home = homedir2(), env = process12.env } = {}) {
584
- return env.XDG_CACHE_HOME ?? join3(home, ".cache");
588
+ return xdgFolder(env.XDG_CACHE_HOME, join4(home, ".cache"));
585
589
  }
586
590
  var SKIPPED_FOLDERS;
587
591
  var init_folders = __esm(() => {
@@ -591,9 +595,9 @@ var init_folders = __esm(() => {
591
595
 
592
596
  // ../kit/src/answers.ts
593
597
  import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
594
- import { dirname as dirname3, join as join4 } from "path";
598
+ import { dirname as dirname3, join as join5 } from "path";
595
599
  function answersFile() {
596
- return join4(cacheFolder(), "kaynooo-cli", "answers.json");
600
+ return join5(cacheFolder(), "kaynooo-cli", "answers.json");
597
601
  }
598
602
  function stored() {
599
603
  try {
@@ -1060,6 +1064,7 @@ init_format();
1060
1064
  init_format();
1061
1065
 
1062
1066
  // ../kit/src/process.ts
1067
+ var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
1063
1068
  var CLIPBOARDS = [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"], ["pbcopy"], ["clip.exe"]];
1064
1069
  async function copyText(text, which = Bun.which) {
1065
1070
  for (const [command, ...args] of CLIPBOARDS) {
@@ -1094,7 +1099,7 @@ init_format();
1094
1099
  // ../kit/src/cli.ts
1095
1100
  init_args();
1096
1101
  import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
1097
- import { dirname as dirname2, join as join2 } from "path";
1102
+ import { dirname as dirname2, join as join3 } from "path";
1098
1103
  import process11 from "process";
1099
1104
 
1100
1105
  // ../kit/src/askpass.ts
@@ -1223,14 +1228,16 @@ init_text2();
1223
1228
  // ../kit/src/usage.ts
1224
1229
  import { appendFileSync, mkdirSync } from "fs";
1225
1230
  import { homedir } from "os";
1226
- import { dirname, isAbsolute, join } from "path";
1231
+ import { dirname, join as join2 } from "path";
1227
1232
  import process10 from "process";
1228
1233
 
1229
1234
  // ../kit/src/logs.ts
1235
+ init_user_config();
1230
1236
  var DAY_MS = 24 * 60 * 60 * 1000;
1231
1237
  var CLI_FOLDER = "kaynooo-cli";
1232
1238
 
1233
1239
  // ../kit/src/usage.ts
1240
+ init_user_config();
1234
1241
  var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1235
1242
  var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1236
1243
  var LONGEST_NAME = 40;
@@ -1239,11 +1246,10 @@ function noteUsageError(message) {
1239
1246
  usageError = message;
1240
1247
  }
1241
1248
  function stateHome(env = process10.env) {
1242
- const dir = env.XDG_STATE_HOME;
1243
- return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
1249
+ return xdgFolder(env.XDG_STATE_HOME, join2(homedir(), ".local", "state"));
1244
1250
  }
1245
1251
  function usagePath(env = process10.env) {
1246
- return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
1252
+ return join2(stateHome(env), CLI_FOLDER, "usage.jsonl");
1247
1253
  }
1248
1254
  function usageRecorded(env = process10.env) {
1249
1255
  const off = env.KAYNOOO_CLI_NO_USAGE;
@@ -1314,6 +1320,10 @@ function takeOutputFlags(argv) {
1314
1320
  async function resolveSummary(summary) {
1315
1321
  return typeof summary === "string" ? summary : summary();
1316
1322
  }
1323
+ function lookup({ commands, aliases }, word) {
1324
+ const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
1325
+ return Object.hasOwn(commands, name) ? commands[name] : undefined;
1326
+ }
1317
1327
  function scopeOf(commands, extra, aliases) {
1318
1328
  return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
1319
1329
  }
@@ -1408,12 +1418,12 @@ async function dispatch(level, typed, { version, redact }) {
1408
1418
  console.log(version);
1409
1419
  return 0;
1410
1420
  }
1411
- let command = level.commands[level.aliases?.[name] ?? name];
1421
+ let command = lookup(level, name);
1412
1422
  let rest = args;
1413
1423
  let ran = name;
1414
1424
  if (command === undefined && level.lazy.length > 0) {
1415
1425
  level = await expand(level, [...level.path.slice(1), ...argv]);
1416
- command = level.commands[level.aliases?.[name] ?? name];
1426
+ command = lookup(level, name);
1417
1427
  }
1418
1428
  if (command === undefined && level.defaultCommand !== undefined) {
1419
1429
  command = level.commands[level.defaultCommand];
@@ -1493,18 +1503,19 @@ async function leafCandidates(run, words) {
1493
1503
  async function candidates(scope, defaultCommand, words, before = []) {
1494
1504
  const [word = "", ...rest] = words;
1495
1505
  const listing = rest.length === 0 && !word.startsWith("-");
1496
- let { commands, aliases } = scope;
1497
- let command = commands[aliases?.[word] ?? word];
1506
+ let { commands } = scope;
1507
+ let command = lookup(scope, word);
1498
1508
  if (listing || command === undefined) {
1499
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
1500
- command = commands[aliases?.[word] ?? word];
1509
+ const expanded = await expand(scope, [...before, ...words]);
1510
+ commands = expanded.commands;
1511
+ command = lookup(expanded, word);
1501
1512
  }
1502
1513
  if (listing) {
1503
1514
  const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1504
1515
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1505
1516
  const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1506
1517
  const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1507
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1518
+ return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
1508
1519
  }
1509
1520
  if (command === undefined) {
1510
1521
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
@@ -1537,7 +1548,7 @@ function packageVersion(entry = Bun.main) {
1537
1548
  } catch {}
1538
1549
  for (let dir = dirname2(resolved);; dir = dirname2(dir)) {
1539
1550
  try {
1540
- const { version } = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
1551
+ const { version } = JSON.parse(readFileSync2(join3(dir, "package.json"), "utf8"));
1541
1552
  if (typeof version === "string")
1542
1553
  return version;
1543
1554
  } catch {}
@@ -1569,8 +1580,7 @@ function commandPath(scope, argv) {
1569
1580
  const path = [];
1570
1581
  let level = scope;
1571
1582
  for (const word of argv.filter((each) => !each.startsWith("-"))) {
1572
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1573
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1583
+ const command = lookup(level, word);
1574
1584
  if (command === undefined)
1575
1585
  break;
1576
1586
  path.push(word);
@@ -1604,6 +1614,7 @@ init_style();
1604
1614
  init_text2();
1605
1615
  // ../kit/src/secrets.ts
1606
1616
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1617
+ var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1607
1618
  // ../kit/src/sessions.ts
1608
1619
  var {Glob } = globalThis.Bun;
1609
1620
  var SESSION_FILES = new Glob("*.json");
@@ -1680,6 +1691,38 @@ function ulid(now = Date.now(), random = randomBytes(16)) {
1680
1691
  function uuidV4() {
1681
1692
  return crypto.randomUUID();
1682
1693
  }
1694
+ function nextUlid(id) {
1695
+ const digits = [...id];
1696
+ for (let i = digits.length - 1;i >= 0; i--) {
1697
+ const value = CROCKFORD.indexOf(digits[i]) + 1;
1698
+ digits[i] = CROCKFORD[value % 32];
1699
+ if (value < 32)
1700
+ break;
1701
+ }
1702
+ return digits.join("");
1703
+ }
1704
+ function nextUuidV7(id) {
1705
+ const bits = BigInt(`0x${id.replaceAll("-", "")}`);
1706
+ const time = bits >> 80n;
1707
+ const random = (bits >> 64n & 0xFFFn) << 62n | bits & (1n << 62n) - 1n;
1708
+ const next = (time << 74n | random) + 1n;
1709
+ const nextTime = next >> 74n;
1710
+ const nextA = next >> 62n & 0xFFFn;
1711
+ const nextB = next & (1n << 62n) - 1n;
1712
+ const hex = (nextTime << 80n | 0x7n << 76n | nextA << 64n | 0x2n << 62n | nextB).toString(16).padStart(32, "0");
1713
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1714
+ }
1715
+ function monotonic(count, draw, successor, clock = Date.now) {
1716
+ const ids = [];
1717
+ let last = Number.NEGATIVE_INFINITY;
1718
+ for (let i = 0;i < count; i++) {
1719
+ const now = clock();
1720
+ const previous = ids.at(-1);
1721
+ ids.push(previous !== undefined && now <= last ? successor(previous) : draw(now));
1722
+ last = Math.max(last, now);
1723
+ }
1724
+ return ids;
1725
+ }
1683
1726
 
1684
1727
  // src/ip.ts
1685
1728
  var IP_SERVICE = "https://ipecho.net/plain";
@@ -1742,10 +1785,11 @@ var ZONELESS = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\
1742
1785
  var DATE_SPACE = /^(\d{4}-\d{2}-\d{2}) /;
1743
1786
  var WHITESPACE2 = /\s+/g;
1744
1787
  var ZONED = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*(?:Z|[+-]\d{2}(?::?\d{2})?)$/i;
1788
+ var HOUR_OFFSET = /([+-]\d{2})$/;
1745
1789
  function parseDate(text, timeZone) {
1746
1790
  const match = ZONELESS.exec(text);
1747
1791
  if (match === null) {
1748
- const ms = ZONED.test(text) ? Date.parse(text.replace(DATE_SPACE, "$1T").replace(WHITESPACE2, "")) : Number.NaN;
1792
+ const ms = ZONED.test(text) ? Date.parse(text.replace(DATE_SPACE, "$1T").replace(WHITESPACE2, "").replace(HOUR_OFFSET, "$1:00")) : Number.NaN;
1749
1793
  return Number.isNaN(ms) ? undefined : ms;
1750
1794
  }
1751
1795
  const [, year, month, day, hour = "0", minute = "0", second = "0", fraction = "0"] = match;
@@ -1781,7 +1825,11 @@ function decodeJwt(token) {
1781
1825
  function claimTimes(payload, now = Date.now(), timeZone) {
1782
1826
  return TIME_CLAIMS.flatMap((claim) => {
1783
1827
  const epoch = payload[claim];
1784
- return typeof epoch === "number" && Number.isFinite(epoch) ? [{ claim, epoch, ...zoned(epoch * 1000, timeZone), relative: relative(epoch * 1000, now) }] : [];
1828
+ if (typeof epoch !== "number" || !Number.isFinite(epoch))
1829
+ return [];
1830
+ if (Number.isNaN(new Date(epoch * 1000).getTime()))
1831
+ return [{ claim, epoch, local: "out of range", utc: "", relative: "" }];
1832
+ return [{ claim, epoch, ...zoned(epoch * 1000, timeZone), relative: relative(epoch * 1000, now) }];
1785
1833
  });
1786
1834
  }
1787
1835
 
@@ -1792,6 +1840,7 @@ function generatePassword(length, format, random = (bytes) => crypto.getRandomVa
1792
1840
  const buffer = Buffer.from(random(new Uint8Array(length)));
1793
1841
  return buffer.toString(format);
1794
1842
  }
1843
+ var BCRYPT_MAX_BYTES = 72;
1795
1844
  async function bcryptHash(password) {
1796
1845
  const hash = await Bun.password.hash(password, { algorithm: "bcrypt", cost: 10 });
1797
1846
  return `$2y$${hash.slice("$2b$".length)}`;
@@ -1900,7 +1949,7 @@ function printRows(rows) {
1900
1949
  }
1901
1950
  var PASSWORD_USAGE = `dev password [length] [format] [-b|--bcrypt [password]] [--copy]: a random password of <length> bytes (default ${DEFAULT_LENGTH}) as hex, base64 (default) or base64url
1902
1951
 
1903
- Printed on stdout, and copied with --copy. With --bcrypt the bcrypt hash (cost 10) prints, of the password given (- asks for it masked on a terminal, or reads stdin, keeping it out of the shell history) or of a generated one, which prints on stderr and is the one --copy copies. The hash has the $2y$ prefix htpasswd -B writes.`;
1952
+ Printed on stdout, and copied with --copy. With --bcrypt the bcrypt hash (cost 10) prints, of the password given (- asks for it masked on a terminal, or reads stdin, keeping it out of the shell history) or of a generated one, which prints on stderr and is the one --copy copies. The hash has the $2y$ prefix htpasswd -B writes; a password over 72 bytes, all bcrypt reads, is refused.`;
1904
1953
  var PASSWORD_EXITS = [[0, "it printed the password or hash"], [2, "a usage error"], [130, "the prompt was cancelled"]];
1905
1954
  var PASSWORD_OPTIONS = {
1906
1955
  bcrypt: { type: "string", short: "b", optional: { bare: "", accepts: STDIN_OR_VALUE }, description: "print the bcrypt hash of the password given, or of a generated one" },
@@ -1923,6 +1972,8 @@ async function password(args) {
1923
1972
  const bcrypt = values.bcrypt === "" ? undefined : values.bcrypt;
1924
1973
  const given = bcrypt === "-" ? await secretInput("the password") : bcrypt;
1925
1974
  const secret = given ?? generatePassword(bytes, format);
1975
+ if (values.bcrypt !== undefined && Buffer.byteLength(secret) > BCRYPT_MAX_BYTES)
1976
+ badUsage(`bcrypt takes a password of at most ${BCRYPT_MAX_BYTES} bytes, this one has ${Buffer.byteLength(secret)}${given === undefined ? `: ${bytes} bytes as ${format} is too long, pick a smaller <length>` : ""}`);
1926
1977
  const hash = values.bcrypt === undefined ? undefined : await bcryptHash(secret);
1927
1978
  const copied = values.copy === true && await copyText(given === undefined ? secret : hash ?? secret);
1928
1979
  if (values.json === true) {
@@ -1967,7 +2018,7 @@ ${bold("payload")}
1967
2018
  ${JSON.stringify(decoded.payload, null, 2)}`);
1968
2019
  if (claims.length > 0) {
1969
2020
  console.log("");
1970
- printRows(claims.map(({ claim, local, utc, relative }) => [claim, `${local} ${utc} ${relative}`]));
2021
+ printRows(claims.map(({ claim, local, utc, relative }) => [claim, [local, utc, relative].filter(Boolean).join(" ")]));
1971
2022
  }
1972
2023
  return 0;
1973
2024
  }
@@ -2010,7 +2061,8 @@ function uuid(args) {
2010
2061
  replaces: 'uuidgen and python -c "import uuid"',
2011
2062
  examples: ["dev uuid", ["dev uuid -n 5 --v7", "five time-ordered UUIDs"]]
2012
2063
  });
2013
- const ids = Array.from({ length: wholeNumber(values.n, "n", 1) }, () => values.v7 === true ? uuidV7() : uuidV4());
2064
+ const count = wholeNumber(values.n, "n", 1);
2065
+ const ids = values.v7 === true ? monotonic(count, (now) => uuidV7(now), nextUuidV7) : Array.from({ length: count }, uuidV4);
2014
2066
  printIds(ids, values.json === true);
2015
2067
  return 0;
2016
2068
  }
@@ -2023,7 +2075,7 @@ function ulidCommand(args) {
2023
2075
  replaces: "installing a ulid package to mint one",
2024
2076
  examples: ["dev ulid", ["dev ulid -n 3", "three ULIDs"]]
2025
2077
  });
2026
- printIds(Array.from({ length: wholeNumber(values.n, "n", 1) }, () => ulid()), values.json === true);
2078
+ printIds(monotonic(wholeNumber(values.n, "n", 1), (now) => ulid(now), nextUlid), values.json === true);
2027
2079
  return 0;
2028
2080
  }
2029
2081
  function printIds(ids, json) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-dev",
3
3
  "type": "module",
4
- "version": "0.7.1",
4
+ "version": "0.7.3",
5
5
  "description": "dev: small developer utilities in one bin: random passwords and bcrypt hashes, JWT decoding, timestamps, UUIDs and ULIDs, base64, URL parts and file hashes.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -32,10 +32,10 @@
32
32
  "registry": "https://git.kaynooo.fr/api/packages/kaynooo/npm/"
33
33
  },
34
34
  "scripts": {
35
- "build": "$npm_execpath build src/cli.ts --target bun --outdir dist",
35
+ "build": "$npm_execpath build src/cli.ts --target bun --outdir dist && $npm_execpath ../../scripts/shell-shebang.ts",
36
36
  "dev": "$npm_execpath src/cli.ts"
37
37
  },
38
38
  "devDependencies": {
39
- "@kaynooo/cli-kit": "0.45.1"
39
+ "@kaynooo/cli-kit": "0.46.4"
40
40
  }
41
41
  }