pivotkit-node 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ All notable changes to `pivotkit-node` are documented in this file. The format is based on
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this package adheres to
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2026-11-24
10
+
11
+ ### Added
12
+
13
+ - The first release: the file handling of `pivotkit-cli/files` and the REST contract of
14
+ `pivotkit-cli/rest`, which pivotkit-cli and pivotkit-server now share from here. `writeNew` and
15
+ `writeSafe` with `exclusive` also work on file systems without hard links, such as FAT, exFAT and
16
+ some SMB mounts.
17
+ - `pivotkit-node/net`: `ipBytes`, `isLoopback`, `retryAfterSeconds` and `networkCodeOf`, the one copy
18
+ of how both front ends read addresses, Retry-After headers and failed connections.
19
+ `NETWORK_FAILURES` is the one table of a failed connection's codes: the command line's words and
20
+ which codes may work again.
21
+ - `CliError` extends `CodedError` of `pivotkit-core/internal`.
22
+
23
+ [Unreleased]: https://github.com/eizedev/pivotkit/compare/pivotkit-node@0.1.0...HEAD
24
+ [0.1.0]: https://github.com/eizedev/pivotkit/releases/tag/pivotkit-node@0.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 eizedev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,17 @@
1
- # Temporary Holding Version
1
+ # pivotkit-node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Internal to [pivotkit](https://github.com/eizedev/pivotkit).
4
+
5
+ It holds what the command line [pivotkit-cli](https://www.npmjs.com/package/pivotkit-cli) and
6
+ [pivotkit-server](https://www.npmjs.com/package/pivotkit-server) share in Node:
7
+
8
+ - `pivotkit-node/files` reads and writes files for a caller.
9
+ - `pivotkit-node/rest` holds what the REST service and its client agree on.
10
+ - `pivotkit-node/net` reads addresses, Retry-After headers and failed connections.
11
+
12
+ Its exports may change in any release. Use `pivotkit-cli/files` and `pivotkit-cli/rest` instead.
13
+ They re-export the same names and follow [versioning](https://pivotkit.eize.dev/versioning/).
14
+
15
+ ## License
16
+
17
+ [MIT](https://github.com/eizedev/pivotkit/blob/main/LICENSE)
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "pivotkit-node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Internal to pivotkit: the Node.js file handling, REST contract and network readings that the pivotkit command line and pivotkit-server share. Use pivotkit-cli/files and pivotkit-cli/rest instead.",
5
+ "license": "MIT",
6
+ "author": "eizedev <oss@eize.dev>",
7
+ "homepage": "https://pivotkit.eize.dev",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/eizedev/pivotkit.git",
11
+ "directory": "packages/pivotkit-node"
12
+ },
13
+ "bugs": "https://github.com/eizedev/pivotkit/issues",
14
+ "keywords": [
15
+ "pivotkit"
16
+ ],
17
+ "type": "module",
18
+ "exports": {
19
+ "./files": {
20
+ "types": "./types/files.d.ts",
21
+ "default": "./src/files.js"
22
+ },
23
+ "./net": {
24
+ "types": "./types/net.d.ts",
25
+ "default": "./src/net.js"
26
+ },
27
+ "./rest": {
28
+ "types": "./types/rest.d.ts",
29
+ "default": "./src/rest.js"
30
+ },
31
+ "./package.json": "./package.json"
32
+ },
33
+ "files": [
34
+ "src",
35
+ "types",
36
+ "README.md",
37
+ "CHANGELOG.md",
38
+ "LICENSE"
39
+ ],
40
+ "engines": {
41
+ "node": ">=24"
42
+ },
43
+ "scripts": {
44
+ "test": "node ../../scripts/test-run.js node --test \"test/*.test.js\"",
45
+ "coverage": "node ../../scripts/test-run.js node --test --experimental-test-coverage --test-coverage-include=\"src/**\" \"test/*.test.js\"",
46
+ "types": "tsc -p .",
47
+ "test:types": "tsc -p test/types",
48
+ "prepack": "npm run types && node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\""
49
+ },
50
+ "dependencies": {
51
+ "pivotkit-core": "^0.10.0",
52
+ "pivotkit-report": "^0.6.0",
53
+ "pivotkit-xlsx": "^0.7.0"
54
+ },
55
+ "devDependencies": {
56
+ "@types/node": "24.19.2"
57
+ },
58
+ "publishConfig": {
59
+ "access": "public"
60
+ }
61
+ }
package/src/errors.js ADDED
@@ -0,0 +1,86 @@
1
+ /*
2
+ * The errors of reading and writing files for a caller, and how a message names what it is about.
3
+ * A CliError has a kind (what went wrong, for scripts) and a code; the command line ends with exit
4
+ * code 2 for it. No message holds the content of a file: a path is named by its base name (a
5
+ * directory below the working directory as typed), text from a file or a view is cleaned before it
6
+ * is printed; what a message may quote from data is the header's field names (each cut) and at most
7
+ * one cell value where it says what to fix, cut at 20 characters.
8
+ */
9
+
10
+ import { basename } from "node:path";
11
+ import { PivotkitError } from "pivotkit-core";
12
+ import { CodedError } from "pivotkit-core/internal";
13
+ import { cleanText } from "pivotkit-core/import";
14
+ import { OperationError } from "pivotkit-report/operations";
15
+
16
+ /** @typedef {"usage" | "io" | "limit" | "template" | "remote" | "internal"} ErrorKind */
17
+
18
+ /** @extends {CodedError<string, undefined>} */
19
+ export class CliError extends CodedError {
20
+ /**
21
+ * @param {ErrorKind} kind
22
+ * @param {string} code a stable name, e.g. NOT_FOUND, OUTSIDE_ALLOWED_DIR, UNKNOWN_OPTION
23
+ * @param {string} message
24
+ */
25
+ constructor(kind, code, message) {
26
+ super(code, message);
27
+ this.name = "CliError";
28
+ this.kind = kind;
29
+ }
30
+ }
31
+
32
+ /** The most characters of a name or message from outside that a message prints. */
33
+ const PRINT_LENGTH = 200;
34
+
35
+ /** Text from a file, a view or the data, safe to print: no control or direction characters, capped. */
36
+ export function printable(text) {
37
+ const clean = cleanText(String(text ?? ""));
38
+ return clean.length > PRINT_LENGTH ? `${clean.slice(0, PRINT_LENGTH - 1)}…` : clean;
39
+ }
40
+
41
+ /** A path as messages name it: its base name only. */
42
+ export const shortName = (path) => printable(path === "-" ? "stdin" : basename(String(path)));
43
+
44
+ /** What Node's file errors mean, by their code. */
45
+ const FILE_ERRORS = Object.freeze({ ENOENT: "not found", EACCES: "not allowed to read or write", EPERM: "not allowed to read or write", EISDIR: "is a directory", ENOTDIR: "a part of the path is not a directory", ELOOP: "is a symbolic link", EEXIST: "exists", ENOSPC: "no space left on the disk", EROFS: "the file system is read-only" });
46
+
47
+ /**
48
+ * The kind of a pivotkit-core error, by its code.
49
+ * @param {PivotkitError} error
50
+ * @returns {ErrorKind}
51
+ */
52
+ function kindOfPivotkitError(error) {
53
+ const code = /** @type {string} */ (error.code);
54
+ // a reader over a limit throws LIMIT_EXCEEDED; pivotkit-xlsx 0.1.0 threw INVALID_FILE with reason
55
+ // LIMIT and details.limit, and a host may still have it installed next to this package
56
+ const overLimit = code === "LIMIT_EXCEEDED" || (code === "INVALID_FILE" && (error.details?.reason === "LIMIT" || typeof error.details?.limit === "string"));
57
+ return overLimit ? "limit" : code === "INVALID_TEMPLATE" ? "template" : code === "INVALID_FILE" ? "io" : code === "INVALID_OPTION" ? "usage" : "internal";
58
+ }
59
+
60
+ /**
61
+ * Any error as a CliError: pivotkit-core's by their code, Node's file errors by theirs (with the
62
+ * file's base name, never its content), anything else as internal.
63
+ * @param {unknown} error
64
+ * @param {string} [path] the file it is about
65
+ * @returns {CliError}
66
+ */
67
+ export function asCliError(error, path) {
68
+ if (error instanceof CliError) {
69
+ return error;
70
+ }
71
+ const name = path ? shortName(path) : "";
72
+ if (error instanceof PivotkitError) {
73
+ const reason = typeof error.details?.reason === "string" ? error.details.reason : /** @type {string} */ (error.code);
74
+ return new CliError(kindOfPivotkitError(error), reason, printable(name && !error.message.includes(name) ? `${name}: ${error.message}` : error.message));
75
+ }
76
+ if (error instanceof OperationError) {
77
+ // an operation of pivotkit-report's table: its code, the CLI's kind for it
78
+ const kind = error.code === "LIMIT_EXCEEDED" ? "limit" : error.code === "INVALID_INPUT" ? "usage" : error.code === "INTERNAL" ? "internal" : "io";
79
+ return new CliError(kind, error.code, printable(error.message));
80
+ }
81
+ const e = /** @type {NodeJS.ErrnoException} */ (error);
82
+ if (e && typeof e.code === "string" && Object.hasOwn(FILE_ERRORS, e.code)) {
83
+ return new CliError("io", e.code, `${name || "file"}: ${FILE_ERRORS[e.code]}`);
84
+ }
85
+ return new CliError("internal", "INTERNAL", printable(e && e.message ? e.message : String(error)));
86
+ }
package/src/files.js ADDED
@@ -0,0 +1,39 @@
1
+ /*
2
+ * pivotkit-node/files: reading and writing files on behalf of a caller, for the command line and
3
+ * pivotkit-server (pivotkit-cli/files re-exports it): a regular file read once with its size checked
4
+ * first, allowed directories by real path, new files that never replace one, and a data file read
5
+ * into an import table with pivotkit-xlsx. Node only. Not a sandbox: see safe-files.js for what the
6
+ * checks cannot do (another process of the same user changing the directories while they run).
7
+ */
8
+
9
+ import { readFile } from "pivotkit-core/import";
10
+ import xlsxReader from "pivotkit-xlsx";
11
+ import { printable, shortName } from "./errors.js";
12
+
13
+ export { NO_HARD_LINKS, TEMP_FILE_NAME, allowedDirs, cleanFileName, isInside, readSafe, readStdin, writeNew, writeSafe } from "./safe-files.js";
14
+ export { CliError, asCliError, printable, shortName } from "./errors.js";
15
+
16
+ /** The data formats the front ends read, by extension. */
17
+ export const DATA_FORMATS = Object.freeze(["csv", "tsv", "txt", "json", "xlsx"]);
18
+
19
+ /**
20
+ * Reader notes that only say how a file was read (its encoding, separator, sheet): "info". The others
21
+ * say the data differs from the file (a column renamed or dropped, text cut, values not converted):
22
+ * warnings.
23
+ */
24
+ // LINES_SKIPPED is a warning: the lines above the header a reader took for a title may be data
25
+ export const INFO_NOTES = Object.freeze(new Set(["ENCODING", "SEPARATOR", "SHEET", "USED_RANGE", "JSON_FLATTENED", "ROWS_EMPTY"]));
26
+
27
+ /**
28
+ * The bytes of a data file as an import table (pivotkit-core/import with pivotkit-xlsx), with the
29
+ * reader's notes as findings named by the file's base name.
30
+ * @param {Uint8Array} bytes
31
+ * @param {string} name the file's name; its extension (or `format`) says how to read it
32
+ * @param {{ format?: string, sheet?: string, timeZone?: string, limits?: Partial<import("pivotkit-core").Limits> }} [options]
33
+ * @returns {Promise<{ table: any, notes: Array<{ severity: "info" | "warning", code: string, path: string, message: string }> }>}
34
+ */
35
+ export async function readTable(bytes, name, { format, sheet, timeZone, limits } = {}) {
36
+ const fileName = format && !name.toLowerCase().endsWith(`.${format}`) ? `${name}.${format}` : name;
37
+ const table = await readFile(new File([/** @type {BlobPart} */ (bytes)], fileName), { plugins: [xlsxReader], ...(limits ? { limits } : {}), ...(sheet ? { sheet } : {}), ...(timeZone ? { timeZone } : {}) });
38
+ return { table, notes: table.notes.map((n) => ({ severity: INFO_NOTES.has(n.code) ? "info" : "warning", code: n.code, path: "", message: printable(`${shortName(name)}: ${n.message}`) })) };
39
+ }
package/src/net.js ADDED
@@ -0,0 +1,164 @@
1
+ /*
2
+ * pivotkit-node/net: how pivotkit-cli and pivotkit-server read what the network hands them: an IP
3
+ * address as its bytes, whether a host or an address is loopback, a Retry-After header, and a failed
4
+ * connection: where its system code is and what that code means (NETWORK_FAILURES). Each front end
5
+ * keeps its own error class; the readings and the words are here, once.
6
+ */
7
+
8
+ import { isIPv4, isIPv6 } from "node:net";
9
+
10
+ /**
11
+ * An IP address as its bytes, or null. Brackets and a zone ("%eth0") are dropped first.
12
+ * @param {string} text
13
+ * @returns {{ v: 4 | 6, bytes: number[] } | null}
14
+ */
15
+ export function ipBytes(text) {
16
+ const address = String(text).replace(/^\[|\]$/g, "").replace(/%.*$/, "");
17
+ if (isIPv4(address)) {
18
+ return { v: 4, bytes: address.split(".").map(Number) };
19
+ }
20
+ if (!isIPv6(address)) {
21
+ return null;
22
+ }
23
+ let tail = [];
24
+ let head = address;
25
+ // a dotted IPv4 address at the end ("::ffff:169.254.169.254") is the last two groups
26
+ const dotted = /(\d+\.\d+\.\d+\.\d+)$/.exec(address);
27
+ if (dotted) {
28
+ const v4 = dotted[1].split(".").map(Number);
29
+ tail = [(v4[0] << 8) | v4[1], (v4[2] << 8) | v4[3]];
30
+ head = address.slice(0, -dotted[1].length);
31
+ head = head.endsWith("::") ? head : head.slice(0, -1);
32
+ }
33
+ const [left, right] = head.includes("::") ? head.split("::") : [head, null];
34
+ const groups = (part) => (part ? part.split(":").filter((g) => g !== "").map((g) => parseInt(g, 16)) : []);
35
+ const l = groups(left);
36
+ const r = right === null ? [] : groups(right);
37
+ const missing = 8 - l.length - r.length - tail.length;
38
+ const words = right === null ? [...l, ...tail] : [...l, ...new Array(Math.max(missing, 0)).fill(0), ...r, ...tail];
39
+ if (words.length !== 8) {
40
+ return null;
41
+ }
42
+ return { v: 6, bytes: words.flatMap((w) => [w >> 8, w & 255]) };
43
+ }
44
+
45
+ /**
46
+ * Whether an address's bytes are loopback: 127.0.0.0/8 or ::1, and with `mapped` also the IPv4-mapped
47
+ * ::ffff:127.0.0.0/104.
48
+ * @param {{ v: 4 | 6, bytes: number[] } | null} ip
49
+ * @param {boolean} mapped
50
+ */
51
+ function loopbackBytes(ip, mapped) {
52
+ if (!ip) {
53
+ return false;
54
+ }
55
+ const b = ip.bytes;
56
+ const zeros = (to) => b.slice(0, to).every((x) => x === 0);
57
+ return ip.v === 4 ? b[0] === 127 : (zeros(15) && b[15] === 1) || (mapped && zeros(10) && b[10] === 255 && b[11] === 255 && b[12] === 127);
58
+ }
59
+
60
+ /**
61
+ * Whether a host is loopback.
62
+ *
63
+ * By default it reads a host as a URL or the configuration writes it: "localhost", an IPv4 address
64
+ * of 127.0.0.0/8 or "::1", brackets allowed ("[::1]"), any case. Only these spellings: a name such as
65
+ * "127.example.com" is no loopback, and neither is an IPv4-mapped "[::ffff:7f00:1]".
66
+ *
67
+ * `address: true` reads an IP address a lookup gave or a socket reached: every spelling counts, a
68
+ * zone is dropped, and the IPv4-mapped ::ffff:127.0.0.0/104 is loopback too. A name never is.
69
+ * @param {string} host
70
+ * @param {{ address?: boolean }} [how]
71
+ */
72
+ export function isLoopback(host, how) {
73
+ if (how?.address === true) {
74
+ return loopbackBytes(ipBytes(String(host ?? "")), true);
75
+ }
76
+ const plain = String(host ?? "").toLowerCase().replace(/^\[(.*)\]$/, "$1");
77
+ return plain === "localhost" || ((plain === "::1" || isIPv4(plain)) && loopbackBytes(ipBytes(plain), false));
78
+ }
79
+
80
+ /**
81
+ * A Retry-After header in seconds: a number of seconds, or an HTTP date (one that has passed is 0).
82
+ * Null without one and for one that is neither. Each caller caps the result by its own rule.
83
+ *
84
+ * `maxDigits` is the longest text read as a number of seconds; a longer one is read as a date.
85
+ * @param {unknown} value
86
+ * @param {{ maxDigits?: number }} [how]
87
+ * @returns {number | null}
88
+ */
89
+ export function retryAfterSeconds(value, { maxDigits = Infinity } = {}) {
90
+ if (typeof value !== "string" || !value.trim()) {
91
+ return null;
92
+ }
93
+ const text = value.trim();
94
+ const seconds = /^\d+$/.test(text) && text.length <= maxDigits ? Number(text) : Math.ceil((Date.parse(value) - Date.now()) / 1000);
95
+ return Number.isFinite(seconds) ? Math.max(seconds, 0) : null;
96
+ }
97
+
98
+ /**
99
+ * Where each kind of client puts the code of a failed connection, in the order it is looked for.
100
+ * node:http and node:https put it on the error, or on each error of an AggregateError when they tried
101
+ * IPv6 and IPv4. Node's fetch puts it on the error's cause, sometimes one level deeper; a client that
102
+ * uses fetch and node:http (the command line's remote mode) looks there first, then on the error.
103
+ */
104
+ const CODE_PLACES = Object.freeze({
105
+ node: [(e) => e?.code, (e) => e?.errors?.[0]?.code],
106
+ fetch: [(e) => e?.cause?.code, (e) => e?.code, (e) => e?.cause?.cause?.code]
107
+ });
108
+
109
+ /**
110
+ * The system code of a connection that failed (ECONNREFUSED, UND_ERR_SOCKET, a TLS code), or null.
111
+ * `client` says where to look (CODE_PLACES); the first code `accept` takes wins.
112
+ * @param {unknown} error
113
+ * @param {{ client: "node" | "fetch", accept?: (code: unknown) => boolean }} how by default any code that is there
114
+ * @returns {unknown}
115
+ */
116
+ export function networkCodeOf(error, { client, accept = (code) => code !== undefined && code !== null }) {
117
+ const e = /** @type {any} */ (error);
118
+ return CODE_PLACES[client].map((place) => place(e)).find(accept) ?? null;
119
+ }
120
+
121
+ /** An object of objects, frozen at both levels. */
122
+ const deepFreeze = (table) => Object.freeze(Object.fromEntries(Object.entries(table).map(([key, entry]) => [key, Object.freeze(entry)])));
123
+
124
+ /**
125
+ * The system codes of a failed connection that pivotkit knows, each once, with what it means:
126
+ *
127
+ * - `text`: the command line's words for it (remote mode's "the server cannot be reached: ...")
128
+ * - `retry`: pivotkit-server's guardedFetch marks a request that failed so as transient
129
+ * - `passes`: a source's load that failed so may pass by itself, so last good data may stand in
130
+ * (sources/run.js; Node's and undici's codes, also on a cause or an AggregateError's errors)
131
+ *
132
+ * The two readings of "may work again" differ by code; each stays as its caller had it.
133
+ * @type {Readonly<Record<string, Readonly<{ text?: string, retry?: true, passes?: true }>>>}
134
+ */
135
+ export const NETWORK_FAILURES = deepFreeze({
136
+ ECONNREFUSED: { text: "the connection was refused (is the server running on that port?)", retry: true, passes: true },
137
+ ENOTFOUND: { text: "the host name is not known", retry: true, passes: true },
138
+ EAI_AGAIN: { text: "the host name cannot be looked up now", retry: true, passes: true },
139
+ ECONNRESET: { text: "the connection was reset", retry: true, passes: true },
140
+ EPIPE: { text: "the connection was closed", retry: true },
141
+ ETIMEDOUT: { text: "the connection timed out", retry: true, passes: true },
142
+ EHOSTUNREACH: { text: "the host cannot be reached", retry: true },
143
+ ENETUNREACH: { text: "the network cannot be reached", retry: true },
144
+ ECONNABORTED: { retry: true },
145
+ UND_ERR_SOCKET: { text: "the connection was closed", retry: true, passes: true },
146
+ UND_ERR_CONNECT_TIMEOUT: { text: "the connection timed out", passes: true },
147
+ UND_ERR_HEADERS_TIMEOUT: { passes: true },
148
+ UND_ERR_BODY_TIMEOUT: { passes: true },
149
+ CERT_HAS_EXPIRED: { text: "the server's certificate has expired" },
150
+ DEPTH_ZERO_SELF_SIGNED_CERT: { text: "the server's certificate is self-signed and not trusted" },
151
+ SELF_SIGNED_CERT_IN_CHAIN: { text: "the server's certificate is not trusted (a self-signed certificate in its chain)" },
152
+ UNABLE_TO_VERIFY_LEAF_SIGNATURE: { text: "the server's certificate cannot be verified" },
153
+ UNABLE_TO_GET_ISSUER_CERT_LOCALLY: { text: "the server's certificate cannot be verified (its issuer is not known here; NODE_EXTRA_CA_CERTS adds one)" },
154
+ ERR_TLS_CERT_ALTNAME_INVALID: { text: "the server's certificate is for another host name" },
155
+ ERR_SSL_WRONG_VERSION_NUMBER: { text: "the server does not speak TLS on that port (http instead of https?)" },
156
+ EPROTO: { text: "the TLS handshake failed (http instead of https on that port?)" }
157
+ });
158
+
159
+ /**
160
+ * What pivotkit knows of a failed connection's code (NETWORK_FAILURES), or an empty entry.
161
+ * @param {unknown} code
162
+ * @returns {Readonly<{ text?: string, retry?: true, passes?: true }>}
163
+ */
164
+ export const networkFailureOf = (code) => (typeof code === "string" && Object.hasOwn(NETWORK_FAILURES, code) ? NETWORK_FAILURES[code] : {});
package/src/rest.js ADDED
@@ -0,0 +1,64 @@
1
+ /*
2
+ * pivotkit-node/rest: what the REST service of pivotkit-server and its client, the command line in
3
+ * remote mode, must agree on: the base path, the source ids, the token syntax, the problem codes and
4
+ * which addresses are loopback. Both depend on this package, so this is the one copy;
5
+ * pivotkit-server and pivotkit-cli/rest re-export it under the same names.
6
+ */
7
+
8
+ import { OPERATION_ERRORS } from "pivotkit-report/operations";
9
+
10
+ /**
11
+ * The extra field of the REST service's protected-resource metadata (RFC 9728 lets a resource add
12
+ * its own) that names the public client `pivotkit login` signs in with (rest.signIn.clientId).
13
+ */
14
+ export const SIGN_IN_CLIENT_FIELD = "pivotkit_client_id";
15
+
16
+ /** A sign-in client's ID: printable, no spaces, at most 200 characters. */
17
+ export const CLIENT_ID_SYNTAX = /^[\x21-\x7e]{1,200}$/;
18
+
19
+ /** The REST service's path under its origin. */
20
+ export const REST_BASE = "/api/v1";
21
+
22
+ /** A source id: letters, digits, "_", "-" and ".", at most 64, starting with a letter or digit. */
23
+ export const SOURCE_ID = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
24
+
25
+ /** What a bearer token may hold (RFC 6750's b64token): a token with other characters never matches a request. */
26
+ export const TOKEN_SYNTAX = /^[A-Za-z0-9\-._~+/]+=*$/;
27
+
28
+ /** Why a token outside TOKEN_SYNTAX does not work. */
29
+ export const TOKEN_SYNTAX_TEXT = "has characters a bearer token cannot carry (letters, digits and - . _ ~ + / only, = at the end), so no request could send it";
30
+
31
+ /** The codes the REST layer adds to the operations', with their status. */
32
+ export const REST_ERRORS = Object.freeze({
33
+ INVALID_TOKEN: 401,
34
+ INSUFFICIENT_SCOPE: 403,
35
+ FORBIDDEN_HOST: 403,
36
+ FORBIDDEN_ORIGIN: 403,
37
+ NOT_FOUND: 404,
38
+ METHOD_NOT_ALLOWED: 405,
39
+ BODY_TOO_LARGE: 413,
40
+ UNSUPPORTED_MEDIA_TYPE: 415,
41
+ VIEW_HAS_ERRORS: 422,
42
+ RATE_LIMITED: 429,
43
+ AUTH_NOT_READY: 503
44
+ });
45
+
46
+ /** Every code a problem can carry. */
47
+ export const PROBLEM_CODES = Object.freeze([...Object.keys(OPERATION_ERRORS), ...Object.keys(REST_ERRORS)]);
48
+
49
+ /** Whether a host is loopback: pivotkit-node/net says which spellings count. */
50
+ export { isLoopback } from "./net.js";
51
+
52
+ /**
53
+ * The RFC 9728 metadata address of a resource: /.well-known/oauth-protected-resource before its path
54
+ * (https://host/api/v1 has it at https://host/.well-known/oauth-protected-resource/api/v1).
55
+ * @param {string | URL} resource
56
+ */
57
+ export function resourceMetadataUrlOf(resource) {
58
+ const url = new URL(resource);
59
+ const path = url.pathname.length > 1 && url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
60
+ url.pathname = `/.well-known/oauth-protected-resource${path === "/" ? "" : path}`;
61
+ url.hash = "";
62
+ url.search = "";
63
+ return url.href;
64
+ }
@@ -0,0 +1,323 @@
1
+ /*
2
+ * Reading and writing files the same safe way, with or without allowed directories:
3
+ *
4
+ * - `--allow-dir` is a hard limit: every file read or written must lie inside one of the directories
5
+ * after its real path is resolved (symbolic links and ".." followed), checked on the path and again
6
+ * on the opened file (its device and inode against the real path's). Without it the CLI reads and
7
+ * writes with the user's own rights, as any command-line tool does.
8
+ * - A file is opened once, without following a symbolic link at its end where the system can
9
+ * (O_NOFOLLOW) and without waiting for a writer (O_NONBLOCK, so a FIFO cannot hang the CLI), then
10
+ * checked on the handle: a regular file only, and its size against the limit before a byte is read.
11
+ * - A file is written to a new temporary file next to it (exclusive create), then renamed over the
12
+ * target: no half-written output, and a symbolic link, a directory or another non-regular file at
13
+ * the target is refused, never replaced.
14
+ *
15
+ * Not a sandbox against another process of the same user that changes the directories while the CLI
16
+ * runs: the checks narrow that window, they do not close it. A hard link inside an allowed directory
17
+ * to a file outside it is that file's name inside: no path check can tell it apart. A temporary file
18
+ * of a run that is killed between its creation and the rename stays behind (".<name>.<pid>-<random>.tmp",
19
+ * `TEMP_FILE_NAME`): this module installs no signal handler, which would change the host's signal
20
+ * handling; a caller that owns a directory removes them (pivotkit-server's output.maxAgeDays).
21
+ * `hardLinks: false` refuses a file with more than one name (a hard link), for callers that read on
22
+ * behalf of someone else (pivotkit-mcp). `writeNew` never replaces a file: the final name is created
23
+ * by writeSafe's exclusive write (link(), which fails when the name exists; where the file system has
24
+ * no hard links, the name is created with O_EXCL and written in place). The module is exported
25
+ * as `pivotkit-node/files` (and `pivotkit-cli/files`).
26
+ */
27
+
28
+ import { constants } from "node:fs";
29
+ import { link, lstat, open, realpath, rename, stat, unlink } from "node:fs/promises";
30
+ import { basename, dirname, join, relative, resolve, isAbsolute, sep } from "node:path";
31
+ import { limitText } from "pivotkit-core/internal";
32
+ import { CliError, printable, shortName } from "./errors.js";
33
+
34
+ /** The calls tests replace: a file system without hard links, a temporary file that cannot be removed. */
35
+ export const fileMeans = { link, unlink };
36
+
37
+ /** The codes of link() where a file system has no hard links (FAT, exFAT, some SMB and FUSE mounts). */
38
+ /** @type {ReadonlySet<string>} */
39
+ export const NO_HARD_LINKS = new Set(["EPERM", "ENOTSUP", "EOPNOTSUPP", "ENOSYS", "EXDEV", "EMLINK"]);
40
+
41
+ const READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
42
+
43
+ /** True when `real` is `dir` or lies inside it (both real paths). */
44
+ export function isInside(real, dir) {
45
+ const rel = relative(dir, real);
46
+ // "..foo" is a name inside the directory; only ".." as the first part leaves it
47
+ return rel === "" || (!isAbsolute(rel) && rel.split(sep)[0] !== "..");
48
+ }
49
+
50
+ /**
51
+ * The allowed directories as real paths; each must exist and be a directory.
52
+ * @param {string[]} dirs
53
+ * @param {string} cwd
54
+ * @returns {Promise<string[]>}
55
+ */
56
+ export async function allowedDirs(dirs, cwd) {
57
+ const out = [];
58
+ for (const dir of dirs) {
59
+ let real;
60
+ try {
61
+ real = await realpath(resolve(cwd, dir));
62
+ } catch {
63
+ throw new CliError("usage", "ALLOW_DIR_NOT_FOUND", `--allow-dir ${shortName(dir)}: not found`);
64
+ }
65
+ if (!(await stat(real)).isDirectory()) {
66
+ throw new CliError("usage", "ALLOW_DIR_NOT_DIRECTORY", `--allow-dir ${shortName(dir)}: not a directory`);
67
+ }
68
+ out.push(real);
69
+ }
70
+ return out;
71
+ }
72
+
73
+ /** Refuses a real path outside the allowed directories (none given: every path is allowed). */
74
+ function checkAllowed(real, allow, path) {
75
+ if (allow.length > 0 && !allow.some((dir) => isInside(real, dir))) {
76
+ // the directories by their base names, as every path in a message
77
+ throw new CliError("io", "OUTSIDE_ALLOWED_DIR", `${shortName(path)}: outside the allowed directories (--allow-dir ${allow.map(shortName).join(", ")})`);
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Reads a regular file of at most `maxBytes` bytes.
83
+ * @param {string} path
84
+ * @param {{ cwd: string, allow: string[], maxBytes: number, limit?: string, hardLinks?: boolean }} options `limit`: the limit's name for
85
+ * the message; `hardLinks: false` refuses a file with more than one name (default true)
86
+ * @returns {Promise<Uint8Array>}
87
+ */
88
+ export async function readSafe(path, { cwd, allow, maxBytes, limit = "fileBytes", hardLinks = true }) {
89
+ const full = resolve(cwd, path);
90
+ let real;
91
+ try {
92
+ real = await realpath(full);
93
+ } catch (e) {
94
+ throw e?.code === "ENOENT" ? new CliError("io", "NOT_FOUND", `${shortName(path)}: not found`) : e;
95
+ }
96
+ checkAllowed(real, allow, path);
97
+ const handle = await open(real, READ_FLAGS);
98
+ try {
99
+ const info = await handle.stat();
100
+ if (!info.isFile()) {
101
+ throw new CliError("io", "NOT_REGULAR_FILE", `${shortName(path)}: not a regular file`);
102
+ }
103
+ const now = await stat(real);
104
+ // the path again after the open: a directory on the way replaced by a link in between
105
+ // gives another real path, the file replaced another device or inode
106
+ const again = await realpath(full).catch(() => null);
107
+ if (now.dev !== info.dev || now.ino !== info.ino || again !== real) {
108
+ throw new CliError("io", "CHANGED", `${shortName(path)}: changed while it was opened`);
109
+ }
110
+ if (!hardLinks && info.nlink > 1) {
111
+ throw new CliError("io", "HARD_LINK", `${shortName(path)}: has more than one name (a hard link); not read`);
112
+ }
113
+ if (info.size > maxBytes) {
114
+ throw tooLarge(path, info.size, maxBytes, limit);
115
+ }
116
+ // the size the file had at the check, plus one byte: a file that has more by then grew (or, as
117
+ // a file of /proc, says it has none): over the limit it is refused as too large, else as changed,
118
+ // never cut
119
+ const buffer = new Uint8Array(Math.min(maxBytes + 1, info.size + 1));
120
+ let length = 0;
121
+ for (;;) {
122
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);
123
+ if (bytesRead === 0) {
124
+ break;
125
+ }
126
+ length += bytesRead;
127
+ if (length > maxBytes) {
128
+ throw tooLarge(path, length, maxBytes, limit);
129
+ }
130
+ if (length > info.size) {
131
+ throw new CliError("io", "CHANGED", `${shortName(path)}: changed while it was read (it has more than the ${info.size.toLocaleString("en-US")} bytes it had)`);
132
+ }
133
+ }
134
+ return buffer.subarray(0, length);
135
+ } finally {
136
+ await handle.close();
137
+ }
138
+ }
139
+
140
+ /** A file over its limit, named by its base name. */
141
+ const tooLarge = (path, size, max, limit) => new CliError("limit", "LIMIT_EXCEEDED", `${shortName(path)}: ${limitText(size, max, "bytes", `limits.${limit}`)}`);
142
+
143
+ /**
144
+ * Reads stdin up to `maxBytes` bytes.
145
+ * @param {AsyncIterable<Uint8Array>} stdin
146
+ * @param {number} maxBytes
147
+ * @param {string} [limit]
148
+ */
149
+ export async function readStdin(stdin, maxBytes, limit = "fileBytes") {
150
+ const chunks = [];
151
+ let length = 0;
152
+ for await (const chunk of stdin) {
153
+ length += chunk.length;
154
+ if (length > maxBytes) {
155
+ throw tooLarge("-", length, maxBytes, limit);
156
+ }
157
+ chunks.push(chunk);
158
+ }
159
+ const out = new Uint8Array(length);
160
+ let at = 0;
161
+ for (const chunk of chunks) {
162
+ out.set(chunk, at);
163
+ at += chunk.length;
164
+ }
165
+ return out;
166
+ }
167
+
168
+ /**
169
+ * The name of writeSafe's temporary files: ".<up to 50 characters of the target's name>.<pid>-<random>.tmp".
170
+ * A write takes seconds; one older than an hour was left by a process that was killed during it.
171
+ */
172
+ export const TEMP_FILE_NAME = /^\..+\.\d+-[0-9a-z]{1,8}\.tmp$/;
173
+
174
+ /**
175
+ * A temporary file's name for the target `name` (TEMP_FILE_NAME). It stays within a file name's 255
176
+ * bytes, however long the target's name is: 50 characters of at most 4 bytes each, then about 25 for
177
+ * the process, a random part and ".tmp". A longer name keeps its first and its last 25 characters,
178
+ * so the temporary file still shows where it belongs and what it is (pivotkit-server's random
179
+ * prefix, its ".pivotkit-out.<format>" mark).
180
+ * @param {string} name the target's base name
181
+ */
182
+ export function tempFileName(name) {
183
+ const chars = Array.from(name);
184
+ const stem = chars.length <= 50 ? name : [...chars.slice(0, 25), ...chars.slice(-25)].join("");
185
+ return `.${stem}.${process.pid}-${Math.random().toString(36).slice(2, 10) || "0"}.tmp`;
186
+ }
187
+
188
+ /**
189
+ * Whether a file name is one of Windows' reserved device names (CON, PRN, AUX, NUL, COM1 to COM9,
190
+ * COM¹ to COM³, LPT1 to LPT9, LPT¹ to LPT³, in any case), also followed by an extension (NUL.txt and
191
+ * NUL.tar.gz are NUL): in every directory it names the device, not a file there (Microsoft's
192
+ * "Naming Files, Paths, and Namespaces"). Trailing dots and spaces are removed first, as Windows
193
+ * does with a name's end.
194
+ * @param {string} name a base name
195
+ */
196
+ export function isWindowsDevice(name) {
197
+ return /^(con|prn|aux|nul|com[1-9\u00b9\u00b2\u00b3]|lpt[1-9\u00b9\u00b2\u00b3])(\..*)?$/i.test(name.replace(/[. ]+$/, ""));
198
+ }
199
+
200
+ /**
201
+ * Writes `bytes` to `path`: into a new temporary file in the target's directory, then renamed over it;
202
+ * with `exclusive`, linked into place instead (linkNew), which fails when a file is there (also one
203
+ * made between the check and the write), so nothing is replaced: `EXISTS`.
204
+ * @param {string} path
205
+ * @param {Uint8Array} bytes
206
+ * @param {{ cwd: string, allow: string[], exclusive?: boolean, mode?: number }} options `mode`: the new file's
207
+ * permissions (0o600: only its owner reads it), also when it replaces one; default the replaced file's, else 0o644
208
+ * @returns {Promise<string>} the real path written
209
+ */
210
+ export async function writeSafe(path, bytes, { cwd, allow, exclusive = false, mode }) {
211
+ const full = resolve(cwd, path);
212
+ let dir;
213
+ try {
214
+ dir = await realpath(dirname(full));
215
+ } catch {
216
+ // below the working directory: name it as typed and how to make it; elsewhere no path at all
217
+ const parent = relative(cwd, dirname(full));
218
+ const inside = parent !== "" && !parent.startsWith("..") && !isAbsolute(parent);
219
+ throw new CliError("io", "NOT_FOUND", inside ? `${shortName(path)}: the directory ${JSON.stringify(printable(parent))} does not exist: create it first (mkdir -p ${printable(parent)})` : `${shortName(path)}: its directory does not exist`);
220
+ }
221
+ const target = join(dir, basename(full));
222
+ checkAllowed(target, allow, path);
223
+ if (process.platform === "win32" && isWindowsDevice(basename(full))) {
224
+ throw new CliError("io", "SPECIAL_FILE", `${shortName(path)}: exists and is a device or another special file; not replaced`);
225
+ }
226
+ const existing = await lstat(target).catch((e) => (e.code === "ENOENT" ? null : Promise.reject(e)));
227
+ if (existing && exclusive) {
228
+ throw new CliError("io", "EXISTS", `${shortName(path)}: is already there; not replaced`);
229
+ }
230
+ if (existing && !existing.isFile()) {
231
+ const what = existing.isSymbolicLink() ? "a symbolic link" : existing.isDirectory() ? "a directory" : "a device or another special file";
232
+ throw new CliError("io", existing.isSymbolicLink() || existing.isDirectory() ? "NOT_REGULAR_FILE" : "SPECIAL_FILE", `${shortName(path)}: exists and is ${what}; not replaced`);
233
+ }
234
+ const temp = join(dir, tempFileName(basename(full)));
235
+ const fileMode = mode ?? (existing ? existing.mode & 0o777 : 0o644);
236
+ await createFile(temp, bytes, fileMode);
237
+ try {
238
+ if (exclusive) {
239
+ await linkNew(temp, target, bytes, fileMode);
240
+ } else {
241
+ await rename(temp, target);
242
+ }
243
+ } catch (e) {
244
+ await unlink(temp).catch(() => undefined);
245
+ throw e.code === "EEXIST" ? new CliError("io", "EXISTS", `${shortName(path)}: is already there; not replaced`) : e;
246
+ }
247
+ return target;
248
+ }
249
+
250
+ /** Creates `path` with `bytes` (O_EXCL, never through a symbolic link), synced; removed again when the write fails. */
251
+ async function createFile(path, bytes, mode) {
252
+ const handle = await open(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), mode);
253
+ try {
254
+ await handle.writeFile(bytes);
255
+ await handle.sync();
256
+ } catch (e) {
257
+ await handle.close();
258
+ await unlink(path).catch(() => undefined);
259
+ throw e;
260
+ }
261
+ await handle.close();
262
+ }
263
+
264
+ /**
265
+ * Gives the temporary file its name with link(), which never replaces: a file that appeared since
266
+ * the check stays as it is. Where the file system has no hard links, the name itself is created
267
+ * exclusively and written; a reader at that moment may see it before its bytes are written.
268
+ */
269
+ async function linkNew(temp, target, bytes, mode) {
270
+ try {
271
+ await fileMeans.link(temp, target);
272
+ } catch (e) {
273
+ if (!NO_HARD_LINKS.has(/** @type {any} */ (e)?.code)) {
274
+ throw e;
275
+ }
276
+ await createFile(target, bytes, mode);
277
+ }
278
+ // the file has its name: a temporary file that cannot be removed stays behind (TEMP_FILE_NAME)
279
+ await fileMeans.unlink(temp).catch(() => undefined);
280
+ }
281
+
282
+ /** The characters a name of writeNew keeps (parentheses too: "Orders (fake backend)"); the others become "-". */
283
+ const NAME_CHARS = /[^A-Za-z0-9 ._()-]/g;
284
+
285
+ /**
286
+ * A file name from a name given from outside: letters, digits, space, ".", "_", "-" and parentheses only, no
287
+ * leading dot, at most `max` characters; "report" when nothing is left.
288
+ * @param {unknown} name
289
+ * @param {number} [max]
290
+ */
291
+ export function cleanFileName(name, max = 80) {
292
+ const clean = String(name ?? "").normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(NAME_CHARS, "-").replace(/-{2,}/g, "-").replace(/^[.\s-]+|[.\s-]+$/g, "").slice(0, max).trim();
293
+ return clean || "report";
294
+ }
295
+
296
+ /**
297
+ * Writes `bytes` as a new file in `dir` (a real path), never replacing one: `<name>.<extension>`, or
298
+ * with "-2", "-3" ... when the name is taken (at most `tries`); each try is writeSafe's exclusive
299
+ * write, so a file that appears in between is never replaced.
300
+ * @param {string} dir a directory's real path
301
+ * @param {string} name the file's name without extension (cleaned with cleanFileName)
302
+ * @param {string} extension without the dot
303
+ * @param {Uint8Array} bytes
304
+ * @param {{ prefix?: string, tries?: number, mode?: number }} [options] `prefix`: put before the name (a random part);
305
+ * `mode`: the new file's permissions (writeSafe's, default 0o644)
306
+ * @returns {Promise<string>} the file's base name
307
+ */
308
+ export async function writeNew(dir, name, extension, bytes, { prefix = "", tries = 100, mode } = {}) {
309
+ const stem = `${prefix}${cleanFileName(name)}`;
310
+ for (let n = 1; n <= tries; n++) {
311
+ const base = `${stem}${n === 1 ? "" : `-${n}`}.${extension}`;
312
+ try {
313
+ await writeSafe(base, bytes, { cwd: dir, allow: [dir], exclusive: true, mode });
314
+ return base;
315
+ } catch (e) {
316
+ // a device's name (Windows' NUL, CON ...) is taken as well: the next name
317
+ if (e?.code !== "EXISTS" && e?.code !== "SPECIAL_FILE") {
318
+ throw e;
319
+ }
320
+ }
321
+ }
322
+ throw new CliError("io", "EXISTS", `${shortName(stem)}: ${tries} files of this name exist already`);
323
+ }
@@ -0,0 +1,25 @@
1
+ import { CodedError } from "pivotkit-core/internal";
2
+ export type ErrorKind = "usage" | "io" | "limit" | "template" | "remote" | "internal";
3
+ /** @typedef {"usage" | "io" | "limit" | "template" | "remote" | "internal"} ErrorKind */
4
+ /** @extends {CodedError<string, undefined>} */
5
+ export declare class CliError extends CodedError<string, undefined> {
6
+ kind: ErrorKind;
7
+ /**
8
+ * @param {ErrorKind} kind
9
+ * @param {string} code a stable name, e.g. NOT_FOUND, OUTSIDE_ALLOWED_DIR, UNKNOWN_OPTION
10
+ * @param {string} message
11
+ */
12
+ constructor(kind: ErrorKind, code: string, message: string);
13
+ }
14
+ /** Text from a file, a view or the data, safe to print: no control or direction characters, capped. */
15
+ export declare function printable(text: any): string;
16
+ /** A path as messages name it: its base name only. */
17
+ export declare const shortName: (path: any) => string;
18
+ /**
19
+ * Any error as a CliError: pivotkit-core's by their code, Node's file errors by theirs (with the
20
+ * file's base name, never its content), anything else as internal.
21
+ * @param {unknown} error
22
+ * @param {string} [path] the file it is about
23
+ * @returns {CliError}
24
+ */
25
+ export declare function asCliError(error: unknown, path?: string): CliError;
@@ -0,0 +1,32 @@
1
+ export { NO_HARD_LINKS, TEMP_FILE_NAME, allowedDirs, cleanFileName, isInside, readSafe, readStdin, writeNew, writeSafe } from "./safe-files.js";
2
+ export { CliError, asCliError, printable, shortName } from "./errors.js";
3
+ /** The data formats the front ends read, by extension. */
4
+ export declare const DATA_FORMATS: readonly string[];
5
+ /**
6
+ * Reader notes that only say how a file was read (its encoding, separator, sheet): "info". The others
7
+ * say the data differs from the file (a column renamed or dropped, text cut, values not converted):
8
+ * warnings.
9
+ */
10
+ export declare const INFO_NOTES: Readonly<Set<string>>;
11
+ /**
12
+ * The bytes of a data file as an import table (pivotkit-core/import with pivotkit-xlsx), with the
13
+ * reader's notes as findings named by the file's base name.
14
+ * @param {Uint8Array} bytes
15
+ * @param {string} name the file's name; its extension (or `format`) says how to read it
16
+ * @param {{ format?: string, sheet?: string, timeZone?: string, limits?: Partial<import("pivotkit-core").Limits> }} [options]
17
+ * @returns {Promise<{ table: any, notes: Array<{ severity: "info" | "warning", code: string, path: string, message: string }> }>}
18
+ */
19
+ export declare function readTable(bytes: Uint8Array, name: string, { format, sheet, timeZone, limits }?: {
20
+ format?: string;
21
+ sheet?: string;
22
+ timeZone?: string;
23
+ limits?: Partial<import("pivotkit-core").Limits>;
24
+ }): Promise<{
25
+ table: any;
26
+ notes: Array<{
27
+ severity: "info" | "warning";
28
+ code: string;
29
+ path: string;
30
+ message: string;
31
+ }>;
32
+ }>;
package/types/net.d.ts ADDED
@@ -0,0 +1,73 @@
1
+ /**
2
+ * An IP address as its bytes, or null. Brackets and a zone ("%eth0") are dropped first.
3
+ * @param {string} text
4
+ * @returns {{ v: 4 | 6, bytes: number[] } | null}
5
+ */
6
+ export declare function ipBytes(text: string): {
7
+ v: 4 | 6;
8
+ bytes: number[];
9
+ } | null;
10
+ /**
11
+ * Whether a host is loopback.
12
+ *
13
+ * By default it reads a host as a URL or the configuration writes it: "localhost", an IPv4 address
14
+ * of 127.0.0.0/8 or "::1", brackets allowed ("[::1]"), any case. Only these spellings: a name such as
15
+ * "127.example.com" is no loopback, and neither is an IPv4-mapped "[::ffff:7f00:1]".
16
+ *
17
+ * `address: true` reads an IP address a lookup gave or a socket reached: every spelling counts, a
18
+ * zone is dropped, and the IPv4-mapped ::ffff:127.0.0.0/104 is loopback too. A name never is.
19
+ * @param {string} host
20
+ * @param {{ address?: boolean }} [how]
21
+ */
22
+ export declare function isLoopback(host: string, how?: {
23
+ address?: boolean;
24
+ }): boolean;
25
+ /**
26
+ * A Retry-After header in seconds: a number of seconds, or an HTTP date (one that has passed is 0).
27
+ * Null without one and for one that is neither. Each caller caps the result by its own rule.
28
+ *
29
+ * `maxDigits` is the longest text read as a number of seconds; a longer one is read as a date.
30
+ * @param {unknown} value
31
+ * @param {{ maxDigits?: number }} [how]
32
+ * @returns {number | null}
33
+ */
34
+ export declare function retryAfterSeconds(value: unknown, { maxDigits }?: {
35
+ maxDigits?: number;
36
+ }): number | null;
37
+ /**
38
+ * The system code of a connection that failed (ECONNREFUSED, UND_ERR_SOCKET, a TLS code), or null.
39
+ * `client` says where to look (CODE_PLACES); the first code `accept` takes wins.
40
+ * @param {unknown} error
41
+ * @param {{ client: "node" | "fetch", accept?: (code: unknown) => boolean }} how by default any code that is there
42
+ * @returns {unknown}
43
+ */
44
+ export declare function networkCodeOf(error: unknown, { client, accept }: {
45
+ client: "node" | "fetch";
46
+ accept?: (code: unknown) => boolean;
47
+ }): unknown;
48
+ /**
49
+ * The system codes of a failed connection that pivotkit knows, each once, with what it means:
50
+ *
51
+ * - `text`: the command line's words for it (remote mode's "the server cannot be reached: ...")
52
+ * - `retry`: pivotkit-server's guardedFetch marks a request that failed so as transient
53
+ * - `passes`: a source's load that failed so may pass by itself, so last good data may stand in
54
+ * (sources/run.js; Node's and undici's codes, also on a cause or an AggregateError's errors)
55
+ *
56
+ * The two readings of "may work again" differ by code; each stays as its caller had it.
57
+ * @type {Readonly<Record<string, Readonly<{ text?: string, retry?: true, passes?: true }>>>}
58
+ */
59
+ export declare const NETWORK_FAILURES: Readonly<Record<string, Readonly<{
60
+ text?: string;
61
+ retry?: true;
62
+ passes?: true;
63
+ }>>>;
64
+ /**
65
+ * What pivotkit knows of a failed connection's code (NETWORK_FAILURES), or an empty entry.
66
+ * @param {unknown} code
67
+ * @returns {Readonly<{ text?: string, retry?: true, passes?: true }>}
68
+ */
69
+ export declare const networkFailureOf: (code: unknown) => Readonly<{
70
+ text?: string;
71
+ retry?: true;
72
+ passes?: true;
73
+ }>;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The extra field of the REST service's protected-resource metadata (RFC 9728 lets a resource add
3
+ * its own) that names the public client `pivotkit login` signs in with (rest.signIn.clientId).
4
+ */
5
+ export declare const SIGN_IN_CLIENT_FIELD = "pivotkit_client_id";
6
+ /** A sign-in client's ID: printable, no spaces, at most 200 characters. */
7
+ export declare const CLIENT_ID_SYNTAX: RegExp;
8
+ /** The REST service's path under its origin. */
9
+ export declare const REST_BASE = "/api/v1";
10
+ /** A source id: letters, digits, "_", "-" and ".", at most 64, starting with a letter or digit. */
11
+ export declare const SOURCE_ID: RegExp;
12
+ /** What a bearer token may hold (RFC 6750's b64token): a token with other characters never matches a request. */
13
+ export declare const TOKEN_SYNTAX: RegExp;
14
+ /** Why a token outside TOKEN_SYNTAX does not work. */
15
+ export declare const TOKEN_SYNTAX_TEXT = "has characters a bearer token cannot carry (letters, digits and - . _ ~ + / only, = at the end), so no request could send it";
16
+ /** The codes the REST layer adds to the operations', with their status. */
17
+ export declare const REST_ERRORS: Readonly<{
18
+ INVALID_TOKEN: 401;
19
+ INSUFFICIENT_SCOPE: 403;
20
+ FORBIDDEN_HOST: 403;
21
+ FORBIDDEN_ORIGIN: 403;
22
+ NOT_FOUND: 404;
23
+ METHOD_NOT_ALLOWED: 405;
24
+ BODY_TOO_LARGE: 413;
25
+ UNSUPPORTED_MEDIA_TYPE: 415;
26
+ VIEW_HAS_ERRORS: 422;
27
+ RATE_LIMITED: 429;
28
+ AUTH_NOT_READY: 503;
29
+ }>;
30
+ /** Every code a problem can carry. */
31
+ export declare const PROBLEM_CODES: readonly string[];
32
+ /** Whether a host is loopback: pivotkit-node/net says which spellings count. */
33
+ export { isLoopback } from "./net.js";
34
+ /**
35
+ * The RFC 9728 metadata address of a resource: /.well-known/oauth-protected-resource before its path
36
+ * (https://host/api/v1 has it at https://host/.well-known/oauth-protected-resource/api/v1).
37
+ * @param {string | URL} resource
38
+ */
39
+ export declare function resourceMetadataUrlOf(resource: string | URL): string;
@@ -0,0 +1,102 @@
1
+ import { link, unlink } from "node:fs/promises";
2
+ /** The calls tests replace: a file system without hard links, a temporary file that cannot be removed. */
3
+ export declare const fileMeans: {
4
+ link: typeof link;
5
+ unlink: typeof unlink;
6
+ };
7
+ /** The codes of link() where a file system has no hard links (FAT, exFAT, some SMB and FUSE mounts). */
8
+ /** @type {ReadonlySet<string>} */
9
+ export declare const NO_HARD_LINKS: ReadonlySet<string>;
10
+ /** True when `real` is `dir` or lies inside it (both real paths). */
11
+ export declare function isInside(real: any, dir: any): boolean;
12
+ /**
13
+ * The allowed directories as real paths; each must exist and be a directory.
14
+ * @param {string[]} dirs
15
+ * @param {string} cwd
16
+ * @returns {Promise<string[]>}
17
+ */
18
+ export declare function allowedDirs(dirs: string[], cwd: string): Promise<string[]>;
19
+ /**
20
+ * Reads a regular file of at most `maxBytes` bytes.
21
+ * @param {string} path
22
+ * @param {{ cwd: string, allow: string[], maxBytes: number, limit?: string, hardLinks?: boolean }} options `limit`: the limit's name for
23
+ * the message; `hardLinks: false` refuses a file with more than one name (default true)
24
+ * @returns {Promise<Uint8Array>}
25
+ */
26
+ export declare function readSafe(path: string, { cwd, allow, maxBytes, limit, hardLinks }: {
27
+ cwd: string;
28
+ allow: string[];
29
+ maxBytes: number;
30
+ limit?: string;
31
+ hardLinks?: boolean;
32
+ }): Promise<Uint8Array>;
33
+ /**
34
+ * Reads stdin up to `maxBytes` bytes.
35
+ * @param {AsyncIterable<Uint8Array>} stdin
36
+ * @param {number} maxBytes
37
+ * @param {string} [limit]
38
+ */
39
+ export declare function readStdin(stdin: AsyncIterable<Uint8Array>, maxBytes: number, limit?: string): Promise<Uint8Array<ArrayBuffer>>;
40
+ /**
41
+ * The name of writeSafe's temporary files: ".<up to 50 characters of the target's name>.<pid>-<random>.tmp".
42
+ * A write takes seconds; one older than an hour was left by a process that was killed during it.
43
+ */
44
+ export declare const TEMP_FILE_NAME: RegExp;
45
+ /**
46
+ * A temporary file's name for the target `name` (TEMP_FILE_NAME). It stays within a file name's 255
47
+ * bytes, however long the target's name is: 50 characters of at most 4 bytes each, then about 25 for
48
+ * the process, a random part and ".tmp". A longer name keeps its first and its last 25 characters,
49
+ * so the temporary file still shows where it belongs and what it is (pivotkit-server's random
50
+ * prefix, its ".pivotkit-out.<format>" mark).
51
+ * @param {string} name the target's base name
52
+ */
53
+ export declare function tempFileName(name: string): string;
54
+ /**
55
+ * Whether a file name is one of Windows' reserved device names (CON, PRN, AUX, NUL, COM1 to COM9,
56
+ * COM¹ to COM³, LPT1 to LPT9, LPT¹ to LPT³, in any case), also followed by an extension (NUL.txt and
57
+ * NUL.tar.gz are NUL): in every directory it names the device, not a file there (Microsoft's
58
+ * "Naming Files, Paths, and Namespaces"). Trailing dots and spaces are removed first, as Windows
59
+ * does with a name's end.
60
+ * @param {string} name a base name
61
+ */
62
+ export declare function isWindowsDevice(name: string): boolean;
63
+ /**
64
+ * Writes `bytes` to `path`: into a new temporary file in the target's directory, then renamed over it;
65
+ * with `exclusive`, linked into place instead (linkNew), which fails when a file is there (also one
66
+ * made between the check and the write), so nothing is replaced: `EXISTS`.
67
+ * @param {string} path
68
+ * @param {Uint8Array} bytes
69
+ * @param {{ cwd: string, allow: string[], exclusive?: boolean, mode?: number }} options `mode`: the new file's
70
+ * permissions (0o600: only its owner reads it), also when it replaces one; default the replaced file's, else 0o644
71
+ * @returns {Promise<string>} the real path written
72
+ */
73
+ export declare function writeSafe(path: string, bytes: Uint8Array, { cwd, allow, exclusive, mode }: {
74
+ cwd: string;
75
+ allow: string[];
76
+ exclusive?: boolean;
77
+ mode?: number;
78
+ }): Promise<string>;
79
+ /**
80
+ * A file name from a name given from outside: letters, digits, space, ".", "_", "-" and parentheses only, no
81
+ * leading dot, at most `max` characters; "report" when nothing is left.
82
+ * @param {unknown} name
83
+ * @param {number} [max]
84
+ */
85
+ export declare function cleanFileName(name: unknown, max?: number): string;
86
+ /**
87
+ * Writes `bytes` as a new file in `dir` (a real path), never replacing one: `<name>.<extension>`, or
88
+ * with "-2", "-3" ... when the name is taken (at most `tries`); each try is writeSafe's exclusive
89
+ * write, so a file that appears in between is never replaced.
90
+ * @param {string} dir a directory's real path
91
+ * @param {string} name the file's name without extension (cleaned with cleanFileName)
92
+ * @param {string} extension without the dot
93
+ * @param {Uint8Array} bytes
94
+ * @param {{ prefix?: string, tries?: number, mode?: number }} [options] `prefix`: put before the name (a random part);
95
+ * `mode`: the new file's permissions (writeSafe's, default 0o644)
96
+ * @returns {Promise<string>} the file's base name
97
+ */
98
+ export declare function writeNew(dir: string, name: string, extension: string, bytes: Uint8Array, { prefix, tries, mode }?: {
99
+ prefix?: string;
100
+ tries?: number;
101
+ mode?: number;
102
+ }): Promise<string>;