@airborne-dev/mcp 0.0.0-stage → 0.1.0
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/SKILL.md +50 -0
- package/dist/api.d.ts +37 -0
- package/dist/api.js +265 -0
- package/dist/archive.d.ts +59 -0
- package/dist/archive.js +862 -0
- package/dist/auth.d.ts +17 -0
- package/dist/auth.js +400 -0
- package/dist/helpers.d.ts +75 -0
- package/dist/helpers.js +31 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +737 -0
- package/package.json +34 -4
- package/README.md +0 -3
package/dist/archive.js
ADDED
|
@@ -0,0 +1,862 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { pipeline } from "node:stream/promises";
|
|
6
|
+
import * as tar from "tar";
|
|
7
|
+
// Case-insensitive names always ignored at any depth
|
|
8
|
+
const ALWAYS_IGNORED_SEGMENTS = new Set([
|
|
9
|
+
"node_modules",
|
|
10
|
+
".git",
|
|
11
|
+
".next",
|
|
12
|
+
".nuxt",
|
|
13
|
+
".svelte-kit",
|
|
14
|
+
".venv",
|
|
15
|
+
"venv",
|
|
16
|
+
"__pycache__",
|
|
17
|
+
".pytest_cache",
|
|
18
|
+
".mypy_cache",
|
|
19
|
+
"coverage",
|
|
20
|
+
".ds_store",
|
|
21
|
+
"thumbs.db",
|
|
22
|
+
".airborne-data",
|
|
23
|
+
".aws",
|
|
24
|
+
".gcloud",
|
|
25
|
+
".ssh",
|
|
26
|
+
".envrc",
|
|
27
|
+
".npmrc",
|
|
28
|
+
".pypirc",
|
|
29
|
+
".netrc",
|
|
30
|
+
"id_rsa",
|
|
31
|
+
"id_dsa",
|
|
32
|
+
"id_ed25519",
|
|
33
|
+
"id_ecdsa",
|
|
34
|
+
]);
|
|
35
|
+
// Only ignored at root level so legitimate nested source folders like `src/build/` are preserved
|
|
36
|
+
const ROOT_ONLY_IGNORED_DIRS = new Set(["dist", "build", "out"]);
|
|
37
|
+
const SAFE_ENV_EXAMPLES = new Set([
|
|
38
|
+
".env.example",
|
|
39
|
+
".env.sample",
|
|
40
|
+
".env.template",
|
|
41
|
+
]);
|
|
42
|
+
const SECRET_FILENAME_RE = /(?:service[-_]?account.*\.json$|credentials.*\.json$|firebase-adminsdk.*\.json$|client_secret.*\.json$|\.(?:pem|key|p8|p12|pfx|ppk|jks|keystore|kdbx|tfvars|tfstate|tfstate\.backup|log)$)/i;
|
|
43
|
+
const MAX_UNCOMPRESSED_BYTES = 500 * 1024 * 1024; // 500 MB pre-compression safety cap
|
|
44
|
+
const MAX_FILE_COUNT = 25_000;
|
|
45
|
+
const MAX_DEPTH = 40;
|
|
46
|
+
const MAX_ENV_FILE_BYTES = 256 * 1024; // 256 KiB local .env safety cap
|
|
47
|
+
const VALID_ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
48
|
+
const FORBIDDEN_ENV_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
49
|
+
const activeTempDirs = new Set();
|
|
50
|
+
let exitHookRegistered = false;
|
|
51
|
+
function cleanupAllTempDirs() {
|
|
52
|
+
for (const dir of Array.from(activeTempDirs)) {
|
|
53
|
+
try {
|
|
54
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
// Best-effort cleanup
|
|
58
|
+
}
|
|
59
|
+
activeTempDirs.delete(dir);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function ensureTempCleanupHook() {
|
|
63
|
+
if (exitHookRegistered)
|
|
64
|
+
return;
|
|
65
|
+
exitHookRegistered = true;
|
|
66
|
+
process.once("exit", cleanupAllTempDirs);
|
|
67
|
+
process.once("SIGINT", () => {
|
|
68
|
+
cleanupAllTempDirs();
|
|
69
|
+
process.exit(130);
|
|
70
|
+
});
|
|
71
|
+
process.once("SIGTERM", () => {
|
|
72
|
+
cleanupAllTempDirs();
|
|
73
|
+
process.exit(143);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
export function isAlwaysIgnored(relativePath, isDir) {
|
|
77
|
+
const segments = relativePath.split("/").filter(Boolean);
|
|
78
|
+
for (let i = 0; i < segments.length; i += 1) {
|
|
79
|
+
const segLower = segments[i].toLowerCase();
|
|
80
|
+
if (ALWAYS_IGNORED_SEGMENTS.has(segLower)) {
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
if (i === 0 && (isDir || segments.length > 1) && ROOT_ONLY_IGNORED_DIRS.has(segLower)) {
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
if (segLower === ".env" ||
|
|
87
|
+
segLower === ".env~" ||
|
|
88
|
+
segLower.endsWith(".env~") ||
|
|
89
|
+
(segLower.startsWith(".env.") && !SAFE_ENV_EXAMPLES.has(segLower))) {
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
if (SECRET_FILENAME_RE.test(segLower)) {
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
function tokenizeSegmentPattern(pattern) {
|
|
99
|
+
const tokens = [];
|
|
100
|
+
let i = 0;
|
|
101
|
+
while (i < pattern.length) {
|
|
102
|
+
const ch = pattern[i];
|
|
103
|
+
if (ch === "\\" && i + 1 < pattern.length) {
|
|
104
|
+
tokens.push({ type: "literal", ch: pattern[i + 1] });
|
|
105
|
+
i += 2;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (ch === "*") {
|
|
109
|
+
// Collapse consecutive stars inside a segment
|
|
110
|
+
if (tokens.length === 0 || tokens[tokens.length - 1].type !== "star") {
|
|
111
|
+
tokens.push({ type: "star" });
|
|
112
|
+
}
|
|
113
|
+
i += 1;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (ch === "?") {
|
|
117
|
+
tokens.push({ type: "qmark" });
|
|
118
|
+
i += 1;
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (ch === "[") {
|
|
122
|
+
let j = i + 1;
|
|
123
|
+
let negated = false;
|
|
124
|
+
if (j < pattern.length && (pattern[j] === "!" || pattern[j] === "^")) {
|
|
125
|
+
negated = true;
|
|
126
|
+
j += 1;
|
|
127
|
+
}
|
|
128
|
+
const chars = new Set();
|
|
129
|
+
const ranges = [];
|
|
130
|
+
let closed = false;
|
|
131
|
+
let first = true;
|
|
132
|
+
while (j < pattern.length) {
|
|
133
|
+
if (pattern[j] === "]" && !first) {
|
|
134
|
+
closed = true;
|
|
135
|
+
j += 1;
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
first = false;
|
|
139
|
+
let c = pattern[j];
|
|
140
|
+
if (c === "\\" && j + 1 < pattern.length) {
|
|
141
|
+
c = pattern[j + 1];
|
|
142
|
+
j += 2;
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
j += 1;
|
|
146
|
+
}
|
|
147
|
+
if (j + 1 < pattern.length && pattern[j] === "-" && pattern[j + 1] !== "]") {
|
|
148
|
+
let endChar = pattern[j + 1];
|
|
149
|
+
if (endChar === "\\" && j + 2 < pattern.length) {
|
|
150
|
+
endChar = pattern[j + 2];
|
|
151
|
+
j += 3;
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
j += 2;
|
|
155
|
+
}
|
|
156
|
+
const startCode = c.charCodeAt(0);
|
|
157
|
+
const endCode = endChar.charCodeAt(0);
|
|
158
|
+
if (startCode <= endCode) {
|
|
159
|
+
ranges.push([startCode, endCode]);
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
ranges.push([endCode, startCode]);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
chars.add(c);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (closed) {
|
|
170
|
+
tokens.push({ type: "class", negated, chars, ranges });
|
|
171
|
+
i = j;
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
tokens.push({ type: "literal", ch });
|
|
176
|
+
i += 1;
|
|
177
|
+
}
|
|
178
|
+
return tokens;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Linear-time O(N*M) wildcard segment matcher (zero ReDoS risk).
|
|
182
|
+
* Supports `*`, `?`, `[abc]`/`[!a-z]` character classes, and `\x` escapes.
|
|
183
|
+
*/
|
|
184
|
+
function matchSegmentTokens(tokens, text) {
|
|
185
|
+
const n = tokens.length;
|
|
186
|
+
const m = text.length;
|
|
187
|
+
let prev = new Uint8Array(m + 1);
|
|
188
|
+
let curr = new Uint8Array(m + 1);
|
|
189
|
+
prev[0] = 1;
|
|
190
|
+
for (let i = 1; i <= n; i += 1) {
|
|
191
|
+
const tok = tokens[i - 1];
|
|
192
|
+
curr.fill(0);
|
|
193
|
+
if (tok.type === "star") {
|
|
194
|
+
let anyPrev = false;
|
|
195
|
+
for (let j = 0; j <= m; j += 1) {
|
|
196
|
+
if (prev[j])
|
|
197
|
+
anyPrev = true;
|
|
198
|
+
if (anyPrev)
|
|
199
|
+
curr[j] = 1;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
for (let j = 1; j <= m; j += 1) {
|
|
204
|
+
if (!prev[j - 1])
|
|
205
|
+
continue;
|
|
206
|
+
const c = text[j - 1];
|
|
207
|
+
let matched = false;
|
|
208
|
+
if (tok.type === "qmark") {
|
|
209
|
+
matched = true;
|
|
210
|
+
}
|
|
211
|
+
else if (tok.type === "literal") {
|
|
212
|
+
matched = c === tok.ch;
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
const code = c.charCodeAt(0);
|
|
216
|
+
const inSet = tok.chars.has(c) ||
|
|
217
|
+
tok.ranges.some(([lo, hi]) => code >= lo && code <= hi);
|
|
218
|
+
matched = tok.negated ? !inSet : inSet;
|
|
219
|
+
}
|
|
220
|
+
if (matched)
|
|
221
|
+
curr[j] = 1;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
const tmp = prev;
|
|
225
|
+
prev = curr;
|
|
226
|
+
curr = tmp;
|
|
227
|
+
}
|
|
228
|
+
return prev[m] === 1;
|
|
229
|
+
}
|
|
230
|
+
// Linear-time O(P*S) path-segment matcher:
|
|
231
|
+
// - `**` matches 0..N segments (e.g. `**/foo`, `a/**/b`)
|
|
232
|
+
// - `**+` matches 1..N segments (trailing `/**` per gitignore(5), e.g. `abc/**`)
|
|
233
|
+
function matchPathSegments(patternSegments, pathSegments) {
|
|
234
|
+
const pLen = patternSegments.length;
|
|
235
|
+
const sLen = pathSegments.length;
|
|
236
|
+
let prev = new Uint8Array(sLen + 1);
|
|
237
|
+
let curr = new Uint8Array(sLen + 1);
|
|
238
|
+
prev[0] = 1;
|
|
239
|
+
for (let i = 1; i <= pLen; i += 1) {
|
|
240
|
+
const pat = patternSegments[i - 1];
|
|
241
|
+
curr.fill(0);
|
|
242
|
+
if (pat === "**") {
|
|
243
|
+
let anyPrev = false;
|
|
244
|
+
for (let j = 0; j <= sLen; j += 1) {
|
|
245
|
+
if (prev[j])
|
|
246
|
+
anyPrev = true;
|
|
247
|
+
if (anyPrev)
|
|
248
|
+
curr[j] = 1;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
else if (pat === "**+") {
|
|
252
|
+
// Must consume at least 1 segment
|
|
253
|
+
let anyPrev = false;
|
|
254
|
+
for (let j = 1; j <= sLen; j += 1) {
|
|
255
|
+
if (prev[j - 1])
|
|
256
|
+
anyPrev = true;
|
|
257
|
+
if (anyPrev)
|
|
258
|
+
curr[j] = 1;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
else {
|
|
262
|
+
for (let j = 1; j <= sLen; j += 1) {
|
|
263
|
+
if (prev[j - 1] && matchSegmentTokens(pat, pathSegments[j - 1])) {
|
|
264
|
+
curr[j] = 1;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
const tmp = prev;
|
|
269
|
+
prev = curr;
|
|
270
|
+
curr = tmp;
|
|
271
|
+
}
|
|
272
|
+
return prev[sLen] === 1;
|
|
273
|
+
}
|
|
274
|
+
// Compiles a single `.gitignore` line into a ReDoS-free linear-time rule supporting:
|
|
275
|
+
// - `!` negation rules & `\#` / `\!` escaped leading markers
|
|
276
|
+
// - Trailing `/` directory-only rules (strictly enforced for both positive & negated rules)
|
|
277
|
+
// - Leading `/` and mid-pattern `/` anchoring
|
|
278
|
+
// - `**/`, `/**/`, and `/**` (1+ segments) multi-segment wildcards
|
|
279
|
+
// - `*`, `?`, `[abc]`/`[!a-z]` character classes, and backslash escapes
|
|
280
|
+
export function compileGitignoreRule(rawLine, basePrefix = "") {
|
|
281
|
+
// Trim unescaped trailing spaces per gitignore spec
|
|
282
|
+
let line = rawLine.replace(/\r$/, "");
|
|
283
|
+
if (!line.trim() || line.startsWith("#") || line.length > 512) {
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
// Strip trailing unescaped spaces
|
|
287
|
+
line = line.replace(/(?<!\\) +$/, "");
|
|
288
|
+
if (!line)
|
|
289
|
+
return null;
|
|
290
|
+
let negated = false;
|
|
291
|
+
if (line.startsWith("!")) {
|
|
292
|
+
negated = true;
|
|
293
|
+
line = line.slice(1);
|
|
294
|
+
}
|
|
295
|
+
else if (line.startsWith("\\#") || line.startsWith("\\!")) {
|
|
296
|
+
line = line.slice(1);
|
|
297
|
+
}
|
|
298
|
+
if (!line)
|
|
299
|
+
return null;
|
|
300
|
+
const dirOnly = line.endsWith("/");
|
|
301
|
+
line = line.replace(/\/+$/, "");
|
|
302
|
+
const leadingSlash = line.startsWith("/");
|
|
303
|
+
line = line.replace(/^\/+/, "");
|
|
304
|
+
if (!line)
|
|
305
|
+
return null;
|
|
306
|
+
const hasSlash = line.includes("/");
|
|
307
|
+
const anchored = leadingSlash || hasSlash;
|
|
308
|
+
const rawParts = line.split("/").filter(Boolean);
|
|
309
|
+
if (rawParts.length === 0)
|
|
310
|
+
return null;
|
|
311
|
+
const segments = [];
|
|
312
|
+
for (let idx = 0; idx < rawParts.length; idx += 1) {
|
|
313
|
+
const part = rawParts[idx];
|
|
314
|
+
if (part === "**") {
|
|
315
|
+
const isTrailingGlobstar = idx === rawParts.length - 1 && rawParts.length > 1;
|
|
316
|
+
const token = isTrailingGlobstar ? "**+" : "**";
|
|
317
|
+
if (segments.length === 0 || segments[segments.length - 1] !== token) {
|
|
318
|
+
segments.push(token);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
else {
|
|
322
|
+
segments.push(tokenizeSegmentPattern(part));
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return {
|
|
326
|
+
negated,
|
|
327
|
+
dirOnly,
|
|
328
|
+
anchored,
|
|
329
|
+
basePrefix,
|
|
330
|
+
segments,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
function ruleMatchesExactPath(rule, pathParts) {
|
|
334
|
+
if (rule.anchored) {
|
|
335
|
+
return matchPathSegments(rule.segments, pathParts);
|
|
336
|
+
}
|
|
337
|
+
// Unanchored single-segment rule (e.g. `*.log`, `build/`): matches basename at any depth
|
|
338
|
+
if (rule.segments.length === 1) {
|
|
339
|
+
const seg = rule.segments[0];
|
|
340
|
+
if (seg === "**" || seg === "**+")
|
|
341
|
+
return true;
|
|
342
|
+
return matchSegmentTokens(seg, pathParts[pathParts.length - 1]);
|
|
343
|
+
}
|
|
344
|
+
return matchPathSegments(["**", ...rule.segments], pathParts);
|
|
345
|
+
}
|
|
346
|
+
function loadGitignoreFile(dirPath, basePrefix) {
|
|
347
|
+
const gitignorePath = path.join(dirPath, ".gitignore");
|
|
348
|
+
try {
|
|
349
|
+
const stat = fs.lstatSync(gitignorePath);
|
|
350
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 512 * 1024) {
|
|
351
|
+
return [];
|
|
352
|
+
}
|
|
353
|
+
const lines = fs.readFileSync(gitignorePath, "utf8").split(/\r?\n/);
|
|
354
|
+
const rules = [];
|
|
355
|
+
for (const line of lines) {
|
|
356
|
+
const rule = compileGitignoreRule(line, basePrefix);
|
|
357
|
+
if (rule)
|
|
358
|
+
rules.push(rule);
|
|
359
|
+
}
|
|
360
|
+
return rules;
|
|
361
|
+
}
|
|
362
|
+
catch {
|
|
363
|
+
return [];
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Evaluates whether an exact path (without ancestor short-circuit) is ignored by `rules`.
|
|
368
|
+
*/
|
|
369
|
+
function isExactPathIgnored(relPath, isDir, rules) {
|
|
370
|
+
let ignored = false;
|
|
371
|
+
for (const rule of rules) {
|
|
372
|
+
if (rule.basePrefix && !relPath.startsWith(rule.basePrefix)) {
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
const localPath = rule.basePrefix
|
|
376
|
+
? relPath.slice(rule.basePrefix.length)
|
|
377
|
+
: relPath;
|
|
378
|
+
if (!localPath)
|
|
379
|
+
continue;
|
|
380
|
+
const parts = localPath.split("/").filter(Boolean);
|
|
381
|
+
if (parts.length === 0)
|
|
382
|
+
continue;
|
|
383
|
+
const matched = rule.dirOnly
|
|
384
|
+
? isDir && ruleMatchesExactPath(rule, parts)
|
|
385
|
+
: ruleMatchesExactPath(rule, parts);
|
|
386
|
+
if (matched) {
|
|
387
|
+
ignored = !rule.negated;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return ignored;
|
|
391
|
+
}
|
|
392
|
+
// Evaluates full gitignore(5) semantics: a path is ignored iff any ancestor directory
|
|
393
|
+
// is net-ignored across all rules, OR the path itself is net-ignored.
|
|
394
|
+
// This ensures directory negations (`assets/*` + `!assets/icons/`, `**/cache/` + `!src/cache/`)
|
|
395
|
+
// preserve descendant files inside unignored directories.
|
|
396
|
+
export function isIgnoredByRules(relPath, isDir, rules) {
|
|
397
|
+
const fullParts = relPath.split("/").filter(Boolean);
|
|
398
|
+
if (fullParts.length === 0)
|
|
399
|
+
return false;
|
|
400
|
+
for (let prefixLen = 1; prefixLen < fullParts.length; prefixLen += 1) {
|
|
401
|
+
const ancestorPath = fullParts.slice(0, prefixLen).join("/");
|
|
402
|
+
if (isExactPathIgnored(ancestorPath, true, rules)) {
|
|
403
|
+
return true;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
return isExactPathIgnored(relPath, isDir, rules);
|
|
407
|
+
}
|
|
408
|
+
function collectFiles(rootDir, currentDir, inheritedRules, out, budget, depth) {
|
|
409
|
+
if (depth > MAX_DEPTH) {
|
|
410
|
+
throw new Error(`Directory nesting exceeds maximum depth of ${MAX_DEPTH} levels.`);
|
|
411
|
+
}
|
|
412
|
+
const relDir = path.relative(rootDir, currentDir).split(path.sep).join("/");
|
|
413
|
+
const basePrefix = relDir ? `${relDir}/` : "";
|
|
414
|
+
const localRules = loadGitignoreFile(currentDir, basePrefix);
|
|
415
|
+
const activeRules = localRules.length > 0 ? [...inheritedRules, ...localRules] : inheritedRules;
|
|
416
|
+
let entries;
|
|
417
|
+
try {
|
|
418
|
+
entries = fs.readdirSync(currentDir, { withFileTypes: true });
|
|
419
|
+
}
|
|
420
|
+
catch (err) {
|
|
421
|
+
const code = err.code;
|
|
422
|
+
if (code === "ENOENT" || code === "EACCES" || code === "EPERM") {
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
throw err;
|
|
426
|
+
}
|
|
427
|
+
for (const entry of entries) {
|
|
428
|
+
// Strictly skip symlinks so malicious symlinks can never escape rootDir
|
|
429
|
+
if (entry.isSymbolicLink()) {
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
432
|
+
const absPath = path.join(currentDir, entry.name);
|
|
433
|
+
const relPath = path.relative(rootDir, absPath).split(path.sep).join("/");
|
|
434
|
+
const isDir = entry.isDirectory();
|
|
435
|
+
if (isAlwaysIgnored(relPath, isDir)) {
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
if (isIgnoredByRules(relPath, isDir, activeRules)) {
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
if (isDir) {
|
|
442
|
+
collectFiles(rootDir, absPath, activeRules, out, budget, depth + 1);
|
|
443
|
+
}
|
|
444
|
+
else if (entry.isFile()) {
|
|
445
|
+
let stat;
|
|
446
|
+
try {
|
|
447
|
+
stat = fs.lstatSync(absPath);
|
|
448
|
+
}
|
|
449
|
+
catch (err) {
|
|
450
|
+
const code = err.code;
|
|
451
|
+
if (code === "ENOENT" || code === "EACCES" || code === "EPERM") {
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
throw err;
|
|
455
|
+
}
|
|
456
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
457
|
+
continue;
|
|
458
|
+
if (out.length >= MAX_FILE_COUNT) {
|
|
459
|
+
throw new Error(`Project contains more than ${MAX_FILE_COUNT.toLocaleString()} deployable files. Add build/data folders to .gitignore.`);
|
|
460
|
+
}
|
|
461
|
+
budget.totalBytes += stat.size;
|
|
462
|
+
if (budget.totalBytes > MAX_UNCOMPRESSED_BYTES) {
|
|
463
|
+
throw new Error(`Project source size exceeds ${Math.round(MAX_UNCOMPRESSED_BYTES / (1024 * 1024))} MB before compression. Add large media/data folders to .gitignore.`);
|
|
464
|
+
}
|
|
465
|
+
out.push(relPath);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Packages a local project directory into a `.tar.gz` archive suitable for
|
|
471
|
+
* direct signed-URL upload to the user's own GCS build bucket.
|
|
472
|
+
*
|
|
473
|
+
* Uses `new tar.Pack({ noDirRecurse: true, follow: false, ... })` + `pack.add(file)` directly
|
|
474
|
+
* so `@`-prefixed paths (like Next.js `@modal/page.tsx`) are NEVER treated as external archives
|
|
475
|
+
* and TOCTOU symlink swaps are rejected.
|
|
476
|
+
*/
|
|
477
|
+
export async function packageAppDirectory(dir) {
|
|
478
|
+
const resolvedDir = path.resolve(dir);
|
|
479
|
+
let rootStat;
|
|
480
|
+
try {
|
|
481
|
+
rootStat = fs.statSync(resolvedDir);
|
|
482
|
+
}
|
|
483
|
+
catch {
|
|
484
|
+
throw new Error(`Directory not found: ${resolvedDir}`);
|
|
485
|
+
}
|
|
486
|
+
if (!rootStat.isDirectory()) {
|
|
487
|
+
throw new Error(`Directory not found: ${resolvedDir}`);
|
|
488
|
+
}
|
|
489
|
+
const files = [];
|
|
490
|
+
const budget = { totalBytes: 0 };
|
|
491
|
+
collectFiles(resolvedDir, resolvedDir, [], files, budget, 0);
|
|
492
|
+
if (files.length === 0) {
|
|
493
|
+
throw new Error(`No deployable files found in ${resolvedDir} after applying ignore rules.`);
|
|
494
|
+
}
|
|
495
|
+
const dockerfileName = files.find((f) => f === "Dockerfile" || f === "dockerfile");
|
|
496
|
+
const hasDockerfile = Boolean(dockerfileName);
|
|
497
|
+
ensureTempCleanupHook();
|
|
498
|
+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "airborne-build-"));
|
|
499
|
+
activeTempDirs.add(tempDir);
|
|
500
|
+
const tarballPath = path.join(tempDir, "source.tar.gz");
|
|
501
|
+
const cleanup = () => {
|
|
502
|
+
activeTempDirs.delete(tempDir);
|
|
503
|
+
try {
|
|
504
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
505
|
+
}
|
|
506
|
+
catch {
|
|
507
|
+
// Best-effort cleanup
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
try {
|
|
511
|
+
const pack = new tar.Pack({
|
|
512
|
+
gzip: true,
|
|
513
|
+
cwd: resolvedDir,
|
|
514
|
+
portable: true,
|
|
515
|
+
follow: false,
|
|
516
|
+
noDirRecurse: true,
|
|
517
|
+
filter: (_p, stat) => {
|
|
518
|
+
const s = stat;
|
|
519
|
+
return Boolean(s && s.isFile() && !s.isSymbolicLink());
|
|
520
|
+
},
|
|
521
|
+
});
|
|
522
|
+
const outStream = fs.createWriteStream(tarballPath, { mode: 0o600 });
|
|
523
|
+
const pipePromise = pipeline(pack, outStream);
|
|
524
|
+
for (const file of files) {
|
|
525
|
+
pack.add(file);
|
|
526
|
+
}
|
|
527
|
+
pack.end();
|
|
528
|
+
await pipePromise;
|
|
529
|
+
const stat = fs.statSync(tarballPath);
|
|
530
|
+
return {
|
|
531
|
+
tarballPath,
|
|
532
|
+
fileCount: files.length,
|
|
533
|
+
sizeBytes: stat.size,
|
|
534
|
+
hasDockerfile,
|
|
535
|
+
dockerfileName,
|
|
536
|
+
cleanup,
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
catch (err) {
|
|
540
|
+
cleanup();
|
|
541
|
+
throw err;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Parses a local `.env` file into a null-prototype key-value map.
|
|
546
|
+
* Supports:
|
|
547
|
+
* - UTF-8 BOM stripping
|
|
548
|
+
* - Line-numbered error on unterminated quotes
|
|
549
|
+
* - Single-pass escape handling (`\n`, `\r`, `\t`, `\"`, `\\`, `\$`)
|
|
550
|
+
* - Quoted values with trailing inline comments (`KEY="abc" # note`)
|
|
551
|
+
* - Multiline double/single-quoted values (e.g. PEM keys)
|
|
552
|
+
*/
|
|
553
|
+
export function parseEnvFile(envFilePath) {
|
|
554
|
+
const resolved = path.resolve(envFilePath);
|
|
555
|
+
let stat;
|
|
556
|
+
try {
|
|
557
|
+
stat = fs.lstatSync(resolved);
|
|
558
|
+
}
|
|
559
|
+
catch {
|
|
560
|
+
throw new Error(`Env file not found: ${resolved}`);
|
|
561
|
+
}
|
|
562
|
+
if (!stat.isFile() || stat.isSymbolicLink()) {
|
|
563
|
+
throw new Error(`Env path is not a regular file: ${resolved}`);
|
|
564
|
+
}
|
|
565
|
+
if (stat.size > MAX_ENV_FILE_BYTES) {
|
|
566
|
+
throw new Error(`Env file exceeds ${Math.round(MAX_ENV_FILE_BYTES / 1024)} KiB limit.`);
|
|
567
|
+
}
|
|
568
|
+
let content = fs.readFileSync(resolved, "utf8");
|
|
569
|
+
if (content.startsWith("\uFEFF")) {
|
|
570
|
+
content = content.slice(1);
|
|
571
|
+
}
|
|
572
|
+
const result = Object.create(null);
|
|
573
|
+
let idx = 0;
|
|
574
|
+
let lineNum = 1;
|
|
575
|
+
const len = content.length;
|
|
576
|
+
while (idx < len) {
|
|
577
|
+
// Skip leading whitespace and blank/comment lines
|
|
578
|
+
while (idx < len &&
|
|
579
|
+
(content[idx] === " " ||
|
|
580
|
+
content[idx] === "\t" ||
|
|
581
|
+
content[idx] === "\r" ||
|
|
582
|
+
content[idx] === "\n")) {
|
|
583
|
+
if (content[idx] === "\n")
|
|
584
|
+
lineNum += 1;
|
|
585
|
+
idx += 1;
|
|
586
|
+
}
|
|
587
|
+
if (idx >= len)
|
|
588
|
+
break;
|
|
589
|
+
if (content[idx] === "#") {
|
|
590
|
+
while (idx < len && content[idx] !== "\n")
|
|
591
|
+
idx += 1;
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
const entryLine = lineNum;
|
|
595
|
+
const lineStart = idx;
|
|
596
|
+
let eqIdx = -1;
|
|
597
|
+
while (idx < len && content[idx] !== "\n" && content[idx] !== "\r") {
|
|
598
|
+
if (content[idx] === "=" && eqIdx === -1) {
|
|
599
|
+
eqIdx = idx;
|
|
600
|
+
break;
|
|
601
|
+
}
|
|
602
|
+
idx += 1;
|
|
603
|
+
}
|
|
604
|
+
if (eqIdx === -1) {
|
|
605
|
+
while (idx < len && content[idx] !== "\n")
|
|
606
|
+
idx += 1;
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
609
|
+
let key = content.slice(lineStart, eqIdx).trim();
|
|
610
|
+
if (key.startsWith("export ")) {
|
|
611
|
+
key = key.slice(7).trim();
|
|
612
|
+
}
|
|
613
|
+
idx = eqIdx + 1;
|
|
614
|
+
while (idx < len && (content[idx] === " " || content[idx] === "\t")) {
|
|
615
|
+
idx += 1;
|
|
616
|
+
}
|
|
617
|
+
let value = "";
|
|
618
|
+
if (idx < len && (content[idx] === '"' || content[idx] === "'")) {
|
|
619
|
+
const quote = content[idx];
|
|
620
|
+
idx += 1;
|
|
621
|
+
let rawVal = "";
|
|
622
|
+
let closed = false;
|
|
623
|
+
while (idx < len) {
|
|
624
|
+
const ch = content[idx];
|
|
625
|
+
if (quote === '"' && ch === "\\" && idx + 1 < len) {
|
|
626
|
+
const next = content[idx + 1];
|
|
627
|
+
if (next === "\n")
|
|
628
|
+
lineNum += 1;
|
|
629
|
+
rawVal += ch + next;
|
|
630
|
+
idx += 2;
|
|
631
|
+
continue;
|
|
632
|
+
}
|
|
633
|
+
if (ch === quote) {
|
|
634
|
+
idx += 1;
|
|
635
|
+
closed = true;
|
|
636
|
+
break;
|
|
637
|
+
}
|
|
638
|
+
if (ch === "\n")
|
|
639
|
+
lineNum += 1;
|
|
640
|
+
rawVal += ch;
|
|
641
|
+
idx += 1;
|
|
642
|
+
}
|
|
643
|
+
if (!closed) {
|
|
644
|
+
throw new Error(`Unterminated ${quote === '"' ? "double" : "single"} quote for "${key}" on line ${entryLine} of ${resolved}.`);
|
|
645
|
+
}
|
|
646
|
+
// Consume rest of line (trailing inline comments after closing quote)
|
|
647
|
+
while (idx < len && content[idx] !== "\n")
|
|
648
|
+
idx += 1;
|
|
649
|
+
if (quote === '"') {
|
|
650
|
+
value = rawVal.replace(/\\([nrt"$`\\])/g, (_m, esc) => esc === "n"
|
|
651
|
+
? "\n"
|
|
652
|
+
: esc === "r"
|
|
653
|
+
? "\r"
|
|
654
|
+
: esc === "t"
|
|
655
|
+
? "\t"
|
|
656
|
+
: esc);
|
|
657
|
+
}
|
|
658
|
+
else {
|
|
659
|
+
value = rawVal;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
else {
|
|
663
|
+
while (idx < len && content[idx] !== "\n" && content[idx] !== "\r") {
|
|
664
|
+
idx += 1;
|
|
665
|
+
}
|
|
666
|
+
const rawUnquoted = content.slice(eqIdx + 1, idx);
|
|
667
|
+
const commentIdx = rawUnquoted.search(/\s+#/);
|
|
668
|
+
value = (commentIdx >= 0 ? rawUnquoted.slice(0, commentIdx) : rawUnquoted).trim();
|
|
669
|
+
}
|
|
670
|
+
if (VALID_ENV_KEY_RE.test(key) && !FORBIDDEN_ENV_KEYS.has(key)) {
|
|
671
|
+
result[key] = value;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
return result;
|
|
675
|
+
}
|
|
676
|
+
export function formatEnvValue(val) {
|
|
677
|
+
// Quote & escape shell metacharacters (including `$`, backticks, parens like `(default)`)
|
|
678
|
+
// so `source .env.local` is safe in bash/zsh/sh and round-trips through parseEnvFile
|
|
679
|
+
if (/[\s#"'\\$`()&|;<>\r\n]/.test(val)) {
|
|
680
|
+
const escaped = val
|
|
681
|
+
.replace(/\\/g, "\\\\")
|
|
682
|
+
.replace(/"/g, '\\"')
|
|
683
|
+
.replace(/\$/g, "\\$")
|
|
684
|
+
.replace(/`/g, "\\`")
|
|
685
|
+
.replace(/\r/g, "\\r")
|
|
686
|
+
.replace(/\n/g, "\\n");
|
|
687
|
+
return `"${escaped}"`;
|
|
688
|
+
}
|
|
689
|
+
return val;
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* Splits `.env` content into logical entries (preserving multiline quoted values as a single entry)
|
|
693
|
+
* so updating a multiline key never leaves orphaned continuation lines behind.
|
|
694
|
+
*/
|
|
695
|
+
function splitEnvEntries(content) {
|
|
696
|
+
const entries = [];
|
|
697
|
+
let idx = 0;
|
|
698
|
+
const len = content.length;
|
|
699
|
+
while (idx < len) {
|
|
700
|
+
const entryStart = idx;
|
|
701
|
+
// Read first line up to '=' or newline
|
|
702
|
+
let eqIdx = -1;
|
|
703
|
+
let firstLineEnd = idx;
|
|
704
|
+
while (firstLineEnd < len &&
|
|
705
|
+
content[firstLineEnd] !== "\n" &&
|
|
706
|
+
content[firstLineEnd] !== "\r") {
|
|
707
|
+
if (content[firstLineEnd] === "=" && eqIdx === -1) {
|
|
708
|
+
eqIdx = firstLineEnd;
|
|
709
|
+
}
|
|
710
|
+
firstLineEnd += 1;
|
|
711
|
+
}
|
|
712
|
+
const firstLine = content.slice(entryStart, firstLineEnd);
|
|
713
|
+
const trimmed = firstLine.trim();
|
|
714
|
+
if (!trimmed || trimmed.startsWith("#") || eqIdx === -1) {
|
|
715
|
+
entries.push(firstLine);
|
|
716
|
+
idx = firstLineEnd;
|
|
717
|
+
if (content[idx] === "\r")
|
|
718
|
+
idx += 1;
|
|
719
|
+
if (content[idx] === "\n")
|
|
720
|
+
idx += 1;
|
|
721
|
+
continue;
|
|
722
|
+
}
|
|
723
|
+
// Check if value opens a quote that spans multiple lines
|
|
724
|
+
let vIdx = eqIdx + 1;
|
|
725
|
+
while (vIdx < firstLineEnd && (content[vIdx] === " " || content[vIdx] === "\t")) {
|
|
726
|
+
vIdx += 1;
|
|
727
|
+
}
|
|
728
|
+
if (vIdx < firstLineEnd && (content[vIdx] === '"' || content[vIdx] === "'")) {
|
|
729
|
+
const quote = content[vIdx];
|
|
730
|
+
let scan = vIdx + 1;
|
|
731
|
+
while (scan < len) {
|
|
732
|
+
const ch = content[scan];
|
|
733
|
+
if (quote === '"' && ch === "\\" && scan + 1 < len) {
|
|
734
|
+
scan += 2;
|
|
735
|
+
continue;
|
|
736
|
+
}
|
|
737
|
+
if (ch === quote) {
|
|
738
|
+
scan += 1;
|
|
739
|
+
break;
|
|
740
|
+
}
|
|
741
|
+
scan += 1;
|
|
742
|
+
}
|
|
743
|
+
while (scan < len && content[scan] !== "\n" && content[scan] !== "\r") {
|
|
744
|
+
scan += 1;
|
|
745
|
+
}
|
|
746
|
+
entries.push(content.slice(entryStart, scan));
|
|
747
|
+
idx = scan;
|
|
748
|
+
if (content[idx] === "\r")
|
|
749
|
+
idx += 1;
|
|
750
|
+
if (content[idx] === "\n")
|
|
751
|
+
idx += 1;
|
|
752
|
+
}
|
|
753
|
+
else {
|
|
754
|
+
entries.push(firstLine);
|
|
755
|
+
idx = firstLineEnd;
|
|
756
|
+
if (content[idx] === "\r")
|
|
757
|
+
idx += 1;
|
|
758
|
+
if (content[idx] === "\n")
|
|
759
|
+
idx += 1;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
return entries;
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* Atomically merges Airborne-provisioned add-on environment variables into
|
|
766
|
+
* `<dir>/.env.local` with `0o600` permissions set BEFORE rename, rejecting symlinks,
|
|
767
|
+
* validating keys, and handling multiline values cleanly.
|
|
768
|
+
*/
|
|
769
|
+
export function upsertEnvLocal(dir, vars) {
|
|
770
|
+
const sanitizedEntries = [];
|
|
771
|
+
for (const [k, v] of Object.entries(vars)) {
|
|
772
|
+
const cleanKey = k.trim();
|
|
773
|
+
if (!VALID_ENV_KEY_RE.test(cleanKey) || FORBIDDEN_ENV_KEYS.has(cleanKey)) {
|
|
774
|
+
throw new Error(`Refusing to write invalid environment key "${k}".`);
|
|
775
|
+
}
|
|
776
|
+
sanitizedEntries.push([cleanKey, String(v)]);
|
|
777
|
+
}
|
|
778
|
+
const resolvedDir = path.resolve(dir);
|
|
779
|
+
fs.mkdirSync(resolvedDir, { recursive: true });
|
|
780
|
+
const envPath = path.join(resolvedDir, ".env.local");
|
|
781
|
+
let existing = "";
|
|
782
|
+
try {
|
|
783
|
+
const stat = fs.lstatSync(envPath);
|
|
784
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
785
|
+
throw new Error(`Refusing to write .env.local: ${envPath} is a symlink or non-regular file.`);
|
|
786
|
+
}
|
|
787
|
+
existing = fs.readFileSync(envPath, "utf8");
|
|
788
|
+
if (existing.startsWith("\uFEFF")) {
|
|
789
|
+
existing = existing.slice(1);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
catch (err) {
|
|
793
|
+
if (err.code !== "ENOENT") {
|
|
794
|
+
throw err;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
const entries = existing ? splitEnvEntries(existing) : [];
|
|
798
|
+
const managedKeys = new Set(sanitizedEntries.map(([k]) => k));
|
|
799
|
+
const remaining = new Map(sanitizedEntries);
|
|
800
|
+
const updatedEntries = [];
|
|
801
|
+
for (const entry of entries) {
|
|
802
|
+
const firstLine = entry.split(/\r?\n/, 1)[0] ?? "";
|
|
803
|
+
const trimmed = firstLine.trim();
|
|
804
|
+
if (!trimmed || trimmed.startsWith("#")) {
|
|
805
|
+
updatedEntries.push(entry);
|
|
806
|
+
continue;
|
|
807
|
+
}
|
|
808
|
+
const stripped = trimmed.startsWith("export ")
|
|
809
|
+
? trimmed.slice(7).trim()
|
|
810
|
+
: trimmed;
|
|
811
|
+
const eqIdx = stripped.indexOf("=");
|
|
812
|
+
if (eqIdx <= 0) {
|
|
813
|
+
updatedEntries.push(entry);
|
|
814
|
+
continue;
|
|
815
|
+
}
|
|
816
|
+
const key = stripped.slice(0, eqIdx).trim();
|
|
817
|
+
if (managedKeys.has(key)) {
|
|
818
|
+
if (remaining.has(key)) {
|
|
819
|
+
const val = remaining.get(key);
|
|
820
|
+
remaining.delete(key);
|
|
821
|
+
updatedEntries.push(`${key}=${formatEnvValue(val)}`);
|
|
822
|
+
}
|
|
823
|
+
// Drop duplicate later occurrences of managed keys so our value wins
|
|
824
|
+
continue;
|
|
825
|
+
}
|
|
826
|
+
updatedEntries.push(entry);
|
|
827
|
+
}
|
|
828
|
+
if (remaining.size > 0) {
|
|
829
|
+
if (updatedEntries.length > 0 &&
|
|
830
|
+
updatedEntries[updatedEntries.length - 1] !== "") {
|
|
831
|
+
updatedEntries.push("");
|
|
832
|
+
}
|
|
833
|
+
updatedEntries.push("# Added by Airborne init_app");
|
|
834
|
+
for (const [k, v] of remaining.entries()) {
|
|
835
|
+
updatedEntries.push(`${k}=${formatEnvValue(v)}`);
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
const tmpPath = `${envPath}.${crypto.randomBytes(8).toString("hex")}.tmp`;
|
|
839
|
+
try {
|
|
840
|
+
fs.writeFileSync(tmpPath, updatedEntries.join("\n").trimEnd() + "\n", {
|
|
841
|
+
encoding: "utf8",
|
|
842
|
+
mode: 0o600,
|
|
843
|
+
});
|
|
844
|
+
try {
|
|
845
|
+
fs.chmodSync(tmpPath, 0o600);
|
|
846
|
+
}
|
|
847
|
+
catch {
|
|
848
|
+
// Windows chmod is a no-op
|
|
849
|
+
}
|
|
850
|
+
fs.renameSync(tmpPath, envPath);
|
|
851
|
+
}
|
|
852
|
+
catch (err) {
|
|
853
|
+
try {
|
|
854
|
+
fs.rmSync(tmpPath, { force: true });
|
|
855
|
+
}
|
|
856
|
+
catch {
|
|
857
|
+
// ignore
|
|
858
|
+
}
|
|
859
|
+
throw err;
|
|
860
|
+
}
|
|
861
|
+
return envPath;
|
|
862
|
+
}
|