soltask 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/config.js ADDED
@@ -0,0 +1,365 @@
1
+ import { closeSync, constants, fstatSync, openSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { CliError, EXIT_AUTH, EXIT_RUNTIME, EXIT_VALIDATION } from "./errors.js";
5
+ import { O_NOFOLLOW_SAFE, O_NONBLOCK_SAFE, tryLstat, writeFileAtomic } from "./fsutil.js";
6
+ import { errorMessage, isObject, nonEmptyString, oneLine } from "./util.js";
7
+ export const ENV_SERVER = "SOLTASK_SERVER";
8
+ export const ENV_CONFIG = "SOLTASK_CONFIG";
9
+ export const ENV_COOKIE = "SOLTASK_COOKIE";
10
+ export const ENV_UNLOCK_KEY = "SOLTASK_UNLOCK_KEY";
11
+ export const ENV_TOKEN = "SOLTASK_TOKEN";
12
+ export const ENV_NSEC = "SOLTASK_NSEC";
13
+ export const ENV_COMMUNITY = "SOLTASK_COMMUNITY";
14
+ export const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
15
+ /** Config keys that belong to one login session; dropped together on logout. */
16
+ export const SESSION_CONFIG_KEYS = [
17
+ "cookie_name",
18
+ "cookie_value",
19
+ "unlock",
20
+ "token",
21
+ "pubkey",
22
+ "profile",
23
+ "communities",
24
+ "saved_at",
25
+ ];
26
+ /** Secrets that must never be persisted to disk regardless of caller input. */
27
+ const FORBIDDEN_CONFIG_KEYS = new Set(["nsec", "password"]);
28
+ /**
29
+ * Hides credentials a person may have typed into a URL before the URL is echoed in a message.
30
+ */
31
+ function redactUrl(raw) {
32
+ return raw.replace(/(^|[a-z][a-z0-9+.-]*:\/\/+|\/+|\s)[^\s?#]*@/gi, "$1***@");
33
+ }
34
+ /**
35
+ * Validates and normalizes a server base URL: http(s) only, no credentials, query, or fragment.
36
+ * A deliberate base path survives (`https://board.example.com/sub/` becomes `https://board.example.com/sub`);
37
+ * the trailing slash does not.
38
+ */
39
+ export function normalizeServerUrl(raw) {
40
+ const text = typeof raw === "string" ? raw.trim() : "";
41
+ if (text === "") {
42
+ throw new CliError(`Server URL is not configured. Pass --server URL, set ${ENV_SERVER}, or run 'login'.`, {
43
+ exitCode: EXIT_AUTH,
44
+ });
45
+ }
46
+ // WHATWG `new URL` silently strips ASCII tabs and line breaks; reject embedded control characters explicitly.
47
+ // eslint-disable-next-line no-control-regex -- rejecting control characters in URLs is intentional
48
+ if (/[\u0000-\u001f\u007f-\u009f]/.test(text)) {
49
+ throw new CliError(`Invalid server URL ${JSON.stringify(oneLine(redactUrl(text)))}; expected http(s)://host[:port]`, {
50
+ exitCode: EXIT_VALIDATION,
51
+ });
52
+ }
53
+ const authority = /^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i.exec(text)?.[1] ?? "";
54
+ if (authority.includes("@") || /[?#]/.test(text)) {
55
+ throw new CliError("Server URL must not contain credentials, query parameters, or fragments", {
56
+ exitCode: EXIT_VALIDATION,
57
+ });
58
+ }
59
+ if (!/^https?:\/\/[^/?#]/i.test(text)) {
60
+ throw new CliError(`Invalid server URL ${JSON.stringify(redactUrl(text))}; expected http(s)://host[:port]`, {
61
+ exitCode: EXIT_VALIDATION,
62
+ });
63
+ }
64
+ let url;
65
+ try {
66
+ url = new URL(text);
67
+ }
68
+ catch {
69
+ throw new CliError(`Invalid server URL ${JSON.stringify(redactUrl(text))}; expected http(s)://host[:port]`, {
70
+ exitCode: EXIT_VALIDATION,
71
+ });
72
+ }
73
+ if ((url.protocol !== "http:" && url.protocol !== "https:") || url.hostname === "") {
74
+ throw new CliError(`Invalid server URL ${JSON.stringify(redactUrl(text))}; expected http(s)://host[:port]`, {
75
+ exitCode: EXIT_VALIDATION,
76
+ });
77
+ }
78
+ if (url.port !== "" && (Number(url.port) < 1 || Number(url.port) > 65535)) {
79
+ throw new CliError(`Invalid server URL ${JSON.stringify(redactUrl(text))}; the port must be between 1 and 65535`, {
80
+ exitCode: EXIT_VALIDATION,
81
+ });
82
+ }
83
+ const path = url.pathname.replace(/\/+$/, "");
84
+ return `${url.protocol}//${url.host}${path}`;
85
+ }
86
+ /** `[scheme, hostname, port]` with the default port filled in, for exact origin comparison; null when not an http(s) URL. */
87
+ export function serverOrigin(url) {
88
+ let parsed;
89
+ try {
90
+ parsed = new URL(url);
91
+ }
92
+ catch {
93
+ return null;
94
+ }
95
+ const scheme = parsed.protocol.replace(/:$/, "");
96
+ if ((scheme !== "http" && scheme !== "https") || parsed.hostname === "") {
97
+ return null;
98
+ }
99
+ const port = parsed.port === "" ? (scheme === "https" ? 443 : 80) : Number(parsed.port);
100
+ return [scheme, parsed.hostname.toLowerCase(), port];
101
+ }
102
+ export function sameServerOrigin(a, b) {
103
+ const left = serverOrigin(a);
104
+ const right = serverOrigin(b);
105
+ return left !== null && right !== null && left.every((part, index) => part === right[index]);
106
+ }
107
+ /** True for plain `http:` to anything but loopback: credentials would cross the network in cleartext. */
108
+ export function isNonLoopbackHttp(url) {
109
+ let parsed;
110
+ try {
111
+ parsed = new URL(url);
112
+ }
113
+ catch {
114
+ return false;
115
+ }
116
+ const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, "");
117
+ return parsed.protocol === "http:" && !LOOPBACK_HOSTS.has(host);
118
+ }
119
+ function expandHome(path, home) {
120
+ if (path === "~") {
121
+ return home;
122
+ }
123
+ return path.startsWith("~/") || path.startsWith("~\\") ? join(home, path.slice(2)) : path;
124
+ }
125
+ /** `--config`, then `SOLTASK_CONFIG`, then `$XDG_CONFIG_HOME/soltask/config.json` (`%APPDATA%\soltask\config.json` on Windows). */
126
+ export function resolveConfigPath(cliConfig, context = {}) {
127
+ const env = context.env ?? process.env;
128
+ const platform = context.platform ?? process.platform;
129
+ const home = context.home ?? homedir();
130
+ if (cliConfig !== undefined && cliConfig !== null && cliConfig !== "") {
131
+ return expandHome(cliConfig, home);
132
+ }
133
+ const fromEnv = nonEmptyString(env[ENV_CONFIG]);
134
+ if (fromEnv !== undefined) {
135
+ return expandHome(fromEnv, home);
136
+ }
137
+ const base = platform === "win32"
138
+ ? (nonEmptyString(env["APPDATA"]) ?? join(home, ".config"))
139
+ : (nonEmptyString(env["XDG_CONFIG_HOME"]) ?? join(home, ".config"));
140
+ return join(base, "soltask", "config.json");
141
+ }
142
+ /** The directory holding the config file must be a real directory: through a link, credentials could leak. */
143
+ function refuseLinkedDirectory(path, action) {
144
+ const dir = dirname(path);
145
+ if (tryLstat(dir)?.isSymbolicLink() === true) {
146
+ throw new CliError(`Refusing to ${action} the config file through a symbolic link: ${dir}`, { exitCode: EXIT_RUNTIME });
147
+ }
148
+ }
149
+ /** Reads the config file; a missing file is an empty config, a symbolic link or a non-object is refused. */
150
+ export function loadConfig(path) {
151
+ let stats;
152
+ try {
153
+ refuseLinkedDirectory(path, "read");
154
+ stats = tryLstat(path);
155
+ }
156
+ catch (err) {
157
+ if (err instanceof CliError) {
158
+ throw err;
159
+ }
160
+ throw new CliError(`Could not read config file ${path}: ${errorMessage(err)}`, { exitCode: EXIT_RUNTIME });
161
+ }
162
+ if (stats === undefined) {
163
+ return {};
164
+ }
165
+ if (stats.isSymbolicLink()) {
166
+ throw new CliError(`Refusing to read config file through a symbolic link: ${path}`, { exitCode: EXIT_RUNTIME });
167
+ }
168
+ if (!stats.isFile()) {
169
+ throw new CliError(`Config path ${path} is not a regular file`, { exitCode: EXIT_RUNTIME });
170
+ }
171
+ let data;
172
+ try {
173
+ const fd = openSync(path, constants.O_RDONLY | O_NOFOLLOW_SAFE | O_NONBLOCK_SAFE);
174
+ try {
175
+ if (!fstatSync(fd).isFile()) {
176
+ throw new CliError(`Config path ${path} is not a regular file`, { exitCode: EXIT_RUNTIME });
177
+ }
178
+ const raw = readFileSync(fd, "utf8").replace(/^\uFEFF/, "");
179
+ data = raw.trim() === "" ? {} : JSON.parse(raw);
180
+ }
181
+ finally {
182
+ closeSync(fd);
183
+ }
184
+ }
185
+ catch (err) {
186
+ if (err instanceof CliError) {
187
+ throw err;
188
+ }
189
+ throw new CliError(`Could not read config file ${path}: ${errorMessage(err)}`, { exitCode: EXIT_RUNTIME });
190
+ }
191
+ if (!isObject(data)) {
192
+ throw new CliError(`Config file ${path} must hold a JSON object`, { exitCode: EXIT_RUNTIME });
193
+ }
194
+ return data;
195
+ }
196
+ /** Writes the config atomically with mode 0600 in a 0700 directory. Secret keys (`nsec`, `password`) are never persisted. */
197
+ export function saveConfig(path, data) {
198
+ const clean = {};
199
+ for (const [key, value] of Object.entries(data)) {
200
+ if (!FORBIDDEN_CONFIG_KEYS.has(key)) {
201
+ clean[key] = value;
202
+ }
203
+ }
204
+ try {
205
+ refuseLinkedDirectory(path, "write");
206
+ }
207
+ catch (err) {
208
+ if (err instanceof CliError) {
209
+ throw err;
210
+ }
211
+ throw new CliError(`Could not save config file ${path}: ${errorMessage(err)}`, { exitCode: EXIT_RUNTIME });
212
+ }
213
+ writeFileAtomic(path, `${JSON.stringify(clean, null, 2)}\n`, {
214
+ fileMode: 0o600,
215
+ dirMode: 0o700,
216
+ refuseSymlink: true,
217
+ label: "config file",
218
+ });
219
+ }
220
+ /** The config minus the keys of a login session. */
221
+ export function withoutSessionFields(cfg) {
222
+ const config = { ...cfg };
223
+ let removed = false;
224
+ for (const key of SESSION_CONFIG_KEYS) {
225
+ if (key in config) {
226
+ removed = true;
227
+ }
228
+ delete config[key];
229
+ }
230
+ return { config, removed };
231
+ }
232
+ /** Looks at the config file's type and permissions without reading it. */
233
+ export function inspectConfigFile(path, platform = process.platform) {
234
+ let stats;
235
+ try {
236
+ const dir = dirname(path);
237
+ if (tryLstat(dir)?.isSymbolicLink() === true) {
238
+ return { exists: true, ok: false, problem: "unsafe", detail: `${dir} is a symbolic link; soltask refuses to use it` };
239
+ }
240
+ stats = tryLstat(path);
241
+ }
242
+ catch (err) {
243
+ return { exists: true, ok: false, problem: "unsafe", detail: `Could not inspect ${path}: ${errorMessage(err)}` };
244
+ }
245
+ if (stats === undefined) {
246
+ return { exists: false, ok: true, detail: `No config file at ${path}` };
247
+ }
248
+ if (stats.isSymbolicLink()) {
249
+ return { exists: true, ok: false, problem: "unsafe", detail: `${path} is a symbolic link; soltask refuses to use it` };
250
+ }
251
+ if (!stats.isFile()) {
252
+ return { exists: true, ok: false, problem: "unsafe", detail: `${path} is not a regular file` };
253
+ }
254
+ if (platform === "win32") {
255
+ return {
256
+ exists: true,
257
+ ok: true,
258
+ detail: `Windows ACLs apply, POSIX modes are not enforced; keep ${path} readable by your account only`,
259
+ };
260
+ }
261
+ const mode = stats.mode & 0o777;
262
+ const ok = (mode & 0o077) === 0;
263
+ return { exists: true, ok, ...(ok ? {} : { problem: "permissions" }), detail: `0${mode.toString(8)} (${path})` };
264
+ }
265
+ /** A sentence to show when the config file deserves attention, or null when there is nothing to say. */
266
+ export function configPermWarning(path, platform = process.platform) {
267
+ const check = inspectConfigFile(path, platform);
268
+ if (!check.exists) {
269
+ return null;
270
+ }
271
+ if (!check.ok) {
272
+ return check.problem === "permissions" ? `Config file permissions are too open: ${check.detail}; run chmod 600 on it` : check.detail;
273
+ }
274
+ return platform === "win32" ? check.detail : null;
275
+ }
276
+ /** `--server`, then `SOLTASK_SERVER`, then the saved server, normalized. */
277
+ export function resolveServer(flagServer, cfg, env = process.env) {
278
+ const raw = nonEmptyString(flagServer) ?? nonEmptyString(env[ENV_SERVER]) ?? nonEmptyString(cfg["server"]);
279
+ return normalizeServerUrl(raw);
280
+ }
281
+ /** `--community`, then `SOLTASK_COMMUNITY`, then saved default `community` in config. */
282
+ export function resolveCommunity(flagCommunity, cfg, env = process.env) {
283
+ return nonEmptyString(flagCommunity) ?? nonEmptyString(env[ENV_COMMUNITY]) ?? nonEmptyString(cfg["community"]);
284
+ }
285
+ /** Parses a `name=value` cookie string (stripping any trailing attributes after `;`), or returns null when invalid. */
286
+ export function parseCookiePair(raw) {
287
+ const firstPart = raw.split(";", 1)[0]?.trim() ?? "";
288
+ const eq = firstPart.indexOf("=");
289
+ if (eq <= 0) {
290
+ return null;
291
+ }
292
+ const name = firstPart.slice(0, eq).trim();
293
+ const value = firstPart.slice(eq + 1).trim();
294
+ if (name === "" || value === "" || /[\s;,]/.test(name) || /[\r\n]/.test(value)) {
295
+ return null;
296
+ }
297
+ return { name, value };
298
+ }
299
+ /** True when any session credential env var (`SOLTASK_COOKIE`, `SOLTASK_UNLOCK_KEY`, `SOLTASK_TOKEN`) is set. */
300
+ export function hasEnvCredentials(env = process.env) {
301
+ return (nonEmptyString(env[ENV_COOKIE]) !== undefined ||
302
+ nonEmptyString(env[ENV_UNLOCK_KEY]) !== undefined ||
303
+ nonEmptyString(env[ENV_TOKEN]) !== undefined);
304
+ }
305
+ /** True when the saved config holds session credentials (cookie+unlock or token). */
306
+ export function hasSavedCredentials(cfg) {
307
+ const hasCookie = nonEmptyString(cfg["cookie_name"]) !== undefined &&
308
+ nonEmptyString(cfg["cookie_value"]) !== undefined &&
309
+ nonEmptyString(cfg["unlock"]) !== undefined;
310
+ return hasCookie || nonEmptyString(cfg["token"]) !== undefined;
311
+ }
312
+ /**
313
+ * Resolves authentication credentials for `serverUrl`.
314
+ *
315
+ * Precedence:
316
+ * 1. `SOLTASK_COOKIE` (`name=value`) + `SOLTASK_UNLOCK_KEY` from the environment (not origin-bound).
317
+ * 2. `SOLTASK_TOKEN` from the environment (optional Bearer mode, not origin-bound).
318
+ * 3. Saved session in `cfg` (`cookie_name` + `cookie_value` + `unlock`, or saved `token`),
319
+ * strictly origin-bound so saved credentials are NEVER sent to a different `--server` origin.
320
+ */
321
+ export function resolveSession(cfg, serverUrl, env = process.env) {
322
+ if (serverOrigin(serverUrl) === null) {
323
+ return null;
324
+ }
325
+ const envCookieRaw = nonEmptyString(env[ENV_COOKIE]);
326
+ const envUnlock = nonEmptyString(env[ENV_UNLOCK_KEY]);
327
+ if (envCookieRaw !== undefined || envUnlock !== undefined) {
328
+ if (envCookieRaw !== undefined && envUnlock !== undefined) {
329
+ const parsed = parseCookiePair(envCookieRaw);
330
+ if (parsed !== null) {
331
+ return {
332
+ mode: "cookie",
333
+ source: "env",
334
+ cookieName: parsed.name,
335
+ cookieValue: parsed.value,
336
+ unlock: envUnlock,
337
+ };
338
+ }
339
+ }
340
+ const envTokenFallback = nonEmptyString(env[ENV_TOKEN]);
341
+ if (envTokenFallback !== undefined) {
342
+ return { mode: "bearer", source: "env", token: envTokenFallback };
343
+ }
344
+ return null;
345
+ }
346
+ const envToken = nonEmptyString(env[ENV_TOKEN]);
347
+ if (envToken !== undefined) {
348
+ return { mode: "bearer", source: "env", token: envToken };
349
+ }
350
+ const savedServer = nonEmptyString(cfg["server"]);
351
+ if (savedServer === undefined || !sameServerOrigin(serverUrl, savedServer)) {
352
+ return null;
353
+ }
354
+ const cookieName = nonEmptyString(cfg["cookie_name"]);
355
+ const cookieValue = nonEmptyString(cfg["cookie_value"]);
356
+ const unlock = nonEmptyString(cfg["unlock"]);
357
+ if (cookieName !== undefined && cookieValue !== undefined && unlock !== undefined) {
358
+ return { mode: "cookie", source: "config", cookieName, cookieValue, unlock };
359
+ }
360
+ const savedToken = nonEmptyString(cfg["token"]);
361
+ if (savedToken !== undefined) {
362
+ return { mode: "bearer", source: "config", token: savedToken };
363
+ }
364
+ return null;
365
+ }
@@ -0,0 +1,70 @@
1
+ import type { ApiClient, ApiClientOptions } from "./client.js";
2
+ import type { JsonObject } from "./util.js";
3
+ export type InputStream = NodeJS.ReadableStream & {
4
+ isTTY?: boolean;
5
+ };
6
+ export interface GlobalOptions {
7
+ server: string | undefined;
8
+ config: string | undefined;
9
+ community: string | undefined;
10
+ json: boolean;
11
+ dryRun: boolean;
12
+ waitLive: boolean;
13
+ }
14
+ /** Everything a command reads from the machine it runs on; tests substitute each piece. */
15
+ export interface RuntimeIO {
16
+ stdin: InputStream;
17
+ env: NodeJS.ProcessEnv;
18
+ cwd: string;
19
+ platform: NodeJS.Platform;
20
+ hostname: () => string;
21
+ nodeVersion: string;
22
+ clientOptions?: ApiClientOptions;
23
+ /** Test seam: how `--wait-live` or retry loops sleep. */
24
+ sleepFn?: (ms: number, signal?: AbortSignal) => Promise<void>;
25
+ }
26
+ export type OptionValue = string | boolean | readonly (string | boolean)[] | undefined;
27
+ export interface OptionSpec {
28
+ type: "boolean" | "string";
29
+ short?: string;
30
+ multiple?: boolean;
31
+ description: string;
32
+ /** Name of the value in help, e.g. `PATH`. */
33
+ placeholder?: string;
34
+ /** The only values accepted, checked for every string option that declares them; `--help` lists them. */
35
+ choices?: readonly string[];
36
+ /** What is used when the option is left out, as `--help` shows it. */
37
+ default?: string;
38
+ }
39
+ export interface CommandContext {
40
+ global: GlobalOptions;
41
+ values: Readonly<Record<string, OptionValue>>;
42
+ positionals: readonly string[];
43
+ io: RuntimeIO;
44
+ configPath: string;
45
+ /** The saved config, read on first use. Throws a `CliError` when the file cannot be used. */
46
+ config(): JsonObject;
47
+ /** An API client for the resolved server and session, built on first use. */
48
+ client(): ApiClient;
49
+ /** Resolved default community (`--community`, `SOLTASK_COMMUNITY`, then saved config `community`). */
50
+ community(): string | undefined;
51
+ flag(name: string): boolean;
52
+ opt(name: string): string | undefined;
53
+ optList(name: string): string[];
54
+ }
55
+ export type CommandHandler = (ctx: CommandContext) => Promise<number>;
56
+ export interface CommandSpec {
57
+ name: string;
58
+ summary: string;
59
+ /** Usage after the program name, e.g. `login [--nsec-stdin | --nsec-file PATH | --nsec VALUE]`. */
60
+ usage: string;
61
+ options?: Readonly<Record<string, OptionSpec>>;
62
+ /** Positional arguments after the command (and its subcommand): how few and how many. */
63
+ positionals?: {
64
+ min: number;
65
+ max: number;
66
+ };
67
+ /** A command with subcommands is only a namespace; each subcommand carries its own options and handler. */
68
+ subcommands?: readonly CommandSpec[];
69
+ handler?: CommandHandler;
70
+ }
@@ -0,0 +1 @@
1
+ export {};