@solidactions/cli 3.23.0 → 3.25.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.
@@ -499,6 +499,10 @@ async function docPushWithConfig(dir, options, config) {
499
499
  trackedMissing.push({ file: relPath, id: entry.id });
500
500
  continue;
501
501
  }
502
+ if (status === 401) {
503
+ process.stderr.write(chalk_1.default.red((0, api_1.authFailedLine)(config.host)) + '\n');
504
+ process.exit(1);
505
+ }
502
506
  process.stderr.write(chalk_1.default.red(`error: ${relPath}: ${data?.message ?? error.message}\n`));
503
507
  process.exit(1);
504
508
  }
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DEVICE_LOGIN_REFUSAL_MESSAGE = exports.LoginHostInvalidError = exports.LoginHostConflictError = exports.API_KEY_PROMPT = exports.selectWorkspaceInteractively = void 0;
6
+ exports.DEVICE_LOGIN_REFUSAL_MESSAGE = exports.LoginHostUserinfoError = exports.LoginHostInvalidError = exports.LoginHostConflictError = exports.API_KEY_PROMPT = exports.selectWorkspaceInteractively = void 0;
7
7
  exports.resolveLoginApiKey = resolveLoginApiKey;
8
8
  exports.clearConfig = clearConfig;
9
9
  exports.resolveLoginHost = resolveLoginHost;
@@ -95,6 +95,16 @@ class LoginHostInvalidError extends Error {
95
95
  }
96
96
  }
97
97
  exports.LoginHostInvalidError = LoginHostInvalidError;
98
+ class LoginHostUserinfoError extends Error {
99
+ label;
100
+ host;
101
+ constructor(label, host) {
102
+ super(`${label} "${(0, host_display_1.displayHost)(host)}" contains a username/password; remove "user:pass@" — the CLI authenticates with your API key.`);
103
+ this.label = label;
104
+ this.host = host;
105
+ }
106
+ }
107
+ exports.LoginHostUserinfoError = LoginHostUserinfoError;
98
108
  function resolveLoginHost(options, env = process.env) {
99
109
  const strip = (h) => h.trim().replace(/\/+$/, '');
100
110
  // Ruling 9: a non-empty value that strips to nothing is INVALID, never "absent".
@@ -105,9 +115,16 @@ function resolveLoginHost(options, env = process.env) {
105
115
  return value;
106
116
  };
107
117
  const rawEnv = env.SOLIDACTIONS_HOST;
108
- const envHost = rawEnv !== undefined && rawEnv.trim() !== '' ? usable(rawEnv, 'SOLIDACTIONS_HOST') : undefined;
118
+ const noUserinfo = (host, label) => {
119
+ if ((0, host_display_1.hostHasUserinfo)(host))
120
+ throw new LoginHostUserinfoError(label, host);
121
+ return host;
122
+ };
123
+ const envHost = rawEnv !== undefined && rawEnv.trim() !== ''
124
+ ? noUserinfo(usable(rawEnv, 'SOLIDACTIONS_HOST'), 'SOLIDACTIONS_HOST')
125
+ : undefined;
109
126
  const explicitHostFlag = (raw) => {
110
- const host = usable(raw, '--host');
127
+ const host = noUserinfo(usable(raw, '--host'), '--host');
111
128
  return { host, flag: `--host ${(0, host_display_1.displayHost)(host)}` };
112
129
  };
113
130
  const explicit = options.host !== undefined
@@ -142,6 +159,10 @@ function resolveLoginHostOrExit(options) {
142
159
  console.error(chalk_1.default.red(`error: ${error.message}`));
143
160
  process.exit(1);
144
161
  }
162
+ if (error instanceof LoginHostUserinfoError) {
163
+ console.error(chalk_1.default.red(`error: ${error.message}`));
164
+ process.exit(1);
165
+ }
145
166
  throw error;
146
167
  }
147
168
  }
@@ -494,6 +515,10 @@ function whoami() {
494
515
  console.error(chalk_1.default.red((0, config_1.credentialConflictMessage)(resolved.credentialConflict)));
495
516
  process.exit(1);
496
517
  }
518
+ if (resolved && (0, host_display_1.hostHasUserinfo)(resolved.config.host)) {
519
+ console.error(chalk_1.default.red((0, config_1.userinfoHostMessage)(resolved.config.host, resolved.sources.host)));
520
+ process.exit(1);
521
+ }
497
522
  if (!resolved || !resolved.config.apiKey) {
498
523
  console.log(chalk_1.default.yellow('Not initialized.'));
499
524
  console.log(chalk_1.default.gray('Run "solidactions login --global" to configure.'));
package/dist/index.js CHANGED
@@ -38,6 +38,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
38
38
  };
