@hardfin/cli 0.1.1-dev.56 → 0.1.1-dev.57

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.
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="cb5319cf-733c-5f06-b5d8-f8f154bf4267")}catch(e){}}();
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="566d9b65-d8fb-507d-8b0e-a21deb646246")}catch(e){}}();
4
4
  import { a as defineCommand, i as GLOBAL_FLAGS, r as ExitCode, t as toInvocation } from "./scrub-BZ0egWxC.js";
5
5
  import { n as toAnswer$1, r as toCompletion, t as PATH_VALUES } from "./completion-tree-DLC6ARLR.js";
6
6
  import { createRequire } from "node:module";
@@ -1127,6 +1127,7 @@ async function request$1(options) {
1127
1127
  const url = new URL(`${options.apiUrl}${toLeadingSlash(options.path)}`);
1128
1128
  for (const [name, value] of options.query ?? []) url.searchParams.append(name, value);
1129
1129
  const headers = {
1130
+ ...options.headers,
1130
1131
  [options.credential.header]: options.credential.value,
1131
1132
  "X-API-Version": API_VERSION,
1132
1133
  Accept: options.downloads ? "*/*" : "application/json"
@@ -1558,98 +1559,120 @@ function toJSONInput(source) {
1558
1559
  return new InputFailure(`${name} does not hold JSON`);
1559
1560
  }
1560
1561
  }
1561
- const apiCommand = defineCommand({
1562
- name: "api",
1563
- summary: "Call a Hardfin API endpoint and print what it answers",
1564
- description: "Reaches every endpoint the API publishes. The path is everything after /v2, and the response envelope is printed as it arrived.",
1565
- arguments: [{
1566
- name: "path",
1567
- description: "The endpoint path, such as /customer or /item/item_V1StGXR8Z5jdHi6B",
1568
- required: true
1569
- }],
1570
- flags: [
1571
- {
1572
- name: "method",
1573
- short: "X",
1574
- description: "The HTTP method to use",
1575
- valueName: "method",
1576
- schema: z.enum([
1577
- "GET",
1578
- "POST",
1579
- "PATCH",
1580
- "PUT",
1581
- "DELETE"
1582
- ]),
1583
- defaultValue: "GET"
1584
- },
1585
- {
1586
- name: "field",
1587
- short: "f",
1588
- description: "A query parameter as key=value, repeatable",
1589
- valueName: "key=value",
1590
- repeatable: true,
1591
- schema: z.array(z.string()).default([])
1592
- },
1593
- {
1594
- name: "input",
1595
- description: "A file holding the JSON request body, or - for stdin",
1596
- valueName: "file",
1597
- schema: z.string().optional()
1598
- },
1599
- {
1600
- name: "json",
1601
- description: "Print machine-readable output, which is the default when stdout is not a terminal",
1602
- schema: z.boolean().optional()
1603
- }
1604
- ],
1605
- examples: [
1606
- {
1607
- description: "List customers",
1608
- command: "hardfin api /customer"
1609
- },
1610
- {
1611
- description: "Take the second page",
1612
- command: "hardfin api /customer -f page=2 -f limit=50"
1562
+ //#endregion
1563
+ //#region src/command/operation.ts
1564
+ /**
1565
+ * toEnum takes a value in any case, as the API does, and answers the spelling the document
1566
+ * lists, which is what a response always uses.
1567
+ */
1568
+ function toEnum(values) {
1569
+ return z.string().transform((value) => values.find((allowed) => allowed.toLowerCase() === value.toLowerCase()) ?? value).pipe(z.enum(values));
1570
+ }
1571
+ const UNSET_FLAG = {
1572
+ name: "unset",
1573
+ description: "A field to clear, named as its flag is, repeatable",
1574
+ valueName: "field",
1575
+ repeatable: true,
1576
+ schema: z.array(z.string())
1577
+ };
1578
+ const INPUT_FLAG = {
1579
+ name: "input",
1580
+ description: "A file holding the JSON request body, or - for standard input. A flag given as well replaces its field",
1581
+ valueName: "path",
1582
+ schema: z.string()
1583
+ };
1584
+ const FILE_FLAG = {
1585
+ name: "file",
1586
+ description: "The file to upload",
1587
+ valueName: "path",
1588
+ schema: z.string()
1589
+ };
1590
+ const OUTPUT_FLAG = {
1591
+ name: "output",
1592
+ description: "Where to write the file, or - for standard output",
1593
+ valueName: "path",
1594
+ schema: z.string()
1595
+ };
1596
+ const JSON_FLAG$1 = {
1597
+ name: "json",
1598
+ description: "Print machine-readable output, which is the default when stdout is not a terminal",
1599
+ schema: z.boolean()
1600
+ };
1601
+ /** defineOperation turns one endpoint into the command that calls it. */
1602
+ function defineOperation(operation) {
1603
+ const flags = [
1604
+ ...operation.queryFlags,
1605
+ ...operation.bodyFlags,
1606
+ ...operation.bodyFlags.some((flag) => flag.nullable) ? [UNSET_FLAG] : [],
1607
+ ...operation.bodyFlags.length > 0 ? [INPUT_FLAG] : [],
1608
+ ...operation.upload ? [...operation.upload.fields, FILE_FLAG] : [],
1609
+ ...operation.downloads ? [OUTPUT_FLAG] : [],
1610
+ JSON_FLAG$1
1611
+ ];
1612
+ return {
1613
+ name: operation.name,
1614
+ summary: operation.summary,
1615
+ description: operation.description ?? operation.summary,
1616
+ arguments: operation.pathParameters,
1617
+ flags,
1618
+ examples: operation.example ? [{
1619
+ description: operation.summary,
1620
+ command: operation.example
1621
+ }] : [],
1622
+ endpoint: {
1623
+ method: operation.method,
1624
+ path: operation.path
1613
1625
  },
1614
- {
1615
- description: "Change an item",
1616
- command: "hardfin api -X PATCH /item/item_V1StGXR8Z5jdHi6B --input body.json"
1617
- }
1618
- ],
1619
- run: runApi
1620
- });
1621
- async function runApi(input) {
1622
- const path = input.args[0];
1623
- if (!path) {
1624
- writeFailure("invalid_arguments", "a path is required, such as /customer", input.isJSON);
1626
+ run: (input) => runOperation(operation, input)
1627
+ };
1628
+ }
1629
+ async function runOperation(operation, input) {
1630
+ const path = toPath(operation, input.args);
1631
+ if (path === void 0) {
1632
+ writeFailure("invalid_arguments", `this command takes ${operation.pathParameters.length} argument(s), each the key of a record`, input.isJSON);
1625
1633
  return ExitCode.USAGE;
1626
1634
  }
1627
- if (!isInsideApi(input.resolved.settings.apiUrl, path)) {
1628
- writeFailure("invalid_arguments", "a path stays inside the API, so it cannot climb out of it with ..", input.isJSON);
1635
+ const given = toGivenBody$1(input.flags["input"]);
1636
+ if (given instanceof InputFailure) {
1637
+ writeFailure("invalid_input", given.message, input.isJSON);
1629
1638
  return ExitCode.USAGE;
1630
1639
  }
1631
- const query = toQuery$1(input.flags["field"]);
1632
- if (query === void 0) {
1633
- writeFailure("invalid_flag", "each --field is key=value, such as -f limit=50", input.isJSON);
1640
+ const missing = operation.bodyFlags.concat(operation.upload?.fields ?? []).filter((flag) => flag.required && input.flags[toOptionKey(flag.name)] === void 0 && !hasPath(given, flag.jsonPath));
1641
+ if (missing.length > 0) {
1642
+ writeFailure("missing_flag", `this command needs ${missing.map((flag) => `--${flag.name}`).join(", ")}`, input.isJSON);
1634
1643
  return ExitCode.USAGE;
1635
1644
  }
1636
- let body;
1637
- if (typeof input.flags["input"] === "string") {
1638
- body = toJSONInput(input.flags["input"]);
1639
- if (body instanceof InputFailure) {
1640
- writeFailure("invalid_input", body.message, input.isJSON);
1645
+ const body = toBody(operation, input.flags, given);
1646
+ if (body instanceof Error) {
1647
+ writeFailure("invalid_flag", body.message, input.isJSON);
1648
+ return ExitCode.USAGE;
1649
+ }
1650
+ if (operation.bodyFlags.length > 0 && body === void 0) {
1651
+ writeFailure("empty_request", `this command changes nothing unless a flag is given, such as ${operation.bodyFlags.slice(0, 3).map((flag) => `--${flag.name}`).join(", ")}. Run it with --help for the rest`, input.isJSON);
1652
+ return ExitCode.USAGE;
1653
+ }
1654
+ let form;
1655
+ if (operation.upload) {
1656
+ const built = await toForm$1(operation.upload, input.flags);
1657
+ if (built instanceof Error) {
1658
+ writeFailure("invalid_input", built.message, input.isJSON);
1641
1659
  return ExitCode.USAGE;
1642
1660
  }
1661
+ form = built;
1643
1662
  }
1644
1663
  try {
1645
- writeData((await request$1({
1664
+ const envelope = await request$1({
1646
1665
  apiUrl: input.resolved.settings.apiUrl,
1647
1666
  credential: await toRequestCredential(input.resolved.settings, input.resolved.sources),
1648
- method: toText(input.flags["method"] ?? "GET").toUpperCase(),
1667
+ method: operation.method,
1649
1668
  path,
1650
- query,
1651
- body
1652
- })).data);
1669
+ query: toQuery$1(operation, input.flags),
1670
+ body,
1671
+ form,
1672
+ downloads: operation.downloads
1673
+ });
1674
+ if (operation.downloads) return toWritten(envelope.data, input);
1675
+ writeData(envelope.data);
1653
1676
  return ExitCode.OK;
1654
1677
  } catch (error) {
1655
1678
  if (error instanceof NoCredential) {
@@ -1663,51 +1686,472 @@ async function runApi(input) {
1663
1686
  throw error;
1664
1687
  }
1665
1688
  }
1666
- /** isInsideApi reports whether a path, once parsed, still lands under the API's own path. */
1667
- function isInsideApi(apiUrl, path) {
1668
- try {
1669
- const base = new URL(apiUrl);
1670
- const target = new URL(`${apiUrl}${path.startsWith("/") ? "" : "/"}${path}`);
1671
- const root = base.pathname.replace(/\/+$/, "");
1672
- return target.origin === base.origin && (target.pathname === root || target.pathname.startsWith(`${root}/`));
1673
- } catch {
1674
- return false;
1689
+ /**
1690
+ * toWritten puts a downloaded file where it was asked for. A terminal is never written to,
1691
+ * because a person would otherwise have their session filled with a file's bytes.
1692
+ */
1693
+ function toWritten(download, input) {
1694
+ const asked = input.flags["output"];
1695
+ const offered = typeof asked === "string" ? void 0 : download.fileName;
1696
+ const path = typeof asked === "string" ? asked : offered === void 0 ? "-" : toLocalName(offered);
1697
+ if (path === void 0 || offered !== void 0 && existsSync(path)) {
1698
+ writeFailure("output_required", path === void 0 ? `this file is offered as ${JSON.stringify(offered)}, which is not a name to write here, so name where to write it with --output` : `${path} already exists, so name where to write this file with --output`, input.isJSON);
1699
+ return ExitCode.USAGE;
1700
+ }
1701
+ if (path === "-") {
1702
+ if (process.stdout.isTTY) {
1703
+ writeFailure("output_required", "this answer is a file, so name where to write it with --output, or send it on with a pipe", input.isJSON);
1704
+ return ExitCode.USAGE;
1705
+ }
1706
+ process.stdout.write(download.bytes);
1707
+ return ExitCode.OK;
1675
1708
  }
1709
+ writeFileSync(path, download.bytes);
1710
+ writeData({
1711
+ written: path,
1712
+ bytes: download.bytes.length,
1713
+ contentType: download.contentType
1714
+ });
1715
+ return ExitCode.OK;
1676
1716
  }
1677
- /** toQuery folds the repeated --field flags into query parameters. */
1678
- function toQuery$1(fields) {
1717
+ /** toLocalName reduces a name the API offered to one file in the working directory, or to nothing. */
1718
+ function toLocalName(offered) {
1719
+ const name = offered.split(/[\\/]/).pop() ?? "";
1720
+ return name === "" || name.startsWith(".") ? void 0 : name;
1721
+ }
1722
+ /** The arguments a URL reads as "this folder" and "the one above", and one that names nothing. */
1723
+ const NOT_A_KEY = /* @__PURE__ */ new Set([
1724
+ "",
1725
+ ".",
1726
+ ".."
1727
+ ]);
1728
+ /** toPath fills the path template from the positional arguments, in order. */
1729
+ function toPath(operation, args) {
1730
+ if (args.length !== operation.pathParameters.length || args.some((argument) => NOT_A_KEY.has(argument))) return;
1731
+ let path = operation.path;
1732
+ for (const [index, parameter] of operation.pathParameters.entries()) path = path.replace(`{${parameter.name}}`, encodeURIComponent(args[index] ?? ""));
1733
+ return path;
1734
+ }
1735
+ /** toQuery carries only the flags this invocation actually set. */
1736
+ function toQuery$1(operation, flags) {
1679
1737
  const query = new URLSearchParams();
1680
- for (const field of Array.isArray(fields) ? fields : []) {
1681
- const split = field.indexOf("=");
1682
- if (split < 1) return;
1683
- query.append(field.slice(0, split), field.slice(split + 1));
1738
+ for (const flag of operation.queryFlags) {
1739
+ const value = flags[toOptionKey(flag.name)];
1740
+ if (value === void 0) continue;
1741
+ const parsed = flag.schema.safeParse(value);
1742
+ const carried = parsed.success ? parsed.data : value;
1743
+ for (const entry of Array.isArray(carried) ? carried : [carried]) query.append(flag.queryName, toText(entry));
1684
1744
  }
1685
1745
  return query;
1686
1746
  }
1687
- //#endregion
1688
- //#region src/auth/browser.ts
1689
- /** isWSL reports whether this Linux is running under Windows. */
1690
- function isWSL() {
1691
- return existsSync("/proc/sys/fs/binfmt_misc/WSLInterop");
1747
+ /** toOptionKey names the parsed flag, which the parser reports in camel case. */
1748
+ function toOptionKey(name) {
1749
+ return name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
1692
1750
  }
1693
- /**
1694
- * toOpenable answers the address a browser may be sent to, and nothing for anything else. The
1695
- * address comes from the authorization server, which a file in the working directory can
1696
- * name, so it is parsed and written out again before any program is handed it.
1697
- */
1698
- function toOpenable(url) {
1699
- let parsed;
1751
+ /** toForm builds the file part and its fields, which an upload endpoint takes. */
1752
+ async function toForm$1(upload, flags) {
1753
+ const path = flags["file"];
1754
+ if (typeof path !== "string") return /* @__PURE__ */ new Error("this command needs --file, the file to upload");
1755
+ const form = new FormData();
1700
1756
  try {
1701
- parsed = new URL(url);
1757
+ form.append(upload.filePart, await openAsBlob(path), basename(path));
1702
1758
  } catch {
1703
- return;
1759
+ return /* @__PURE__ */ new Error(`${path} cannot be read`);
1704
1760
  }
1705
- const isLocal = parsed.protocol === "http:" && LOOPBACK_HOSTS.has(parsed.hostname);
1706
- return parsed.protocol === "https:" || isLocal ? parsed.href : void 0;
1707
- }
1708
- const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
1709
- "127.0.0.1",
1710
- "[::1]",
1761
+ for (const field of upload.fields) {
1762
+ const value = flags[toOptionKey(field.name)];
1763
+ if (value !== void 0) {
1764
+ const parsed = field.schema.safeParse(value);
1765
+ form.append(field.jsonPath[0] ?? field.name, toText(parsed.success ? parsed.data : value));
1766
+ }
1767
+ }
1768
+ return form;
1769
+ }
1770
+ /** toGivenBody reads the --input body, which a generated command takes only as a JSON object. */
1771
+ function toGivenBody$1(source) {
1772
+ if (typeof source !== "string") return;
1773
+ const read = toJSONInput(source);
1774
+ if (read instanceof InputFailure) return read;
1775
+ if (typeof read !== "object" || read === null || Array.isArray(read)) return new InputFailure(`the body in ${source === "-" ? "standard input" : source} must be a JSON object, such as {"name": "Acme"}`);
1776
+ return read;
1777
+ }
1778
+ /** hasPath reports whether a body already holds a value at a field's path. */
1779
+ function hasPath(body, path) {
1780
+ let holder = body;
1781
+ for (const name of path) {
1782
+ if (typeof holder !== "object" || holder === null || !(name in holder)) return false;
1783
+ holder = holder[name];
1784
+ }
1785
+ return true;
1786
+ }
1787
+ /** toBody builds the request body from the --input body and the flags, a flag winning over its field. */
1788
+ function toBody(operation, flags, given) {
1789
+ const body = given ? structuredClone(given) : {};
1790
+ let hasField = given !== void 0;
1791
+ for (const flag of operation.bodyFlags) {
1792
+ const value = flags[toOptionKey(flag.name)];
1793
+ if (value === void 0) continue;
1794
+ if (flag.element) {
1795
+ const elements = toElements(flag, Array.isArray(value) ? value.map(toText) : [toText(value)]);
1796
+ if (elements instanceof Error) return elements;
1797
+ set(body, flag.jsonPath, elements);
1798
+ hasField = true;
1799
+ continue;
1800
+ }
1801
+ const parsed = flag.schema.safeParse(value);
1802
+ set(body, flag.jsonPath, parsed.success ? parsed.data : value);
1803
+ hasField = true;
1804
+ }
1805
+ const cleared = toCleared(operation, flags, body);
1806
+ if (cleared instanceof Error) return cleared;
1807
+ return hasField || cleared ? body : void 0;
1808
+ }
1809
+ /** toCleared sends null for each field named by --unset, which is how a field is cleared. */
1810
+ function toCleared(operation, flags, body) {
1811
+ const named = flags["unset"];
1812
+ const names = Array.isArray(named) ? named.map(toText) : named === void 0 ? [] : [toText(named)];
1813
+ for (const name of names) {
1814
+ const flag = operation.bodyFlags.find((entry) => entry.name === name.replace(/^--/, ""));
1815
+ if (!flag) return /* @__PURE__ */ new Error(`--unset names no field called ${name}`);
1816
+ if (!flag.nullable) return /* @__PURE__ */ new Error(`--${flag.name} cannot be cleared, because the API does not accept null for it`);
1817
+ set(body, flag.jsonPath, null);
1818
+ }
1819
+ return names.length > 0;
1820
+ }
1821
+ /** toElements reads the key=value pairs a repeated flag carries for one array element. */
1822
+ function toElements(flag, values) {
1823
+ const elements = [];
1824
+ for (const value of values) {
1825
+ const element = {};
1826
+ for (const pair of value.split(",")) {
1827
+ const split = pair.indexOf("=");
1828
+ if (split < 1) return /* @__PURE__ */ new Error(`--${flag.name} takes ${flag.element?.join("=, ") ?? ""}=, such as --${flag.name} ${flag.element?.[0] ?? "field"}=value. A value cannot contain a comma`);
1829
+ const isJSON = pair[split - 1] === ":";
1830
+ const key = pair.slice(0, isJSON ? split - 1 : split).trim();
1831
+ if (flag.element && !flag.element.includes(key)) return /* @__PURE__ */ new Error(`--${flag.name} has no field ${key}. It takes ${flag.element.join(", ")}`);
1832
+ if (key in element) return /* @__PURE__ */ new Error(`--${flag.name} names ${key} twice in one element, so which one it takes is not clear`);
1833
+ const value = pair.slice(split + 1).trim();
1834
+ if (flag.elementUuids?.includes(key) && !z.uuid().safeParse(value).success) return /* @__PURE__ */ new Error(`--${flag.name} needs a UUID for ${key}, such as 3f2a9c1e-5b7d-4e8a-9c21-7d4e5f6a8b90, and ${value || "nothing"} is not one`);
1835
+ const types = flag.elementTypes?.[key];
1836
+ const typed = isJSON ? toJSONValue(value, types ?? ["string"]) : toTyped(value, types);
1837
+ if (typed === NOT_TAKEN) return /* @__PURE__ */ new Error(`--${flag.name} needs ${toNamedTypes(types ?? ["string"])} for ${key}, and ${value || "nothing"} is not one`);
1838
+ element[key] = typed;
1839
+ }
1840
+ elements.push(element);
1841
+ }
1842
+ return elements;
1843
+ }
1844
+ /** Marks text that is none of the types a field takes. */
1845
+ const NOT_TAKEN = Symbol("not taken");
1846
+ const NUMBER = /^-?\d+(\.\d+)?$/;
1847
+ /**
1848
+ * toTyped reads the text after key= as the type the document gives the field. A field that
1849
+ * takes text is sent as typed, whatever it looks like, because 36 may be a serial number. A
1850
+ * field that takes no text has only one reading, so order=2 is sent as the number.
1851
+ */
1852
+ function toTyped(text, types) {
1853
+ if (types === void 0 || types.includes("string")) return text;
1854
+ if (types.includes("null") && text === "null") return null;
1855
+ if ((types.includes("integer") || types.includes("number")) && NUMBER.test(text)) {
1856
+ const value = Number(text);
1857
+ if (types.includes("number") || Number.isInteger(value)) return value;
1858
+ }
1859
+ if (types.includes("boolean") && (text === "true" || text === "false")) return text === "true";
1860
+ return NOT_TAKEN;
1861
+ }
1862
+ /**
1863
+ * toJSONValue reads the text after key:= as JSON, and takes it when the field takes its type.
1864
+ * It is how a custom field is given the number 36 or true, where key= would send the text.
1865
+ */
1866
+ function toJSONValue(text, types) {
1867
+ let value;
1868
+ try {
1869
+ value = JSON.parse(text);
1870
+ } catch {
1871
+ return NOT_TAKEN;
1872
+ }
1873
+ const type = value === null ? "null" : typeof value;
1874
+ return (types.includes(type) || type === "number" && types.includes("integer") && Number.isInteger(value)) && type !== "object" ? value : NOT_TAKEN;
1875
+ }
1876
+ /** toNamedTypes says in words what a field takes, for the message that refuses a value. */
1877
+ function toNamedTypes(types) {
1878
+ const named = {
1879
+ integer: "a whole number",
1880
+ number: "a number",
1881
+ boolean: "true or false",
1882
+ string: "text in quotes",
1883
+ null: "null"
1884
+ };
1885
+ return types.filter((type) => type in named).map((type) => named[type]).join(" or ");
1886
+ }
1887
+ /** set writes a value at its path, building the objects a nested field needs. */
1888
+ function set(body, path, value) {
1889
+ let holder = body;
1890
+ for (const name of path.slice(0, -1)) {
1891
+ holder[name] = holder[name] ?? {};
1892
+ holder = holder[name];
1893
+ }
1894
+ holder[path[path.length - 1] ?? ""] = value;
1895
+ }
1896
+ //#endregion
1897
+ //#region src/command/api.ts
1898
+ const METHODS = [
1899
+ "GET",
1900
+ "POST",
1901
+ "PATCH",
1902
+ "PUT",
1903
+ "DELETE"
1904
+ ];
1905
+ /** The part name the API's upload endpoints take a file under. */
1906
+ const DEFAULT_FILE_PART = "data";
1907
+ /** The headers that carry the credential and the version, which the CLI sets and a caller does not. */
1908
+ const KEPT_HEADERS = /* @__PURE__ */ new Set([
1909
+ "authorization",
1910
+ "x-api-key",
1911
+ "x-api-version",
1912
+ "host",
1913
+ "content-length"
1914
+ ]);
1915
+ const apiCommand = defineCommand({
1916
+ name: "api",
1917
+ summary: "Call a Hardfin API endpoint and print what it answers",
1918
+ description: "Reaches every endpoint the API publishes, for when no generated command fits. The path is everything after /v2, and what the endpoint answered with is printed. A file is uploaded with --file and downloaded with --output.",
1919
+ arguments: [{
1920
+ name: "path",
1921
+ description: "The endpoint path, such as /customer or /item/item_V1StGXR8Z5jdHi6B",
1922
+ required: true
1923
+ }],
1924
+ flags: [
1925
+ {
1926
+ name: "method",
1927
+ short: "X",
1928
+ description: "The HTTP method to use",
1929
+ valueName: "method",
1930
+ schema: z.enum(METHODS),
1931
+ defaultValue: "GET"
1932
+ },
1933
+ {
1934
+ name: "field",
1935
+ short: "f",
1936
+ description: "A query parameter as key=value, repeatable",
1937
+ valueName: "key=value",
1938
+ repeatable: true,
1939
+ schema: z.array(z.string()).default([])
1940
+ },
1941
+ {
1942
+ name: "input",
1943
+ description: "A file holding the JSON request body, or - for stdin",
1944
+ valueName: "file",
1945
+ schema: z.string().optional()
1946
+ },
1947
+ {
1948
+ name: "file",
1949
+ description: "A file to upload as multipart, in place of a JSON body",
1950
+ valueName: "path",
1951
+ schema: z.string().optional()
1952
+ },
1953
+ {
1954
+ name: "file-part",
1955
+ description: `The name of the part the file is sent as, which is ${DEFAULT_FILE_PART} when not given`,
1956
+ valueName: "name",
1957
+ schema: z.string().optional()
1958
+ },
1959
+ {
1960
+ name: "form",
1961
+ short: "F",
1962
+ description: "A field sent beside the file as key=value, repeatable",
1963
+ valueName: "key=value",
1964
+ repeatable: true,
1965
+ schema: z.array(z.string()).default([])
1966
+ },
1967
+ {
1968
+ name: "header",
1969
+ short: "H",
1970
+ description: "A request header as Name: value, repeatable",
1971
+ valueName: "name: value",
1972
+ repeatable: true,
1973
+ schema: z.array(z.string()).default([])
1974
+ },
1975
+ {
1976
+ name: "output",
1977
+ description: "Where to write a file the endpoint answers with, or - for standard output",
1978
+ valueName: "path",
1979
+ schema: z.string().optional()
1980
+ },
1981
+ {
1982
+ name: "json",
1983
+ description: "Print machine-readable output, which is the default when stdout is not a terminal",
1984
+ schema: z.boolean().optional()
1985
+ }
1986
+ ],
1987
+ examples: [
1988
+ {
1989
+ description: "List customers",
1990
+ command: "hardfin api /customer"
1991
+ },
1992
+ {
1993
+ description: "Take the second page",
1994
+ command: "hardfin api /customer -f page=2 -f limit=50"
1995
+ },
1996
+ {
1997
+ description: "Change an item",
1998
+ command: "hardfin api -X PATCH /item/item_V1StGXR8Z5jdHi6B --input body.json"
1999
+ },
2000
+ {
2001
+ description: "Download a file",
2002
+ command: "hardfin api /file/file_7hq2mx9pkr4stz8w --output photo.jpg"
2003
+ },
2004
+ {
2005
+ description: "Upload a file, with the fields the endpoint takes beside it",
2006
+ command: "hardfin api -X POST /file --file photo.jpg -F fileType=ASSET_FILE -F forEntity=0192f7d4-3b6a-7c1e-9f2d-5a8b4c6e7d70"
2007
+ },
2008
+ {
2009
+ description: "Send a header",
2010
+ command: "hardfin api /file/file_7hq2mx9pkr4stz8w -H \"If-None-Match: \\\"abc\\\"\" --output photo.jpg"
2011
+ }
2012
+ ],
2013
+ run: runApi
2014
+ });
2015
+ async function runApi(input) {
2016
+ const path = input.args[0];
2017
+ if (!path) {
2018
+ writeFailure("invalid_arguments", "a path is required, such as /customer", input.isJSON);
2019
+ return ExitCode.USAGE;
2020
+ }
2021
+ if (!isInsideApi(input.resolved.settings.apiUrl, path)) {
2022
+ writeFailure("invalid_arguments", "a path stays inside the API, so it cannot climb out of it with ..", input.isJSON);
2023
+ return ExitCode.USAGE;
2024
+ }
2025
+ const query = toQuery(input.flags["field"]);
2026
+ if (query === void 0) {
2027
+ writeFailure("invalid_flag", "each --field is key=value, such as -f limit=50", input.isJSON);
2028
+ return ExitCode.USAGE;
2029
+ }
2030
+ const headers = toHeaders(input.flags["header"]);
2031
+ if (headers instanceof Error) {
2032
+ writeFailure("invalid_flag", headers.message, input.isJSON);
2033
+ return ExitCode.USAGE;
2034
+ }
2035
+ const method = toText(input.flags["method"] ?? "GET").toUpperCase();
2036
+ const isUpload = typeof input.flags["file"] === "string";
2037
+ if (isUpload && (typeof input.flags["input"] === "string" || method === "GET")) {
2038
+ writeFailure("invalid_flag", method === "GET" ? "--file uploads a file, so give the method with -X, such as -X POST" : "--file and --input both give the body, so give one of them", input.isJSON);
2039
+ return ExitCode.USAGE;
2040
+ }
2041
+ let body;
2042
+ if (typeof input.flags["input"] === "string") {
2043
+ body = toJSONInput(input.flags["input"]);
2044
+ if (body instanceof InputFailure) {
2045
+ writeFailure("invalid_input", body.message, input.isJSON);
2046
+ return ExitCode.USAGE;
2047
+ }
2048
+ }
2049
+ const form = isUpload ? await toForm(input.flags) : void 0;
2050
+ if (form instanceof Error) {
2051
+ writeFailure("invalid_input", form.message, input.isJSON);
2052
+ return ExitCode.USAGE;
2053
+ }
2054
+ const isDownload = typeof input.flags["output"] === "string";
2055
+ try {
2056
+ const envelope = await request$1({
2057
+ apiUrl: input.resolved.settings.apiUrl,
2058
+ credential: await toRequestCredential(input.resolved.settings, input.resolved.sources),
2059
+ method,
2060
+ path,
2061
+ query,
2062
+ body,
2063
+ form,
2064
+ headers,
2065
+ downloads: isDownload
2066
+ });
2067
+ if (isDownload) return toWritten(envelope.data, input);
2068
+ writeData(envelope.data);
2069
+ return ExitCode.OK;
2070
+ } catch (error) {
2071
+ if (error instanceof NoCredential) {
2072
+ writeFailure("not_signed_in", error.message, input.isJSON);
2073
+ return ExitCode.NOT_AUTHENTICATED;
2074
+ }
2075
+ if (error instanceof RequestFailure) {
2076
+ writeFailure(toRequestCode(error), error.message, input.isJSON, error.errors, error.requestId, error.status);
2077
+ return error.status === 401 ? ExitCode.NOT_AUTHENTICATED : ExitCode.ERROR;
2078
+ }
2079
+ throw error;
2080
+ }
2081
+ }
2082
+ /** isInsideApi reports whether a path, once parsed, still lands under the API's own path. */
2083
+ function isInsideApi(apiUrl, path) {
2084
+ try {
2085
+ const base = new URL(apiUrl);
2086
+ const target = new URL(`${apiUrl}${path.startsWith("/") ? "" : "/"}${path}`);
2087
+ const root = base.pathname.replace(/\/+$/, "");
2088
+ return target.origin === base.origin && (target.pathname === root || target.pathname.startsWith(`${root}/`));
2089
+ } catch {
2090
+ return false;
2091
+ }
2092
+ }
2093
+ /** toHeaders reads the repeated --header flags, and refuses one the CLI sets itself. */
2094
+ function toHeaders(given) {
2095
+ const headers = {};
2096
+ for (const header of Array.isArray(given) ? given : []) {
2097
+ const split = header.indexOf(":");
2098
+ const name = header.slice(0, Math.max(split, 0)).trim();
2099
+ if (split < 1 || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) return /* @__PURE__ */ new Error(`--header is Name: value, such as -H "If-None-Match: abc", and ${JSON.stringify(header)} is not`);
2100
+ if (KEPT_HEADERS.has(name.toLowerCase())) return /* @__PURE__ */ new Error(`--header cannot set ${name}, because the CLI sets it from your sign in and settings`);
2101
+ headers[name] = header.slice(split + 1).trim();
2102
+ }
2103
+ return headers;
2104
+ }
2105
+ /** toForm builds the multipart body an upload sends: the file, and the fields given beside it. */
2106
+ async function toForm(flags) {
2107
+ const path = toText(flags["file"]);
2108
+ const form = new FormData();
2109
+ try {
2110
+ form.append(toText(flags["filePart"] ?? DEFAULT_FILE_PART), await openAsBlob(path), basename(path));
2111
+ } catch {
2112
+ return /* @__PURE__ */ new Error(`${path} cannot be read`);
2113
+ }
2114
+ for (const field of Array.isArray(flags["form"]) ? flags["form"] : []) {
2115
+ const split = field.indexOf("=");
2116
+ if (split < 1) return /* @__PURE__ */ new Error(`each --form is key=value, such as -F fileType=ASSET_FILE, and ${JSON.stringify(field)} is not`);
2117
+ form.append(field.slice(0, split), field.slice(split + 1));
2118
+ }
2119
+ return form;
2120
+ }
2121
+ /** toQuery folds the repeated --field flags into query parameters. */
2122
+ function toQuery(fields) {
2123
+ const query = new URLSearchParams();
2124
+ for (const field of Array.isArray(fields) ? fields : []) {
2125
+ const split = field.indexOf("=");
2126
+ if (split < 1) return;
2127
+ query.append(field.slice(0, split), field.slice(split + 1));
2128
+ }
2129
+ return query;
2130
+ }
2131
+ //#endregion
2132
+ //#region src/auth/browser.ts
2133
+ /** isWSL reports whether this Linux is running under Windows. */
2134
+ function isWSL() {
2135
+ return existsSync("/proc/sys/fs/binfmt_misc/WSLInterop");
2136
+ }
2137
+ /**
2138
+ * toOpenable answers the address a browser may be sent to, and nothing for anything else. The
2139
+ * address comes from the authorization server, which a file in the working directory can
2140
+ * name, so it is parsed and written out again before any program is handed it.
2141
+ */
2142
+ function toOpenable(url) {
2143
+ let parsed;
2144
+ try {
2145
+ parsed = new URL(url);
2146
+ } catch {
2147
+ return;
2148
+ }
2149
+ const isLocal = parsed.protocol === "http:" && LOOPBACK_HOSTS.has(parsed.hostname);
2150
+ return parsed.protocol === "https:" || isLocal ? parsed.href : void 0;
2151
+ }
2152
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
2153
+ "127.0.0.1",
2154
+ "[::1]",
1711
2155
  "localhost"
1712
2156
  ]);
1713
2157
  /**
@@ -1933,7 +2377,7 @@ const YES_FLAG = {
1933
2377
  description: "Make the change without asking",
1934
2378
  schema: z.boolean()
1935
2379
  };
1936
- const JSON_FLAG$1 = {
2380
+ const JSON_FLAG = {
1937
2381
  name: "json",
1938
2382
  description: "Print machine-readable output, which is the default when stdout is not a terminal",
1939
2383
  schema: z.boolean()
@@ -1943,7 +2387,7 @@ const installCommand = defineCommand({
1943
2387
  summary: "Set up completion in your shell",
1944
2388
  description: "Writes the completion script under your data directory and loads it from your shell's startup file, between two marked lines. Fish loads it from its completions directory, so no startup file changes. Run it again after upgrading, so the script matches the CLI.",
1945
2389
  arguments: [SHELL_ARGUMENT],
1946
- flags: [YES_FLAG, JSON_FLAG$1],
2390
+ flags: [YES_FLAG, JSON_FLAG],
1947
2391
  examples: [{
1948
2392
  description: "Install for the shell you are using",
1949
2393
  command: "hardfin completion install"
@@ -1958,7 +2402,7 @@ const uninstallCommand = defineCommand({
1958
2402
  summary: "Remove completion from your shell",
1959
2403
  description: "Removes the script install wrote, and the marked lines it added to your shell's startup file.",
1960
2404
  arguments: [SHELL_ARGUMENT],
1961
- flags: [YES_FLAG, JSON_FLAG$1],
2405
+ flags: [YES_FLAG, JSON_FLAG],
1962
2406
  examples: [{
1963
2407
  description: "Remove completion from zsh",
1964
2408
  command: "hardfin completion uninstall zsh"
@@ -2618,811 +3062,477 @@ const HOST = "127.0.0.1";
2618
3062
  * the machine hands out, which is why the server matches a loopback redirect by everything
2619
3063
  * except its port.
2620
3064
  */
2621
- async function toListener(timeoutMs, state) {
2622
- let settle = () => {};
2623
- let fail = () => {};
2624
- const callback = new Promise((resolve, reject) => {
2625
- settle = resolve;
2626
- fail = reject;
2627
- });
2628
- const server = createServer((request, response) => {
2629
- const answered = toCallback(request);
2630
- if (answered === void 0) {
2631
- response.writeHead(404).end();
2632
- return;
2633
- }
2634
- if (!isOurs(answered, state)) {
2635
- writePage(response, 400, "Not this sign in", "This page did not come from the sign in your terminal started.");
2636
- return;
2637
- }
2638
- writeOutcome(response, answered);
2639
- settle(answered);
2640
- });
2641
- await new Promise((resolve, reject) => {
2642
- server.once("error", reject);
2643
- server.listen(0, HOST, resolve);
2644
- });
2645
- const timer = setTimeout(() => {
2646
- fail(new TimedOut("the browser did not come back in time"));
2647
- close(server, timer);
2648
- }, timeoutMs);
2649
- return {
2650
- redirectUri: `http://${HOST}:${server.address().port}${CALLBACK_PATH}`,
2651
- callback: callback.finally(() => {
2652
- close(server, timer);
2653
- }),
2654
- close: () => {
2655
- close(server, timer);
2656
- }
2657
- };
2658
- }
2659
- function toCallback(request) {
2660
- const url = new URL(request.url ?? "/", `http://${HOST}`);
2661
- if (url.pathname !== CALLBACK_PATH) return;
2662
- return {
2663
- source: "listener",
2664
- code: url.searchParams.get("code") ?? void 0,
2665
- state: url.searchParams.get("state") ?? void 0,
2666
- issuer: url.searchParams.get("iss") ?? void 0,
2667
- error: url.searchParams.get("error") ?? void 0,
2668
- errorDescription: url.searchParams.get("error_description") ?? void 0
2669
- };
2670
- }
2671
- /**
2672
- * isOurs answers whether a response belongs to this sign in. A refusal with no state at all
2673
- * is still taken, because not every authorization server sends the state back with one.
2674
- */
2675
- function isOurs(callback, state) {
2676
- if (callback.state !== void 0) return callback.state === state;
2677
- return callback.code === void 0 && callback.error !== void 0;
2678
- }
2679
- function writeOutcome(response, callback) {
2680
- if (!callback.error) {
2681
- writePage(response, 200, "Signed in", "You can close this tab and return to your terminal.");
2682
- return;
2683
- }
2684
- writePage(response, 200, "Sign in refused", `${callback.error}${callback.errorDescription ? `: ${callback.errorDescription}` : ""}`);
2685
- }
2686
- /** toEscaped makes text safe to put in a page, because the words of a refusal come from the URL. */
2687
- function toEscaped(text) {
2688
- return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
2689
- }
2690
- function writePage(response, status, heading, words) {
2691
- const title = toEscaped(heading);
2692
- const detail = toEscaped(words);
2693
- response.writeHead(status, {
2694
- "Content-Type": "text/html; charset=utf-8",
2695
- "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
2696
- "X-Content-Type-Options": "nosniff"
2697
- }).end(`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title></head><body style="font-family: system-ui, sans-serif; padding: 3rem; max-width: 34rem"><h1 style="font-size: 1.25rem">${title}</h1><p>${detail}</p></body></html>`);
2698
- }
2699
- function close(server, timer) {
2700
- clearTimeout(timer);
2701
- server.close();
2702
- server.closeAllConnections();
2703
- }
2704
- //#endregion
2705
- //#region src/auth/pkce.ts
2706
- /** toPkce makes a fresh verifier and the challenge derived from it. */
2707
- function toPkce() {
2708
- const verifier = toUrlSafe(randomBytes(32));
2709
- return {
2710
- verifier,
2711
- challenge: toUrlSafe(createHash("sha256").update(verifier).digest()),
2712
- method: "S256"
2713
- };
2714
- }
2715
- /** toState makes the value that ties a callback to the request that started it. */
2716
- function toState() {
2717
- return toUrlSafe(randomBytes(16));
2718
- }
2719
- function toUrlSafe(bytes) {
2720
- return bytes.toString("base64url");
2721
- }
2722
- //#endregion
2723
- //#region src/auth/clipboard.ts
2724
- /** toClipboardCommand names how this host takes text onto the clipboard. */
2725
- function toClipboardCommand() {
2726
- if (process.platform === "darwin") return ["pbcopy", []];
2727
- if (process.platform === "win32") return ["clip", []];
2728
- if (existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")) return ["clip.exe", []];
2729
- if (process.env["WAYLAND_DISPLAY"]) return ["wl-copy", []];
2730
- return ["xclip", ["-selection", "clipboard"]];
2731
- }
2732
- /** copyToClipboard puts text on the clipboard, and reports whether anything took it. */
2733
- function copyToClipboard(text, copy = spawnSync) {
2734
- const command = toClipboardCommand();
2735
- if (!command) return false;
2736
- const [name, args] = command;
2737
- const result = copy(name, args, { input: text });
2738
- return result.error === void 0 && result.status === 0;
2739
- }
2740
- //#endregion
2741
- //#region src/auth/prompt.ts
2742
- const CTRL_C = "";
2743
- const CTRL_BACKSLASH = "";
2744
- const BACKSPACE = "";
2745
- /**
2746
- * toPastedCallback reads what a person pasted. A browser that could not reach the listener
2747
- * leaves the whole redirect in the address bar, and a page that shows the code leaves
2748
- * `code#state`, so both are accepted alongside a bare code.
2749
- */
2750
- function toPastedCallback(pasted) {
2751
- const value = pasted.trim();
2752
- if (value.startsWith("http://") || value.startsWith("https://")) {
2753
- const url = new URL(value);
2754
- return {
2755
- source: "pasted",
2756
- code: url.searchParams.get("code") ?? void 0,
2757
- state: url.searchParams.get("state") ?? void 0,
2758
- issuer: url.searchParams.get("iss") ?? void 0,
2759
- error: url.searchParams.get("error") ?? void 0,
2760
- errorDescription: url.searchParams.get("error_description") ?? void 0
2761
- };
2762
- }
2763
- const [code, state] = value.split("#");
2764
- return {
2765
- source: "pasted",
2766
- code: code || void 0,
2767
- state: state || void 0
2768
- };
2769
- }
2770
- /**
2771
- * toPrompt watches the keyboard while the browser is away. Pressing c copies the URL, and
2772
- * pasting a code finishes the sign in on a machine whose browser cannot reach this listener.
2773
- */
2774
- function toPrompt(url, input = process.stdin, copy = copyToClipboard) {
3065
+ async function toListener(timeoutMs, state) {
2775
3066
  let settle = () => {};
2776
3067
  let fail = () => {};
2777
- const pasted = new Promise((resolve, reject) => {
3068
+ const callback = new Promise((resolve, reject) => {
2778
3069
  settle = resolve;
2779
3070
  fail = reject;
2780
3071
  });
2781
- pasted.catch(() => {});
2782
- if (!input.isTTY) return {
2783
- pasted,
2784
- close: () => {}
2785
- };
2786
- let typed = "";
2787
- const onData = (chunk) => {
2788
- const isKeystroke = chunk.length === 1;
2789
- for (const character of chunk) {
2790
- if (character === CTRL_C || character === CTRL_BACKSLASH) {
2791
- fail(new Interrupted());
2792
- return;
2793
- }
2794
- if (character === "\r" || character === "\n") {
2795
- if (typed.trim() === "") continue;
2796
- process.stderr.write("\n");
2797
- settle(toPastedCallback(typed));
2798
- return;
2799
- }
2800
- if (character === BACKSPACE) {
2801
- typed = typed.slice(0, -1);
2802
- process.stderr.write("\b \b");
2803
- continue;
2804
- }
2805
- if (isKeystroke && (character === "c" || character === "C") && typed === "") {
2806
- process.stderr.write(copy(url) ? "Copied the URL to your clipboard\n" : "Nothing on this host takes a clipboard\n");
2807
- continue;
2808
- }
2809
- if (character < " ") continue;
2810
- typed += character;
2811
- process.stderr.write(character);
3072
+ const server = createServer((request, response) => {
3073
+ const answered = toCallback(request);
3074
+ if (answered === void 0) {
3075
+ response.writeHead(404).end();
3076
+ return;
3077
+ }
3078
+ if (!isOurs(answered, state)) {
3079
+ writePage(response, 400, "Not this sign in", "This page did not come from the sign in your terminal started.");
3080
+ return;
3081
+ }
3082
+ writeOutcome(response, answered);
3083
+ settle(answered);
3084
+ });
3085
+ await new Promise((resolve, reject) => {
3086
+ server.once("error", reject);
3087
+ server.listen(0, HOST, resolve);
3088
+ });
3089
+ const timer = setTimeout(() => {
3090
+ fail(new TimedOut("the browser did not come back in time"));
3091
+ close(server, timer);
3092
+ }, timeoutMs);
3093
+ return {
3094
+ redirectUri: `http://${HOST}:${server.address().port}${CALLBACK_PATH}`,
3095
+ callback: callback.finally(() => {
3096
+ close(server, timer);
3097
+ }),
3098
+ close: () => {
3099
+ close(server, timer);
2812
3100
  }
2813
3101
  };
2814
- input.setRawMode(true);
2815
- input.setEncoding("utf8");
2816
- input.resume();
2817
- input.on("data", onData);
2818
- const close = () => {
2819
- input.off("data", onData);
2820
- input.setRawMode(false);
2821
- input.pause();
2822
- };
3102
+ }
3103
+ function toCallback(request) {
3104
+ const url = new URL(request.url ?? "/", `http://${HOST}`);
3105
+ if (url.pathname !== CALLBACK_PATH) return;
2823
3106
  return {
2824
- pasted: pasted.finally(close),
2825
- close
3107
+ source: "listener",
3108
+ code: url.searchParams.get("code") ?? void 0,
3109
+ state: url.searchParams.get("state") ?? void 0,
3110
+ issuer: url.searchParams.get("iss") ?? void 0,
3111
+ error: url.searchParams.get("error") ?? void 0,
3112
+ errorDescription: url.searchParams.get("error_description") ?? void 0
2826
3113
  };
2827
3114
  }
2828
- //#endregion
2829
- //#region src/command/login.ts
2830
- /** The scopes a sign-in asks for, with offline access so a refresh token comes back. */
2831
- const DEFAULT_SCOPES = "hardfin:read hardfin:write offline_access";
2832
- /** The scopes a sign in asks for when it must not be able to change anything. */
2833
- const READ_ONLY_SCOPES = "hardfin:read offline_access";
2834
- const WAIT_MS = 3e5;
2835
- const loginCommand = defineCommand({
2836
- name: "login",
2837
- summary: "Sign in to Hardfin through a browser",
2838
- description: "Opens the browser to approve this CLI, then keeps the refresh token in the OS keyring, or in a file with owner-only permissions where there is no keyring. Access tokens are never written anywhere.",
2839
- arguments: [],
2840
- flags: [
2841
- {
2842
- name: "read-only",
2843
- description: "Ask for read access alone, so nothing run with this sign in can change a record",
2844
- schema: z.boolean()
2845
- },
2846
- {
2847
- name: "scope",
2848
- description: `The scopes to ask for, separated by spaces, which are ${DEFAULT_SCOPES} when not given`,
2849
- valueName: "scopes",
2850
- schema: z.string()
2851
- },
2852
- {
2853
- name: "no-browser",
2854
- description: "Print the URL instead of opening it",
2855
- schema: z.boolean()
2856
- },
2857
- {
2858
- name: "device",
2859
- description: "Approve on another machine, by typing a code, with no listener on this one",
2860
- schema: z.boolean()
2861
- },
2862
- {
2863
- name: "json",
2864
- description: "Print machine-readable output, which is the default when stdout is not a terminal",
2865
- schema: z.boolean()
2866
- }
2867
- ],
2868
- examples: [
2869
- {
2870
- description: "Sign in",
2871
- command: "hardfin login"
2872
- },
2873
- {
2874
- description: "Sign in so that nothing can be changed",
2875
- command: "hardfin login --read-only"
2876
- },
2877
- {
2878
- description: "Sign in over SSH, opening the URL yourself",
2879
- command: "hardfin login --no-browser"
2880
- },
2881
- {
2882
- description: "Approve from your phone or another machine",
2883
- command: "hardfin login --device"
2884
- }
2885
- ],
2886
- run: runLogin
2887
- });
2888
- async function runLogin(input) {
2889
- const settings = input.resolved.settings;
2890
- const isReadOnly = input.flags["readOnly"] === true;
2891
- if (isReadOnly && input.flags["scope"] !== void 0) {
2892
- writeFailure("invalid_flag", "--read-only and --scope both name the scopes to ask for, so give one of them", input.isJSON);
2893
- return ExitCode.USAGE;
2894
- }
2895
- try {
2896
- const clientId = settings.clientId;
2897
- const metadata = await toMetadata(settings.issuerUrl);
2898
- const scope = isReadOnly ? READ_ONLY_SCOPES : toText(input.flags["scope"] ?? DEFAULT_SCOPES);
2899
- if (input.flags["device"] === true) return await runDeviceLogin(input, metadata, scope);
2900
- const state = toState();
2901
- const listener = await toListener(WAIT_MS, state);
2902
- const pkce = toPkce();
2903
- const url = toAuthorizationUrl(metadata.authorization_endpoint, {
2904
- clientId,
2905
- redirectUri: listener.redirectUri,
2906
- scope,
2907
- state,
2908
- challenge: pkce.challenge
2909
- });
2910
- const opened = input.flags["noBrowser"] !== true && !process.env["HARDFIN_NO_BROWSER"] && openBrowser(url);
2911
- if (input.isJSON) writeEvent({
2912
- event: "sign_in_url",
2913
- url,
2914
- browserOpened: opened,
2915
- waitSeconds: WAIT_MS / 1e3
2916
- });
2917
- else process.stderr.write(opened ? `Opening your browser to sign in. If it did not open:\n\n${url}\n\n` : `Open this URL to sign in:\n\n${url}\n\n`);
2918
- const prompt = toPrompt(url);
2919
- if (process.stdin.isTTY) process.stderr.write("Press c to copy the URL, or paste the code or redirect URL here: ");
2920
- let callback;
2921
- try {
2922
- callback = await Promise.race([listener.callback, prompt.pasted]);
2923
- } finally {
2924
- listener.close();
2925
- prompt.close();
2926
- }
2927
- if (!input.isJSON) process.stderr.write(callback.error ? "\n" : "\nApproved, finishing the sign in\n");
2928
- if (callback.error) {
2929
- writeFailure("sign_in_failed", `sign in was refused: ${callback.error}${callback.errorDescription ? `, ${callback.errorDescription}` : ""}`, input.isJSON);
2930
- return ExitCode.ERROR;
2931
- }
2932
- if (callback.source === "listener" ? callback.state !== state : callback.state !== void 0 && callback.state !== state) {
2933
- writeFailure("sign_in_failed", "the browser came back with a state this sign in did not send", input.isJSON);
2934
- return ExitCode.ERROR;
2935
- }
2936
- if (callback.issuer !== void 0 && callback.issuer.replace(/\/+$/, "") !== metadata.issuer.replace(/\/+$/, "")) {
2937
- writeFailure("sign_in_failed", `the browser came back from ${callback.issuer}, which is not ${metadata.issuer}`, input.isJSON);
2938
- return ExitCode.ERROR;
2939
- }
2940
- if (!callback.code) {
2941
- writeFailure("sign_in_failed", "the browser came back without an authorization code", input.isJSON);
2942
- return ExitCode.ERROR;
2943
- }
2944
- return await toSignedIn(input, metadata, await toTokensFromCode(metadata.token_endpoint, clientId, callback.code, listener.redirectUri, pkce));
2945
- } catch (error) {
2946
- if (error instanceof DiscoveryFailure || error instanceof GrantFailure || error instanceof SignInStopped) {
2947
- writeFailure("sign_in_failed", error.message, input.isJSON);
2948
- return ExitCode.ERROR;
2949
- }
2950
- throw error;
2951
- }
3115
+ /**
3116
+ * isOurs answers whether a response belongs to this sign in. A refusal with no state at all
3117
+ * is still taken, because not every authorization server sends the state back with one.
3118
+ */
3119
+ function isOurs(callback, state) {
3120
+ if (callback.state !== void 0) return callback.state === state;
3121
+ return callback.code === void 0 && callback.error !== void 0;
2952
3122
  }
2953
- /** runDeviceLogin waits while the person approves on a machine that has a browser. */
2954
- async function runDeviceLogin(input, metadata, scope) {
2955
- const settings = input.resolved.settings;
2956
- if (!metadata.device_authorization_endpoint) {
2957
- writeFailure("sign_in_failed", `${metadata.issuer} does not offer the device grant, so sign in without --device`, input.isJSON);
2958
- return ExitCode.ERROR;
2959
- }
2960
- const device = await toDeviceAuthorization(metadata.device_authorization_endpoint, settings.clientId, scope);
2961
- const url = device.verificationUriComplete ?? device.verificationUri;
2962
- const opened = input.flags["noBrowser"] !== true && !process.env["HARDFIN_NO_BROWSER"] && openBrowser(url);
2963
- if (input.isJSON) writeEvent({
2964
- event: "device_code",
2965
- userCode: device.userCode,
2966
- verificationUri: device.verificationUri,
2967
- url,
2968
- browserOpened: opened,
2969
- waitSeconds: Math.max(0, Math.round((device.expiresAt - Date.now()) / 1e3))
2970
- });
2971
- else process.stderr.write([
2972
- "",
2973
- ` Code ${toPrintable(device.userCode)}`,
2974
- ` At ${toPrintable(device.verificationUri)}`,
2975
- "",
2976
- opened ? "Opened your browser there. Waiting for approval\n" : "Open that page on any machine, and enter the code. Waiting for approval\n"
2977
- ].join("\n"));
2978
- const prompt = toPrompt(url);
2979
- try {
2980
- return await toSignedIn(input, metadata, await toDeviceTokens(toTokensFromDevice(metadata.token_endpoint, settings.clientId, device), prompt.pasted));
2981
- } finally {
2982
- prompt.close();
3123
+ function writeOutcome(response, callback) {
3124
+ if (!callback.error) {
3125
+ writePage(response, 200, "Signed in", "You can close this tab and return to your terminal.");
3126
+ return;
2983
3127
  }
3128
+ writePage(response, 200, "Sign in refused", `${callback.error}${callback.errorDescription ? `: ${callback.errorDescription}` : ""}`);
3129
+ }
3130
+ /** toEscaped makes text safe to put in a page, because the words of a refusal come from the URL. */
3131
+ function toEscaped(text) {
3132
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
3133
+ }
3134
+ function writePage(response, status, heading, words) {
3135
+ const title = toEscaped(heading);
3136
+ const detail = toEscaped(words);
3137
+ response.writeHead(status, {
3138
+ "Content-Type": "text/html; charset=utf-8",
3139
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
3140
+ "X-Content-Type-Options": "nosniff"
3141
+ }).end(`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title></head><body style="font-family: system-ui, sans-serif; padding: 3rem; max-width: 34rem"><h1 style="font-size: 1.25rem">${title}</h1><p>${detail}</p></body></html>`);
2984
3142
  }
2985
- /**
2986
- * toDeviceTokens waits for the approval, or for the keyboard. Ctrl-C arrives as an Interrupted
2987
- * and stops quietly. Text followed by Enter means the person typed the code here, where it
2988
- * does nothing, so they are told where it goes instead.
2989
- */
2990
- async function toDeviceTokens(approved, typed) {
2991
- return await Promise.race([approved, typed.then(() => {
2992
- throw new SignInStopped("Sign in stopped. The code goes on the page in your browser, not here. Run hardfin login to try again.");
2993
- })]);
3143
+ function close(server, timer) {
3144
+ clearTimeout(timer);
3145
+ server.close();
3146
+ server.closeAllConnections();
2994
3147
  }
2995
- /** toSignedIn stores what a sign in issued, whichever flow issued it. */
2996
- async function toSignedIn(input, metadata, tokens) {
2997
- const refreshToken = tokens.refreshToken;
2998
- if (!refreshToken) {
2999
- writeFailure("sign_in_failed", "the authorization server issued no refresh token, so this sign in cannot be kept", input.isJSON);
3000
- return ExitCode.ERROR;
3001
- }
3002
- const scopes = toGrantedScopes(tokens);
3003
- const backend = await withLock(() => keep$1(input.resolved.settings.issuerUrl, refreshToken, tokens.refreshExpiresAt, scopes));
3004
- if (input.isJSON) {
3005
- writeData({
3006
- signedIn: true,
3007
- issuer: metadata.issuer,
3008
- scope: tokens.scope ?? null,
3009
- scopes: scopes ?? null,
3010
- canWrite: toCanWrite(scopes),
3011
- storedIn: backend
3012
- });
3013
- return ExitCode.OK;
3014
- }
3015
- const stored = backend === "keyring" ? "your OS keyring" : toCredentialPath();
3016
- writeData([
3017
- `Signed in to ${metadata.issuer}`,
3018
- `Scope ${scopes?.join(" ") ?? tokens.scope ?? "as granted"}`,
3019
- ...toCanWrite(scopes) === false ? ["Access read-only, so a command that changes a record will be refused"] : [],
3020
- `Stored in ${stored}`,
3021
- "",
3022
- "Run hardfin status to see what this CLI is using",
3023
- ...isInstalled() ? [] : ["Run hardfin completion install to complete commands with Tab"]
3024
- ].join("\n"));
3025
- return ExitCode.OK;
3148
+ //#endregion
3149
+ //#region src/auth/pkce.ts
3150
+ /** toPkce makes a fresh verifier and the challenge derived from it. */
3151
+ function toPkce() {
3152
+ const verifier = toUrlSafe(randomBytes(32));
3153
+ return {
3154
+ verifier,
3155
+ challenge: toUrlSafe(createHash("sha256").update(verifier).digest()),
3156
+ method: "S256"
3157
+ };
3026
3158
  }
3027
- /** writeEvent tells a program what a sign in is waiting on, as one line of JSON on stderr. */
3028
- function writeEvent(event) {
3029
- process.stderr.write(`${JSON.stringify(event)}\n`);
3159
+ /** toState makes the value that ties a callback to the request that started it. */
3160
+ function toState() {
3161
+ return toUrlSafe(randomBytes(16));
3030
3162
  }
3031
- /** toAuthorizationUrl builds the URL the person approves this CLI at. */
3032
- function toAuthorizationUrl(endpoint, request) {
3033
- const url = new URL(endpoint);
3034
- url.searchParams.set("response_type", "code");
3035
- url.searchParams.set("client_id", request.clientId);
3036
- url.searchParams.set("redirect_uri", request.redirectUri);
3037
- url.searchParams.set("scope", request.scope);
3038
- url.searchParams.set("state", request.state);
3039
- url.searchParams.set("code_challenge", request.challenge);
3040
- url.searchParams.set("code_challenge_method", "S256");
3041
- return url.toString();
3163
+ function toUrlSafe(bytes) {
3164
+ return bytes.toString("base64url");
3042
3165
  }
3043
3166
  //#endregion
3044
- //#region src/command/logout.ts
3045
- const logoutCommand = defineCommand({
3046
- name: "logout",
3047
- summary: "Sign out, and tell Hardfin to forget this machine",
3048
- description: "Removes the stored refresh token and asks the authorization server to revoke it, so a copy taken from this machine stops working.",
3049
- arguments: [],
3050
- flags: [{
3051
- name: "json",
3052
- description: "Print machine-readable output, which is the default when stdout is not a terminal",
3053
- schema: z.boolean()
3054
- }],
3055
- examples: [{
3056
- description: "Sign out",
3057
- command: "hardfin logout"
3058
- }],
3059
- run: runLogout
3060
- });
3061
- async function runLogout(input) {
3062
- const settings = input.resolved.settings;
3063
- const stored = toCredential(settings.issuerUrl);
3064
- if (!stored) {
3065
- writeData({
3066
- signedOut: false,
3067
- issuer: settings.issuerUrl,
3068
- reason: "no sign in was stored"
3069
- });
3070
- return ExitCode.OK;
3071
- }
3072
- let revoked = false;
3073
- try {
3074
- const metadata = await toMetadata(settings.issuerUrl);
3075
- if (metadata.revocation_endpoint) {
3076
- await revoke(metadata.revocation_endpoint, settings.clientId, stored.refreshToken);
3077
- revoked = true;
3078
- }
3079
- } catch {
3080
- revoked = false;
3081
- }
3082
- await withLock(() => {
3083
- forget(settings.issuerUrl);
3084
- });
3085
- forgetHeldTokens();
3086
- writeData({
3087
- signedOut: true,
3088
- issuer: settings.issuerUrl,
3089
- revoked
3090
- });
3091
- return ExitCode.OK;
3167
+ //#region src/auth/clipboard.ts
3168
+ /** toClipboardCommand names how this host takes text onto the clipboard. */
3169
+ function toClipboardCommand() {
3170
+ if (process.platform === "darwin") return ["pbcopy", []];
3171
+ if (process.platform === "win32") return ["clip", []];
3172
+ if (existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")) return ["clip.exe", []];
3173
+ if (process.env["WAYLAND_DISPLAY"]) return ["wl-copy", []];
3174
+ return ["xclip", ["-selection", "clipboard"]];
3175
+ }
3176
+ /** copyToClipboard puts text on the clipboard, and reports whether anything took it. */
3177
+ function copyToClipboard(text, copy = spawnSync) {
3178
+ const command = toClipboardCommand();
3179
+ if (!command) return false;
3180
+ const [name, args] = command;
3181
+ const result = copy(name, args, { input: text });
3182
+ return result.error === void 0 && result.status === 0;
3092
3183
  }
3093
3184
  //#endregion
3094
- //#region src/command/operation.ts
3185
+ //#region src/auth/prompt.ts
3186
+ const CTRL_C = "";
3187
+ const CTRL_BACKSLASH = "";
3188
+ const BACKSPACE = "";
3095
3189
  /**
3096
- * toEnum takes a value in any case, as the API does, and answers the spelling the document
3097
- * lists, which is what a response always uses.
3190
+ * toPastedCallback reads what a person pasted. A browser that could not reach the listener
3191
+ * leaves the whole redirect in the address bar, and a page that shows the code leaves
3192
+ * `code#state`, so both are accepted alongside a bare code.
3098
3193
  */
3099
- function toEnum(values) {
3100
- return z.string().transform((value) => values.find((allowed) => allowed.toLowerCase() === value.toLowerCase()) ?? value).pipe(z.enum(values));
3194
+ function toPastedCallback(pasted) {
3195
+ const value = pasted.trim();
3196
+ if (value.startsWith("http://") || value.startsWith("https://")) {
3197
+ const url = new URL(value);
3198
+ return {
3199
+ source: "pasted",
3200
+ code: url.searchParams.get("code") ?? void 0,
3201
+ state: url.searchParams.get("state") ?? void 0,
3202
+ issuer: url.searchParams.get("iss") ?? void 0,
3203
+ error: url.searchParams.get("error") ?? void 0,
3204
+ errorDescription: url.searchParams.get("error_description") ?? void 0
3205
+ };
3206
+ }
3207
+ const [code, state] = value.split("#");
3208
+ return {
3209
+ source: "pasted",
3210
+ code: code || void 0,
3211
+ state: state || void 0
3212
+ };
3101
3213
  }
3102
- const UNSET_FLAG = {
3103
- name: "unset",
3104
- description: "A field to clear, named as its flag is, repeatable",
3105
- valueName: "field",
3106
- repeatable: true,
3107
- schema: z.array(z.string())
3108
- };
3109
- const INPUT_FLAG = {
3110
- name: "input",
3111
- description: "A file holding the JSON request body, or - for standard input. A flag given as well replaces its field",
3112
- valueName: "path",
3113
- schema: z.string()
3114
- };
3115
- const FILE_FLAG = {
3116
- name: "file",
3117
- description: "The file to upload",
3118
- valueName: "path",
3119
- schema: z.string()
3120
- };
3121
- const OUTPUT_FLAG = {
3122
- name: "output",
3123
- description: "Where to write the file, or - for standard output",
3124
- valueName: "path",
3125
- schema: z.string()
3126
- };
3127
- const JSON_FLAG = {
3128
- name: "json",
3129
- description: "Print machine-readable output, which is the default when stdout is not a terminal",
3130
- schema: z.boolean()
3131
- };
3132
- /** defineOperation turns one endpoint into the command that calls it. */
3133
- function defineOperation(operation) {
3134
- const flags = [
3135
- ...operation.queryFlags,
3136
- ...operation.bodyFlags,
3137
- ...operation.bodyFlags.some((flag) => flag.nullable) ? [UNSET_FLAG] : [],
3138
- ...operation.bodyFlags.length > 0 ? [INPUT_FLAG] : [],
3139
- ...operation.upload ? [...operation.upload.fields, FILE_FLAG] : [],
3140
- ...operation.downloads ? [OUTPUT_FLAG] : [],
3141
- JSON_FLAG
3142
- ];
3214
+ /**
3215
+ * toPrompt watches the keyboard while the browser is away. Pressing c copies the URL, and
3216
+ * pasting a code finishes the sign in on a machine whose browser cannot reach this listener.
3217
+ */
3218
+ function toPrompt(url, input = process.stdin, copy = copyToClipboard) {
3219
+ let settle = () => {};
3220
+ let fail = () => {};
3221
+ const pasted = new Promise((resolve, reject) => {
3222
+ settle = resolve;
3223
+ fail = reject;
3224
+ });
3225
+ pasted.catch(() => {});
3226
+ if (!input.isTTY) return {
3227
+ pasted,
3228
+ close: () => {}
3229
+ };
3230
+ let typed = "";
3231
+ const onData = (chunk) => {
3232
+ const isKeystroke = chunk.length === 1;
3233
+ for (const character of chunk) {
3234
+ if (character === CTRL_C || character === CTRL_BACKSLASH) {
3235
+ fail(new Interrupted());
3236
+ return;
3237
+ }
3238
+ if (character === "\r" || character === "\n") {
3239
+ if (typed.trim() === "") continue;
3240
+ process.stderr.write("\n");
3241
+ settle(toPastedCallback(typed));
3242
+ return;
3243
+ }
3244
+ if (character === BACKSPACE) {
3245
+ typed = typed.slice(0, -1);
3246
+ process.stderr.write("\b \b");
3247
+ continue;
3248
+ }
3249
+ if (isKeystroke && (character === "c" || character === "C") && typed === "") {
3250
+ process.stderr.write(copy(url) ? "Copied the URL to your clipboard\n" : "Nothing on this host takes a clipboard\n");
3251
+ continue;
3252
+ }
3253
+ if (character < " ") continue;
3254
+ typed += character;
3255
+ process.stderr.write(character);
3256
+ }
3257
+ };
3258
+ input.setRawMode(true);
3259
+ input.setEncoding("utf8");
3260
+ input.resume();
3261
+ input.on("data", onData);
3262
+ const close = () => {
3263
+ input.off("data", onData);
3264
+ input.setRawMode(false);
3265
+ input.pause();
3266
+ };
3143
3267
  return {
3144
- name: operation.name,
3145
- summary: operation.summary,
3146
- description: operation.description ?? operation.summary,
3147
- arguments: operation.pathParameters,
3148
- flags,
3149
- examples: operation.example ? [{
3150
- description: operation.summary,
3151
- command: operation.example
3152
- }] : [],
3153
- endpoint: {
3154
- method: operation.method,
3155
- path: operation.path
3156
- },
3157
- run: (input) => runOperation(operation, input)
3268
+ pasted: pasted.finally(close),
3269
+ close
3158
3270
  };
3159
3271
  }
3160
- async function runOperation(operation, input) {
3161
- const path = toPath(operation, input.args);
3162
- if (path === void 0) {
3163
- writeFailure("invalid_arguments", `this command takes ${operation.pathParameters.length} argument(s), each the key of a record`, input.isJSON);
3164
- return ExitCode.USAGE;
3165
- }
3166
- const given = toGivenBody$1(input.flags["input"]);
3167
- if (given instanceof InputFailure) {
3168
- writeFailure("invalid_input", given.message, input.isJSON);
3169
- return ExitCode.USAGE;
3170
- }
3171
- const missing = operation.bodyFlags.concat(operation.upload?.fields ?? []).filter((flag) => flag.required && input.flags[toOptionKey(flag.name)] === void 0 && !hasPath(given, flag.jsonPath));
3172
- if (missing.length > 0) {
3173
- writeFailure("missing_flag", `this command needs ${missing.map((flag) => `--${flag.name}`).join(", ")}`, input.isJSON);
3174
- return ExitCode.USAGE;
3175
- }
3176
- const body = toBody(operation, input.flags, given);
3177
- if (body instanceof Error) {
3178
- writeFailure("invalid_flag", body.message, input.isJSON);
3179
- return ExitCode.USAGE;
3180
- }
3181
- if (operation.bodyFlags.length > 0 && body === void 0) {
3182
- writeFailure("empty_request", `this command changes nothing unless a flag is given, such as ${operation.bodyFlags.slice(0, 3).map((flag) => `--${flag.name}`).join(", ")}. Run it with --help for the rest`, input.isJSON);
3183
- return ExitCode.USAGE;
3184
- }
3185
- let form;
3186
- if (operation.upload) {
3187
- const built = await toForm(operation.upload, input.flags);
3188
- if (built instanceof Error) {
3189
- writeFailure("invalid_input", built.message, input.isJSON);
3190
- return ExitCode.USAGE;
3272
+ //#endregion
3273
+ //#region src/command/login.ts
3274
+ /** The scopes a sign-in asks for, with offline access so a refresh token comes back. */
3275
+ const DEFAULT_SCOPES = "hardfin:read hardfin:write offline_access";
3276
+ /** The scopes a sign in asks for when it must not be able to change anything. */
3277
+ const READ_ONLY_SCOPES = "hardfin:read offline_access";
3278
+ const WAIT_MS = 3e5;
3279
+ const loginCommand = defineCommand({
3280
+ name: "login",
3281
+ summary: "Sign in to Hardfin through a browser",
3282
+ description: "Opens the browser to approve this CLI, then keeps the refresh token in the OS keyring, or in a file with owner-only permissions where there is no keyring. Access tokens are never written anywhere.",
3283
+ arguments: [],
3284
+ flags: [
3285
+ {
3286
+ name: "read-only",
3287
+ description: "Ask for read access alone, so nothing run with this sign in can change a record",
3288
+ schema: z.boolean()
3289
+ },
3290
+ {
3291
+ name: "scope",
3292
+ description: `The scopes to ask for, separated by spaces, which are ${DEFAULT_SCOPES} when not given`,
3293
+ valueName: "scopes",
3294
+ schema: z.string()
3295
+ },
3296
+ {
3297
+ name: "no-browser",
3298
+ description: "Print the URL instead of opening it",
3299
+ schema: z.boolean()
3300
+ },
3301
+ {
3302
+ name: "device",
3303
+ description: "Approve on another machine, by typing a code, with no listener on this one",
3304
+ schema: z.boolean()
3305
+ },
3306
+ {
3307
+ name: "json",
3308
+ description: "Print machine-readable output, which is the default when stdout is not a terminal",
3309
+ schema: z.boolean()
3191
3310
  }
3192
- form = built;
3311
+ ],
3312
+ examples: [
3313
+ {
3314
+ description: "Sign in",
3315
+ command: "hardfin login"
3316
+ },
3317
+ {
3318
+ description: "Sign in so that nothing can be changed",
3319
+ command: "hardfin login --read-only"
3320
+ },
3321
+ {
3322
+ description: "Sign in over SSH, opening the URL yourself",
3323
+ command: "hardfin login --no-browser"
3324
+ },
3325
+ {
3326
+ description: "Approve from your phone or another machine",
3327
+ command: "hardfin login --device"
3328
+ }
3329
+ ],
3330
+ run: runLogin
3331
+ });
3332
+ async function runLogin(input) {
3333
+ const settings = input.resolved.settings;
3334
+ const isReadOnly = input.flags["readOnly"] === true;
3335
+ if (isReadOnly && input.flags["scope"] !== void 0) {
3336
+ writeFailure("invalid_flag", "--read-only and --scope both name the scopes to ask for, so give one of them", input.isJSON);
3337
+ return ExitCode.USAGE;
3193
3338
  }
3194
3339
  try {
3195
- const envelope = await request$1({
3196
- apiUrl: input.resolved.settings.apiUrl,
3197
- credential: await toRequestCredential(input.resolved.settings, input.resolved.sources),
3198
- method: operation.method,
3199
- path,
3200
- query: toQuery(operation, input.flags),
3201
- body,
3202
- form,
3203
- downloads: operation.downloads
3340
+ const clientId = settings.clientId;
3341
+ const metadata = await toMetadata(settings.issuerUrl);
3342
+ const scope = isReadOnly ? READ_ONLY_SCOPES : toText(input.flags["scope"] ?? DEFAULT_SCOPES);
3343
+ if (input.flags["device"] === true) return await runDeviceLogin(input, metadata, scope);
3344
+ const state = toState();
3345
+ const listener = await toListener(WAIT_MS, state);
3346
+ const pkce = toPkce();
3347
+ const url = toAuthorizationUrl(metadata.authorization_endpoint, {
3348
+ clientId,
3349
+ redirectUri: listener.redirectUri,
3350
+ scope,
3351
+ state,
3352
+ challenge: pkce.challenge
3204
3353
  });
3205
- if (operation.downloads) return toWritten(envelope.data, input);
3206
- writeData(envelope.data);
3207
- return ExitCode.OK;
3208
- } catch (error) {
3209
- if (error instanceof NoCredential) {
3210
- writeFailure("not_signed_in", error.message, input.isJSON);
3211
- return ExitCode.NOT_AUTHENTICATED;
3354
+ const opened = input.flags["noBrowser"] !== true && !process.env["HARDFIN_NO_BROWSER"] && openBrowser(url);
3355
+ if (input.isJSON) writeEvent({
3356
+ event: "sign_in_url",
3357
+ url,
3358
+ browserOpened: opened,
3359
+ waitSeconds: WAIT_MS / 1e3
3360
+ });
3361
+ else process.stderr.write(opened ? `Opening your browser to sign in. If it did not open:\n\n${url}\n\n` : `Open this URL to sign in:\n\n${url}\n\n`);
3362
+ const prompt = toPrompt(url);
3363
+ if (process.stdin.isTTY) process.stderr.write("Press c to copy the URL, or paste the code or redirect URL here: ");
3364
+ let callback;
3365
+ try {
3366
+ callback = await Promise.race([listener.callback, prompt.pasted]);
3367
+ } finally {
3368
+ listener.close();
3369
+ prompt.close();
3212
3370
  }
3213
- if (error instanceof RequestFailure) {
3214
- writeFailure(toRequestCode(error), error.message, input.isJSON, error.errors, error.requestId, error.status);
3215
- return error.status === 401 ? ExitCode.NOT_AUTHENTICATED : ExitCode.ERROR;
3371
+ if (!input.isJSON) process.stderr.write(callback.error ? "\n" : "\nApproved, finishing the sign in\n");
3372
+ if (callback.error) {
3373
+ writeFailure("sign_in_failed", `sign in was refused: ${callback.error}${callback.errorDescription ? `, ${callback.errorDescription}` : ""}`, input.isJSON);
3374
+ return ExitCode.ERROR;
3216
3375
  }
3217
- throw error;
3218
- }
3219
- }
3220
- /**
3221
- * toWritten puts a downloaded file where it was asked for. A terminal is never written to,
3222
- * because a person would otherwise have their session filled with a file's bytes.
3223
- */
3224
- function toWritten(download, input) {
3225
- const asked = input.flags["output"];
3226
- const offered = typeof asked === "string" ? void 0 : download.fileName;
3227
- const path = typeof asked === "string" ? asked : offered === void 0 ? "-" : toLocalName(offered);
3228
- if (path === void 0 || offered !== void 0 && existsSync(path)) {
3229
- writeFailure("output_required", path === void 0 ? `this file is offered as ${JSON.stringify(offered)}, which is not a name to write here, so name where to write it with --output` : `${path} already exists, so name where to write this file with --output`, input.isJSON);
3230
- return ExitCode.USAGE;
3231
- }
3232
- if (path === "-") {
3233
- if (process.stdout.isTTY) {
3234
- writeFailure("output_required", "this answer is a file, so name where to write it with --output, or send it on with a pipe", input.isJSON);
3235
- return ExitCode.USAGE;
3376
+ if (callback.source === "listener" ? callback.state !== state : callback.state !== void 0 && callback.state !== state) {
3377
+ writeFailure("sign_in_failed", "the browser came back with a state this sign in did not send", input.isJSON);
3378
+ return ExitCode.ERROR;
3236
3379
  }
3237
- process.stdout.write(download.bytes);
3238
- return ExitCode.OK;
3239
- }
3240
- writeFileSync(path, download.bytes);
3241
- writeData({
3242
- written: path,
3243
- bytes: download.bytes.length,
3244
- contentType: download.contentType
3245
- });
3246
- return ExitCode.OK;
3247
- }
3248
- /** toLocalName reduces a name the API offered to one file in the working directory, or to nothing. */
3249
- function toLocalName(offered) {
3250
- const name = offered.split(/[\\/]/).pop() ?? "";
3251
- return name === "" || name.startsWith(".") ? void 0 : name;
3252
- }
3253
- /** The arguments a URL reads as "this folder" and "the one above", and one that names nothing. */
3254
- const NOT_A_KEY = /* @__PURE__ */ new Set([
3255
- "",
3256
- ".",
3257
- ".."
3258
- ]);
3259
- /** toPath fills the path template from the positional arguments, in order. */
3260
- function toPath(operation, args) {
3261
- if (args.length !== operation.pathParameters.length || args.some((argument) => NOT_A_KEY.has(argument))) return;
3262
- let path = operation.path;
3263
- for (const [index, parameter] of operation.pathParameters.entries()) path = path.replace(`{${parameter.name}}`, encodeURIComponent(args[index] ?? ""));
3264
- return path;
3265
- }
3266
- /** toQuery carries only the flags this invocation actually set. */
3267
- function toQuery(operation, flags) {
3268
- const query = new URLSearchParams();
3269
- for (const flag of operation.queryFlags) {
3270
- const value = flags[toOptionKey(flag.name)];
3271
- if (value === void 0) continue;
3272
- const parsed = flag.schema.safeParse(value);
3273
- const carried = parsed.success ? parsed.data : value;
3274
- for (const entry of Array.isArray(carried) ? carried : [carried]) query.append(flag.queryName, toText(entry));
3275
- }
3276
- return query;
3277
- }
3278
- /** toOptionKey names the parsed flag, which the parser reports in camel case. */
3279
- function toOptionKey(name) {
3280
- return name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
3281
- }
3282
- /** toForm builds the file part and its fields, which an upload endpoint takes. */
3283
- async function toForm(upload, flags) {
3284
- const path = flags["file"];
3285
- if (typeof path !== "string") return /* @__PURE__ */ new Error("this command needs --file, the file to upload");
3286
- const form = new FormData();
3287
- try {
3288
- form.append(upload.filePart, await openAsBlob(path), basename(path));
3289
- } catch {
3290
- return /* @__PURE__ */ new Error(`${path} cannot be read`);
3291
- }
3292
- for (const field of upload.fields) {
3293
- const value = flags[toOptionKey(field.name)];
3294
- if (value !== void 0) {
3295
- const parsed = field.schema.safeParse(value);
3296
- form.append(field.jsonPath[0] ?? field.name, toText(parsed.success ? parsed.data : value));
3380
+ if (callback.issuer !== void 0 && callback.issuer.replace(/\/+$/, "") !== metadata.issuer.replace(/\/+$/, "")) {
3381
+ writeFailure("sign_in_failed", `the browser came back from ${callback.issuer}, which is not ${metadata.issuer}`, input.isJSON);
3382
+ return ExitCode.ERROR;
3297
3383
  }
3298
- }
3299
- return form;
3300
- }
3301
- /** toGivenBody reads the --input body, which a generated command takes only as a JSON object. */
3302
- function toGivenBody$1(source) {
3303
- if (typeof source !== "string") return;
3304
- const read = toJSONInput(source);
3305
- if (read instanceof InputFailure) return read;
3306
- if (typeof read !== "object" || read === null || Array.isArray(read)) return new InputFailure(`the body in ${source === "-" ? "standard input" : source} must be a JSON object, such as {"name": "Acme"}`);
3307
- return read;
3308
- }
3309
- /** hasPath reports whether a body already holds a value at a field's path. */
3310
- function hasPath(body, path) {
3311
- let holder = body;
3312
- for (const name of path) {
3313
- if (typeof holder !== "object" || holder === null || !(name in holder)) return false;
3314
- holder = holder[name];
3315
- }
3316
- return true;
3317
- }
3318
- /** toBody builds the request body from the --input body and the flags, a flag winning over its field. */
3319
- function toBody(operation, flags, given) {
3320
- const body = given ? structuredClone(given) : {};
3321
- let hasField = given !== void 0;
3322
- for (const flag of operation.bodyFlags) {
3323
- const value = flags[toOptionKey(flag.name)];
3324
- if (value === void 0) continue;
3325
- if (flag.element) {
3326
- const elements = toElements(flag, Array.isArray(value) ? value.map(toText) : [toText(value)]);
3327
- if (elements instanceof Error) return elements;
3328
- set(body, flag.jsonPath, elements);
3329
- hasField = true;
3330
- continue;
3384
+ if (!callback.code) {
3385
+ writeFailure("sign_in_failed", "the browser came back without an authorization code", input.isJSON);
3386
+ return ExitCode.ERROR;
3331
3387
  }
3332
- const parsed = flag.schema.safeParse(value);
3333
- set(body, flag.jsonPath, parsed.success ? parsed.data : value);
3334
- hasField = true;
3388
+ return await toSignedIn(input, metadata, await toTokensFromCode(metadata.token_endpoint, clientId, callback.code, listener.redirectUri, pkce));
3389
+ } catch (error) {
3390
+ if (error instanceof DiscoveryFailure || error instanceof GrantFailure || error instanceof SignInStopped) {
3391
+ writeFailure("sign_in_failed", error.message, input.isJSON);
3392
+ return ExitCode.ERROR;
3393
+ }
3394
+ throw error;
3335
3395
  }
3336
- const cleared = toCleared(operation, flags, body);
3337
- if (cleared instanceof Error) return cleared;
3338
- return hasField || cleared ? body : void 0;
3339
3396
  }
3340
- /** toCleared sends null for each field named by --unset, which is how a field is cleared. */
3341
- function toCleared(operation, flags, body) {
3342
- const named = flags["unset"];
3343
- const names = Array.isArray(named) ? named.map(toText) : named === void 0 ? [] : [toText(named)];
3344
- for (const name of names) {
3345
- const flag = operation.bodyFlags.find((entry) => entry.name === name.replace(/^--/, ""));
3346
- if (!flag) return /* @__PURE__ */ new Error(`--unset names no field called ${name}`);
3347
- if (!flag.nullable) return /* @__PURE__ */ new Error(`--${flag.name} cannot be cleared, because the API does not accept null for it`);
3348
- set(body, flag.jsonPath, null);
3397
+ /** runDeviceLogin waits while the person approves on a machine that has a browser. */
3398
+ async function runDeviceLogin(input, metadata, scope) {
3399
+ const settings = input.resolved.settings;
3400
+ if (!metadata.device_authorization_endpoint) {
3401
+ writeFailure("sign_in_failed", `${metadata.issuer} does not offer the device grant, so sign in without --device`, input.isJSON);
3402
+ return ExitCode.ERROR;
3349
3403
  }
3350
- return names.length > 0;
3351
- }
3352
- /** toElements reads the key=value pairs a repeated flag carries for one array element. */
3353
- function toElements(flag, values) {
3354
- const elements = [];
3355
- for (const value of values) {
3356
- const element = {};
3357
- for (const pair of value.split(",")) {
3358
- const split = pair.indexOf("=");
3359
- if (split < 1) return /* @__PURE__ */ new Error(`--${flag.name} takes ${flag.element?.join("=, ") ?? ""}=, such as --${flag.name} ${flag.element?.[0] ?? "field"}=value. A value cannot contain a comma`);
3360
- const isJSON = pair[split - 1] === ":";
3361
- const key = pair.slice(0, isJSON ? split - 1 : split).trim();
3362
- if (flag.element && !flag.element.includes(key)) return /* @__PURE__ */ new Error(`--${flag.name} has no field ${key}. It takes ${flag.element.join(", ")}`);
3363
- if (key in element) return /* @__PURE__ */ new Error(`--${flag.name} names ${key} twice in one element, so which one it takes is not clear`);
3364
- const value = pair.slice(split + 1).trim();
3365
- if (flag.elementUuids?.includes(key) && !z.uuid().safeParse(value).success) return /* @__PURE__ */ new Error(`--${flag.name} needs a UUID for ${key}, such as 3f2a9c1e-5b7d-4e8a-9c21-7d4e5f6a8b90, and ${value || "nothing"} is not one`);
3366
- const types = flag.elementTypes?.[key];
3367
- const typed = isJSON ? toJSONValue(value, types ?? ["string"]) : toTyped(value, types);
3368
- if (typed === NOT_TAKEN) return /* @__PURE__ */ new Error(`--${flag.name} needs ${toNamedTypes(types ?? ["string"])} for ${key}, and ${value || "nothing"} is not one`);
3369
- element[key] = typed;
3370
- }
3371
- elements.push(element);
3404
+ const device = await toDeviceAuthorization(metadata.device_authorization_endpoint, settings.clientId, scope);
3405
+ const url = device.verificationUriComplete ?? device.verificationUri;
3406
+ const opened = input.flags["noBrowser"] !== true && !process.env["HARDFIN_NO_BROWSER"] && openBrowser(url);
3407
+ if (input.isJSON) writeEvent({
3408
+ event: "device_code",
3409
+ userCode: device.userCode,
3410
+ verificationUri: device.verificationUri,
3411
+ url,
3412
+ browserOpened: opened,
3413
+ waitSeconds: Math.max(0, Math.round((device.expiresAt - Date.now()) / 1e3))
3414
+ });
3415
+ else process.stderr.write([
3416
+ "",
3417
+ ` Code ${toPrintable(device.userCode)}`,
3418
+ ` At ${toPrintable(device.verificationUri)}`,
3419
+ "",
3420
+ opened ? "Opened your browser there. Waiting for approval\n" : "Open that page on any machine, and enter the code. Waiting for approval\n"
3421
+ ].join("\n"));
3422
+ const prompt = toPrompt(url);
3423
+ try {
3424
+ return await toSignedIn(input, metadata, await toDeviceTokens(toTokensFromDevice(metadata.token_endpoint, settings.clientId, device), prompt.pasted));
3425
+ } finally {
3426
+ prompt.close();
3372
3427
  }
3373
- return elements;
3374
3428
  }
3375
- /** Marks text that is none of the types a field takes. */
3376
- const NOT_TAKEN = Symbol("not taken");
3377
- const NUMBER = /^-?\d+(\.\d+)?$/;
3378
3429
  /**
3379
- * toTyped reads the text after key= as the type the document gives the field. A field that
3380
- * takes text is sent as typed, whatever it looks like, because 36 may be a serial number. A
3381
- * field that takes no text has only one reading, so order=2 is sent as the number.
3430
+ * toDeviceTokens waits for the approval, or for the keyboard. Ctrl-C arrives as an Interrupted
3431
+ * and stops quietly. Text followed by Enter means the person typed the code here, where it
3432
+ * does nothing, so they are told where it goes instead.
3382
3433
  */
3383
- function toTyped(text, types) {
3384
- if (types === void 0 || types.includes("string")) return text;
3385
- if (types.includes("null") && text === "null") return null;
3386
- if ((types.includes("integer") || types.includes("number")) && NUMBER.test(text)) {
3387
- const value = Number(text);
3388
- if (types.includes("number") || Number.isInteger(value)) return value;
3389
- }
3390
- if (types.includes("boolean") && (text === "true" || text === "false")) return text === "true";
3391
- return NOT_TAKEN;
3434
+ async function toDeviceTokens(approved, typed) {
3435
+ return await Promise.race([approved, typed.then(() => {
3436
+ throw new SignInStopped("Sign in stopped. The code goes on the page in your browser, not here. Run hardfin login to try again.");
3437
+ })]);
3392
3438
  }
3393
- /**
3394
- * toJSONValue reads the text after key:= as JSON, and takes it when the field takes its type.
3395
- * It is how a custom field is given the number 36 or true, where key= would send the text.
3396
- */
3397
- function toJSONValue(text, types) {
3398
- let value;
3399
- try {
3400
- value = JSON.parse(text);
3401
- } catch {
3402
- return NOT_TAKEN;
3439
+ /** toSignedIn stores what a sign in issued, whichever flow issued it. */
3440
+ async function toSignedIn(input, metadata, tokens) {
3441
+ const refreshToken = tokens.refreshToken;
3442
+ if (!refreshToken) {
3443
+ writeFailure("sign_in_failed", "the authorization server issued no refresh token, so this sign in cannot be kept", input.isJSON);
3444
+ return ExitCode.ERROR;
3403
3445
  }
3404
- const type = value === null ? "null" : typeof value;
3405
- return (types.includes(type) || type === "number" && types.includes("integer") && Number.isInteger(value)) && type !== "object" ? value : NOT_TAKEN;
3446
+ const scopes = toGrantedScopes(tokens);
3447
+ const backend = await withLock(() => keep$1(input.resolved.settings.issuerUrl, refreshToken, tokens.refreshExpiresAt, scopes));
3448
+ if (input.isJSON) {
3449
+ writeData({
3450
+ signedIn: true,
3451
+ issuer: metadata.issuer,
3452
+ scope: tokens.scope ?? null,
3453
+ scopes: scopes ?? null,
3454
+ canWrite: toCanWrite(scopes),
3455
+ storedIn: backend
3456
+ });
3457
+ return ExitCode.OK;
3458
+ }
3459
+ const stored = backend === "keyring" ? "your OS keyring" : toCredentialPath();
3460
+ writeData([
3461
+ `Signed in to ${metadata.issuer}`,
3462
+ `Scope ${scopes?.join(" ") ?? tokens.scope ?? "as granted"}`,
3463
+ ...toCanWrite(scopes) === false ? ["Access read-only, so a command that changes a record will be refused"] : [],
3464
+ `Stored in ${stored}`,
3465
+ "",
3466
+ "Run hardfin status to see what this CLI is using",
3467
+ ...isInstalled() ? [] : ["Run hardfin completion install to complete commands with Tab"]
3468
+ ].join("\n"));
3469
+ return ExitCode.OK;
3406
3470
  }
3407
- /** toNamedTypes says in words what a field takes, for the message that refuses a value. */
3408
- function toNamedTypes(types) {
3409
- const named = {
3410
- integer: "a whole number",
3411
- number: "a number",
3412
- boolean: "true or false",
3413
- string: "text in quotes",
3414
- null: "null"
3415
- };
3416
- return types.filter((type) => type in named).map((type) => named[type]).join(" or ");
3471
+ /** writeEvent tells a program what a sign in is waiting on, as one line of JSON on stderr. */
3472
+ function writeEvent(event) {
3473
+ process.stderr.write(`${JSON.stringify(event)}\n`);
3417
3474
  }
3418
- /** set writes a value at its path, building the objects a nested field needs. */
3419
- function set(body, path, value) {
3420
- let holder = body;
3421
- for (const name of path.slice(0, -1)) {
3422
- holder[name] = holder[name] ?? {};
3423
- holder = holder[name];
3475
+ /** toAuthorizationUrl builds the URL the person approves this CLI at. */
3476
+ function toAuthorizationUrl(endpoint, request) {
3477
+ const url = new URL(endpoint);
3478
+ url.searchParams.set("response_type", "code");
3479
+ url.searchParams.set("client_id", request.clientId);
3480
+ url.searchParams.set("redirect_uri", request.redirectUri);
3481
+ url.searchParams.set("scope", request.scope);
3482
+ url.searchParams.set("state", request.state);
3483
+ url.searchParams.set("code_challenge", request.challenge);
3484
+ url.searchParams.set("code_challenge_method", "S256");
3485
+ return url.toString();
3486
+ }
3487
+ //#endregion
3488
+ //#region src/command/logout.ts
3489
+ const logoutCommand = defineCommand({
3490
+ name: "logout",
3491
+ summary: "Sign out, and tell Hardfin to forget this machine",
3492
+ description: "Removes the stored refresh token and asks the authorization server to revoke it, so a copy taken from this machine stops working.",
3493
+ arguments: [],
3494
+ flags: [{
3495
+ name: "json",
3496
+ description: "Print machine-readable output, which is the default when stdout is not a terminal",
3497
+ schema: z.boolean()
3498
+ }],
3499
+ examples: [{
3500
+ description: "Sign out",
3501
+ command: "hardfin logout"
3502
+ }],
3503
+ run: runLogout
3504
+ });
3505
+ async function runLogout(input) {
3506
+ const settings = input.resolved.settings;
3507
+ const stored = toCredential(settings.issuerUrl);
3508
+ if (!stored) {
3509
+ writeData({
3510
+ signedOut: false,
3511
+ issuer: settings.issuerUrl,
3512
+ reason: "no sign in was stored"
3513
+ });
3514
+ return ExitCode.OK;
3424
3515
  }
3425
- holder[path[path.length - 1] ?? ""] = value;
3516
+ let revoked = false;
3517
+ try {
3518
+ const metadata = await toMetadata(settings.issuerUrl);
3519
+ if (metadata.revocation_endpoint) {
3520
+ await revoke(metadata.revocation_endpoint, settings.clientId, stored.refreshToken);
3521
+ revoked = true;
3522
+ }
3523
+ } catch {
3524
+ revoked = false;
3525
+ }
3526
+ await withLock(() => {
3527
+ forget(settings.issuerUrl);
3528
+ });
3529
+ forgetHeldTokens();
3530
+ writeData({
3531
+ signedOut: true,
3532
+ issuer: settings.issuerUrl,
3533
+ revoked
3534
+ });
3535
+ return ExitCode.OK;
3426
3536
  }
3427
3537
  //#endregion
3428
3538
  //#region src/mcp/confine.ts
@@ -7247,5 +7357,5 @@ async function toReported(error, isJSON, resolved, level = "error") {
7247
7357
  //#endregion
7248
7358
  export { toCli, toParseExitCode, toReported, wasReportAttempted, writeCrash };
7249
7359
 
7250
- //# sourceMappingURL=program-CI4W2agw.js.map
7251
- //# debugId=cb5319cf-733c-5f06-b5d8-f8f154bf4267
7360
+ //# sourceMappingURL=program-PaNgBWFL.js.map
7361
+ //# debugId=566d9b65-d8fb-507d-8b0e-a21deb646246