@tenonhq/dovetail-core 0.0.130 → 0.0.132

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/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,8 @@ 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 fingerprint_1 = require("./fingerprint");
21
+ const authFailure_1 = require("./authFailure");
19
22
  // Benchmark sink. Null when --benchmark is off; zero overhead in that case.
20
23
  let _benchmarkSink = null;
21
24
  function setBenchmarkSink(sink) {
@@ -149,6 +152,67 @@ async function _callDovetailApi(op, call) {
149
152
  throw _enrichDovetailApiError(e, endpoint);
150
153
  }
151
154
  }
155
+ // The table a request targeted: the Table API path segment, or the `table` field
156
+ // of a Dovetail REST body. "" when neither is present. Only used to name the table
157
+ // in the 403 message, which echoes it only when it is a plain table name.
158
+ function _requestTable(path, data) {
159
+ var match = /^api\/now\/table\/([A-Za-z0-9_]+)(\/|$)/.exec(path);
160
+ if (match)
161
+ return match[1];
162
+ var body = data;
163
+ if (typeof body === "string") {
164
+ try {
165
+ body = JSON.parse(body);
166
+ }
167
+ catch (_) {
168
+ return "";
169
+ }
170
+ }
171
+ if (body && typeof body === "object") {
172
+ var table = body.table;
173
+ if (typeof table === "string")
174
+ return table;
175
+ }
176
+ return "";
177
+ }
178
+ /**
179
+ * The ONE place an HTTP 401/403 is recorded (#185). Every request an snClient
180
+ * makes passes its response interceptor, which calls this, so `push`,
181
+ * `reconcile --apply`, `create-record`, `delete-record`, `createUpdateSet` and any
182
+ * future verb get the same message and exit code without wiring a call site.
183
+ *
184
+ * Never throws: the caller must still see the original HTTP error.
185
+ */
186
+ function _noteAuthRejection(e) {
187
+ try {
188
+ if (!axios_1.default.isAxiosError(e) || !e.response)
189
+ return;
190
+ var config = e.config;
191
+ var method = config && typeof config.method === "string" ? config.method.toUpperCase() : "";
192
+ var url = config ? config.url : undefined;
193
+ var rejection = (0, authFailure_1.classifyAuthRejection)({
194
+ status: e.response.status,
195
+ method: method,
196
+ url: url,
197
+ });
198
+ if (!rejection)
199
+ return;
200
+ (0, authFailure_1.recordAuthFailure)({ write: rejection.write });
201
+ if (!(0, authFailure_1.firstRejectionOfKind)(rejection))
202
+ return;
203
+ var path = (0, authFailure_1.requestPath)(url);
204
+ var baseURL = config && typeof config.baseURL === "string" ? config.baseURL : "";
205
+ Logger_1.logger.error((0, authFailure_1.buildAuthFailureMessage)({
206
+ status: rejection.status,
207
+ action: "calling " + (method ? method + " " : "") + (path ? path : "the instance"),
208
+ instance: baseURL ? baseURL : process.env.SN_INSTANCE,
209
+ table: _requestTable(path, config ? config.data : undefined),
210
+ }));
211
+ }
212
+ catch (_) {
213
+ // Reporting must never mask the HTTP error itself.
214
+ }
215
+ }
152
216
  function _getRetryAfterMs(e) {
153
217
  if (axios_1.default.isAxiosError(e) && e.response && e.response.headers) {
154
218
  var retryAfter = e.response.headers["retry-after"];
@@ -172,11 +236,16 @@ const retryOnHttpErr = async (f, recSummary) => {
172
236
  catch (e) {
173
237
  var status = _getHttpStatus(e);
174
238
  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.");
239
+ // 401/403: Auth failure — fail immediately. The snClient response
240
+ // interceptor (_noteAuthRejection) has already recorded it and printed the
241
+ // instance, env file and next step once; this line names the record.
242
+ if ((0, authFailure_1.isAuthStatus)(status)) {
243
+ Logger_1.logger.error((status === 401 ? "Unauthorized (401)" : "Forbidden (403)") +
244
+ " pushing " + recSummary + ". " +
245
+ (status === 401
246
+ ? "ServiceNow rejected the credentials."
247
+ : "ServiceNow refused the write for this user.") +
248
+ " See the message above for the instance, env file and next step.");
180
249
  throw e;
181
250
  }
182
251
  // 404: Record not found — fail immediately
@@ -311,6 +380,8 @@ const snClient = (baseURL, username, password, apiKey) => {
311
380
  }, function (error) {
312
381
  // Preserve original rejection; don't record errored requests (they skew
313
382
  // latency tails without adding signal for the "scales the same" question).
383
+ // A 401/403 is noted here, the one place every request passes (#185).
384
+ _noteAuthRejection(error);
314
385
  return Promise.reject(error);
315
386
  });
316
387
  const client = (0, axios_rate_limit_1.default)(rawAxios, { maxRPS: 20 });
@@ -539,7 +610,19 @@ const snClient = (baseURL, username, password, apiKey) => {
539
610
  const endpoint = `api/cadso/dovetail_sync/bulkDownload`;
540
611
  const tableCount = Object.keys(missingFiles).length;
541
612
  FileLogger_1.fileLogger.debug("Bulk downloading files for " + tableCount + " tables");
542
- return client.post(endpoint, { missingFiles, tableOptions });
613
+ // `fingerprint` is client-only: stripped from the request, applied to the
614
+ // response (see fingerprint.ts).
615
+ return client
616
+ .post(endpoint, {
617
+ missingFiles,
618
+ tableOptions: (0, fingerprint_1.stripClientOnlyTableOptions)(tableOptions),
619
+ })
620
+ .then(function (resp) {
621
+ if (resp && resp.data && resp.data.result) {
622
+ (0, fingerprint_1.applyFingerprints)(resp.data.result, tableOptions);
623
+ }
624
+ return resp;
625
+ });
543
626
  };
544
627
  const getManifest = (scope, config, withFiles = false) => {
545
628
  const endpoint = `api/cadso/dovetail_sync/getManifest/${scope}`;
@@ -548,12 +631,22 @@ const snClient = (baseURL, username, password, apiKey) => {
548
631
  var cleanIncludes = _stripUnderscoreKeys(includes);
549
632
  var cleanExcludes = _stripUnderscoreKeys(excludes);
550
633
  FileLogger_1.fileLogger.debug("Fetching manifest for scope " + scope + (withFiles ? " (with file contents)" : " (structure only)"));
551
- return client.post(endpoint, {
634
+ return client
635
+ .post(endpoint, {
552
636
  includes: cleanIncludes,
553
637
  excludes: cleanExcludes,
554
- tableOptions,
638
+ tableOptions: (0, fingerprint_1.stripClientOnlyTableOptions)(tableOptions),
555
639
  withFiles,
556
640
  getContents: withFiles, // ServiceNow expects getContents, not withFiles
641
+ })
642
+ .then(function (resp) {
643
+ // Fingerprinted fields come back as `<field>.sha256` entries (and with
644
+ // hashed content when withFiles is set), so the manifest, the
645
+ // missing-file check and every writer agree on the on-disk name.
646
+ if (resp && resp.data && resp.data.result && resp.data.result.tables) {
647
+ (0, fingerprint_1.applyFingerprints)(resp.data.result.tables, tableOptions);
648
+ }
649
+ return resp;
557
650
  });
558
651
  };
559
652
  const changeUpdateSet = (params) => {
@@ -687,6 +780,8 @@ const unwrapSNResponse = async (clientPromise) => {
687
780
  scope = manifestMatch[1];
688
781
  Logger_1.logger.error("Error from " + instance + ": HTTP " + status + " " +
689
782
  method + " " + url + snMessage);
783
+ // A 401/403 was already recorded, with its next step, by the snClient
784
+ // response interceptor (_noteAuthRejection).
690
785
  FileLogger_1.fileLogger.debug("REST error detail", {
691
786
  instance: instance,
692
787
  scope: scope,
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ // The exit hook in a REAL Node process (#185).
3
+ //
4
+ // authFailure.test.ts checks installAuthExitCode against a hand-built fake `proc`,
5
+ // which would still pass if Node ignored an `exitCode` set inside an `exit`
6
+ // listener. These tests spawn `node`, install the hook on the real `process`, and
7
+ // assert the status the parent actually sees.
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const child_process_1 = require("child_process");
13
+ const fs_1 = __importDefault(require("fs"));
14
+ const os_1 = __importDefault(require("os"));
15
+ const path_1 = __importDefault(require("path"));
16
+ const typescript_1 = __importDefault(require("typescript"));
17
+ var RUNNER = [
18
+ '"use strict";',
19
+ 'var auth = require("./authFailure.js");',
20
+ "auth.installAuthExitCode(process);",
21
+ "var mode = process.argv[2];",
22
+ "var exitWith = process.argv[3];",
23
+ 'if (mode === "write") auth.recordAuthFailure({ write: true });',
24
+ 'if (mode === "read") auth.recordAuthFailure();',
25
+ 'if (exitWith !== "natural") process.exit(Number(exitWith));',
26
+ "",
27
+ ].join("\n");
28
+ describe("installAuthExitCode in a child process (#185)", function () {
29
+ var dir = "";
30
+ var runner = "";
31
+ beforeAll(function () {
32
+ dir = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), "dove-auth-exit-"));
33
+ // authFailure.ts imports nothing, so one transpiled file is the whole module.
34
+ var source = fs_1.default.readFileSync(path_1.default.join(__dirname, "..", "authFailure.ts"), "utf8");
35
+ var compiled = typescript_1.default.transpileModule(source, {
36
+ compilerOptions: {
37
+ module: typescript_1.default.ModuleKind.CommonJS,
38
+ target: typescript_1.default.ScriptTarget.ES2019,
39
+ },
40
+ });
41
+ fs_1.default.writeFileSync(path_1.default.join(dir, "authFailure.js"), compiled.outputText);
42
+ runner = path_1.default.join(dir, "runner.js");
43
+ fs_1.default.writeFileSync(runner, RUNNER);
44
+ });
45
+ afterAll(function () {
46
+ if (dir)
47
+ fs_1.default.rmSync(dir, { recursive: true, force: true });
48
+ });
49
+ function exitStatus(mode, exitWith) {
50
+ var result = (0, child_process_1.spawnSync)(process.execPath, [runner, mode, exitWith], {
51
+ encoding: "utf8",
52
+ timeout: 20000,
53
+ });
54
+ if (result.error)
55
+ throw result.error;
56
+ return result.status;
57
+ }
58
+ it("a rejected write turns process.exit(0) into 77", function () {
59
+ expect(exitStatus("write", "0")).toBe(77);
60
+ });
61
+ it("nothing recorded leaves process.exit(0) at 0", function () {
62
+ expect(exitStatus("none", "0")).toBe(0);
63
+ });
64
+ it("a tolerated 401 read turns process.exit(1) into 77", function () {
65
+ expect(exitStatus("read", "1")).toBe(77);
66
+ });
67
+ it("a tolerated 401 read leaves a clean exit at 0", function () {
68
+ expect(exitStatus("read", "0")).toBe(0);
69
+ });
70
+ it("a rejected write turns process.exit(1) and a natural end into 77", function () {
71
+ expect(exitStatus("write", "1")).toBe(77);
72
+ expect(exitStatus("write", "natural")).toBe(77);
73
+ });
74
+ it("nothing recorded leaves process.exit(1) at 1", function () {
75
+ expect(exitStatus("none", "1")).toBe(1);
76
+ });
77
+ it("any other exit code is left alone, even after a rejected write", function () {
78
+ expect(exitStatus("write", "2")).toBe(2);
79
+ expect(exitStatus("read", "130")).toBe(130);
80
+ });
81
+ });
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const authFailure_1 = require("../authFailure");
4
+ var SECRET = "hunter2-do-not-print";
5
+ var HOST = "example.invalid";
6
+ describe("authFailure (#185)", function () {
7
+ beforeEach(function () {
8
+ (0, authFailure_1.resetAuthFailureState)();
9
+ });
10
+ it("uses a distinct exit code", function () {
11
+ expect(authFailure_1.AUTH_EXIT_CODE).toBe(77);
12
+ expect((0, authFailure_1.isAuthStatus)(401)).toBe(true);
13
+ expect((0, authFailure_1.isAuthStatus)(403)).toBe(true);
14
+ expect((0, authFailure_1.isAuthStatus)(404)).toBe(false);
15
+ expect((0, authFailure_1.isAuthStatus)("401")).toBe(false);
16
+ });
17
+ describe("instanceHost", function () {
18
+ it("reduces an instance value to a bare host", function () {
19
+ expect((0, authFailure_1.instanceHost)(HOST)).toBe(HOST);
20
+ expect((0, authFailure_1.instanceHost)("https://" + HOST + "/")).toBe(HOST);
21
+ expect((0, authFailure_1.instanceHost)("https://" + HOST + "/api/now?x=1")).toBe(HOST);
22
+ });
23
+ it("drops userinfo so a credential in the value cannot leak", function () {
24
+ expect((0, authFailure_1.instanceHost)("https://admin:" + SECRET + "@" + HOST)).toBe(HOST);
25
+ });
26
+ it("returns empty for anything that is not a plain host", function () {
27
+ expect((0, authFailure_1.instanceHost)("")).toBe("");
28
+ expect((0, authFailure_1.instanceHost)(undefined)).toBe("");
29
+ expect((0, authFailure_1.instanceHost)("not a host; echo x")).toBe("");
30
+ });
31
+ });
32
+ describe("classifyAuthRejection", function () {
33
+ it("treats a 401 on any method as a rejection, a write only when it is not a GET", function () {
34
+ expect((0, authFailure_1.classifyAuthRejection)({ status: 401, method: "get" })).toEqual({ status: 401, write: false });
35
+ expect((0, authFailure_1.classifyAuthRejection)({ status: 401, method: "POST" })).toEqual({ status: 401, write: true });
36
+ });
37
+ it("treats a 403 as a rejection only on a write", function () {
38
+ expect((0, authFailure_1.classifyAuthRejection)({ status: 403, method: "GET" })).toBeNull();
39
+ ["post", "PUT", "patch", "DELETE"].forEach(function (method) {
40
+ expect((0, authFailure_1.classifyAuthRejection)({ status: 403, method: method, url: "api/now/table/x" })).toEqual({
41
+ status: 403,
42
+ write: true,
43
+ });
44
+ });
45
+ });
46
+ it("counts the read-only POST endpoints as reads", function () {
47
+ expect((0, authFailure_1.classifyAuthRejection)({ status: 403, method: "POST", url: "api/cadso/dovetail_sync/getManifest/x_s" })).toBeNull();
48
+ expect((0, authFailure_1.classifyAuthRejection)({ status: 403, method: "POST", url: "/api/cadso/dovetail_sync/bulkDownload?x=1" })).toBeNull();
49
+ expect((0, authFailure_1.classifyAuthRejection)({ status: 401, method: "POST", url: "api/cadso/dovetail_sync/bulkDownload" })).toEqual({ status: 401, write: false });
50
+ // A look-alike name is still a write.
51
+ expect((0, authFailure_1.classifyAuthRejection)({ status: 403, method: "POST", url: "api/cadso/dovetail_sync/getManifestX" })).toEqual({ status: 403, write: true });
52
+ });
53
+ it("ignores other statuses and never calls a request with no method a write", function () {
54
+ expect((0, authFailure_1.classifyAuthRejection)({ status: 404, method: "POST" })).toBeNull();
55
+ expect((0, authFailure_1.classifyAuthRejection)({ status: "403", method: "POST" })).toBeNull();
56
+ expect((0, authFailure_1.classifyAuthRejection)({ status: 403, method: undefined })).toBeNull();
57
+ expect((0, authFailure_1.classifyAuthRejection)({ status: 401, method: 7 })).toEqual({ status: 401, write: false });
58
+ });
59
+ it("reports the first rejection of each kind once", function () {
60
+ expect((0, authFailure_1.firstRejectionOfKind)({ status: 403, write: true })).toBe(true);
61
+ expect((0, authFailure_1.firstRejectionOfKind)({ status: 403, write: true })).toBe(false);
62
+ expect((0, authFailure_1.firstRejectionOfKind)({ status: 401, write: true })).toBe(true);
63
+ expect((0, authFailure_1.firstRejectionOfKind)({ status: 401, write: false })).toBe(true);
64
+ });
65
+ });
66
+ describe("requestPath", function () {
67
+ it("keeps only the path", function () {
68
+ expect((0, authFailure_1.requestPath)("api/now/table/x/abc")).toBe("api/now/table/x/abc");
69
+ expect((0, authFailure_1.requestPath)("/api/now/table/x?sysparm_query=a%3Db#frag")).toBe("api/now/table/x");
70
+ expect((0, authFailure_1.requestPath)("https://admin:" + SECRET + "@" + HOST + "/api/now/table/x")).toBe("api/now/table/x");
71
+ });
72
+ it("returns empty for anything it cannot echo safely", function () {
73
+ expect((0, authFailure_1.requestPath)(undefined)).toBe("");
74
+ expect((0, authFailure_1.requestPath)("")).toBe("");
75
+ expect((0, authFailure_1.requestPath)("api/now/table/x y")).toBe("");
76
+ expect((0, authFailure_1.requestPath)("api/$(whoami)")).toBe("");
77
+ });
78
+ });
79
+ describe("reauthCommand", function () {
80
+ it("is plain dove login when no --env was used", function () {
81
+ expect((0, authFailure_1.reauthCommand)()).toBe("dove login");
82
+ });
83
+ it("carries the --env selector the user typed", function () {
84
+ (0, authFailure_1.setAuthContext)({ envPath: "/work/.env.loft", envArg: "loft" });
85
+ expect((0, authFailure_1.reauthCommand)()).toBe("dove login --env loft");
86
+ expect((0, authFailure_1.reauthCommand)("../envs/shop.env")).toBe("dove login --env ../envs/shop.env");
87
+ });
88
+ it("never echoes a selector with shell metacharacters", function () {
89
+ expect((0, authFailure_1.reauthCommand)("loft; echo x")).toBe("dove login --env <name>");
90
+ expect((0, authFailure_1.reauthCommand)("$(whoami)")).toBe("dove login --env <name>");
91
+ expect((0, authFailure_1.reauthCommand)("a b")).toBe("dove login --env <name>");
92
+ });
93
+ });
94
+ describe("buildAuthFailureMessage", function () {
95
+ it("names the host, the env file and the re-auth command for a 401", function () {
96
+ (0, authFailure_1.setAuthContext)({ envPath: "/work/.env.loft", envArg: "loft" });
97
+ var msg = (0, authFailure_1.buildAuthFailureMessage)({
98
+ status: 401,
99
+ action: "pushing sys_script_include > Thing",
100
+ instance: HOST,
101
+ });
102
+ expect(msg).toContain("Unauthorized (401) pushing sys_script_include > Thing");
103
+ expect(msg).toContain(HOST + " rejected the credentials loaded from /work/.env.loft");
104
+ expect(msg).toContain("Re-authenticate with: dove login --env loft");
105
+ expect(msg).toContain("exits 77");
106
+ });
107
+ it("explains a 403 as a refused write and does not offer dove login as the remedy", function () {
108
+ (0, authFailure_1.setAuthContext)({ envPath: "/work/.env", envArg: "" });
109
+ var msg = (0, authFailure_1.buildAuthFailureMessage)({
110
+ status: 403,
111
+ action: "calling POST api/x",
112
+ instance: HOST,
113
+ table: "sys_script_include",
114
+ });
115
+ expect(msg).toContain("Forbidden (403) calling POST api/x");
116
+ expect(msg).toContain(HOST + " accepted the sign-in but refused the write for this user");
117
+ expect(msg).toContain("Check the role or ACL for table sys_script_include for the user in /work/.env");
118
+ expect(msg).toContain("exits 77");
119
+ expect(msg).not.toContain("dove login");
120
+ expect(msg).not.toContain("Re-authenticate");
121
+ });
122
+ it("a 403 with no usable table name says 'the table' and never echoes an odd value", function () {
123
+ var plain = (0, authFailure_1.buildAuthFailureMessage)({ status: 403, action: "calling POST api/x" });
124
+ expect(plain).toContain("Check the role or ACL for the table for the user in the loaded env file");
125
+ var odd = (0, authFailure_1.buildAuthFailureMessage)({
126
+ status: 403,
127
+ action: "calling POST api/x",
128
+ table: "x; echo " + SECRET,
129
+ });
130
+ expect(odd).toContain("for the table for the user");
131
+ expect(odd).not.toContain(SECRET);
132
+ });
133
+ it("a 401 still offers dove login", function () {
134
+ var msg = (0, authFailure_1.buildAuthFailureMessage)({ status: 401, action: "calling GET api/x", instance: HOST });
135
+ expect(msg).toContain("Re-authenticate with: dove login");
136
+ });
137
+ it("falls back to neutral wording when the host and env file are unknown", function () {
138
+ var msg = (0, authFailure_1.buildAuthFailureMessage)({ status: 401, action: "pushing x" });
139
+ expect(msg).toContain("the ServiceNow instance rejected the credentials in the loaded env file");
140
+ expect(msg).toContain("dove login");
141
+ });
142
+ it("never prints a credential, whatever the environment holds", function () {
143
+ var saved = { user: process.env.SN_USER, password: process.env.SN_PASSWORD, key: process.env.SN_API_KEY };
144
+ process.env.SN_USER = "svc-" + SECRET;
145
+ process.env.SN_PASSWORD = SECRET;
146
+ process.env.SN_API_KEY = "key-" + SECRET;
147
+ try {
148
+ (0, authFailure_1.setAuthContext)({ envPath: "/work/.env.loft", envArg: "loft" });
149
+ [401, 403].forEach(function (status) {
150
+ var msg = (0, authFailure_1.buildAuthFailureMessage)({
151
+ status: status,
152
+ action: "pushing x",
153
+ instance: "https://admin:" + SECRET + "@" + HOST,
154
+ });
155
+ expect(msg).not.toContain(SECRET);
156
+ expect(msg).toContain(HOST);
157
+ });
158
+ }
159
+ finally {
160
+ if (saved.user === undefined)
161
+ delete process.env.SN_USER;
162
+ else
163
+ process.env.SN_USER = saved.user;
164
+ if (saved.password === undefined)
165
+ delete process.env.SN_PASSWORD;
166
+ else
167
+ process.env.SN_PASSWORD = saved.password;
168
+ if (saved.key === undefined)
169
+ delete process.env.SN_API_KEY;
170
+ else
171
+ process.env.SN_API_KEY = saved.key;
172
+ }
173
+ });
174
+ });
175
+ describe("resolveExitCode", function () {
176
+ it("leaves every code alone when nothing was rejected", function () {
177
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(0);
178
+ expect((0, authFailure_1.resolveExitCode)(1)).toBe(1);
179
+ expect((0, authFailure_1.resolveExitCode)(2)).toBe(2);
180
+ expect((0, authFailure_1.resolveExitCode)(undefined)).toBe(0);
181
+ });
182
+ it("re-maps only a generic failure after a rejected read", function () {
183
+ (0, authFailure_1.recordAuthFailure)();
184
+ expect((0, authFailure_1.resolveExitCode)(1)).toBe(77);
185
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(0);
186
+ expect((0, authFailure_1.resolveExitCode)(2)).toBe(2);
187
+ });
188
+ it("never lets a rejected write exit clean, and keeps other codes", function () {
189
+ (0, authFailure_1.recordAuthFailure)({ write: true });
190
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(77);
191
+ expect((0, authFailure_1.resolveExitCode)(1)).toBe(77);
192
+ expect((0, authFailure_1.resolveExitCode)(2)).toBe(2);
193
+ expect((0, authFailure_1.resolveExitCode)(130)).toBe(130);
194
+ });
195
+ });
196
+ describe("installAuthExitCode", function () {
197
+ function fakeProcess() {
198
+ var listeners = [];
199
+ var proc = {
200
+ exitCode: undefined,
201
+ on: function (_event, listener) {
202
+ listeners.push(listener);
203
+ return proc;
204
+ },
205
+ emitExit: function (code) {
206
+ listeners.forEach(function (l) {
207
+ l(code);
208
+ });
209
+ },
210
+ };
211
+ return proc;
212
+ }
213
+ it("sets the auth exit code on exit after a rejected write", function () {
214
+ var proc = fakeProcess();
215
+ (0, authFailure_1.installAuthExitCode)(proc);
216
+ (0, authFailure_1.recordAuthFailure)({ write: true });
217
+ proc.emitExit(1);
218
+ expect(proc.exitCode).toBe(77);
219
+ });
220
+ it("does not touch the exit code when nothing was rejected", function () {
221
+ var proc = fakeProcess();
222
+ (0, authFailure_1.installAuthExitCode)(proc);
223
+ proc.emitExit(1);
224
+ expect(proc.exitCode).toBeUndefined();
225
+ });
226
+ });
227
+ });
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ // After the instance delete, `dove delete` removes the record's local folder.
3
+ // It used to join the TOP-LEVEL sourceDirectory (src/<table>/<name>), but
4
+ // records live under their scope's folder (src/Core/..., or nested as
5
+ // src/UIComponents/<scope>/...), so the cleanup silently found nothing. It now
6
+ // uses the scope's own folder.
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ jest.mock("../Logger", function () {
12
+ return {
13
+ logger: {
14
+ info: jest.fn(),
15
+ debug: jest.fn(),
16
+ warn: jest.fn(),
17
+ error: jest.fn(),
18
+ success: jest.fn(),
19
+ getLogLevel: function () { return "info"; },
20
+ },
21
+ };
22
+ });
23
+ jest.mock("../FileLogger", function () {
24
+ return { fileLogger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() } };
25
+ });
26
+ jest.mock("../commands", function () {
27
+ return { setLogLevel: jest.fn() };
28
+ });
29
+ var mockRoot = "";
30
+ jest.mock("../config", function () {
31
+ var p = jest.requireActual("path");
32
+ return {
33
+ getSourcePath: function () { return p.join(mockRoot, "src"); },
34
+ getSourcePathForScope: function (scope) {
35
+ return p.join(mockRoot, "src", "UIComponents", scope);
36
+ },
37
+ loadScopeManifest: jest.fn().mockResolvedValue(undefined),
38
+ getManifest: function () { return undefined; },
39
+ getConfig: function () { return { scopes: {} }; },
40
+ isMultiScopeManifest: function () { return false; },
41
+ };
42
+ });
43
+ jest.mock("../FileUtils", function () {
44
+ return { writeScopeManifest: jest.fn().mockResolvedValue(undefined) };
45
+ });
46
+ var mockDelete = jest.fn();
47
+ jest.mock("../snClient", function () {
48
+ return {
49
+ defaultClient: function () {
50
+ return { deleteRecord: mockDelete };
51
+ },
52
+ };
53
+ });
54
+ const fs_1 = __importDefault(require("fs"));
55
+ const os_1 = __importDefault(require("os"));
56
+ const path_1 = __importDefault(require("path"));
57
+ const deleteRecordCommand_1 = require("../deleteRecordCommand");
58
+ describe("deleteRecordCommand local cleanup", function () {
59
+ beforeEach(function () {
60
+ mockRoot = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), "dove-delete-"));
61
+ mockDelete.mockReset();
62
+ mockDelete.mockResolvedValue({ data: { result: { name: "Panel" } } });
63
+ });
64
+ afterEach(function () {
65
+ fs_1.default.rmSync(mockRoot, { recursive: true, force: true });
66
+ });
67
+ it("removes the record folder under the scope's own folder", async function () {
68
+ var recordDir = path_1.default.join(mockRoot, "src", "UIComponents", "x_cadso_ui_panel", "sys_ux_lib_component", "Panel");
69
+ fs_1.default.mkdirSync(recordDir, { recursive: true });
70
+ fs_1.default.writeFileSync(path_1.default.join(recordDir, "metaData.json"), "{}");
71
+ await (0, deleteRecordCommand_1.deleteRecordCommand)({
72
+ table: "sys_ux_lib_component",
73
+ name: "Panel",
74
+ scope: "x_cadso_ui_panel",
75
+ sysid: "abc",
76
+ ci: true,
77
+ logLevel: "info",
78
+ });
79
+ expect(mockDelete).toHaveBeenCalledTimes(1);
80
+ expect(fs_1.default.existsSync(recordDir)).toBe(false);
81
+ });
82
+ it("leaves a same-named folder under the top-level source path alone", async function () {
83
+ var wrongDir = path_1.default.join(mockRoot, "src", "sys_ux_lib_component", "Panel");
84
+ fs_1.default.mkdirSync(wrongDir, { recursive: true });
85
+ await (0, deleteRecordCommand_1.deleteRecordCommand)({
86
+ table: "sys_ux_lib_component",
87
+ name: "Panel",
88
+ scope: "x_cadso_ui_panel",
89
+ sysid: "abc",
90
+ ci: true,
91
+ logLevel: "info",
92
+ });
93
+ expect(fs_1.default.existsSync(wrongDir)).toBe(true);
94
+ });
95
+ });
@@ -107,6 +107,25 @@ describe("getFileContextWithSkipReason", function () {
107
107
  expect(result.context.name).toBe("TestRecord");
108
108
  expect(result.context.scope).toBe("x_test");
109
109
  });
110
+ it("refuses a .sha256 fingerprint file even when its field is in the manifest", function () {
111
+ mockManifest = {
112
+ scope: "x_cadso_ui_form",
113
+ tables: {
114
+ sys_ux_lib_source_script: {
115
+ records: {
116
+ Bundle: {
117
+ sys_id: "f9cd",
118
+ files: [{ name: "script", type: "sha256" }],
119
+ },
120
+ },
121
+ },
122
+ },
123
+ };
124
+ mockIsMultiScope = false;
125
+ var result = (0, FileUtils_1.getFileContextWithSkipReason)("/project/src/UIComponents/x_cadso_ui_form/sys_ux_lib_source_script/Bundle/script.sha256");
126
+ expect(result.context).toBeUndefined();
127
+ expect(result.skipReason).toBe("fingerprint only, read-only");
128
+ });
110
129
  it("throws when no manifest is loaded", function () {
111
130
  mockManifest = null;
112
131
  expect(function () {