39
39
  Object.defineProperty(exports, "__esModule", { value: true });
40
40
  exports.program = void 0;
41
+ // Must stay first: it edits DEBUG before any dependency can load `debug`, and refuses a network NODE_DEBUG (cli#194).
42
+ require("./utils/debug-guard");
41
43
  const chalk_1 = __importDefault(require("chalk"));
42
44
  const commander_1 = require("commander");
43
45
  const deploy_1 = require("./commands/deploy");
package/dist/utils/api.js CHANGED
@@ -292,6 +292,10 @@ function requireResolvedConfig() {
292
292
  console.error(chalk_1.default.red((0, config_1.credentialConflictMessage)(resolved.credentialConflict)));
293
293
  process.exit(1);
294
294
  }
295
+ if (resolved && (0, host_display_1.hostHasUserinfo)(resolved.config.host)) {
296
+ console.error(chalk_1.default.red((0, config_1.userinfoHostMessage)(resolved.config.host, resolved.sources.host)));
297
+ process.exit(1);
298
+ }
295
299
  if (!resolved || !resolved.config.apiKey) {
296
300
  console.error(chalk_1.default.red('Not initialized. Run `solidactions login --global` first.'));
297
301
  process.exit(1);
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.DEFAULT_HOST = void 0;
7
7
  exports.normalizeHost = normalizeHost;
8
+ exports.userinfoHostMessage = userinfoHostMessage;
8
9
  exports.credentialConflictMessage = credentialConflictMessage;
9
10
  exports.setCliWorkspaceOverride = setCliWorkspaceOverride;
10
11
  exports.getGlobalConfigPath = getGlobalConfigPath;
@@ -30,6 +31,10 @@ function normalizeHost(host) {
30
31
  function describeSource(source, envVar) {
31
32
  return source === 'env' ? `$${envVar}` : String(source);
32
33
  }
34
+ /** The refusal for a resolved host that carries userinfo (cli#195). Never includes the userinfo. */
35
+ function userinfoHostMessage(host, source) {
36
+ return `error: the host "${(0, host_display_1.displayHost)(host)}" (from ${describeSource(source, 'SOLIDACTIONS_HOST')}) contains a username/password; remove "user:pass@" — the CLI authenticates with your API key.`;
37
+ }
33
38
  /** The refusal shown when a key would be sent to a host it was not configured with. Never includes the key. */
34
39
  function credentialConflictMessage(conflict) {
35
40
  if (conflict.keySource === 'env') {
@@ -8,6 +8,7 @@ exports.databaseCredentialDeadline = databaseCredentialDeadline;
8
8
  exports.isDatabaseCredentialAuthFailure = isDatabaseCredentialAuthFailure;
9
9
  exports.databaseCredentialFailureCode = databaseCredentialFailureCode;
10
10
  exports.safeDatabaseRequestError = safeDatabaseRequestError;
11
+ exports.preserveAuthFailure = preserveAuthFailure;
11
12
  exports.runDatabaseClientOperationWithDeadline = runDatabaseClientOperationWithDeadline;
12
13
  exports.requestDatabaseOperation = requestDatabaseOperation;
13
14
  exports.requestDatabaseDumpStream = requestDatabaseDumpStream;
@@ -80,7 +81,7 @@ class DatabaseOperationError extends Error {
80
81
  }
81
82
  }
82
83
  exports.DatabaseOperationError = DatabaseOperationError;
83
- function safeDatabaseRequestError(error) {
84
+ function safeDatabaseRequestError(error, host) {
84
85
  const augmented = (0, api_1.augmentTokenMissingAbilityMessage)(error);
85
86
  const response = augmented?.response;
86
87
  const status = typeof response?.status === 'number' ? response.status : undefined;
@@ -88,6 +89,10 @@ function safeDatabaseRequestError(error) {
88
89
  ? response.data.code.trim()
89
90
  : '';
90
91
  const stableCode = codeCandidate.length > 0 ? codeCandidate : null;
92
+ if (status === 401) {
93
+ // The one-line, host-naming 401 every command prints (cli#186).
94
+ return new DatabaseOperationError(stableCode ?? 'unauthenticated', (0, api_1.authFailedLine)(host), 401);
95
+ }
91
96
  const code = stableCode ?? 'upstream_unavailable';
92
97
  const appMessage = stableCode !== null
93
98
  && typeof response?.data?.message === 'string'
@@ -102,6 +107,20 @@ function safeDatabaseRequestError(error) {
102
107
  : undefined;
103
108
  return new DatabaseOperationError(code, message, status, sizeLimitBytes);
104
109
  }
110
+ /**
111
+ * A wrapper that adds operational state disclosure must not lose a 401's
112
+ * host line and status (cli#186). When the underlying failure is a 401 (a
113
+ * DatabaseOperationError whose message is already the shared host line),
114
+ * the surfaced error keeps its code and status and starts with that line,
115
+ * followed by the disclosure on a second line. Any other failure keeps the
116
+ * wrapper's existing error exactly.
117
+ */
118
+ function preserveAuthFailure(error, disclosure, fallbackCode, fallbackMessage) {
119
+ if (error instanceof DatabaseOperationError && error.status === 401) {
120
+ return new DatabaseOperationError(error.code, `${error.message}\n${disclosure}`, 401);
121
+ }
122
+ return new DatabaseOperationError(fallbackCode, fallbackMessage);
123
+ }
105
124
  function positiveTimeout(value, fallback) {
106
125
  return typeof value === 'number' && Number.isFinite(value) && value > 0
107
126
  ? value
@@ -170,7 +189,7 @@ async function requestDatabaseOperation(config, body, dependencies = {}) {
170
189
  return response.data;
171
190
  }
172
191
  catch (error) {
173
- throw safeDatabaseRequestError(error);
192
+ throw safeDatabaseRequestError(error, config.host);
174
193
  }
175
194
  }
176
195
  /** Request the existing server-side SQL dump as a stream. */
@@ -190,7 +209,7 @@ async function requestDatabaseDumpStream(config, name, dependencies = {}) {
190
209
  return response.data;
191
210
  }
192
211
  catch (error) {
193
- throw safeDatabaseRequestError(error);
212
+ throw safeDatabaseRequestError(error, config.host);
194
213
  }
195
214
  }
196
215
  function safeDirectClientError() {
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.guardDebugNamespaces = guardDebugNamespaces;
7
+ exports.nodeDebugNetworkSection = nodeDebugNetworkSection;
8
+ exports.refuseNetworkNodeDebug = refuseNetworkNodeDebug;
9
+ const chalk_1 = __importDefault(require("chalk"));
10
+ /**
11
+ * cli#194: keep the API key out of every debug channel.
12
+ *
13
+ * - `DEBUG` (the `debug` package): axios sends every request through
14
+ * follow-redirects, whose `debug` namespace dumps the request options (the
15
+ * Authorization header, a URL's userinfo). `debug` reads DEBUG once, when it
16
+ * first loads, and a skip (`-name`) beats any match, so appending the skip
17
+ * here turns that namespace off while every other one keeps working.
18
+ * - `NODE_DEBUG` (Node's util.debuglog): the http/net/tls sections dump
19
+ * connection options, headers included, for the axios path and the MCP
20
+ * transport. Node fixes the enabled sections during bootstrap, before any
21
+ * user code, so they cannot be turned off here: refuse to run instead
22
+ * (recorded on cli#194).
23
+ *
24
+ * src/index.ts imports this module first, before anything can load `debug`
25
+ * or make a request.
26
+ */
27
+ const DEBUG_SKIP = '-follow-redirects';
28
+ const NETWORK_SECTIONS = ['http', 'https', 'http2', 'net', 'tls'];
29
+ function guardDebugNamespaces(env = process.env) {
30
+ const value = env.DEBUG;
31
+ if (value === undefined || value.trim() === '') {
32
+ return;
33
+ }
34
+ if (value.split(/[\s,]+/).includes(DEBUG_SKIP)) {
35
+ return;
36
+ }
37
+ env.DEBUG = `${value},${DEBUG_SKIP}`;
38
+ }
39
+ /** The first network section NODE_DEBUG enables, matched exactly as Node's initializeDebugEnv does; null when none. */
40
+ function nodeDebugNetworkSection(value) {
41
+ if (!value) {
42
+ return null;
43
+ }
44
+ const pattern = value
45
+ .replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
46
+ .replace(/\*/g, '.*')
47
+ .replace(/,/g, '$|^');
48
+ const enabled = new RegExp(`^${pattern}$`, 'i');
49
+ return NETWORK_SECTIONS.find((section) => enabled.test(section)) ?? null;
50
+ }
51
+ function refuseNetworkNodeDebug(env = process.env) {
52
+ const section = nodeDebugNetworkSection(env.NODE_DEBUG);
53
+ if (section === null) {
54
+ return;
55
+ }
56
+ process.stderr.write(`${chalk_1.default.red(`error: NODE_DEBUG=${JSON.stringify(env.NODE_DEBUG)} turns on Node's "${section}" debug output, which prints request headers including your API key. Remove http, https, http2, net and tls from NODE_DEBUG (or unset it) and run again.`)}\n`);
57
+ process.exit(1);
58
+ }
59
+ refuseNetworkNodeDebug();
60
+ guardDebugNamespaces();
@@ -0,0 +1,342 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.LockHeldError = exports.UnsupportedTargetError = exports.WriteStepError = exports.PublicationRefusedError = exports.LinkOnTheWayError = exports.nameKey = exports.lockNameFor = void 0;
7
+ exports.isReservedName = isReservedName;
8
+ exports.faultsFromEnv = faultsFromEnv;
9
+ exports.ensureRealDirs = ensureRealDirs;
10
+ exports.writeAll = writeAll;
11
+ exports.acquireLock = acquireLock;
12
+ exports.releaseLock = releaseLock;
13
+ exports.writeFileAtomic = writeFileAtomic;
14
+ const crypto_1 = __importDefault(require("crypto"));
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const path_1 = __importDefault(require("path"));
17
+ /**
18
+ * doc pull's write path (cli#168, cli#188, cli#182; spec §1, PM ruling 12). The pull stops at the first error and
19
+ * records exactly what it wrote: each file is written to a sibling temp file (opened O_WRONLY|O_CREAT|O_EXCL|O_NOFOLLOW)
20
+ * and renamed into place, after the target is re-checked against the state the preflight saw; the caller then writes the
21
+ * manifest once. A rename replaces the directory entry, so a hard link's other names keep their bytes and a link at the
22
+ * final name is replaced, not followed. The pull never deletes, moves or restores anything it did not create in this run
23
+ * (its own temp file, and its own lock file, are the only things it removes here), so there is nothing to roll back.
24
+ * One O_EXCL lock file in the destination root keeps two pulls apart. Node has no openat: a directory component swapped
25
+ * for a link, or a final component changed between its check and its rename, is a documented residual race in the
26
+ * user's own folder (spec §1.6). No power-loss durability is claimed.
27
+ */
28
+ const O_NOFOLLOW = fs_1.default.constants.O_NOFOLLOW ?? 0;
29
+ const NEW_FILE_FLAGS = fs_1.default.constants.O_WRONLY | fs_1.default.constants.O_CREAT | fs_1.default.constants.O_EXCL | O_NOFOLLOW;
30
+ /** The name prefix of writeFileAtomic's temp files; reserved with the manifest and its lock (spec §1.3 Names). */
31
+ const TEMP_PREFIX = '.sa-write-';
32
+ /** The lock file's name beside a manifest. */
33
+ const lockNameFor = (manifestName) => `${manifestName}.lock`;
34
+ exports.lockNameFor = lockNameFor;
35
+ /**
36
+ * The key two names are compared by: composed (NFC) and lower-cased, so spellings one filesystem or
37
+ * another treats as one entry get one key (spec §1.3, cli#168).
38
+ */
39
+ const nameKey = (name) => name.normalize('NFC').toLowerCase().normalize('NFC');
40
+ exports.nameKey = nameKey;
41
+ /** A name doc pull keeps for itself at every level: the manifest, its lock, and the temp-file prefix (spec §1.3). */
42
+ function isReservedName(name, manifestName) {
43
+ const key = (0, exports.nameKey)(name);
44
+ return key === (0, exports.nameKey)(manifestName) || key === (0, exports.nameKey)((0, exports.lockNameFor)(manifestName)) || key.startsWith((0, exports.nameKey)(TEMP_PREFIX));
45
+ }
46
+ class LinkOnTheWayError extends Error {
47
+ component;
48
+ constructor(component) {
49
+ super(`${component} is a symbolic link or not a directory`);
50
+ this.component = component;
51
+ this.name = 'LinkOnTheWayError';
52
+ }
53
+ }
54
+ exports.LinkOnTheWayError = LinkOnTheWayError;
55
+ class PublicationRefusedError extends Error {
56
+ relPath;
57
+ constructor(relPath) {
58
+ super(`${relPath} changed after doc pull checked it`);
59
+ this.relPath = relPath;
60
+ this.name = 'PublicationRefusedError';
61
+ }
62
+ }
63
+ exports.PublicationRefusedError = PublicationRefusedError;
64
+ class WriteStepError extends Error {
65
+ relPath;
66
+ cause;
67
+ constructor(relPath, cause) {
68
+ super(cause instanceof Error ? cause.message : String(cause));
69
+ this.relPath = relPath;
70
+ this.cause = cause;
71
+ this.name = 'WriteStepError';
72
+ }
73
+ }
74
+ exports.WriteStepError = WriteStepError;
75
+ /** Ruling 9: a folder (or any entry that is neither a file nor a link) at a target is never moved or deleted. */
76
+ class UnsupportedTargetError extends Error {
77
+ relPath;
78
+ constructor(relPath) {
79
+ super(`${relPath} is a folder now`);
80
+ this.relPath = relPath;
81
+ this.name = 'UnsupportedTargetError';
82
+ }
83
+ }
84
+ exports.UnsupportedTargetError = UnsupportedTargetError;
85
+ /** The lock file is already there: another pull may be writing to the destination, or a killed one left it (spec §1.4). */
86
+ class LockHeldError extends Error {
87
+ lockName;
88
+ constructor(lockName) {
89
+ super(`${lockName} exists`);
90
+ this.lockName = lockName;
91
+ this.name = 'LockHeldError';
92
+ }
93
+ }
94
+ exports.LockHeldError = LockHeldError;
95
+ const sha256 = (data) => crypto_1.default.createHash('sha256').update(data).digest('hex');
96
+ const segments = (rel) => rel.split('/');
97
+ function ioFault(what) {
98
+ return Object.assign(new Error(`EIO: i/o error, ${what} (test hook)`), { code: 'EIO' });
99
+ }
100
+ /**
101
+ * Test-only injected failures (spec §1.8, sanctioned by PM ruling 7). Inert unless
102
+ * SOLIDACTIONS_TEST_HOOKS=1. Never documented for users.
103
+ */
104
+ function faultsFromEnv(env = process.env) {
105
+ const none = {
106
+ beforeManifestTemp: () => undefined,
107
+ beforeManifestRename: () => undefined,
108
+ afterChecks: () => undefined,
109
+ beforeWrites: () => undefined,
110
+ afterWrites: () => undefined,
111
+ beforeRename: () => undefined,
112
+ afterRename: () => undefined,
113
+ };
114
+ if (env.SOLIDACTIONS_TEST_HOOKS !== '1')
115
+ return none;
116
+ const faults = { ...none };
117
+ // A comma-separated list combines faults, e.g. "fail-rename:2,create-before-commit:a.md".
118
+ for (const spec of (env.SOLIDACTIONS_DOC_PULL_TEST_FAULT ?? '').split(',')) {
119
+ const [name, arg = ''] = spec.split(/:(.*)/s);
120
+ switch (name) {
121
+ case 'fail-rename':
122
+ faults.beforeRename = (n) => { if (n === Number(arg))
123
+ throw ioFault('rename'); };
124
+ break;
125
+ case 'fail-manifest-temp':
126
+ faults.beforeManifestTemp = () => { throw ioFault('open manifest temp'); };
127
+ break;
128
+ case 'fail-manifest-rename':
129
+ faults.beforeManifestRename = () => { throw ioFault('rename manifest'); };
130
+ break;
131
+ case 'kill-after-renames':
132
+ faults.afterRename = (n) => { if (n === Number(arg))
133
+ process.kill(process.pid, 'SIGKILL'); };
134
+ break;
135
+ case 'create-after-checks':
136
+ faults.afterChecks = (destination) => {
137
+ const abs = path_1.default.join(destination, ...segments(arg));
138
+ fs_1.default.mkdirSync(path_1.default.dirname(abs), { recursive: true });
139
+ fs_1.default.writeFileSync(abs, 'RACE');
140
+ };
141
+ break;
142
+ case 'create-before-commit':
143
+ faults.beforeWrites = (destination) => fs_1.default.writeFileSync(path_1.default.join(destination, ...segments(arg)), 'RACE');
144
+ break;
145
+ case 'mkdir-before-commit':
146
+ faults.beforeWrites = (destination) => {
147
+ const dir = path_1.default.join(destination, ...segments(arg));
148
+ fs_1.default.mkdirSync(dir);
149
+ fs_1.default.writeFileSync(path_1.default.join(dir, 'user.txt'), 'USER');
150
+ };
151
+ break;
152
+ case 'change-after-writes':
153
+ faults.afterWrites = (destination) => fs_1.default.writeFileSync(path_1.default.join(destination, ...segments(arg)), 'CHANGED');
154
+ break;
155
+ case 'break-after-writes': {
156
+ // `<how>:<rel>`: the entry at <rel> is made uninspectable before the outcomes are decided (cli#168 FR5).
157
+ const [how, rel = ''] = arg.split(/:(.*)/s);
158
+ faults.afterWrites = (destination) => {
159
+ const abs = path_1.default.join(destination, ...segments(rel));
160
+ if (how === 'chmod0') {
161
+ fs_1.default.chmodSync(abs, 0o000);
162
+ return;
163
+ }
164
+ fs_1.default.rmSync(abs, { recursive: true, force: true });
165
+ if (how === 'folder')
166
+ fs_1.default.mkdirSync(abs);
167
+ else if (how === 'file')
168
+ fs_1.default.writeFileSync(abs, 'BLOCKER');
169
+ else if (how === 'loop')
170
+ fs_1.default.symlinkSync(path_1.default.basename(abs), abs);
171
+ };
172
+ break;
173
+ }
174
+ case 'link-before-commit': {
175
+ const [linkRel, linkTarget] = arg.split('>');
176
+ faults.beforeWrites = (destination) => fs_1.default.symlinkSync(linkTarget, path_1.default.join(destination, ...segments(linkRel)));
177
+ break;
178
+ }
179
+ default:
180
+ break;
181
+ }
182
+ }
183
+ return faults;
184
+ }
185
+ function lstatOrNull(abs) {
186
+ try {
187
+ return fs_1.default.lstatSync(abs);
188
+ }
189
+ catch (error) {
190
+ if (error.code === 'ENOENT')
191
+ return null;
192
+ throw error;
193
+ }
194
+ }
195
+ /** True when the regular file at `targetAbs` already holds exactly `data`; a file that cannot be read does not. */
196
+ function holdsBytes(targetAbs, data) {
197
+ try {
198
+ return sha256(fs_1.default.readFileSync(targetAbs)) === sha256(data);
199
+ }
200
+ catch {
201
+ return false;
202
+ }
203
+ }
204
+ /**
205
+ * Whether the target is still in a state the checks allowed the pull to replace. Rule 5 (spec §1.1): a regular file that
206
+ * already holds the bytes about to be written is never a conflict, whatever it was authorized as.
207
+ */
208
+ function stillAuthorized(targetAbs, authorized, data) {
209
+ if (authorized.kind === 'any')
210
+ return true;
211
+ const stat = lstatOrNull(targetAbs);
212
+ if (authorized.kind === 'absent')
213
+ return stat === null || (stat.isFile() && holdsBytes(targetAbs, data));
214
+ if (stat === null || !stat.isFile())
215
+ return false;
216
+ const current = sha256(fs_1.default.readFileSync(targetAbs));
217
+ return current === authorized.sha256 || current === sha256(data);
218
+ }
219
+ /** Every folder of `dirRel` under `destination`, created where missing; a link or a file on the way refuses (cli#182). Returns the folder's path. */
220
+ function ensureRealDirs(destination, dirRel) {
221
+ const parts = dirRel === '' ? [] : segments(dirRel);
222
+ let current = destination;
223
+ for (let i = 0; i < parts.length; i++) {
224
+ current = path_1.default.join(current, parts[i]);
225
+ let stat = lstatOrNull(current);
226
+ if (stat === null) {
227
+ fs_1.default.mkdirSync(current);
228
+ stat = fs_1.default.lstatSync(current);
229
+ }
230
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
231
+ throw new LinkOnTheWayError(parts.slice(0, i + 1).join('/'));
232
+ }
233
+ }
234
+ return current;
235
+ }
236
+ /** Create `abs` (it must not exist) holding `data`; returns the new file's `dev:ino`. */
237
+ function writeNew(abs, data) {
238
+ const fd = fs_1.default.openSync(abs, NEW_FILE_FLAGS, 0o666);
239
+ try {
240
+ fs_1.default.writeFileSync(fd, data);
241
+ const stat = fs_1.default.fstatSync(fd);
242
+ return `${stat.dev}:${stat.ino}`;
243
+ }
244
+ finally {
245
+ fs_1.default.closeSync(fd);
246
+ }
247
+ }
248
+ /**
249
+ * Write every planned file in order, stopping at the first one that cannot be written or whose target is no longer in the
250
+ * state the preflight saw (spec §1.3). Nothing is deleted or restored: the files written before the stop stay, and are
251
+ * returned so the caller can record them.
252
+ */
253
+ function writeAll(destination, writes, faults) {
254
+ faults.beforeWrites(destination);
255
+ const placed = [];
256
+ for (let i = 0; i < writes.length; i++) {
257
+ const write = writes[i];
258
+ const targetAbs = path_1.default.join(destination, ...segments(write.relPath));
259
+ let identity;
260
+ try {
261
+ const dirAbs = ensureRealDirs(destination, write.dirRel);
262
+ identity = writeFileAtomic(dirAbs, path_1.default.basename(targetAbs), write.data, () => {
263
+ const existing = lstatOrNull(targetAbs);
264
+ if (existing !== null && !existing.isFile() && !existing.isSymbolicLink())
265
+ throw new UnsupportedTargetError(write.relPath);
266
+ if (!stillAuthorized(targetAbs, write.authorized, write.data))
267
+ throw new PublicationRefusedError(write.relPath);
268
+ faults.beforeRename(i + 1);
269
+ });
270
+ }
271
+ catch (error) {
272
+ const typed = error instanceof LinkOnTheWayError || error instanceof PublicationRefusedError || error instanceof UnsupportedTargetError;
273
+ return { placed, stop: { write, error: typed ? error : new WriteStepError(write.relPath, error) } };
274
+ }
275
+ placed.push({ ...write, identity });
276
+ faults.afterRename(i + 1);
277
+ }
278
+ return { placed, stop: null };
279
+ }
280
+ /**
281
+ * Create the destination's lock file, holding this pid (spec §1.4). Any existing entry of that name refuses, a link or a
282
+ * folder included; the file is never removed or liveness-tested except by the pull that created it (releaseLock).
283
+ */
284
+ function acquireLock(destination, manifestName) {
285
+ const lockName = (0, exports.lockNameFor)(manifestName);
286
+ const lockAbs = path_1.default.join(destination, lockName);
287
+ let fd;
288
+ try {
289
+ fd = fs_1.default.openSync(lockAbs, NEW_FILE_FLAGS, 0o666);
290
+ }
291
+ catch (error) {
292
+ if (error.code === 'EEXIST')
293
+ throw new LockHeldError(lockName);
294
+ throw error;
295
+ }
296
+ try {
297
+ fs_1.default.writeFileSync(fd, `${process.pid}\n`);
298
+ }
299
+ catch (error) {
300
+ fs_1.default.closeSync(fd);
301
+ fs_1.default.unlinkSync(lockAbs); // the file this call just created
302
+ throw error;
303
+ }
304
+ fs_1.default.closeSync(fd);
305
+ }
306
+ /** Remove the lock this process created: only a regular file still holding this pid, so a lock someone else made is never touched. */
307
+ function releaseLock(destination, manifestName) {
308
+ const lockAbs = path_1.default.join(destination, (0, exports.lockNameFor)(manifestName));
309
+ try {
310
+ if (lstatOrNull(lockAbs)?.isFile() === true && fs_1.default.readFileSync(lockAbs, 'utf8') === `${process.pid}\n`)
311
+ fs_1.default.unlinkSync(lockAbs);
312
+ }
313
+ catch {
314
+ // already gone, or not ours to inspect
315
+ }
316
+ }
317
+ /**
318
+ * Write `dir/name` through a sibling temp file and a rename: never half-written, never through a link at `name`.
319
+ * `beforeRename` runs after the temp file exists and just before the rename; if it throws, the temp file is removed.
320
+ * Returns the `dev:ino` of the file renamed in (a rename keeps the temp file's inode).
321
+ */
322
+ function writeFileAtomic(dir, name, data, beforeRename) {
323
+ const tempAbs = path_1.default.join(dir, `${TEMP_PREFIX}${process.pid}-${crypto_1.default.randomBytes(6).toString('hex')}.tmp`);
324
+ const identity = writeNew(tempAbs, data);
325
+ try {
326
+ beforeRename?.();
327
+ const existing = lstatOrNull(path_1.default.join(dir, name));
328
+ if (existing !== null && existing.isFile())
329
+ fs_1.default.chmodSync(tempAbs, existing.mode & 0o7777);
330
+ fs_1.default.renameSync(tempAbs, path_1.default.join(dir, name));
331
+ }
332
+ catch (error) {
333
+ try {
334
+ fs_1.default.unlinkSync(tempAbs);
335
+ }
336
+ catch {
337
+ // already gone
338
+ }
339
+ throw error;
340
+ }
341
+ return identity;
342
+ }
@@ -9,6 +9,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9
9
  };
10
10
  Object.defineProperty(exports, "__esModule", { value: true });
11
11
  exports.DOCS_MANIFEST = void 0;
12
+ exports.docsFrom = docsFrom;
13
+ exports.entryAt = entryAt;
12
14
  exports.sha256Hex = sha256Hex;
13
15
  exports.readManifest = readManifest;
14
16
  exports.writeManifest = writeManifest;
@@ -16,7 +18,19 @@ const fs_1 = __importDefault(require("fs"));
16
18
  const path_1 = __importDefault(require("path"));
17
19
  const crypto_1 = __importDefault(require("crypto"));
18
20
  const chalk_1 = __importDefault(require("chalk"));
21
+ const doc_pull_writes_1 = require("./doc-pull-writes");
19
22
  exports.DOCS_MANIFEST = '.solidactions-docs.json';
23
+ /** A `docs` dictionary holding `entries` in order: no prototype, so no name is inherited and none reaches a setter. */
24
+ function docsFrom(entries) {
25
+ const docs = Object.create(null);
26
+ for (const [relPath, entry] of entries)
27
+ docs[relPath] = entry;
28
+ return docs;
29
+ }
30
+ /** The entry `manifest` records at `relPath`: an own key only, never an inherited name. */
31
+ function entryAt(manifest, relPath) {
32
+ return manifest != null && Object.hasOwn(manifest.docs, relPath) ? manifest.docs[relPath] : undefined;
33
+ }
20
34
  /** sha256 hex digest of the given bytes/string, as written to disk. */
21
35
  function sha256Hex(data) {
22
36
  return crypto_1.default.createHash('sha256').update(data).digest('hex');
@@ -34,7 +48,11 @@ function readManifest(dir, opts = {}) {
34
48
  return null;
35
49
  }
36
50
  try {
37
- return JSON.parse(fs_1.default.readFileSync(manifestPath, 'utf8'));
51
+ const manifest = JSON.parse(fs_1.default.readFileSync(manifestPath, 'utf8'));
52
+ // JSON.parse makes every key an own one; the copy keeps it so for every later lookup and insertion.
53
+ if (manifest !== null && typeof manifest.docs === 'object' && manifest.docs !== null)
54
+ manifest.docs = docsFrom(Object.entries(manifest.docs));
55
+ return manifest;
38
56
  }
39
57
  catch {
40
58
  if (opts.warnOnParseError) {
@@ -43,6 +61,7 @@ function readManifest(dir, opts = {}) {
43
61
  return null;
44
62
  }
45
63
  }
46
- function writeManifest(dir, manifest) {
47
- fs_1.default.writeFileSync(path_1.default.join(dir, exports.DOCS_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
64
+ /** `beforeRename` is doc pull's test seam (spec §1.8): it runs once the temp file exists, just before the rename. */
65
+ function writeManifest(dir, manifest, beforeRename) {
66
+ (0, doc_pull_writes_1.writeFileAtomic)(dir, exports.DOCS_MANIFEST, `${JSON.stringify(manifest, null, 2)}\n`, beforeRename);
48
67
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.displayHost = displayHost;
4
+ exports.hostHasUserinfo = hostHasUserinfo;
4
5
  /**
5
6
  * Host as shown in user-facing output: a URL with any userinfo stripped
6
7
  * (credentials must never reach the terminal), otherwise shown as
@@ -26,6 +27,24 @@ function displayHost(host) {
26
27
  }
27
28
  return shown;
28
29
  }
30
+ /**
31
+ * True when a host carries userinfo (`user:pass@`, `user@`). axios turns URL
32
+ * userinfo into a Basic Authorization header that replaces the CLI's API-key header, so
33
+ * such a host can never authenticate; config resolution and login refuse it
34
+ * (cli#195, Peter's ruling on CrewOps ask task-cliahostwithuser-922c).
35
+ */
36
+ function hostHasUserinfo(host) {
37
+ try {
38
+ const url = new URL(host);
39
+ if (url.host !== '') {
40
+ return url.username !== '' || url.password !== '';
41
+ }
42
+ }
43
+ catch {
44
+ // Not a URL `new URL` accepts: look at the authority by hand below.
45
+ }
46
+ return /^([a-z][a-z0-9+.-]*:\/\/)?[^/?#]*@/i.test(host);
47
+ }
29
48
  const INVALID_HOST_PLACEHOLDER = '<invalid host>';
30
49
  /**
31
50
  * Fallback for a value `new URL` rejects (`http://u:secret@localhost:bad-port`),