@tenonhq/dovetail-core 0.0.129 → 0.0.131

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/README.md CHANGED
@@ -49,6 +49,44 @@ See [`UPDATE_SET_COMMANDS.md`](UPDATE_SET_COMMANDS.md) for the full update-set C
49
49
  - An in-progress set with the same name already in that scope is refused (exit 1) rather than duplicated.
50
50
  - The set is created, not activated — the success line prints its sys_id; use `npx dove switchUpdateSet --sysId <sys_id> -s <scope>` (or `npx dove createUpdateSet`, which creates and activates in one step).
51
51
 
52
+ ### Exit codes
53
+
54
+ | Code | Meaning |
55
+ | ---- | ------- |
56
+ | `0` | The command finished. |
57
+ | `1` | The command failed (any reason not listed below). |
58
+ | `77` | ServiceNow rejected the credentials or refused the request. A write got HTTP 401 or 403, or a failing command got HTTP 401 on a read. |
59
+
60
+ A write is any request that changes the instance, whichever command sends it: `push`,
61
+ `reconcile --apply` (create and delete), `create`, `delete`, `createUpdateSet`, the
62
+ update-set and scope switches that save a user preference, and so on. The check runs
63
+ on every request `dove` makes, so a new command is covered without extra wiring.
64
+
65
+ On a 401, or a 403 on a write, `dove` names the instance host, the request, and the
66
+ env file the credentials were loaded from. That message prints once per run, not once
67
+ per record. It never prints a credential. The next step depends on the status:
68
+
69
+ - **401**: the credentials were rejected. `dove` prints the command that
70
+ re-authenticates: `dove login`, or `dove login --env <name>` when the command ran
71
+ with `--env`.
72
+ - **403 on a write**: the sign-in worked and the instance refused the write for this
73
+ user. `dove` names the table when it can and says to check the role or ACL for it.
74
+ It does not suggest `dove login`, because signing in again as the same user changes
75
+ nothing.
76
+
77
+ Exit codes:
78
+
79
+ - A write that was turned away exits `77` even when the command itself reports
80
+ per-record results and would otherwise exit `0` (`push`) or `1` (`reconcile --apply`).
81
+ - A 401 on a read changes the exit code only when the command then fails: `1` becomes
82
+ `77`. A command that tolerated it and succeeded still exits `0`.
83
+ - A 403 on a read does not change the exit code, because it is usually one table's
84
+ ACL. The manifest and file downloads behind `refresh` count as reads.
85
+ - Every other exit code is unchanged.
86
+
87
+ Exit code `77` and the credential-failure message are in `@tenonhq/dovetail-core` 0.0.131
88
+ and later.
89
+
52
90
  ## Plugins
53
91
 
54
92
  Dovetail's build pipeline is plugin-driven. Each plugin is an npm package implementing `run(context, content, options) => Promise<PluginResults>`. Shipped plugins live in sibling packages (`@tenonhq/dovetail-typescript-plugin`, `-babel-plugin`, `-webpack-plugin`, `-sass-plugin`, `-eslint-plugin`, `-prettier-plugin`, `-babel-preset-servicenow`, `-babel-plugin-remove-modules`).
