@kaynooo/cli-env 0.0.0-stage → 0.8.1
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/LICENSE +21 -0
- package/README.md +47 -2
- package/dist/ev.js +2422 -0
- package/dist/redact.js +1576 -0
- package/package.json +37 -4
- package/src/dotenv.ts +164 -0
package/dist/ev.js
ADDED
|
@@ -0,0 +1,2422 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
|
|
4
|
+
// src/ev.ts
|
|
5
|
+
import process11 from "process";
|
|
6
|
+
|
|
7
|
+
// ../kit/src/args.ts
|
|
8
|
+
import process6 from "process";
|
|
9
|
+
import { parseArgs } from "util";
|
|
10
|
+
|
|
11
|
+
// ../kit/src/format.ts
|
|
12
|
+
import process3 from "process";
|
|
13
|
+
|
|
14
|
+
// ../kit/src/style.ts
|
|
15
|
+
import process2 from "process";
|
|
16
|
+
|
|
17
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
18
|
+
function x(s) {
|
|
19
|
+
let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
|
|
20
|
+
if (!/^[a-f0-9]+$/.test(r))
|
|
21
|
+
return [0, 0, 0];
|
|
22
|
+
let t = r.length, n = (c) => Number.parseInt(c, 16);
|
|
23
|
+
if (t === 3 || t === 4) {
|
|
24
|
+
let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
|
|
25
|
+
return g !== undefined ? [c, u, h, g] : [c, u, h];
|
|
26
|
+
}
|
|
27
|
+
if (t !== 6 && t !== 8)
|
|
28
|
+
throw Error(`Invalid hex color length: ${t}`);
|
|
29
|
+
let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
|
|
30
|
+
if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
|
|
31
|
+
throw Error(`Invalid hex color value: ${s}`);
|
|
32
|
+
return y !== undefined ? [a, b, o, y] : [a, b, o];
|
|
33
|
+
}
|
|
34
|
+
function A(s) {
|
|
35
|
+
let [r, t, n, a] = s;
|
|
36
|
+
if (a)
|
|
37
|
+
return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
|
|
38
|
+
return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
|
|
39
|
+
}
|
|
40
|
+
function R(s, r, t) {
|
|
41
|
+
s = (s % 360 + 360) % 360, t /= 100;
|
|
42
|
+
let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
|
|
43
|
+
let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
|
|
44
|
+
return Math.round(255 * y);
|
|
45
|
+
};
|
|
46
|
+
return [a(0), a(8), a(4)];
|
|
47
|
+
}
|
|
48
|
+
function k(s) {
|
|
49
|
+
let [r, t, n] = s;
|
|
50
|
+
r /= 255, t /= 255, n /= 255;
|
|
51
|
+
let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
|
|
52
|
+
if (a !== b) {
|
|
53
|
+
let u = a - b;
|
|
54
|
+
if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
|
|
55
|
+
o = (t - n) / u + (t < n ? 6 : 0);
|
|
56
|
+
else if (a === t)
|
|
57
|
+
o = (n - r) / u + 2;
|
|
58
|
+
else
|
|
59
|
+
o = (r - t) / u + 4;
|
|
60
|
+
o /= 6;
|
|
61
|
+
}
|
|
62
|
+
return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
|
|
63
|
+
}
|
|
64
|
+
function H(s, r, t) {
|
|
65
|
+
s = (s % 360 + 360) % 360, r /= 100, t /= 100;
|
|
66
|
+
let n = (a) => {
|
|
67
|
+
let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
|
|
68
|
+
return Math.round(255 * o);
|
|
69
|
+
};
|
|
70
|
+
return [n(5), n(3), n(1)];
|
|
71
|
+
}
|
|
72
|
+
function f(s) {
|
|
73
|
+
let [r, t, n] = s;
|
|
74
|
+
r /= 255, t /= 255, n /= 255;
|
|
75
|
+
let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
|
|
76
|
+
if (o !== 0) {
|
|
77
|
+
if (a === r)
|
|
78
|
+
y = (t - n) / o + (t < n ? 6 : 0);
|
|
79
|
+
else if (a === t)
|
|
80
|
+
y = (n - r) / o + 2;
|
|
81
|
+
else
|
|
82
|
+
y = (r - t) / o + 4;
|
|
83
|
+
y /= 6;
|
|
84
|
+
}
|
|
85
|
+
return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
|
|
86
|
+
}
|
|
87
|
+
function O(s) {
|
|
88
|
+
let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
|
|
89
|
+
if (a === 1)
|
|
90
|
+
return [0, 0, 0, 100];
|
|
91
|
+
let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
|
|
92
|
+
return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
|
|
93
|
+
}
|
|
94
|
+
function v(s, r, t, n) {
|
|
95
|
+
return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
|
|
96
|
+
}
|
|
97
|
+
var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
|
98
|
+
var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
|
|
99
|
+
var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
|
|
100
|
+
function T(s) {
|
|
101
|
+
let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
|
|
102
|
+
return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
|
|
103
|
+
}
|
|
104
|
+
function M(s, r, t) {
|
|
105
|
+
let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
|
|
106
|
+
return [u(o), u(y), u(c)];
|
|
107
|
+
}
|
|
108
|
+
function d(s) {
|
|
109
|
+
let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
|
|
110
|
+
return [i(r, 4), i(a, 4), i(b, 2)];
|
|
111
|
+
}
|
|
112
|
+
function C(s, r, t) {
|
|
113
|
+
let n = t * Math.PI / 180;
|
|
114
|
+
return M(s, r * Math.cos(n), r * Math.sin(n));
|
|
115
|
+
}
|
|
116
|
+
function l(s) {
|
|
117
|
+
let r = s / 255;
|
|
118
|
+
return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
class e {
|
|
122
|
+
r;
|
|
123
|
+
g;
|
|
124
|
+
b;
|
|
125
|
+
a;
|
|
126
|
+
constructor(s, r, t, n = 1) {
|
|
127
|
+
this.r = s, this.g = r, this.b = t, this.a = n;
|
|
128
|
+
}
|
|
129
|
+
static from(s, r) {
|
|
130
|
+
if (s === "hex") {
|
|
131
|
+
let [t, n, a, b] = x(r);
|
|
132
|
+
return new e(t, n, a, b);
|
|
133
|
+
}
|
|
134
|
+
if (s === "rgb") {
|
|
135
|
+
if (Array.isArray(r)) {
|
|
136
|
+
let [o, y, c, u] = r;
|
|
137
|
+
return new e(o, y, c, u);
|
|
138
|
+
}
|
|
139
|
+
let { r: t, g: n, b: a, a: b } = r;
|
|
140
|
+
return new e(t, n, a, b);
|
|
141
|
+
}
|
|
142
|
+
if (s === "hsl") {
|
|
143
|
+
let t, n, a, b;
|
|
144
|
+
if (Array.isArray(r))
|
|
145
|
+
[t, n, a, b] = r;
|
|
146
|
+
else
|
|
147
|
+
({ h: t, s: n, l: a, a: b } = r);
|
|
148
|
+
let [o, y, c] = R(t, n, a);
|
|
149
|
+
return new e(o, y, c, b);
|
|
150
|
+
}
|
|
151
|
+
if (s === "hsv") {
|
|
152
|
+
let t, n, a, b;
|
|
153
|
+
if (Array.isArray(r))
|
|
154
|
+
[t, n, a, b] = r;
|
|
155
|
+
else
|
|
156
|
+
({ h: t, s: n, v: a, a: b } = r);
|
|
157
|
+
let [o, y, c] = H(t, n, a);
|
|
158
|
+
return new e(o, y, c, b);
|
|
159
|
+
}
|
|
160
|
+
if (s === "cmyk") {
|
|
161
|
+
let t, n, a, b, o;
|
|
162
|
+
if (Array.isArray(r))
|
|
163
|
+
[t, n, a, b, o] = r;
|
|
164
|
+
else
|
|
165
|
+
({ c: t, m: n, y: a, k: b, a: o } = r);
|
|
166
|
+
let [y, c, u] = v(t, n, a, b);
|
|
167
|
+
return new e(y, c, u, o);
|
|
168
|
+
}
|
|
169
|
+
if (s === "oklch") {
|
|
170
|
+
let t, n, a, b;
|
|
171
|
+
if (Array.isArray(r))
|
|
172
|
+
[t, n, a, b] = r;
|
|
173
|
+
else
|
|
174
|
+
({ l: t, c: n, h: a, a: b } = r);
|
|
175
|
+
let [o, y, c] = C(t, n, a);
|
|
176
|
+
return new e(o, y, c, b);
|
|
177
|
+
}
|
|
178
|
+
if (s === "oklab") {
|
|
179
|
+
let t, n, a, b;
|
|
180
|
+
if (Array.isArray(r))
|
|
181
|
+
[t, n, a, b] = r;
|
|
182
|
+
else
|
|
183
|
+
({ l: t, a: n, b: a, alpha: b } = r);
|
|
184
|
+
let [o, y, c] = M(t, n, a);
|
|
185
|
+
return new e(o, y, c, b);
|
|
186
|
+
}
|
|
187
|
+
throw Error("Invalid input");
|
|
188
|
+
}
|
|
189
|
+
to(s) {
|
|
190
|
+
switch (s) {
|
|
191
|
+
case "rgb":
|
|
192
|
+
return [this.r, this.g, this.b];
|
|
193
|
+
case "rgba":
|
|
194
|
+
return [this.r, this.g, this.b, this.a];
|
|
195
|
+
case "hex":
|
|
196
|
+
return A([this.r, this.g, this.b]);
|
|
197
|
+
case "hexa":
|
|
198
|
+
return A([this.r, this.g, this.b, this.a]);
|
|
199
|
+
case "hsl":
|
|
200
|
+
return k([this.r, this.g, this.b]);
|
|
201
|
+
case "hsla":
|
|
202
|
+
return [...k([this.r, this.g, this.b]), this.a];
|
|
203
|
+
case "hsv":
|
|
204
|
+
return f([this.r, this.g, this.b]);
|
|
205
|
+
case "hsva":
|
|
206
|
+
return [...f([this.r, this.g, this.b]), this.a];
|
|
207
|
+
case "cmyk":
|
|
208
|
+
return O([this.r, this.g, this.b]);
|
|
209
|
+
case "cmyka":
|
|
210
|
+
return [...O([this.r, this.g, this.b]), this.a];
|
|
211
|
+
case "oklch":
|
|
212
|
+
return d([this.r, this.g, this.b]);
|
|
213
|
+
case "oklcha":
|
|
214
|
+
return [...d([this.r, this.g, this.b]), this.a];
|
|
215
|
+
case "oklab":
|
|
216
|
+
return T([this.r, this.g, this.b]);
|
|
217
|
+
case "oklaba":
|
|
218
|
+
return [...T([this.r, this.g, this.b]), this.a];
|
|
219
|
+
default:
|
|
220
|
+
return [this.r, this.g, this.b];
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
getLuminance() {
|
|
224
|
+
let s = l(this.r), r = l(this.g), t = l(this.b);
|
|
225
|
+
return 0.2126 * s + 0.7152 * r + 0.0722 * t;
|
|
226
|
+
}
|
|
227
|
+
contrastRatio(s) {
|
|
228
|
+
let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
|
|
229
|
+
return (n + 0.05) / (a + 0.05);
|
|
230
|
+
}
|
|
231
|
+
bestContrastForeground() {
|
|
232
|
+
let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
|
|
233
|
+
return t >= n ? s : r;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
|
|
238
|
+
var r = 39;
|
|
239
|
+
var o = 49;
|
|
240
|
+
var f2 = "\x1B[";
|
|
241
|
+
var C2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
|
|
242
|
+
let [a, l, s] = e.from("hex", i).to("rgb");
|
|
243
|
+
return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
|
|
244
|
+
}, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
|
|
245
|
+
var b = new Set(["", "1", "2", "3", "true"]);
|
|
246
|
+
function h(i, n = globalThis.process?.env ?? {}) {
|
|
247
|
+
if (n.FORCE_COLOR !== undefined)
|
|
248
|
+
return b.has(n.FORCE_COLOR);
|
|
249
|
+
if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
|
|
250
|
+
return false;
|
|
251
|
+
return i?.isTTY === true;
|
|
252
|
+
}
|
|
253
|
+
function d2(i, n, a) {
|
|
254
|
+
if (!h(a.stream ?? globalThis.process?.stdout, a.env))
|
|
255
|
+
return n;
|
|
256
|
+
let l = "", s = "";
|
|
257
|
+
for (let g = 0, y = i.length;g < y; g++) {
|
|
258
|
+
let [c, p] = i[g];
|
|
259
|
+
l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
|
|
260
|
+
}
|
|
261
|
+
return l + n + s;
|
|
262
|
+
}
|
|
263
|
+
function u(i, n = []) {
|
|
264
|
+
return new Proxy((l) => d2(n, l, i), { get(l, s) {
|
|
265
|
+
let g = C2[s];
|
|
266
|
+
if (Array.isArray(g))
|
|
267
|
+
return u(i, [...n, g]);
|
|
268
|
+
if (typeof g === "function")
|
|
269
|
+
return (...y) => u(i, [...n, g(...y)]);
|
|
270
|
+
throw Error(`Unknown style: ${String(s)}`);
|
|
271
|
+
} });
|
|
272
|
+
}
|
|
273
|
+
function le(i = {}) {
|
|
274
|
+
return u(i);
|
|
275
|
+
}
|
|
276
|
+
var t = le();
|
|
277
|
+
|
|
278
|
+
// ../kit/src/style.ts
|
|
279
|
+
var MARKS = {
|
|
280
|
+
ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
|
|
281
|
+
warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
|
|
282
|
+
problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
|
|
283
|
+
note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
|
|
284
|
+
};
|
|
285
|
+
function takesControlCodes(stream, env = process2.env) {
|
|
286
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
|
|
287
|
+
}
|
|
288
|
+
function paint(stream, env = process2.env) {
|
|
289
|
+
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
290
|
+
}
|
|
291
|
+
function marked(mark, text, stream, detail, env = process2.env) {
|
|
292
|
+
const colors = paint(stream, env);
|
|
293
|
+
const { symbol, word, paint: tint } = MARKS[mark];
|
|
294
|
+
const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
|
|
295
|
+
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
296
|
+
}
|
|
297
|
+
function ok(text, detail) {
|
|
298
|
+
console.log(marked("ok", text, process2.stdout, detail));
|
|
299
|
+
}
|
|
300
|
+
var STATUSES = {
|
|
301
|
+
passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
|
|
302
|
+
failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
|
|
303
|
+
running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
|
|
304
|
+
queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
|
|
305
|
+
skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
|
|
306
|
+
};
|
|
307
|
+
var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
|
|
308
|
+
|
|
309
|
+
// ../kit/src/format.ts
|
|
310
|
+
function upTo(text, separator) {
|
|
311
|
+
const end = text.indexOf(separator);
|
|
312
|
+
return end === -1 ? text : text.slice(0, end);
|
|
313
|
+
}
|
|
314
|
+
function truncate(text, width) {
|
|
315
|
+
return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
|
|
316
|
+
}
|
|
317
|
+
var LINE_BREAKS = /\s*\n\s*/g;
|
|
318
|
+
var ESCAPE = String.fromCharCode(27);
|
|
319
|
+
function textWidth(text) {
|
|
320
|
+
return Bun.stringWidth(text);
|
|
321
|
+
}
|
|
322
|
+
function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
|
|
323
|
+
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
324
|
+
const widths = [];
|
|
325
|
+
for (const row of cells) {
|
|
326
|
+
for (const [index, cell] of row.entries())
|
|
327
|
+
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
328
|
+
}
|
|
329
|
+
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
330
|
+
const colors = paint(process3.stdout);
|
|
331
|
+
const lines = shown.map((row) => row.map((cell, index) => {
|
|
332
|
+
const width = widths[index] ?? 0;
|
|
333
|
+
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
334
|
+
if (align[index] === "right")
|
|
335
|
+
return `${gap}${cell}`;
|
|
336
|
+
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
337
|
+
}).join(" ").trimEnd());
|
|
338
|
+
return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
|
|
339
|
+
`);
|
|
340
|
+
}
|
|
341
|
+
function narrow(rows, widths, limit) {
|
|
342
|
+
const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
|
|
343
|
+
const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
|
|
344
|
+
const floor = 8;
|
|
345
|
+
while (used() > limit) {
|
|
346
|
+
let widest = -1;
|
|
347
|
+
for (const [index, width] of widths.entries()) {
|
|
348
|
+
if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
|
|
349
|
+
widest = index;
|
|
350
|
+
}
|
|
351
|
+
if (widest === -1)
|
|
352
|
+
break;
|
|
353
|
+
widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
|
|
354
|
+
}
|
|
355
|
+
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
356
|
+
}
|
|
357
|
+
function printJson(value) {
|
|
358
|
+
console.log(JSON.stringify(value, undefined, 2));
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// ../kit/src/help.ts
|
|
362
|
+
import process4 from "process";
|
|
363
|
+
var OPTIONAL = /\[[^\]]+\]/g;
|
|
364
|
+
var USAGE_PREFIX = /^usage:\s*/i;
|
|
365
|
+
var FULL_STOP = /\.$/;
|
|
366
|
+
function usageLine(usage, colors = paint(process4.stdout)) {
|
|
367
|
+
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
368
|
+
}
|
|
369
|
+
function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces } = {}) {
|
|
370
|
+
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
|
|
371
|
+
`);
|
|
372
|
+
}
|
|
373
|
+
function replacesRows(replaces, colors = paint(process4.stdout)) {
|
|
374
|
+
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
375
|
+
}
|
|
376
|
+
function wantsHelpJson(env = process4.env) {
|
|
377
|
+
return env.KIT_HELP === "json";
|
|
378
|
+
}
|
|
379
|
+
function description(usage, { examples = [], replaces } = {}) {
|
|
380
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
381
|
+
`);
|
|
382
|
+
const first = lines[0];
|
|
383
|
+
const colon = first.indexOf(": ");
|
|
384
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
385
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
386
|
+
return {
|
|
387
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
388
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
389
|
+
...replaces === undefined ? {} : { replaces },
|
|
390
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
function exampleRows(examples, colors = paint(process4.stdout)) {
|
|
394
|
+
if (examples.length === 0)
|
|
395
|
+
return [];
|
|
396
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
397
|
+
}
|
|
398
|
+
function optionRows(options, colors = paint(process4.stdout)) {
|
|
399
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
400
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
401
|
+
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
402
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
403
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
404
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
|
|
405
|
+
});
|
|
406
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
407
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// ../kit/src/text.ts
|
|
411
|
+
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
412
|
+
function distance(a, b) {
|
|
413
|
+
let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
|
|
414
|
+
for (const [i, left] of [...a].entries()) {
|
|
415
|
+
const current = [i + 1];
|
|
416
|
+
for (const [j, right] of [...b].entries())
|
|
417
|
+
current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
|
|
418
|
+
previous = current;
|
|
419
|
+
}
|
|
420
|
+
return previous[b.length] ?? 0;
|
|
421
|
+
}
|
|
422
|
+
function closest(name, names) {
|
|
423
|
+
const started = names.find((known) => known.startsWith(name));
|
|
424
|
+
if (started !== undefined)
|
|
425
|
+
return started;
|
|
426
|
+
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
427
|
+
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
428
|
+
}
|
|
429
|
+
// ../kit/src/input.ts
|
|
430
|
+
import process5 from "process";
|
|
431
|
+
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
432
|
+
if (path === "-") {
|
|
433
|
+
if (process5.stdin.isTTY)
|
|
434
|
+
fail(noStdin);
|
|
435
|
+
return Bun.stdin.text();
|
|
436
|
+
}
|
|
437
|
+
const file = Bun.file(path);
|
|
438
|
+
if (!await file.exists())
|
|
439
|
+
fail(`no file ${path}`);
|
|
440
|
+
return file.text();
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// ../kit/src/args.ts
|
|
444
|
+
var DASHES = /^-+/;
|
|
445
|
+
function jsonOption(holds) {
|
|
446
|
+
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
class Exit extends Error {
|
|
450
|
+
code;
|
|
451
|
+
hint;
|
|
452
|
+
constructor(message, code, hint) {
|
|
453
|
+
super(message);
|
|
454
|
+
this.code = code;
|
|
455
|
+
this.hint = hint;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
function fail(message, code = 2, hint) {
|
|
459
|
+
throw new Exit(message, code, hint);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
class UsageError extends Exit {
|
|
463
|
+
constructor(message, hint) {
|
|
464
|
+
super(message, 2, hint);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
function badUsage(message) {
|
|
468
|
+
throw new UsageError(message);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
class HelpShown extends Exit {
|
|
472
|
+
constructor() {
|
|
473
|
+
super("help shown", 0);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
class Completing {
|
|
478
|
+
options;
|
|
479
|
+
positionals;
|
|
480
|
+
candidates;
|
|
481
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
482
|
+
this.options = options;
|
|
483
|
+
this.positionals = positionals;
|
|
484
|
+
this.candidates = candidates;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
var completion = { active: false };
|
|
488
|
+
var OUTPUT_OPTIONS = {
|
|
489
|
+
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
490
|
+
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
491
|
+
};
|
|
492
|
+
function applyOutput(color, plain, env = process6.env) {
|
|
493
|
+
const when = plain === true ? "never" : color ?? "auto";
|
|
494
|
+
if (when === "auto")
|
|
495
|
+
return;
|
|
496
|
+
if (when !== "always" && when !== "never")
|
|
497
|
+
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
498
|
+
if (when === "always") {
|
|
499
|
+
env.FORCE_COLOR = "1";
|
|
500
|
+
delete env.NO_COLOR;
|
|
501
|
+
} else {
|
|
502
|
+
env.NO_COLOR = "1";
|
|
503
|
+
delete env.FORCE_COLOR;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
function parse(args, usage, options, settings = {}) {
|
|
507
|
+
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
508
|
+
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
509
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
510
|
+
if (completion.active)
|
|
511
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
512
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
513
|
+
let parsed;
|
|
514
|
+
try {
|
|
515
|
+
parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
516
|
+
} catch (error) {
|
|
517
|
+
const message = parseError(error);
|
|
518
|
+
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
519
|
+
}
|
|
520
|
+
const values = parsed.values;
|
|
521
|
+
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
522
|
+
if (values.help === true) {
|
|
523
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
|
|
524
|
+
throw new HelpShown;
|
|
525
|
+
}
|
|
526
|
+
checkChoices(parsed.values, all);
|
|
527
|
+
checkConflicts(parsed.values, all);
|
|
528
|
+
if (settings.positionals !== undefined)
|
|
529
|
+
checkPositionals(parsed.positionals, settings.positionals);
|
|
530
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
531
|
+
}
|
|
532
|
+
function splitRest(args, passes) {
|
|
533
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
534
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
535
|
+
}
|
|
536
|
+
function splitTrailing(args, options, count) {
|
|
537
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
538
|
+
let seen = 0;
|
|
539
|
+
if (count === 0)
|
|
540
|
+
return { own: args, rest: undefined };
|
|
541
|
+
for (let at = 0;at < args.length; at++) {
|
|
542
|
+
const word = args[at];
|
|
543
|
+
if (word === "--")
|
|
544
|
+
break;
|
|
545
|
+
if (word.startsWith("-")) {
|
|
546
|
+
if (takesValue(word))
|
|
547
|
+
at++;
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
seen++;
|
|
551
|
+
if (seen === count)
|
|
552
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
553
|
+
}
|
|
554
|
+
return { own: args, rest: undefined };
|
|
555
|
+
}
|
|
556
|
+
function listed(options, allowNegative) {
|
|
557
|
+
if (!allowNegative)
|
|
558
|
+
return options;
|
|
559
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
560
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
561
|
+
return [[name, option]];
|
|
562
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
563
|
+
}));
|
|
564
|
+
}
|
|
565
|
+
function withBare(args, options) {
|
|
566
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
567
|
+
if (bare.size === 0)
|
|
568
|
+
return args;
|
|
569
|
+
const separator = args.indexOf("--");
|
|
570
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
571
|
+
return [...own.flatMap((arg, index) => {
|
|
572
|
+
const optional = bare.get(arg);
|
|
573
|
+
const next = own[index + 1];
|
|
574
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
575
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
576
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
577
|
+
}
|
|
578
|
+
function checkConflicts(values, options) {
|
|
579
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
580
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
581
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
582
|
+
if (other !== undefined)
|
|
583
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
function checkChoices(values, options) {
|
|
587
|
+
for (const [name, option] of Object.entries(options)) {
|
|
588
|
+
if (option.choices === undefined)
|
|
589
|
+
continue;
|
|
590
|
+
const given = values[name];
|
|
591
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
592
|
+
if (typeof value === "string")
|
|
593
|
+
oneOf(value, name, option.choices);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
function oneOf(value, name, choices) {
|
|
598
|
+
if (!choices.includes(value))
|
|
599
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
600
|
+
return value;
|
|
601
|
+
}
|
|
602
|
+
function checkPositionals(given, names) {
|
|
603
|
+
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
604
|
+
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
605
|
+
if (given.length < required)
|
|
606
|
+
badUsage(`missing ${names[given.length]}`);
|
|
607
|
+
if (!variadic && given.length > names.length)
|
|
608
|
+
badUsage(`unexpected argument ${given[names.length]}`);
|
|
609
|
+
}
|
|
610
|
+
function joinDashValues(args, options) {
|
|
611
|
+
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
612
|
+
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
613
|
+
const joined = [];
|
|
614
|
+
for (let i = 0;i < args.length; i++) {
|
|
615
|
+
const arg = args[i] ?? "";
|
|
616
|
+
if (arg === "--")
|
|
617
|
+
return [...joined, ...args.slice(i)];
|
|
618
|
+
const name = longOf.get(arg);
|
|
619
|
+
const next = args[i + 1];
|
|
620
|
+
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
621
|
+
joined.push(`--${name}=${next}`);
|
|
622
|
+
i++;
|
|
623
|
+
} else {
|
|
624
|
+
joined.push(arg);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
return joined;
|
|
628
|
+
}
|
|
629
|
+
function parseError(error) {
|
|
630
|
+
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
631
|
+
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
632
|
+
}
|
|
633
|
+
var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
634
|
+
function nearestOption(message, options, allowNegative) {
|
|
635
|
+
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
636
|
+
if (typed === undefined)
|
|
637
|
+
return;
|
|
638
|
+
const word = typed.replace(DASHES, "");
|
|
639
|
+
if (word.length < 2 && !typed.startsWith("--"))
|
|
640
|
+
return;
|
|
641
|
+
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
642
|
+
...option.short === undefined ? [] : [`-${option.short}`],
|
|
643
|
+
`--${name}`,
|
|
644
|
+
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
645
|
+
]);
|
|
646
|
+
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
647
|
+
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
648
|
+
}
|
|
649
|
+
// ../kit/src/progress.ts
|
|
650
|
+
var ESC = String.fromCharCode(27);
|
|
651
|
+
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
652
|
+
var RESET_STYLE = `${ESC}[0m`;
|
|
653
|
+
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
654
|
+
// ../kit/src/cli.ts
|
|
655
|
+
import process8 from "process";
|
|
656
|
+
|
|
657
|
+
// ../kit/src/usage.ts
|
|
658
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
659
|
+
import { homedir } from "os";
|
|
660
|
+
import { dirname, isAbsolute, join } from "path";
|
|
661
|
+
import process7 from "process";
|
|
662
|
+
|
|
663
|
+
// ../kit/src/logs.ts
|
|
664
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
665
|
+
var CLI_FOLDER = "kaynooo-cli";
|
|
666
|
+
|
|
667
|
+
// ../kit/src/usage.ts
|
|
668
|
+
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
669
|
+
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
670
|
+
var LONGEST_NAME = 40;
|
|
671
|
+
var usageError;
|
|
672
|
+
function noteUsageError(message) {
|
|
673
|
+
usageError = message;
|
|
674
|
+
}
|
|
675
|
+
function stateHome(env = process7.env) {
|
|
676
|
+
const dir = env.XDG_STATE_HOME;
|
|
677
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
|
|
678
|
+
}
|
|
679
|
+
function usagePath(env = process7.env) {
|
|
680
|
+
return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
681
|
+
}
|
|
682
|
+
function usageRecorded(env = process7.env) {
|
|
683
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
684
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
685
|
+
}
|
|
686
|
+
function flagNames(argv) {
|
|
687
|
+
const end = argv.indexOf("--");
|
|
688
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
689
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
690
|
+
}
|
|
691
|
+
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
692
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
693
|
+
usageError = undefined;
|
|
694
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
695
|
+
}
|
|
696
|
+
function recordUsage(entry, env = process7.env) {
|
|
697
|
+
if (!usageRecorded(env))
|
|
698
|
+
return;
|
|
699
|
+
try {
|
|
700
|
+
const path = usagePath(env);
|
|
701
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
702
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
703
|
+
`, { mode: 384 });
|
|
704
|
+
} catch {}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
// ../kit/src/cli.ts
|
|
708
|
+
var LEVEL_OPTIONS = {
|
|
709
|
+
...OUTPUT_OPTIONS,
|
|
710
|
+
help: { type: "boolean", short: "h", description: "show this help" }
|
|
711
|
+
};
|
|
712
|
+
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
713
|
+
async function commandRows(all, colors) {
|
|
714
|
+
const commands = shown(all);
|
|
715
|
+
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
716
|
+
const groups = new Map([["Commands:", []]]);
|
|
717
|
+
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
718
|
+
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
719
|
+
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
720
|
+
const rows = groups.get(heading) ?? [];
|
|
721
|
+
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
722
|
+
groups.set(heading, rows);
|
|
723
|
+
}
|
|
724
|
+
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
725
|
+
}
|
|
726
|
+
function shown(commands) {
|
|
727
|
+
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
728
|
+
}
|
|
729
|
+
function takeOutputFlags(argv) {
|
|
730
|
+
let index = 0;
|
|
731
|
+
for (;index < argv.length; index++) {
|
|
732
|
+
const word = argv[index];
|
|
733
|
+
if (word === "--plain")
|
|
734
|
+
applyOutput(undefined, true);
|
|
735
|
+
else if (word.startsWith("--color="))
|
|
736
|
+
applyOutput(word.slice("--color=".length), undefined);
|
|
737
|
+
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
738
|
+
applyOutput(argv[++index], undefined);
|
|
739
|
+
else
|
|
740
|
+
break;
|
|
741
|
+
}
|
|
742
|
+
return argv.slice(index);
|
|
743
|
+
}
|
|
744
|
+
async function resolveSummary(summary) {
|
|
745
|
+
return typeof summary === "string" ? summary : summary();
|
|
746
|
+
}
|
|
747
|
+
function scopeOf(commands, extra, aliases) {
|
|
748
|
+
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
749
|
+
}
|
|
750
|
+
async function expand(scope, words) {
|
|
751
|
+
if (scope.lazy.length === 0)
|
|
752
|
+
return scope;
|
|
753
|
+
const commands = { ...scope.commands };
|
|
754
|
+
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
755
|
+
for (const [name, command] of Object.entries(added))
|
|
756
|
+
commands[name] ??= command;
|
|
757
|
+
}
|
|
758
|
+
return { ...scope, commands, lazy: [] };
|
|
759
|
+
}
|
|
760
|
+
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
761
|
+
const colors = paint(stream);
|
|
762
|
+
const prefix = path.join(" ");
|
|
763
|
+
const summary = await resolveSummary(lazySummary);
|
|
764
|
+
if (wantsHelpJson())
|
|
765
|
+
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
766
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
767
|
+
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
768
|
+
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
769
|
+
return [
|
|
770
|
+
header(colors, summary),
|
|
771
|
+
"",
|
|
772
|
+
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
773
|
+
...replacesRows(replaces, colors),
|
|
774
|
+
"",
|
|
775
|
+
...await commandRows(commands, colors),
|
|
776
|
+
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
777
|
+
"",
|
|
778
|
+
colors.bold("Options:"),
|
|
779
|
+
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
780
|
+
...exampleRows(examples ?? [], colors),
|
|
781
|
+
"",
|
|
782
|
+
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
783
|
+
].join(`
|
|
784
|
+
`);
|
|
785
|
+
}
|
|
786
|
+
function printError(prefix, message, hint, cause) {
|
|
787
|
+
const colors = paint(process8.stderr);
|
|
788
|
+
const styled = takesControlCodes(process8.stderr);
|
|
789
|
+
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
790
|
+
const under = (label, text, tint) => text === undefined ? "" : `
|
|
791
|
+
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
792
|
+
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
793
|
+
}
|
|
794
|
+
function printJsonError(message, hint, cause) {
|
|
795
|
+
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
796
|
+
}
|
|
797
|
+
function wantsJson(argv) {
|
|
798
|
+
const end = argv.indexOf("--");
|
|
799
|
+
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
800
|
+
}
|
|
801
|
+
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
802
|
+
if (error instanceof HelpShown)
|
|
803
|
+
return 0;
|
|
804
|
+
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
805
|
+
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
806
|
+
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
807
|
+
if (error instanceof UsageError)
|
|
808
|
+
noteUsageError(error.message);
|
|
809
|
+
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
810
|
+
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
811
|
+
return error instanceof Exit ? error.code : 1;
|
|
812
|
+
}
|
|
813
|
+
async function dispatch(level, typed, { version, redact }) {
|
|
814
|
+
const prefix = level.path.join(" ");
|
|
815
|
+
let argv;
|
|
816
|
+
try {
|
|
817
|
+
argv = takeOutputFlags(typed);
|
|
818
|
+
} catch (error) {
|
|
819
|
+
return reportThrown(prefix, error);
|
|
820
|
+
}
|
|
821
|
+
const [name, ...args] = argv;
|
|
822
|
+
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
823
|
+
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
824
|
+
try {
|
|
825
|
+
return await fallback.run([]);
|
|
826
|
+
} catch (error) {
|
|
827
|
+
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
if (name === undefined && level.path.length > 1) {
|
|
831
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
|
|
832
|
+
return 2;
|
|
833
|
+
}
|
|
834
|
+
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
835
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
|
|
836
|
+
return 0;
|
|
837
|
+
}
|
|
838
|
+
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
839
|
+
console.log(version);
|
|
840
|
+
return 0;
|
|
841
|
+
}
|
|
842
|
+
let command = level.commands[level.aliases?.[name] ?? name];
|
|
843
|
+
let rest = args;
|
|
844
|
+
let ran = name;
|
|
845
|
+
if (command === undefined && level.lazy.length > 0) {
|
|
846
|
+
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
847
|
+
command = level.commands[level.aliases?.[name] ?? name];
|
|
848
|
+
}
|
|
849
|
+
if (command === undefined && level.defaultCommand !== undefined) {
|
|
850
|
+
command = level.commands[level.defaultCommand];
|
|
851
|
+
rest = argv;
|
|
852
|
+
ran = level.defaultCommand;
|
|
853
|
+
}
|
|
854
|
+
if (command === undefined) {
|
|
855
|
+
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
856
|
+
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
857
|
+
return 2;
|
|
858
|
+
}
|
|
859
|
+
if ("commands" in command) {
|
|
860
|
+
const { summary } = command;
|
|
861
|
+
return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
|
|
862
|
+
}
|
|
863
|
+
try {
|
|
864
|
+
return await command.run(rest);
|
|
865
|
+
} catch (error) {
|
|
866
|
+
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
var COMPLETE = "__complete";
|
|
870
|
+
var FILES = "__files__";
|
|
871
|
+
async function completingOf(run) {
|
|
872
|
+
completion.active = true;
|
|
873
|
+
try {
|
|
874
|
+
await run([]);
|
|
875
|
+
} catch (error) {
|
|
876
|
+
if (error instanceof Completing)
|
|
877
|
+
return error;
|
|
878
|
+
} finally {
|
|
879
|
+
completion.active = false;
|
|
880
|
+
}
|
|
881
|
+
return new Completing({});
|
|
882
|
+
}
|
|
883
|
+
async function optionsOf(run) {
|
|
884
|
+
return (await completingOf(run)).options;
|
|
885
|
+
}
|
|
886
|
+
function candidateLine(candidate) {
|
|
887
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
888
|
+
}
|
|
889
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
890
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
891
|
+
let index = 0;
|
|
892
|
+
let at = 0;
|
|
893
|
+
while (at < before.length) {
|
|
894
|
+
const word = before[at];
|
|
895
|
+
if (word === "--") {
|
|
896
|
+
index += before.length - at - 1;
|
|
897
|
+
break;
|
|
898
|
+
}
|
|
899
|
+
if (!word.startsWith("-"))
|
|
900
|
+
index++;
|
|
901
|
+
else if (takesValue(word))
|
|
902
|
+
at++;
|
|
903
|
+
at++;
|
|
904
|
+
}
|
|
905
|
+
const last = positionals.at(-1);
|
|
906
|
+
if (index < positionals.length)
|
|
907
|
+
return positionals[index];
|
|
908
|
+
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
909
|
+
}
|
|
910
|
+
async function leafCandidates(run, words) {
|
|
911
|
+
const completing = await completingOf(run);
|
|
912
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
913
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
914
|
+
const flag = words.at(-2);
|
|
915
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
916
|
+
if (option?.type === "string") {
|
|
917
|
+
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
918
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
919
|
+
}
|
|
920
|
+
const name = positionalBeingTyped(words.slice(0, -1), completing);
|
|
921
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
922
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
923
|
+
}
|
|
924
|
+
async function candidates(scope, defaultCommand, words, before = []) {
|
|
925
|
+
const [word = "", ...rest] = words;
|
|
926
|
+
const listing = rest.length === 0 && !word.startsWith("-");
|
|
927
|
+
let { commands, aliases } = scope;
|
|
928
|
+
let command = commands[aliases?.[word] ?? word];
|
|
929
|
+
if (listing || command === undefined) {
|
|
930
|
+
({ commands, aliases } = await expand(scope, [...before, ...words]));
|
|
931
|
+
command = commands[aliases?.[word] ?? word];
|
|
932
|
+
}
|
|
933
|
+
if (listing) {
|
|
934
|
+
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
935
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
936
|
+
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
937
|
+
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
938
|
+
return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
|
|
939
|
+
}
|
|
940
|
+
if (command === undefined) {
|
|
941
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
942
|
+
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
943
|
+
}
|
|
944
|
+
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
945
|
+
}
|
|
946
|
+
async function printCandidates(found) {
|
|
947
|
+
for (const line of await found)
|
|
948
|
+
console.log(line);
|
|
949
|
+
return 0;
|
|
950
|
+
}
|
|
951
|
+
async function runCli(cli, argv = process8.argv.slice(2)) {
|
|
952
|
+
if (argv[0] === COMPLETE)
|
|
953
|
+
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
954
|
+
const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version: cli.version, redact: cli.redact });
|
|
955
|
+
if (cli.usage !== false) {
|
|
956
|
+
try {
|
|
957
|
+
recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
|
|
958
|
+
} catch {}
|
|
959
|
+
}
|
|
960
|
+
return code;
|
|
961
|
+
}
|
|
962
|
+
function commandPath(scope, argv) {
|
|
963
|
+
const path = [];
|
|
964
|
+
let level = scope;
|
|
965
|
+
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
966
|
+
const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
|
|
967
|
+
const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
|
|
968
|
+
if (command === undefined)
|
|
969
|
+
break;
|
|
970
|
+
path.push(word);
|
|
971
|
+
if (!("commands" in command))
|
|
972
|
+
break;
|
|
973
|
+
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
974
|
+
}
|
|
975
|
+
return path.length === 0 ? undefined : path.join(" ");
|
|
976
|
+
}
|
|
977
|
+
async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
|
|
978
|
+
if (argv[0] === COMPLETE)
|
|
979
|
+
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
980
|
+
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
981
|
+
console.log(version);
|
|
982
|
+
return 0;
|
|
983
|
+
}
|
|
984
|
+
let code;
|
|
985
|
+
try {
|
|
986
|
+
code = await run(argv);
|
|
987
|
+
} catch (error) {
|
|
988
|
+
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
989
|
+
}
|
|
990
|
+
if (usage !== false)
|
|
991
|
+
recordUsage(usageEntry(name, undefined, argv, code));
|
|
992
|
+
return code;
|
|
993
|
+
}
|
|
994
|
+
// ../kit/src/secrets.ts
|
|
995
|
+
var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
|
|
996
|
+
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
997
|
+
var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
|
|
998
|
+
function isSecretName(name) {
|
|
999
|
+
return SECRET_PART.test(name) || name.split(WORD_BREAKS).some((word) => SECRET_WORDS.has(word.toLowerCase()));
|
|
1000
|
+
}
|
|
1001
|
+
// ../kit/src/sessions.ts
|
|
1002
|
+
var {Glob } = globalThis.Bun;
|
|
1003
|
+
var SESSION_FILES = new Glob("*.json");
|
|
1004
|
+
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1005
|
+
// package.json
|
|
1006
|
+
var version = "0.8.1";
|
|
1007
|
+
|
|
1008
|
+
// src/commands/audit.ts
|
|
1009
|
+
import { stat as stat4 } from "fs/promises";
|
|
1010
|
+
import { relative, resolve } from "path";
|
|
1011
|
+
import process10 from "process";
|
|
1012
|
+
|
|
1013
|
+
// ../kit/src/shell.ts
|
|
1014
|
+
var SEPARATORS = new Set([`
|
|
1015
|
+
`, ";", "|"]);
|
|
1016
|
+
var PLAIN_BREAKERS = new Set(["<", ">", "(", ")", "&", "|"]);
|
|
1017
|
+
var GLOB_CHARS = new Set(["*", "?", "["]);
|
|
1018
|
+
var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
|
|
1019
|
+
var SAFE_WORD = /^[\w@%+=:,./-]+$/;
|
|
1020
|
+
var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
|
|
1021
|
+
var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
|
|
1022
|
+
var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh"]);
|
|
1023
|
+
var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, "su", "runuser"]);
|
|
1024
|
+
var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
|
|
1025
|
+
var PRINTERS = new Set(["echo", "printf"]);
|
|
1026
|
+
var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
1027
|
+
function wrapper(short = "", long = [], operands = 0) {
|
|
1028
|
+
return { short, long, operands };
|
|
1029
|
+
}
|
|
1030
|
+
var WRAPPERS = new Map([
|
|
1031
|
+
["command", wrapper()],
|
|
1032
|
+
["builtin", wrapper()],
|
|
1033
|
+
["nohup", wrapper()],
|
|
1034
|
+
["setsid", wrapper()],
|
|
1035
|
+
["busybox", wrapper()],
|
|
1036
|
+
["exec", wrapper("a")],
|
|
1037
|
+
["time", wrapper("fo", ["--format", "--output"])],
|
|
1038
|
+
["env", wrapper("uCS", ["--unset", "--chdir", "--split-string", "--argv0"])],
|
|
1039
|
+
["sudo", wrapper("ughpCTrtUDR", ["--user", "--group", "--host", "--prompt", "--close-from", "--command-timeout", "--role", "--type", "--other-user", "--chdir", "--chroot"])],
|
|
1040
|
+
["doas", wrapper("uC")],
|
|
1041
|
+
["timeout", wrapper("sk", ["--signal", "--kill-after"], 1)],
|
|
1042
|
+
["nice", wrapper("n", ["--adjustment"])],
|
|
1043
|
+
["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
|
|
1044
|
+
["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
|
|
1045
|
+
["chroot", wrapper("", ["--userspec", "--groups"], 1)],
|
|
1046
|
+
["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
|
|
1047
|
+
]);
|
|
1048
|
+
function shellQuote(word) {
|
|
1049
|
+
return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// src/audit.ts
|
|
1053
|
+
import { readdir as readdir2, stat as stat2 } from "fs/promises";
|
|
1054
|
+
import { dirname as dirname3, join as join3 } from "path";
|
|
1055
|
+
var {$ } = globalThis.Bun;
|
|
1056
|
+
|
|
1057
|
+
// src/files.ts
|
|
1058
|
+
import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
|
|
1059
|
+
import { basename, dirname as dirname2, join as join2 } from "path";
|
|
1060
|
+
|
|
1061
|
+
// src/dotenv.ts
|
|
1062
|
+
var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
|
|
1063
|
+
var EXPORTED = /^\s*export\s/;
|
|
1064
|
+
var INLINE_COMMENT = /\s+#.*$/;
|
|
1065
|
+
var CARRIAGE_RETURN = /\r$/;
|
|
1066
|
+
var ESCAPES = { n: `
|
|
1067
|
+
`, r: "\r", t: "\t", '"': '"', "\\": "\\", $: "$" };
|
|
1068
|
+
var LINE_BREAK = /[\r\n]/;
|
|
1069
|
+
var RAW_ONLY = /["\\]/;
|
|
1070
|
+
var NEEDS_QUOTES = /[\s#"'\\$`]/;
|
|
1071
|
+
function closingQuote(text, quote) {
|
|
1072
|
+
for (let index = 0;index < text.length; index++) {
|
|
1073
|
+
if (quote === '"' && text[index] === "\\")
|
|
1074
|
+
index++;
|
|
1075
|
+
else if (text[index] === quote)
|
|
1076
|
+
return index;
|
|
1077
|
+
}
|
|
1078
|
+
return -1;
|
|
1079
|
+
}
|
|
1080
|
+
function unescapeDollar(text) {
|
|
1081
|
+
return text.replaceAll("\\$", "$");
|
|
1082
|
+
}
|
|
1083
|
+
function unescapeDouble(text) {
|
|
1084
|
+
let out = "";
|
|
1085
|
+
for (let index = 0;index < text.length; index++) {
|
|
1086
|
+
const next = text[index + 1];
|
|
1087
|
+
if (text[index] === "\\" && next !== undefined && next in ESCAPES) {
|
|
1088
|
+
out += ESCAPES[next];
|
|
1089
|
+
index++;
|
|
1090
|
+
} else {
|
|
1091
|
+
out += text[index];
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
return out;
|
|
1095
|
+
}
|
|
1096
|
+
function parseDotenv(text) {
|
|
1097
|
+
const physical = text.split(`
|
|
1098
|
+
`);
|
|
1099
|
+
const lines = [];
|
|
1100
|
+
for (let index = 0;index < physical.length; index++) {
|
|
1101
|
+
const line = physical[index] ?? "";
|
|
1102
|
+
const match = ASSIGNMENT.exec(line.replace(CARRIAGE_RETURN, ""));
|
|
1103
|
+
if (match === null) {
|
|
1104
|
+
lines.push({ raw: line });
|
|
1105
|
+
continue;
|
|
1106
|
+
}
|
|
1107
|
+
const [, key = "", rest = ""] = match;
|
|
1108
|
+
const start = rest.trimStart();
|
|
1109
|
+
const quote = start[0];
|
|
1110
|
+
if (quote !== '"' && quote !== "'" && quote !== "`") {
|
|
1111
|
+
lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()) });
|
|
1112
|
+
continue;
|
|
1113
|
+
}
|
|
1114
|
+
let body = start.slice(1);
|
|
1115
|
+
let raw = line;
|
|
1116
|
+
let end = closingQuote(body, quote);
|
|
1117
|
+
while (end === -1 && index + 1 < physical.length) {
|
|
1118
|
+
index++;
|
|
1119
|
+
body += `
|
|
1120
|
+
${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
|
|
1121
|
+
raw += `
|
|
1122
|
+
${physical[index] ?? ""}`;
|
|
1123
|
+
end = closingQuote(body, quote);
|
|
1124
|
+
}
|
|
1125
|
+
const inner = end === -1 ? body : body.slice(0, end);
|
|
1126
|
+
lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
|
|
1127
|
+
}
|
|
1128
|
+
return { lines };
|
|
1129
|
+
}
|
|
1130
|
+
function serializeDotenv(file) {
|
|
1131
|
+
return file.lines.map((line) => line.raw).join(`
|
|
1132
|
+
`);
|
|
1133
|
+
}
|
|
1134
|
+
function entries(file) {
|
|
1135
|
+
const map = new Map;
|
|
1136
|
+
for (const line of file.lines) {
|
|
1137
|
+
if (line.key !== undefined)
|
|
1138
|
+
map.set(line.key, line.value ?? "");
|
|
1139
|
+
}
|
|
1140
|
+
return map;
|
|
1141
|
+
}
|
|
1142
|
+
function formatAssignment(key, value) {
|
|
1143
|
+
if (value === "" || !NEEDS_QUOTES.test(value))
|
|
1144
|
+
return `${key}=${value}`;
|
|
1145
|
+
if (RAW_ONLY.test(value) && !value.includes("'") && !LINE_BREAK.test(value))
|
|
1146
|
+
return `${key}='${value.replaceAll("$", "\\$")}'`;
|
|
1147
|
+
const escaped = value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("\r", "\\r").replaceAll(`
|
|
1148
|
+
`, "\\n").replaceAll("$", "\\$");
|
|
1149
|
+
return `${key}="${escaped}"`;
|
|
1150
|
+
}
|
|
1151
|
+
function setLine(file, key, value, raw) {
|
|
1152
|
+
const index = file.lines.findLastIndex((line) => line.key === key);
|
|
1153
|
+
const existing = file.lines[index];
|
|
1154
|
+
if (existing !== undefined) {
|
|
1155
|
+
const exported = EXPORTED.test(existing.raw) ? "export " : "";
|
|
1156
|
+
file.lines[index] = { raw: raw ?? `${exported}${formatAssignment(key, value)}`, key, value };
|
|
1157
|
+
return;
|
|
1158
|
+
}
|
|
1159
|
+
const line = { raw: raw ?? formatAssignment(key, value), key, value };
|
|
1160
|
+
const last = file.lines.at(-1);
|
|
1161
|
+
if (last === undefined)
|
|
1162
|
+
file.lines.push(line, { raw: "" });
|
|
1163
|
+
else if (last.raw === "")
|
|
1164
|
+
file.lines.splice(-1, 0, line);
|
|
1165
|
+
else
|
|
1166
|
+
file.lines.push(line, { raw: "" });
|
|
1167
|
+
}
|
|
1168
|
+
function removeKey(file, key) {
|
|
1169
|
+
const before = file.lines.length;
|
|
1170
|
+
file.lines = file.lines.filter((line) => line.key !== key);
|
|
1171
|
+
return before - file.lines.length;
|
|
1172
|
+
}
|
|
1173
|
+
function lastLine(file, key) {
|
|
1174
|
+
return file.lines.findLast((line) => line.key === key);
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
// src/mask.ts
|
|
1178
|
+
var MIN_KNOWN_LENGTH = 4;
|
|
1179
|
+
var KEY_MASK = "*** private key redacted ***";
|
|
1180
|
+
var PLAIN_VALUE = /^(?:true|false|null|none|nil|yes|no|on|off|undefined)$/i;
|
|
1181
|
+
var PLACEHOLDER = /^[$%{<(*/]/;
|
|
1182
|
+
var URL_PASSWORD = /(?<![a-z0-9+.-])[a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:([^\s'"]{1,1024})@/dgi;
|
|
1183
|
+
var PORT = /^\d{1,5}$/;
|
|
1184
|
+
var ESCAPE2 = /[.*+?^${}()|[\]\\]/g;
|
|
1185
|
+
function isPlaceholder(value) {
|
|
1186
|
+
return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
|
|
1187
|
+
}
|
|
1188
|
+
var TOKEN_FORMATS = [
|
|
1189
|
+
{ kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
|
|
1190
|
+
{ kind: "GitLab token", pattern: /\bglpat-[\w-]{20,}/dg },
|
|
1191
|
+
{ kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
|
|
1192
|
+
{ kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
|
|
1193
|
+
{ kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
|
|
1194
|
+
{ kind: "AWS access key", pattern: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/dg },
|
|
1195
|
+
{ kind: "npm token", pattern: /\bnpm_[A-Za-z0-9]{30,}/dg },
|
|
1196
|
+
{ kind: "Stripe key", pattern: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}/dg },
|
|
1197
|
+
{ kind: "Google API key", pattern: /\bAIza[\w-]{35}/dg },
|
|
1198
|
+
{ kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
|
|
1199
|
+
{ kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
|
|
1200
|
+
{ kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
|
|
1201
|
+
{ kind: "password", pattern: /(?<![\w-])(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?=([^\s"'&;,]{4,})/dgi, skip: isPlaceholder },
|
|
1202
|
+
{ kind: "password", pattern: /(?<![\w-])["']?(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?["']?\s*[:=]\s*(["'])((?:\\.|(?!\1)[^\\\n]){4,})\1/dgi, skip: isPlaceholder }
|
|
1203
|
+
];
|
|
1204
|
+
var PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
|
|
1205
|
+
var PEM_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
|
|
1206
|
+
var PEM_BODY = /(?<=-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----)(?:(?!-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----)[\s\S])+/dg;
|
|
1207
|
+
var PEM_BEGIN_ALL = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/g;
|
|
1208
|
+
var URL_PARTS = /(?<![a-z0-9+.-])[a-z][a-z0-9+.-]{0,31}:\/\/([^\s/?#'"<>`]*)([^\s?#'"<>`]*)(?:\?([^\s#'"<>`]*))?/dgi;
|
|
1209
|
+
var PATH_SEGMENT = /[^/]+/g;
|
|
1210
|
+
var SECRET_PARAM = /^(?:token|[a-z]+_token|key|api[_-]?key|access[_-]?key|secret|[a-z]+_secret|password|passwd|pwd|sig|signature|auth|authorization)$/i;
|
|
1211
|
+
var WEBHOOK_FORMATS = [
|
|
1212
|
+
["Discord webhook", /(?:^|\.)discord(?:app)?\.com\/api\/(?:v\d+\/)?webhooks\/\d+\/([\w-]+)/di],
|
|
1213
|
+
["Slack webhook", /^hooks\.slack\.com\/(?:services|workflows)\/(?:[\w-]+\/)*([\w-]+)/di],
|
|
1214
|
+
["Uptime Kuma push URL", /\/api\/push\/([\w-]+)/di],
|
|
1215
|
+
["healthchecks.io ping URL", /^hc-ping\.com\/([\w-]+)/di]
|
|
1216
|
+
];
|
|
1217
|
+
var OPAQUE_SEGMENT = /^(?:(?=[\w-]{20,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w-]+|(?=[A-Za-z\d]{32,}$)(?=.*[A-Za-z])(?=.*\d).+)$/;
|
|
1218
|
+
function hint(value) {
|
|
1219
|
+
const shown = Math.min(3, Math.floor(value.length / 4));
|
|
1220
|
+
return `${value.slice(0, shown)}***(${value.length})`;
|
|
1221
|
+
}
|
|
1222
|
+
function forms(value) {
|
|
1223
|
+
return [...new Set([value, encodeURIComponent(value), JSON.stringify(value).slice(1, -1)])];
|
|
1224
|
+
}
|
|
1225
|
+
function knownSecrets(pairs) {
|
|
1226
|
+
const keys = new Map;
|
|
1227
|
+
for (const [key, value] of pairs) {
|
|
1228
|
+
if (value.length < MIN_KNOWN_LENGTH || PLAIN_VALUE.test(value))
|
|
1229
|
+
continue;
|
|
1230
|
+
for (const form of forms(value)) {
|
|
1231
|
+
if (!keys.has(form))
|
|
1232
|
+
keys.set(form, key);
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
if (keys.size === 0)
|
|
1236
|
+
return { pattern: undefined, keys };
|
|
1237
|
+
const alternatives = [...keys.keys()].sort((a, b) => b.length - a.length).map((value) => value.replace(ESCAPE2, "\\$&"));
|
|
1238
|
+
return { pattern: new RegExp(`(?<!\\w)(?:${alternatives.join("|")})(?!\\w)`, "g"), keys };
|
|
1239
|
+
}
|
|
1240
|
+
function passwordSpans(text) {
|
|
1241
|
+
const spans = [];
|
|
1242
|
+
for (const url of text.matchAll(URL_PASSWORD)) {
|
|
1243
|
+
const [start, end] = url.indices?.[1] ?? [];
|
|
1244
|
+
const password = url[1] ?? "";
|
|
1245
|
+
const slash = password.indexOf("/");
|
|
1246
|
+
if (start !== undefined && end !== undefined && !(slash !== -1 && PORT.test(password.slice(0, slash))))
|
|
1247
|
+
spans.push([start, end]);
|
|
1248
|
+
}
|
|
1249
|
+
return spans;
|
|
1250
|
+
}
|
|
1251
|
+
function urlPasswords(text) {
|
|
1252
|
+
return passwordSpans(text).map(([start, end]) => text.slice(start, end));
|
|
1253
|
+
}
|
|
1254
|
+
function urlTokens(line) {
|
|
1255
|
+
const found = [];
|
|
1256
|
+
const add = (kind, start, value) => {
|
|
1257
|
+
found.push({ start, end: start + value.length, kind, mask: hint(value) });
|
|
1258
|
+
};
|
|
1259
|
+
for (const url of line.matchAll(URL_PARTS)) {
|
|
1260
|
+
const [authority, path = "", query] = [url[1] ?? "", url[2] ?? "", url[3]];
|
|
1261
|
+
const authorityStart = url.indices?.[1]?.[0];
|
|
1262
|
+
const pathStart = url.indices?.[2]?.[0];
|
|
1263
|
+
const queryStart = url.indices?.[3]?.[0];
|
|
1264
|
+
if (authorityStart === undefined || pathStart === undefined)
|
|
1265
|
+
continue;
|
|
1266
|
+
const hostAt = authority.lastIndexOf("@") + 1;
|
|
1267
|
+
const target = authority.slice(hostAt) + path;
|
|
1268
|
+
for (const [kind, pattern] of WEBHOOK_FORMATS) {
|
|
1269
|
+
const [start, end] = pattern.exec(target)?.indices?.[1] ?? [];
|
|
1270
|
+
if (start !== undefined && end !== undefined)
|
|
1271
|
+
add(kind, authorityStart + hostAt + start, target.slice(start, end));
|
|
1272
|
+
}
|
|
1273
|
+
for (const segment of path.matchAll(PATH_SEGMENT)) {
|
|
1274
|
+
if (OPAQUE_SEGMENT.test(segment[0]))
|
|
1275
|
+
add("URL token", pathStart + segment.index, segment[0]);
|
|
1276
|
+
}
|
|
1277
|
+
if (query === undefined || queryStart === undefined)
|
|
1278
|
+
continue;
|
|
1279
|
+
let offset = 0;
|
|
1280
|
+
for (const param of query.split("&")) {
|
|
1281
|
+
const equals = param.indexOf("=");
|
|
1282
|
+
if (equals > 0 && equals < param.length - 1 && SECRET_PARAM.test(param.slice(0, equals)))
|
|
1283
|
+
add("URL token", queryStart + offset + equals + 1, param.slice(equals + 1));
|
|
1284
|
+
offset += param.length + 1;
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
return found.filter((match) => match.end > match.start);
|
|
1288
|
+
}
|
|
1289
|
+
function findSecrets(line, known) {
|
|
1290
|
+
const found = [];
|
|
1291
|
+
for (const [start, end] of passwordSpans(line))
|
|
1292
|
+
found.push({ start, end, kind: "URL password", mask: "***" });
|
|
1293
|
+
for (const body of line.matchAll(PEM_BODY)) {
|
|
1294
|
+
const [start, end] = body.indices?.[0] ?? [];
|
|
1295
|
+
if (start !== undefined && end !== undefined)
|
|
1296
|
+
found.push({ start, end, kind: "private key", mask: KEY_MASK });
|
|
1297
|
+
}
|
|
1298
|
+
for (const { kind, pattern, skip } of TOKEN_FORMATS) {
|
|
1299
|
+
for (const token of line.matchAll(pattern)) {
|
|
1300
|
+
const [start, end] = token.indices?.at(-1) ?? [];
|
|
1301
|
+
if (start === undefined || end === undefined)
|
|
1302
|
+
continue;
|
|
1303
|
+
const value = line.slice(start, end);
|
|
1304
|
+
if (!skip?.(value))
|
|
1305
|
+
found.push({ start, end, kind, mask: hint(value) });
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
found.push(...urlTokens(line));
|
|
1309
|
+
if (known?.pattern !== undefined) {
|
|
1310
|
+
for (const value of line.matchAll(known.pattern))
|
|
1311
|
+
found.push({ start: value.index, end: value.index + value[0].length, kind: `value of ${known.keys.get(value[0])}`, mask: hint(value[0]) });
|
|
1312
|
+
}
|
|
1313
|
+
found.sort((a, b) => a.start - b.start || b.end - a.end);
|
|
1314
|
+
const kept = [];
|
|
1315
|
+
for (const match of found) {
|
|
1316
|
+
if (match.start >= (kept.at(-1)?.end ?? 0))
|
|
1317
|
+
kept.push(match);
|
|
1318
|
+
}
|
|
1319
|
+
return kept;
|
|
1320
|
+
}
|
|
1321
|
+
function openKeyBody(line) {
|
|
1322
|
+
const last = [...line.matchAll(PEM_BEGIN_ALL)].at(-1);
|
|
1323
|
+
if (last === undefined)
|
|
1324
|
+
return;
|
|
1325
|
+
const after = line.slice(last.index + last[0].length);
|
|
1326
|
+
return PEM_END.test(after) ? undefined : after.trim();
|
|
1327
|
+
}
|
|
1328
|
+
function maskLine(line, known) {
|
|
1329
|
+
let out = "";
|
|
1330
|
+
let at = 0;
|
|
1331
|
+
for (const match of findSecrets(line, known)) {
|
|
1332
|
+
out += line.slice(at, match.start) + match.mask;
|
|
1333
|
+
at = match.end;
|
|
1334
|
+
}
|
|
1335
|
+
return out + line.slice(at);
|
|
1336
|
+
}
|
|
1337
|
+
function maskValue(key, value, known) {
|
|
1338
|
+
if (value === "")
|
|
1339
|
+
return value;
|
|
1340
|
+
return isSecretName(key) || PEM_BEGIN.test(value) ? hint(value) : maskLine(value, known);
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
// src/files.ts
|
|
1344
|
+
var ENV_FILE = /^(?:\.env(?:\..+)?|.+\.env|\.envrc)$/;
|
|
1345
|
+
var TEMPLATE = /\.(?:example|sample|template|dist|defaults)$/;
|
|
1346
|
+
var KNOWN_DEPTH = 3;
|
|
1347
|
+
var SKIPPED = new Set(["node_modules", ".git", "vendor"]);
|
|
1348
|
+
var LOCK_WAIT_MS = 5000;
|
|
1349
|
+
var LOCK_STALE_MS = 30000;
|
|
1350
|
+
async function isFileEntry(entry, path) {
|
|
1351
|
+
if (entry.isFile())
|
|
1352
|
+
return true;
|
|
1353
|
+
if (!entry.isSymbolicLink())
|
|
1354
|
+
return false;
|
|
1355
|
+
try {
|
|
1356
|
+
return (await stat(path)).isFile();
|
|
1357
|
+
} catch {
|
|
1358
|
+
return false;
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
async function envFiles(folder = process.cwd()) {
|
|
1362
|
+
const found = await readdir(folder, { withFileTypes: true });
|
|
1363
|
+
const names = [];
|
|
1364
|
+
for (const entry of found) {
|
|
1365
|
+
if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join2(folder, entry.name)))
|
|
1366
|
+
names.push(entry.name);
|
|
1367
|
+
}
|
|
1368
|
+
return names.sort();
|
|
1369
|
+
}
|
|
1370
|
+
async function readEnv(path) {
|
|
1371
|
+
const file = Bun.file(path);
|
|
1372
|
+
if (!await file.exists())
|
|
1373
|
+
fail(`${path} does not exist`);
|
|
1374
|
+
return parseDotenv(await file.text());
|
|
1375
|
+
}
|
|
1376
|
+
async function writeAtomic(path, text) {
|
|
1377
|
+
let target = path;
|
|
1378
|
+
let mode = 384;
|
|
1379
|
+
let owner;
|
|
1380
|
+
try {
|
|
1381
|
+
target = await realpath(path);
|
|
1382
|
+
const current = await stat(target);
|
|
1383
|
+
mode = current.mode & 511;
|
|
1384
|
+
owner = current;
|
|
1385
|
+
} catch (error) {
|
|
1386
|
+
if (error.code !== "ENOENT")
|
|
1387
|
+
throw error;
|
|
1388
|
+
}
|
|
1389
|
+
const temp = join2(dirname2(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
|
|
1390
|
+
try {
|
|
1391
|
+
await writeFile(temp, text, { mode: 384, flag: "wx" });
|
|
1392
|
+
if (owner !== undefined)
|
|
1393
|
+
await keepOwner(temp, owner);
|
|
1394
|
+
await chmod(temp, mode);
|
|
1395
|
+
await rename(temp, target);
|
|
1396
|
+
} finally {
|
|
1397
|
+
await rm(temp, { force: true });
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
async function keepOwner(path, owner) {
|
|
1401
|
+
try {
|
|
1402
|
+
await chown(path, owner.uid, owner.gid);
|
|
1403
|
+
} catch (error) {
|
|
1404
|
+
if (error.code !== "EPERM")
|
|
1405
|
+
throw error;
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
async function writeEnv(path, file) {
|
|
1409
|
+
await writeAtomic(path, serializeDotenv(file));
|
|
1410
|
+
}
|
|
1411
|
+
async function withLocks(paths, fn) {
|
|
1412
|
+
const held = [];
|
|
1413
|
+
try {
|
|
1414
|
+
for (const path of [...new Set(paths)].sort())
|
|
1415
|
+
held.push(await acquire(path));
|
|
1416
|
+
return await fn();
|
|
1417
|
+
} finally {
|
|
1418
|
+
for (const lock of held)
|
|
1419
|
+
await rm(lock, { force: true });
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
async function acquire(path) {
|
|
1423
|
+
let real = path;
|
|
1424
|
+
try {
|
|
1425
|
+
real = await realpath(path);
|
|
1426
|
+
} catch {}
|
|
1427
|
+
const lock = join2(dirname2(real), `.${basename(real)}.lock`);
|
|
1428
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
1429
|
+
while (true) {
|
|
1430
|
+
try {
|
|
1431
|
+
await writeFile(lock, String(process.pid), { flag: "wx", mode: 384 });
|
|
1432
|
+
return lock;
|
|
1433
|
+
} catch (error) {
|
|
1434
|
+
if (error.code !== "EEXIST")
|
|
1435
|
+
throw error;
|
|
1436
|
+
}
|
|
1437
|
+
try {
|
|
1438
|
+
if (Date.now() - (await stat(lock)).mtimeMs > LOCK_STALE_MS)
|
|
1439
|
+
await rm(lock, { force: true });
|
|
1440
|
+
} catch {}
|
|
1441
|
+
if (Date.now() > deadline)
|
|
1442
|
+
fail(`${path} is locked by another ev run (${lock})`, 1);
|
|
1443
|
+
await Bun.sleep(25);
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
function secretPairs(file) {
|
|
1447
|
+
const pairs = [];
|
|
1448
|
+
for (const [key, value] of entries(file)) {
|
|
1449
|
+
if (isSecretName(key))
|
|
1450
|
+
pairs.push([key, value]);
|
|
1451
|
+
else
|
|
1452
|
+
pairs.push(...urlPasswords(value).map((password) => [key, password]));
|
|
1453
|
+
}
|
|
1454
|
+
return pairs;
|
|
1455
|
+
}
|
|
1456
|
+
async function envFilesBelow(folder, depth = 0) {
|
|
1457
|
+
const found = [];
|
|
1458
|
+
let children;
|
|
1459
|
+
try {
|
|
1460
|
+
children = await readdir(folder, { withFileTypes: true });
|
|
1461
|
+
} catch {
|
|
1462
|
+
return found;
|
|
1463
|
+
}
|
|
1464
|
+
for (const entry of children) {
|
|
1465
|
+
const path = join2(folder, entry.name);
|
|
1466
|
+
if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
|
|
1467
|
+
found.push(...await envFilesBelow(path, depth + 1));
|
|
1468
|
+
else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
|
|
1469
|
+
found.push(path);
|
|
1470
|
+
}
|
|
1471
|
+
return found;
|
|
1472
|
+
}
|
|
1473
|
+
async function loadKnown(folder = process.cwd(), extra = []) {
|
|
1474
|
+
const pairs = extra.flatMap(secretPairs);
|
|
1475
|
+
for (const path of await envFilesBelow(folder)) {
|
|
1476
|
+
try {
|
|
1477
|
+
pairs.push(...secretPairs(parseDotenv(await Bun.file(path).text())));
|
|
1478
|
+
} catch {}
|
|
1479
|
+
}
|
|
1480
|
+
return knownSecrets(pairs);
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
// src/audit.ts
|
|
1484
|
+
var MAX_DEPTH = 5;
|
|
1485
|
+
var SKIPPED2 = new Set(["node_modules", ".git", "vendor"]);
|
|
1486
|
+
var COMPOSE_FILE = /^(?:docker-)?compose[\w.-]*\.ya?ml$/;
|
|
1487
|
+
var ENTRY = /^\s*(?:-\s*)?["']?([A-Z0-9_]+)["']?\s*[:=]\s*["']?([^"'\s#]+)/;
|
|
1488
|
+
var SETTING_SUFFIX = /_(?:TTL|FILE|PATH|DIR|NAME|TIMEOUT|EXPIRY|EXPIRES|LIFETIME|LENGTH|ENABLED|ALGORITHM|HEADER|PREFIX|COUNT|MAX|MIN)$/i;
|
|
1489
|
+
var ACL_READER = /^(?:user|group):[^:]+:r/;
|
|
1490
|
+
var FLAG = /^(?:[01]|yes|no|true|false)$/i;
|
|
1491
|
+
function isInlineSecret(name, value) {
|
|
1492
|
+
if (value === "" || value.startsWith("$") || value.startsWith("/run/secrets/") || FLAG.test(value))
|
|
1493
|
+
return false;
|
|
1494
|
+
return isSecretName(name) && !SETTING_SUFFIX.test(name) || urlPasswords(value).some((password) => !password.startsWith("$"));
|
|
1495
|
+
}
|
|
1496
|
+
function inlineSecrets(compose) {
|
|
1497
|
+
const names = compose.split(`
|
|
1498
|
+
`).flatMap((line) => {
|
|
1499
|
+
const [, name = "", value = ""] = ENTRY.exec(line) ?? [];
|
|
1500
|
+
return isInlineSecret(name, value) ? [name] : [];
|
|
1501
|
+
});
|
|
1502
|
+
return [...new Set(names)];
|
|
1503
|
+
}
|
|
1504
|
+
async function openToOthers(path) {
|
|
1505
|
+
if (((await stat2(path)).mode & 4) === 0)
|
|
1506
|
+
return false;
|
|
1507
|
+
for (let dir = dirname3(path);dir !== "/"; dir = dirname3(dir)) {
|
|
1508
|
+
if (((await stat2(dir)).mode & 1) === 0)
|
|
1509
|
+
return false;
|
|
1510
|
+
}
|
|
1511
|
+
return true;
|
|
1512
|
+
}
|
|
1513
|
+
async function sharedWith(path) {
|
|
1514
|
+
const info = await stat2(path);
|
|
1515
|
+
const shared = (info.mode & 32) !== 0 && info.gid !== info.uid && info.gid !== process.getgid?.();
|
|
1516
|
+
if (!shared && (Bun.which("getfacl") === null || !await hasAclReader(path)))
|
|
1517
|
+
return false;
|
|
1518
|
+
for (let dir = dirname3(path);dir !== "/"; dir = dirname3(dir)) {
|
|
1519
|
+
if (((await stat2(dir)).mode & 9) === 0)
|
|
1520
|
+
return false;
|
|
1521
|
+
}
|
|
1522
|
+
return true;
|
|
1523
|
+
}
|
|
1524
|
+
async function hasAclReader(path) {
|
|
1525
|
+
const acl = await $`getfacl --absolute-names --omit-header -- ${path}`.quiet().nothrow();
|
|
1526
|
+
return acl.exitCode === 0 && acl.stdout.toString().split(`
|
|
1527
|
+
`).some((line) => ACL_READER.test(line));
|
|
1528
|
+
}
|
|
1529
|
+
async function tracked(path) {
|
|
1530
|
+
const run = await $`git ls-files --error-unmatch -- ${path}`.cwd(dirname3(path)).quiet().nothrow();
|
|
1531
|
+
const error = run.stderr.toString();
|
|
1532
|
+
if (run.exitCode === 0)
|
|
1533
|
+
return true;
|
|
1534
|
+
if (run.exitCode === 1 || error.includes("not a git repository"))
|
|
1535
|
+
return false;
|
|
1536
|
+
throw new Error(`git could not tell whether ${path} is tracked: ${error.trim() || `exit ${run.exitCode}`}`);
|
|
1537
|
+
}
|
|
1538
|
+
async function* candidates2(root, unread, depth = 0) {
|
|
1539
|
+
let found;
|
|
1540
|
+
try {
|
|
1541
|
+
found = await readdir2(root, { withFileTypes: true });
|
|
1542
|
+
} catch {
|
|
1543
|
+
unread.push(root);
|
|
1544
|
+
return;
|
|
1545
|
+
}
|
|
1546
|
+
for (const entry of found) {
|
|
1547
|
+
const path = join3(root, entry.name);
|
|
1548
|
+
if (entry.isDirectory() && depth < MAX_DEPTH && !SKIPPED2.has(entry.name))
|
|
1549
|
+
yield* candidates2(path, unread, depth + 1);
|
|
1550
|
+
else if (!TEMPLATE.test(entry.name) && (ENV_FILE.test(entry.name) || COMPOSE_FILE.test(entry.name)) && await isFileEntry(entry, path))
|
|
1551
|
+
yield path;
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
async function audit(roots) {
|
|
1555
|
+
const exposed = [];
|
|
1556
|
+
const unread = [];
|
|
1557
|
+
for (const root of roots) {
|
|
1558
|
+
for await (const path of candidates2(root, unread)) {
|
|
1559
|
+
const others = await openToOthers(path);
|
|
1560
|
+
const readable = others || await sharedWith(path);
|
|
1561
|
+
const group = readable && !others ? true : undefined;
|
|
1562
|
+
const name = path.slice(path.lastIndexOf("/") + 1);
|
|
1563
|
+
if (ENV_FILE.test(name)) {
|
|
1564
|
+
const isTracked = await tracked(path);
|
|
1565
|
+
if (readable || isTracked)
|
|
1566
|
+
exposed.push({ path, readable, ...group && { group }, tracked: isTracked });
|
|
1567
|
+
continue;
|
|
1568
|
+
}
|
|
1569
|
+
const secrets = readable ? inlineSecrets(await Bun.file(path).text()) : [];
|
|
1570
|
+
if (secrets.length > 0)
|
|
1571
|
+
exposed.push({ path, readable, ...group && { group }, tracked: false, secrets });
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
return { exposed: exposed.sort((a, b) => a.path.localeCompare(b.path)), unread };
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
// src/fix.ts
|
|
1578
|
+
import { chmod as chmod2, chown as chown2, lstat, rm as rm2, stat as stat3 } from "fs/promises";
|
|
1579
|
+
import { dirname as dirname4, join as join4 } from "path";
|
|
1580
|
+
var MAP_ENTRY = /^(\s*)(["']?)([A-Z0-9_]+)\2(\s*:)(.*)$/;
|
|
1581
|
+
var LIST_ENTRY = /^(\s*-[ \t]*)(["']?)([A-Z0-9_]+)=(.*)$/;
|
|
1582
|
+
var TRAILING = /^\s*(?:#.*)?$/;
|
|
1583
|
+
var PLAIN_COMMENT = /\s+#.*$/;
|
|
1584
|
+
var NOT_PLAIN = /^[|>&*![{]/;
|
|
1585
|
+
var ENV_PLAIN = /^[^\s#"'\\$`]*$/;
|
|
1586
|
+
function quoted(text, quote) {
|
|
1587
|
+
let value = "";
|
|
1588
|
+
for (let index = 0;index < text.length; index++) {
|
|
1589
|
+
const char = text[index] ?? "";
|
|
1590
|
+
const next = text[index + 1];
|
|
1591
|
+
if (quote === "'" && char === "'" && next === "'") {
|
|
1592
|
+
value += "'";
|
|
1593
|
+
index++;
|
|
1594
|
+
} else if (quote === '"' && char === "\\") {
|
|
1595
|
+
if (next !== "\\" && next !== '"')
|
|
1596
|
+
return;
|
|
1597
|
+
value += next;
|
|
1598
|
+
index++;
|
|
1599
|
+
} else if (char === quote) {
|
|
1600
|
+
return { value, after: text.slice(index + 1) };
|
|
1601
|
+
} else {
|
|
1602
|
+
value += char;
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
return;
|
|
1606
|
+
}
|
|
1607
|
+
function plain(text) {
|
|
1608
|
+
const value = text.replace(PLAIN_COMMENT, "").trimEnd();
|
|
1609
|
+
return { value, after: text.slice(value.length) };
|
|
1610
|
+
}
|
|
1611
|
+
function composeEntry(line) {
|
|
1612
|
+
const map = MAP_ENTRY.exec(line);
|
|
1613
|
+
if (map !== null) {
|
|
1614
|
+
const [, indent = "", keyQuote = "", key = "", colon = "", spaced = ""] = map;
|
|
1615
|
+
const rest = spaced.trimStart();
|
|
1616
|
+
const separator = colon + spaced.slice(0, spaced.length - rest.length);
|
|
1617
|
+
const quote = rest[0] === '"' || rest[0] === "'" ? rest[0] : "";
|
|
1618
|
+
const scalar = quote === "" ? plain(rest) : quoted(rest.slice(1), quote);
|
|
1619
|
+
if (scalar === undefined || !TRAILING.test(scalar.after))
|
|
1620
|
+
return { key, value: rest, unmovable: "its value is written in a form ev does not rewrite" };
|
|
1621
|
+
if (quote === "" && NOT_PLAIN.test(scalar.value))
|
|
1622
|
+
return { key, value: scalar.value, unmovable: "its value is a block, anchor, alias, tag or collection" };
|
|
1623
|
+
return { key, value: scalar.value, swap: (ref) => `${indent}${keyQuote}${key}${keyQuote}${separator}${quote}${ref}${quote}${scalar.after}` };
|
|
1624
|
+
}
|
|
1625
|
+
const list = LIST_ENTRY.exec(line);
|
|
1626
|
+
if (list === null)
|
|
1627
|
+
return;
|
|
1628
|
+
const [, dash = "", quote = "", key = "", rest = ""] = list;
|
|
1629
|
+
const scalar = quote === "" ? plain(rest) : quoted(rest, quote);
|
|
1630
|
+
if (scalar === undefined || !TRAILING.test(scalar.after))
|
|
1631
|
+
return { key, value: rest, unmovable: "its value is written in a form ev does not rewrite" };
|
|
1632
|
+
return { key, value: scalar.value, swap: (ref) => `${dash}${quote}${key}=${ref}${quote}${scalar.after}` };
|
|
1633
|
+
}
|
|
1634
|
+
function envLine(key, value) {
|
|
1635
|
+
if (ENV_PLAIN.test(value))
|
|
1636
|
+
return `${key}=${value}`;
|
|
1637
|
+
return value.includes("'") || value.includes(`
|
|
1638
|
+
`) ? undefined : `${key}='${value}'`;
|
|
1639
|
+
}
|
|
1640
|
+
async function isLink(path) {
|
|
1641
|
+
try {
|
|
1642
|
+
return (await lstat(path)).isSymbolicLink();
|
|
1643
|
+
} catch (error) {
|
|
1644
|
+
if (error.code === "ENOENT")
|
|
1645
|
+
return false;
|
|
1646
|
+
throw error;
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
async function resolved(path) {
|
|
1650
|
+
const run = Bun.spawn(["docker", "compose", "-f", path, "config", "--format", "json"], { cwd: dirname4(path), stdout: "pipe", stderr: "ignore", stdin: "ignore" });
|
|
1651
|
+
const [out, code] = await Promise.all([new Response(run.stdout).text(), run.exited]);
|
|
1652
|
+
return code === 0 ? out : undefined;
|
|
1653
|
+
}
|
|
1654
|
+
function gainedBy(before, after, key) {
|
|
1655
|
+
const services = (config) => Object.entries(JSON.parse(config).services ?? {});
|
|
1656
|
+
const had = new Set(services(before).filter(([, service]) => service.environment?.[key] !== undefined).map(([name]) => name));
|
|
1657
|
+
return services(after).filter(([name, service]) => service.environment?.[key] !== undefined && !had.has(name)).map(([name]) => name);
|
|
1658
|
+
}
|
|
1659
|
+
async function shutOthersOut(path, group = false) {
|
|
1660
|
+
try {
|
|
1661
|
+
await chmod2(path, (await stat3(path)).mode & (group ? 448 : 504));
|
|
1662
|
+
return true;
|
|
1663
|
+
} catch (error) {
|
|
1664
|
+
if (error.code === "EPERM")
|
|
1665
|
+
return false;
|
|
1666
|
+
throw error;
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
async function fixCompose(path, group = false) {
|
|
1670
|
+
const env = join4(dirname4(path), ".env");
|
|
1671
|
+
const compose = await Bun.file(path).text();
|
|
1672
|
+
const envBefore = await Bun.file(env).exists() ? await Bun.file(env).text() : undefined;
|
|
1673
|
+
const dotenv = parseDotenv(envBefore ?? "");
|
|
1674
|
+
const known = entries(dotenv);
|
|
1675
|
+
const fix = { path, env, moved: [], left: [], open: [] };
|
|
1676
|
+
const linked = await isLink(env);
|
|
1677
|
+
const lines = compose.split(`
|
|
1678
|
+
`).map((line) => {
|
|
1679
|
+
const entry = composeEntry(line);
|
|
1680
|
+
if (entry === undefined || !isInlineSecret(entry.key, entry.value))
|
|
1681
|
+
return line;
|
|
1682
|
+
const { key } = entry;
|
|
1683
|
+
if ("unmovable" in entry) {
|
|
1684
|
+
fix.left.push({ key, why: entry.unmovable });
|
|
1685
|
+
return line;
|
|
1686
|
+
}
|
|
1687
|
+
if (linked) {
|
|
1688
|
+
fix.left.push({ key, why: "its .env is a symbolic link" });
|
|
1689
|
+
return line;
|
|
1690
|
+
}
|
|
1691
|
+
if (entry.value.replaceAll("$$", "").includes("$")) {
|
|
1692
|
+
fix.left.push({ key, why: "its value reads another variable" });
|
|
1693
|
+
return line;
|
|
1694
|
+
}
|
|
1695
|
+
const value = entry.value.replaceAll("$$", "$");
|
|
1696
|
+
const existing = known.get(key);
|
|
1697
|
+
if (existing === undefined) {
|
|
1698
|
+
const raw = envLine(key, value);
|
|
1699
|
+
if (raw === undefined) {
|
|
1700
|
+
fix.left.push({ key, why: "its value holds a quote or line break a .env cannot keep literal" });
|
|
1701
|
+
return line;
|
|
1702
|
+
}
|
|
1703
|
+
setLine(dotenv, key, value, raw);
|
|
1704
|
+
known.set(key, value);
|
|
1705
|
+
} else if (existing !== value) {
|
|
1706
|
+
fix.left.push({ key, why: `${env.slice(env.lastIndexOf("/") + 1)} already sets it to another value` });
|
|
1707
|
+
return line;
|
|
1708
|
+
}
|
|
1709
|
+
if (!fix.moved.includes(key))
|
|
1710
|
+
fix.moved.push(key);
|
|
1711
|
+
return entry.swap(`\${${key}}`);
|
|
1712
|
+
});
|
|
1713
|
+
if (fix.moved.length > 0)
|
|
1714
|
+
await move(fix, compose, lines.join(`
|
|
1715
|
+
`), envBefore, serializeDotenv(dotenv));
|
|
1716
|
+
for (const file of [path, env]) {
|
|
1717
|
+
if (!(file === env && linked) && await Bun.file(file).exists() && !await shutOthersOut(file, group))
|
|
1718
|
+
fix.open.push(file);
|
|
1719
|
+
}
|
|
1720
|
+
return fix;
|
|
1721
|
+
}
|
|
1722
|
+
async function move(fix, compose, composeAfter, envBefore, envAfter) {
|
|
1723
|
+
const { path, env } = fix;
|
|
1724
|
+
const docker = Bun.which("docker") !== null;
|
|
1725
|
+
const before = docker ? await resolved(path) : undefined;
|
|
1726
|
+
if (envBefore === undefined) {
|
|
1727
|
+
await writeAtomic(env, envAfter);
|
|
1728
|
+
const { uid, gid } = await stat3(path);
|
|
1729
|
+
try {
|
|
1730
|
+
await chown2(env, uid, gid);
|
|
1731
|
+
} catch {}
|
|
1732
|
+
} else {
|
|
1733
|
+
await writeAtomic(env, envAfter);
|
|
1734
|
+
}
|
|
1735
|
+
await writeAtomic(path, composeAfter);
|
|
1736
|
+
if (!docker) {
|
|
1737
|
+
fix.check = "no docker";
|
|
1738
|
+
return;
|
|
1739
|
+
}
|
|
1740
|
+
if (before === undefined) {
|
|
1741
|
+
fix.check = "fails before";
|
|
1742
|
+
return;
|
|
1743
|
+
}
|
|
1744
|
+
const after = await resolved(path);
|
|
1745
|
+
if (after === before) {
|
|
1746
|
+
fix.check = "same";
|
|
1747
|
+
return;
|
|
1748
|
+
}
|
|
1749
|
+
await writeAtomic(path, compose);
|
|
1750
|
+
if (envBefore === undefined)
|
|
1751
|
+
await rm2(env);
|
|
1752
|
+
else
|
|
1753
|
+
await writeAtomic(env, envBefore);
|
|
1754
|
+
fix.check = "rolled back";
|
|
1755
|
+
fix.left.push(...fix.moved.map((key) => {
|
|
1756
|
+
const gained = after === undefined ? [] : gainedBy(before, after, key);
|
|
1757
|
+
return { key, why: gained.length > 0 ? `${gained.join(", ")} ${gained.length > 1 ? "load" : "loads"} the .env through env_file and would gain it, so it was put back` : "docker compose config resolved differently once moved, so it was put back" };
|
|
1758
|
+
}));
|
|
1759
|
+
fix.moved = [];
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1762
|
+
// src/commands/audit.ts
|
|
1763
|
+
var usage2 = `ev audit [dir...] [--fix]
|
|
1764
|
+
|
|
1765
|
+
Lists the .env files any account on the machine can read or git tracks, and the compose files any account can read that write a secret out (a secret-named value or a URL password) instead of reading it from a .env, never printing a value.
|
|
1766
|
+
Looks under each folder (the current one by default) down to 5 levels, skipping node_modules, vendor and .git, and leaves .example, .sample, .template and .dist files out. A folder it cannot read is named on stderr.
|
|
1767
|
+
With --fix, moves each secret a listed compose file writes out into the .env beside it as \${KEY}, puts it back when \`docker compose config\` resolves differently after, and shuts other accounts out of both files and of every listed .env; a key the .env already sets to another value stays put.
|
|
1768
|
+
Exits 0 when it finds none (with --fix, when none is left), 1 when it finds one, 2 on a usage error.`;
|
|
1769
|
+
var options = {
|
|
1770
|
+
json: jsonOption("the findings and the folders it could not read"),
|
|
1771
|
+
fix: { type: "boolean", description: "move inline compose secrets into a .env and shut other accounts out" }
|
|
1772
|
+
};
|
|
1773
|
+
var MAX_UNREAD_LISTED = 3;
|
|
1774
|
+
var CHECKS = {
|
|
1775
|
+
same: "docker compose config resolves the same",
|
|
1776
|
+
"rolled back": "docker compose config resolved differently, so everything was put back",
|
|
1777
|
+
"no docker": "not checked against docker compose config: docker is not installed",
|
|
1778
|
+
"fails before": "not checked against docker compose config: it already failed on the file"
|
|
1779
|
+
};
|
|
1780
|
+
async function isFolder(path) {
|
|
1781
|
+
try {
|
|
1782
|
+
return (await stat4(path)).isDirectory();
|
|
1783
|
+
} catch {
|
|
1784
|
+
return false;
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
function shown2(path) {
|
|
1788
|
+
return path.startsWith(`${process10.cwd()}/`) ? relative(process10.cwd(), path) : path;
|
|
1789
|
+
}
|
|
1790
|
+
async function fixAll(exposed, json) {
|
|
1791
|
+
const fixed = [];
|
|
1792
|
+
let left = false;
|
|
1793
|
+
for (const { path, readable, group, tracked, secrets } of exposed) {
|
|
1794
|
+
const fix = secrets === undefined ? undefined : await fixCompose(path, group === true);
|
|
1795
|
+
const open = fix?.open ?? (readable && !await shutOthersOut(path, group === true) ? [path] : []);
|
|
1796
|
+
if (fix !== undefined)
|
|
1797
|
+
fixed.push(fix);
|
|
1798
|
+
left ||= tracked || open.length > 0 || (fix?.left.length ?? 0) > 0;
|
|
1799
|
+
if (json)
|
|
1800
|
+
continue;
|
|
1801
|
+
const lines = [
|
|
1802
|
+
...fix === undefined || fix.moved.length === 0 ? [] : [`moved ${fix.moved.join(", ")} into ${shown2(fix.env)}`],
|
|
1803
|
+
...fix?.left.map(({ key, why }) => `left ${key} in place: ${why}`) ?? [],
|
|
1804
|
+
...fix?.check === undefined ? [] : [CHECKS[fix.check]],
|
|
1805
|
+
...open.map((file) => `another account owns ${file === path ? "it" : shown2(file)}, so it stays readable: sudo chmod go-rwx ${shellQuote(shown2(file))}`),
|
|
1806
|
+
...readable && !open.includes(path) ? ["now unreadable by other accounts"] : [],
|
|
1807
|
+
...tracked ? [`tracked by git: git rm --cached ${shellQuote(shown2(path))}, then ignore it`] : []
|
|
1808
|
+
];
|
|
1809
|
+
console.log(`${shown2(path)}
|
|
1810
|
+
${lines.join(`
|
|
1811
|
+
`)}`);
|
|
1812
|
+
}
|
|
1813
|
+
return { fixed, left };
|
|
1814
|
+
}
|
|
1815
|
+
async function audit2(args) {
|
|
1816
|
+
const parsed = parse(args, usage2, options);
|
|
1817
|
+
const roots = (parsed.positionals.length > 0 ? parsed.positionals : ["."]).map((dir) => resolve(dir));
|
|
1818
|
+
for (const dir of roots) {
|
|
1819
|
+
if (!await isFolder(dir))
|
|
1820
|
+
fail(`${dir} is not a folder`);
|
|
1821
|
+
}
|
|
1822
|
+
const { exposed, unread } = await audit(roots);
|
|
1823
|
+
const json = parsed.values.json === true;
|
|
1824
|
+
if (!json && unread.length > MAX_UNREAD_LISTED) {
|
|
1825
|
+
console.error(`could not read ${unread.length} folders, so they were not audited (--json lists them)`);
|
|
1826
|
+
} else if (!json) {
|
|
1827
|
+
for (const dir of unread)
|
|
1828
|
+
console.error(`could not read ${dir}, so it was not audited`);
|
|
1829
|
+
}
|
|
1830
|
+
if (parsed.values.fix === true && (json || exposed.length > 0)) {
|
|
1831
|
+
const { fixed, left } = await fixAll(exposed, json);
|
|
1832
|
+
if (json)
|
|
1833
|
+
printJson({ fixed, exposed: (await audit(roots)).exposed, unread });
|
|
1834
|
+
return left ? 1 : 0;
|
|
1835
|
+
}
|
|
1836
|
+
if (json) {
|
|
1837
|
+
printJson({ exposed, unread });
|
|
1838
|
+
return exposed.length > 0 ? 1 : 0;
|
|
1839
|
+
}
|
|
1840
|
+
if (exposed.length === 0) {
|
|
1841
|
+
console.log("no exposed .env file nor compose file writing a secret out");
|
|
1842
|
+
return 0;
|
|
1843
|
+
}
|
|
1844
|
+
const uid = process10.getuid?.();
|
|
1845
|
+
for (const { path, readable, group, tracked, secrets } of exposed) {
|
|
1846
|
+
const sudo = uid !== undefined && uid !== 0 && (await stat4(path)).uid !== uid ? "sudo " : "";
|
|
1847
|
+
const problems = [
|
|
1848
|
+
...secrets === undefined ? [] : [`writes out ${secrets.join(", ")}: ev audit --fix moves the values into a .env beside it`],
|
|
1849
|
+
...readable ? [group === true ? `readable by its group or an ACL: ${sudo}chmod go-rwx ${shellQuote(shown2(path))}` : `readable by any account: ${sudo}chmod o-rwx ${shellQuote(shown2(path))}`] : [],
|
|
1850
|
+
...tracked ? [`tracked by git: git rm --cached ${shellQuote(shown2(path))}, then ignore it`] : []
|
|
1851
|
+
];
|
|
1852
|
+
console.log(`${shown2(path)}
|
|
1853
|
+
${problems.join(`
|
|
1854
|
+
`)}`);
|
|
1855
|
+
}
|
|
1856
|
+
return 1;
|
|
1857
|
+
}
|
|
1858
|
+
|
|
1859
|
+
// src/commands/compare.ts
|
|
1860
|
+
var diffUsage = `ev diff <a> <b>
|
|
1861
|
+
|
|
1862
|
+
Names the keys set in one file and not the other, never their values.
|
|
1863
|
+
|
|
1864
|
+
Exits 0 when both set the same keys, 1 when they differ, 2 on a usage error.`;
|
|
1865
|
+
var missingUsage = `ev missing [file]
|
|
1866
|
+
|
|
1867
|
+
Names the keys the reference file sets that the file (.env by default) does not.
|
|
1868
|
+
|
|
1869
|
+
Exits 0 when none is missing, 1 when some are, 2 on a usage error.`;
|
|
1870
|
+
async function keys(path) {
|
|
1871
|
+
return new Set(entries(await readEnv(path)).keys());
|
|
1872
|
+
}
|
|
1873
|
+
async function diff(args) {
|
|
1874
|
+
const parsed = parse(args, diffUsage, {});
|
|
1875
|
+
const [a, b] = parsed.positionals;
|
|
1876
|
+
if (a === undefined || b === undefined)
|
|
1877
|
+
fail(`needs two files
|
|
1878
|
+
|
|
1879
|
+
${diffUsage}`);
|
|
1880
|
+
const left = await keys(a);
|
|
1881
|
+
const right = await keys(b);
|
|
1882
|
+
const lines = [
|
|
1883
|
+
...[...left].filter((key) => !right.has(key)).map((key) => `only in ${a}: ${key}`),
|
|
1884
|
+
...[...right].filter((key) => !left.has(key)).map((key) => `only in ${b}: ${key}`)
|
|
1885
|
+
];
|
|
1886
|
+
if (lines.length === 0)
|
|
1887
|
+
return 0;
|
|
1888
|
+
console.log(lines.join(`
|
|
1889
|
+
`));
|
|
1890
|
+
return 1;
|
|
1891
|
+
}
|
|
1892
|
+
async function missing(args) {
|
|
1893
|
+
const parsed = parse(args, missingUsage, { against: { type: "string", description: "the reference file (.env.example by default)" } });
|
|
1894
|
+
const [file = ".env"] = parsed.positionals;
|
|
1895
|
+
const against = parsed.values.against ?? ".env.example";
|
|
1896
|
+
const have = await keys(file);
|
|
1897
|
+
const absent = [...await keys(against)].filter((key) => !have.has(key));
|
|
1898
|
+
if (absent.length === 0)
|
|
1899
|
+
return 0;
|
|
1900
|
+
console.log(absent.map((key) => `${key} (set in ${against}, not in ${file})`).join(`
|
|
1901
|
+
`));
|
|
1902
|
+
return 1;
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
// src/commands/edit.ts
|
|
1906
|
+
var DEFAULT_FILE = ".env";
|
|
1907
|
+
var TRAILING_NEWLINE = /\r?\n$/;
|
|
1908
|
+
var KEY_NAME = /^[A-Z_][\w.-]*$/i;
|
|
1909
|
+
var setUsage = `ev set KEY [file]
|
|
1910
|
+
|
|
1911
|
+
Sets KEY in the file (.env by default, created when missing), replacing its line in place or appending one. The value is read from stdin, or from -F <file>, so it never appears in a command line; --empty sets it to an empty value.
|
|
1912
|
+
|
|
1913
|
+
Exits 0 when it wrote the key, 1 when it could not, 2 on a usage error.`;
|
|
1914
|
+
var unsetUsage = `ev unset KEY [file]
|
|
1915
|
+
|
|
1916
|
+
Removes every line setting KEY from the file (.env by default), leaving comments and other lines as they are.
|
|
1917
|
+
|
|
1918
|
+
Exits 0 when it removed the key, 1 when the file does not set it, 2 on a usage error.`;
|
|
1919
|
+
var mvUsage = `ev mv KEY --from <file> --to <file>
|
|
1920
|
+
|
|
1921
|
+
Moves KEY's line from one file to another, as written. Refuses to replace a key the target already sets unless --force.
|
|
1922
|
+
|
|
1923
|
+
Exits 0 when it moved the key, 1 when the source lacks it or the target already sets it, 2 on a usage error.`;
|
|
1924
|
+
var cpUsage = `ev cp KEY --from <file> --to <file> [--as NEWKEY]
|
|
1925
|
+
|
|
1926
|
+
Copies KEY's value from one file to another without printing it, replacing the key's line in the target in place or appending one, and prints the masked result as ev set does. --as stores the copy under another key.
|
|
1927
|
+
|
|
1928
|
+
Exits 0 when it copied the key, 1 when the source lacks it, 2 on a usage error.`;
|
|
1929
|
+
async function readValue(from) {
|
|
1930
|
+
const input = await readInput(from ?? "-", { noStdin: "pipe the value on stdin or give -F <file>, it is never taken from the command line" });
|
|
1931
|
+
if (input === "")
|
|
1932
|
+
fail("the value is empty, nothing was written: --empty sets an empty value");
|
|
1933
|
+
return input.replace(TRAILING_NEWLINE, "");
|
|
1934
|
+
}
|
|
1935
|
+
function checkKey(key) {
|
|
1936
|
+
if (!KEY_NAME.test(key))
|
|
1937
|
+
badUsage(`${JSON.stringify(key)} is not a valid key: letters, digits, _, . and - only, not starting with a digit`);
|
|
1938
|
+
}
|
|
1939
|
+
async function readOrEmpty(path) {
|
|
1940
|
+
return await Bun.file(path).exists() ? readEnv(path) : { lines: [] };
|
|
1941
|
+
}
|
|
1942
|
+
async function set(args) {
|
|
1943
|
+
const parsed = parse(args, setUsage, {
|
|
1944
|
+
file: { type: "string", short: "F", description: "read the value from this file instead of stdin" },
|
|
1945
|
+
empty: { type: "boolean", description: "set an empty value, reading nothing" }
|
|
1946
|
+
});
|
|
1947
|
+
const [key, target = DEFAULT_FILE] = parsed.positionals;
|
|
1948
|
+
if (key === undefined)
|
|
1949
|
+
fail(`missing KEY
|
|
1950
|
+
|
|
1951
|
+
${setUsage}`);
|
|
1952
|
+
if (parsed.values.empty === true && parsed.values.file !== undefined)
|
|
1953
|
+
fail("--empty and -F exclude each other");
|
|
1954
|
+
checkKey(key);
|
|
1955
|
+
const value = parsed.values.empty === true ? "" : await readValue(parsed.values.file);
|
|
1956
|
+
const file = await withLocks([target], async () => {
|
|
1957
|
+
const current = await readOrEmpty(target);
|
|
1958
|
+
setLine(current, key, value);
|
|
1959
|
+
await writeEnv(target, current);
|
|
1960
|
+
return current;
|
|
1961
|
+
});
|
|
1962
|
+
console.log(`${target}: ${key}=${maskValue(key, value, await loadKnown(process.cwd(), [file])).replaceAll(`
|
|
1963
|
+
`, "\\n")}`);
|
|
1964
|
+
return 0;
|
|
1965
|
+
}
|
|
1966
|
+
async function unset(args) {
|
|
1967
|
+
const parsed = parse(args, unsetUsage, {});
|
|
1968
|
+
const [key, target = DEFAULT_FILE] = parsed.positionals;
|
|
1969
|
+
if (key === undefined)
|
|
1970
|
+
fail(`missing KEY
|
|
1971
|
+
|
|
1972
|
+
${unsetUsage}`);
|
|
1973
|
+
await withLocks([target], async () => {
|
|
1974
|
+
const file = await readEnv(target);
|
|
1975
|
+
if (removeKey(file, key) === 0)
|
|
1976
|
+
fail(`${key} is not set in ${target}`, 1);
|
|
1977
|
+
await writeEnv(target, file);
|
|
1978
|
+
});
|
|
1979
|
+
console.log(`${target}: removed ${key}`);
|
|
1980
|
+
return 0;
|
|
1981
|
+
}
|
|
1982
|
+
async function transfer(key, from, to, newKey, replace) {
|
|
1983
|
+
checkKey(key);
|
|
1984
|
+
if (newKey !== undefined)
|
|
1985
|
+
checkKey(newKey);
|
|
1986
|
+
if (from === to && newKey === undefined)
|
|
1987
|
+
fail("--from and --to are the same file");
|
|
1988
|
+
const source = await readEnv(from);
|
|
1989
|
+
const line = lastLine(source, key);
|
|
1990
|
+
if (line === undefined)
|
|
1991
|
+
fail(`${key} is not set in ${from}`, 1);
|
|
1992
|
+
const target = from === to ? source : await readOrEmpty(to);
|
|
1993
|
+
const name = newKey ?? key;
|
|
1994
|
+
if (!replace && entries(target).has(name))
|
|
1995
|
+
fail(`${to} already sets ${name}, --force replaces it`, 1);
|
|
1996
|
+
const value = line.value ?? "";
|
|
1997
|
+
setLine(target, name, value, newKey === undefined && !entries(target).has(name) ? line.raw : undefined);
|
|
1998
|
+
await writeEnv(to, target);
|
|
1999
|
+
return { source, target, value, name };
|
|
2000
|
+
}
|
|
2001
|
+
async function mv(args) {
|
|
2002
|
+
const parsed = parse(args, mvUsage, {
|
|
2003
|
+
from: { type: "string", description: "the file to take KEY from" },
|
|
2004
|
+
to: { type: "string", description: "the file to put KEY in, created when missing" },
|
|
2005
|
+
force: { type: "boolean", description: "replace KEY when the target already sets it" }
|
|
2006
|
+
});
|
|
2007
|
+
const [key] = parsed.positionals;
|
|
2008
|
+
const { from, to, force } = parsed.values;
|
|
2009
|
+
if (key === undefined || from === undefined || to === undefined)
|
|
2010
|
+
fail(`needs KEY, --from and --to
|
|
2011
|
+
|
|
2012
|
+
${mvUsage}`);
|
|
2013
|
+
await withLocks([from, to], async () => {
|
|
2014
|
+
const { source } = await transfer(key, from, to, undefined, force === true);
|
|
2015
|
+
removeKey(source, key);
|
|
2016
|
+
await writeEnv(from, source);
|
|
2017
|
+
});
|
|
2018
|
+
console.log(`${key}: ${from} -> ${to}`);
|
|
2019
|
+
return 0;
|
|
2020
|
+
}
|
|
2021
|
+
async function cp(args) {
|
|
2022
|
+
const parsed = parse(args, cpUsage, {
|
|
2023
|
+
from: { type: "string", description: "the file to take KEY from" },
|
|
2024
|
+
to: { type: "string", description: "the file to put the copy in, created when missing" },
|
|
2025
|
+
as: { type: "string", description: "store the copy under this key instead" }
|
|
2026
|
+
});
|
|
2027
|
+
const [key] = parsed.positionals;
|
|
2028
|
+
const { from, to, as } = parsed.values;
|
|
2029
|
+
if (key === undefined || from === undefined || to === undefined)
|
|
2030
|
+
fail(`needs KEY, --from and --to
|
|
2031
|
+
|
|
2032
|
+
${cpUsage}`);
|
|
2033
|
+
const { source, target, value, name } = await withLocks([from, to], async () => transfer(key, from, to, as, true));
|
|
2034
|
+
const known = await loadKnown(process.cwd(), [source, target]);
|
|
2035
|
+
console.log(`${to}: ${name}=${maskValue(name, value, known).replaceAll(`
|
|
2036
|
+
`, "\\n")}`);
|
|
2037
|
+
return 0;
|
|
2038
|
+
}
|
|
2039
|
+
|
|
2040
|
+
// src/commands/pins.ts
|
|
2041
|
+
import { readdir as readdir4, stat as stat5 } from "fs/promises";
|
|
2042
|
+
import { join as join6, resolve as resolve2 } from "path";
|
|
2043
|
+
|
|
2044
|
+
// src/pins.ts
|
|
2045
|
+
import { readdir as readdir3, readFile } from "fs/promises";
|
|
2046
|
+
import { join as join5, relative as relative2 } from "path";
|
|
2047
|
+
var OPTIONAL2 = /^\s*([A-Z][A-Z0-9_]*)\s*:\s*s\.Optional\(/gm;
|
|
2048
|
+
var REACHING = /(?:URL|URI|TOKEN|KEY|SECRET|PASSWORD|DSN|_HOST)(?:_FILE)?$/;
|
|
2049
|
+
var SELF = /(?:^|_)(?:PUBLIC|SITE|BASE|APP)_URL$/;
|
|
2050
|
+
var RENDERS = /\b(?:testSite|proxyKeyTests)\s*\(/;
|
|
2051
|
+
var NOT_NEEDED = /\/\/\s*ev pins:\s*none reached\b/;
|
|
2052
|
+
var OVERRIDE = /\boverrideEnv\s*\(/g;
|
|
2053
|
+
var KEY = /(?:^|[{,])\s*([A-Z_]\w*)\s*:/gi;
|
|
2054
|
+
var TEST_FILE = /\.test\.[cm]?[jt]sx?$/;
|
|
2055
|
+
var ENV_TEST = /^\.env\.test(?:\.local)?$/;
|
|
2056
|
+
var TEST_ROOTS = ["tests", "test", "__tests__", "e2e", "src"];
|
|
2057
|
+
var SKIPPED3 = new Set(["node_modules", ".git", ".kay", "dist", "vendor"]);
|
|
2058
|
+
var SCHEMA_CANDIDATES = ["src/env.ts", "env.ts", "src/env/index.ts"];
|
|
2059
|
+
var OPENERS = new Set(["(", "[", "{"]);
|
|
2060
|
+
var CLOSERS = new Set([")", "]", "}"]);
|
|
2061
|
+
var QUOTES = new Set(["'", '"', "`"]);
|
|
2062
|
+
async function exists(path) {
|
|
2063
|
+
return Bun.file(path).exists();
|
|
2064
|
+
}
|
|
2065
|
+
async function walk(folder, keep) {
|
|
2066
|
+
const found = [];
|
|
2067
|
+
let entries = [];
|
|
2068
|
+
try {
|
|
2069
|
+
entries = await readdir3(folder, { withFileTypes: true });
|
|
2070
|
+
} catch {
|
|
2071
|
+
return found;
|
|
2072
|
+
}
|
|
2073
|
+
for (const entry of entries) {
|
|
2074
|
+
if (SKIPPED3.has(entry.name))
|
|
2075
|
+
continue;
|
|
2076
|
+
const path = join5(folder, entry.name);
|
|
2077
|
+
if (entry.isDirectory())
|
|
2078
|
+
found.push(...await walk(path, keep));
|
|
2079
|
+
else if (entry.isFile() && keep(entry.name))
|
|
2080
|
+
found.push(path);
|
|
2081
|
+
}
|
|
2082
|
+
return found.sort();
|
|
2083
|
+
}
|
|
2084
|
+
async function testFiles(folder) {
|
|
2085
|
+
const found = [];
|
|
2086
|
+
for (const root of TEST_ROOTS) {
|
|
2087
|
+
found.push(...await walk(join5(folder, root), (name) => TEST_FILE.test(name)));
|
|
2088
|
+
}
|
|
2089
|
+
return found;
|
|
2090
|
+
}
|
|
2091
|
+
function balanced(text, open) {
|
|
2092
|
+
let depth = 0;
|
|
2093
|
+
let quote = "";
|
|
2094
|
+
for (let index = open;index < text.length; index++) {
|
|
2095
|
+
const char = text[index] ?? "";
|
|
2096
|
+
if (quote !== "") {
|
|
2097
|
+
if (char === "\\")
|
|
2098
|
+
index++;
|
|
2099
|
+
else if (char === quote)
|
|
2100
|
+
quote = "";
|
|
2101
|
+
} else if (QUOTES.has(char)) {
|
|
2102
|
+
quote = char;
|
|
2103
|
+
} else if (OPENERS.has(char)) {
|
|
2104
|
+
depth++;
|
|
2105
|
+
} else if (CLOSERS.has(char) && --depth === 0) {
|
|
2106
|
+
return text.slice(open + 1, index);
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
return text.slice(open + 1);
|
|
2110
|
+
}
|
|
2111
|
+
function topLevel(text) {
|
|
2112
|
+
let depth = 0;
|
|
2113
|
+
let quote = "";
|
|
2114
|
+
let out = "";
|
|
2115
|
+
for (let index = 0;index < text.length; index++) {
|
|
2116
|
+
const char = text[index] ?? "";
|
|
2117
|
+
if (quote !== "") {
|
|
2118
|
+
if (char === "\\")
|
|
2119
|
+
index++;
|
|
2120
|
+
else if (char === quote)
|
|
2121
|
+
quote = "";
|
|
2122
|
+
} else if (QUOTES.has(char)) {
|
|
2123
|
+
quote = char;
|
|
2124
|
+
} else if (OPENERS.has(char)) {
|
|
2125
|
+
out += depth === 0 ? char : "";
|
|
2126
|
+
depth++;
|
|
2127
|
+
} else if (CLOSERS.has(char)) {
|
|
2128
|
+
depth--;
|
|
2129
|
+
out += depth === 0 ? char : "";
|
|
2130
|
+
} else if (depth <= 1) {
|
|
2131
|
+
out += char;
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
return out;
|
|
2135
|
+
}
|
|
2136
|
+
function overriddenNames(source) {
|
|
2137
|
+
const names = new Set;
|
|
2138
|
+
for (const match of source.matchAll(OVERRIDE)) {
|
|
2139
|
+
const args = topLevel(balanced(source, match.index + match[0].length - 1));
|
|
2140
|
+
const object = args.slice(args.indexOf(",") + 1);
|
|
2141
|
+
for (const key of object.matchAll(KEY))
|
|
2142
|
+
names.add(key[1] ?? "");
|
|
2143
|
+
}
|
|
2144
|
+
return names;
|
|
2145
|
+
}
|
|
2146
|
+
function optionalNames(source) {
|
|
2147
|
+
const start = source.indexOf("defineEnv(");
|
|
2148
|
+
return start === -1 ? [] : [...source.slice(start).matchAll(OPTIONAL2)].map((match) => match[1] ?? "");
|
|
2149
|
+
}
|
|
2150
|
+
function reachesOutside(name) {
|
|
2151
|
+
return REACHING.test(name) && !SELF.test(name);
|
|
2152
|
+
}
|
|
2153
|
+
async function schemaFile(folder) {
|
|
2154
|
+
for (const candidate of SCHEMA_CANDIDATES) {
|
|
2155
|
+
const path = join5(folder, candidate);
|
|
2156
|
+
if (await exists(path) && (await readFile(path, "utf8")).includes("defineEnv("))
|
|
2157
|
+
return path;
|
|
2158
|
+
}
|
|
2159
|
+
return;
|
|
2160
|
+
}
|
|
2161
|
+
async function testEnvKeys(folder) {
|
|
2162
|
+
const keys = new Set;
|
|
2163
|
+
for (const entry of await readdir3(folder, { withFileTypes: true })) {
|
|
2164
|
+
if (!entry.isFile() || !ENV_TEST.test(entry.name))
|
|
2165
|
+
continue;
|
|
2166
|
+
for (const line of parseDotenv(await readFile(join5(folder, entry.name), "utf8")).lines) {
|
|
2167
|
+
if (line.key !== undefined)
|
|
2168
|
+
keys.add(line.key);
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
return keys;
|
|
2172
|
+
}
|
|
2173
|
+
async function pinningPreload(folder) {
|
|
2174
|
+
const path = join5(folder, "bunfig.toml");
|
|
2175
|
+
if (!await exists(path))
|
|
2176
|
+
return;
|
|
2177
|
+
const config = Bun.TOML.parse(await readFile(path, "utf8"));
|
|
2178
|
+
const preloads = [config.test?.preload, config.preload].flat().filter((entry) => typeof entry === "string" && entry.startsWith("."));
|
|
2179
|
+
for (const preload of preloads) {
|
|
2180
|
+
const file = join5(folder, preload);
|
|
2181
|
+
if (!await exists(file))
|
|
2182
|
+
continue;
|
|
2183
|
+
const source = await readFile(file, "utf8");
|
|
2184
|
+
if (source.includes(".env") && source.includes("process.env"))
|
|
2185
|
+
return preload;
|
|
2186
|
+
}
|
|
2187
|
+
return;
|
|
2188
|
+
}
|
|
2189
|
+
async function checkApp(folder, except = new Set) {
|
|
2190
|
+
const schema = await schemaFile(folder);
|
|
2191
|
+
if (schema === undefined)
|
|
2192
|
+
return;
|
|
2193
|
+
const reaching = optionalNames(await readFile(schema, "utf8")).filter((name) => reachesOutside(name) && !except.has(name));
|
|
2194
|
+
const preload = await pinningPreload(folder);
|
|
2195
|
+
const app = { app: folder, schema: relative2(folder, schema), reaching, unpinned: [], files: [], ...preload !== undefined && { preload } };
|
|
2196
|
+
if (preload !== undefined)
|
|
2197
|
+
return app;
|
|
2198
|
+
const fromEnv = await testEnvKeys(folder);
|
|
2199
|
+
const open = reaching.filter((name) => !fromEnv.has(name));
|
|
2200
|
+
const anywhere = new Set;
|
|
2201
|
+
for (const path of await testFiles(folder)) {
|
|
2202
|
+
const source = await readFile(path, "utf8");
|
|
2203
|
+
const pinned = overriddenNames(source);
|
|
2204
|
+
for (const name of pinned)
|
|
2205
|
+
anywhere.add(name);
|
|
2206
|
+
const unpinned = open.filter((name) => !pinned.has(name));
|
|
2207
|
+
if (RENDERS.test(source) && !NOT_NEEDED.test(source) && unpinned.length > 0)
|
|
2208
|
+
app.files.push({ file: relative2(folder, path), unpinned });
|
|
2209
|
+
}
|
|
2210
|
+
app.unpinned = open.filter((name) => !anywhere.has(name));
|
|
2211
|
+
return app;
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
// src/commands/pins.ts
|
|
2215
|
+
var usage3 = `ev pins [dir] [--except NAME,...]
|
|
2216
|
+
|
|
2217
|
+
Checks that an app's tests pin the env that reaches outside.
|
|
2218
|
+
Reads the app's env schema (the file calling defineEnv, src/env.ts) and lists its optional URL, key, token, secret, password and host variables, then the ones no \`.env.test\` entry, test-level overrideEnv or local bunfig preload dropping what .env sets pins, and each test file that calls testSite or proxyKeyTests without pinning them all.
|
|
2219
|
+
A file whose pages reach none of them says so with a \`// ev pins: none reached, <why>\` comment.
|
|
2220
|
+
The dir is an app, or a monorepo holding apps one level down (the current folder by default).
|
|
2221
|
+
Reads variable names only, never a value.
|
|
2222
|
+
Exits 0 when everything is pinned, 1 when something is not, 2 on a usage error.`;
|
|
2223
|
+
var options2 = {
|
|
2224
|
+
json: jsonOption("each app with its reaching, unpinned variables and flagged test files"),
|
|
2225
|
+
except: { type: "string", description: "comma-separated variables to leave out, as ones that only link back to the app" }
|
|
2226
|
+
};
|
|
2227
|
+
async function isFolder2(path) {
|
|
2228
|
+
try {
|
|
2229
|
+
return (await stat5(path)).isDirectory();
|
|
2230
|
+
} catch {
|
|
2231
|
+
return false;
|
|
2232
|
+
}
|
|
2233
|
+
}
|
|
2234
|
+
async function apps(dir, except) {
|
|
2235
|
+
const own = await checkApp(dir, except);
|
|
2236
|
+
if (own !== undefined)
|
|
2237
|
+
return [own];
|
|
2238
|
+
const found = [];
|
|
2239
|
+
for (const entry of (await readdir4(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
2240
|
+
if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules")
|
|
2241
|
+
continue;
|
|
2242
|
+
const app = await checkApp(join6(dir, entry.name), except);
|
|
2243
|
+
if (app !== undefined)
|
|
2244
|
+
found.push(app);
|
|
2245
|
+
}
|
|
2246
|
+
return found;
|
|
2247
|
+
}
|
|
2248
|
+
function failing(app) {
|
|
2249
|
+
return app.unpinned.length > 0 || app.files.length > 0;
|
|
2250
|
+
}
|
|
2251
|
+
function name(app, root) {
|
|
2252
|
+
return app.app === root ? app.app.split("/").at(-1) ?? app.app : app.app.slice(root.length + 1);
|
|
2253
|
+
}
|
|
2254
|
+
async function pins(args) {
|
|
2255
|
+
const parsed = parse(args, usage3, options2, { positionals: ["[dir]"] });
|
|
2256
|
+
const json = parsed.values.json === true;
|
|
2257
|
+
const root = resolve2(parsed.positionals[0] ?? ".");
|
|
2258
|
+
const except = new Set((parsed.values.except ?? "").split(",").map((entry) => entry.trim()).filter((entry) => entry !== ""));
|
|
2259
|
+
if (!await isFolder2(root))
|
|
2260
|
+
fail(`${root} is not a folder`);
|
|
2261
|
+
const found = await apps(root, except);
|
|
2262
|
+
if (found.length === 0)
|
|
2263
|
+
fail(`no env schema (a defineEnv call in src/env.ts) in ${root} or its folders`);
|
|
2264
|
+
if (json) {
|
|
2265
|
+
printJson(found.map((app) => ({ ...app, app: name(app, root) })));
|
|
2266
|
+
return found.some(failing) ? 1 : 0;
|
|
2267
|
+
}
|
|
2268
|
+
for (const app of found) {
|
|
2269
|
+
const label = name(app, root);
|
|
2270
|
+
if (!failing(app)) {
|
|
2271
|
+
ok(label, app.preload === undefined ? `${app.reaching.length} reaching variables pinned` : `every variable pinned by ${app.preload}`);
|
|
2272
|
+
continue;
|
|
2273
|
+
}
|
|
2274
|
+
console.log(`${label}: ${app.reaching.length} optional variables reach outside`);
|
|
2275
|
+
if (app.unpinned.length > 0)
|
|
2276
|
+
console.log(` unpinned by .env.test or any overrideEnv: ${app.unpinned.join(", ")}`);
|
|
2277
|
+
for (const { file, unpinned } of app.files)
|
|
2278
|
+
console.log(` ${file} renders a page without pinning: ${unpinned.join(", ")}`);
|
|
2279
|
+
}
|
|
2280
|
+
return found.some(failing) ? 1 : 0;
|
|
2281
|
+
}
|
|
2282
|
+
|
|
2283
|
+
// src/commands/read.ts
|
|
2284
|
+
var {$: $2 } = globalThis.Bun;
|
|
2285
|
+
var listUsage = `ev list [file]
|
|
2286
|
+
|
|
2287
|
+
Prints every key of the folder's .env* files, or of one file, with secret values masked: a few leading characters and the length under a key named like TOKEN, SECRET, PASSWORD, PASS, PWD, KEY, PRIVATE, DSN, AUTH, SALT or COOKIE, any value equal to a secret of the folder's .env* files, and the password and tokens of any URL.
|
|
2288
|
+
|
|
2289
|
+
Exits 0 when it printed them, 1 when there is no .env* file, 2 on a usage error.`;
|
|
2290
|
+
var getUsage = `ev get KEY [file]
|
|
2291
|
+
|
|
2292
|
+
Prints the masked value of one key, from every .env* file that sets it or from one file.
|
|
2293
|
+
|
|
2294
|
+
Exits 0 when the key is set, 1 when it is not set anywhere, 2 on a usage error.`;
|
|
2295
|
+
function display(key, value, known) {
|
|
2296
|
+
return maskValue(key, value, known).replaceAll(`
|
|
2297
|
+
`, "\\n").replaceAll("\r", "\\r");
|
|
2298
|
+
}
|
|
2299
|
+
async function readAll(names) {
|
|
2300
|
+
const files = [];
|
|
2301
|
+
for (const name of names)
|
|
2302
|
+
files.push([name, await readEnv(name)]);
|
|
2303
|
+
return { files, known: await loadKnown(process.cwd(), files.map(([, file]) => file)) };
|
|
2304
|
+
}
|
|
2305
|
+
async function list(args) {
|
|
2306
|
+
const parsed = parse(args, listUsage, {});
|
|
2307
|
+
const [file] = parsed.positionals;
|
|
2308
|
+
const names = file === undefined ? await envFiles() : [file];
|
|
2309
|
+
if (names.length === 0)
|
|
2310
|
+
fail("no .env* file in this folder", 1);
|
|
2311
|
+
const rows = [];
|
|
2312
|
+
const { files, known } = await readAll(names);
|
|
2313
|
+
for (const [name, file] of files) {
|
|
2314
|
+
for (const [key, value] of entries(file))
|
|
2315
|
+
rows.push([name, key, display(key, value, known)]);
|
|
2316
|
+
}
|
|
2317
|
+
if (rows.length > 0)
|
|
2318
|
+
console.log(table(rows));
|
|
2319
|
+
return 0;
|
|
2320
|
+
}
|
|
2321
|
+
async function get(args) {
|
|
2322
|
+
const parsed = parse(args, getUsage, {});
|
|
2323
|
+
const [key, file] = parsed.positionals;
|
|
2324
|
+
if (key === undefined)
|
|
2325
|
+
fail(`missing KEY
|
|
2326
|
+
|
|
2327
|
+
${getUsage}`);
|
|
2328
|
+
const names = file === undefined ? await envFiles() : [file];
|
|
2329
|
+
const rows = [];
|
|
2330
|
+
const { files, known } = await readAll(names);
|
|
2331
|
+
for (const [name, file] of files) {
|
|
2332
|
+
const value = entries(file).get(key);
|
|
2333
|
+
if (value !== undefined)
|
|
2334
|
+
rows.push([name, display(key, value, known)]);
|
|
2335
|
+
}
|
|
2336
|
+
if (rows.length === 0)
|
|
2337
|
+
fail(`${key} is not set in ${file ?? "any .env* file"}`, 1);
|
|
2338
|
+
console.log(file === undefined ? table(rows) : rows[0]?.[1]);
|
|
2339
|
+
return 0;
|
|
2340
|
+
}
|
|
2341
|
+
var grepUsage = `ev grep [-i] <regex> [file...]
|
|
2342
|
+
|
|
2343
|
+
Prints the keys matching the regular expression, from the folder's .env* files or the files given, with their values masked as ev list does. The regex is matched against the key only, never the value: \`ev grep '^DATABASE_'\` instead of \`grep ^DATABASE_ .env\`.
|
|
2344
|
+
|
|
2345
|
+
Exits 0 when a key matches, 1 when none does, 2 on a usage error.`;
|
|
2346
|
+
var showUsage = `ev show <rev>:<file>
|
|
2347
|
+
|
|
2348
|
+
Prints every key of an env file as a git revision holds it, values masked as ev list does: \`ev show HEAD~1:api/.env\` instead of \`git show HEAD~1:api/.env\`.
|
|
2349
|
+
|
|
2350
|
+
Exits 0 when it printed them, 1 when git cannot show the file, 2 on a usage error.`;
|
|
2351
|
+
var REVISION = /^([^:]+):(.+)$/;
|
|
2352
|
+
async function grep(args) {
|
|
2353
|
+
const parsed = parse(args, grepUsage, { "ignore-case": { type: "boolean", short: "i", description: "match the key whatever its case" } });
|
|
2354
|
+
const [source, ...given] = parsed.positionals;
|
|
2355
|
+
if (source === undefined)
|
|
2356
|
+
fail(`missing the regex
|
|
2357
|
+
|
|
2358
|
+
${grepUsage}`);
|
|
2359
|
+
let pattern;
|
|
2360
|
+
try {
|
|
2361
|
+
pattern = new RegExp(source, parsed.values["ignore-case"] === true ? "i" : "");
|
|
2362
|
+
} catch (error) {
|
|
2363
|
+
fail(`${source} is no valid regular expression: ${error instanceof Error ? error.message : String(error)}`);
|
|
2364
|
+
}
|
|
2365
|
+
const names = given.length === 0 ? await envFiles() : given;
|
|
2366
|
+
const rows = [];
|
|
2367
|
+
const { files, known } = await readAll(names);
|
|
2368
|
+
for (const [name, file] of files) {
|
|
2369
|
+
for (const [key, value] of entries(file)) {
|
|
2370
|
+
if (pattern.test(key))
|
|
2371
|
+
rows.push([name, key, display(key, value, known)]);
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
if (rows.length === 0)
|
|
2375
|
+
fail(`no key matches ${source} in ${names.join(", ") || "any .env* file"}`, 1);
|
|
2376
|
+
console.log(table(rows));
|
|
2377
|
+
return 0;
|
|
2378
|
+
}
|
|
2379
|
+
async function show(args) {
|
|
2380
|
+
const parsed = parse(args, showUsage, {});
|
|
2381
|
+
const [target] = parsed.positionals;
|
|
2382
|
+
const [, revision, path] = REVISION.exec(target ?? "") ?? [];
|
|
2383
|
+
if (revision === undefined || path === undefined)
|
|
2384
|
+
fail(`give <rev>:<file>
|
|
2385
|
+
|
|
2386
|
+
${showUsage}`);
|
|
2387
|
+
if (revision.startsWith("-"))
|
|
2388
|
+
fail(`${revision} is not a revision: it reads as a git option`);
|
|
2389
|
+
const shown = await $2`git show --end-of-options ${`${revision}:${path}`}`.quiet().nothrow();
|
|
2390
|
+
if (shown.exitCode !== 0)
|
|
2391
|
+
fail(`git show ${revision}:${path} failed: ${shown.stderr.toString().trim()}`, 1);
|
|
2392
|
+
const file = parseDotenv(shown.stdout.toString());
|
|
2393
|
+
const known = await loadKnown(process.cwd(), [file]);
|
|
2394
|
+
const rows = [...entries(file)].map(([key, value]) => [key, display(key, value, known)]);
|
|
2395
|
+
if (rows.length > 0)
|
|
2396
|
+
console.log(table(rows));
|
|
2397
|
+
return 0;
|
|
2398
|
+
}
|
|
2399
|
+
|
|
2400
|
+
// src/ev.ts
|
|
2401
|
+
process11.exitCode = await runCli({
|
|
2402
|
+
name: "ev",
|
|
2403
|
+
version,
|
|
2404
|
+
about: ".env files listed and edited with secrets masked",
|
|
2405
|
+
replaces: "cat .env, grep on env files and editing them by hand",
|
|
2406
|
+
examples: ["ev list", ["ev get DATABASE_URL", "one key, its value masked"]],
|
|
2407
|
+
commands: {
|
|
2408
|
+
list: { run: list, summary: "every key of the .env* files, secrets masked" },
|
|
2409
|
+
get: { run: get, summary: "one key's masked value" },
|
|
2410
|
+
grep: { run: grep, summary: "the keys matching a regex, values masked" },
|
|
2411
|
+
show: { run: show, summary: "an env file at a git revision, values masked" },
|
|
2412
|
+
set: { run: set, summary: "set a key, the value read from stdin or -F" },
|
|
2413
|
+
unset: { run: unset, summary: "remove a key from a file" },
|
|
2414
|
+
cp: { run: cp, summary: "copy a key from one file to another, the value never printed" },
|
|
2415
|
+
mv: { run: mv, summary: "move a key from one file to another" },
|
|
2416
|
+
diff: { run: diff, summary: "keys set in one file and not the other" },
|
|
2417
|
+
missing: { run: missing, summary: "keys of .env.example that .env lacks" },
|
|
2418
|
+
pins: { run: pins, summary: "the env vars reaching outside that an app's tests leave to a developer's env" },
|
|
2419
|
+
audit: { run: audit2, summary: ".env files others can read or git tracks, compose files writing secrets out" }
|
|
2420
|
+
},
|
|
2421
|
+
aliases: { ls: "list" }
|
|
2422
|
+
});
|