bdy 1.25.38-stage → 1.25.38

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.38-stage",
4
+ "version": "1.25.38",
5
5
  "type": "commonjs",
6
6
  "license": "MIT",
7
7
  "homepage": "https://buddy.works/docs/cli",
@@ -0,0 +1,219 @@
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.remoteAgentAction = exports.remoteTunnelCreate = exports.remoteTunnelView = exports.remoteTunnelStatus = exports.remoteTunnelListItem = exports.remoteAgentFlag = exports.remoteAgentStatus = exports.remoteAgentApiStatus = exports.resolveRemoteAgent = exports.addRemoteAgentOptions = void 0;
7
+ const texts_1 = require("../../texts");
8
+ const input_1 = __importDefault(require("../../input"));
9
+ const cliError_1 = __importDefault(require("../../cliError"));
10
+ const tunnel_1 = require("../../types/tunnel");
11
+ // The options of the remote mode. The tunnel commands already use -w for
12
+ // --whitelist, so there the workspace has no short flag.
13
+ const addRemoteAgentOptions = (command, workspaceShort = true) => {
14
+ command.option('--agent <identifier>', texts_1.OPTION_AGENT_REMOTE);
15
+ command.option(workspaceShort ? '-w, --workspace <domain>' : '--workspace <domain>', texts_1.OPTION_REST_API_WORKSPACE);
16
+ command.option('-p, --project <name>', texts_1.OPTION_REST_API_PROJECT);
17
+ };
18
+ exports.addRemoteAgentOptions = addRemoteAgentOptions;
19
+ const notFound = () => new cliError_1.default('not_found', texts_1.ERR_AGENT_NOT_FOUND, texts_1.HINT_AGENT_REMOTE);
20
+ // null without --agent: the command goes to the local agent as before.
21
+ //
22
+ // --agent takes the agent's identifier or its hash id. With a project
23
+ // (--project, BUDDY_PROJECT, linked project) /identifiers looks among the
24
+ // agents of the project and of the workspace both (the backend's scope for
25
+ // agents, unlike the exact scope of the list), so a workspace agent is found
26
+ // from a linked directory too. /identifiers resolves an identifier or a
27
+ // numeric id only, so a value it does not know is tried as a hash id.
28
+ const resolveRemoteAgent = async (options) => {
29
+ if (!options.agent)
30
+ return null;
31
+ const workspace = input_1.default.restApiWorkspace(options.workspace);
32
+ const project = input_1.default.restApiProject(options.project, true);
33
+ const client = input_1.default.restApiTokenClient();
34
+ const resolved = await client.getResourceByIdentifier(workspace, {
35
+ project: project || undefined,
36
+ server_agent: options.agent,
37
+ });
38
+ if (resolved.server_agent_id) {
39
+ return { client, workspace, agentId: resolved.server_agent_id };
40
+ }
41
+ try {
42
+ const agent = await client.getServerAgent(workspace, options.agent);
43
+ return { client, workspace, agentId: agent.id };
44
+ }
45
+ catch (err) {
46
+ // a value that is not a hash id at all answers 400
47
+ if (err instanceof cliError_1.default && ['not_found', 'usage_error'].includes(err.code)) {
48
+ throw notFound();
49
+ }
50
+ throw err;
51
+ }
52
+ };
53
+ exports.resolveRemoteAgent = resolveRemoteAgent;
54
+ // The local agent's `/status` answer rebuilt from the REST view, so the JSON
55
+ // of `agent version` and `agent status` keeps one shape. The connection detail
56
+ // of the local status (fetch failed, initializing) is not reported over REST.
57
+ const remoteAgentApiStatus = (agent) => ({
58
+ id: agent.id,
59
+ status: agent.disabled ? tunnel_1.TUNNEL_AGENT_STATUS.DISABLED : tunnel_1.TUNNEL_AGENT_STATUS.ENABLED,
60
+ version: agent.version || null,
61
+ updating: agent.action === tunnel_1.TUNNEL_AGENT_ACTION.UPDATE ||
62
+ agent.action === tunnel_1.TUNNEL_AGENT_UPDATE_STATUS.STARTED,
63
+ enabled: !agent.disabled,
64
+ target: !!agent.target,
65
+ tunneling: !!agent.tunneling,
66
+ proxy: !!agent.proxy,
67
+ });
68
+ exports.remoteAgentApiStatus = remoteAgentApiStatus;
69
+ // `agent status`: the API status plus what the local command adds about the
70
+ // installation - here only what the REST view knows.
71
+ const remoteAgentStatus = (agent) => ({
72
+ ...(0, exports.remoteAgentApiStatus)(agent),
73
+ installed: true,
74
+ standalone: !agent.service,
75
+ running: !!agent.active,
76
+ orphaned_config: null,
77
+ });
78
+ exports.remoteAgentStatus = remoteAgentStatus;
79
+ // `agent target|proxy|tunnel ...` with --agent: reads the flag (no value) or
80
+ // sets it with a PATCH, which the backend pushes to the agent, and returns the
81
+ // stored state. null without --agent.
82
+ const remoteAgentFlag = async (options, flag, value) => {
83
+ const remote = await (0, exports.resolveRemoteAgent)(options);
84
+ if (!remote)
85
+ return null;
86
+ const agent = value === undefined
87
+ ? await remote.client.getServerAgent(remote.workspace, remote.agentId)
88
+ : await remote.client.updateServerAgent(remote.workspace, remote.agentId, {
89
+ [flag]: value,
90
+ });
91
+ return !!agent[flag];
92
+ };
93
+ exports.remoteAgentFlag = remoteAgentFlag;
94
+ // A latency the agent has not reported is unreachable, as the local agent says
95
+ const latency = (value) => value === undefined || value === null ? -1 : value;
96
+ // `agent tunnel list --agent`: one item of the local agent's `/tunnels`
97
+ // answer rebuilt from the REST view (the SSH tunnel is left out by both).
98
+ const remoteTunnelListItem = (tunnel) => ({
99
+ id: tunnel.id,
100
+ type: tunnel.type,
101
+ target: tunnel.endpoint,
102
+ domain: tunnel.domain,
103
+ subdomain: tunnel.subdomain,
104
+ serve: tunnel.http?.serve_path,
105
+ status: tunnel.active ? tunnel_1.TUNNEL_STATUS.OPEN : tunnel_1.TUNNEL_STATUS.CLOSED,
106
+ region: tunnel.region,
107
+ sshId: tunnel.ssh?.ssh_id,
108
+ sshForwardPort: tunnel.ssh?.forward_port,
109
+ regionLatency: latency(tunnel.region_latency),
110
+ targetLatency: latency(tunnel.target_latency),
111
+ });
112
+ exports.remoteTunnelListItem = remoteTunnelListItem;
113
+ // `agent tunnel status <id> --agent`: the status message the local agent
114
+ // streams for a tunnel, rebuilt from the REST view. Left out: `connections`
115
+ // (the agent's open connections - the REST view has only their count) and
116
+ // `dns` (the local check of the entry host).
117
+ const remoteTunnelStatus = (tunnel) => ({
118
+ regionLatency: { latency: latency(tunnel.region_latency) },
119
+ targetLatency: { latency: latency(tunnel.target_latency) },
120
+ identify: tunnel.http_identified ? { type: tunnel.http_identified } : null,
121
+ totalConnections: tunnel.total_connections ?? 0,
122
+ serve: tunnel.http?.serve_path,
123
+ log: !!tunnel.http?.log_requests,
124
+ status: tunnel.active ? tunnel_1.TUNNEL_STATUS.OPEN : tunnel_1.TUNNEL_STATUS.CLOSED,
125
+ region: tunnel.region,
126
+ type: tunnel.type,
127
+ target: tunnel.endpoint,
128
+ terminate: tunnel.tls?.terminate_at,
129
+ id: tunnel.id,
130
+ subdomain: tunnel.subdomain,
131
+ domain: tunnel.domain,
132
+ sshId: tunnel.ssh?.ssh_id,
133
+ sshForwardPort: tunnel.ssh?.forward_port,
134
+ });
135
+ exports.remoteTunnelStatus = remoteTunnelStatus;
136
+ // What the tunnel views read on top of the status message: the note and the
137
+ // open connections, of which the REST view knows the count only.
138
+ const remoteTunnelView = (tunnel) => {
139
+ const connections = {};
140
+ for (let i = 0; i < (tunnel.current_connections || 0); i += 1) {
141
+ connections[String(i)] = true;
142
+ }
143
+ return { ...(0, exports.remoteTunnelStatus)(tunnel), note: tunnel.note, connections };
144
+ };
145
+ exports.remoteTunnelView = remoteTunnelView;
146
+ // The CLI keeps a fraction, the API a whole percentage (an integer 0-100): a
147
+ // threshold with a fraction of a percent is refused rather than rounded into
148
+ // another value than the one the local agent would use.
149
+ const remoteCircuitBreaker = (fraction) => {
150
+ if (fraction === undefined || fraction === null)
151
+ return undefined;
152
+ const percent = fraction * 100;
153
+ const whole = Math.round(percent);
154
+ // the float product of a whole percentage is off by an epsilon (0.07 * 100)
155
+ if (Math.abs(percent - whole) > 1e-9) {
156
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_CB_THRESHOLD_NOT_INTEGER_REMOTE)(parseFloat(percent.toFixed(6))));
157
+ }
158
+ return whole;
159
+ };
160
+ const defined = (body) => {
161
+ Object.keys(body).forEach((key) => body[key] === undefined && delete body[key]);
162
+ return body;
163
+ };
164
+ // A tunnel definition (`Cfg.prepareTunnel`: the options of `agent tunnel
165
+ // tcp|tls|http`, or a tunnel of the config for `agent tunnel start`) as the
166
+ // body of POST /server-agents/{id}/tunnels. What the definition leaves out the
167
+ // backend fills with the agent's defaults (its region, timeout 30, no
168
+ // whitelist): the config defaults of this machine are no business of another.
169
+ const remoteTunnelCreate = (tunnel) => {
170
+ const body = defined({
171
+ type: tunnel.type,
172
+ endpoint: tunnel.target,
173
+ name: tunnel.name,
174
+ region: tunnel.region,
175
+ whitelist: tunnel.whitelist,
176
+ timeout: tunnel.timeout,
177
+ note: tunnel.note,
178
+ agent_note: tunnel.agentNote,
179
+ });
180
+ if (tunnel.type === tunnel_1.TUNNEL_TYPE.HTTP) {
181
+ body.http = defined({
182
+ auth_type: tunnel.authType,
183
+ login: tunnel.login,
184
+ password: tunnel.password,
185
+ tls_ca: tunnel.ca,
186
+ verify_certificate: tunnel.verify,
187
+ compression: tunnel.compression,
188
+ http2: tunnel.http2,
189
+ log_requests: tunnel.log,
190
+ request_headers: tunnel.headers,
191
+ response_headers: tunnel.responseHeaders,
192
+ whitelist_user_agents: tunnel.useragents,
193
+ rewrite_host_header: tunnel.host,
194
+ serve_path: tunnel.serve,
195
+ circuit_breaker: remoteCircuitBreaker(tunnel.circuitBreaker),
196
+ });
197
+ }
198
+ else if (tunnel.type === tunnel_1.TUNNEL_TYPE.TLS) {
199
+ body.tls = defined({
200
+ terminate_at: tunnel.terminate,
201
+ private_key: tunnel.key,
202
+ certificate: tunnel.cert,
203
+ ca_certificate: tunnel.ca,
204
+ });
205
+ }
206
+ return body;
207
+ };
208
+ exports.remoteTunnelCreate = remoteTunnelCreate;
209
+ // `agent update` / `agent debug` with --agent: the action is queued on the
210
+ // agent and done when the agent gets it - nothing is awaited. true once
211
+ // requested, null without --agent.
212
+ const remoteAgentAction = async (options, type) => {
213
+ const remote = await (0, exports.resolveRemoteAgent)(options);
214
+ if (!remote)
215
+ return null;
216
+ await remote.client.createServerAgentAction(remote.workspace, remote.agentId, type);
217
+ return true;
218
+ };
219
+ exports.remoteAgentAction = remoteAgentAction;
@@ -0,0 +1,42 @@
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
+ const utils_1 = require("../../../utils");
7
+ const texts_1 = require("../../../texts");
8
+ const input_1 = __importDefault(require("../../../input"));
9
+ const output_1 = __importDefault(require("../../../output"));
10
+ const scope_1 = require("../scope");
11
+ // --path repeats instead of taking a list: a variadic option would swallow the
12
+ // positional arguments that follow it
13
+ const collect = (value, previous = []) => [...previous, value];
14
+ const commandDistroRoutePurge = (0, utils_1.newCommand)('purge', texts_1.DESC_COMMAND_ROUTE_PURGE, {
15
+ requiredScopes: [utils_1.REST_API_SCOPE.DISTRIBUTION_WRITE],
16
+ examples: texts_1.EXAMPLE_ROUTE_PURGE,
17
+ });
18
+ commandDistroRoutePurge.option('-w, --workspace <domain>', texts_1.OPTION_REST_API_WORKSPACE);
19
+ commandDistroRoutePurge.option('-p, --project <name>', texts_1.OPTION_REST_API_PROJECT);
20
+ commandDistroRoutePurge.option('--environment <identifier>', texts_1.OPTION_DISTRO_ENVIRONMENT);
21
+ commandDistroRoutePurge.option('--scope <scope>', texts_1.OPT_COMMAND_SCOPE_ENVIRONMENT);
22
+ commandDistroRoutePurge.option('--all', texts_1.OPT_COMMAND_ROUTE_PURGE_ALL);
23
+ commandDistroRoutePurge.option('--path <path>', texts_1.OPT_COMMAND_ROUTE_PURGE_PATH, collect);
24
+ commandDistroRoutePurge.option('--format <text|json>', texts_1.OPTION_FORMAT);
25
+ commandDistroRoutePurge.argument('<identifier>', texts_1.OPT_COMMAND_DISTRO_IDENTIFIER);
26
+ commandDistroRoutePurge.argument('<route-id>', texts_1.OPT_COMMAND_ROUTE_ID);
27
+ commandDistroRoutePurge.action(async (identifier, routeId, options) => {
28
+ const paths = options.path || [];
29
+ // one or the other: --all already covers every path
30
+ if (!!options.all === paths.length > 0) {
31
+ output_1.default.exitError(texts_1.ERR_COMMAND_ROUTE_PURGE_WHAT);
32
+ }
33
+ const workspace = input_1.default.restApiWorkspace(options.workspace);
34
+ const client = input_1.default.restApiTokenClient();
35
+ const ctx = await (0, scope_1.resolveDistroContext)(client, workspace, options, identifier);
36
+ const body = { purge_all: !!options.all };
37
+ if (paths.length)
38
+ body.purge_paths = paths;
39
+ await client.purgeRouteCache(workspace, ctx.api, ctx.distributionId, routeId, body);
40
+ output_1.default.exitResult(options.format === 'json', { purged: routeId, ...body }, texts_1.TXT_COMMAND_ROUTE_PURGED);
41
+ });
42
+ exports.default = commandDistroRoutePurge;
@@ -0,0 +1,77 @@
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.resolveDistroContext = void 0;
7
+ const texts_1 = require("../../texts");
8
+ const output_1 = __importDefault(require("../../output"));
9
+ const cliError_1 = __importDefault(require("../../cliError"));
10
+ const input_1 = __importDefault(require("../../input"));
11
+ const distro_1 = require("../../types/distro");
12
+ // Shared resolve preamble of the distro and route commands: flags/env ->
13
+ // scope -> /identifiers -> hash ids, exiting on a miss.
14
+ //
15
+ // Environments exist in projects and in the workspace. An explicit --project
16
+ // is a statement "the environment of this project", so it never falls back;
17
+ // a project implied by BUDDY_PROJECT or a linked directory only narrows the
18
+ // first lookup, and a workspace environment of that identifier is used when
19
+ // the project has none - otherwise a workspace environment's distributions
20
+ // would be unreachable from inside a linked project.
21
+ const resolveDistroContext = async (client, workspace, options, distribution) => {
22
+ const project = input_1.default.restApiProject(options.project, true);
23
+ const scope = input_1.default.scope(project, options.scope || '', options.environment, true);
24
+ if (options.environment && scope !== distro_1.SCOPE.ENVIRONMENT) {
25
+ output_1.default.exitError(texts_1.ERR_COMMAND_DISTRO_ENVIRONMENT_SCOPE);
26
+ }
27
+ const ctx = {
28
+ scope,
29
+ project: scope === distro_1.SCOPE.WORKSPACE ? null : project,
30
+ environment: null,
31
+ environmentId: null,
32
+ api: {},
33
+ distributionId: null,
34
+ };
35
+ let resolved = null;
36
+ if (scope === distro_1.SCOPE.ENVIRONMENT) {
37
+ const environment = options.environment;
38
+ resolved = await client.getResourceByIdentifier(workspace, {
39
+ project: project || undefined,
40
+ environment,
41
+ distribution,
42
+ });
43
+ if (resolved.domain && !resolved.environment_id && project && !options.project) {
44
+ ctx.project = null;
45
+ resolved = await client.getResourceByIdentifier(workspace, {
46
+ environment,
47
+ distribution,
48
+ });
49
+ }
50
+ if (!resolved.domain) {
51
+ output_1.default.exitError(new cliError_1.default('not_found', texts_1.ERR_WORKSPACE_NOT_FOUND, texts_1.HINT_WORKSPACE_LIST));
52
+ }
53
+ if (!resolved.environment_id) {
54
+ output_1.default.exitError(new cliError_1.default('not_found', texts_1.ERR_ENVIRONMENT_NOT_FOUND, texts_1.HINT_ENVIRONMENT_LIST));
55
+ }
56
+ ctx.environment = environment;
57
+ ctx.environmentId = resolved.environment_id;
58
+ ctx.api = { environmentId: ctx.environmentId };
59
+ }
60
+ else {
61
+ ctx.api = { project: ctx.project };
62
+ if (distribution) {
63
+ resolved = await client.getDistributionByIdentifier(workspace, { project: ctx.project }, distribution);
64
+ if (!resolved.domain) {
65
+ output_1.default.exitError(new cliError_1.default('not_found', texts_1.ERR_WORKSPACE_NOT_FOUND, texts_1.HINT_WORKSPACE_LIST));
66
+ }
67
+ }
68
+ }
69
+ if (distribution) {
70
+ if (!resolved?.distribution_id) {
71
+ output_1.default.exitError(new cliError_1.default('not_found', texts_1.ERR_COMMAND_DISTRO_NOT_FOUND, texts_1.HINT_DISTRO_LIST));
72
+ }
73
+ ctx.distributionId = resolved.distribution_id;
74
+ }
75
+ return ctx;
76
+ };
77
+ exports.resolveDistroContext = resolveDistroContext;
@@ -0,0 +1,218 @@
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
+ const node_os_1 = require("node:os");
7
+ const node_fs_1 = require("node:fs");
8
+ const promises_1 = require("node:stream/promises");
9
+ const utils_1 = require("../../utils");
10
+ const texts_1 = require("../../texts");
11
+ const output_1 = __importDefault(require("../../output"));
12
+ const input_1 = __importDefault(require("../../input"));
13
+ const cliError_1 = __importDefault(require("../../cliError"));
14
+ const distro_1 = require("../../types/distro");
15
+ const injection_1 = require("./injection");
16
+ const secretMask_1 = __importDefault(require("./secretMask"));
17
+ const collect = (value, previous = []) => [...previous, value];
18
+ // After the command exits its output may still be on the way: in the pipes,
19
+ // in the masking, in our own stdout. And a process the command left in the
20
+ // background (`sh -c 'daemon & ...'`) inherited the pipes and keeps them open
21
+ // for as long as it lives, writing or silent. bdy is the only reader of those
22
+ // pipes, so it stays until they close - leaving earlier would cut the
23
+ // daemon's output and, on its next write, kill it with SIGPIPE. --wait
24
+ // (seconds, 0 = no limit) bounds that: past it bdy gives up and exits with 1.
25
+ // The time is counted only over checks that came on time: a write to a slow
26
+ // reader (`| less`) blocks bdy (stdout is in blocking mode, index.ts), and
27
+ // output held up that way is not the command's fault - it is never cut.
28
+ const OUTPUT_CHECK_MS = 100;
29
+ const DEFAULT_WAIT_SECONDS = 300;
30
+ const parseWait = (value) => {
31
+ if (!/^\d+$/.test(value)) {
32
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_VARIABLE_INJECT_WAIT)(value));
33
+ }
34
+ return Number(value);
35
+ };
36
+ // true when all the output got through, false when --wait ran out first
37
+ const waitForOutput = (masks, done, waitSeconds) => new Promise((resolve) => {
38
+ // a destroyed stdout (reader gone) never empties - nothing to wait for
39
+ const unflushed = (stream) => !stream.destroyed && (stream.writableNeedDrain || stream.writableLength > 0);
40
+ const busy = () => unflushed(process.stdout) ||
41
+ unflushed(process.stderr) ||
42
+ masks.some((mask) => mask.writableLength > 0 || mask.readableLength > 0);
43
+ let ended = false;
44
+ let waitedMs = 0;
45
+ let last = Date.now();
46
+ const finish = (complete) => {
47
+ clearInterval(check);
48
+ resolve(complete);
49
+ };
50
+ const check = setInterval(() => {
51
+ const now = Date.now();
52
+ const elapsed = now - last;
53
+ last = now;
54
+ const held = busy();
55
+ // the pipes closed and our own buffers are empty
56
+ if (ended && !held)
57
+ return finish(true);
58
+ if (held || elapsed > OUTPUT_CHECK_MS * 2)
59
+ return;
60
+ waitedMs += elapsed;
61
+ if (waitSeconds && waitedMs >= waitSeconds * 1000)
62
+ finish(false);
63
+ }, OUTPUT_CHECK_MS);
64
+ void done.then(() => {
65
+ ended = true;
66
+ if (!busy())
67
+ finish(true);
68
+ });
69
+ });
70
+ // Files written by --var-file. Removed on every way out of the process that
71
+ // runs JavaScript - the command's end, an error, a forwarded signal - as all
72
+ // of them go through process.exit. Only a SIGKILL of bdy leaves them behind.
73
+ const written = [];
74
+ const removeWritten = () => {
75
+ for (const path of written.splice(0)) {
76
+ try {
77
+ (0, node_fs_1.unlinkSync)(path);
78
+ }
79
+ catch {
80
+ // already gone - the command may have removed it itself
81
+ }
82
+ }
83
+ };
84
+ const writeSecretFile = (path, content) => {
85
+ try {
86
+ // wx: never take a file that exists - deleting it afterwards would
87
+ // destroy something of the user's (an ~/.ssh/id_rsa)
88
+ (0, node_fs_1.writeFileSync)(path, content, { flag: 'wx', mode: 0o600 });
89
+ }
90
+ catch (err) {
91
+ const { code, message } = err;
92
+ if (code === 'EEXIST') {
93
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_VARIABLE_INJECT_FILE_EXISTS)(path));
94
+ }
95
+ throw new cliError_1.default('command_failed', (0, texts_1.ERR_VARIABLE_INJECT_FILE_WRITE)(path, message));
96
+ }
97
+ written.push(path);
98
+ };
99
+ // Without --scope the lookup of the other environment commands: the project
100
+ // of the context first (-p, BUDDY_PROJECT, linked), then the workspace. With
101
+ // --scope exactly one of them, no fallback - the variables injected must not
102
+ // come from an environment of the same name the user did not mean.
103
+ const resolveEnvironment = async (client, workspace, options) => {
104
+ if (!options.scope) {
105
+ return {
106
+ environmentId: await input_1.default.environmentId(client, workspace, options.environment, options),
107
+ projectIdentifier: null,
108
+ };
109
+ }
110
+ const project = input_1.default.restApiProject(options.project, true);
111
+ const scope = input_1.default.scope(project, options.scope);
112
+ const resolved = await client.getEnvironmentByIdentifier(workspace, options.environment, scope === distro_1.SCOPE.PROJECT ? project : null);
113
+ if (!resolved.environment_id) {
114
+ throw new cliError_1.default('not_found', texts_1.ERR_ENVIRONMENT_NOT_FOUND, texts_1.HINT_ENVIRONMENT_LIST);
115
+ }
116
+ return {
117
+ environmentId: resolved.environment_id,
118
+ projectIdentifier: scope === distro_1.SCOPE.PROJECT ? (resolved.project_identifier ?? null) : null,
119
+ };
120
+ };
121
+ const commandVariableInject = (0, utils_1.newCommand)('inject', texts_1.DESC_COMMAND_VARIABLE_INJECT, {
122
+ requiredScopes: [
123
+ utils_1.REST_API_SCOPE.VARIABLE_READ,
124
+ utils_1.REST_API_SCOPE.ENVIRONMENT_READ,
125
+ utils_1.REST_API_SCOPE.MASKED_VARIABLE_VALUE_DECRYPTED,
126
+ ],
127
+ examples: texts_1.EXAMPLE_VARIABLE_INJECT,
128
+ });
129
+ commandVariableInject.aliases(['exec', 'run']);
130
+ commandVariableInject.option('-w, --workspace <domain>', texts_1.OPTION_REST_API_WORKSPACE);
131
+ commandVariableInject.option('-p, --project <name>', texts_1.OPTION_REST_API_PROJECT);
132
+ commandVariableInject.option('--scope <scope>', texts_1.OPT_COMMAND_SCOPE);
133
+ commandVariableInject.requiredOption('--environment <identifier>', texts_1.OPTION_VARIABLE_INJECT_ENVIRONMENT);
134
+ commandVariableInject.option('--var <key>', texts_1.OPTION_VARIABLE_INJECT_VAR, collect);
135
+ commandVariableInject.option('--var-file <key:path>', texts_1.OPTION_VARIABLE_INJECT_VAR_FILE, collect);
136
+ commandVariableInject.option('--no-masking', texts_1.OPTION_VARIABLE_INJECT_NO_MASKING);
137
+ commandVariableInject.option('--wait <seconds>', texts_1.OPTION_VARIABLE_INJECT_WAIT, parseWait, DEFAULT_WAIT_SECONDS);
138
+ commandVariableInject.argument('<command...>', texts_1.OPTION_VARIABLE_INJECT_COMMAND);
139
+ // everything after the first argument is the command's, even when it looks
140
+ // like an option of ours (`bdy var exec --environment x ls --var`)
141
+ commandVariableInject.passThroughOptions();
142
+ commandVariableInject.action(async (command, options) => {
143
+ const workspace = input_1.default.restApiWorkspace(options.workspace);
144
+ const varFiles = (options.varFile ?? []).map(injection_1.parseVarFile);
145
+ const client = input_1.default.restApiTokenClient();
146
+ const { environmentId, projectIdentifier } = await resolveEnvironment(client, workspace, options);
147
+ const [result, environment] = await Promise.all([
148
+ client.getVariables(workspace, { environmentId }),
149
+ client.getEnvironment(workspace, environmentId),
150
+ ]);
151
+ // --scope PROJECT is a statement "the environment of this project": the
152
+ // API is asked along the project line, and the answer verified once more
153
+ if (projectIdentifier && environment.project?.name !== projectIdentifier) {
154
+ throw new cliError_1.default('not_found', texts_1.ERR_ENVIRONMENT_NOT_FOUND, texts_1.HINT_ENVIRONMENT_LIST);
155
+ }
156
+ const injection = (0, injection_1.buildInjection)(result.variables ?? [], environment, options.var ?? [], varFiles);
157
+ process.on('exit', removeWritten);
158
+ for (const { path, content } of injection.files)
159
+ writeSecretFile(path, content);
160
+ // Masking needs the output through bdy, which takes the terminal away from
161
+ // the command. Without anything to mask it keeps the terminal.
162
+ const masking = options.masking !== false && injection.secrets.length > 0;
163
+ if (options.masking !== false && injection.unmasked.length) {
164
+ output_1.default.noteWarning((0, texts_1.WARN_VARIABLE_INJECT_NOT_MASKED)(injection.unmasked));
165
+ }
166
+ const { spawn } = require('cross-spawn');
167
+ const child = spawn(command[0], command.slice(1), {
168
+ env: { ...process.env, ...injection.env },
169
+ stdio: masking ? ['inherit', 'pipe', 'pipe'] : 'inherit',
170
+ });
171
+ // The terminal sends Ctrl+C and Ctrl+\ to the whole foreground group, the
172
+ // command included: let it decide, and end when it ends - passing it on as
173
+ // well would be a second interrupt, which terraform, docker compose or npm
174
+ // take as "force quit now". bdy is on a terminal when any of its stdio is
175
+ // (`echo yes | bdy ...` still is; with masking only the command's output
176
+ // goes through bdy). Without one (a supervisor, `timeout -s INT`) such a
177
+ // signal is meant for bdy alone and is passed on, like SIGTERM and SIGHUP
178
+ // always are, so the command is not left running and the files are
179
+ // removed when it exits. SIGTSTP (Ctrl+Z) keeps its default: bdy stops
180
+ // together with the command, so the shell sees the job stopped and gives
181
+ // the prompt back.
182
+ const onTerminal = process.stdin.isTTY || process.stdout.isTTY || process.stderr.isTTY;
183
+ for (const signal of ['SIGINT', 'SIGQUIT']) {
184
+ process.on(signal, () => {
185
+ if (!onTerminal)
186
+ child.kill(signal);
187
+ });
188
+ }
189
+ for (const signal of ['SIGTERM', 'SIGHUP']) {
190
+ process.on(signal, () => child.kill(signal));
191
+ }
192
+ const masks = masking
193
+ ? [new secretMask_1.default(injection.secrets), new secretMask_1.default(injection.secrets)]
194
+ : [];
195
+ const streams = masks.map((mask, i) => (0, promises_1.pipeline)((i ? child.stderr : child.stdout), mask, (i ? process.stderr : process.stdout), { end: false }).catch(() => {
196
+ // our stdout closed by its reader (`| head`): the command gets
197
+ // EPIPE/SIGPIPE on its next write, as it would without bdy
198
+ }));
199
+ const exitCode = await new Promise((resolve, reject) => {
200
+ child.on('error', (err) => reject(err.code === 'ENOENT'
201
+ ? new cliError_1.default('command_failed', (0, texts_1.ERR_VARIABLE_INJECT_COMMAND_NOT_FOUND)(command[0]))
202
+ : err));
203
+ // exit, not close: close waits for every copy of the stdio pipes, and a
204
+ // process the command left in the background may hold them for as long
205
+ // as it lives - bdy would hang with the secret files still on disk
206
+ child.on('exit', (code, signal) => {
207
+ // the shell convention for a command killed by a signal
208
+ resolve(signal ? 128 + (node_os_1.constants.signals[signal] ?? 0) : (code ?? 1));
209
+ });
210
+ });
211
+ removeWritten();
212
+ if (!(await waitForOutput(masks, Promise.all(streams), options.wait))) {
213
+ output_1.default.noteWarning((0, texts_1.WARN_VARIABLE_INJECT_WAIT_EXCEEDED)(options.wait));
214
+ output_1.default.exitCode(1);
215
+ }
216
+ output_1.default.exitCode(exitCode);
217
+ });
218
+ exports.default = commandVariableInject;
@@ -0,0 +1,182 @@
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.buildInjection = exports.parseVarFile = void 0;
7
+ const node_os_1 = require("node:os");
8
+ const node_path_1 = require("node:path");
9
+ const utils_1 = require("../../utils");
10
+ const texts_1 = require("../../texts");
11
+ const cliError_1 = __importDefault(require("../../cliError"));
12
+ // The API keeps these as base64 (they may be binary); the keys are text.
13
+ const BASE64_TYPES = [
14
+ utils_1.VARIABLE_TYPE.FILE,
15
+ utils_1.VARIABLE_TYPE.P12,
16
+ utils_1.VARIABLE_TYPE.IOS_KEYCHAIN,
17
+ utils_1.VARIABLE_TYPE.IOS_PROVISION_PROFILES,
18
+ ];
19
+ const MASKED = '!encrypted';
20
+ const MIN_MASKED_LINE = 8;
21
+ const MIN_MASKED_VALUE = 6;
22
+ // KEY:PATH, split on the first colon: a key has none, a Windows path may.
23
+ // `~` is expanded here - the shell leaves it alone in the middle of a word.
24
+ const parseVarFile = (spec) => {
25
+ const at = spec.indexOf(':');
26
+ const key = at < 0 ? '' : spec.slice(0, at);
27
+ let path = at < 0 ? '' : spec.slice(at + 1);
28
+ if (!key || !path) {
29
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_VARIABLE_INJECT_VAR_FILE_FORMAT)(spec));
30
+ }
31
+ if (path === '~' || path.startsWith('~/'))
32
+ path = (0, node_os_1.homedir)() + path.slice(1);
33
+ return { key, path: (0, node_path_1.resolve)(path) };
34
+ };
35
+ exports.parseVarFile = parseVarFile;
36
+ /**
37
+ * What goes into the command, from GET /variables?environment_id=: the
38
+ * environment's own variables first, then its bases nearest first, so the
39
+ * first variable of a key is the one that applies.
40
+ *
41
+ * VAR variables go into the process environment - all of them, or only the
42
+ * ones named by --var. File variables go only where --var-file puts them,
43
+ * with their password/passphrase as KEY_PASSWORD/KEY_PASSPHRASE.
44
+ *
45
+ * An encrypted value the API did not decrypt fails the whole run: injecting
46
+ * the masked form would hand the command a wrong secret without a word. The
47
+ * API does not say why it was not decrypted, so the reason is read from the
48
+ * response, in the order the API checks it: a bare marker is the missing
49
+ * manage permission, a marker with the ciphertext is the environment flag or,
50
+ * with the flag on, the token's scope.
51
+ */
52
+ const buildInjection = (variables, environment, vars, varFiles) => {
53
+ const byKey = new Map();
54
+ for (const variable of variables) {
55
+ if (!byKey.has(variable.key))
56
+ byKey.set(variable.key, variable);
57
+ }
58
+ const find = (key) => {
59
+ const variable = byKey.get(key);
60
+ if (!variable) {
61
+ throw new cliError_1.default('not_found', (0, texts_1.ERR_VARIABLE_INJECT_NOT_FOUND)(key), (0, texts_1.HINT_VARIABLE_INJECT_LIST)(environment.identifier ?? '<environment>'));
62
+ }
63
+ if (variable.disabled) {
64
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_VARIABLE_INJECT_DISABLED)(key));
65
+ }
66
+ return variable;
67
+ };
68
+ let plain;
69
+ if (vars.length) {
70
+ plain = [...new Set(vars)].map((key) => {
71
+ const variable = find(key);
72
+ const type = variable.type ?? utils_1.VARIABLE_TYPE.VAR;
73
+ if (type !== utils_1.VARIABLE_TYPE.VAR) {
74
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_VARIABLE_INJECT_NOT_VAR)(key, type));
75
+ }
76
+ return variable;
77
+ });
78
+ }
79
+ else {
80
+ plain = [...byKey.values()].filter((v) => (v.type ?? utils_1.VARIABLE_TYPE.VAR) === utils_1.VARIABLE_TYPE.VAR && !v.disabled);
81
+ }
82
+ const keys = new Set();
83
+ const paths = new Set();
84
+ const fileVars = varFiles.map(({ key, path }) => {
85
+ if (keys.has(key)) {
86
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_VARIABLE_INJECT_VAR_FILE_DUPLICATE_KEY)(key));
87
+ }
88
+ if (paths.has(path)) {
89
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_VARIABLE_INJECT_VAR_FILE_DUPLICATE_PATH)(path));
90
+ }
91
+ keys.add(key);
92
+ paths.add(path);
93
+ const variable = find(key);
94
+ if ((variable.type ?? utils_1.VARIABLE_TYPE.VAR) === utils_1.VARIABLE_TYPE.VAR) {
95
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_VARIABLE_INJECT_NOT_FILE)(key));
96
+ }
97
+ return { variable, path };
98
+ });
99
+ // every secret field that reaches the command, checked before anything runs
100
+ const masked = [];
101
+ const check = (key, value, secret) => {
102
+ if (secret && typeof value === 'string' && value.startsWith(MASKED)) {
103
+ masked.push({ key, value });
104
+ }
105
+ };
106
+ for (const v of plain)
107
+ check(v.key, v.value, !!v.encrypted);
108
+ for (const { variable: v } of fileVars) {
109
+ check(v.key, v.value, !!v.encrypted);
110
+ check(v.key, v.password, true);
111
+ check(v.key, v.passphrase, true);
112
+ }
113
+ if (masked.length) {
114
+ const failing = [...new Set(masked.map((m) => m.key))];
115
+ if (masked.some((m) => m.value === MASKED)) {
116
+ const noAccess = [
117
+ ...new Set(masked.filter((m) => m.value === MASKED).map((m) => m.key)),
118
+ ];
119
+ throw new cliError_1.default('forbidden', (0, texts_1.ERR_VARIABLE_INJECT_NO_ACCESS)(noAccess), texts_1.HINT_VARIABLE_INJECT_NO_ACCESS);
120
+ }
121
+ if (!environment.allow_decrypted_values) {
122
+ throw new cliError_1.default('forbidden', (0, texts_1.ERR_VARIABLE_INJECT_NOT_ALLOWED)(failing), texts_1.HINT_VARIABLE_INJECT_NOT_ALLOWED);
123
+ }
124
+ throw new cliError_1.default('forbidden', (0, texts_1.ERR_VARIABLE_INJECT_NO_SCOPE)(failing), texts_1.HINT_VARIABLE_INJECT_NO_SCOPE);
125
+ }
126
+ const injection = { env: {}, files: [], secrets: [], unmasked: [] };
127
+ // without the line ending a key or a file ends with, so printing one does
128
+ // not swallow the newline after it
129
+ const addSecret = (key, value) => {
130
+ let bytes = Buffer.isBuffer(value) ? value : Buffer.from(value);
131
+ let end = bytes.length;
132
+ while (end && (bytes[end - 1] === 0x0a || bytes[end - 1] === 0x0d))
133
+ end--;
134
+ bytes = bytes.subarray(0, end);
135
+ if (!bytes.length)
136
+ return;
137
+ if (bytes.length < MIN_MASKED_VALUE) {
138
+ if (!injection.unmasked.includes(key))
139
+ injection.unmasked.push(key);
140
+ return;
141
+ }
142
+ injection.secrets.push(bytes);
143
+ // a key or a file printed in part (`head -1`, a tool quoting one line of
144
+ // it) is masked line by line too; a short line is no secret on its own
145
+ // and masking it would garble unrelated output
146
+ if (bytes.includes(0x0a)) {
147
+ for (const line of bytes.toString('latin1').split(/\r?\n/)) {
148
+ if (line.length >= MIN_MASKED_LINE)
149
+ injection.secrets.push(Buffer.from(line, 'latin1'));
150
+ }
151
+ }
152
+ };
153
+ for (const v of plain) {
154
+ const value = v.value ?? '';
155
+ injection.env[v.key] = value;
156
+ if (v.encrypted)
157
+ addSecret(v.key, value);
158
+ }
159
+ const extras = [];
160
+ for (const { variable: v, path } of fileVars) {
161
+ const value = v.value ?? '';
162
+ const content = BASE64_TYPES.includes(v.type)
163
+ ? Buffer.from(value, 'base64')
164
+ : Buffer.from(value);
165
+ injection.files.push({ path, content });
166
+ if (v.encrypted)
167
+ addSecret(v.key, content);
168
+ if (v.password)
169
+ extras.push({ name: `${v.key}_PASSWORD`, key: v.key, value: v.password });
170
+ if (v.passphrase)
171
+ extras.push({ name: `${v.key}_PASSPHRASE`, key: v.key, value: v.passphrase });
172
+ }
173
+ for (const { name, key, value } of extras) {
174
+ if (name in injection.env) {
175
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_VARIABLE_INJECT_NAME_CONFLICT)(name, key));
176
+ }
177
+ injection.env[name] = value;
178
+ addSecret(name, value);
179
+ }
180
+ return injection;
181
+ };
182
+ exports.buildInjection = buildInjection;
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const node_stream_1 = require("node:stream");
4
+ const MASK = Buffer.from('***');
5
+ /**
6
+ * Replaces the secrets in a byte stream with ***. Works on bytes, not text,
7
+ * so binary output passes through intact and a multi-byte character split
8
+ * between chunks is not a concern.
9
+ *
10
+ * A secret can arrive split between two writes, so a tail of a chunk that is
11
+ * the start of a secret is held back until the next chunk shows whether it
12
+ * is one. Only such a tail is held - anything else goes out at once - and
13
+ * only for flushDelay: a prompt that happens to end like the start of a
14
+ * secret must not hang. A secret written in two parts further apart than
15
+ * that is not masked; programs print a value in one write.
16
+ */
17
+ class SecretMask extends node_stream_1.Transform {
18
+ flushDelay;
19
+ secrets;
20
+ longest;
21
+ pending = Buffer.alloc(0);
22
+ timer = null;
23
+ // bytes taken in so far, for telling a stream that still flows from one
24
+ // that went quiet
25
+ bytesIn = 0;
26
+ constructor(secrets, flushDelay = 50) {
27
+ super();
28
+ this.flushDelay = flushDelay;
29
+ // longest first, so a secret containing another is masked whole
30
+ this.secrets = secrets
31
+ .filter((s) => s.length)
32
+ .sort((a, b) => b.length - a.length);
33
+ this.longest = this.secrets[0]?.length ?? 0;
34
+ }
35
+ _transform(chunk, _encoding, callback) {
36
+ this.clearTimer();
37
+ this.bytesIn += chunk.length;
38
+ const data = this.pending.length ? Buffer.concat([this.pending, chunk]) : chunk;
39
+ const out = [];
40
+ let i = 0;
41
+ for (;;) {
42
+ let at = -1;
43
+ let match = null;
44
+ for (const secret of this.secrets) {
45
+ const index = data.indexOf(secret, i);
46
+ if (index >= 0 && (at < 0 || index < at)) {
47
+ at = index;
48
+ match = secret;
49
+ }
50
+ }
51
+ if (!match)
52
+ break;
53
+ out.push(data.subarray(i, at), MASK);
54
+ i = at + match.length;
55
+ }
56
+ const hold = this.heldTail(data, i);
57
+ out.push(data.subarray(i, hold));
58
+ this.pending = Buffer.from(data.subarray(hold));
59
+ const ready = Buffer.concat(out);
60
+ if (ready.length)
61
+ this.push(ready);
62
+ if (this.pending.length) {
63
+ this.timer = setTimeout(() => this.release(), this.flushDelay);
64
+ }
65
+ callback();
66
+ }
67
+ _flush(callback) {
68
+ this.release();
69
+ callback();
70
+ }
71
+ _destroy(err, callback) {
72
+ this.clearTimer();
73
+ callback(err);
74
+ }
75
+ // Earliest position from which the rest of data starts some secret.
76
+ heldTail(data, from) {
77
+ const start = Math.max(from, data.length - this.longest + 1);
78
+ for (let p = start; p < data.length; p++) {
79
+ const rest = data.subarray(p);
80
+ if (this.secrets.some((s) => s.length > rest.length && s.subarray(0, rest.length).equals(rest))) {
81
+ return p;
82
+ }
83
+ }
84
+ return data.length;
85
+ }
86
+ release() {
87
+ this.clearTimer();
88
+ if (this.pending.length) {
89
+ const pending = this.pending;
90
+ this.pending = Buffer.alloc(0);
91
+ this.push(pending);
92
+ }
93
+ }
94
+ clearTimer() {
95
+ if (this.timer)
96
+ clearTimeout(this.timer);
97
+ this.timer = null;
98
+ }
99
+ }
100
+ exports.default = SecretMask;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bdy",
3
3
  "preferGlobal": false,
4
- "version": "1.25.38-stage",
4
+ "version": "1.25.38",
5
5
  "type": "commonjs",
6
6
  "license": "MIT",
7
7
  "homepage": "https://buddy.works/docs/cli",