@@ -0,0 +1,243 @@
1
+ "use strict";
2
+ /**
3
+ * What `dove` says and how it exits when ServiceNow rejects its credentials (#185).
4
+ *
5
+ * A 401 or 403 used to surface as a generic "verify your credentials" line and the
6
+ * same exit code as every other failure, so a script could not tell "the instance
7
+ * turned us away" from "a record failed to build". This module owns the two halves
8
+ * of the fix:
9
+ *
10
+ * 1. The MESSAGE — which instance, which env file the credentials came from, and
11
+ * the next step. For a 401: the exact command that re-authenticates
12
+ * (`dove login`, with `--env <name>` when one was used). For a 403 on a write:
13
+ * check the role or ACL for the table, since signing in again changes nothing.
14
+ * 2. The EXIT CODE — AUTH_EXIT_CODE, distinct from the generic 1.
15
+ *
16
+ * NEVER A CREDENTIAL. The message is built only from the instance host, the env
17
+ * file's PATH and the `--env` selector the user typed. Nothing is read out of the
18
+ * env file, and the host is reduced to a bare hostname first, so a value that
19
+ * carries userinfo (`user:pass@host`) cannot leak through it.
20
+ *
21
+ * No imports from the rest of core: snClient.ts must be able to use this without
22
+ * a circular dependency on config.ts. bootstrap.ts pushes the context in.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.AUTH_EXIT_CODE = void 0;
26
+ exports.setAuthContext = setAuthContext;
27
+ exports.resetAuthFailureState = resetAuthFailureState;
28
+ exports.isAuthStatus = isAuthStatus;
29
+ exports.requestPath = requestPath;
30
+ exports.classifyAuthRejection = classifyAuthRejection;
31
+ exports.firstRejectionOfKind = firstRejectionOfKind;
32
+ exports.instanceHost = instanceHost;
33
+ exports.reauthCommand = reauthCommand;
34
+ exports.buildAuthFailureMessage = buildAuthFailureMessage;
35
+ exports.recordAuthFailure = recordAuthFailure;
36
+ exports.resolveExitCode = resolveExitCode;
37
+ exports.installAuthExitCode = installAuthExitCode;
38
+ /**
39
+ * Exit code for "ServiceNow rejected the credentials" (HTTP 401 or 403).
40
+ * 77 is EX_NOPERM in sysexits.h — "permission denied". Every other failure keeps
41
+ * the exit code it had (1).
42
+ */
43
+ exports.AUTH_EXIT_CODE = 77;
44
+ var context = { envPath: "", envArg: "" };
45
+ /** A failed WRITE was rejected (forces the auth exit code, even over a clean exit). */
46
+ var writeRejected = false;
47
+ /** Any request was rejected (re-maps a generic failure exit to the auth exit code). */
48
+ var anyRejected = false;
49
+ /** Called once by bootstrap, after the env file is resolved. Values are paths/names only. */
50
+ function setAuthContext(next) {
51
+ var n = next || {};
52
+ context = {
53
+ envPath: typeof n.envPath === "string" ? n.envPath : "",
54
+ envArg: typeof n.envArg === "string" ? n.envArg : "",
55
+ };
56
+ }
57
+ /** Which rejection kinds already had their full message printed (see classifyAuthRejection). */
58
+ var announced = {};
59
+ /** Test seam: forget the context and every recorded failure. */
60
+ function resetAuthFailureState() {
61
+ context = { envPath: "", envArg: "" };
62
+ writeRejected = false;
63
+ anyRejected = false;
64
+ announced = {};
65
+ }
66
+ function isAuthStatus(status) {
67
+ return status === 401 || status === 403;
68
+ }
69
+ /**
70
+ * POST endpoints that only READ. Everything else that is not a GET changes the
71
+ * instance. A 403 on one of these is treated like a 403 on a GET.
72
+ */
73
+ var READ_ONLY_POST_ENDPOINTS = [
74
+ "api/cadso/dovetail_sync/getManifest",
75
+ "api/cadso/dovetail_sync/bulkDownload",
76
+ ];
77
+ /**
78
+ * The request path, safe to echo: no scheme, host, userinfo, query or fragment,
79
+ * and only ordinary path characters. Returns "" for anything else.
80
+ */
81
+ function requestPath(rawUrl) {
82
+ if (typeof rawUrl !== "string")
83
+ return "";
84
+ var path = rawUrl.trim().replace(/^[a-z][a-z0-9+.-]*:\/\/[^\/?#]*/i, "");
85
+ var cut = path.search(/[?#]/);
86
+ if (cut !== -1)
87
+ path = path.slice(0, cut);
88
+ path = path.replace(/^\/+/, "");
89
+ if (path.length === 0 || path.length > 200)
90
+ return "";
91
+ if (!/^[A-Za-z0-9._\/-]+$/.test(path))
92
+ return "";
93
+ return path;
94
+ }
95
+ function isReadOnlyPost(method, path) {
96
+ if (method !== "POST")
97
+ return false;
98
+ for (var i = 0; i < READ_ONLY_POST_ENDPOINTS.length; i += 1) {
99
+ var endpoint = READ_ONLY_POST_ENDPOINTS[i];
100
+ if (path === endpoint || path.indexOf(endpoint + "/") === 0)
101
+ return true;
102
+ }
103
+ return false;
104
+ }
105
+ /**
106
+ * Decide what a rejected HTTP request means for the exit code. Pure.
107
+ *
108
+ * - 401 on any request: the credentials were rejected
109
+ * - 403 on a write (any method but GET, bar the read-only POSTs above): the
110
+ * instance refused the change
111
+ * - 403 on a read: null. It is usually one table's ACL, and callers probe and
112
+ * fall back, so it changes nothing
113
+ * - any other status: null
114
+ *
115
+ * An unknown method counts as a read, so a malformed error can never force the
116
+ * auth exit code on its own.
117
+ */
118
+ function classifyAuthRejection(input) {
119
+ var i = input || { status: undefined, method: undefined };
120
+ if (!isAuthStatus(i.status))
121
+ return null;
122
+ var method = typeof i.method === "string" ? i.method.toUpperCase() : "";
123
+ var write = method !== "" && method !== "GET" && !isReadOnlyPost(method, requestPath(i.url));
124
+ if (i.status === 403 && !write)
125
+ return null;
126
+ return { status: i.status, write: write };
127
+ }
128
+ /**
129
+ * True the first time a rejection of this kind is seen in the process, so the full
130
+ * message prints once instead of once per record on a large push.
131
+ */
132
+ function firstRejectionOfKind(rejection) {
133
+ var kind = rejection.status + (rejection.write ? ":write" : ":read");
134
+ if (announced[kind] === true)
135
+ return false;
136
+ announced[kind] = true;
137
+ return true;
138
+ }
139
+ /**
140
+ * Reduce an SN_INSTANCE value to a bare hostname: no scheme, no userinfo, no path,
141
+ * no query. Returns "" for anything that is not a plain host, so the caller falls
142
+ * back to a neutral phrase instead of echoing an unexpected value.
143
+ */
144
+ function instanceHost(raw) {
145
+ if (typeof raw !== "string")
146
+ return "";
147
+ var host = raw.trim().replace(/^[a-z][a-z0-9+.-]*:\/\//i, "");
148
+ var at = host.lastIndexOf("@");
149
+ if (at !== -1)
150
+ host = host.slice(at + 1);
151
+ var cut = host.search(/[\/?#]/);
152
+ if (cut !== -1)
153
+ host = host.slice(0, cut);
154
+ if (!/^[A-Za-z0-9.-]+(:[0-9]{1,5})?$/.test(host))
155
+ return "";
156
+ return host;
157
+ }
158
+ /**
159
+ * The `--env` selector, when it is safe to echo into a suggested command: a bare
160
+ * name or a path made of ordinary filename characters. Anything else (spaces, shell
161
+ * metacharacters) yields "" and the suggestion uses a placeholder instead.
162
+ */
163
+ function echoableEnvArg(envArg) {
164
+ return /^[A-Za-z0-9._\/~-]+$/.test(envArg) ? envArg : "";
165
+ }
166
+ /** The command that re-authenticates this invocation's instance. */
167
+ function reauthCommand(envArg) {
168
+ var arg = typeof envArg === "string" ? envArg : context.envArg;
169
+ if (!arg)
170
+ return "dove login";
171
+ var safe = echoableEnvArg(arg);
172
+ return "dove login --env " + (safe ? safe : "<name>");
173
+ }
174
+ /** A table name safe to echo, or "". */
175
+ function echoableTable(table) {
176
+ return typeof table === "string" && /^[A-Za-z0-9_]{1,80}$/.test(table) ? table : "";
177
+ }
178
+ /**
179
+ * The actionable message for a 401/403. Pure: reads the module context and its
180
+ * arguments, nothing else. Contains no credential.
181
+ *
182
+ * The two statuses need different remedies. A 401 means the credentials were
183
+ * rejected, so the fix is to sign in again. A 403 means the sign-in worked and the
184
+ * instance refused the write for this user: signing in again as the same user
185
+ * changes nothing, so the message points at the role or ACL instead.
186
+ */
187
+ function buildAuthFailureMessage(input) {
188
+ var host = instanceHost(input.instance);
189
+ var where = host ? host : "the ServiceNow instance";
190
+ if (input.status === 401) {
191
+ var source = context.envPath
192
+ ? "the credentials loaded from " + context.envPath
193
+ : "the credentials in the loaded env file";
194
+ return ("Unauthorized (401) " + input.action + ". " +
195
+ where + " rejected " + source + " — the user, password or API key is wrong or expired." +
196
+ " Re-authenticate with: " + reauthCommand() +
197
+ " — then re-run. (dove exits " + exports.AUTH_EXIT_CODE + " for a credential failure.)");
198
+ }
199
+ var table = echoableTable(input.table);
200
+ return ("Forbidden (403) " + input.action + ". " +
201
+ where + " accepted the sign-in but refused the write for this user." +
202
+ " Check the role or ACL for " + (table ? "table " + table : "the table") +
203
+ " for the user in " + (context.envPath ? context.envPath : "the loaded env file") +
204
+ ", then re-run. (dove exits " + exports.AUTH_EXIT_CODE + " for a refused write.)");
205
+ }
206
+ /**
207
+ * Record that the instance rejected a request. `write: true` is a rejected WRITE —
208
+ * the command did not do what it was asked, so it must not exit clean.
209
+ */
210
+ function recordAuthFailure(opts) {
211
+ anyRejected = true;
212
+ if (opts && opts.write === true)
213
+ writeRejected = true;
214
+ }
215
+ /**
216
+ * The exit code the process should finish with, given the code it was about to use.
217
+ *
218
+ * - a rejected WRITE: 0 or 1 becomes AUTH_EXIT_CODE (a push that was turned away
219
+ * is not a success, even though the push command itself exits 0 after reporting)
220
+ * - any other rejection: only a generic failure (1) becomes AUTH_EXIT_CODE — a
221
+ * command that tolerated the rejection and succeeded still exits 0
222
+ * - every other code is left exactly as it was
223
+ */
224
+ function resolveExitCode(code) {
225
+ var current = typeof code === "number" && !isNaN(code) ? code : 0;
226
+ if (writeRejected && (current === 0 || current === 1))
227
+ return exports.AUTH_EXIT_CODE;
228
+ if (anyRejected && current === 1)
229
+ return exports.AUTH_EXIT_CODE;
230
+ return current;
231
+ }
232
+ /**
233
+ * Install the process `exit` hook that applies resolveExitCode. Called only from the
234
+ * CLI entry point — importing dovetail-core as a library never touches exit codes.
235
+ */
236
+ function installAuthExitCode(proc) {
237
+ proc.on("exit", function (code) {
238
+ var next = resolveExitCode(code);
239
+ if (next !== code) {
240
+ proc.exitCode = next;
241
+ }
242
+ });
243
+ }
package/dist/bootstrap.js CHANGED
@@ -41,13 +41,24 @@ const dotenv_1 = __importDefault(require("dotenv"));
41
41
  const ConfigManager = __importStar(require("./config"));
42
42
  const Logger_1 = require("./Logger");
43
43
  const envArg_1 = require("./envArg");
44
+ const authFailure_1 = require("./authFailure");
44
45
  async function init() {
45
46
  // Honor a per-command `--env <path>` override before config/env load so
46
47
  // dotenv reads the requested file. Resolved here (not in loadConfigs) because
47
48
  // the override must be set before loadEnvPath runs inside loadConfigs.
48
49
  const envArg = (0, envArg_1.parseEnvArg)(process.argv.slice(2));
49
50
  if (envArg) {
50
- ConfigManager.setEnvPathOverride((0, envArg_1.resolveEnvArgPath)(envArg));
51
+ ConfigManager.setEnvPathOverride((0, envArg_1.resolveEnvArgPath)(envArg, undefined, {
52
+ onParentMatch: function (foundPath) {
53
+ // stderr, never stdout (stdout carries --json / format json output).
54
+ // The path only — never anything from the file. Same notice as dove-sn.
55
+ process.stderr.write("dove: --env " +
56
+ envArg +
57
+ ": using " +
58
+ foundPath +
59
+ " (found in a parent directory)\n");
60
+ },
61
+ }));
51
62
  }
52
63
  let configLoaded = false;
53
64
  try {
@@ -61,6 +72,9 @@ async function init() {
61
72
  try {
62
73
  let path = ConfigManager.getEnvPath();
63
74
  dotenv_1.default.config({ path });
75
+ // Only the file's PATH and the selector the user typed — never its contents.
76
+ // Lets a 401/403 name the env file and the exact re-auth command (#185).
77
+ (0, authFailure_1.setAuthContext)({ envPath: path, envArg: envArg || "" });
64
78
  }
65
79
  catch (e) {
66
80
  Logger_1.logger.error("Failed to load environment: " + String(e));
package/dist/envArg.js CHANGED
@@ -3,9 +3,12 @@ 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.ENV_WALK_UP_MAX_LEVELS = void 0;
6
7
  exports.parseEnvArg = parseEnvArg;
7
8
  exports.resolveEnvArgPath = resolveEnvArgPath;
9
+ exports.findEnvFileUpward = findEnvFileUpward;
8
10
  const fs_1 = __importDefault(require("fs"));
11
+ const os_1 = __importDefault(require("os"));
9
12
  const path_1 = __importDefault(require("path"));
10
13
  /**
11
14
  * Per-invocation .env selection for the `dove` CLI.
@@ -31,6 +34,11 @@ const path_1 = __importDefault(require("path"));
31
34
  var ENV_FLAGS = ["--env", "--env-file", "--envFile", "-e"];
32
35
  // Prefix a bare instance name is expanded with (`prod` → `.env.prod`).
33
36
  var BARE_NAME_PREFIX = ".env.";
37
+ /**
38
+ * How many parent directories a bare instance name's file is looked for in,
39
+ * above the cwd. Mirrored in packages/servicenow/src/loadEnv.ts.
40
+ */
41
+ exports.ENV_WALK_UP_MAX_LEVELS = 8;
34
42
  /**
35
43
  * @description Extracts the env-file selector from a raw argv slice. Supports
36
44
  * both `--env <value>` and `--env=<value>` (and the `-e` / `--env-file`
@@ -75,14 +83,20 @@ function parseEnvArg(argv) {
75
83
  * `workshop.env`) is an explicit filename in cwd, used as-is even when
76
84
  * it does not exist yet — `dove login --env` may be about to create it.
77
85
  * 4. Anything else is a bare instance name: `prod` → `<cwd>/.env.prod`.
78
- * Does not check existence; a missing file keeps dove's historical behavior
79
- * (nothing is loaded from it).
86
+ * When that file does not exist, the parent directories are searched
87
+ * (findEnvFileUpward) and the nearest existing `.env.prod` wins, so a
88
+ * nested git worktree can use the per-instance file of the checkout it
89
+ * lives in. Nothing found → `<cwd>/.env.prod`, as before.
90
+ * Only rule 4 walks up; paths and explicit filenames never do. Existence is
91
+ * checked with stat only — no file is read here. A missing file keeps dove's
92
+ * historical behavior (nothing is loaded from it).
80
93
  * @param {string} rawPath - The value returned by parseEnvArg.
81
94
  * @param {string} [cwd] - Base directory for relative paths and bare names (defaults to process.cwd()).
95
+ * @param {EnvWalkUpOptions} [options] - Home-directory bound and a callback for a parent-directory match.
82
96
  * @returns {string} An absolute path to the requested .env file.
83
97
  * @throws {Error} When rawPath is not a non-empty string.
84
98
  */
85
- function resolveEnvArgPath(rawPath, cwd) {
99
+ function resolveEnvArgPath(rawPath, cwd, options) {
86
100
  if (typeof rawPath !== "string" || rawPath.trim().length === 0) {
87
101
  throw new Error("--env must be a non-empty env-file name or path.");
88
102
  }
@@ -98,7 +112,148 @@ function resolveEnvArgPath(rawPath, cwd) {
98
112
  if (value.indexOf(".") !== -1) {
99
113
  return literal;
100
114
  }
101
- return path_1.default.resolve(base, BARE_NAME_PREFIX + value);
115
+ var fileName = BARE_NAME_PREFIX + value;
116
+ var inCwd = path_1.default.resolve(base, fileName);
117
+ if (isExistingFile(inCwd)) {
118
+ return inCwd;
119
+ }
120
+ var opts = options || {};
121
+ var found = findEnvFileUpward({
122
+ fileName: fileName,
123
+ startDir: base,
124
+ homeDir: opts.homeDir,
125
+ ownerUid: opts.ownerUid,
126
+ });
127
+ if (found === null) {
128
+ return inCwd;
129
+ }
130
+ if (typeof opts.onParentMatch === "function") {
131
+ try {
132
+ opts.onParentMatch(found);
133
+ }
134
+ catch (e) {
135
+ // A logging callback must never change which file is selected.
136
+ }
137
+ }
138
+ return found;
139
+ }
140
+ /**
141
+ * @description Looks for `fileName` in the parent directories of `startDir`
142
+ * (not in `startDir` itself) and returns the nearest one that exists as a
143
+ * regular file owned by the current user. Bounds: at most `maxLevels` parents
144
+ * (default ENV_WALK_UP_MAX_LEVELS); never the home directory or anything above
145
+ * it; never the filesystem root. A file owned by someone else (e.g. planted in
146
+ * a shared or world-writable ancestor such as /tmp when the cwd is outside the
147
+ * home directory) is skipped, never selected. Uses stat only and never reads a
148
+ * file. Never throws: bad input or no match returns null.
149
+ * Keep behaviorally identical to findEnvFileUpward in
150
+ * packages/servicenow/src/loadEnv.ts — packages/servicenow/tests/envWalkUpParity.test.ts
151
+ * runs both.
152
+ * @param {{fileName: string, startDir: string, homeDir?: string, maxLevels?: number, ownerUid?: number}} args
153
+ * @returns {string|null} The absolute path of the nearest match, or null.
154
+ */
155
+ function findEnvFileUpward(args) {
156
+ if (!args ||
157
+ typeof args.fileName !== "string" ||
158
+ typeof args.startDir !== "string") {
159
+ return null;
160
+ }
161
+ var fileName = args.fileName;
162
+ if (fileName.length === 0 ||
163
+ /[\\/]/.test(fileName) ||
164
+ fileName === "." ||
165
+ fileName === "..") {
166
+ return null;
167
+ }
168
+ if (args.startDir.length === 0) {
169
+ return null;
170
+ }
171
+ var maxLevels = typeof args.maxLevels === "number" &&
172
+ isFinite(args.maxLevels) &&
173
+ args.maxLevels >= 0
174
+ ? Math.floor(args.maxLevels)
175
+ : exports.ENV_WALK_UP_MAX_LEVELS;
176
+ var home = typeof args.homeDir === "string" ? args.homeDir : safeHomeDir();
177
+ var homeResolved = home.length > 0 ? path_1.default.resolve(home) : "";
178
+ var ownerUid = typeof args.ownerUid === "number" && isFinite(args.ownerUid)
179
+ ? args.ownerUid
180
+ : currentUid();
181
+ var dir = path_1.default.resolve(args.startDir);
182
+ for (var level = 0; level < maxLevels; level++) {
183
+ var parent = path_1.default.dirname(dir);
184
+ if (parent === dir) {
185
+ break; // already at the root
186
+ }
187
+ dir = parent;
188
+ if (path_1.default.dirname(dir) === dir) {
189
+ break; // never the filesystem root
190
+ }
191
+ if (homeResolved.length > 0 &&
192
+ isSameOrAncestor({ dir: dir, of: homeResolved })) {
193
+ break; // never the home directory or above it
194
+ }
195
+ var candidate = path_1.default.join(dir, fileName);
196
+ if (isOwnedFile({ candidate: candidate, ownerUid: ownerUid })) {
197
+ return candidate;
198
+ }
199
+ }
200
+ return null;
201
+ }
202
+ /**
203
+ * @description True when the path is a regular file owned by `ownerUid`
204
+ * (any owner when `ownerUid` is negative). Stat only. Never throws.
205
+ * @param {{candidate: string, ownerUid: number}} args
206
+ * @returns {boolean}
207
+ */
208
+ function isOwnedFile(args) {
209
+ try {
210
+ var stat = fs_1.default.statSync(args.candidate);
211
+ if (!stat.isFile()) {
212
+ return false;
213
+ }
214
+ return args.ownerUid < 0 || stat.uid === args.ownerUid;
215
+ }
216
+ catch (e) {
217
+ return false;
218
+ }
219
+ }
220
+ /**
221
+ * @description process.getuid(), or -1 where it does not exist (Windows),
222
+ * which disables the ownership check. Never throws.
223
+ * @returns {number}
224
+ */
225
+ function currentUid() {
226
+ try {
227
+ return typeof process.getuid === "function" ? process.getuid() : -1;
228
+ }
229
+ catch (e) {
230
+ return -1;
231
+ }
232
+ }
233
+ /**
234
+ * @description True when `dir` is `of` itself or one of its ancestors.
235
+ * @param {{dir: string, of: string}} args - Both absolute.
236
+ * @returns {boolean}
237
+ */
238
+ function isSameOrAncestor(args) {
239
+ var rel = path_1.default.relative(args.dir, args.of);
240
+ if (rel === "") {
241
+ return true;
242
+ }
243
+ return rel.indexOf("..") !== 0 && !path_1.default.isAbsolute(rel);
244
+ }
245
+ /**
246
+ * @description os.homedir(), or "" when it cannot be determined. Never throws.
247
+ * @returns {string}
248
+ */
249
+ function safeHomeDir() {
250
+ try {
251
+ var home = os_1.default.homedir();
252
+ return typeof home === "string" ? home : "";
253
+ }
254
+ catch (e) {
255
+ return "";
256
+ }
102
257
  }
103
258
  /**
104
259
  * @description True when the path exists and is a regular file. Never throws.
package/dist/index.js CHANGED
@@ -8,6 +8,7 @@ exports.encodeV2Values = exports.decodeV2Values = void 0;
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const bootstrap_1 = require("./bootstrap");
10
10
  const FileLogger_1 = require("./FileLogger");
11
+ const authFailure_1 = require("./authFailure");
11
12
  // Library exports — consumers can `import { decodeV2Values } from "@tenonhq/dovetail-core"`.
12
13
  // Keep exports above the CLI entry so bundlers/TS can tree-shake and require() consumers
13
14
  // never accidentally invoke main().
@@ -28,6 +29,9 @@ async function main() {
28
29
  // Only run the CLI when this file is executed directly (e.g. `npx dove`, `node dist/index.js`).
29
30
  // When imported as a library, require.main !== module and main() is skipped.
30
31
  if (require.main === module) {
32
+ // A run the instance turned away (HTTP 401/403) exits AUTH_EXIT_CODE (77), not the
33
+ // generic 1 — see authFailure.ts. Every other exit code is left as it was.
34
+ (0, authFailure_1.installAuthExitCode)(process);
31
35
  main().catch(function (e) {
32
36
  FileLogger_1.fileLogger.error("Fatal error: " + String(e));
33
37
  process.exit(1);
@@ -53,6 +53,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
53
53
  return (mod && mod.__esModule) ? mod : { "default": mod };
54
54
  };
55
55
  Object.defineProperty(exports, "__esModule", { value: true });
56
+ exports.applyDeletes = applyDeletes;
56
57
  exports.applyCreates = applyCreates;
57
58
  exports.reconcileCommand = reconcileCommand;
58
59
  const path_1 = __importDefault(require("path"));
package/dist/snClient.js CHANGED
@@ -8,6 +8,7 @@ exports.setBenchmarkSink = setBenchmarkSink;
8
8
  exports._resetDovetailApiFallback = _resetDovetailApiFallback;
9
9
  exports._isUsingLegacyPath = _isUsingLegacyPath;
10
10
  exports._callDovetailApi = _callDovetailApi;
11
+ exports._noteAuthRejection = _noteAuthRejection;
11
12
  exports.unwrapTableAPIFirstItem = unwrapTableAPIFirstItem;
12
13
  const axios_1 = __importDefault(require("axios"));
13
14
  const axios_cookiejar_support_1 = require("axios-cookiejar-support");
@@ -16,6 +17,7 @@ const tough_cookie_1 = require("tough-cookie");
16
17
  const genericUtils_1 = require("./genericUtils");
17
18
  const Logger_1 = require("./Logger");
18
19
  const FileLogger_1 = require("./FileLogger");
20
+ const authFailure_1 = require("./authFailure");
19
21
  // Benchmark sink. Null when --benchmark is off; zero overhead in that case.
20
22
  let _benchmarkSink = null;
21
23
  function setBenchmarkSink(sink) {
@@ -149,6 +151,67 @@ async function _callDovetailApi(op, call) {
149
151
  throw _enrichDovetailApiError(e, endpoint);
150
152
  }
151
153
  }
154
+ // The table a request targeted: the Table API path segment, or the `table` field
155
+ // of a Dovetail REST body. "" when neither is present. Only used to name the table
156
+ // in the 403 message, which echoes it only when it is a plain table name.
157
+ function _requestTable(path, data) {
158
+ var match = /^api\/now\/table\/([A-Za-z0-9_]+)(\/|$)/.exec(path);
159
+ if (match)
160
+ return match[1];
161
+ var body = data;
162
+ if (typeof body === "string") {
163
+ try {
164
+ body = JSON.parse(body);
165
+ }
166
+ catch (_) {
167
+ return "";
168
+ }
169
+ }
170
+ if (body && typeof body === "object") {
171
+ var table = body.table;
172
+ if (typeof table === "string")
173
+ return table;
174
+ }
175
+ return "";
176
+ }
177
+ /**
178
+ * The ONE place an HTTP 401/403 is recorded (#185). Every request an snClient
179
+ * makes passes its response interceptor, which calls this, so `push`,
180
+ * `reconcile --apply`, `create-record`, `delete-record`, `createUpdateSet` and any
181
+ * future verb get the same message and exit code without wiring a call site.
182
+ *
183
+ * Never throws: the caller must still see the original HTTP error.
184
+ */
185
+ function _noteAuthRejection(e) {
186
+ try {
187
+ if (!axios_1.default.isAxiosError(e) || !e.response)
188
+ return;
189
+ var config = e.config;
190
+ var method = config && typeof config.method === "string" ? config.method.toUpperCase() : "";
191
+ var url = config ? config.url : undefined;
192
+ var rejection = (0, authFailure_1.classifyAuthRejection)({
193
+ status: e.response.status,
194
+ method: method,
195
+ url: url,
196
+ });
197
+ if (!rejection)
198
+ return;
199
+ (0, authFailure_1.recordAuthFailure)({ write: rejection.write });
200
+ if (!(0, authFailure_1.firstRejectionOfKind)(rejection))
201
+ return;
202
+ var path = (0, authFailure_1.requestPath)(url);
203
+ var baseURL = config && typeof config.baseURL === "string" ? config.baseURL : "";
204
+ Logger_1.logger.error((0, authFailure_1.buildAuthFailureMessage)({
205
+ status: rejection.status,
206
+ action: "calling " + (method ? method + " " : "") + (path ? path : "the instance"),
207
+ instance: baseURL ? baseURL : process.env.SN_INSTANCE,
208
+ table: _requestTable(path, config ? config.data : undefined),
209
+ }));
210
+ }
211
+ catch (_) {
212
+ // Reporting must never mask the HTTP error itself.
213
+ }
214
+ }
152
215
  function _getRetryAfterMs(e) {
153
216
  if (axios_1.default.isAxiosError(e) && e.response && e.response.headers) {
154
217
  var retryAfter = e.response.headers["retry-after"];
@@ -172,11 +235,16 @@ const retryOnHttpErr = async (f, recSummary) => {
172
235
  catch (e) {
173
236
  var status = _getHttpStatus(e);
174
237
  attempt++;
175
- // 401/403: Auth failure — fail immediately
176
- if (status === 401 || status === 403) {
177
- var authMsg = status === 401 ? "Unauthorized" : "Forbidden";
178
- Logger_1.logger.error(authMsg + " (" + status + ") pushing " + recSummary +
179
- ". Verify your ServiceNow credentials and permissions.");
238
+ // 401/403: Auth failure — fail immediately. The snClient response
239
+ // interceptor (_noteAuthRejection) has already recorded it and printed the
240
+ // instance, env file and next step once; this line names the record.
241
+ if ((0, authFailure_1.isAuthStatus)(status)) {
242
+ Logger_1.logger.error((status === 401 ? "Unauthorized (401)" : "Forbidden (403)") +
243
+ " pushing " + recSummary + ". " +
244
+ (status === 401
245
+ ? "ServiceNow rejected the credentials."
246
+ : "ServiceNow refused the write for this user.") +
247
+ " See the message above for the instance, env file and next step.");
180
248
  throw e;
181
249
  }
182
250
  // 404: Record not found — fail immediately
@@ -311,6 +379,8 @@ const snClient = (baseURL, username, password, apiKey) => {
311
379
  }, function (error) {
312
380
  // Preserve original rejection; don't record errored requests (they skew
313
381
  // latency tails without adding signal for the "scales the same" question).
382
+ // A 401/403 is noted here, the one place every request passes (#185).
383
+ _noteAuthRejection(error);
314
384
  return Promise.reject(error);
315
385
  });
316
386
  const client = (0, axios_rate_limit_1.default)(rawAxios, { maxRPS: 20 });
@@ -687,6 +757,8 @@ const unwrapSNResponse = async (clientPromise) => {
687
757
  scope = manifestMatch[1];
688
758
  Logger_1.logger.error("Error from " + instance + ": HTTP " + status + " " +
689
759
  method + " " + url + snMessage);
760
+ // A 401/403 was already recorded, with its next step, by the snClient
761
+ // response interceptor (_noteAuthRejection).
690
762
  FileLogger_1.fileLogger.debug("REST error detail", {
691
763
  instance: instance,
692
764
  scope: scope,