bdy 1.25.44-dev → 1.26.0-dev

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bdy",
3
3
  "preferGlobal": false,
4
- "version": "1.25.44-dev",
4
+ "version": "1.26.0-dev",
5
5
  "type": "commonjs",
6
6
  "license": "MIT",
7
7
  "homepage": "https://buddy.works/docs/cli",
@@ -50,6 +50,7 @@ class AgentLinux extends system_1.default {
50
50
  // cannot stop that. Closing this means the agent reading the token from a file only it can
51
51
  // read, which is a change of where the token lives, not of this template.
52
52
  getServiceConfig(id, host, token, port, user) {
53
+ this.validateServiceConfig(id, host, token, port);
53
54
  const cli = this.getSystemBinaryPath();
54
55
  return `[Unit]
55
56
  Description=Buddy Server Agent
@@ -126,8 +127,9 @@ WantedBy=multi-user.target`;
126
127
  async changeUser(user) {
127
128
  try {
128
129
  const json = this.loadSystemConfig();
129
- // Resolved before the service is touched: a name this machine does not have would
130
- // otherwise leave it stopped, with a config naming a user that does not exist
130
+ // Both checked before the service is touched: a config the unit cannot be rendered from, or
131
+ // a name this machine does not have, would otherwise leave it stopped
132
+ this.validateServiceConfig(json.id, json.host, json.token, json.port);
131
133
  if (user)
132
134
  await this.resolveUserIds(user);
133
135
  logger_1.default.info(texts_1.LOG_AGENT_STOPPING_SYSTEM);
@@ -173,6 +173,13 @@ class AgentManagerClass {
173
173
  logger_1.default.error(texts_1.LOG_AGENT_UPDATE_NO_ADMIN);
174
174
  return report(tunnel_1.TUNNEL_AGENT_UPDATE_STATUS.NO_ADMIN);
175
175
  }
176
+ // Before anything is staged: the update directory is created inside the system one, and
177
+ // the binary verified there is executed by this root process. On an install still at the
178
+ // 0777 an old cli left, anyone could swap it in between - see AgentSystem.tightenSystemDir.
179
+ if (!(await this.system.tightenSystemDir())) {
180
+ logger_1.default.error(texts_1.LOG_AGENT_UPDATE_FAILED);
181
+ return report(tunnel_1.TUNNEL_AGENT_UPDATE_STATUS.FAILED);
182
+ }
176
183
  const current = (0, utils_1.getVersion)();
177
184
  const latest = await (0, utils_1.getLatestVersion)();
178
185
  // Equality only, deliberately not "is latest newer": this runs on an explicit remote
@@ -862,6 +869,14 @@ class AgentManagerClass {
862
869
  await this.disableAgentAndExit(texts_1.ERR_AGENT_NOT_REGISTERED);
863
870
  return false;
864
871
  }
872
+ // A legacy install that is never updated remotely would otherwise stay world-writable for
873
+ // good. Only a service running with admin rights can take the directory back, and only one
874
+ // that still needs it does: a service user without them would fail every chown here.
875
+ if (this.system.serviceMode &&
876
+ this.system.isSystemDirLoose() &&
877
+ (await this.system.hasAdminRights())) {
878
+ await this.system.tightenSystemDir();
879
+ }
865
880
  const ok = this.resaveAgentConfig();
866
881
  if (!ok) {
867
882
  await this.disableAgentAndExit(texts_1.ERR_SAVING_AGENT_CONFIG);
@@ -42,6 +42,7 @@ class AgentOsx extends system_1.default {
42
42
  // the file mode is - see the note in AgentLinux.getServiceConfig. Closing this means the agent
43
43
  // reading the token from a file only it can read, which is a change of where the token lives.
44
44
  getServiceConfig(id, host, token, port, user) {
45
+ this.validateServiceConfig(id, host, token, port);
45
46
  const cli = this.getSystemBinaryPath();
46
47
  let cfg = `<?xml version='1.0' encoding='UTF-8'?>
47
48
  <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -137,8 +138,9 @@ class AgentOsx extends system_1.default {
137
138
  async changeUser(user) {
138
139
  try {
139
140
  const json = this.loadSystemConfig();
140
- // Resolved before the service is touched: a name this machine does not have would
141
- // otherwise leave it stopped, with a config naming a user that does not exist
141
+ // Both checked before the service is touched: a config the unit cannot be rendered from, or
142
+ // a name this machine does not have, would otherwise leave it stopped
143
+ this.validateServiceConfig(json.id, json.host, json.token, json.port);
142
144
  if (user)
143
145
  await this.resolveUserIds(user);
144
146
  logger_1.default.info(texts_1.LOG_AGENT_STOPPING_SYSTEM);
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const node_fs_1 = require("node:fs");
7
7
  const https_1 = __importDefault(require("https"));
8
8
  const path_1 = __importDefault(require("path"));
9
+ const node_stream_1 = require("node:stream");
9
10
  const utils_1 = require("../utils");
10
11
  const texts_1 = require("../texts");
11
12
  const logger_1 = __importDefault(require("../logger"));
@@ -49,6 +50,23 @@ class AgentSystem {
49
50
  getSystemConfigDir() {
50
51
  return '';
51
52
  }
53
+ // extend
54
+ getServicePath() {
55
+ return '';
56
+ }
57
+ // The values the service definition is rendered from - the systemd unit, the launchd plist. On
58
+ // changeUser they come out of agent.json, which belongs to the service user, who may write it:
59
+ // unchecked, a newline in any of them adds a directive to the unit (`ExecStartPre=+...` runs as
60
+ // root whatever User= says) and a `<` or `&` rewrites the plist. Every legitimate value fits: the
61
+ // id is a hash id, the token a UUID, the host an https URL.
62
+ validateServiceConfig(id, host, token, port) {
63
+ const safe = /^[A-Za-z0-9._:/+=@-]+$/;
64
+ const strings = [id, host, token].every((v) => typeof v === 'string' && safe.test(v));
65
+ const p = typeof port === 'string' && /^\d+$/.test(port) ? Number(port) : port;
66
+ const portOk = typeof p === 'number' && Number.isInteger(p) && p >= 1 && p <= 65535;
67
+ if (!strings || !portOk)
68
+ throw new Error(texts_1.ERR_AGENT_SERVICE_CONFIG_INVALID);
69
+ }
52
70
  // `--app` installs no service and runs the agent as the invoking user, so its files
53
71
  // belong to that user: a system location was the only thing making the mode need root.
54
72
  // They get their own directory rather than sitting next to cfg.json, so nothing here can
@@ -257,15 +275,53 @@ class AgentSystem {
257
275
  }
258
276
  this.tryRemove(backup);
259
277
  }
278
+ // Run by root after install and update, in a directory the service user owns: a link left at
279
+ // `bdy` would take the 0755 to any file it points at. So the mode goes on a descriptor opened
280
+ // without following one, the same way applySystemModes sets them.
260
281
  fixBinaryRights() {
261
- return new Promise((resolve, reject) => {
262
- (0, node_fs_1.chmod)(this.getSystemBinaryPath(), 0o755, (err) => {
263
- if (err)
264
- reject(err);
265
- else
266
- resolve();
267
- });
268
- });
282
+ const p = this.getSystemBinaryPath();
283
+ try {
284
+ if ((0, utils_1.isWindows)()) {
285
+ (0, node_fs_1.chmodSync)(p, 0o755);
286
+ return Promise.resolve();
287
+ }
288
+ const fd = this.openNoFollow(p);
289
+ try {
290
+ if (!(0, node_fs_1.fstatSync)(fd).isFile())
291
+ throw new Error((0, texts_1.ERR_AGENT_DIR_REPLACED)(p));
292
+ (0, node_fs_1.fchmodSync)(fd, 0o755);
293
+ }
294
+ finally {
295
+ (0, node_fs_1.closeSync)(fd);
296
+ }
297
+ return Promise.resolve();
298
+ }
299
+ catch (err) {
300
+ return Promise.reject(err);
301
+ }
302
+ }
303
+ // Writes one of the files in the system directory without following a link at its name. Root
304
+ // writes in here on install and `agent debug`, the directory belongs to the service user, and
305
+ // writeFile and chmod both follow a link that user could have left in place of one of ours - to
306
+ // /etc/shadow, say, which would come out overwritten and 0644. Refused at the open (O_NOFOLLOW)
307
+ // rather than checked first: a check is a second lookup the name can change in between.
308
+ // O_NONBLOCK so a fifo left here fails the open instead of hanging it.
309
+ writeFileNoFollow(p, data, mode) {
310
+ let flags = node_fs_1.constants.O_WRONLY | node_fs_1.constants.O_CREAT | node_fs_1.constants.O_TRUNC;
311
+ if (!(0, utils_1.isWindows)())
312
+ flags |= node_fs_1.constants.O_NOFOLLOW | node_fs_1.constants.O_NONBLOCK;
313
+ const fd = (0, node_fs_1.openSync)(p, flags, mode);
314
+ try {
315
+ if (!(0, utils_1.isWindows)()) {
316
+ if (!(0, node_fs_1.fstatSync)(fd).isFile())
317
+ throw new Error((0, texts_1.ERR_AGENT_DIR_REPLACED)(p));
318
+ (0, node_fs_1.fchmodSync)(fd, mode);
319
+ }
320
+ (0, node_fs_1.writeFileSync)(fd, data, { encoding: 'utf-8' });
321
+ }
322
+ finally {
323
+ (0, node_fs_1.closeSync)(fd);
324
+ }
269
325
  }
270
326
  loadSystemConfig() {
271
327
  const str = (0, node_fs_1.readFileSync)(this.getActiveConfigPath(), 'utf-8');
@@ -523,6 +579,53 @@ class AgentSystem {
523
579
  }
524
580
  });
525
581
  }
582
+ // An install made by cli <=1.23.5 left this directory at 0777 and its files at 0666, and only
583
+ // install, changeUser and the admin-run `bdy agent update` ever took that back - never a remote
584
+ // update or a plain service start, which is how most of the fleet runs. A machine updated
585
+ // remotely kept a world-writable directory holding the binary and config the root service
586
+ // loads, and the staging directory of its next update. The same two steps as update(), in the
587
+ // same order. False only when the directory could not be taken back (replaced by a link, a
588
+ // user that no longer resolves): the one case where staging a binary in it is not safe.
589
+ async tightenSystemDir() {
590
+ if ((0, utils_1.isWindows)())
591
+ return true;
592
+ const svcUser = this.readServiceUser();
593
+ if (svcUser === null) {
594
+ logger_1.default.error((0, texts_1.LOG_AGENT_RIGHTS_SKIPPED)(this.getServicePath()));
595
+ return true;
596
+ }
597
+ try {
598
+ await this.chownSystemDir(svcUser);
599
+ this.applySystemModes();
600
+ return true;
601
+ }
602
+ catch (err) {
603
+ logger_1.default.error(err);
604
+ return false;
605
+ }
606
+ }
607
+ // Group or others can write the system directory: an install tightenSystemDir has not been
608
+ // through yet. Through a no-follow descriptor, like everything else that inspects it as root.
609
+ isSystemDirLoose() {
610
+ if ((0, utils_1.isWindows)())
611
+ return false;
612
+ let fd;
613
+ try {
614
+ fd = this.openNoFollow(this.getSystemConfigDir(), true);
615
+ }
616
+ catch {
617
+ return false;
618
+ }
619
+ try {
620
+ return ((0, node_fs_1.fstatSync)(fd).mode & 0o022) !== 0;
621
+ }
622
+ catch {
623
+ return false;
624
+ }
625
+ finally {
626
+ (0, node_fs_1.closeSync)(fd);
627
+ }
628
+ }
526
629
  ensureStandaloneConfigDir() {
527
630
  const p = this.getStandaloneConfigDir();
528
631
  (0, node_fs_1.mkdirSync)(p, { recursive: true });
@@ -568,35 +671,47 @@ class AgentSystem {
568
671
  getBinaryArchivePath() {
569
672
  return path_1.default.join(this.getSystemConfigDir(), this.getBinaryArchive());
570
673
  }
674
+ // Root downloads the release archive to a fixed name in the service user's directory. Opened
675
+ // by path, a link that user left at that name had the archive written over, and its mode set
676
+ // on, whatever it points at. So the name is removed and created exclusively, never followed:
677
+ // either it is ours, created right here at 0600, or the download fails.
571
678
  downloadFile(url, dest) {
572
679
  return new Promise((resolve, reject) => {
573
- const file = (0, node_fs_1.createWriteStream)(dest);
680
+ let fd;
681
+ try {
682
+ (0, node_fs_1.rmSync)(dest, { force: true });
683
+ let flags = node_fs_1.constants.O_WRONLY | node_fs_1.constants.O_CREAT | node_fs_1.constants.O_EXCL;
684
+ if (!(0, utils_1.isWindows)())
685
+ flags |= node_fs_1.constants.O_NOFOLLOW;
686
+ fd = (0, node_fs_1.openSync)(dest, flags, 0o600);
687
+ }
688
+ catch (err) {
689
+ reject(err);
690
+ return;
691
+ }
692
+ const file = (0, node_fs_1.createWriteStream)(dest, { fd });
693
+ // Whatever is at the name by then is removed as a name: a link is unlinked, never followed
694
+ const discard = () => (0, node_fs_1.rmSync)(dest, { force: true });
574
695
  const request = https_1.default.get(url, (response) => {
575
696
  if (response.statusCode !== 200) {
576
- file.close();
577
- (0, node_fs_1.rmSync)(dest);
697
+ response.resume();
698
+ file.destroy();
699
+ discard();
578
700
  reject(new Error('File not found'));
579
701
  return;
580
702
  }
581
- response.pipe(file);
582
- file.once('finish', () => {
583
- file.close((err) => {
584
- if (err)
585
- reject(err);
586
- else {
587
- (0, node_fs_1.chmod)(dest, 0o600, (err) => {
588
- if (err)
589
- reject(err);
590
- else
591
- resolve();
592
- });
593
- }
594
- });
703
+ (0, node_stream_1.pipeline)(response, file, (err) => {
704
+ if (err) {
705
+ discard();
706
+ reject(err);
707
+ }
708
+ else
709
+ resolve();
595
710
  });
596
711
  });
597
712
  request.once('error', (err) => {
598
- file.close();
599
- (0, node_fs_1.rmSync)(dest);
713
+ file.destroy();
714
+ discard();
600
715
  reject(err);
601
716
  });
602
717
  });
@@ -963,19 +1078,16 @@ class AgentSystem {
963
1078
  this.ensureStandaloneConfigDir();
964
1079
  else
965
1080
  this.ensureSystemConfigDir();
966
- (0, node_fs_1.writeFileSync)(p, JSON.stringify({
1081
+ // Taken from where the file actually landed rather than from getActiveFileMode: this
1082
+ // is the one write that can create the file the resolution keys on
1083
+ this.writeFileNoFollow(p, JSON.stringify({
967
1084
  id,
968
1085
  host,
969
1086
  token,
970
1087
  port,
971
1088
  standalone,
972
1089
  debug,
973
- }), {
974
- encoding: 'utf-8',
975
- });
976
- // Taken from where the file actually landed rather than from getActiveFileMode: this
977
- // is the one write that can create the file the resolution keys on
978
- (0, node_fs_1.chmodSync)(p, inUserDir ? 0o600 : 0o644);
1090
+ }), inUserDir ? 0o600 : 0o644);
979
1091
  return true;
980
1092
  }
981
1093
  catch (err) {
@@ -0,0 +1,31 @@
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.isDestination = exports.resolveEntryPath = void 0;
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ const texts_1 = require("./texts");
9
+ // Where an entry lands, or a throw when that is not inside outPath. Entry names are whatever the
10
+ // archive says: joined as they came, `../x` wrote next to the destination and a `../dir/` entry
11
+ // went through unzipper.ts's removePath - a recursive rm of a directory the user never pointed us
12
+ // at. Used by every extractor of server-sent archives (unzipper.ts, crawl run). Checked
13
+ // before any rm, mkdir or write, and the whole extraction stops: an archive carrying such a name
14
+ // is not one to trust with the rest of its entries either. path.resolve also takes absolute names
15
+ // (`/x`, `C:\x`) and, on windows, `..\x`.
16
+ //
17
+ // The destination itself (`./`, `.`) is in bounds only for a directory entry - `tar -C dir .` puts
18
+ // one first - and isDestination() tells the extractor not to remove it: that entry used to rm -rf
19
+ // the whole destination the user pointed us at. A file there is refused like an escape.
20
+ const resolveEntryPath = (outPath, name, isDirectory = false) => {
21
+ const root = node_path_1.default.resolve(outPath);
22
+ const full = node_path_1.default.resolve(root, name);
23
+ const inside = full.startsWith(root + node_path_1.default.sep) || (isDirectory && full === root);
24
+ if (!inside) {
25
+ throw new Error((0, texts_1.ERR_ARCHIVE_ENTRY_OUTSIDE)(name));
26
+ }
27
+ return full;
28
+ };
29
+ exports.resolveEntryPath = resolveEntryPath;
30
+ const isDestination = (outPath, fullPath) => node_path_1.default.resolve(outPath) === fullPath;
31
+ exports.isDestination = isDestination;
@@ -3,6 +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.extractCrawlPackage = void 0;
6
7
  const utils_1 = require("../../utils");
7
8
  const commander_1 = require("commander");
8
9
  const texts_1 = require("../../texts");
@@ -12,6 +13,7 @@ const promises_1 = require("node:stream/promises");
12
13
  const node_fs_1 = require("node:fs");
13
14
  const node_path_1 = __importDefault(require("node:path"));
14
15
  const promises_2 = require("node:fs/promises");
16
+ const archivePath_1 = require("../../archivePath");
15
17
  const commandCrawlRun = (0, utils_1.newCommand)('run', texts_1.DESC_COMMAND_CRAWL_RUN, {
16
18
  examples: texts_1.EXAMPLE_CRAWL_RUN,
17
19
  });
@@ -50,7 +52,6 @@ commandCrawlRun.action(async (inputUrl, options) => {
50
52
  const { createCrawlContext, applyToken, applyCiAndCommitInfo } = require('../../visualTest/context');
51
53
  const { validateInputAndOptions } = require('./validation');
52
54
  const { getCiAndGitInfo } = require('@buddy-works/ci-info');
53
- const tar = require('tar-stream');
54
55
  const Input = require('../../input').default;
55
56
  const token = await Input.crawlSuiteToken();
56
57
  if (!token) {
@@ -69,33 +70,10 @@ commandCrawlRun.action(async (inputUrl, options) => {
69
70
  }
70
71
  say('Downloading crawl package');
71
72
  const crawlPackageStream = await downloadCrawlPackage(ctx, buildId);
72
- const brotliDecompressor = (0, node_zlib_1.createBrotliDecompress)();
73
- const unpack = tar.extract();
74
73
  const preparedOutputDir = outputDir.startsWith('.')
75
74
  ? node_path_1.default.join(process.cwd(), outputDir)
76
75
  : outputDir;
77
- let files = 0;
78
- unpack.on('entry', async (header, stream, next) => {
79
- const newFilePath = node_path_1.default.join(preparedOutputDir, header.name);
80
- try {
81
- if (header.type === 'file') {
82
- await (0, promises_2.mkdir)(node_path_1.default.dirname(newFilePath), { recursive: true });
83
- const fileWriteStream = (0, node_fs_1.createWriteStream)(newFilePath);
84
- await (0, promises_1.pipeline)(stream, fileWriteStream);
85
- files += 1;
86
- next();
87
- }
88
- else {
89
- stream.resume();
90
- next();
91
- }
92
- }
93
- catch (entryError) {
94
- sayError(json, `Error processing entry ${header.name}: ${entryError}`);
95
- next(entryError);
96
- }
97
- });
98
- await (0, promises_1.pipeline)(crawlPackageStream, brotliDecompressor, unpack);
76
+ const files = await (0, exports.extractCrawlPackage)(crawlPackageStream, preparedOutputDir, (txt) => sayError(json, txt));
99
77
  output_1.default.exitResult(json, { build_id: buildId, output_dir: preparedOutputDir, files }, 'Downloading crawl package finished');
100
78
  }
101
79
  catch (error) {
@@ -158,4 +136,58 @@ async function watchSessionStatus(ctx, buildId, json) {
158
136
  });
159
137
  });
160
138
  }
139
+ // Unpacks the crawl package - a brotli tar - into outputDir and returns how many files it wrote.
140
+ // Entry names come from the crawl service, built from the URLs of a site somebody else runs, so
141
+ // each one goes through resolveEntryPath: joined as it came, `../x` was written outside outputDir.
142
+ // Only files are written, directories are made as their files need them, as before.
143
+ const extractCrawlPackage = async (source, outputDir, onError = () => { }) => {
144
+ const tar = require('tar-stream');
145
+ const { Readable } = require('node:stream');
146
+ const unpack = tar.extract();
147
+ let files = 0;
148
+ // Entries are taken one at a time from the extractor rather than handed out by its 'entry'
149
+ // event: an error passed back through that event's next() reached node 20 as an uncaught
150
+ // exception instead of failing this function. Same shape as unzipper.ts's tar extraction.
151
+ const parsing = (0, promises_1.pipeline)(source, (0, node_zlib_1.createBrotliDecompress)(), unpack);
152
+ // parsing can reject while an entry is still being written below, well before it is awaited
153
+ parsing.catch(() => { });
154
+ let entryErr;
155
+ try {
156
+ for await (const entry of unpack) {
157
+ const header = entry.header;
158
+ if (header.type !== 'file') {
159
+ entry.resume();
160
+ continue;
161
+ }
162
+ try {
163
+ const newFilePath = (0, archivePath_1.resolveEntryPath)(outputDir, header.name);
164
+ await (0, promises_2.mkdir)(node_path_1.default.dirname(newFilePath), { recursive: true });
165
+ // A node stream in front of the streamx entry: node cannot tell one already destroyed
166
+ await (0, promises_1.pipeline)(Readable.from(entry), (0, node_fs_1.createWriteStream)(newFilePath));
167
+ files += 1;
168
+ }
169
+ catch (err) {
170
+ entry.resume();
171
+ onError(`Error processing entry ${header.name}: ${err}`);
172
+ throw err;
173
+ }
174
+ }
175
+ }
176
+ catch (err) {
177
+ entryErr = err;
178
+ }
179
+ try {
180
+ await parsing;
181
+ }
182
+ catch (err) {
183
+ // An entry refused stops the loop, which destroys the extractor: the pipeline then only
184
+ // reports a premature close, and the entry has the cause
185
+ if (!entryErr || err.code !== 'ERR_STREAM_PREMATURE_CLOSE')
186
+ throw err;
187
+ }
188
+ if (entryErr)
189
+ throw entryErr;
190
+ return files;
191
+ };
192
+ exports.extractCrawlPackage = extractCrawlPackage;
161
193
  exports.default = commandCrawlRun;
@@ -36,11 +36,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.isBuddyGitRemote = void 0;
39
40
  const utils_1 = require("../../../utils");
40
41
  const texts_1 = require("../../../texts");
41
42
  const readline = __importStar(require("node:readline"));
42
43
  const output_1 = __importDefault(require("../../../output"));
43
44
  const input_1 = __importDefault(require("../../../input"));
45
+ const cfg_1 = __importDefault(require("../../../project/cfg"));
44
46
  const commandProjectGitCredential = (0, utils_1.newCommand)('credential', texts_1.DESC_COMMAND_PROJECT_GIT_CREDENTIAL);
45
47
  commandProjectGitCredential.hideVersionUpdate = true;
46
48
  commandProjectGitCredential.argument('[action]');
@@ -52,20 +54,19 @@ commandProjectGitCredential.action(async (action) => {
52
54
  try {
53
55
  const client = input_1.default.restApiTokenClient();
54
56
  const workspace = input_1.default.restApiWorkspace();
55
- let myHost = input.host === 'app.local.io';
56
- if (!myHost) {
57
- const projects = await client.getProjects(workspace, 1, 1);
58
- myHost =
59
- projects.projects.length > 0 &&
60
- projects.projects[0].html_url.includes(input.host);
61
- }
62
- if (myHost) {
63
- // git credential protocol output - a machine-read payload, so it
64
- // bypasses terminal-kit formatting
65
- output_1.default.data(`protocol=${input.protocol || 'https'}`);
66
- output_1.default.data(`host=${input.host}`);
67
- output_1.default.data(`username=${client.token}`);
68
- output_1.default.data(`password=`);
57
+ // The project this repo is linked to - not the first one of the workspace, whose host says
58
+ // nothing about where this repo's remote lives
59
+ const project = cfg_1.default.getProject() || input_1.default.restApiProject(undefined, true);
60
+ if (project) {
61
+ const data = await client.getProject(workspace, project);
62
+ if ((0, exports.isBuddyGitRemote)(input, data)) {
63
+ // git credential protocol output - a machine-read payload, so it
64
+ // bypasses terminal-kit formatting
65
+ output_1.default.data('protocol=https');
66
+ output_1.default.data(`host=${input.host}`);
67
+ output_1.default.data(`username=${client.token}`);
68
+ output_1.default.data(`password=`);
69
+ }
69
70
  }
70
71
  }
71
72
  catch {
@@ -73,6 +74,29 @@ commandProjectGitCredential.action(async (action) => {
73
74
  }
74
75
  output_1.default.exitNormal();
75
76
  });
77
+ // Whether git is asking for the project's own Buddy remote, the only one the REST API token is
78
+ // for. git sends it in Basic auth to whatever server answered 401, so this is the whole defence:
79
+ // the host has to be the project remote's host exactly - a substring test handed the token to
80
+ // `dy.works` or a bare workspace slug - and the protocol https, or the token crosses the network
81
+ // readable. A project with an external integration keeps its code elsewhere (GitHub, GitLab...),
82
+ // so its remote never gets the token, whatever its host.
83
+ const isBuddyGitRemote = (input, project) => {
84
+ if (input.protocol !== 'https' || !input.host)
85
+ return false;
86
+ if (!project || project.integration || !project.http_repository)
87
+ return false;
88
+ try {
89
+ const remote = new URL(project.http_repository);
90
+ if (remote.protocol !== 'https:')
91
+ return false;
92
+ // Through URL on both sides, so a default port written out (`:443`) compares equal
93
+ return new URL(`https://${input.host}`).host === remote.host;
94
+ }
95
+ catch {
96
+ return false;
97
+ }
98
+ };
99
+ exports.isBuddyGitRemote = isBuddyGitRemote;
76
100
  const parseGitInput = async () => {
77
101
  const result = {};
78
102
  const rl = readline.createInterface({